text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { EOF, createToken } from "../../src/scan/tokens_public"
import { Lexer } from "../../src/scan/lexer_public"
import {
EmbeddedActionsParser,
CstParser
} from "../../src/parse/parser/traits/parser_traits"
import { EMPTY_ALT } from "../../src/parse/parser/parser"
import { expect } from "chai"
import {
EarlyExitException,
MismatchedTokenException,
NotAllInputParsedException,
NoViableAltException
} from "../../src/parse/exceptions_public"
import {
tokenStructuredMatcher,
augmentTokenTypes
} from "../../src/scan/tokens"
import { createRegularToken, setEquality } from "../utils/matchers"
import { IMultiModeLexerDefinition, IToken, TokenType } from "@chevrotain/types"
function defineRecognizerSpecs(
contextName,
createToken,
createTokenInstance,
tokenMatcher
) {
context("Recognizer " + contextName, () => {
const PlusTok = createToken({ name: "PlusTok" })
PlusTok.LABEL = "+"
const MinusTok = createToken({ name: "MinusTok" })
const IntTok = createToken({ name: "IntTok" })
const DotTok = createToken({ name: "DotTok" })
const IdentTok = createToken({ name: "IdentTok" })
const ALL_TOKENS = [PlusTok, MinusTok, IntTok, IdentTok, DotTok]
augmentTokenTypes(ALL_TOKENS)
describe("The Parsing DSL", () => {
it("provides a production SUBRULE1-5 that invokes another rule", () => {
class SubRuleTestParser extends EmbeddedActionsParser {
private result = ""
private index = 1
constructor(input: IToken[] = []) {
super(ALL_TOKENS, {})
this.performSelfAnalysis()
this.input = input
}
public topRule = this.RULE("topRule", () => {
this.SUBRULE1(this.subRule)
this.SUBRULE2(this.subRule)
this.SUBRULE3(this.subRule)
this.subrule(66, this.subRule)
this.SUBRULE5(this.subRule)
return this.result
})
public subRule = this.RULE("subRule", () => {
this.CONSUME(PlusTok)
this.ACTION(() => {
// side effect
this.result += this.index++
})
})
}
const input = [
createTokenInstance(PlusTok),
createTokenInstance(PlusTok),
createTokenInstance(PlusTok),
createTokenInstance(PlusTok),
createTokenInstance(PlusTok)
]
const parser = new SubRuleTestParser(input)
const result = parser.topRule()
expect(result).to.equal("12345")
})
it("provides a production SUBRULE1-5 that can accept arguments from its caller", () => {
class SubRuleArgsParser extends EmbeddedActionsParser {
private numbers = ""
private letters = ""
constructor(input: IToken[] = []) {
super(ALL_TOKENS, {})
this.performSelfAnalysis()
this.input = input
}
public topRule = this.RULE("topRule", () => {
this.SUBRULE(this.subRule, { ARGS: [6, "a"] })
this.SUBRULE1(this.subRule2, { ARGS: [5, "b"] })
this.SUBRULE2(this.subRule, { ARGS: [4, "c"] })
this.SUBRULE3(this.subRule, { ARGS: [3, "d"] })
this.SUBRULE4(this.subRule, { ARGS: [2, "e"] })
this.SUBRULE5(this.subRule, { ARGS: [1, "f"] })
return {
numbers: this.numbers,
letters: this.letters
}
})
public subRule = this.RULE(
"subRule",
(numFromCaller, charFromCaller) => {
this.CONSUME(PlusTok)
this.ACTION(() => {
// side effect
this.numbers += numFromCaller
this.letters += charFromCaller
})
}
)
public subRule2 = this.RULE(
"subRule2",
(numFromCaller, charFromCaller) => {
this.CONSUME(PlusTok)
this.ACTION(() => {
// side effect
this.numbers += numFromCaller
this.letters += charFromCaller
})
}
)
}
const input = [
createTokenInstance(PlusTok),
createTokenInstance(PlusTok),
createTokenInstance(PlusTok),
createTokenInstance(PlusTok),
createTokenInstance(PlusTok),
createTokenInstance(PlusTok)
]
const parser = new SubRuleArgsParser(input)
const result = parser.topRule()
expect(result.letters).to.equal("abcdef")
expect(result.numbers).to.equal("654321")
})
describe("supports EMPTY(...) alternative convenience function", () => {
class EmptyAltParser extends EmbeddedActionsParser {
constructor(input: IToken[] = []) {
super(ALL_TOKENS, {})
this.performSelfAnalysis()
this.input = input
}
public orRule = this.RULE("orRule", this.parseOrRule)
private parseOrRule(): string {
return this.OR7([
{
ALT: () => {
this.CONSUME1(PlusTok)
return "+"
}
},
{
ALT: () => {
this.CONSUME1(MinusTok)
return "-"
}
},
{
ALT: EMPTY_ALT("EMPTY_ALT")
}
])
}
}
it("can match an non-empty alternative in an OR with an empty alternative", () => {
const input = [createTokenInstance(PlusTok)]
const parser = new EmptyAltParser(input)
expect(parser.orRule()).to.equal("+")
})
it("can match an empty alternative", () => {
const input = []
const parser = new EmptyAltParser(input)
expect(parser.orRule()).to.equal("EMPTY_ALT")
})
it("has a utility function for defining EMPTY ALTERNATIVES", () => {
const noArgsEmptyAlt = EMPTY_ALT()
expect(noArgsEmptyAlt()).to.be.undefined
const valueEmptyAlt = EMPTY_ALT(666)
expect(valueEmptyAlt()).to.equal(666)
})
})
})
describe("Token categories support", () => {
it("Can consume a Token that belongs to multiple categories", () => {
const Keyword = createToken({ name: "Keyword" })
const Literal = createToken({ name: "Literal" })
const TrueLiteral = createToken({
name: "TrueLiteral",
categories: [Keyword, Literal]
})
class CategoriesParser extends EmbeddedActionsParser {
constructor(input: IToken[] = []) {
super([Keyword, Literal], {})
this.performSelfAnalysis()
this.input = input
}
public keyRule = this.RULE("keyRule", () => {
this.CONSUME(Keyword)
})
public litRule = this.RULE("litRule", () => {
this.CONSUME(Literal)
})
}
const parser = new CategoriesParser([])
parser.input = [createTokenInstance(TrueLiteral)]
parser.keyRule()
expect(parser.errors).to.be.empty
parser.input = [createTokenInstance(TrueLiteral)]
parser.litRule()
expect(parser.errors).to.be.empty
})
})
describe("The Error Recovery functionality of the Chevrotain Parser", () => {
class ManyRepetitionRecovery extends EmbeddedActionsParser {
constructor(input: IToken[] = [], isErrorRecoveryEnabled = true) {
super(ALL_TOKENS, {
recoveryEnabled: isErrorRecoveryEnabled
})
this.performSelfAnalysis()
this.input = input
}
public qualifiedName = this.RULE(
"qualifiedName",
this.parseQualifiedName,
{
recoveryValueFunc: () => ["666"]
}
)
private parseQualifiedName(): string[] {
const idents = []
idents.push(this.CONSUME1(IdentTok).image)
this.MANY({
DEF: () => {
this.CONSUME1(DotTok)
idents.push(this.CONSUME2(IdentTok).image)
}
})
this.CONSUME1(EOF)
return idents
}
}
class ManySepRepetitionRecovery extends EmbeddedActionsParser {
constructor(input: IToken[] = [], isErrorRecoveryEnabled = true) {
super(ALL_TOKENS, {
recoveryEnabled: isErrorRecoveryEnabled
})
this.performSelfAnalysis()
this.input = input
}
public qualifiedName = this.RULE(
"qualifiedName",
this.parseQualifiedName,
{
recoveryValueFunc: () => ["333"]
}
)
private parseQualifiedName(): string[] {
const idents = []
idents.push(this.CONSUME1(IdentTok).image)
this.CONSUME1(DotTok)
this.MANY_SEP({
SEP: DotTok,
DEF: () => {
idents.push(this.CONSUME2(IdentTok).image)
}
})
this.CONSUME1(EOF)
return idents
}
}
class ManySepSubRuleRepetitionRecovery extends EmbeddedActionsParser {
constructor(input: IToken[] = []) {
super(ALL_TOKENS, {
recoveryEnabled: true
})
this.performSelfAnalysis()
this.input = input
}
public qualifiedName = this.RULE(
"qualifiedName",
this.parseQualifiedName
)
public identifier = this.RULE("identifier", this.parseIdentifier)
public idents = []
private parseQualifiedName(): string[] {
this.idents = []
this.MANY_SEP({
SEP: DotTok,
DEF: () => {
this.SUBRULE(this.identifier)
}
})
this.CONSUME1(EOF)
return this.idents
}
private parseIdentifier(): void {
this.idents.push(this.CONSUME1(IdentTok).image)
}
public canTokenTypeBeInsertedInRecovery(tokClass: TokenType) {
// this parser is meant to test a scenario with re-sync recovery and MANY_SEP --> disable TokenInsertion
return false
}
}
class AtLeastOneRepetitionRecovery extends EmbeddedActionsParser {
constructor(input: IToken[] = [], isErrorRecoveryEnabled = true) {
super(ALL_TOKENS, {
recoveryEnabled: isErrorRecoveryEnabled
})
this.performSelfAnalysis()
this.input = input
}
public qualifiedName = this.RULE(
"qualifiedName",
this.parseQualifiedName,
{
recoveryValueFunc: () => ["777"]
}
)
private parseQualifiedName(): string[] {
const idents = []
idents.push(this.CONSUME1(IdentTok).image)
this.AT_LEAST_ONE({
DEF: () => {
this.CONSUME1(DotTok)
idents.push(this.CONSUME2(IdentTok).image)
},
ERR_MSG: "bamba"
})
this.CONSUME1(EOF)
return idents
}
}
class AtLeastOneSepRepetitionRecovery extends EmbeddedActionsParser {
constructor(input: IToken[] = [], isErrorRecoveryEnabled = true) {
super(ALL_TOKENS, {
recoveryEnabled: isErrorRecoveryEnabled
})
this.performSelfAnalysis()
this.input = input
}
public qualifiedName = this.RULE(
"qualifiedName",
this.parseQualifiedName,
{
recoveryValueFunc: () => ["999"]
}
)
private parseQualifiedName(): string[] {
const idents = []
this.AT_LEAST_ONE_SEP({
SEP: DotTok,
DEF: () => {
idents.push(this.CONSUME1(IdentTok).image)
}
})
this.CONSUME1(EOF)
return idents
}
}
it("can CONSUME tokens with an index specifying the occurrence for the specific token in the current rule", () => {
const parser: any = new EmbeddedActionsParser(ALL_TOKENS, {
recoveryEnabled: true
})
parser.reset()
const testInput = [
createTokenInstance(IntTok, "1"),
createTokenInstance(PlusTok),
createTokenInstance(IntTok, "2"),
createTokenInstance(PlusTok),
createTokenInstance(IntTok, "3")
]
parser.tokVector = testInput
parser.tokVectorLength = testInput.length
expect(parser.CONSUME4(IntTok)).to.equal(testInput[0])
expect(parser.CONSUME2(PlusTok)).to.equal(testInput[1])
expect(parser.CONSUME1(IntTok)).to.equal(testInput[2])
expect(parser.CONSUME3(PlusTok)).to.equal(testInput[3])
expect(parser.CONSUME1(IntTok)).to.equal(testInput[4])
expect(tokenMatcher(parser.LA(1), EOF))
})
it("will not perform inRepetition recovery while in backtracking mode", () => {
const parser: any = new EmbeddedActionsParser([PlusTok], {})
parser.isBackTrackingStack.push(1)
expect(parser.shouldInRepetitionRecoveryBeTried(MinusTok, 1)).to.equal(
false
)
})
it("can perform in-repetition recovery for MANY grammar rule", () => {
// a.b+.c
const input = [
createTokenInstance(IdentTok, "a"),
createTokenInstance(DotTok),
createTokenInstance(IdentTok, "b"),
createTokenInstance(PlusTok),
createTokenInstance(DotTok),
createTokenInstance(IdentTok, "c")
]
const parser = new ManyRepetitionRecovery(input)
expect(parser.qualifiedName()).to.deep.equal(["a", "b", "c"])
expect(parser.errors.length).to.equal(1)
})
it("can disable in-repetition recovery for MANY grammar rule", () => {
// a.b+.c
const input = [
createTokenInstance(IdentTok, "a"),
createTokenInstance(DotTok),
createTokenInstance(IdentTok, "b"),
createTokenInstance(PlusTok),
createTokenInstance(DotTok),
createTokenInstance(IdentTok, "c")
]
const parser = new ManyRepetitionRecovery(input, false)
expect(parser.qualifiedName()).to.deep.equal(["666"])
expect(parser.errors.length).to.equal(1)
})
it("can perform in-repetition recovery for MANY_SEP grammar rule", () => {
// a.b+.c
const input = [
createTokenInstance(IdentTok, "a"),
createTokenInstance(DotTok),
createTokenInstance(IdentTok, "b"),
createTokenInstance(PlusTok),
createTokenInstance(DotTok),
createTokenInstance(IdentTok, "c")
]
const parser = new ManySepRepetitionRecovery(input)
expect(parser.qualifiedName()).to.deep.equal(["a", "b", "c"])
expect(parser.errors.length).to.equal(1)
})
it("can disable in-repetition recovery for MANY_SEP grammar rule", () => {
// a.b+.c
const input = [
createTokenInstance(IdentTok, "a"),
createTokenInstance(DotTok),
createTokenInstance(IdentTok, "b"),
createTokenInstance(PlusTok),
createTokenInstance(DotTok),
createTokenInstance(IdentTok, "c")
]
const parser = new ManySepRepetitionRecovery(input, false)
expect(parser.qualifiedName()).to.deep.equal(["333"])
expect(parser.errors.length).to.equal(1)
})
it("can perform in-repetition recovery for MANY_SEP grammar rule #2", () => {
// a.b..c...d
const input = [
createTokenInstance(IdentTok, "a"),
createTokenInstance(DotTok),
createTokenInstance(DotTok),
createTokenInstance(DotTok),
createTokenInstance(IdentTok, "b")
]
const parser = new ManySepSubRuleRepetitionRecovery(input)
expect(parser.qualifiedName()).to.deep.equal(["a", "b"])
expect(parser.errors.length).to.equal(2)
})
it("can perform in-repetition recovery for AT_LEAST_ONE grammar rule", () => {
// a.b+.c
const input = [
createTokenInstance(IdentTok, "a"),
createTokenInstance(DotTok),
createTokenInstance(IdentTok, "b"),
createTokenInstance(PlusTok),
createTokenInstance(DotTok),
createTokenInstance(IdentTok, "c")
]
const parser = new AtLeastOneRepetitionRecovery(input)
expect(parser.qualifiedName()).to.deep.equal(["a", "b", "c"])
expect(parser.errors.length).to.equal(1)
})
it("can disable in-repetition recovery for AT_LEAST_ONE grammar rule", () => {
// a.b+.c
const input = [
createTokenInstance(IdentTok, "a"),
createTokenInstance(DotTok),
createTokenInstance(IdentTok, "b"),
createTokenInstance(PlusTok),
createTokenInstance(DotTok),
createTokenInstance(IdentTok, "c")
]
const parser = new AtLeastOneRepetitionRecovery(input, false)
expect(parser.qualifiedName()).to.deep.equal(["777"])
expect(parser.errors.length).to.equal(1)
})
it("can perform in-repetition recovery for AT_LEAST_ONE_SEP grammar rule", () => {
// a.b+.c
const input = [
createTokenInstance(IdentTok, "a"),
createTokenInstance(DotTok),
createTokenInstance(IdentTok, "b"),
createTokenInstance(PlusTok),
createTokenInstance(DotTok),
createTokenInstance(IdentTok, "c")
]
const parser = new AtLeastOneSepRepetitionRecovery(input)
expect(parser.qualifiedName()).to.deep.equal(["a", "b", "c"])
expect(parser.errors.length).to.equal(1)
})
it("can disable in-repetition recovery for AT_LEAST_ONE_SEP grammar rule", () => {
// a.b+.c
const input = [
createTokenInstance(IdentTok, "a"),
createTokenInstance(DotTok),
createTokenInstance(IdentTok, "b"),
createTokenInstance(PlusTok),
createTokenInstance(DotTok),
createTokenInstance(IdentTok, "c")
]
const parser = new AtLeastOneSepRepetitionRecovery(input, false)
expect(parser.qualifiedName()).to.deep.equal(["999"])
expect(parser.errors.length).to.equal(1)
})
it("can perform single Token insertion", () => {
const A = createToken({ name: "A", pattern: /A/ })
const B = createToken({ name: "B", pattern: /B/ })
const C = createToken({ name: "C", pattern: /C/ })
const allTokens = [A, B, C]
const lexer = new Lexer(allTokens, {
positionTracking: "onlyOffset"
})
class SingleTokenInsertRegular extends EmbeddedActionsParser {
constructor(input: IToken[] = []) {
super(allTokens, {
recoveryEnabled: true
})
this.performSelfAnalysis()
this.input = input
}
public topRule = this.RULE("topRule", () => {
this.CONSUME(A)
const insertedToken = this.CONSUME(B)
this.CONSUME(C)
return insertedToken
})
}
const lexResult = lexer.tokenize("AC")
const parser = new SingleTokenInsertRegular(lexResult.tokens)
const insertedToken = parser.topRule()
expect(insertedToken.isInsertedInRecovery).to.be.true
expect(insertedToken.image).to.equal("")
expect(insertedToken.startOffset).to.be.NaN
expect(insertedToken.endOffset).to.be.NaN
expect(insertedToken.startLine).to.be.NaN
expect(insertedToken.endLine).to.be.NaN
expect(insertedToken.startColumn).to.be.NaN
expect(insertedToken.endColumn).to.be.NaN
})
})
describe("The Parsing DSL methods are expressions", () => {
it("OR will return the chosen alternative's grammar action's returned value", () => {
class OrExpressionParser extends EmbeddedActionsParser {
constructor(input: IToken[] = []) {
super(ALL_TOKENS, {})
this.performSelfAnalysis()
this.input = input
}
public orRule = this.RULE("orRule", () => {
return this.OR([
{
ALT: () => {
this.CONSUME1(MinusTok)
return 666
}
},
{
ALT: () => {
this.CONSUME1(PlusTok)
return "bamba"
}
}
])
})
}
const parser = new OrExpressionParser([])
parser.input = [createTokenInstance(MinusTok)]
expect(parser.orRule()).to.equal(666)
parser.input = [createTokenInstance(PlusTok)]
expect(parser.orRule()).to.equal("bamba")
})
it("OPTION will return the grammar action value or undefined if the option was not taken", () => {
class OptionExpressionParser extends EmbeddedActionsParser {
constructor(input: IToken[] = []) {
super(ALL_TOKENS, {})
this.performSelfAnalysis()
this.input = input
}
public optionRule = this.RULE("optionRule", () => {
return this.OPTION(() => {
this.CONSUME(IdentTok)
return "bamba"
})
})
}
const parser = new OptionExpressionParser([])
parser.input = [createTokenInstance(IdentTok)]
expect(parser.optionRule()).to.equal("bamba")
parser.input = [createTokenInstance(IntTok)]
expect(parser.optionRule()).to.be.undefined
})
})
describe("The BaseRecognizer", () => {
it("Cannot be initialized with a token vector (pre v4.0 API) ", () => {
expect(
() => new EmbeddedActionsParser([createTokenInstance(PlusTok)])
).to.throw(
"The Parser constructor no longer accepts a token vector as the first argument"
)
})
it("Cannot be initialized with a serializedGrammar property (pre v6.0 API)", () => {
const config: any = { serializedGrammar: {} }
expect(() => new EmbeddedActionsParser([], config)).to.throw(
"The Parser's configuration can no longer contain a <serializedGrammar> property."
)
})
it("Cannot be initialized with an empty Token vocabulary", () => {
expect(() => new EmbeddedActionsParser([])).to.throw(
"A Token Vocabulary cannot be empty"
)
})
it("Can skip Grammar Validations during initialization", () => {
class SkipValidationsParser extends EmbeddedActionsParser {
constructor(skipValidationsValue) {
super(ALL_TOKENS, {
skipValidations: skipValidationsValue
})
this.RULE("goodRule", () => {
this.CONSUME(IntTok)
// Duplicate CONSUME Idx error
this.CONSUME(IntTok)
})
this.performSelfAnalysis()
}
}
expect(() => new SkipValidationsParser(true)).to.not.throw()
expect(() => new SkipValidationsParser(false)).to.throw(
"Parser Definition Errors detected:"
)
})
it("can only SAVE_ERROR for recognition exceptions", () => {
const parser: any = new EmbeddedActionsParser([IntTok])
expect(() =>
parser.SAVE_ERROR(new Error("I am some random Error"))
).to.throw(
"Trying to save an Error which is not a RecognitionException"
)
expect(parser.input).to.be.an.instanceof(Array)
})
it("when it runs out of input EOF will be returned", () => {
const parser: any = new EmbeddedActionsParser([IntTok, PlusTok], {})
const sampleInput = [
createTokenInstance(IntTok, "1"),
createTokenInstance(PlusTok)
]
parser.tokVector = sampleInput
parser.tokVectorLength = sampleInput.length
parser.CONSUME(IntTok)
parser.CONSUME(PlusTok)
expect(tokenMatcher(parser.LA(1), EOF))
expect(tokenMatcher(parser.LA(1), EOF))
expect(tokenMatcher(parser.SKIP_TOKEN(), EOF))
expect(tokenMatcher(parser.SKIP_TOKEN(), EOF))
// and we can go on and on and on... this avoid returning null/undefined
// see: https://en.wikipedia.org/wiki/Tony_Hoare#Apologies_and_retractions
})
it("invoking an OPTION will return the inner grammar action's value or undefined", () => {
class OptionsReturnValueParser extends EmbeddedActionsParser {
constructor(input: IToken[] = [createTokenInstance(IntTok, "666")]) {
super(ALL_TOKENS, {})
this.performSelfAnalysis()
this.input = input
}
public trueOptionRule = this.RULE("trueOptionRule", () => {
return this.OPTION({
GATE: () => true,
DEF: () => {
this.CONSUME(IntTok)
return true
}
})
})
public falseOptionRule = this.RULE("falseOptionRule", () => {
return this.OPTION({
GATE: () => false,
DEF: () => {
this.CONSUME(IntTok)
return false
}
})
})
}
const successfulOption = new OptionsReturnValueParser().trueOptionRule()
expect(successfulOption).to.equal(true)
const failedOption = new OptionsReturnValueParser().falseOptionRule()
expect(failedOption).to.equal(undefined)
})
it("will return false if a RecognitionException is thrown during backtracking and rethrow any other kind of Exception", () => {
const parser: any = new EmbeddedActionsParser([IntTok])
const backTrackingThrows = parser.BACKTRACK(
() => {
throw new Error("division by zero, boom")
},
() => {
return true
}
)
expect(() => backTrackingThrows.call(parser)).to.throw(
"division by zero, boom"
)
const throwsRecogError = () => {
throw new NotAllInputParsedException(
"sad sad panda",
createTokenInstance(PlusTok)
)
}
const backTrackingFalse = parser.BACKTRACK(throwsRecogError, () => {
return true
})
expect(backTrackingFalse.call(parser)).to.equal(false)
})
})
describe("The BaseRecognizer", () => {
it("Will throw an error if performSelfAnalysis never called", () => {
class WrongOrderOfSelfAnalysisParser extends EmbeddedActionsParser {
constructor() {
super(ALL_TOKENS)
this.RULE("goodRule", () => {
this.CONSUME(IntTok)
})
this.RULE("badRule", () => {
this.CONSUME(IntTok)
})
}
}
expect(
() => (new WrongOrderOfSelfAnalysisParser().input = [])
).to.throw(
`Missing <performSelfAnalysis> invocation at the end of the Parser's constructor.`
)
})
it("Will throw an error if performSelfAnalysis is called before all the rules have been defined", () => {
class WrongOrderOfSelfAnalysisParser extends EmbeddedActionsParser {
constructor() {
super(ALL_TOKENS)
this.RULE("goodRule", () => {
this.CONSUME(IntTok)
})
this.performSelfAnalysis()
this.RULE("badRule", () => {
this.CONSUME(IntTok)
})
}
}
expect(() => new WrongOrderOfSelfAnalysisParser()).to.throw(
"Grammar rule <badRule> may not be defined after the 'performSelfAnalysis' method has been called"
)
})
it("Will throw an error is performSelfAnalysis is called before all the rules have been defined - static invocation", () => {
class WrongOrderOfSelfAnalysisParser extends EmbeddedActionsParser {
constructor() {
super(ALL_TOKENS)
this.RULE("goodRule", () => {
this.CONSUME(IntTok)
})
this.performSelfAnalysis()
this.RULE("badRule", () => {
this.CONSUME(IntTok)
})
}
}
expect(() => new WrongOrderOfSelfAnalysisParser()).to.throw(
"Grammar rule <badRule> may not be defined after the 'performSelfAnalysis' method has been called"
)
})
it("can be initialized with a vector of Tokens", () => {
const parser: any = new EmbeddedActionsParser([
PlusTok,
MinusTok,
IntTok
])
const tokensMap = (<any>parser).tokensMap
expect(tokensMap.PlusTok).to.equal(PlusTok)
expect(tokensMap.MinusTok).to.equal(MinusTok)
expect(tokensMap.IntTok).to.equal(IntTok)
})
it("can be initialized with a Dictionary of Tokens", () => {
const initTokenDictionary = {
PlusTok: PlusTok,
MinusTok: MinusTok,
IntToken: IntTok
}
const parser: any = new EmbeddedActionsParser({
PlusTok: PlusTok,
MinusTok: MinusTok,
IntToken: IntTok
})
const tokensMap = (<any>parser).tokensMap
// the implementation should clone the dictionary to avoid bugs caused by mutability
expect(tokensMap).not.to.equal(initTokenDictionary)
expect(tokensMap.PlusTok).to.equal(PlusTok)
expect(tokensMap.MinusTok).to.equal(MinusTok)
expect(tokensMap.IntToken).to.equal(IntTok)
})
it("can be initialized with a IMultiModeLexerDefinition of Tokens", () => {
const multiModeLexerDef: IMultiModeLexerDefinition = {
modes: {
bamba: [PlusTok],
bisli: [MinusTok, IntTok]
},
defaultMode: "bisli"
}
const parser: any = new EmbeddedActionsParser(multiModeLexerDef)
const tokensMap = (<any>parser).tokensMap
// the implementation should clone the dictionary to avoid bugs caused by mutability
expect(tokensMap).not.to.equal(multiModeLexerDef)
expect(tokensMap.PlusTok).to.equal(PlusTok)
expect(tokensMap.MinusTok).to.equal(MinusTok)
expect(tokensMap.IntTok).to.equal(IntTok)
})
it("cannot be initialized with other parameters", () => {
expect(() => {
return new EmbeddedActionsParser(null)
}).to.throw()
expect(() => {
return new EmbeddedActionsParser(<any>666)
}).to.throw()
expect(() => {
return new EmbeddedActionsParser(<any>"woof woof")
}).to.throw()
})
it("will not swallow none Recognizer errors when attempting 'in rule error recovery'", () => {
class NotSwallowInRuleParser extends EmbeddedActionsParser {
constructor(input: IToken[] = []) {
super(ALL_TOKENS, {
recoveryEnabled: true
})
this.performSelfAnalysis()
this.input = input
}
public someRule = this.RULE("someRule", () => {
this.CONSUME1(DotTok)
})
}
const parser: any = new NotSwallowInRuleParser([
createTokenInstance(IntTok, "1")
])
parser.tryInRuleRecovery = () => {
throw Error("oops")
}
expect(() => parser.someRule()).to.throw("oops")
})
it("will not swallow none Recognizer errors during Token consumption", () => {
class NotSwallowInTokenConsumption extends EmbeddedActionsParser {
constructor(input: IToken[] = []) {
super(ALL_TOKENS, {
recoveryEnabled: true
})
this.performSelfAnalysis()
this.input = input
}
public someRule = this.RULE("someRule", () => {
this.CONSUME1(DotTok)
})
}
const parser: any = new NotSwallowInTokenConsumption([
createTokenInstance(IntTok, "1")
])
;(parser as any).consumeInternal = () => {
throw Error("oops")
}
expect(() => parser.someRule()).to.throw("oops")
})
it("will rethrow none Recognizer errors during Token consumption - recovery disabled + nested rule", () => {
class RethrowOtherErrors extends EmbeddedActionsParser {
constructor(input: IToken[] = []) {
super(ALL_TOKENS, {
recoveryEnabled: true
})
this.performSelfAnalysis()
this.input = input
}
public someRule = this.RULE("someRule", () => {
let isThrown = false
try {
this.SUBRULE(this.someNestedRule)
} catch (e) {
isThrown = true
} finally {
this.ACTION(() => {
expect(isThrown).to.be.true
})
}
})
public someNestedRule = this.RULE(
"someNestedRule",
() => {
this.CONSUME1(DotTok)
this.CONSUME1(IdentTok)
},
{
resyncEnabled: false
}
)
}
const parser: any = new RethrowOtherErrors([
createTokenInstance(IntTok, "1")
])
parser.someRule()
})
it("Will use Token LABELS for mismatch error messages when available", () => {
class LabelTokParser extends EmbeddedActionsParser {
constructor(input: IToken[] = []) {
super([PlusTok, MinusTok])
this.performSelfAnalysis()
this.input = input
}
public rule = this.RULE("rule", () => {
this.CONSUME1(PlusTok)
})
}
const parser = new LabelTokParser([createTokenInstance(MinusTok)])
parser.rule()
expect(parser.errors[0]).to.be.an.instanceof(MismatchedTokenException)
expect(parser.errors[0].message).to.include("+")
expect(parser.errors[0].message).to.not.include("token of type")
})
it("Will not use Token LABELS for mismatch error messages when unavailable", () => {
class NoLabelTokParser extends EmbeddedActionsParser {
constructor(input: IToken[] = []) {
super([PlusTok, MinusTok])
this.performSelfAnalysis()
this.input = input
}
public rule = this.RULE("rule", () => {
this.CONSUME1(MinusTok)
})
}
const parser = new NoLabelTokParser([createTokenInstance(PlusTok)])
parser.rule()
expect(parser.errors[0]).to.be.an.instanceof(MismatchedTokenException)
expect(parser.errors[0].message).to.include("MinusTok")
expect(parser.errors[0].message).to.include("token of type")
expect(parser.errors[0].context.ruleStack).to.deep.equal(["rule"])
})
it("Supports custom overriding of the mismatch token error message", () => {
const SemiColon = createToken({ name: "SemiColon" })
class CustomConsumeErrorParser extends EmbeddedActionsParser {
constructor(input: IToken[] = []) {
super([SemiColon])
this.performSelfAnalysis()
this.input = input
}
public myStatement = this.RULE("myStatement", () => {
this.CONSUME1(SemiColon, {
ERR_MSG: "expecting semiColon at end of myStatement"
})
})
}
const parser = new CustomConsumeErrorParser([
createTokenInstance(PlusTok)
])
parser.myStatement()
expect(parser.errors[0]).to.be.an.instanceof(MismatchedTokenException)
expect(parser.errors[0].message).to.equal(
"expecting semiColon at end of myStatement"
)
expect(parser.errors[0].context.ruleStack).to.deep.equal([
"myStatement"
])
})
it("Supports custom overriding of the NO Matching Alternative error message", () => {
const SemiColon = createToken({ name: "SemiColon" })
class CustomOrErrorParser extends EmbeddedActionsParser {
constructor(input: IToken[] = []) {
super([SemiColon])
this.performSelfAnalysis()
this.input = input
}
public myStatement = this.RULE("myStatement", () => {
this.OR1({
DEF: [
{ ALT: () => this.CONSUME(PlusTok) },
{ ALT: () => this.CONSUME(MinusTok) }
],
ERR_MSG: "None of the alternatives matched"
})
})
}
const parser = new CustomOrErrorParser([createTokenInstance(DotTok)])
parser.myStatement()
expect(parser.errors[0]).to.be.an.instanceof(NoViableAltException)
expect(parser.errors[0].message).to.include(
"None of the alternatives matched"
)
expect(parser.errors[0].context.ruleStack).to.deep.equal([
"myStatement"
])
})
it("Will use Token LABELS for noViableAlt error messages when unavailable", () => {
class LabelAltParser extends EmbeddedActionsParser {
constructor(input: IToken[] = []) {
super([PlusTok, MinusTok])
this.performSelfAnalysis()
this.input = input
}
public rule = this.RULE("rule", () => {
this.OR([
{
ALT: () => {
this.CONSUME1(PlusTok)
}
},
{
ALT: () => {
this.CONSUME1(MinusTok)
}
}
])
})
}
const parser = new LabelAltParser([])
parser.rule()
expect(parser.errors[0]).to.be.an.instanceof(NoViableAltException)
expect(parser.errors[0].context.ruleStack).to.deep.equal(["rule"])
expect(parser.errors[0].message).to.include("MinusTok")
expect(parser.errors[0].message).to.include("+")
expect(parser.errors[0].message).to.not.include("PlusTok")
})
it("Will not throw a JS runtime exception on noViableAlt - issue #887", () => {
class MaxlookaheadOneAlt extends EmbeddedActionsParser {
constructor(input: IToken[] = []) {
super([PlusTok, MinusTok], { maxLookahead: 1 })
this.performSelfAnalysis()
this.input = input
}
public rule = this.RULE("rule", () => {
this.OR([
{
ALT: () => {
this.CONSUME1(PlusTok)
}
},
{
ALT: () => {
this.CONSUME1(MinusTok)
}
}
])
})
}
const parser = new MaxlookaheadOneAlt([])
parser.rule()
expect(parser.errors[0]).to.be.an.instanceof(NoViableAltException)
expect(parser.errors[0].context.ruleStack).to.deep.equal(["rule"])
expect(parser.errors[0].message).to.include("MinusTok")
expect(parser.errors[0].message).to.include("+")
expect(parser.errors[0].message).to.not.include("PlusTok")
})
it("Supports custom error messages for OR", () => {
class LabelAltParser2 extends EmbeddedActionsParser {
constructor(input: IToken[] = []) {
super([PlusTok, MinusTok], {})
this.performSelfAnalysis()
this.input = input
}
public rule = this.RULE("rule", () => {
this.OR({
DEF: [
{
ALT: () => {
this.CONSUME1(PlusTok)
}
},
{
ALT: () => {
this.CONSUME1(MinusTok)
}
}
],
ERR_MSG: "bisli"
})
})
}
const parser = new LabelAltParser2([])
parser.rule()
expect(parser.errors[0]).to.be.an.instanceof(NoViableAltException)
expect(parser.errors[0].context.ruleStack).to.deep.equal(["rule"])
expect(parser.errors[0].message).to.include("bisli")
})
it("Will include the ruleStack in a recognition Exception", () => {
class NestedRulesParser extends EmbeddedActionsParser {
constructor(input: IToken[] = []) {
super([PlusTok, MinusTok])
this.performSelfAnalysis()
this.input = input
}
public rule = this.RULE("rule", () => {
this.OPTION({
DEF: () => {
this.SUBRULE1(this.rule2)
}
})
})
public rule2 = this.RULE("rule2", () => {
this.OPTION(() => {
this.SUBRULE5(this.rule3)
})
})
public rule3 = this.RULE("rule3", () => {
this.CONSUME1(MinusTok)
this.CONSUME1(PlusTok)
})
}
const parser = new NestedRulesParser([
createTokenInstance(MinusTok),
createTokenInstance(MinusTok)
])
parser.rule()
expect(parser.errors[0]).to.be.an.instanceof(MismatchedTokenException)
expect(parser.errors[0].context.ruleStack).to.deep.equal([
"rule",
"rule2",
"rule3"
])
expect(parser.errors[0].context.ruleOccurrenceStack).to.deep.equal([
0, 1, 5
])
})
it("Will build an error message for AT_LEAST_ONE automatically", () => {
class ImplicitAtLeastOneErrParser extends EmbeddedActionsParser {
constructor(input: IToken[] = []) {
super([PlusTok, MinusTok])
this.performSelfAnalysis()
this.input = input
}
public rule = this.RULE("rule", () => {
this.AT_LEAST_ONE(() => {
this.SUBRULE(this.rule2)
})
})
public rule2 = this.RULE("rule2", () => {
this.OR([
{
ALT: () => {
this.CONSUME1(MinusTok)
}
},
{
ALT: () => {
this.CONSUME1(PlusTok)
}
}
])
})
}
const parser = new ImplicitAtLeastOneErrParser([
createTokenInstance(IntTok, "666"),
createTokenInstance(MinusTok),
createTokenInstance(MinusTok)
])
parser.rule()
expect(parser.errors[0]).to.be.an.instanceof(EarlyExitException)
expect(parser.errors[0].message).to.contain(
"expecting at least one iteration"
)
expect(parser.errors[0].message).to.contain("MinusTok")
expect(parser.errors[0].message).to.contain("+")
expect(parser.errors[0].message).to.contain("but found: '666'")
expect(parser.errors[0].context.ruleStack).to.deep.equal(["rule"])
})
it("supports custom error messages for AT_LEAST_ONE", () => {
class ExplicitAtLeastOneErrParser extends EmbeddedActionsParser {
constructor(input: IToken[] = []) {
super([PlusTok, MinusTok])
this.performSelfAnalysis()
this.input = input
}
public rule = this.RULE("rule", () => {
this.AT_LEAST_ONE({
DEF: () => {
this.SUBRULE(this.rule2)
},
ERR_MSG: "bamba"
})
})
public rule2 = this.RULE("rule2", () => {
this.OR([
{
ALT: () => {
this.CONSUME1(MinusTok)
}
},
{
ALT: () => {
this.CONSUME1(PlusTok)
}
}
])
})
}
const parser = new ExplicitAtLeastOneErrParser([
createTokenInstance(IntTok, "666"),
createTokenInstance(MinusTok),
createTokenInstance(MinusTok)
])
parser.rule()
expect(parser.errors[0]).to.be.an.instanceof(EarlyExitException)
expect(parser.errors[0].message).to.contain("bamba")
expect(parser.errors[0].context.ruleStack).to.deep.equal(["rule"])
})
it("Will build an error message for AT_LEAST_ONE_SEP automatically", () => {
class ImplicitAtLeastOneSepErrParser extends EmbeddedActionsParser {
constructor(input: IToken[] = []) {
super([PlusTok, MinusTok, IdentTok])
this.performSelfAnalysis()
this.input = input
}
public rule = this.RULE("rule", () => {
this.AT_LEAST_ONE_SEP({
SEP: IdentTok,
DEF: () => {
this.SUBRULE(this.rule2)
}
})
})
public rule2 = this.RULE("rule2", () => {
this.OR([
{
ALT: () => {
this.CONSUME1(MinusTok)
}
},
{
ALT: () => {
this.CONSUME1(PlusTok)
}
}
])
})
}
const parser = new ImplicitAtLeastOneSepErrParser([
createTokenInstance(IntTok, "666"),
createTokenInstance(MinusTok),
createTokenInstance(MinusTok)
])
parser.rule()
expect(parser.errors[0]).to.be.an.instanceof(EarlyExitException)
expect(parser.errors[0].message).to.contain(
"expecting at least one iteration"
)
expect(parser.errors[0].message).to.contain("MinusTok")
expect(parser.errors[0].message).to.contain("+")
expect(parser.errors[0].message).to.contain("but found: '666'")
expect(parser.errors[0].context.ruleStack).to.deep.equal(["rule"])
expect(parser.errors[0].context.ruleOccurrenceStack).to.deep.equal([0])
})
it("can serialize a Grammar's Structure", () => {
class SomeParser extends EmbeddedActionsParser {
constructor(input: IToken[] = []) {
super([PlusTok, MinusTok, IdentTok])
this.performSelfAnalysis()
this.input = input
}
public rule = this.RULE("rule", () => {
this.AT_LEAST_ONE_SEP({
SEP: IdentTok,
DEF: () => {
this.SUBRULE(this.rule2)
}
})
})
public rule2 = this.RULE("rule2", () => {
this.OR([
{
ALT: () => {
this.CONSUME1(MinusTok)
}
},
{
ALT: () => {
this.CONSUME1(PlusTok)
}
}
])
})
}
const parser = new SomeParser([])
const serializedGrammar = parser.getSerializedGastProductions()
// not bothering with more in-depth checks as those unit tests exist elsewhere
expect(serializedGrammar).to.have.lengthOf(2)
expect(serializedGrammar[0].type).to.equal("Rule")
expect(serializedGrammar[1].type).to.equal("Rule")
})
it("can provide syntactic content assist suggestions", () => {
class ContentAssistParser extends EmbeddedActionsParser {
constructor(input: IToken[] = []) {
super([PlusTok, MinusTok, IdentTok])
this.performSelfAnalysis()
this.input = input
}
public topRule = this.RULE("topRule", () => {
this.MANY(() => {
this.SUBRULE4(this.rule2)
})
})
public rule2 = this.RULE("rule2", () => {
this.OR([
{
ALT: () => {
this.CONSUME1(MinusTok)
}
},
{
ALT: () => {
this.CONSUME3(PlusTok)
}
}
])
})
}
const parser = new ContentAssistParser([])
setEquality(parser.computeContentAssist("topRule", []), [
{
nextTokenType: MinusTok,
nextTokenOccurrence: 1,
ruleStack: ["topRule", "rule2"],
occurrenceStack: [1, 4]
},
{
nextTokenType: PlusTok,
nextTokenOccurrence: 3,
ruleStack: ["topRule", "rule2"],
occurrenceStack: [1, 4]
}
])
setEquality(
parser.computeContentAssist("topRule", [
createTokenInstance(MinusTok)
]),
[
{
nextTokenType: MinusTok,
nextTokenOccurrence: 1,
ruleStack: ["topRule", "rule2"],
occurrenceStack: [1, 4]
},
{
nextTokenType: PlusTok,
nextTokenOccurrence: 3,
ruleStack: ["topRule", "rule2"],
occurrenceStack: [1, 4]
}
]
)
expect(() =>
parser.computeContentAssist("invalid_rule_name", [])
).to.throw("does not exist in this grammar")
})
})
})
}
defineRecognizerSpecs(
"Regular Tokens Mode",
createToken,
createRegularToken,
tokenStructuredMatcher
) | the_stack |
import test from 'japa'
import { join } from 'path'
import supertest from 'supertest'
import { createServer } from 'http'
import { Ignitor } from '../src/Ignitor'
import { setupApplicationFiles, fs } from '../test-helpers'
test.group('Ignitor | Http', (group) => {
group.before(() => {
process.env.ENV_SILENT = 'true'
})
group.beforeEach(() => {
process.env.NODE_ENV = 'testing'
})
group.after(async () => {
await fs.cleanup()
delete process.env.ENV_SILENT
delete process.env.APP_KEY
})
group.afterEach(async () => {
process.removeAllListeners('SIGINT')
process.removeAllListeners('SIGTERM')
delete process.env.NODE_ENV
await fs.cleanup()
})
test('call ready hook on providers before starting the http server', async (assert, done) => {
await fs.add(
'providers/AppProvider.ts',
`
export default class AppProvider {
constructor (protected $app) {}
public static needsApplication = true
public async ready () {
this.$app.container.use('Adonis/Core/Server').hookCalled = true
}
}
`
)
await setupApplicationFiles(['./providers/AppProvider'])
const httpServer = new Ignitor(fs.basePath).httpServer()
await httpServer.start()
const server = httpServer.application.container.use('Adonis/Core/Server')
server.instance!.close(() => {
done()
})
assert.isTrue(server['hookCalled'])
})
test('start http server to accept incoming requests', async (assert, done) => {
await setupApplicationFiles()
const ignitor = new Ignitor(fs.basePath)
const httpServer = ignitor.httpServer()
await httpServer.application.setup()
await httpServer.application.registerProviders()
await httpServer.application.bootProviders()
/**
* Define routes
*/
const server = httpServer.application.container.use('Adonis/Core/Server')
httpServer.application.container.use('Adonis/Core/Route').get('/', async () => 'handled')
await httpServer.start((handler) => createServer(handler))
assert.isTrue(httpServer.application.isReady)
const { text } = await supertest(server.instance).get('/').expect(200)
server.instance!.close()
setTimeout(() => {
assert.isFalse(httpServer.application.isReady)
assert.equal(text, 'handled')
done()
}, 100)
})
test('forward errors to app error handler', async (assert, done) => {
await setupApplicationFiles()
await fs.add(
'app/Exceptions/Handler.ts',
`
export default class Handler {
async handle (error) {
return \`handled \${error.message}\`
}
report () {
}
}
`
)
/**
* Overwriting .adonisrc.json
*/
await fs.add(
'.adonisrc.json',
JSON.stringify({
typescript: true,
autoloads: {
App: './app',
},
providers: [join(__dirname, '../providers/AppProvider.ts')],
exceptionHandlerNamespace: 'App/Exceptions/Handler',
})
)
const ignitor = new Ignitor(fs.basePath)
const httpServer = ignitor.httpServer()
await httpServer.application.setup()
await httpServer.application.registerProviders()
await httpServer.application.bootProviders()
await httpServer.start((handler) => createServer(handler))
const server = httpServer.application.container.use('Adonis/Core/Server')
const { text } = await supertest(server.instance).get('/').expect(404)
server.instance!.close(() => {
done()
})
assert.equal(text, 'handled E_ROUTE_NOT_FOUND: Cannot GET:/')
})
test('kill app when server receives error', async (assert) => {
assert.plan(1)
await setupApplicationFiles()
const ignitor = new Ignitor(fs.basePath)
const httpServer = ignitor.httpServer()
httpServer.application.setup()
httpServer.application.registerProviders()
await httpServer.application.bootProviders()
httpServer.kill = async function kill() {
assert.isTrue(true)
server.instance!.close()
}
await httpServer.start((handler) => createServer(handler))
const server = httpServer.application.container.use('Adonis/Core/Server')
server.instance!.emit('error', new Error())
})
test('close http server gracefully when closing the app', async (assert, done) => {
assert.plan(2)
await setupApplicationFiles()
const ignitor = new Ignitor(fs.basePath)
const httpServer = ignitor.httpServer()
await httpServer.start((handler) => createServer(handler))
const server = httpServer.application.container.use('Adonis/Core/Server')
server.instance!.on('close', () => {
assert.isTrue(true)
assert.isFalse(httpServer.application.isReady)
done()
})
await httpServer.close()
})
test('invoke shutdown method when gracefully closing the app', async (assert) => {
await fs.add(
'providers/AppProvider.ts',
`
export default class AppProvider {
constructor (protected $app) {}
public static needsApplication = true
public async shutdown () {
this.$app.container.use('Adonis/Core/Server').hookCalled = true
}
}
`
)
await setupApplicationFiles(['./providers/AppProvider'])
const ignitor = new Ignitor(fs.basePath)
const httpServer = ignitor.httpServer()
await httpServer.start((handler) => createServer(handler))
const server = httpServer.application.container.use('Adonis/Core/Server')
await httpServer.close()
assert.isTrue(server['hookCalled'])
})
})
test.group('Ignitor | HTTP | Static Assets', (group) => {
group.before(() => {
process.env.ENV_SILENT = 'true'
})
group.beforeEach(() => {
process.env.NODE_ENV = 'testing'
})
group.after(async () => {
await fs.cleanup()
delete process.env.ENV_SILENT
delete process.env.APP_KEY
})
group.afterEach(async () => {
process.removeAllListeners('SIGINT')
process.removeAllListeners('SIGTERM')
delete process.env.NODE_ENV
await fs.cleanup()
})
test('serve static files when static hooks is enabled', async (assert, done) => {
await setupApplicationFiles()
await fs.add(
'config/static.ts',
`
export const enabled = true
`
)
await fs.add('public/style.css', 'body { background: #000 }')
const ignitor = new Ignitor(fs.basePath)
const httpServer = ignitor.httpServer()
await httpServer.application.setup()
await httpServer.application.registerProviders()
await httpServer.application.bootProviders()
const server = httpServer.application.container.use('Adonis/Core/Server')
await httpServer.start((handler) => createServer(handler))
assert.isTrue(httpServer.application.isReady)
const { text } = await supertest(server.instance).get('/style.css').expect(200)
server.instance!.close()
setTimeout(() => {
assert.isFalse(httpServer.application.isReady)
assert.equal(text, 'body { background: #000 }')
done()
}, 100)
})
test('serve static files from a custom public path', async (assert, done) => {
await setupApplicationFiles()
await fs.add(
'config/static.ts',
`
export const enabled = true
`
)
/**
* Overwriting .adonisrc.json
*/
const existingContent = await fs.get('.adonisrc.json')
await fs.add(
'.adonisrc.json',
JSON.stringify(
Object.assign(JSON.parse(existingContent), {
directories: {
public: 'www',
},
})
)
)
await fs.add('www/style.css', 'body { background: #000 }')
const ignitor = new Ignitor(fs.basePath)
const httpServer = ignitor.httpServer()
await httpServer.application.setup()
await httpServer.application.registerProviders()
await httpServer.application.bootProviders()
const server = httpServer.application.container.use('Adonis/Core/Server')
await httpServer.start((handler) => createServer(handler))
assert.isTrue(httpServer.application.isReady)
const { text } = await supertest(server.instance).get('/style.css').expect(200)
server.instance!.close()
setTimeout(() => {
assert.isFalse(httpServer.application.isReady)
assert.equal(text, 'body { background: #000 }')
done()
}, 100)
})
})
test.group('Ignitor | HTTP | CORS', (group) => {
group.before(() => {
process.env.ENV_SILENT = 'true'
})
group.beforeEach(() => {
process.env.NODE_ENV = 'testing'
})
group.after(async () => {
await fs.cleanup()
delete process.env.ENV_SILENT
delete process.env.APP_KEY
})
group.afterEach(async () => {
process.removeAllListeners('SIGINT')
process.removeAllListeners('SIGTERM')
delete process.env.NODE_ENV
await fs.cleanup()
})
test('respond to pre-flight requests when cors are enabled', async (assert, done) => {
await setupApplicationFiles()
await fs.add(
'config/cors.ts',
`
export const enabled = true
export const exposeHeaders = []
export const methods = ['GET']
export const origin = true
export const headers = true
`
)
const ignitor = new Ignitor(fs.basePath)
const httpServer = ignitor.httpServer()
await httpServer.application.setup()
await httpServer.application.registerProviders()
await httpServer.application.bootProviders()
const server = httpServer.application.container.use('Adonis/Core/Server')
await httpServer.start((handler) => createServer(handler))
assert.isTrue(httpServer.application.isReady)
const { header } = await supertest(server.instance)
.options('/')
.set('origin', 'foo.com')
.set('Access-Control-Request-Method', 'GET')
.expect(204)
server.instance!.close()
setTimeout(() => {
assert.isFalse(httpServer.application.isReady)
assert.equal(header['access-control-allow-origin'], 'foo.com')
assert.equal(header['access-control-allow-methods'], 'GET')
done()
}, 100)
})
}) | the_stack |
import { inject, injectable } from 'inversify';
import { FindConditions, FindManyOptions, In, IsNull, LessThan, LessThanOrEqual, MoreThanOrEqual } from 'typeorm';
import * as apid from '../../../api';
import Reserve from '../../db/entities/Reserve';
import { IReserveUpdateValues } from '../event/IReserveEvent';
import IPromiseRetry from '../IPromiseRetry';
import IDBOperator from './IDBOperator';
import IReserveDB, {
IFindRuleOption,
IFindTimeRangesOption,
IFindTimeSpecificationOption,
IGetManualIdsOption,
IReserveTimeOption,
RuleIdCountResult,
} from './IReserveDB';
@injectable()
export default class ReserveDB implements IReserveDB {
private op: IDBOperator;
private promieRetry: IPromiseRetry;
constructor(@inject('IDBOperator') op: IDBOperator, @inject('IPromiseRetry') promieRetry: IPromiseRetry) {
this.op = op;
this.promieRetry = promieRetry;
}
/**
* バックアップから復元
* @param items: Reserve[]
* @return Promise<void>
*/
public async restore(items: Reserve[]): Promise<void> {
// get queryRunner
const connection = await this.op.getConnection();
const queryRunner = connection.createQueryRunner();
// start transaction
await queryRunner.startTransaction();
let hasError = false;
try {
// 削除
await queryRunner.manager.delete(Reserve, {});
// 挿入処理
for (const item of items) {
await queryRunner.manager.insert(Reserve, item);
}
await queryRunner.commitTransaction();
} catch (err) {
console.error(err);
hasError = err;
await queryRunner.rollbackTransaction();
} finally {
await queryRunner.release();
}
if (hasError) {
throw new Error('restore error');
}
}
/**
* 1つだけ挿入
* @param reserve: Reserve
* @return inserted id
*/
public async insertOnce(reserve: Reserve): Promise<apid.ReserveId> {
const connection = await this.op.getConnection();
const queryBuilder = connection.createQueryBuilder().insert().into(Reserve).values(reserve);
const insertedResult = await this.promieRetry.run(() => {
return queryBuilder.execute();
});
return insertedResult.identifiers[0].id;
}
/**
* 1件更新
* @param reserve: Reserve
*/
public async updateOnce(reserve: Reserve): Promise<void> {
const connection = await this.op.getConnection();
const queryBuilder = connection
.createQueryBuilder()
.update(Reserve)
.set(reserve)
.where('id = :id', { id: reserve.id });
await this.promieRetry.run(() => {
return queryBuilder.execute();
});
}
/**
* delete, insert, update をまとめて行う
* @param values: IReserveUpdateValues
*/
public async updateMany(values: IReserveUpdateValues): Promise<void> {
const connection = await this.op.getConnection();
const queryRunner = connection.createQueryRunner();
// start transaction
await queryRunner.startTransaction();
let hasError = false;
try {
// delete
if (typeof values.delete !== 'undefined' && values.delete.length > 0) {
const deleteIds = values.delete.map(d => {
return d.id;
});
await queryRunner.manager.delete(Reserve, deleteIds);
}
// insert
if (typeof values.insert !== 'undefined' && values.insert.length > 0) {
for (const newReserve of values.insert) {
const result = await queryRunner.manager.insert(Reserve, newReserve);
// set inserted id
newReserve.id = result.identifiers[0].id;
}
}
// update
if (typeof values.update !== 'undefined' && values.update.length > 0) {
for (const u of values.update) {
await queryRunner.manager.update(Reserve, u.id, u);
}
}
await queryRunner.commitTransaction();
} catch (err) {
console.error(err);
hasError = true;
await queryRunner.rollbackTransaction();
} finally {
await queryRunner.release();
}
if (hasError === true) {
throw new Error('ReserveUpdateManyError');
}
}
/**
* 指定した id の予約情報を取得する
* @param reserveId: apid.ReserveId
* @return Promise<Reserve | null>
*/
public async findId(reserveId: apid.ReserveId): Promise<Reserve | null> {
const connection = await this.op.getConnection();
const queryBuilder = await connection.getRepository(Reserve);
const result = await this.promieRetry.run(() => {
return queryBuilder.findOne({
where: { id: reserveId },
});
});
return typeof result === 'undefined' ? null : result;
}
/**
* 全件取得
* @param option: GetReserveOption
* @return Promise<Reserve[]>
*/
public async findAll(option: apid.GetReserveOption): Promise<[Reserve[], number]> {
const connection = await this.op.getConnection();
const queryBuilder = await connection.getRepository(Reserve);
return await this.promieRetry.run(() => {
return queryBuilder.findAndCount(this.createFindOption(option));
});
}
private createFindOption(option: apid.GetReserveOption): FindManyOptions<Reserve> {
const findConditions: FindConditions<Reserve> = {};
this.setReserveTypeOption(option.type, findConditions);
if (typeof option.ruleId !== 'undefined') {
findConditions.ruleId = option.ruleId;
}
const findOption: FindManyOptions<Reserve> = {
where: findConditions,
};
if (typeof option.offset !== 'undefined') {
findOption.skip = option.offset;
}
if (typeof option.limit !== 'undefined') {
findOption.take = option.limit;
}
findOption.order = {
startAt: 'ASC',
};
return findOption;
}
private setReserveTypeOption(type: apid.GetReserveType | undefined, findConditions: FindConditions<Reserve>): void {
if (type === 'normal') {
findConditions.isConflict = false;
findConditions.isSkip = false;
findConditions.isOverlap = false;
} else if (type === 'conflict') {
findConditions.isConflict = true;
findConditions.isSkip = false;
findConditions.isOverlap = false;
} else if (type === 'skip') {
findConditions.isConflict = false;
findConditions.isSkip = true;
findConditions.isOverlap = false;
} else if (type === 'overlap') {
findConditions.isConflict = false;
findConditions.isSkip = false;
findConditions.isOverlap = true;
}
}
/**
* オプションで指定した時刻間の予約情報を取得する
* @param option: GetReserveListsOption
* @return Promise<Reserve[]>
*/
public async findLists(option?: apid.GetReserveListsOption): Promise<Reserve[]> {
const connection = await this.op.getConnection();
const queryBuilder = connection.getRepository(Reserve);
return await this.promieRetry.run(() => {
return typeof option === 'undefined'
? queryBuilder.find()
: queryBuilder.find(this.createFindListOption(option));
});
}
private createFindListOption(option: apid.GetReserveListsOption): FindManyOptions<Reserve> {
const findConditions: FindConditions<Reserve> = {
startAt: LessThanOrEqual((<apid.GetReserveListsOption>option).endAt),
endAt: MoreThanOrEqual((<apid.GetReserveListsOption>option).startAt),
};
return { where: findConditions };
}
/**
* program id を指定して検索
* @param programId program id
* @return Promise<Reserve[]>
*/
public async findProgramId(programId: apid.ProgramId): Promise<Reserve[]> {
const connection = await this.op.getConnection();
const queryBuilder = connection.getRepository(Reserve);
return await this.promieRetry.run(() => {
return queryBuilder.find({
where: { programId: programId },
});
});
}
/**
* 指定した時間帯の予約情報を取得する
* @param option: IFindTimeRangesOption
* @return Promise<Reserve[]>
*/
public async findTimeRanges(option: IFindTimeRangesOption): Promise<Reserve[]> {
// times が空か
if (option.times.length === 0) {
return [];
}
const connection = await this.op.getConnection();
let queryBuilder = await connection.getRepository(Reserve).createQueryBuilder('reserve');
// option.times の重複を削除
const newTimes: IReserveTimeOption[] = [];
const timeIndex: { [key: string]: boolean } = {};
for (const time of option.times) {
const key = time.startAt.toString() + time.endAt.toString();
if (typeof timeIndex[key] === 'undefined') {
timeIndex[key] = true;
newTimes.push(time);
}
}
option.times = newTimes;
// option.times の連続した時間を一つにまとめる
option.times = option.times.reduce((acc, cur, index) => {
if (index === 0) {
return acc;
}
if (acc[acc.length - 1].endAt === cur.startAt) {
acc[acc.length - 1].endAt = cur.endAt;
} else {
acc.push(cur);
}
return acc;
}, option.times.slice(0, 1));
// times
let timesQuery = '';
const timesValues: any = {};
option.times.forEach((time, i) => {
const startAtName = `startAt${i}`;
const endAtName = `endAt${i}`;
const baseQuery = `(reserve.endAt >= :${startAtName} and reserve.startAt < :${endAtName})`;
timesQuery += i === option.times.length - 1 ? baseQuery : `${baseQuery} or `;
timesValues[startAtName] = time.startAt;
timesValues[endAtName] = time.endAt;
});
queryBuilder = queryBuilder.where(`(${timesQuery})`, timesValues);
// isSkip
if (option.hasSkip === false) {
queryBuilder = queryBuilder.andWhere('reserve.isSkip = :isSkip', {
isSkip: false,
});
}
// isConflict
if (option.hasConflict === false) {
queryBuilder = queryBuilder.andWhere('reserve.isConflict = :isConflict', {
isConflict: false,
});
}
// isOverlap
if (option.hasOverlap === false) {
queryBuilder = queryBuilder.andWhere('reserve.isOverlap = :isOverlap', {
isOverlap: false,
});
}
// 指定された ruleId の除外
if (typeof option.excludeRuleId !== 'undefined') {
queryBuilder = queryBuilder.andWhere('(reserve.ruleId <> :ruleId or reserve.ruleId is null)', {
ruleId: option.excludeRuleId,
});
}
// 指定された予約 id の除外
if (typeof option.excludeReserveId !== 'undefined') {
queryBuilder = queryBuilder.andWhere('reserve.id <> :reserveId', {
reserveId: option.excludeReserveId,
});
}
queryBuilder = queryBuilder.orderBy('reserve.startAt', 'ASC');
return await this.promieRetry.run(() => {
return queryBuilder.getMany();
});
}
/**
* 指定した ruleId の予約情報を取り出す
* @param option IFindRuleOption
*/
public async findRuleId(option: IFindRuleOption): Promise<Reserve[]> {
const connection = await this.op.getConnection();
const whereOption: FindConditions<Reserve>[] = [{ ruleId: option.ruleId }];
if (option.hasSkip === false) {
whereOption.push({ isSkip: false });
}
if (option.hasConflict === false) {
whereOption.push({ isConflict: false });
}
if (option.hasOverlap === false) {
whereOption.push({ isOverlap: false });
}
const queryBuilder = connection.getRepository(Reserve);
return await this.promieRetry.run(() => {
return queryBuilder.find({
where: whereOption,
order: {
startAt: 'ASC',
},
});
});
}
/**
* baseTime で指定した時間より古い予約を取得する
* @param baseTime: apid.UnixtimeMS
* @return Promise<Reserve[]>
*/
public async findOldTime(baseTime: apid.UnixtimeMS): Promise<Reserve[]> {
const connection = await this.op.getConnection();
const queryBuilder = connection.getRepository(Reserve);
return await this.promieRetry.run(() => {
return queryBuilder.find({
endAt: LessThan(baseTime),
});
});
}
/**
* 時刻指定予約を検索する
* @param option: IFindTimeSpecificationOption
* @return Promise<Reserve | null>
*/
public async findTimeSpecification(option: IFindTimeSpecificationOption): Promise<Reserve | null> {
const connection = await this.op.getConnection();
const queryBuilder = connection.getRepository(Reserve);
const result = await this.promieRetry.run(() => {
return queryBuilder.findOne({
where: {
channelId: option.channelId,
startAt: option.startAt,
endAt: option.endAt,
ruleId: IsNull(),
},
});
});
return typeof result === 'undefined' ? null : result;
}
/**
* 手動予約の reserve id を取得する
* @param option: IGetManualIdsOption
*/
public async getManualIds(option: IGetManualIdsOption): Promise<apid.ReserveId[]> {
const connection = await this.op.getConnection();
let queryBuilder = connection
.createQueryBuilder()
.select('reserve.id')
.from(Reserve, 'reserve')
.where('reserve.ruleId is null');
if (option.hasTimeReserve === false) {
queryBuilder = queryBuilder.andWhere('reserve.programId is not null');
}
queryBuilder = queryBuilder.orderBy('reserve.id', 'ASC');
const result = await this.promieRetry.run(() => {
return queryBuilder.getMany();
});
return result.map(r => {
return r.id;
});
}
/**
* ruleId を指定して予約数をカウントする
* @param ruleIds: apid.RuleId[]
* @param type: apid.GetReserveType
* @return Promise<RuleIdCountResult[]>
*/
public async countRuleIds(ruleIds: apid.RuleId[], type: apid.GetReserveType): Promise<RuleIdCountResult[]> {
const connection = await this.op.getConnection();
const whereOption: FindConditions<Reserve> = {
ruleId: In(ruleIds),
};
this.setReserveTypeOption(type, whereOption);
const queryBuilder = connection
.getRepository(Reserve)
.createQueryBuilder('reserve')
.select(['ruleId, count(ruleId) as ruleIdCnt'])
.where(whereOption)
.groupBy('ruleId');
return await this.promieRetry.run(() => {
return queryBuilder.getRawMany();
});
}
} | the_stack |
import * as React from 'react';
import _isEmpty from 'lodash/isEmpty';
import OlMap from 'ol/Map';
import OlLayerVector from 'ol/layer/Vector';
import OlSourceVector from 'ol/source/Vector';
import OlCollection from 'ol/Collection';
import OlMultiPolygon from 'ol/geom/MultiPolygon';
import OlMultiLineString from 'ol/geom/MultiLineString';
import OlStyleStyle from 'ol/style/Style';
import OlStyleStroke from 'ol/style/Stroke';
import OlStyleFill from 'ol/style/Fill';
import OlStyleCircle from 'ol/style/Circle';
import OlInteractionDraw, { DrawEvent } from 'ol/interaction/Draw';
import { unByKey } from 'ol/Observable';
import OlOverlay from 'ol/Overlay';
import OlMapBrowserEvent from 'ol/MapBrowserEvent';
import OlGeometryType from 'ol/geom/GeometryType';
import OlOverlayPositioning from 'ol/OverlayPositioning';
import MeasureUtil from '@terrestris/ol-util/dist/MeasureUtil/MeasureUtil';
import MapUtil from '@terrestris/ol-util/dist/MapUtil/MapUtil';
import ToggleButton, { ToggleButtonProps } from '../ToggleButton/ToggleButton';
import { CSS_PREFIX } from '../../constants';
import './MeasureButton.less';
interface DefaultProps {
/**
* Name of system vector layer which will be used to draw measurement
* results.
*/
measureLayerName: string;
/**
* Fill color of the measurement feature.
*/
fillColor: string;
/**
* Stroke color of the measurement feature.
*/
strokeColor: string;
/**
* Determines if a marker with current measurement should be shown every
* time the user clicks while measuring a distance. Default is false.
*/
showMeasureInfoOnClickedPoints: boolean;
/**
* Determines if a tooltip with helpful information is shown next to the mouse
* position. Default is true.
*/
showHelpTooltip: boolean;
/**
* How many decimal places will be allowed for the measure tooltips.
* Default is 2.
*/
decimalPlacesInTooltips: number;
/**
* Used to allow / disallow multiple drawings at a time on the map.
* Default is false.
* TODO known issue: only label of the last drawn feature will be shown!
*/
multipleDrawing: boolean;
/**
* Tooltip which will be shown on map mouserover after measurement button
* was activated.
*/
clickToDrawText: string;
/**
* Tooltip which will be shown after polygon measurement button was toggled
* and at least one click in the map is occured.
*/
continuePolygonMsg: string;
/**
* Tooltip which will be shown after line measurement button was toggled
* and at least one click in the map is occured.
*/
continueLineMsg: string;
/**
* Tooltip which will be shown after angle measurement button was toggled
* and at least one click in the map is occured.
*/
continueAngleMsg: string;
/**
* CSS classes we'll assign to the popups and tooltips from measuring.
* Overwrite this object to style the text of the popups / overlays, if you
* don't want to use default classes.
*/
measureTooltipCssClasses: {
tooltip: string;
tooltipDynamic: string;
tooltipStatic: string;
};
/**
* Whether the measure button is pressed.
*/
pressed: boolean;
/**
* A custom onToogle function that will be called if button is toggled
*/
onToggle: (pressed: boolean) => void;
}
interface BaseProps {
/**
* The className which should be added.
*/
className?: string;
/**
* Instance of OL map this component is bound to.
*/
map: OlMap;
/**
* Whether line, area or angle will be measured.
*/
measureType: 'line' | 'polygon' | 'angle';
}
export type MeasureButtonProps = BaseProps & Partial<DefaultProps> & ToggleButtonProps;
/**
* The MeasureButton.
*
* @class The MeasureButton
* @extends React.Component
*/
class MeasureButton extends React.Component<MeasureButtonProps> {
/**
* The default properties.
*/
static defaultProps: DefaultProps = {
measureLayerName: 'react-geo_measure',
fillColor: 'rgba(255, 0, 0, 0.5)',
strokeColor: 'rgba(255, 0, 0, 0.8)',
showMeasureInfoOnClickedPoints: false,
showHelpTooltip: true,
decimalPlacesInTooltips: 2,
multipleDrawing: false,
continuePolygonMsg: 'Click to draw area',
continueLineMsg: 'Click to draw line',
continueAngleMsg: 'Click to draw angle',
clickToDrawText: 'Click to measure',
measureTooltipCssClasses: {
tooltip: `${CSS_PREFIX}measure-tooltip`,
tooltipDynamic: `${CSS_PREFIX}measure-tooltip-dynamic`,
tooltipStatic: `${CSS_PREFIX}measure-tooltip-static`
},
pressed: false,
onToggle: () => undefined
};
/**
* The className added to this component.
*
* @private
*/
className = `${CSS_PREFIX}measurebutton`;
/**
* Currently drawn feature.
*
* @private
*/
_feature = null;
/**
* Overlay to show the measurement.
*
* @private
*/
_measureTooltip = null;
/**
* Overlay to show the help messages.
*
* @private
*/
_helpTooltip = null;
/**
* The help tooltip element.
*
* @private
*/
_helpTooltipElement = null;
/**
* The measure tooltip element.
*
* @private
*/
_measureTooltipElement = null;
/**
* An array of created overlays we use for the tooltips. Used to eventually
* clean up everything we added.
*
* @private
*/
_createdTooltipOverlays = [];
/**
* An array of created divs we use for the tooltips. Used to eventually
* clean up everything we added.
*
* @private
*/
_createdTooltipDivs = [];
/**
* An object holding keyed `OlEventsKey` instances returned by the `on`
* method of `OlObservable`. These keys are used to unbind temporary
* listeners on events of the `OlInteractionDraw` or `OlMap`. The keys
* are the names of the events on the various objects. The `click` key is
* not always bound, but only for certain #measureType values.
*
* In #cleanup, we unbind all events we have bound so as to not leak
* memory, and to ensure we have no concurring listeners being active at a
* time (E.g. when multiple measure buttons are in an application).
*
* @private
*/
_eventKeys = {
drawstart: null,
drawend: null,
pointermove: null,
click: null,
change: null
};
/**
* The vector layer showing the geometries added by the draw interaction.
*
* @private
*/
_measureLayer = null;
/**
* The draw interaction used to draw the geometries to measure.
*
* @private
*/
_drawInteraction = null;
/**
* Creates the MeasureButton.
*
* @constructs MeasureButton
*/
constructor(props: BaseProps) {
super(props);
this.onDrawInteractionActiveChange = this.onDrawInteractionActiveChange.bind(this);
this.onToggle = this.onToggle.bind(this);
this.onDrawStart = this.onDrawStart.bind(this);
this.onDrawEnd = this.onDrawEnd.bind(this);
this.onDrawInteractionGeometryChange = this.onDrawInteractionGeometryChange.bind(this);
this.onMapPointerMove = this.onMapPointerMove.bind(this);
this.onMapClick = this.onMapClick.bind(this);
}
/**
* `componentDidMount` method of the MeasureButton.
*
* @method
*/
componentDidMount() {
this.createMeasureLayer();
this.createDrawInteraction();
}
/**
* Ensures that component is properly cleaned up on unmount.
*/
componentWillUnmount() {
if (this.props.pressed) {
this.onToggle(false);
}
}
/**
* Called when the button is toggled, this method ensures that everything
* is cleaned up when unpressed, and that measuring can start when pressed.
*
* @method
*/
onToggle(pressed: boolean) {
const {
map,
onToggle
} = this.props;
this.cleanup();
onToggle(pressed);
if (pressed && this._drawInteraction) {
this._drawInteraction.setActive(pressed);
this._eventKeys.drawstart = this._drawInteraction.on(
'drawstart', e => this.onDrawStart(e)
);
this._eventKeys.drawend = this._drawInteraction.on(
'drawend', e => this.onDrawEnd(e)
);
this._eventKeys.pointermove = map.on(
'pointermove', e => this.onMapPointerMove(e)
);
}
}
/**
* Creates measure vector layer and add this to the map.
*
* @method
*/
createMeasureLayer() {
const {
measureLayerName,
fillColor,
strokeColor,
map
} = this.props;
let measureLayer = MapUtil.getLayerByName(map, measureLayerName);
if (!measureLayer) {
measureLayer = new OlLayerVector({
properties: {
name: measureLayerName,
},
source: new OlSourceVector({
features: new OlCollection()
}),
style: new OlStyleStyle({
fill: new OlStyleFill({
color: fillColor
}),
stroke: new OlStyleStroke({
color: strokeColor,
width: 2
}),
image: new OlStyleCircle({
radius: 7,
fill: new OlStyleFill({
color: fillColor
})
})
})
});
map.addLayer(measureLayer);
}
this._measureLayer = measureLayer;
}
/**
* Creates a correctly configured OL draw interaction depending on
* the configured measureType.
*
* @return {OlInteractionDraw} The created interaction, which is not yet
* added to the map.
*
* @method
*/
createDrawInteraction() {
const {
fillColor,
strokeColor,
measureType,
pressed,
map
} = this.props;
const maxPoints = measureType === 'angle' ? 2 : undefined;
const drawType = measureType === 'polygon' ? OlGeometryType.MULTI_POLYGON : OlGeometryType.MULTI_LINE_STRING;
const drawInteraction = new OlInteractionDraw({
source: this._measureLayer.getSource(),
type: drawType,
maxPoints: maxPoints,
style: new OlStyleStyle({
fill: new OlStyleFill({
color: fillColor
}),
stroke: new OlStyleStroke({
color: strokeColor,
lineDash: [10, 10],
width: 2
}),
image: new OlStyleCircle({
radius: 5,
stroke: new OlStyleStroke({
color: strokeColor
}),
fill: new OlStyleFill({
color: fillColor
})
})
}),
freehandCondition: function() {
return false;
}
});
map.addInteraction(drawInteraction);
drawInteraction.on('change:active', () => this.onDrawInteractionActiveChange());
this._drawInteraction = drawInteraction;
if (pressed) {
this.onDrawInteractionActiveChange();
}
drawInteraction.setActive(pressed);
}
/**
* Adjusts visibility of measurement related tooltips depending on active
* status of draw interaction.
*/
onDrawInteractionActiveChange() {
const {
showHelpTooltip
} = this.props;
if (this._drawInteraction.getActive()) {
if (showHelpTooltip) {
this.createHelpTooltip();
}
this.createMeasureTooltip();
} else {
if (showHelpTooltip) {
this.removeHelpTooltip();
}
this.removeMeasureTooltip();
}
}
/**
* Called if the current geometry of the draw interaction has changed.
*
* @param evt The generic change event.
*/
onDrawInteractionGeometryChange(/* evt*/) {
this.updateMeasureTooltip();
}
/**
* Called on map click.
*
* @param evt The pointer event.
*/
onMapClick(evt: OlMapBrowserEvent<MouseEvent>) {
const {
measureType,
showMeasureInfoOnClickedPoints
} = this.props;
if (showMeasureInfoOnClickedPoints && measureType === 'line') {
this.addMeasureStopTooltip(evt.coordinate);
}
}
/**
* Sets up listeners whenever the drawing of a measurement sketch is
* started.
*
* @param evt The event which contains the
* feature we are drawing.
*
* @method
*/
onDrawStart(evt: DrawEvent) {
const {
showHelpTooltip,
multipleDrawing,
map
} = this.props;
const source = this._measureLayer.getSource();
this._feature = evt.feature;
this._eventKeys.change = this._feature.getGeometry().on('change',
this.onDrawInteractionGeometryChange);
this._eventKeys.click = map.on('click', (e: OlMapBrowserEvent<MouseEvent>) => this.onMapClick(e));
if (!multipleDrawing && source.getFeatures().length > 0) {
this.cleanupTooltips();
this.createMeasureTooltip();
if (showHelpTooltip) {
this.createHelpTooltip();
}
source.clear();
}
}
/**
* Called whenever measuring stops, this method draws static tooltips with
* the result onto the map canvas and unregisters various listeners.
*
* @method
*/
onDrawEnd(evt: DrawEvent) {
const {
measureType,
multipleDrawing,
showMeasureInfoOnClickedPoints,
measureTooltipCssClasses
} = this.props;
if (this._eventKeys.click) {
unByKey(this._eventKeys.click);
}
if (this._eventKeys.change) {
unByKey(this._eventKeys.change);
}
if (multipleDrawing) {
this.addMeasureStopTooltip((evt.feature.getGeometry() as OlMultiPolygon|OlMultiLineString).getLastCoordinate());
}
// Fix doubled label for lastPoint of line
if ((multipleDrawing || showMeasureInfoOnClickedPoints) && measureType === 'line') {
this.removeMeasureTooltip();
} else {
this._measureTooltipElement.className =
`${measureTooltipCssClasses.tooltip} ${measureTooltipCssClasses.tooltipStatic}`;
this._measureTooltip.setOffset([0, -7]);
}
this.updateMeasureTooltip();
// unset sketch
this._feature = null;
// fix doubled label for last point of line
if ((multipleDrawing || showMeasureInfoOnClickedPoints) && measureType === 'line') {
this._measureTooltipElement = null;
this.createMeasureTooltip();
}
}
/**
* Adds a tooltip on click where a measuring stop occured.
*
* @param coordinate The coordinate for the tooltip.
*/
addMeasureStopTooltip(coordinate: Array<number>) {
const {
measureType,
decimalPlacesInTooltips,
map,
measureTooltipCssClasses
} = this.props;
if (!_isEmpty(this._feature)) {
let geom = this._feature.getGeometry();
if (geom instanceof OlMultiPolygon) {
geom = geom.getPolygons()[0];
}
if (geom instanceof OlMultiLineString) {
geom = geom.getLineStrings()[0];
}
const value = measureType === 'line' ?
MeasureUtil.formatLength(geom, map, decimalPlacesInTooltips) :
MeasureUtil.formatArea(geom, map, decimalPlacesInTooltips);
if (parseInt(value, 10) > 0) {
const div = document.createElement('div');
div.className = `${measureTooltipCssClasses.tooltip} ${measureTooltipCssClasses.tooltipStatic}`;
div.innerHTML = value;
const tooltip = new OlOverlay({
element: div,
offset: [0, -15],
positioning: OlOverlayPositioning.BOTTOM_CENTER
});
map.addOverlay(tooltip);
tooltip.setPosition(coordinate);
this._createdTooltipDivs.push(div);
this._createdTooltipOverlays.push(tooltip);
}
}
}
/**
* Creates a new measure tooltip as `OlOverlay`.
*/
createMeasureTooltip() {
const {
map,
measureTooltipCssClasses
} = this.props;
if (this._measureTooltipElement) {
return;
}
this._measureTooltipElement = document.createElement('div');
this._measureTooltipElement.className =
`${measureTooltipCssClasses.tooltip} ${measureTooltipCssClasses.tooltipDynamic}`;
this._measureTooltip = new OlOverlay({
element: this._measureTooltipElement,
offset: [0, -15],
positioning: OlOverlayPositioning.BOTTOM_CENTER
});
map.addOverlay(this._measureTooltip);
}
/**
* Creates a new help tooltip as `OlOverlay`.
*/
createHelpTooltip() {
const {
map,
measureTooltipCssClasses
} = this.props;
if (this._helpTooltipElement) {
return;
}
this._helpTooltipElement = document.createElement('div');
this._helpTooltipElement.className = measureTooltipCssClasses.tooltip;
this._helpTooltip = new OlOverlay({
element: this._helpTooltipElement,
offset: [15, 0],
positioning: OlOverlayPositioning.CENTER_LEFT
});
map.addOverlay(this._helpTooltip);
}
/**
* Removes help tooltip from the map if measure button was untoggled.
*/
removeHelpTooltip() {
if (this._helpTooltip) {
this.props.map.removeOverlay(this._helpTooltip);
}
this._helpTooltipElement = null;
this._helpTooltip = null;
}
/**
* Removes measure tooltip from the map if measure button was untoggled.
*
* @method
*/
removeMeasureTooltip() {
if (this._measureTooltip) {
this.props.map.removeOverlay(this._measureTooltip);
}
this._measureTooltipElement = null;
this._measureTooltip = null;
}
/**
* Cleans up tooltips when the button is unpressed.
*
* @method
*/
cleanupTooltips() {
const {
map
} = this.props;
this._createdTooltipOverlays.forEach((tooltipOverlay) => {
map.removeOverlay(tooltipOverlay);
});
this._createdTooltipOverlays = [];
this._createdTooltipDivs.forEach((tooltipDiv) => {
const parent = tooltipDiv && tooltipDiv.parentNode;
if (parent) {
parent.removeChild(tooltipDiv);
}
});
this._createdTooltipDivs = [];
this.removeMeasureTooltip();
}
/**
* Cleans up artifacts from measuring when the button is unpressed.
*
* @method
*/
cleanup() {
if (this._drawInteraction) {
this._drawInteraction.setActive(false);
}
Object.keys(this._eventKeys).forEach(key => {
if (this._eventKeys[key]) {
unByKey(this._eventKeys[key]);
}
});
this.cleanupTooltips();
if (this._measureLayer) {
this._measureLayer.getSource().clear();
}
}
/**
* Called on map's pointermove event.
*
* @param evt The pointer event.
*/
onMapPointerMove(evt: any) {
if (!evt.dragging) {
this.updateHelpTooltip(evt.coordinate);
}
}
/**
* Updates the position and the text of the help tooltip.
*
* @param coordinate The coordinate to center the tooltip to.
*/
updateHelpTooltip(coordinate: any) {
const {
measureType,
clickToDrawText,
continuePolygonMsg,
continueLineMsg,
continueAngleMsg
} = this.props;
if (!this._helpTooltipElement) {
return;
}
let msg = clickToDrawText;
if (this._helpTooltipElement) {
if (measureType === 'polygon') {
msg = continuePolygonMsg;
} else if (measureType === 'line') {
msg = continueLineMsg;
} else if (measureType === 'angle') {
msg = continueAngleMsg;
}
this._helpTooltipElement.innerHTML = msg;
this._helpTooltip.setPosition(coordinate);
}
}
/**
* Updates the text and position of the measture tooltip.
*/
updateMeasureTooltip() {
const {
measureType,
decimalPlacesInTooltips,
map
} = this.props;
if (!this._measureTooltipElement) {
return;
}
if (this._feature) {
let output;
let geom = this._feature.getGeometry();
if (geom instanceof OlMultiPolygon) {
geom = geom.getPolygons()[0];
}
if (geom instanceof OlMultiLineString) {
geom = geom.getLineStrings()[0];
}
let measureTooltipCoord = geom.getLastCoordinate();
if (measureType === 'polygon') {
output = MeasureUtil.formatArea(geom, map, decimalPlacesInTooltips);
// attach area at interior point
measureTooltipCoord = geom.getInteriorPoint().getCoordinates();
} else if (measureType === 'line') {
output = MeasureUtil.formatLength(geom, map, decimalPlacesInTooltips);
} else if (measureType === 'angle') {
output = MeasureUtil.formatAngle(geom, map, decimalPlacesInTooltips);
}
this._measureTooltipElement.innerHTML = output;
this._measureTooltip.setPosition(measureTooltipCoord);
}
}
/**
* The render function.
*/
render() {
const {
className,
map,
measureType,
measureLayerName,
fillColor,
strokeColor,
showMeasureInfoOnClickedPoints,
showHelpTooltip,
multipleDrawing,
clickToDrawText,
continuePolygonMsg,
continueLineMsg,
continueAngleMsg,
decimalPlacesInTooltips,
measureTooltipCssClasses,
onToggle,
...passThroughProps
} = this.props;
const finalClassName = className
? `${className} ${this.className}`
: this.className;
return (
<ToggleButton
onToggle={this.onToggle}
className={finalClassName}
{...passThroughProps}
/>
);
}
}
export default MeasureButton; | the_stack |
import { TestBed } from '@angular/core/testing';
import { provideMockActions } from '@ngrx/effects/testing';
import { hot } from 'jasmine-marbles';
import { Observable } from 'rxjs';
import { Entity } from '../decorators/entity-decorator';
import { Key } from '../decorators/key-decorator';
import { IEntityError } from '../service/wrapper-models';
import { fromEntityActions, ofEntityAction, ofEntityType } from './action-operators';
import { EntityActionTypes } from './action-types';
import { Clear } from './actions';
import { Create, CreateFailure, CreateMany, CreateManyFailure, CreateManySuccess, CreateSuccess } from './create-actions';
import { Deselect, DeselectAll, Deselected, DeselectedMany, DeselectMany, DeselectManyByKeys } from './deselection-actions';
import { Load, LoadFailure, LoadSuccess } from './load-actions';
import { LoadAll, LoadAllFailure, LoadAllSuccess } from './load-all-actions';
import { LoadMany, LoadManyFailure, LoadManySuccess } from './load-many-actions';
import { LoadPage, LoadPageSuccess } from './load-page-actions';
import { LoadRange, LoadRangeFailure, LoadRangeSuccess } from './load-range-actions';
import { Replace, ReplaceFailure, ReplaceMany, ReplaceManyFailure, ReplaceManySuccess, ReplaceSuccess } from './replace-actions';
import { Select, SelectByKey, SelectMany, SelectManyByKeys, SelectMore, SelectMoreByKeys } from './selection-actions';
import { Update, UpdateFailure, UpdateMany, UpdateManyFailure, UpdateManySuccess, UpdateSuccess } from './update-actions';
const xform = {
fromServer: data => data,
toServer: data => data
};
@Entity({
modelName: 'TestEntity',
transform: [xform]
})
class TestEntity {
@Key id: number;
firstName: string;
lastName: string;
}
class AltEntity {
@Key id: number;
data: string;
}
const brian: TestEntity = {
id: 1,
firstName: 'Brian',
lastName: 'Love'
};
const jon: TestEntity = {
id: 2,
firstName: 'Jon',
lastName: 'Rista'
};
const fyneman: TestEntity = {
id: 3,
firstName: 'Richard',
lastName: 'Feynman'
};
const einstein: TestEntity = {
id: 6,
firstName: 'Albert',
lastName: 'Einstein'
};
const developers: TestEntity[] = [brian, jon];
const scientists: TestEntity[] = [fyneman, einstein];
const testError: IEntityError = {
info: {
modelName: '',
modelType: TestEntity
},
message: 'Test error'
};
const criteria = { criteria: 'test' };
const page = { page: 2, size: 10 };
const range = { start: 10, end: 20 };
const regex = {
v4: /^(?:[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12})|(?:0{8}-0{4}-0{4}-0{4}-0{12})$/u,
v5: /^(?:[a-f0-9]{8}-[a-f0-9]{4}-5[a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12})|(?:0{8}-0{4}-0{4}-0{4}-0{12})$/u
};
const isUuid = (value: string): boolean => {
return regex.v4.test(value) || regex.v5.test(value);
};
describe('NgRX Auto-Entity: Actions', () => {
let actions: Observable<any>;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideMockActions(() => actions)]
});
});
describe('Correlated Actions', () => {
it('should construct EntityAction with correlationId initialized to a random uuid', () => {
const action = new Load(TestEntity, 1);
expect(isUuid(action.correlationId)).toEqual(true);
});
});
describe('Transformations', () => {
it('should attach entity transformations to entity info', () => {
const action = new Load(TestEntity, 1);
expect(action.info.transform).toEqual([xform]);
});
});
describe('Actions: Load', () => {
describe('Load', () => {
it('should construct EntityAction with proper details', () => {
const action = new Load(TestEntity, 1);
expect(action.type).toEqual('[TestEntity] (Generic) Load');
expect(action.actionType).toEqual(EntityActionTypes.Load);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.keys).toEqual(1);
});
it('should construct EntityAction with proper details and criteria', () => {
const action = new Load(TestEntity, 1, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Load');
expect(action.actionType).toEqual(EntityActionTypes.Load);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.keys).toEqual(1);
expect(action.criteria).toEqual(criteria);
});
it('should construct EntityAction with optional arguments', () => {
const action = new Load(TestEntity);
expect(action.type).toEqual('[TestEntity] (Generic) Load');
expect(action.actionType).toEqual(EntityActionTypes.Load);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.keys).toEqual(undefined);
});
});
describe('LoadSuccess', () => {
it('should construct EntityAction with proper details', () => {
const keys = [1, 2];
const action = new LoadSuccess(TestEntity, jon, keys, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Load: Success');
expect(action.actionType).toEqual(EntityActionTypes.LoadSuccess);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.keys).toEqual(keys);
expect(action.criteria).toEqual(criteria);
expect(action.entity).toEqual(jon);
});
});
describe('LoadFailure', () => {
it('should construct EntityAction with proper details', () => {
const keys = [1, 2];
const action = new LoadFailure(TestEntity, testError, keys, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Load: Failure');
expect(action.actionType).toEqual(EntityActionTypes.LoadFailure);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.error).toEqual(testError);
expect(action.keys).toEqual(keys);
expect(action.criteria).toEqual(criteria);
});
});
});
describe('Actions: LoadMany', () => {
describe('LoadMany', () => {
it('should construct EntityAction with proper details', () => {
const action = new LoadMany(TestEntity, 'test');
expect(action.type).toEqual('[TestEntity] (Generic) Load Many');
expect(action.actionType).toEqual(EntityActionTypes.LoadMany);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.criteria).toEqual('test');
});
});
describe('LoadManySuccess', () => {
it('should construct EntityAction with proper details', () => {
const action = new LoadManySuccess(TestEntity, [jon], criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Load Many: Success');
expect(action.actionType).toEqual(EntityActionTypes.LoadManySuccess);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.criteria).toEqual(criteria);
expect(action.entities).toEqual([jon]);
});
});
describe('LoadManyFailure', () => {
it('should construct EntityAction with proper details', () => {
const action = new LoadManyFailure(TestEntity, testError, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Load Many: Failure');
expect(action.actionType).toEqual(EntityActionTypes.LoadManyFailure);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.error).toEqual(testError);
expect(action.criteria).toEqual(criteria);
});
});
});
describe('Actions: LoadAll', () => {
describe('LoadAll', () => {
it('should construct EntityAction with proper details', () => {
const action = new LoadAll(TestEntity, 'test');
expect(action.type).toEqual('[TestEntity] (Generic) Load All');
expect(action.actionType).toEqual(EntityActionTypes.LoadAll);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.criteria).toEqual('test');
});
});
describe('LoadAllSuccess', () => {
it('should construct EntityAction with proper details', () => {
const action = new LoadAllSuccess(TestEntity, [jon], criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Load All: Success');
expect(action.actionType).toEqual(EntityActionTypes.LoadAllSuccess);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.criteria).toEqual(criteria);
expect(action.entities).toEqual([jon]);
});
});
describe('LoadAllFailure', () => {
it('should construct EntityAction with proper details', () => {
const action = new LoadAllFailure(TestEntity, testError, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Load All: Failure');
expect(action.actionType).toEqual(EntityActionTypes.LoadAllFailure);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.error).toEqual(testError);
expect(action.criteria).toEqual(criteria);
});
});
});
describe('Actions: LoadPage', () => {
describe('LoadPage', () => {
it('should construct EntityAction with proper details', () => {
const action = new LoadPage(TestEntity, { page: 2, size: 10 });
expect(action.type).toEqual('[TestEntity] (Generic) Load Page');
expect(action.actionType).toEqual(EntityActionTypes.LoadPage);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.page).toEqual({ page: 2, size: 10 });
});
it('should construct EntityAction with proper details and criteria', () => {
const action = new LoadPage(TestEntity, { page: 2, size: 10 }, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Load Page');
expect(action.actionType).toEqual(EntityActionTypes.LoadPage);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.page).toEqual({ page: 2, size: 10 });
expect(action.criteria).toEqual(criteria);
});
});
describe('LoadPageSuccess', () => {
it('should construct EntityAction with proper details', () => {
const action = new LoadPageSuccess(
TestEntity,
developers,
{
page: { page: 1, size: 2 },
totalCount: 10
},
criteria
);
expect(action.type).toEqual('[TestEntity] (Generic) Load Page: Success');
expect(action.actionType).toEqual(EntityActionTypes.LoadPageSuccess);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entities).toEqual(developers);
expect(action.pageInfo).toEqual({
page: {
page: 1,
size: 2
},
totalCount: 10
});
expect(action.criteria).toEqual(criteria);
});
});
describe('LoadPageFailure', () => {
it('should construct EntityAction with proper details', () => {
const action = new LoadAllFailure(TestEntity, testError, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Load All: Failure');
expect(action.actionType).toEqual(EntityActionTypes.LoadAllFailure);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.error).toEqual(testError);
expect(action.criteria).toEqual(criteria);
});
});
});
describe('Actions: LoadRange', () => {
describe('LoadRange', () => {
it('should construct EntityAction with proper details for start/end range', () => {
const action = new LoadRange(TestEntity, { start: 10, end: 20 });
expect(action.type).toEqual('[TestEntity] (Generic) Load Range');
expect(action.actionType).toEqual(EntityActionTypes.LoadRange);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.range).toEqual({ start: 10, end: 20 });
});
it('should construct EntityAction with proper details and criteria for start/end range', () => {
const action = new LoadRange(TestEntity, { start: 10, end: 20 }, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Load Range');
expect(action.actionType).toEqual(EntityActionTypes.LoadRange);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.range).toEqual({ start: 10, end: 20 });
expect(action.criteria).toEqual(criteria);
});
it('should construct EntityAction with proper details for first/last range', () => {
const action = new LoadRange(TestEntity, { first: 10, last: 20 });
expect(action.type).toEqual('[TestEntity] (Generic) Load Range');
expect(action.actionType).toEqual(EntityActionTypes.LoadRange);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.range).toEqual({ first: 10, last: 20 });
});
it('should construct EntityAction with proper details and criteria for first/last range', () => {
const action = new LoadRange(TestEntity, { first: 10, last: 20 }, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Load Range');
expect(action.actionType).toEqual(EntityActionTypes.LoadRange);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.range).toEqual({ first: 10, last: 20 });
expect(action.criteria).toEqual(criteria);
});
it('should construct EntityAction with proper details for skip/take range', () => {
const action = new LoadRange(TestEntity, { skip: 10, take: 10 });
expect(action.type).toEqual('[TestEntity] (Generic) Load Range');
expect(action.actionType).toEqual(EntityActionTypes.LoadRange);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.range).toEqual({ skip: 10, take: 10 });
});
it('should construct EntityAction with proper details and criteria for skip/take range', () => {
const action = new LoadRange(TestEntity, { skip: 10, take: 10 }, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Load Range');
expect(action.actionType).toEqual(EntityActionTypes.LoadRange);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.range).toEqual({ skip: 10, take: 10 });
expect(action.criteria).toEqual(criteria);
});
});
describe('LoadRangeSuccess', () => {
it('should construct EntityAction with proper details for start/end range', () => {
const action = new LoadRangeSuccess(
TestEntity,
developers,
{
range: {
start: 1,
end: 10
},
totalCount: 2
},
criteria
);
expect(action.type).toEqual('[TestEntity] (Generic) Load Range: Success');
expect(action.actionType).toEqual(EntityActionTypes.LoadRangeSuccess);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entities).toEqual(developers);
expect(action.rangeInfo).toEqual({
range: {
start: 1,
end: 10
},
totalCount: 2
});
expect(action.criteria).toEqual(criteria);
});
});
describe('LoadRangeFailure', () => {
it('should construct EntityAction with proper details', () => {
const action = new LoadRangeFailure(TestEntity, testError, range, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Load Range: Failure');
expect(action.actionType).toEqual(EntityActionTypes.LoadRangeFailure);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.error).toEqual(testError);
expect(action.range).toEqual(range);
expect(action.criteria).toEqual(criteria);
});
});
});
describe('Actions: Create', () => {
describe('Create', () => {
it('should construct EntityAction with proper details', () => {
const action = new Create(TestEntity, fyneman);
expect(action.type).toEqual('[TestEntity] (Generic) Create');
expect(action.actionType).toEqual(EntityActionTypes.Create);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entity).toEqual(fyneman);
});
it('should construct EntityAction with proper details and criteria', () => {
const action = new Create(TestEntity, fyneman, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Create');
expect(action.actionType).toEqual(EntityActionTypes.Create);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entity).toEqual(fyneman);
expect(action.criteria).toEqual(criteria);
});
});
describe('CreateSuccess', () => {
it('should construct EntityAction with proper details', () => {
const action = new CreateSuccess(TestEntity, fyneman, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Create: Success');
expect(action.actionType).toEqual(EntityActionTypes.CreateSuccess);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.criteria).toEqual(criteria);
expect(action.entity).toEqual(fyneman);
});
});
describe('CreateFailure', () => {
it('should construct EntityAction with proper details', () => {
const action = new CreateFailure(TestEntity, testError, fyneman, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Create: Failure');
expect(action.actionType).toEqual(EntityActionTypes.CreateFailure);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.error).toEqual(testError);
expect(action.entity).toEqual(fyneman);
expect(action.criteria).toEqual(criteria);
});
});
});
describe('Actions: CreateMany', () => {
describe('CreateMany', () => {
it('should construct EntityAction with proper details', () => {
const action = new CreateMany(TestEntity, scientists);
expect(action.type).toEqual('[TestEntity] (Generic) Create Many');
expect(action.actionType).toEqual(EntityActionTypes.CreateMany);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entities).toEqual(scientists);
});
it('should construct EntityAction with proper details and criteria', () => {
const action = new CreateMany(TestEntity, scientists, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Create Many');
expect(action.actionType).toEqual(EntityActionTypes.CreateMany);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entities).toEqual(scientists);
expect(action.criteria).toEqual(criteria);
});
});
describe('CreateManySuccess', () => {
it('should construct EntityAction with proper details', () => {
const action = new CreateManySuccess(TestEntity, scientists, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Create Many: Success');
expect(action.actionType).toEqual(EntityActionTypes.CreateManySuccess);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.criteria).toEqual(criteria);
expect(action.entities).toEqual(scientists);
});
});
describe('CreateManyFailure', () => {
it('should construct EntityAction with proper details', () => {
const action = new CreateManyFailure(TestEntity, testError, scientists, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Create Many: Failure');
expect(action.actionType).toEqual(EntityActionTypes.CreateManyFailure);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.error).toEqual(testError);
expect(action.entities).toEqual(scientists);
expect(action.criteria).toEqual(criteria);
});
});
});
describe('Actions: Update', () => {
describe('Update', () => {
it('should construct EntityAction with proper details', () => {
const action = new Update(TestEntity, fyneman);
expect(action.type).toEqual('[TestEntity] (Generic) Update');
expect(action.actionType).toEqual(EntityActionTypes.Update);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entity).toEqual(fyneman);
});
it('should construct EntityAction with proper details and criteria', () => {
const action = new Update(TestEntity, fyneman, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Update');
expect(action.actionType).toEqual(EntityActionTypes.Update);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entity).toEqual(fyneman);
expect(action.criteria).toEqual(criteria);
});
});
describe('UpdateSuccess', () => {
it('should construct EntityAction with proper details', () => {
const action = new UpdateSuccess(TestEntity, fyneman, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Update: Success');
expect(action.actionType).toEqual(EntityActionTypes.UpdateSuccess);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.criteria).toEqual(criteria);
expect(action.entity).toEqual(fyneman);
});
});
describe('UpdateFailure', () => {
it('should construct EntityAction with proper details', () => {
const action = new UpdateFailure(TestEntity, testError, fyneman, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Update: Failure');
expect(action.actionType).toEqual(EntityActionTypes.UpdateFailure);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.error).toEqual(testError);
expect(action.entity).toEqual(fyneman);
expect(action.criteria).toEqual(criteria);
});
});
});
describe('Actions: UpdateMany', () => {
describe('UpdateMany', () => {
it('should construct EntityAction with proper details', () => {
const action = new UpdateMany(TestEntity, scientists);
expect(action.type).toEqual('[TestEntity] (Generic) Update Many');
expect(action.actionType).toEqual(EntityActionTypes.UpdateMany);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entities).toEqual(scientists);
});
it('should construct EntityAction with proper details and criteria', () => {
const action = new UpdateMany(TestEntity, scientists, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Update Many');
expect(action.actionType).toEqual(EntityActionTypes.UpdateMany);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entities).toEqual(scientists);
expect(action.criteria).toEqual(criteria);
});
});
describe('UpdateManySuccess', () => {
it('should construct EntityAction with proper details', () => {
const action = new UpdateManySuccess(TestEntity, scientists, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Update Many: Success');
expect(action.actionType).toEqual(EntityActionTypes.UpdateManySuccess);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.criteria).toEqual(criteria);
expect(action.entities).toEqual(scientists);
});
});
describe('UpdateManyFailure', () => {
it('should construct EntityAction with proper details', () => {
const action = new UpdateManyFailure(TestEntity, testError, scientists, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Update Many: Failure');
expect(action.actionType).toEqual(EntityActionTypes.UpdateManyFailure);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.error).toEqual(testError);
expect(action.entities).toEqual(scientists);
expect(action.criteria).toEqual(criteria);
});
});
});
describe('Actions: Replace', () => {
describe('Replace', () => {
it('should construct EntityAction with proper details', () => {
const action = new Replace(TestEntity, fyneman);
expect(action.type).toEqual('[TestEntity] (Generic) Replace');
expect(action.actionType).toEqual(EntityActionTypes.Replace);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entity).toEqual(fyneman);
});
it('should construct EntityAction with proper details and criteria', () => {
const action = new Replace(TestEntity, fyneman, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Replace');
expect(action.actionType).toEqual(EntityActionTypes.Replace);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entity).toEqual(fyneman);
expect(action.criteria).toEqual(criteria);
});
});
describe('ReplaceSuccess', () => {
it('should construct EntityAction with proper details', () => {
const action = new ReplaceSuccess(TestEntity, fyneman, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Replace: Success');
expect(action.actionType).toEqual(EntityActionTypes.ReplaceSuccess);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.criteria).toEqual(criteria);
expect(action.entity).toEqual(fyneman);
});
});
describe('ReplaceFailure', () => {
it('should construct EntityAction with proper details', () => {
const action = new ReplaceFailure(TestEntity, testError, fyneman, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Replace: Failure');
expect(action.actionType).toEqual(EntityActionTypes.ReplaceFailure);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.error).toEqual(testError);
expect(action.entity).toEqual(fyneman);
expect(action.criteria).toEqual(criteria);
});
});
});
describe('Actions: ReplaceMany', () => {
describe('ReplaceMany', () => {
it('should construct EntityAction with proper details', () => {
const action = new ReplaceMany(TestEntity, scientists);
expect(action.type).toEqual('[TestEntity] (Generic) Replace Many');
expect(action.actionType).toEqual(EntityActionTypes.ReplaceMany);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entities).toEqual(scientists);
});
it('should construct EntityAction with proper details and criteria', () => {
const action = new ReplaceMany(TestEntity, scientists, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Replace Many');
expect(action.actionType).toEqual(EntityActionTypes.ReplaceMany);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entities).toEqual(scientists);
expect(action.criteria).toEqual(criteria);
});
});
describe('ReplaceManySuccess', () => {
it('should construct EntityAction with proper details', () => {
const action = new ReplaceManySuccess(TestEntity, scientists, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Replace Many: Success');
expect(action.actionType).toEqual(EntityActionTypes.ReplaceManySuccess);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.criteria).toEqual(criteria);
expect(action.entities).toEqual(scientists);
});
});
describe('ReplaceManyFailure', () => {
it('should construct EntityAction with proper details', () => {
const action = new ReplaceManyFailure(TestEntity, testError, scientists, criteria);
expect(action.type).toEqual('[TestEntity] (Generic) Replace Many: Failure');
expect(action.actionType).toEqual(EntityActionTypes.ReplaceManyFailure);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.error).toEqual(testError);
expect(action.entities).toEqual(scientists);
expect(action.criteria).toEqual(criteria);
});
});
});
describe('Action: Clear', () => {
it('should construct EntityAction with proper details', () => {
const action = new Clear(TestEntity);
expect(action.type).toEqual('[TestEntity] (Generic) Clear');
expect(action.actionType).toEqual(EntityActionTypes.Clear);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
});
});
describe('Action: Select', () => {
it('should construct EntityAction with proper details', () => {
const action = new Select(TestEntity, fyneman);
expect(action.type).toEqual('[TestEntity] (Generic) Select');
expect(action.actionType).toEqual(EntityActionTypes.Select);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entity).toEqual(fyneman);
});
});
describe('Action: SelectMany', () => {
it('should construct EntityAction with proper details', () => {
const action = new SelectMany(TestEntity, scientists);
expect(action.type).toEqual('[TestEntity] (Generic) Select Many');
expect(action.actionType).toEqual(EntityActionTypes.SelectMany);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entities).toEqual(scientists);
});
it('should throw error during construction if non-array (object) passed', () => {
expect(() => {
// tslint:disable-next-line:no-unused-expression
new SelectMany(TestEntity, {} as any);
}).toThrow(new Error('[NGRX-AE] ! SelectMany action requires an array of entities.'));
});
it('should throw error during construction if non-array (null) passed', () => {
expect(() => {
// tslint:disable-next-line:no-unused-expression
new SelectMany(TestEntity, null);
}).toThrow(new Error('[NGRX-AE] ! SelectMany action requires an array of entities.'));
});
it('should throw error during construction if non-array (undefined) passed', () => {
expect(() => {
// tslint:disable-next-line:no-unused-expression
new SelectMany(TestEntity, undefined);
}).toThrow(new Error('[NGRX-AE] ! SelectMany action requires an array of entities.'));
});
});
describe('Action: SelectMore', () => {
it('should construct EntityAction with proper details', () => {
const action = new SelectMore(TestEntity, scientists);
expect(action.type).toEqual('[TestEntity] (Generic) Select More');
expect(action.actionType).toEqual(EntityActionTypes.SelectMore);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entities).toEqual(scientists);
});
it('should throw error during construction if non-array (object) passed', () => {
expect(() => {
// tslint:disable-next-line:no-unused-expression
new SelectMore(TestEntity, {} as any);
}).toThrow(new Error('[NGRX-AE] ! SelectMore action requires an array of entities.'));
});
it('should throw error during construction if non-array (null) passed', () => {
expect(() => {
// tslint:disable-next-line:no-unused-expression
new SelectMore(TestEntity, null);
}).toThrow(new Error('[NGRX-AE] ! SelectMore action requires an array of entities.'));
});
it('should throw error during construction if non-array (undefined) passed', () => {
expect(() => {
// tslint:disable-next-line:no-unused-expression
new SelectMore(TestEntity, undefined);
}).toThrow(new Error('[NGRX-AE] ! SelectMore action requires an array of entities.'));
});
});
describe('Action: SelectByKey', () => {
it('should construct EntityAction with proper details (number key)', () => {
const action = new SelectByKey(TestEntity, 1);
expect(action.type).toEqual('[TestEntity] (Generic) Select by Key');
expect(action.actionType).toEqual(EntityActionTypes.SelectByKey);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entityKey).toEqual(1);
});
it('should construct EntityAction with proper details (string key)', () => {
const action = new SelectByKey(TestEntity, 'key');
expect(action.type).toEqual('[TestEntity] (Generic) Select by Key');
expect(action.actionType).toEqual(EntityActionTypes.SelectByKey);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entityKey).toEqual('key');
});
});
describe('Action: SelectManyByKeys', () => {
it('should construct EntityAction with proper details (number keys)', () => {
const action = new SelectManyByKeys(TestEntity, [1, 2]);
expect(action.type).toEqual('[TestEntity] (Generic) Select Many by Keys');
expect(action.actionType).toEqual(EntityActionTypes.SelectManyByKeys);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entitiesKeys).toEqual([1, 2]);
});
it('should construct EntityAction with proper details (string keys)', () => {
const action = new SelectManyByKeys(TestEntity, ['key_a', 'key_b']);
expect(action.type).toEqual('[TestEntity] (Generic) Select Many by Keys');
expect(action.actionType).toEqual(EntityActionTypes.SelectManyByKeys);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entitiesKeys).toEqual(['key_a', 'key_b']);
});
it('should throw error during construction if non-array (object) passed', () => {
expect(() => {
// tslint:disable-next-line:no-unused-expression
new SelectManyByKeys(TestEntity, {} as any);
}).toThrow(new Error('[NGRX-AE] ! SelectManyByKeys action requires an array of entity keys.'));
});
it('should throw error during construction if non-array (null) passed', () => {
expect(() => {
// tslint:disable-next-line:no-unused-expression
new SelectManyByKeys(TestEntity, null);
}).toThrow(new Error('[NGRX-AE] ! SelectManyByKeys action requires an array of entity keys.'));
});
it('should throw error during construction if non-array (undefined) passed', () => {
expect(() => {
// tslint:disable-next-line:no-unused-expression
new SelectManyByKeys(TestEntity, undefined);
}).toThrow(new Error('[NGRX-AE] ! SelectManyByKeys action requires an array of entity keys.'));
});
});
describe('Action: SelectMoreByKeys', () => {
it('should construct EntityAction with proper details (number keys)', () => {
const action = new SelectMoreByKeys(TestEntity, [1, 2]);
expect(action.type).toEqual('[TestEntity] (Generic) Select More by Keys');
expect(action.actionType).toEqual(EntityActionTypes.SelectMoreByKeys);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entitiesKeys).toEqual([1, 2]);
});
it('should construct EntityAction with proper details (string keys)', () => {
const action = new SelectMoreByKeys(TestEntity, ['key_a', 'key_b']);
expect(action.type).toEqual('[TestEntity] (Generic) Select More by Keys');
expect(action.actionType).toEqual(EntityActionTypes.SelectMoreByKeys);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entitiesKeys).toEqual(['key_a', 'key_b']);
});
it('should throw error during construction if non-array (object) passed', () => {
expect(() => {
// tslint:disable-next-line:no-unused-expression
new SelectMoreByKeys(TestEntity, {} as any);
}).toThrow(new Error('[NGRX-AE] ! SelectMoreByKeys action requires an array of entity keys.'));
});
it('should throw error during construction if non-array (null) passed', () => {
expect(() => {
// tslint:disable-next-line:no-unused-expression
new SelectMoreByKeys(TestEntity, null);
}).toThrow(new Error('[NGRX-AE] ! SelectMoreByKeys action requires an array of entity keys.'));
});
it('should throw error during construction if non-array (undefined) passed', () => {
expect(() => {
// tslint:disable-next-line:no-unused-expression
new SelectMoreByKeys(TestEntity, undefined);
}).toThrow(new Error('[NGRX-AE] ! SelectMoreByKeys action requires an array of entity keys.'));
});
});
describe('Action: Deselect', () => {
it('should construct EntityAction with proper details', () => {
const action = new Deselect(TestEntity);
expect(action.type).toEqual('[TestEntity] (Generic) Deselect');
expect(action.actionType).toEqual(EntityActionTypes.Deselect);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
});
});
describe('Action: DeselectMany', () => {
it('should construct EntityAction with proper details', () => {
const action = new DeselectMany(TestEntity, scientists);
expect(action.type).toEqual('[TestEntity] (Generic) Deselect of Many');
expect(action.actionType).toEqual(EntityActionTypes.DeselectMany);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entities).toEqual(scientists);
});
it('should throw error during construction if non-array (object) passed', () => {
expect(() => {
// tslint:disable-next-line:no-unused-expression
new DeselectMany(TestEntity, {} as any);
}).toThrow(new Error('[NGRX-AE] ! DeselectMany action requires an array of entities.'));
});
it('should throw error during construction if non-array (null) passed', () => {
expect(() => {
// tslint:disable-next-line:no-unused-expression
new DeselectMany(TestEntity, null);
}).toThrow(new Error('[NGRX-AE] ! DeselectMany action requires an array of entities.'));
});
it('should throw error during construction if non-array (undefined) passed', () => {
expect(() => {
// tslint:disable-next-line:no-unused-expression
new DeselectMany(TestEntity, undefined);
}).toThrow(new Error('[NGRX-AE] ! DeselectMany action requires an array of entities.'));
});
});
describe('Action: DeselectManyByKeys', () => {
it('should construct EntityAction with proper details (number keys)', () => {
const action = new DeselectManyByKeys(TestEntity, [1, 2]);
expect(action.type).toEqual('[TestEntity] (Generic) Deselect of Many by Keys');
expect(action.actionType).toEqual(EntityActionTypes.DeselectManyByKeys);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entitiesKeys).toEqual([1, 2]);
});
it('should construct EntityAction with proper details (string keys)', () => {
const action = new DeselectManyByKeys(TestEntity, ['key_a', 'key_b']);
expect(action.type).toEqual('[TestEntity] (Generic) Deselect of Many by Keys');
expect(action.actionType).toEqual(EntityActionTypes.DeselectManyByKeys);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entitiesKeys).toEqual(['key_a', 'key_b']);
});
it('should throw error during construction if non-array (object) passed', () => {
expect(() => {
// tslint:disable-next-line:no-unused-expression
new DeselectManyByKeys(TestEntity, {} as any);
}).toThrow(new Error('[NGRX-AE] ! DeselectManyByKeys action requires an array of entity keys.'));
});
it('should throw error during construction if non-array (null) passed', () => {
expect(() => {
// tslint:disable-next-line:no-unused-expression
new DeselectManyByKeys(TestEntity, null);
}).toThrow(new Error('[NGRX-AE] ! DeselectManyByKeys action requires an array of entity keys.'));
});
it('should throw error during construction if non-array (undefined) passed', () => {
expect(() => {
// tslint:disable-next-line:no-unused-expression
new DeselectManyByKeys(TestEntity, undefined);
}).toThrow(new Error('[NGRX-AE] ! DeselectManyByKeys action requires an array of entity keys.'));
});
});
describe('Action: DeselectAll', () => {
it('should construct EntityAction with proper details', () => {
const action = new DeselectAll(TestEntity);
expect(action.type).toEqual('[TestEntity] (Generic) Deselect of All');
expect(action.actionType).toEqual(EntityActionTypes.DeselectAll);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
});
});
describe('Action: Deselected', () => {
it('should construct EntityAction with proper details', () => {
const action = new Deselected(TestEntity);
expect(action.type).toEqual('[TestEntity] (Generic) Deselection');
expect(action.actionType).toEqual(EntityActionTypes.Deselected);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
});
});
describe('Action: DeselectedMany', () => {
it('should construct EntityAction with proper details', () => {
const action = new DeselectedMany(TestEntity, scientists);
expect(action.type).toEqual('[TestEntity] (Generic) Deselection of Many');
expect(action.actionType).toEqual(EntityActionTypes.DeselectedMany);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entities).toEqual(scientists);
});
it('should construct EntityAction if null is passed', () => {
const action = new DeselectedMany(TestEntity, null);
expect(action.type).toEqual('[TestEntity] (Generic) Deselection of Many');
expect(action.actionType).toEqual(EntityActionTypes.DeselectedMany);
expect(action.info.modelType).toEqual(TestEntity);
expect(action.info.modelName).toEqual('TestEntity');
expect(action.entities).toEqual(null);
});
it('should throw error during construction if non-array (object) passed', () => {
expect(() => {
// tslint:disable-next-line:no-unused-expression
new DeselectedMany(TestEntity, {} as any);
}).toThrow(new Error('[NGRX-AE] ! DeselectedMany action requires an array of entities or keys.'));
});
it('should throw error during construction if non-array (number) passed', () => {
expect(() => {
// tslint:disable-next-line:no-unused-expression
new DeselectedMany(TestEntity, 2 as any);
}).toThrow(new Error('[NGRX-AE] ! DeselectedMany action requires an array of entities or keys.'));
});
it('should throw error during construction if non-array (undefined) passed', () => {
expect(() => {
// tslint:disable-next-line:no-unused-expression
new DeselectedMany(TestEntity, undefined);
}).toThrow(new Error('[NGRX-AE] ! DeselectedMany action requires an array of entities or keys.'));
});
});
describe('Operator: ofActionType<T extends EntityAction>', () => {
it('should match action type', () => {
const action = new Load(TestEntity, 'id');
actions = hot('-a', { a: action });
const expected = hot('-a', { a: action });
const result = actions.pipe(ofEntityAction(EntityActionTypes.Load));
expect(result).toBeObservable(expected);
});
it('should match action type and ignore prior non-matching', () => {
const action1 = new LoadAll(TestEntity);
const action2 = new Load(TestEntity, 'id');
actions = hot('-a-b', { a: action1, b: action2 });
const expected = hot('---b', { b: action2 });
const result = actions.pipe(ofEntityAction(EntityActionTypes.Load));
expect(result).toBeObservable(expected);
});
it('should match action type and ignore subsequent non-matching', () => {
const action1 = new LoadAll(TestEntity);
const action2 = new Load(TestEntity, 'id');
actions = hot('-a-b', { a: action2, b: action1 });
const expected = hot('-a--', { a: action2 });
const result = actions.pipe(ofEntityAction(EntityActionTypes.Load));
expect(result).toBeObservable(expected);
});
it('should match action type and ignore orior and subsequent non-matching', () => {
const action1 = new LoadAll(TestEntity);
const action2 = new Load(TestEntity, 'id');
const action3 = new LoadAll(TestEntity);
actions = hot('-a-b-c', { a: action1, b: action2, c: action3 });
const expected = hot('---b--', { b: action2 });
const result = actions.pipe(ofEntityAction(EntityActionTypes.Load));
expect(result).toBeObservable(expected);
});
it('should match multiple action types', () => {
const action1 = new LoadAll(TestEntity);
const action2 = new Load(TestEntity, 'id');
const action3 = new LoadAll(TestEntity);
actions = hot('-a-b-c', { a: action1, b: action2, c: action3 });
const expected = hot('-a-b-c', { a: action1, b: action2, c: action3 });
const result = actions.pipe(ofEntityAction(EntityActionTypes.Load, EntityActionTypes.LoadAll));
expect(result).toBeObservable(expected);
});
it('should match multiple action types and ignore non-matching', () => {
const action1 = new LoadAll(TestEntity);
const action2 = new LoadMany(TestEntity);
const action3 = new Load(TestEntity, 'id');
const action4 = new LoadAll(TestEntity);
const action5 = new LoadMany(TestEntity);
actions = hot('-a-b-c-d-e', { a: action1, b: action2, c: action3, d: action4, e: action5 });
const expected = hot('-a---c-d--', { a: action1, c: action3, d: action4 });
const result = actions.pipe(ofEntityAction(EntityActionTypes.Load, EntityActionTypes.LoadAll));
expect(result).toBeObservable(expected);
});
it('should match no action types if none match', () => {
const action1 = new LoadAll(TestEntity);
const action2 = new LoadMany(TestEntity);
const action3 = new Load(TestEntity, 'id');
const action4 = new LoadAll(TestEntity);
const action5 = new LoadMany(TestEntity);
actions = hot('-a-b-c-d-e', { a: action1, b: action2, c: action3, d: action4, e: action5 });
const expected = hot('----------');
const result = actions.pipe(ofEntityAction(EntityActionTypes.LoadPage));
expect(result).toBeObservable(expected);
});
});
describe('Operator: ofEntityType<TModel, T extends EntityAction>', () => {
it('should match action type and entity type', () => {
const action = new Load(TestEntity, 'id');
actions = hot('-a', { a: action });
const expected = hot('-a', { a: action });
const result = actions.pipe(ofEntityType(TestEntity, EntityActionTypes.Load));
expect(result).toBeObservable(expected);
});
it('should match action type and entity type and ignore prior non-matching', () => {
const action1 = new LoadAll(TestEntity);
const action2 = new Load(TestEntity, 'id');
actions = hot('-a-b', { a: action1, b: action2 });
const expected = hot('---b', { b: action2 });
const result = actions.pipe(ofEntityType(TestEntity, EntityActionTypes.Load));
expect(result).toBeObservable(expected);
});
it('should match action type and entity type and ignore subsequent non-matching', () => {
const action1 = new LoadAll(TestEntity);
const action2 = new Load(TestEntity, 'id');
actions = hot('-a-b', { a: action2, b: action1 });
const expected = hot('-a--', { a: action2 });
const result = actions.pipe(ofEntityType(TestEntity, EntityActionTypes.Load));
expect(result).toBeObservable(expected);
});
it('should match action type and entity type and ignore orior and subsequent non-matching', () => {
const action1 = new LoadAll(TestEntity);
const action2 = new Load(TestEntity, 'id');
const action3 = new LoadAll(TestEntity);
actions = hot('-a-b-c', { a: action1, b: action2, c: action3 });
const expected = hot('---b--', { b: action2 });
const result = actions.pipe(ofEntityType(TestEntity, EntityActionTypes.Load));
expect(result).toBeObservable(expected);
});
it('should match multiple action types and entity type', () => {
const action1 = new LoadAll(TestEntity);
const action2 = new Load(TestEntity, 'id');
const action3 = new LoadAll(TestEntity);
actions = hot('-a-b-c', { a: action1, b: action2, c: action3 });
const expected = hot('-a-b-c', { a: action1, b: action2, c: action3 });
const result = actions.pipe(ofEntityType(TestEntity, EntityActionTypes.Load, EntityActionTypes.LoadAll));
expect(result).toBeObservable(expected);
});
it('should match multiple action types and entity type and ignore non-matching', () => {
const action1 = new LoadAll(TestEntity);
const action2 = new LoadMany(TestEntity);
const action3 = new Load(TestEntity, 'id');
const action4 = new LoadAll(TestEntity);
const action5 = new LoadMany(TestEntity);
actions = hot('-a-b-c-d-e', { a: action1, b: action2, c: action3, d: action4, e: action5 });
const expected = hot('-a---c-d--', { a: action1, c: action3, d: action4 });
const result = actions.pipe(ofEntityType(TestEntity, EntityActionTypes.Load, EntityActionTypes.LoadAll));
expect(result).toBeObservable(expected);
});
it('should match no action types if none match for entity type', () => {
const action1 = new LoadAll(TestEntity);
const action2 = new LoadMany(TestEntity);
const action3 = new Load(TestEntity, 'id');
const action4 = new LoadAll(TestEntity);
const action5 = new LoadMany(TestEntity);
actions = hot('-a-b-c-d-e', { a: action1, b: action2, c: action3, d: action4, e: action5 });
const expected = hot('----------');
const result = actions.pipe(ofEntityType(TestEntity, EntityActionTypes.LoadPage));
expect(result).toBeObservable(expected);
});
});
describe('Operator: fromEntityTypes<TModel, T extends EntityAction>', () => {
it('should match action type and entity types', () => {
const action1 = new Load(TestEntity, 'id');
const action2 = new Load(AltEntity, 'id');
actions = hot('-a-b', { a: action1, b: action2 });
const expected = hot('-a-b', { a: action1, b: action2 });
const result = fromEntityActions(actions, [TestEntity, AltEntity], EntityActionTypes.Load);
expect(result).toBeObservable(expected);
});
it('should match action type and entity types and ignore prior non-matching', () => {
const action1 = new LoadAll(TestEntity);
const action2 = new Load(TestEntity, 'id');
const action3 = new Load(AltEntity, 'id');
actions = hot('-a-b-c', { a: action1, b: action2, c: action3 });
const expected = hot('---b-c', { b: action2, c: action3 });
const result = fromEntityActions(actions, [TestEntity, AltEntity], EntityActionTypes.Load);
expect(result).toBeObservable(expected);
});
it('should match action type and entity types and ignore intermediate non-matching', () => {
const action1 = new LoadAll(TestEntity);
const action2 = new Load(TestEntity, 'id');
const action3 = new Load(AltEntity, 'id');
actions = hot('-a-b-c', { a: action2, b: action1, c: action3 });
const expected = hot('-a---c-', { a: action2, c: action3 });
const result = fromEntityActions(actions, [TestEntity, AltEntity], EntityActionTypes.Load);
expect(result).toBeObservable(expected);
});
it('should match action type and entity types and ignore prior and subsequent non-matching', () => {
const action1 = new LoadAll(TestEntity);
const action2 = new Load(TestEntity, 'id');
const action3 = new Load(AltEntity, 'id');
const action4 = new LoadAll(TestEntity);
actions = hot('-a-b-c-d', { a: action1, b: action2, c: action3, d: action4 });
const expected = hot('---b-c--', { b: action2, c: action3 });
const result = fromEntityActions(actions, [TestEntity, AltEntity], EntityActionTypes.Load);
expect(result).toBeObservable(expected);
});
it('should match multiple action types and entity types', () => {
const action1 = new LoadAll(TestEntity);
const action2 = new Load(TestEntity, 'id');
const action3 = new Load(AltEntity, 'id');
const action4 = new LoadAll(TestEntity);
actions = hot('-a-b-c-d', { a: action1, b: action2, c: action3, d: action4 });
const expected = hot('-a-b-c-d', { a: action1, b: action2, c: action3, d: action4 });
const result = fromEntityActions(actions, [TestEntity, AltEntity], EntityActionTypes.Load, EntityActionTypes.LoadAll);
expect(result).toBeObservable(expected);
});
it('should match multiple action types and entity types and ignore non-matching', () => {
const action1 = new LoadAll(TestEntity);
const action2 = new LoadMany(TestEntity);
const action3 = new Load(TestEntity, 'id');
const action4 = new Load(AltEntity, 'id');
const action5 = new LoadAll(TestEntity);
const action6 = new LoadMany(TestEntity);
actions = hot('-a-b-c-d-e-f', { a: action1, b: action2, c: action3, d: action4, e: action5, f: action6 });
const expected = hot('-a---c-d-e--', { a: action1, c: action3, d: action4, e: action5 });
const result = fromEntityActions(actions, [TestEntity, AltEntity], EntityActionTypes.Load, EntityActionTypes.LoadAll);
expect(result).toBeObservable(expected);
});
it('should match no action types if none match for entity types', () => {
const action1 = new LoadAll(TestEntity);
const action2 = new LoadMany(TestEntity);
const action3 = new Load(TestEntity, 'id');
const action4 = new Load(AltEntity, 'id');
const action5 = new LoadAll(TestEntity);
const action6 = new LoadMany(TestEntity);
actions = hot('-a-b-c-d-e-f', { a: action1, b: action2, c: action3, d: action4, e: action5, f: action6 });
const expected = hot('------------');
const result = fromEntityActions(actions, [TestEntity, AltEntity], EntityActionTypes.LoadPage);
expect(result).toBeObservable(expected);
});
});
}); | the_stack |
import 'regenerator-runtime/runtime.js';
import { AudioAtom } from '@guardian/atoms-rendering';
import type { ICommentResponse as CommentResponse } from '@guardian/bridget';
import { Topic } from '@guardian/bridget/Topic';
import { App } from '@guardian/discussion-rendering/build/App';
import { either } from '@guardian/types';
import {
ads,
getAdSlots,
reportNativeElementPositionChanges,
sendTargetingParams,
slideshow,
videos,
} from 'client/nativeCommunication';
import setup from 'client/setup';
import { createEmbedComponentFromProps } from 'components/embedWrapper';
import FollowStatus from 'components/followStatus';
import FooterContent from 'components/footerContent';
import EpicContent from 'components/shared/epicContent';
import { formatDate, formatLocal, isValidDate } from 'date';
import { handleErrors, isObject } from 'lib';
import {
acquisitionsClient,
commercialClient,
discussionClient,
navigationClient,
notificationsClient,
userClient,
} from 'native/nativeApi';
import type { ReactElement } from 'react';
import { createElement as h } from 'react';
import ReactDOM from 'react-dom';
import { stringToPillar } from 'themeStyles';
import { logger } from '../logger';
import { hydrate as hydrateAtoms } from './atoms';
// ----- Run ----- //
interface FontFaceSet {
readonly ready: Promise<FontFaceSet>;
}
declare global {
interface Document {
fonts: FontFaceSet;
}
}
function getTopic(follow: Element | null): Topic | null {
const id = follow?.getAttribute('data-id');
const displayName = follow?.getAttribute('data-display-name');
if (!id) {
logger.error('No id for topic');
return null;
}
if (!displayName) {
logger.error('No display name for topic');
return null;
}
return new Topic({ id, displayName, type: 'tag-contributor' });
}
function followToggle(topic: Topic): void {
const followStatus = document.querySelector('.js-follow-status');
if (!followStatus) return;
void notificationsClient.isFollowing(topic).then((following) => {
if (following) {
void notificationsClient.unfollow(topic).then((_) => {
ReactDOM.render(
h(FollowStatus, { isFollowing: false }),
followStatus,
);
});
} else {
void notificationsClient.follow(topic).then((_) => {
ReactDOM.render(
h(FollowStatus, { isFollowing: true }),
followStatus,
);
});
}
});
}
function topicClick(e: Event): void {
const follow = document.querySelector('.js-follow');
const topic = getTopic(follow);
if (topic) {
followToggle(topic);
}
}
function topics(): void {
const follow = document.querySelector('.js-follow');
const topic = getTopic(follow);
const followStatus = document.querySelector('.js-follow-status');
if (topic) {
follow?.addEventListener('click', topicClick);
void notificationsClient.isFollowing(topic).then((following) => {
if (following && followStatus) {
ReactDOM.render(
h(FollowStatus, { isFollowing: true }),
followStatus,
);
}
});
}
}
function formatDates(): void {
Array.from(document.querySelectorAll('time[data-date]')).forEach((time) => {
const timestamp = time.getAttribute('data-date');
try {
if (timestamp) {
time.textContent = formatDate(new Date(timestamp));
}
} catch (e) {
const message =
timestamp ?? 'because the data-date attribute was empty';
logger.error(`Unable to parse and format date ${message}`, e);
}
});
}
// TODO: show epics on opinion articles
function insertEpic(): void {
const epicPlaceholder = document.getElementById('js-epic-placeholder');
if (epicPlaceholder) {
epicPlaceholder.innerHTML = '';
}
if (navigator.onLine && epicPlaceholder) {
Promise.all([userClient.isPremium(), acquisitionsClient.getEpics()])
.then(([isPremium, maybeEpic]) => {
if (!isPremium && maybeEpic.epic) {
const { title, body, firstButton, secondButton } =
maybeEpic.epic;
const epicProps = {
title,
body,
firstButton,
secondButton,
};
ReactDOM.render(h(EpicContent, epicProps), epicPlaceholder);
}
})
.catch((error) => console.error(error));
}
}
declare type ArticlePillar =
| 'news'
| 'opinion'
| 'sport'
| 'culture'
| 'lifestyle';
function isPillarString(pillar: string): boolean {
return ['news', 'opinion', 'sport', 'culture', 'lifestyle'].includes(
pillar.toLowerCase(),
);
}
function renderComments(): void {
const commentContainer = document.getElementById('comments');
const pillarString = commentContainer?.getAttribute('data-pillar');
const shortUrl = commentContainer?.getAttribute('data-short-id');
const isClosedForComments = !!commentContainer?.getAttribute('pillar');
if (pillarString && isPillarString(pillarString) && shortUrl) {
const pillar = pillarString as ArticlePillar;
const user = {
userId: 'abc123',
displayName: 'Jane Smith',
webUrl: '',
apiUrl: '',
secureAvatarUrl: '',
avatar: '',
badge: [],
};
const additionalHeaders = {};
const props = {
shortUrl,
baseUrl: 'https://discussion.theguardian.com/discussion-api',
pillar: stringToPillar(pillar),
user,
isClosedForComments,
additionalHeaders,
expanded: false,
apiKey: 'ios',
onPermalinkClick: (commentId: number): void => {
console.log(commentId);
},
onRecommend: (commentId: number): Promise<boolean> => {
return discussionClient.recommend(commentId);
},
onComment: (
shortUrl: string,
body: string,
): Promise<CommentResponse & { status: 'ok' | 'error' }> => {
return discussionClient
.comment(shortUrl, body)
.then((response) => ({ ...response, status: 'ok' }));
},
onReply: (
shortUrl: string,
body: string,
parentCommentId: number,
): Promise<CommentResponse & { status: 'ok' | 'error' }> => {
return discussionClient
.reply(shortUrl, body, parentCommentId)
.then((response) => ({ ...response, status: 'ok' }));
},
onPreview: (body: string): Promise<string> => {
return discussionClient.preview(body);
},
};
ReactDOM.render(h(App, props), commentContainer);
}
}
function footerLinks(): void {
const privacySettingsLink = document.getElementById('js-privacy-settings');
const privacyPolicyLink = document.getElementById('js-privacy-policy');
privacyPolicyLink?.addEventListener('click', (e) => {
e.preventDefault();
void navigationClient.openPrivacyPolicy();
});
privacySettingsLink?.addEventListener('click', (e) => {
e.preventDefault();
void navigationClient.openPrivacySettings();
});
}
function footerInit(): void {
userClient
.doesCcpaApply()
.then((isCcpa) => {
const comp = h(FooterContent, { isCcpa });
ReactDOM.render(comp, document.getElementById('js-footer'));
footerLinks();
})
.catch((error) => {
logger.error(error);
});
}
type FormData = Record<string, string>;
function submit(body: FormData, form: Element): void {
fetch(
'https://callouts.code.dev-guardianapis.com/formstack-campaign/submit',
{
method: 'POST',
body: JSON.stringify(body),
},
)
.then(() => {
const message = document.createElement('p');
message.textContent = 'Thank you for your contribution';
if (form.firstChild) {
form.replaceChild(message, form.firstChild);
}
})
.catch(() => {
const errorPlaceholder = form.querySelector('.js-error-message');
if (errorPlaceholder) {
errorPlaceholder.textContent =
'Sorry, there was a problem submitting your form. Please try again later.';
}
});
}
function readFile(file: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
setTimeout(reject, 30000);
reader.addEventListener('load', () => {
if (reader.result) {
const fileAsBase64 = reader.result
.toString()
.split(';base64,')[1];
resolve(fileAsBase64);
}
});
reader.addEventListener('error', () => {
reject();
});
reader.readAsDataURL(file);
});
}
function callouts(): void {
const callouts = Array.from(document.querySelectorAll('.js-callout'));
callouts.forEach((callout) => {
const buttons = Array.from(
callout.querySelectorAll('.js-callout-expand'),
);
buttons.forEach((button) => {
button.addEventListener('click', () => {
callout.toggleAttribute('open');
});
});
const form = callout.querySelector('form');
if (!form) return;
form.addEventListener(
'submit',
// eslint-disable-next-line @typescript-eslint/no-misused-promises -- use async function
async (e): Promise<void> => {
try {
e.preventDefault();
const elements = form.getElementsByTagName('input');
const data = Array.from(elements).reduce(
async (o: Promise<FormData>, elem) => {
const acc = await o;
const { type, checked, name, value, files } = elem;
if (type === 'radio') {
if (checked) {
acc[name] = value;
}
} else if (type === 'file' && files?.length) {
acc[name] = await readFile(files[0]);
} else if (value) {
acc[name] = value;
}
return Promise.resolve(acc);
},
Promise.resolve({}),
);
submit(await data, form);
} catch (e) {
const errorPlaceholder =
form.querySelector('.js-error-message');
if (errorPlaceholder) {
errorPlaceholder.textContent =
'There was a problem with the file you uploaded above. We accept images and pdfs up to 6MB';
}
}
},
);
});
}
function hasSeenCards(): void {
const articleIds = Array.from(document.querySelectorAll('.js-card'))
.map((card) => card.getAttribute('data-article-id') ?? '')
.filter((articleId) => articleId !== '');
void userClient.filterSeenArticles(articleIds).then((seenArticles) => {
seenArticles.forEach((id) => {
document
.querySelector(`.js-card[data-article-id='${id}']`)
?.classList.add('fade');
});
});
}
function initAudioAtoms(): void {
Array.from(document.querySelectorAll('.js-audio-atom')).forEach((atom) => {
const id = atom.getAttribute('id');
const trackUrl = atom.getAttribute('trackurl');
const kicker = atom.getAttribute('kicker');
const title = atom.getAttribute('title');
const pillar = parseInt(atom.getAttribute('pillar') ?? '0');
// Work required to provide the audio atom duration server side.
const duration = parseInt(atom.getAttribute('duration') ?? '0');
if (id && trackUrl && kicker && title && pillar) {
ReactDOM.hydrate(
h(AudioAtom, { id, trackUrl, pillar, kicker, title, duration }),
atom,
);
}
});
}
function localDates(): void {
const date = document.querySelector('time.js-date');
const dateString = date?.getAttribute('data-date');
if (!dateString || !date) return;
try {
const localDate = new Date(dateString);
if (isValidDate(localDate)) {
date.textContent = formatLocal(localDate);
}
} catch (e) {
console.error('Could not set a local date', e);
}
}
function richLinks(): void {
document
.querySelectorAll('.js-rich-link[data-article-id]')
.forEach((richLink) => {
const articleId = richLink.getAttribute('data-article-id');
if (articleId) {
const options = {
headers: {
Accept: 'application/json',
},
};
void fetch(`${articleId}?richlink`, options)
.then(handleErrors)
.then((resp) => resp.json())
.then((response: unknown) => {
if (isObject(response)) {
const pillar =
typeof response.pillar === 'string'
? response.pillar.toLowerCase()
: null;
const image = response.image;
if (pillar) {
richLink.classList.add(`js-${pillar}`);
}
const placeholder =
richLink.querySelector('.js-image');
if (placeholder && typeof image === 'string') {
const img = document.createElement('img');
img.addEventListener('load', (_) => {
const currentAdSlots = getAdSlots();
void commercialClient.updateAdverts(
currentAdSlots,
);
});
img.setAttribute('alt', 'Related article');
img.setAttribute('src', image);
placeholder.appendChild(img);
}
}
})
.catch((error) => console.error(error));
}
});
}
function hydrateClickToView(): void {
document
.querySelectorAll('.js-click-to-view-container')
.forEach((container) =>
either(
(error: string) => {
logger.error(
`Failed to create Embed for hydration: ${error}`,
);
},
(embedComponent: ReactElement) => {
ReactDOM.hydrate(embedComponent, container);
},
)(createEmbedComponentFromProps(container)),
);
}
function resizeEmailSignups(): void {
const isIframe = (elem: Element): elem is HTMLIFrameElement =>
elem.tagName === 'IFRAME';
const emailSignupIframes = document.querySelectorAll('.js-email-signup');
Array.from(emailSignupIframes).forEach((emailSignupIframe) => {
if (isIframe(emailSignupIframe)) {
const innerIframe =
emailSignupIframe.contentDocument?.querySelector('iframe');
if (innerIframe) {
innerIframe.style.width = '100%';
}
}
});
}
setup();
sendTargetingParams();
ads();
videos();
resizeEmailSignups();
reportNativeElementPositionChanges();
topics();
slideshow();
formatDates();
footerInit();
insertEpic();
callouts();
renderComments();
hasSeenCards();
initAudioAtoms();
hydrateAtoms();
localDates();
richLinks();
hydrateClickToView(); | the_stack |
import { KeyboardEvents, KeyboardEventArgs, closest, addClass, isNullOrUndefined, removeClass } from '@syncfusion/ej2-base';
import { PivotView } from '../base/pivotview';
import * as cls from '../../common/base/css-constant';
import { FocusStrategy } from '@syncfusion/ej2-grids/src/grid/services/focus-strategy';
import { PivotCellSelectedEventArgs } from '../../common/base/interface';
import { IAxisSet } from '../../base/engine';
import * as events from '../../common/base/constant';
/**
* PivotView Keyboard interaction
*/
/** @hidden */
export class KeyboardInteraction {
/** @hidden */
public event: KeyboardEventArgs;
private parent: PivotView;
private keyConfigs: { [key: string]: string } = {
tab: 'tab',
shiftTab: 'shift+tab',
enter: 'enter',
shiftUp: 'shift+upArrow',
shiftDown: 'shift+downArrow',
shiftLeft: 'shift+leftArrow',
shiftRight: 'shift+rightArrow',
shiftEnter: 'shift+enter',
ctrlEnter: 'ctrl+enter',
upArrow: 'upArrow',
downArrow: 'downArrow',
leftArrow: 'leftArrow',
rightArrow: 'rightArrow',
escape: 'escape',
ctrlShiftF: 'ctrl+shift+f'
};
private pivotViewKeyboardModule: KeyboardEvents;
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
private timeOutObj: any;
/**
* Constructor.
* @param {PivotView} parent - Instance of pivot table.
*/
constructor(parent: PivotView) { /* eslint-disable-line */
this.parent = parent;
this.event = undefined;
this.parent.element.tabIndex = this.parent.element.tabIndex === -1 ? 0 : this.parent.element.tabIndex;
this.pivotViewKeyboardModule = new KeyboardEvents(this.parent.element, {
keyAction: this.keyActionHandler.bind(this),
keyConfigs: this.keyConfigs,
eventName: 'keydown'
});
}
private keyActionHandler(e: KeyboardEventArgs): void {
switch (e.action) {
case 'tab':
this.processTab(e);
break;
case 'shiftTab':
this.processShiftTab(e);
break;
case 'enter':
case 'shiftEnter':
case 'ctrlEnter':
this.processEnter(e);
break;
case 'shiftUp':
case 'shiftDown':
case 'shiftLeft':
case 'shiftRight':
case 'upArrow':
case 'downArrow':
case 'leftArrow':
case 'rightArrow':
this.processSelection(e);
break;
case 'escape':
this.clearSelection();
break;
case 'ctrlShiftF':
this.toggleFieldList(e);
break;
}
}
private getNextButton(target: HTMLElement): HTMLElement {
let allPivotButtons: HTMLElement[] = this.allpivotButtons(target as HTMLElement);
removeClass(allPivotButtons, 'e-btn-focused');
if (this.parent.grid.element.querySelector('.' + cls.PIVOT_BUTTON_CLASS)) {
let len: number = allPivotButtons.length;
for (let i: number = 0; i < len; i++) {
if (allPivotButtons[i].getAttribute('data-uid') === target.getAttribute('data-uid')) {
return (allPivotButtons[i + 1] ? allPivotButtons[i + 1] : target);
}
}
}
return target;
}
private getPrevButton(target: HTMLElement): HTMLElement {
let allPivotButtons: HTMLElement[] = this.allpivotButtons(target as HTMLElement);
removeClass(allPivotButtons, 'e-btn-focused');
if (this.parent.grid.element.querySelector('.' + cls.PIVOT_BUTTON_CLASS)) {
let len: number = allPivotButtons.length;
for (let i: number = 0; i < len; i++) {
if (allPivotButtons[i].getAttribute('data-uid') === target.getAttribute('data-uid')) {
return (allPivotButtons[i - 1] ? allPivotButtons[i - 1] : target);
}
}
}
return target;
}
private allpivotButtons(target: HTMLElement): HTMLElement[] {
let buttons: HTMLElement[] = [];
if (target && this.parent.showGroupingBar) {
let columnFilterValueGroup: HTMLElement = closest(target, '.' + cls.GRID_GROUPING_BAR_CLASS) as HTMLElement;
let rowGroup: HTMLElement = closest(target, '.' + cls.GROUP_PIVOT_ROW) as HTMLElement;
let chartGroup: HTMLElement = closest(target, '.' + cls.CHART_GROUPING_BAR_CLASS) as HTMLElement;
let tableAxis: boolean = target.classList.contains(cls.ROWSHEADER);
let chartAxis: boolean;
let rowAxis: boolean;
let columnFilterValueAxis: boolean;
if (columnFilterValueGroup !== null) {
rowAxis = columnFilterValueGroup.classList.contains(cls.GRID_GROUPING_BAR_CLASS);
} else if (rowGroup !== null) {
columnFilterValueAxis = rowGroup.classList.contains(cls.GROUP_PIVOT_ROW);
} else if (chartGroup !== null) {
chartAxis = chartGroup.classList.contains(cls.CHART_GROUPING_BAR_CLASS);
}
if (rowAxis || columnFilterValueAxis || tableAxis) {
/* eslint-disable */
let groupingbarButton: HTMLElement[] = [].slice.call(this.parent.element.querySelector('.' + cls.GRID_GROUPING_BAR_CLASS).querySelectorAll('.' + cls.PIVOT_BUTTON_CLASS));
let headerButton: HTMLElement[] = [].slice.call(this.parent.element.querySelector('.' + cls.GROUP_PIVOT_ROW).querySelectorAll('.' + cls.PIVOT_BUTTON_CLASS));
buttons = groupingbarButton.concat(headerButton);
}
else if (chartAxis) {
buttons = [].slice.call(this.parent.element.querySelector('.' + cls.CHART_GROUPING_BAR_CLASS).querySelectorAll('.' + cls.PIVOT_BUTTON_CLASS));
}
}
/* eslint-enable */
return buttons;
}
private processTab(e: Event): void {
let target: Element = (e.target as HTMLElement);
if (target && (closest(target, '.' + cls.PIVOT_BUTTON_CLASS) || target.classList.contains('e-group-row'))) {
if (this.parent.grid) {
let gridFocus: FocusStrategy = this.parent.grid.serviceLocator.getService<FocusStrategy>('focus');
if (target.classList.contains('e-group-row') && target.querySelector('.e-btn-focused')) {
target = target.querySelector('.e-btn-focused');
} else if (target.classList.contains('e-group-row')) {
gridFocus.focus();
let element: HTMLElement = gridFocus.getFocusedElement();
addClass([element], ['e-focused', 'e-focus']);
element.setAttribute('tabindex', '0');
e.preventDefault();
return;
}
let nextButton: HTMLElement = this.getNextButton(target as HTMLElement);
if (nextButton.getAttribute('data-uid') !== target.getAttribute('data-uid')) {
if (this.parent.element.querySelector('.e-focused')) {
this.parent.element.querySelector('.e-focused').setAttribute('tabindex', '-1');
removeClass(this.parent.element.querySelectorAll('.e-focus'), 'e-focus');
removeClass(this.parent.element.querySelectorAll('.e-focused'), 'e-focused');
gridFocus.setFocusedElement(this.parent.element.querySelector('.e-headercell'));
this.parent.element.querySelector('.e-headercell').setAttribute('tabindex', '0');
} else {
gridFocus.currentInfo.skipAction = true;
}
addClass([nextButton], 'e-btn-focused');
nextButton.focus();
} else {
gridFocus.focus();
let element: HTMLElement = gridFocus.getFocusedElement();
addClass([element], ['e-focused', 'e-focus']);
element.setAttribute('tabindex', '0');
}
e.preventDefault();
return;
}
} else if (!this.parent.showGroupingBar && this.parent.showFieldList &&
target && closest(target, '.' + cls.TOGGLE_FIELD_LIST_CLASS)) {
if (this.parent.grid) {
let gridFocus: FocusStrategy = this.parent.grid.serviceLocator.getService<FocusStrategy>('focus');
gridFocus.focus();
let element: HTMLElement = gridFocus.getFocusedElement();
addClass([element], ['e-focused', 'e-focus']);
element.setAttribute('tabindex', '0');
e.preventDefault();
return;
}
} else if (!this.parent.showGroupingBar && !this.parent.showFieldList &&
target && closest(target, '.' + cls.PIVOT_VIEW_CLASS) && !closest(target, '.e-popup.e-popup-open')) {
if (this.parent.grid) {
let gridElement: HTMLElement = closest(target, '.' + cls.PIVOT_VIEW_CLASS) as HTMLElement;
let gridFocus: FocusStrategy = this.parent.grid.serviceLocator.getService<FocusStrategy>('focus');
let rows: HTMLElement[] = [].slice.call(gridElement.getElementsByTagName('tr')) as HTMLElement[];
if (target.innerHTML === ((rows[rows.length - 1]).lastChild as HTMLElement).innerHTML) {
gridFocus.currentInfo.skipAction = true;
} else {
gridFocus.focus();
let element: HTMLElement = gridFocus.getFocusedElement();
addClass([element], ['e-focused', 'e-focus']);
element.setAttribute('tabindex', '0');
e.preventDefault();
return;
}
}
} else if (target && closest(target, '.' + cls.GRID_TOOLBAR) && this.parent.toolbar && this.parent.toolbarModule) {
clearTimeout(this.timeOutObj);
this.timeOutObj = setTimeout(() => {
removeClass(closest(target, '.' + cls.GRID_TOOLBAR).querySelectorAll('.e-menu-item.e-focused'), 'e-focused');
if (document.activeElement && document.activeElement.classList.contains('e-menu-item')) {
addClass([document.activeElement], 'e-focused');
}
});
} else if (target.classList.contains('e-numerictextbox')) {
let gridFocus: FocusStrategy = this.parent.grid.serviceLocator.getService<FocusStrategy>('focus');
gridFocus.focus();
let element: HTMLElement = gridFocus.getFocusedElement();
removeClass([element], ['e-focused', 'e-focus']);
element.setAttribute('tabindex', '0');
e.preventDefault();
}
}
private processShiftTab(e: Event): void {
let target: Element = (e.target as HTMLElement);
if (target && (closest(target, '.' + cls.PIVOT_BUTTON_CLASS) || target.classList.contains('e-group-row'))) {
if (this.parent.grid) {
let gridFocus: FocusStrategy = this.parent.grid.serviceLocator.getService<FocusStrategy>('focus');
if (target.classList.contains('e-group-row') && target.querySelector('.e-btn-focused')) {
target = target.querySelector('.e-btn-focused');
} else if (target.classList.contains('e-group-row')) {
target = this.parent.element.querySelector('.e-btn-focused') ? this.parent.element.querySelector('.e-btn-focused') :
this.parent.element.querySelector('.' + cls.GRID_GROUPING_BAR_CLASS);
let allPivotButtons: HTMLElement[] = this.allpivotButtons(target as HTMLElement);
if (allPivotButtons.length > 0 && allPivotButtons[allPivotButtons.length - 1]) {
gridFocus.currentInfo.skipAction = true;
allPivotButtons[allPivotButtons.length - 1].focus();
removeClass(allPivotButtons, 'e-btn-focused');
addClass([allPivotButtons[allPivotButtons.length - 1]], 'e-btn-focused');
e.preventDefault();
return;
}
}
let prevButton: HTMLElement = this.getPrevButton(target as HTMLElement);
if (prevButton.getAttribute('data-uid') !== target.getAttribute('data-uid')) {
gridFocus.currentInfo.skipAction = true;
prevButton.focus();
e.preventDefault();
return;
}
}
} else if (target && this.parent.grid && (target.classList.contains('e-movablefirst') ||
(target.classList.contains('e-rowsheader') && closest(target, 'tr').getAttribute('data-uid') ===
this.parent.grid.element.querySelector('.e-frozencontent tr').getAttribute('data-uid')))) {
let gridFocus: FocusStrategy = this.parent.grid.serviceLocator.getService<FocusStrategy>('focus');
if (target.classList.contains('e-movablefirst')) {
target = (this.parent.element.querySelector('.' + cls.GROUP_ROW_CLASS + ' .e-btn-focused')) ?
(this.parent.element.querySelector('.' + cls.GROUP_ROW_CLASS + ' .e-btn-focused')) :
(this.parent.element.querySelector('.' + cls.GROUP_ROW_CLASS));
let element: HTMLElement = gridFocus.getFocusedElement();
removeClass([element], ['e-focused', 'e-focus']);
}
let allPivotButtons: HTMLElement[] = this.allpivotButtons(target as HTMLElement);
if (allPivotButtons.length > 0) {
gridFocus.currentInfo.skipAction = true;
setTimeout(() => {
allPivotButtons[allPivotButtons.length - 1].focus();
});
removeClass(allPivotButtons, 'e-btn-focused');
addClass([allPivotButtons[allPivotButtons.length - 1]], 'e-btn-focused');
e.preventDefault();
return;
}
} else if (target && closest(target, '.' + cls.GRID_TOOLBAR) &&
this.parent.toolbar && this.parent.toolbarModule) {
clearTimeout(this.timeOutObj);
this.timeOutObj = setTimeout(() => {
removeClass(closest(target, '.' + cls.GRID_TOOLBAR).querySelectorAll('.e-menu-item.e-focused'), 'e-focused');
if (document.activeElement && document.activeElement.classList.contains('e-menu-item')) {
addClass([document.activeElement], 'e-focused');
}
});
} else if (target.classList.contains('e-numerictextbox')) {
let gridFocus: FocusStrategy = this.parent.grid.serviceLocator.getService<FocusStrategy>('focus');
gridFocus.focus();
let element: HTMLElement = gridFocus.getFocusedElement();
removeClass([element], ['e-focused', 'e-focus']);
element.setAttribute('tabindex', '0');
e.preventDefault();
}
}
private processEnter(e: KeyboardEventArgs): void {
let target: Element = (e.target as HTMLElement);
if (target && closest(target, '.' + cls.GRID_CLASS)) {
let gridFocus: FocusStrategy = this.parent.grid.serviceLocator.getService<FocusStrategy>('focus');
if (e.keyCode === 13 && !e.shiftKey && !e.ctrlKey) {
if (target.querySelector('.' + cls.ICON)) {
this.event = e;
(target.querySelector('.' + cls.ICON) as HTMLElement).click();
gridFocus.focus();
let element: HTMLElement = gridFocus.getFocusedElement();
addClass([element], ['e-focused', 'e-focus']);
element.setAttribute('tabindex', '0');
} else if (target.classList.contains('e-valuescontent')) {
target.dispatchEvent(new MouseEvent('dblclick', {
'view': window,
'bubbles': true,
'cancelable': true
}));
if (target.querySelector('.e-numerictextbox')) {
(target as HTMLElement).click();
}
} else if (target.classList.contains('e-numerictextbox')) {
gridFocus.focus();
let element: HTMLElement = gridFocus.getFocusedElement();
removeClass([element], ['e-focused', 'e-focus']);
}
} else if (e.keyCode === 13 && e.shiftKey && !e.ctrlKey) {
if (this.parent.enableValueSorting) {
this.event = e;
(target as HTMLElement).click();
gridFocus.focus();
let element: HTMLElement = gridFocus.getFocusedElement();
addClass([element], ['e-focused', 'e-focus']);
element.setAttribute('tabindex', '0');
}
} else if (e.keyCode === 13 && !e.shiftKey && e.ctrlKey) {
if (this.parent.hyperlinkSettings && target.querySelector('a')) {
(target.querySelector('a') as HTMLElement).click();
}
}
e.preventDefault();
return;
}
}
private clearSelection(): void {
let control: PivotView = this.parent as PivotView;
removeClass(control.element.querySelectorAll('.' + cls.CELL_SELECTED_BGCOLOR + ',.' + cls.SELECTED_BGCOLOR), [cls.SELECTED_BGCOLOR, cls.CELL_SELECTED_BGCOLOR, cls.CELL_ACTIVE_BGCOLOR]);
this.parent.renderModule.selected();
}
private processSelection(e: KeyboardEventArgs): void {
let target: HTMLElement = e.target as HTMLElement;
if (this.parent.grid && this.parent.gridSettings.allowSelection && this.parent.gridSettings.selectionSettings.mode !== 'Row' &&
!target.classList.contains('e-numerictextbox')) {
let control: PivotView = this.parent as PivotView;
let colIndex: number = Number((e.target as HTMLElement).getAttribute('aria-colIndex'));
let rowIndex: number = Number((e.target as HTMLElement).getAttribute('index'));
let ele: HTMLElement;
/* eslint-disable */
if (target.nodeName === 'TH' || target.nodeName === 'TD') {
if (e.action === 'shiftUp' || e.action === 'upArrow') {
ele = (rowIndex === 0 || colIndex === 0 || (target.nodeName !== 'TH' &&
control.renderModule.rowStartPos !== rowIndex)) ? null : this.getParentElement(control, ele, colIndex, rowIndex - 1);
} else if (e.action === 'shiftDown' || e.action === 'downArrow') {
ele = control.element.querySelector('th[aria-colindex="' + colIndex + '"][index="' + (rowIndex + 1) + '"]');
}
else if (e.action === 'shiftLeft' || e.action === 'leftArrow') {
ele = (e.target as HTMLElement).previousSibling as HTMLElement;
}
else {
ele = (e.target as HTMLElement).nextSibling as HTMLElement;
}
}
if (!isNullOrUndefined(ele)) {
if (control.gridSettings.selectionSettings.mode === 'Both' ? !ele.classList.contains(cls.ROW_CELL_CLASS) : true) {
colIndex = Number(ele.getAttribute('aria-colindex'));
rowIndex = Number(ele.getAttribute('index'));
let colSpan: number = Number(ele.getAttribute('aria-colspan'));
control.clearSelection(ele, e, colIndex, rowIndex);
let selectArgs: PivotCellSelectedEventArgs = {
cancel: false,
isCellClick: true,
currentCell: ele,
data: control.pivotValues[rowIndex][colIndex] as IAxisSet
};
control.trigger(events.cellSelecting, selectArgs, (observedArgs: PivotCellSelectedEventArgs) => {
if (!observedArgs.cancel) {
control.applyColumnSelection(e, ele, colIndex, colIndex + (colSpan > 0 ? (colSpan - 1) : 0), rowIndex);
}
});
} else {
control.clearSelection(ele, e, colIndex, rowIndex);
}
} else {
if (e.action === 'upArrow') {
ele = control.element.querySelector('[aria-colindex="' + colIndex + '"][index="' + (rowIndex - 1) + '"]');
rowIndex--;
}
else if (e.action === 'downArrow') {
ele = control.element.querySelector('[aria-colindex="' + colIndex + '"][index="' + (rowIndex + 1) + '"]');
rowIndex++;
}
if (!isNullOrUndefined(ele)) {
control.clearSelection(ele, e, colIndex, rowIndex);
}
}
}
else if (target && (e.keyCode === 37 || e.keyCode === 38) &&
this.parent && this.parent.showGroupingBar && this.parent.groupingBarModule && !target.classList.contains('e-numerictextbox')) {
if (this.parent.grid && this.parent.element.querySelector('.e-frozenheader') && this.parent.element.querySelector('.e-frozenheader').querySelectorAll('.e-focus').length > 0) {
removeClass(this.parent.element.querySelector('.e-frozenheader').querySelectorAll('.e-focus'), 'e-focus');
removeClass(this.parent.element.querySelector('.e-frozenheader').querySelectorAll('.e-focused'), 'e-focused');
this.parent.element.querySelector('.e-headercell').setAttribute('tabindex', '-1');
let gridFocus: FocusStrategy = this.parent.grid.serviceLocator.getService<FocusStrategy>('focus');
gridFocus.setFocusedElement(target);
addClass([target], ['e-focused', 'e-focus']);
target.setAttribute('tabindex', '0');
target.focus();
e.preventDefault();
return;
}
} else if (target.classList.contains('e-numerictextbox') && (e.action === 'rightArrow' || e.action === 'leftArrow')) {
(target as HTMLElement).click();
}
/* eslint-enable */
}
private getParentElement(control: PivotView, ele: HTMLElement, colIndex: number, rowIndex: number): HTMLElement {
while (!ele) {
ele = control.element.querySelector('[aria-colindex="' + colIndex + '"][index="' + rowIndex + '"]');
colIndex--;
}
return ele;
}
private toggleFieldList(e: Event): void {
if (this.parent && !this.parent.isDestroyed && this.parent.showFieldList &&
this.parent.pivotFieldListModule && !this.parent.pivotFieldListModule.isDestroyed &&
this.parent.element.querySelector('.' + cls.TOGGLE_FIELD_LIST_CLASS)) {
if (!this.parent.element.querySelector('.' + cls.TOGGLE_FIELD_LIST_CLASS).classList.contains(cls.ICON_HIDDEN)) {
(this.parent.element.querySelector('.' + cls.TOGGLE_FIELD_LIST_CLASS) as HTMLElement).click();
e.preventDefault();
return;
} else if (this.parent.element.querySelector('.' + cls.TOGGLE_FIELD_LIST_CLASS).classList.contains(cls.ICON_HIDDEN) &&
this.parent.pivotFieldListModule.dialogRenderer && this.parent.pivotFieldListModule.dialogRenderer.fieldListDialog &&
!this.parent.pivotFieldListModule.dialogRenderer.fieldListDialog.isDestroyed) {
this.parent.pivotFieldListModule.dialogRenderer.fieldListDialog.hide();
}
}
}
/**
* To destroy the keyboard module.
* @returns {void}
* @private
*/
public destroy(): void {
if (this.pivotViewKeyboardModule) {
this.pivotViewKeyboardModule.destroy();
} else {
return;
}
}
} | the_stack |
import { SessionContext } from '@jupyterlab/apputils';
import { Cell, ICellModel } from '@jupyterlab/cells';
import { CodeEditor } from '@jupyterlab/codeeditor';
import * as nbformat from '@jupyterlab/nbformat';
import { Notebook, NotebookPanel } from '@jupyterlab/notebook';
import {
IObservableList,
IObservableUndoableList
} from '@jupyterlab/observables';
import { Session } from '@jupyterlab/services';
import { ICommandContext } from '../../command_manager';
import { PositionConverter } from '../../converter';
import { LSPExtension } from '../../index';
import { IEditorPosition, IVirtualPosition } from '../../positioning';
import { until_ready } from '../../utils';
import { VirtualDocument } from '../../virtual/document';
import { WidgetAdapter } from '../adapter';
import IEditor = CodeEditor.IEditor;
import ILanguageInfoMetadata = nbformat.ILanguageInfoMetadata;
export class NotebookAdapter extends WidgetAdapter<NotebookPanel> {
editor: Notebook;
private ce_editor_to_cell: Map<IEditor, Cell>;
private known_editors_ids: Set<string>;
private _language_info: ILanguageInfoMetadata;
private type: nbformat.CellType = 'code';
constructor(extension: LSPExtension, editor_widget: NotebookPanel) {
super(extension, editor_widget);
this.ce_editor_to_cell = new Map();
this.editor = editor_widget.content;
this.known_editors_ids = new Set();
this.initialized = new Promise<void>((resolve, reject) => {
this.init_once_ready().then(resolve).catch(reject);
});
}
private async update_language_info() {
const language_info = (
await this.widget.context.sessionContext?.session?.kernel?.info
)?.language_info;
if (language_info) {
this._language_info = language_info;
} else {
throw new Error(
'Language info update failed (no session, kernel, or info available)'
);
}
}
async on_kernel_changed(
_session: SessionContext,
change: Session.ISessionConnection.IKernelChangedArgs
) {
if (!change.newValue) {
this.console.log('Kernel was shut down');
return;
}
try {
// note: we need to wait until ready before updating language info
this.console.log('Changed kernel, will try to reconnect');
const old_language_info = this._language_info;
await until_ready(this.is_ready, -1);
await this.update_language_info();
const new_language_info = this._language_info;
if (
old_language_info?.name != new_language_info.name ||
old_language_info?.mimetype != new_language_info?.mimetype ||
old_language_info?.file_extension != new_language_info?.file_extension
) {
this.console.log(
`Changed to ${this._language_info.name} kernel, reconnecting`
);
this.reload_connection();
} else {
this.console.log(
'Keeping old LSP connection as the new kernel uses the same langauge'
);
}
} catch (err) {
this.console.warn(err);
// try to reconnect anyway
this.reload_connection();
}
}
dispose() {
if (this.isDisposed) {
return;
}
this.widget.context.sessionContext.kernelChanged.disconnect(
this.on_kernel_changed,
this
);
this.widget.content.activeCellChanged.disconnect(
this.activeCellChanged,
this
);
super.dispose();
// editors are needed for the parent dispose() to unbind signals, so they are the last to go
this.ce_editor_to_cell.clear();
}
is_ready = () => {
return (
!this.widget.isDisposed &&
this.widget.context.isReady &&
this.widget.content.isVisible &&
this.widget.content.widgets.length > 0 &&
this.widget.context.sessionContext.session?.kernel != null
);
};
get document_path(): string {
return this.widget.context.path;
}
protected language_info(): ILanguageInfoMetadata {
return this._language_info;
}
get mime_type(): string {
let language_metadata = this.language_info();
if (!language_metadata || !language_metadata.mimetype) {
// fallback to the code cell mime type if no kernel in use
return this.widget.content.codeMimetype;
}
return language_metadata.mimetype;
}
get language_file_extension(): string | undefined {
let language_metadata = this.language_info();
if (!language_metadata || !language_metadata.file_extension) {
return;
}
return language_metadata.file_extension.replace('.', '');
}
get wrapper_element() {
return this.widget.node;
}
protected async init_once_ready() {
this.console.log('waiting for', this.document_path, 'to fully load');
await this.widget.context.sessionContext.ready;
await until_ready(this.is_ready, -1);
await this.update_language_info();
this.console.log(this.document_path, 'ready for connection');
this.init_virtual();
// connect the document, but do not open it as the adapter will handle this
// after registering all features
this.connect_document(this.virtual_editor.virtual_document, false).catch(
this.console.warn
);
this.widget.context.sessionContext.kernelChanged.connect(
this.on_kernel_changed,
this
);
this.widget.content.activeCellChanged.connect(this.activeCellChanged, this);
this._connectModelSignals(this.widget);
this.editor.modelChanged.connect(notebook => {
// note: this should not usually happen;
// there is no default action that would trigger this,
// its just a failsafe in case if another extension decides
// to swap the notebook model
this.console.warn(
'Model changed, connecting cell change handler; this is not something we were expecting'
);
this._connectModelSignals(notebook);
});
}
private _connectModelSignals(notebook: NotebookPanel | Notebook) {
if (notebook.model === null) {
this.console.warn(
`Model is missing for notebook ${notebook}, cannot connet cell changed signal!`
);
} else {
notebook.model.cells.changed.connect(this.handle_cell_change, this);
}
}
async handle_cell_change(
cells: IObservableUndoableList<ICellModel>,
change: IObservableList.IChangedArgs<ICellModel>
) {
let cellsAdded: ICellModel[] = [];
let cellsRemoved: ICellModel[] = [];
const type = this.type;
if (change.type === 'set') {
// handling of conversions is important, because the editors get re-used and their handlers inherited,
// so we need to clear our handlers from editors of e.g. markdown cells which previously were code cells.
let convertedToMarkdownOrRaw = [];
let convertedToCode = [];
if (change.newValues.length === change.oldValues.length) {
// during conversion the cells should not get deleted nor added
for (let i = 0; i < change.newValues.length; i++) {
if (
change.oldValues[i].type === type &&
change.newValues[i].type !== type
) {
convertedToMarkdownOrRaw.push(change.newValues[i]);
} else if (
change.oldValues[i].type !== type &&
change.newValues[i].type === type
) {
convertedToCode.push(change.newValues[i]);
}
}
cellsAdded = convertedToCode;
cellsRemoved = convertedToMarkdownOrRaw;
}
} else if (change.type == 'add') {
cellsAdded = change.newValues.filter(
cellModel => cellModel.type === type
);
}
// note: editorRemoved is not emitted for removal of cells by change of type 'remove' (but only during cell type conversion)
// because there is no easy way to get the widget associated with the removed cell(s) - because it is no
// longer in the notebook widget list! It would need to be tracked on our side, but it is not necessary
// as (except for a tiny memory leak) it should not impact the functionality in any way
if (
cellsRemoved.length ||
cellsAdded.length ||
change.type === 'move' ||
change.type === 'remove'
) {
// in contrast to the file editor document which can be only changed by the modification of the editor content,
// the notebook document cna also get modified by a change in the number or arrangement of editors themselves;
// for this reason each change has to trigger documents update (so that LSP mirror is in sync).
await this.update_documents();
}
for (let cellModel of cellsRemoved) {
let cellWidget = this.widget.content.widgets.find(
cell => cell.model.id === cellModel.id
);
if (!cellWidget) {
this.console.warn(
`Widget for removed cell with ID: ${cellModel.id} not found!`
);
continue;
}
this.known_editors_ids.delete(cellWidget.editor.uuid);
// for practical purposes this editor got removed from our consideration;
// it might seem that we should instead look for the editor indicated by
// the oldValues[i] cellModel, but this one got already transferred to the
// markdown cell in newValues[i]
this.editorRemoved.emit({
editor: cellWidget.editor
});
}
for (let cellModel of cellsAdded) {
let cellWidget = this.widget.content.widgets.find(
cell => cell.model.id === cellModel.id
);
if (!cellWidget) {
this.console.warn(
`Widget for added cell with ID: ${cellModel.id} not found!`
);
continue;
}
this.known_editors_ids.add(cellWidget.editor.uuid);
this.editorAdded.emit({
editor: cellWidget.editor
});
}
}
get editors(): CodeEditor.IEditor[] {
if (this.isDisposed) {
return [];
}
let notebook = this.widget.content;
this.ce_editor_to_cell.clear();
if (notebook.isDisposed) {
return [];
}
return notebook.widgets
.filter(cell => cell.model.type === 'code')
.map(cell => {
this.ce_editor_to_cell.set(cell.editor, cell);
return cell.editor;
});
}
create_virtual_document() {
return new VirtualDocument({
language: this.language,
path: this.document_path,
overrides_registry: this.code_overrides,
foreign_code_extractors: this.foreign_code_extractors,
file_extension: this.language_file_extension,
// notebooks are continuous, each cell is dependent on the previous one
standalone: false,
// notebooks are not supported by LSP servers
has_lsp_supported_file: false,
console: this.console
});
}
get activeEditor() {
return this.widget.content.activeCell?.editor;
}
private activeCellChanged(notebook: Notebook, cell: Cell) {
if (cell.model.type !== this.type) {
return;
}
if (!this.known_editors_ids.has(cell.editor.uuid)) {
this.known_editors_ids.add(cell.editor.uuid);
this.editorAdded.emit({
editor: cell.editor
});
}
this.activeEditorChanged.emit({
editor: cell.editor
});
}
context_from_active_document(): ICommandContext | null {
let cell = this.widget.content.activeCell;
if (cell === null) {
return null;
}
// short circuit if disposed
if (!this.virtual_editor || !this.get_context) {
return null;
}
if (cell.model.type !== this.type) {
// context will be sought on all cells to verify if the context menu should be visible,
// thus it is ok to just return null; it seems to stem from the implementation detail
// upstream, i.e. the markdown cells appear to be created by transforming the code cells
// but do not quote me on that.
return null;
}
let editor = cell.editor;
let ce_cursor = editor.getCursorPosition();
let cm_cursor = PositionConverter.ce_to_cm(ce_cursor) as IEditorPosition;
let virtual_editor = this.virtual_editor;
if (virtual_editor == null) {
return null;
}
let root_position = virtual_editor.transform_from_editor_to_root(
editor,
cm_cursor
);
if (root_position == null) {
this.console.warn('Could not retrieve current context', virtual_editor);
return null;
}
return this.get_context(root_position);
}
get_editor_index_at(position: IVirtualPosition): number {
let cell = this.get_cell_at(position);
let notebook = this.widget.content;
return notebook.widgets.findIndex(other_cell => {
return cell === other_cell;
});
}
get_editor_index(ce_editor: CodeEditor.IEditor): number {
let cell = this.ce_editor_to_cell.get(ce_editor)!;
let notebook = this.widget.content;
return notebook.widgets.findIndex(other_cell => {
return cell === other_cell;
});
}
get_editor_wrapper(ce_editor: CodeEditor.IEditor): HTMLElement {
let cell = this.ce_editor_to_cell.get(ce_editor)!;
return cell.node;
}
private get_cell_at(pos: IVirtualPosition): Cell {
let ce_editor =
this.virtual_editor.virtual_document.get_editor_at_virtual_line(pos);
return this.ce_editor_to_cell.get(ce_editor)!;
}
} | the_stack |
import '@graphql-codegen/testing';
import { parse } from 'graphql';
import { codegen } from '@graphql-codegen/core';
import { plugin } from '../src';
import { TypeScriptResolversPluginConfig } from '../src/config';
function generate({ schema, config }: { schema: string; config: TypeScriptResolversPluginConfig }) {
return codegen({
filename: 'graphql.ts',
schema: parse(schema),
documents: [],
plugins: [
{
'typescript-resolvers': {},
},
],
config,
pluginMap: {
'typescript-resolvers': {
plugin,
},
},
});
}
describe('TypeScript Resolvers Plugin + Apollo Federation', () => {
it('should add __resolveReference to objects that have @key', async () => {
const federatedSchema = /* GraphQL */ `
type Query {
allUsers: [User]
}
type User @key(fields: "id") {
id: ID!
name: String
username: String
}
type Book {
id: ID!
}
`;
const content = await generate({
schema: federatedSchema,
config: {
federation: true,
},
});
// User should have it
expect(content).toBeSimilarStringTo(`
__resolveReference?: ReferenceResolver<Maybe<ResolversTypes['User']>, { __typename: 'User' } & GraphQLRecursivePick<ParentType, {"id":true}>, ContextType>;
`);
// Foo shouldn't because it doesn't have @key
expect(content).not.toBeSimilarStringTo(`
__resolveReference?: ReferenceResolver<Maybe<ResolversTypes['Book']>, { __typename: 'Book' } & GraphQLRecursivePick<ParentType, {"id":true}>, ContextType>;
`);
});
it('should support extend keyword', async () => {
const federatedSchema = /* GraphQL */ `
extend type Query {
allUsers: [User]
}
extend type User @key(fields: "id") {
id: ID!
name: String
username: String
}
type Book {
id: ID!
}
`;
const content = await generate({
schema: federatedSchema,
config: {
federation: true,
},
});
// User should have it
expect(content).toBeSimilarStringTo(`
__resolveReference?: ReferenceResolver<Maybe<ResolversTypes['User']>, { __typename: 'User' } & GraphQLRecursivePick<ParentType, {"id":true}>, ContextType>;
`);
// Foo shouldn't because it doesn't have @key
expect(content).not.toBeSimilarStringTo(`
__resolveReference?: ReferenceResolver<Maybe<ResolversTypes['Book']>, { __typename: 'Book' } & GraphQLRecursivePick<ParentType, {"id":true}>, ContextType>;
`);
});
it('should include fields from @requires directive', async () => {
const federatedSchema = /* GraphQL */ `
type Query {
users: [User]
}
type User @key(fields: "id") {
id: ID!
name: String @external
age: Int! @external
username: String @requires(fields: "name age")
}
`;
const content = await generate({
schema: federatedSchema,
config: {
federation: true,
},
});
// User should have it
expect(content).toBeSimilarStringTo(`
export type UserResolvers<ContextType = any, ParentType extends ResolversParentTypes['User'] = ResolversParentTypes['User']> = {
__resolveReference?: ReferenceResolver<Maybe<ResolversTypes['User']>, { __typename: 'User' } & GraphQLRecursivePick<ParentType, {"id":true}>, ContextType>;
id?: Resolver<ResolversTypes['ID'], { __typename: 'User' } & GraphQLRecursivePick<ParentType, {"id":true}>, ContextType>;
username?: Resolver<Maybe<ResolversTypes['String']>, { __typename: 'User' } & GraphQLRecursivePick<ParentType, {"id":true}> & GraphQLRecursivePick<ParentType, {"name":true,"age":true}>, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
`);
});
it('should handle nested fields from @requires directive', async () => {
const federatedSchema = /* GraphQL */ `
type Query {
users: [User]
}
extend type User @key(fields: "id") {
id: ID! @external
name: String @external
age: Int! @external
address: Address! @external
username: String @requires(fields: "name age address { street }")
}
extend type Address {
street: String! @external
zip: Int! @external
}
`;
const content = await generate({
schema: federatedSchema,
config: {
federation: true,
},
});
expect(content).toBeSimilarStringTo(`
export type UserResolvers<ContextType = any, ParentType extends ResolversParentTypes['User'] = ResolversParentTypes['User']> = {
__resolveReference?: ReferenceResolver<Maybe<ResolversTypes['User']>, { __typename: 'User' } & GraphQLRecursivePick<ParentType, {"id":true}>, ContextType>;
username?: Resolver<Maybe<ResolversTypes['String']>, { __typename: 'User' } & GraphQLRecursivePick<ParentType, {"id":true}> & GraphQLRecursivePick<ParentType, {"name":true,"age":true,"address":{"street":true}}>, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
`);
});
it('should handle nested fields from @key directive', async () => {
const federatedSchema = /* GraphQL */ `
type Query {
users: [User]
}
type User @key(fields: "name { first last }") {
name: Name! @external
username: String
}
type Name {
first: String! @external
last: String! @external
}
`;
const content = await generate({
schema: federatedSchema,
config: {
federation: true,
},
});
expect(content).toBeSimilarStringTo(`
export type UserResolvers<ContextType = any, ParentType extends ResolversParentTypes['User'] = ResolversParentTypes['User']> = {
__resolveReference?: ReferenceResolver<Maybe<ResolversTypes['User']>, { __typename: 'User' } & GraphQLRecursivePick<ParentType, {"name":{"first":true,"last":true}}>, ContextType>;
username?: Resolver<Maybe<ResolversTypes['String']>, { __typename: 'User' } & GraphQLRecursivePick<ParentType, {"name":{"first":true,"last":true}}>, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
`);
});
it('should not apply key/requires fields restriction for base federated types', async () => {
const federatedSchema = /* GraphQL */ `
type Query {
users: [User]
}
type User @key(fields: "name { first last }") {
name: Name!
username: String
}
type Name {
first: String!
last: String!
}
`;
const content = await generate({
schema: federatedSchema,
config: {
federation: true,
},
});
expect(content).toBeSimilarStringTo(`
export type UserResolvers<ContextType = any, ParentType extends ResolversParentTypes['User'] = ResolversParentTypes['User']> = {
__resolveReference?: ReferenceResolver<Maybe<ResolversTypes['User']>, { __typename: 'User' } & GraphQLRecursivePick<ParentType, {"name":{"first":true,"last":true}}>, ContextType>;
name?: Resolver<ResolversTypes['Name'], ParentType, ContextType>;
username?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
`);
});
it.skip('should handle interface types', async () => {
const federatedSchema = /* GraphQL */ `
type Query {
people: [Person]
}
extend interface Person @key(fields: "name { first last }") {
name: Name! @external
age: Int @requires(fields: "name")
}
extend type User implements Person @key(fields: "name { first last }") {
name: Name! @external
age: Int @requires(fields: "name { first last }")
username: String
}
type Admin implements Person @key(fields: "name { first last }") {
name: Name! @external
age: Int @requires(fields: "name { first last }")
permissions: [String!]!
}
extend type Name {
first: String! @external
last: String! @external
}
`;
const content = await generate({
schema: federatedSchema,
config: {
federation: true,
},
});
expect(content).toBeSimilarStringTo(`
export type PersonResolvers<ContextType = any, ParentType extends ResolversParentTypes['Person'] = ResolversParentTypes['Person']> = {
__resolveType: TypeResolveFn<'User' | 'Admin', ParentType, ContextType>;
age?: Resolver<Maybe<ResolversTypes['Int']>, { __typename: 'User' | 'Admin' } & GraphQLRecursivePick<ParentType, {"name":{"first":true,"last":true}}>, ContextType>;
};
`);
});
it('should skip to generate resolvers of fields with @external directive', async () => {
const federatedSchema = /* GraphQL */ `
type Query {
users: [User]
}
type Book {
author: User @provides(fields: "name")
}
type User @key(fields: "id") {
id: ID!
name: String @external
username: String @external
}
`;
const content = await generate({
schema: federatedSchema,
config: {
federation: true,
},
});
// UserResolver should not have a resolver function of name field
expect(content).toBeSimilarStringTo(`
export type UserResolvers<ContextType = any, ParentType extends ResolversParentTypes['User'] = ResolversParentTypes['User']> = {
__resolveReference?: ReferenceResolver<Maybe<ResolversTypes['User']>, { __typename: 'User' } & GraphQLRecursivePick<ParentType, {"id":true}>, ContextType>;
id?: Resolver<ResolversTypes['ID'], { __typename: 'User' } & GraphQLRecursivePick<ParentType, {"id":true}>, ContextType>;
name?: Resolver<Maybe<ResolversTypes['String']>, { __typename: 'User' } & GraphQLRecursivePick<ParentType, {"id":true}>, ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
`);
});
it('should not include _FieldSet scalar', async () => {
const federatedSchema = /* GraphQL */ `
type Query {
users: [User]
}
type User @key(fields: "id") {
id: ID!
name: String
username: String
}
type Book {
id: ID!
}
`;
const content = await generate({
schema: federatedSchema,
config: {
federation: true,
},
});
expect(content).not.toMatch(`_FieldSet`);
});
it('should not include federation directives', async () => {
const federatedSchema = /* GraphQL */ `
type Query {
users: [User]
}
type User @key(fields: "id") {
id: ID!
name: String
username: String
}
type Book {
id: ID!
}
`;
const content = await generate({
schema: federatedSchema,
config: {
federation: true,
},
});
expect(content).not.toMatch('ExternalDirectiveResolver');
expect(content).not.toMatch('RequiresDirectiveResolver');
expect(content).not.toMatch('ProvidesDirectiveResolver');
expect(content).not.toMatch('KeyDirectiveResolver');
});
it('should not add directive definitions and scalars if they are already there', async () => {
const federatedSchema = /* GraphQL */ `
scalar _FieldSet
directive @key(fields: _FieldSet!) on OBJECT | INTERFACE
type Query {
allUsers: [User]
}
type User @key(fields: "id") {
id: ID!
name: String
username: String
}
type Book {
id: ID!
}
`;
const content = await generate({
schema: federatedSchema,
config: {
federation: true,
},
});
expect(content).not.toMatch(`_FieldSet`);
expect(content).not.toMatch('ExternalDirectiveResolver');
expect(content).not.toMatch('RequiresDirectiveResolver');
expect(content).not.toMatch('ProvidesDirectiveResolver');
expect(content).not.toMatch('KeyDirectiveResolver');
});
it('should allow for duplicated directives', async () => {
const federatedSchema = /* GraphQL */ `
type Query {
allUsers: [User]
}
extend type User @key(fields: "id") @key(fields: "name") {
id: ID! @external
name: String
username: String
}
type Book {
id: ID!
}
`;
const content = await generate({
schema: federatedSchema,
config: {
federation: true,
},
});
// User should have it
expect(content).toBeSimilarStringTo(`
export type UserResolvers<ContextType = any, ParentType extends ResolversParentTypes['User'] = ResolversParentTypes['User']> = {
__resolveReference?: ReferenceResolver<Maybe<ResolversTypes['User']>, { __typename: 'User' } & (GraphQLRecursivePick<ParentType, {"id":true}> | GraphQLRecursivePick<ParentType, {"name":true}>), ContextType>;
name?: Resolver<Maybe<ResolversTypes['String']>, { __typename: 'User' } & (GraphQLRecursivePick<ParentType, {"id":true}> | GraphQLRecursivePick<ParentType, {"name":true}>), ContextType>;
username?: Resolver<Maybe<ResolversTypes['String']>, { __typename: 'User' } & (GraphQLRecursivePick<ParentType, {"id":true}> | GraphQLRecursivePick<ParentType, {"name":true}>), ContextType>;
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
};
`);
});
it.skip('should only extend an original type by a mapped type', async () => {
const federatedSchema = /* GraphQL */ `
type Query {
users: [User]
}
type User @key(fields: "id") {
id: ID!
name: String
age: Int!
username: String
}
`;
const content = await generate({
schema: federatedSchema,
config: {
federation: true,
mappers: {
User: 'UserExtension',
},
},
});
// User should have it
expect(content).toBeSimilarStringTo(`
export type UserResolvers<ContextType = any, ParentType extends ResolversParentTypes['User'] = ResolversParentTypes['User']> = {
__resolveReference?: ReferenceResolver<Maybe<ResolversTypes['User']>, { __typename: 'User' } & Pick<ParentType, 'id'>, ContextType>;
id?: Resolver<ResolversTypes['ID'], UserExtension & ParentType, ContextType>;
username?: Resolver<Maybe<ResolversTypes['String']>, UserExtension & ParentType & Pick<ParentType, 'name', 'age'>, ContextType>;
};
`);
});
it('should not generate unused scalars', async () => {
const federatedSchema = /* GraphQL */ `
type Query {
user(id: ID!): User!
}
type User {
id: ID!
username: String!
}
`;
const content = await generate({
schema: federatedSchema,
config: {
federation: true,
},
});
// no GraphQLScalarTypeConfig
expect(content).not.toContain('GraphQLScalarTypeConfig');
// no GraphQLScalarType
expect(content).not.toContain('GraphQLScalarType');
});
describe('When field definition wrapping is enabled', () => {
it('should add the UnwrappedObject type', async () => {
const federatedSchema = /* GraphQL */ `
type User @key(fields: "id") {
id: ID!
}
`;
const content = await generate({
schema: federatedSchema,
config: {
federation: true,
wrapFieldDefinitions: true,
},
});
expect(content).toBeSimilarStringTo(`type UnwrappedObject<T> = {`);
});
it('should add UnwrappedObject around ParentType for __resloveReference', async () => {
const federatedSchema = /* GraphQL */ `
type User @key(fields: "id") {
id: ID!
}
`;
const content = await generate({
schema: federatedSchema,
config: {
federation: true,
wrapFieldDefinitions: true,
},
});
// __resolveReference should be unwrapped
expect(content).toBeSimilarStringTo(`
__resolveReference?: ReferenceResolver<Maybe<ResolversTypes['User']>, { __typename: 'User' } & GraphQLRecursivePick<UnwrappedObject<ParentType>, {"id":true}>, ContextType>;
`);
// but ID should not
expect(content).toBeSimilarStringTo(`id?: Resolver<ResolversTypes['ID'], ParentType, ContextType>`);
});
});
}); | the_stack |
import {Request} from '../lib/request';
import {Response} from '../lib/response';
import {AWSError} from '../lib/error';
import {Service} from '../lib/service';
import {ServiceConfigurationOptions} from '../lib/service';
import {ConfigBase as Config} from '../lib/config-base';
interface Blob {}
declare class QLDBSession extends Service {
/**
* Constructs a service object. This object has one method for each API operation.
*/
constructor(options?: QLDBSession.Types.ClientConfiguration)
config: Config & QLDBSession.Types.ClientConfiguration;
/**
* Sends a command to an Amazon QLDB ledger. Instead of interacting directly with this API, we recommend using the QLDB driver or the QLDB shell to execute data transactions on a ledger. If you are working with an AWS SDK, use the QLDB driver. The driver provides a high-level abstraction layer above this QLDB Session data plane and manages SendCommand API calls for you. For information and a list of supported programming languages, see Getting started with the driver in the Amazon QLDB Developer Guide. If you are working with the AWS Command Line Interface (AWS CLI), use the QLDB shell. The shell is a command line interface that uses the QLDB driver to interact with a ledger. For information, see Accessing Amazon QLDB using the QLDB shell.
*/
sendCommand(params: QLDBSession.Types.SendCommandRequest, callback?: (err: AWSError, data: QLDBSession.Types.SendCommandResult) => void): Request<QLDBSession.Types.SendCommandResult, AWSError>;
/**
* Sends a command to an Amazon QLDB ledger. Instead of interacting directly with this API, we recommend using the QLDB driver or the QLDB shell to execute data transactions on a ledger. If you are working with an AWS SDK, use the QLDB driver. The driver provides a high-level abstraction layer above this QLDB Session data plane and manages SendCommand API calls for you. For information and a list of supported programming languages, see Getting started with the driver in the Amazon QLDB Developer Guide. If you are working with the AWS Command Line Interface (AWS CLI), use the QLDB shell. The shell is a command line interface that uses the QLDB driver to interact with a ledger. For information, see Accessing Amazon QLDB using the QLDB shell.
*/
sendCommand(callback?: (err: AWSError, data: QLDBSession.Types.SendCommandResult) => void): Request<QLDBSession.Types.SendCommandResult, AWSError>;
}
declare namespace QLDBSession {
export interface AbortTransactionRequest {
}
export interface AbortTransactionResult {
/**
* Contains server-side performance information for the command.
*/
TimingInformation?: TimingInformation;
}
export type CommitDigest = Buffer|Uint8Array|Blob|string;
export interface CommitTransactionRequest {
/**
* Specifies the transaction ID of the transaction to commit.
*/
TransactionId: TransactionId;
/**
* Specifies the commit digest for the transaction to commit. For every active transaction, the commit digest must be passed. QLDB validates CommitDigest and rejects the commit with an error if the digest computed on the client does not match the digest computed by QLDB. The purpose of the CommitDigest parameter is to ensure that QLDB commits a transaction if and only if the server has processed the exact set of statements sent by the client, in the same order that client sent them, and with no duplicates.
*/
CommitDigest: CommitDigest;
}
export interface CommitTransactionResult {
/**
* The transaction ID of the committed transaction.
*/
TransactionId?: TransactionId;
/**
* The commit digest of the committed transaction.
*/
CommitDigest?: CommitDigest;
/**
* Contains server-side performance information for the command.
*/
TimingInformation?: TimingInformation;
/**
* Contains metrics about the number of I/O requests that were consumed.
*/
ConsumedIOs?: IOUsage;
}
export interface EndSessionRequest {
}
export interface EndSessionResult {
/**
* Contains server-side performance information for the command.
*/
TimingInformation?: TimingInformation;
}
export interface ExecuteStatementRequest {
/**
* Specifies the transaction ID of the request.
*/
TransactionId: TransactionId;
/**
* Specifies the statement of the request.
*/
Statement: Statement;
/**
* Specifies the parameters for the parameterized statement in the request.
*/
Parameters?: StatementParameters;
}
export interface ExecuteStatementResult {
/**
* Contains the details of the first fetched page.
*/
FirstPage?: Page;
/**
* Contains server-side performance information for the command.
*/
TimingInformation?: TimingInformation;
/**
* Contains metrics about the number of I/O requests that were consumed.
*/
ConsumedIOs?: IOUsage;
}
export interface FetchPageRequest {
/**
* Specifies the transaction ID of the page to be fetched.
*/
TransactionId: TransactionId;
/**
* Specifies the next page token of the page to be fetched.
*/
NextPageToken: PageToken;
}
export interface FetchPageResult {
/**
* Contains details of the fetched page.
*/
Page?: Page;
/**
* Contains server-side performance information for the command.
*/
TimingInformation?: TimingInformation;
/**
* Contains metrics about the number of I/O requests that were consumed.
*/
ConsumedIOs?: IOUsage;
}
export interface IOUsage {
/**
* The number of read I/O requests that the command performed.
*/
ReadIOs?: ReadIOs;
/**
* The number of write I/O requests that the command performed.
*/
WriteIOs?: WriteIOs;
}
export type IonBinary = Buffer|Uint8Array|Blob|string;
export type IonText = string;
export type LedgerName = string;
export interface Page {
/**
* A structure that contains values in multiple encoding formats.
*/
Values?: ValueHolders;
/**
* The token of the next page.
*/
NextPageToken?: PageToken;
}
export type PageToken = string;
export type ProcessingTimeMilliseconds = number;
export type ReadIOs = number;
export interface SendCommandRequest {
/**
* Specifies the session token for the current command. A session token is constant throughout the life of the session. To obtain a session token, run the StartSession command. This SessionToken is required for every subsequent command that is issued during the current session.
*/
SessionToken?: SessionToken;
/**
* Command to start a new session. A session token is obtained as part of the response.
*/
StartSession?: StartSessionRequest;
/**
* Command to start a new transaction.
*/
StartTransaction?: StartTransactionRequest;
/**
* Command to end the current session.
*/
EndSession?: EndSessionRequest;
/**
* Command to commit the specified transaction.
*/
CommitTransaction?: CommitTransactionRequest;
/**
* Command to abort the current transaction.
*/
AbortTransaction?: AbortTransactionRequest;
/**
* Command to execute a statement in the specified transaction.
*/
ExecuteStatement?: ExecuteStatementRequest;
/**
* Command to fetch a page.
*/
FetchPage?: FetchPageRequest;
}
export interface SendCommandResult {
/**
* Contains the details of the started session that includes a session token. This SessionToken is required for every subsequent command that is issued during the current session.
*/
StartSession?: StartSessionResult;
/**
* Contains the details of the started transaction.
*/
StartTransaction?: StartTransactionResult;
/**
* Contains the details of the ended session.
*/
EndSession?: EndSessionResult;
/**
* Contains the details of the committed transaction.
*/
CommitTransaction?: CommitTransactionResult;
/**
* Contains the details of the aborted transaction.
*/
AbortTransaction?: AbortTransactionResult;
/**
* Contains the details of the executed statement.
*/
ExecuteStatement?: ExecuteStatementResult;
/**
* Contains the details of the fetched page.
*/
FetchPage?: FetchPageResult;
}
export type SessionToken = string;
export interface StartSessionRequest {
/**
* The name of the ledger to start a new session against.
*/
LedgerName: LedgerName;
}
export interface StartSessionResult {
/**
* Session token of the started session. This SessionToken is required for every subsequent command that is issued during the current session.
*/
SessionToken?: SessionToken;
/**
* Contains server-side performance information for the command.
*/
TimingInformation?: TimingInformation;
}
export interface StartTransactionRequest {
}
export interface StartTransactionResult {
/**
* The transaction ID of the started transaction.
*/
TransactionId?: TransactionId;
/**
* Contains server-side performance information for the command.
*/
TimingInformation?: TimingInformation;
}
export type Statement = string;
export type StatementParameters = ValueHolder[];
export interface TimingInformation {
/**
* The amount of time that was taken for the command to finish processing, measured in milliseconds.
*/
ProcessingTimeMilliseconds?: ProcessingTimeMilliseconds;
}
export type TransactionId = string;
export interface ValueHolder {
/**
* An Amazon Ion binary value contained in a ValueHolder structure.
*/
IonBinary?: IonBinary;
/**
* An Amazon Ion plaintext value contained in a ValueHolder structure.
*/
IonText?: IonText;
}
export type ValueHolders = ValueHolder[];
export type WriteIOs = number;
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
export type apiVersion = "2019-07-11"|"latest"|string;
export interface ClientApiVersions {
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
apiVersion?: apiVersion;
}
export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions;
/**
* Contains interfaces for use with the QLDBSession client.
*/
export import Types = QLDBSession;
}
export = QLDBSession; | the_stack |
import { mapToInternalFieldValidationSchema } from './field-schema.mapper';
import {
FieldValidationSchema,
FieldValidationFunctionSync,
InternalFieldValidationSchema,
FieldValidationFunctionAsync,
FullFieldValidation,
} from '../model';
describe('field-schema.mapper specs', () => {
it('spec #1: should return empty object when it feeds fieldValidationSchema equals undefined', () => {
// Arrange
const fieldValidationSchema: FieldValidationSchema = void 0;
// Act
const result = mapToInternalFieldValidationSchema(fieldValidationSchema);
// Assert
expect(result).toEqual({});
});
it('spec #2: should return empty object when it feeds fieldValidationSchema equals null', () => {
// Arrange
const fieldValidationSchema: FieldValidationSchema = null;
// Act
const result = mapToInternalFieldValidationSchema(fieldValidationSchema);
// Assert
expect(result).toEqual({});
});
it('spec #3: should return empty object when it feeds fieldValidationSchema equals empty object', () => {
// Arrange
const fieldValidationSchema: FieldValidationSchema = {};
// Act
const result = mapToInternalFieldValidationSchema(fieldValidationSchema);
// Assert
expect(result).toEqual({});
});
it('spec #4: should return InternalFieldValidationSchema when it feeds fieldValidationSchema with one FieldValidationFunctionSync', done => {
// Arrange
const validator: FieldValidationFunctionSync = () => ({
succeeded: true,
message: 'test message',
type: 'test type',
});
const fieldValidationSchema: FieldValidationSchema = {
fieldId: [validator],
};
// Act
const result = mapToInternalFieldValidationSchema(fieldValidationSchema);
// Assert
const expectedResult: InternalFieldValidationSchema = {
fieldId: [
{
validator: expect.any(Function),
customArgs: void 0,
message: void 0,
},
],
};
expect(result).toEqual(expectedResult);
result['fieldId'][0].validator(null).then(validationResult => {
expect(validationResult).toEqual({
succeeded: true,
message: 'test message',
type: 'test type',
});
done();
});
});
it('spec #5: should return InternalFieldValidationSchema when it feeds fieldValidationSchema with two FieldValidationFunctionSync', done => {
// Arrange
const validator1: FieldValidationFunctionSync = () => ({
succeeded: true,
message: 'test message 1',
type: 'test type 1',
});
const validator2: FieldValidationFunctionSync = () => ({
succeeded: false,
message: 'test message 2',
type: 'test type 2',
});
const fieldValidationSchema: FieldValidationSchema = {
fieldId: [validator1, validator2],
};
// Act
const result = mapToInternalFieldValidationSchema(fieldValidationSchema);
// Assert
const expectedResult: InternalFieldValidationSchema = {
fieldId: [
{
validator: expect.any(Function),
customArgs: void 0,
message: void 0,
},
{
validator: expect.any(Function),
customArgs: void 0,
message: void 0,
},
],
};
expect(result).toEqual(expectedResult);
Promise.all([
result['fieldId'][0].validator(null),
result['fieldId'][1].validator(null),
]).then(validationResults => {
expect(validationResults[0]).toEqual({
succeeded: true,
message: 'test message 1',
type: 'test type 1',
});
expect(validationResults[1]).toEqual({
succeeded: false,
message: 'test message 2',
type: 'test type 2',
});
done();
});
});
it('spec #6: should return InternalFieldValidationSchema when it feeds fieldValidationSchema with two fields with one FieldValidationFunctionSync', done => {
// Arrange
const validator1: FieldValidationFunctionSync = () => ({
succeeded: true,
message: 'test message 1',
type: 'test type 1',
});
const validator2: FieldValidationFunctionSync = () => ({
succeeded: false,
message: 'test message 2',
type: 'test type 2',
});
const fieldValidationSchema: FieldValidationSchema = {
fieldId1: [validator1],
fieldId2: [validator2],
};
// Act
const result = mapToInternalFieldValidationSchema(fieldValidationSchema);
// Assert
const expectedResult: InternalFieldValidationSchema = {
fieldId1: [
{
validator: expect.any(Function),
customArgs: void 0,
message: void 0,
},
],
fieldId2: [
{
validator: expect.any(Function),
customArgs: void 0,
message: void 0,
},
],
};
expect(result).toEqual(expectedResult);
Promise.all([
result['fieldId1'][0].validator(null),
result['fieldId2'][0].validator(null),
]).then(validationResults => {
expect(validationResults[0]).toEqual({
succeeded: true,
message: 'test message 1',
type: 'test type 1',
});
expect(validationResults[1]).toEqual({
succeeded: false,
message: 'test message 2',
type: 'test type 2',
});
done();
});
});
it('spec #7: should return InternalFieldValidationSchema when it feeds fieldValidationSchema with one FieldValidationFunctionAsync', done => {
// Arrange
const validator: FieldValidationFunctionAsync = () =>
Promise.resolve({
succeeded: true,
message: 'test message',
type: 'test type',
});
const fieldValidationSchema: FieldValidationSchema = {
fieldId: [validator],
};
// Act
const result = mapToInternalFieldValidationSchema(fieldValidationSchema);
// Assert
const expectedResult: InternalFieldValidationSchema = {
fieldId: [
{
validator: expect.any(Function),
customArgs: void 0,
message: void 0,
},
],
};
expect(result).toEqual(expectedResult);
result['fieldId'][0].validator(null).then(validationResult => {
expect(validationResult).toEqual({
succeeded: true,
message: 'test message',
type: 'test type',
});
done();
});
});
it('spec #8: should return InternalFieldValidationSchema when it feeds fieldValidationSchema with two FieldValidationFunctionAsync', done => {
// Arrange
const validator1: FieldValidationFunctionAsync = () =>
Promise.resolve({
succeeded: true,
message: 'test message 1',
type: 'test type 1',
});
const validator2: FieldValidationFunctionAsync = () =>
Promise.resolve({
succeeded: false,
message: 'test message 2',
type: 'test type 2',
});
const fieldValidationSchema: FieldValidationSchema = {
fieldId: [validator1, validator2],
};
// Act
const result = mapToInternalFieldValidationSchema(fieldValidationSchema);
// Assert
const expectedResult: InternalFieldValidationSchema = {
fieldId: [
{
validator: expect.any(Function),
customArgs: void 0,
message: void 0,
},
{
validator: expect.any(Function),
customArgs: void 0,
message: void 0,
},
],
};
expect(result).toEqual(expectedResult);
Promise.all([
result['fieldId'][0].validator(null),
result['fieldId'][1].validator(null),
]).then(validationResults => {
expect(validationResults[0]).toEqual({
succeeded: true,
message: 'test message 1',
type: 'test type 1',
});
expect(validationResults[1]).toEqual({
succeeded: false,
message: 'test message 2',
type: 'test type 2',
});
done();
});
});
it('spec #9: should return InternalFieldValidationSchema when it feeds fieldValidationSchema with two fields with one FieldValidationFunctionAsync', done => {
// Arrange
const validator1: FieldValidationFunctionAsync = () =>
Promise.resolve({
succeeded: true,
message: 'test message 1',
type: 'test type 1',
});
const validator2: FieldValidationFunctionAsync = () =>
Promise.resolve({
succeeded: false,
message: 'test message 2',
type: 'test type 2',
});
const fieldValidationSchema: FieldValidationSchema = {
fieldId1: [validator1],
fieldId2: [validator2],
};
// Act
const result = mapToInternalFieldValidationSchema(fieldValidationSchema);
// Assert
const expectedResult: InternalFieldValidationSchema = {
fieldId1: [
{
validator: expect.any(Function),
customArgs: void 0,
message: void 0,
},
],
fieldId2: [
{
validator: expect.any(Function),
customArgs: void 0,
message: void 0,
},
],
};
expect(result).toEqual(expectedResult);
Promise.all([
result['fieldId1'][0].validator(null),
result['fieldId2'][0].validator(null),
]).then(validationResults => {
expect(validationResults[0]).toEqual({
succeeded: true,
message: 'test message 1',
type: 'test type 1',
});
expect(validationResults[1]).toEqual({
succeeded: false,
message: 'test message 2',
type: 'test type 2',
});
done();
});
});
it('spec #10: should return InternalFieldValidationSchema when it feeds fieldValidationSchema with one FullFieldValidation and sync validator', done => {
// Arrange
const validator: FieldValidationFunctionSync = () => ({
succeeded: true,
message: 'test message',
type: 'test type',
});
const fullFieldValidation: FullFieldValidation = {
validator,
customArgs: { arg: 1 },
message: 'updated message',
};
const fieldValidationSchema: FieldValidationSchema = {
fieldId: [fullFieldValidation],
};
// Act
const result = mapToInternalFieldValidationSchema(fieldValidationSchema);
// Assert
const expectedResult: InternalFieldValidationSchema = {
fieldId: [
{
validator: expect.any(Function),
customArgs: { arg: 1 },
message: 'updated message',
},
],
};
expect(result).toEqual(expectedResult);
result['fieldId'][0].validator(null).then(validationResult => {
expect(validationResult).toEqual({
succeeded: true,
message: 'test message',
type: 'test type',
});
done();
});
});
it('spec #11: should return InternalFieldValidationSchema when it feeds fieldValidationSchema with two FullFieldValidation and sync validator', done => {
// Arrange
const validator1: FieldValidationFunctionSync = () => ({
succeeded: true,
message: 'test message 1',
type: 'test type 1',
});
const fullFieldValidation1: FullFieldValidation = {
validator: validator1,
customArgs: { arg: 1 },
message: 'updated message 1',
};
const validator2: FieldValidationFunctionSync = () => ({
succeeded: false,
message: 'test message 2',
type: 'test type 2',
});
const fullFieldValidation2: FullFieldValidation = {
validator: validator2,
customArgs: { arg: 2 },
message: 'updated message 2',
};
const fieldValidationSchema: FieldValidationSchema = {
fieldId: [fullFieldValidation1, fullFieldValidation2],
};
// Act
const result = mapToInternalFieldValidationSchema(fieldValidationSchema);
// Assert
const expectedResult: InternalFieldValidationSchema = {
fieldId: [
{
validator: expect.any(Function),
customArgs: { arg: 1 },
message: 'updated message 1',
},
{
validator: expect.any(Function),
customArgs: { arg: 2 },
message: 'updated message 2',
},
],
};
expect(result).toEqual(expectedResult);
Promise.all([
result['fieldId'][0].validator(null),
result['fieldId'][1].validator(null),
]).then(validationResults => {
expect(validationResults[0]).toEqual({
succeeded: true,
message: 'test message 1',
type: 'test type 1',
});
expect(validationResults[1]).toEqual({
succeeded: false,
message: 'test message 2',
type: 'test type 2',
});
done();
});
});
it('spec #12: should return InternalFieldValidationSchema when it feeds fieldValidationSchema with two fields with one FullFieldValidation and sync validator', done => {
// Arrange
const validator1: FieldValidationFunctionSync = () => ({
succeeded: true,
message: 'test message 1',
type: 'test type 1',
});
const fullFieldValidation1: FullFieldValidation = {
validator: validator1,
customArgs: { arg: 1 },
message: 'updated message 1',
};
const validator2: FieldValidationFunctionSync = () => ({
succeeded: false,
message: 'test message 2',
type: 'test type 2',
});
const fullFieldValidation2: FullFieldValidation = {
validator: validator2,
customArgs: { arg: 2 },
message: 'updated message 2',
};
const fieldValidationSchema: FieldValidationSchema = {
fieldId1: [fullFieldValidation1],
fieldId2: [fullFieldValidation2],
};
// Act
const result = mapToInternalFieldValidationSchema(fieldValidationSchema);
// Assert
const expectedResult: InternalFieldValidationSchema = {
fieldId1: [
{
validator: expect.any(Function),
customArgs: { arg: 1 },
message: 'updated message 1',
},
],
fieldId2: [
{
validator: expect.any(Function),
customArgs: { arg: 2 },
message: 'updated message 2',
},
],
};
expect(result).toEqual(expectedResult);
Promise.all([
result['fieldId1'][0].validator(null),
result['fieldId2'][0].validator(null),
]).then(validationResults => {
expect(validationResults[0]).toEqual({
succeeded: true,
message: 'test message 1',
type: 'test type 1',
});
expect(validationResults[1]).toEqual({
succeeded: false,
message: 'test message 2',
type: 'test type 2',
});
done();
});
});
it('spec #13: should return InternalFieldValidationSchema when it feeds fieldValidationSchema with one FullFieldValidation and async validator', done => {
// Arrange
const validator: FieldValidationFunctionAsync = () =>
Promise.resolve({
succeeded: true,
message: 'test message',
type: 'test type',
});
const fullFieldValidation: FullFieldValidation = {
validator,
customArgs: { arg: 1 },
message: 'updated message',
};
const fieldValidationSchema: FieldValidationSchema = {
fieldId: [fullFieldValidation],
};
// Act
const result = mapToInternalFieldValidationSchema(fieldValidationSchema);
// Assert
const expectedResult: InternalFieldValidationSchema = {
fieldId: [
{
validator: expect.any(Function),
customArgs: { arg: 1 },
message: 'updated message',
},
],
};
expect(result).toEqual(expectedResult);
result['fieldId'][0].validator(null).then(validationResult => {
expect(validationResult).toEqual({
succeeded: true,
message: 'test message',
type: 'test type',
});
done();
});
});
it('spec #14: should return InternalFieldValidationSchema when it feeds fieldValidationSchema with two FullFieldValidation and async validator', done => {
// Arrange
const validator1: FieldValidationFunctionAsync = () =>
Promise.resolve({
succeeded: true,
message: 'test message 1',
type: 'test type 1',
});
const fullFieldValidation1: FullFieldValidation = {
validator: validator1,
customArgs: { arg: 1 },
message: 'updated message 1',
};
const validator2: FieldValidationFunctionAsync = () =>
Promise.resolve({
succeeded: false,
message: 'test message 2',
type: 'test type 2',
});
const fullFieldValidation2: FullFieldValidation = {
validator: validator2,
customArgs: { arg: 2 },
message: 'updated message 2',
};
const fieldValidationSchema: FieldValidationSchema = {
fieldId: [fullFieldValidation1, fullFieldValidation2],
};
// Act
const result = mapToInternalFieldValidationSchema(fieldValidationSchema);
// Assert
const expectedResult: InternalFieldValidationSchema = {
fieldId: [
{
validator: expect.any(Function),
customArgs: { arg: 1 },
message: 'updated message 1',
},
{
validator: expect.any(Function),
customArgs: { arg: 2 },
message: 'updated message 2',
},
],
};
expect(result).toEqual(expectedResult);
Promise.all([
result['fieldId'][0].validator(null),
result['fieldId'][1].validator(null),
]).then(validationResults => {
expect(validationResults[0]).toEqual({
succeeded: true,
message: 'test message 1',
type: 'test type 1',
});
expect(validationResults[1]).toEqual({
succeeded: false,
message: 'test message 2',
type: 'test type 2',
});
done();
});
});
it('spec #15: should return InternalFieldValidationSchema when it feeds fieldValidationSchema with two fields with one FullFieldValidation and async validator', done => {
// Arrange
const validator1: FieldValidationFunctionAsync = () =>
Promise.resolve({
succeeded: true,
message: 'test message 1',
type: 'test type 1',
});
const fullFieldValidation1: FullFieldValidation = {
validator: validator1,
customArgs: { arg: 1 },
message: 'updated message 1',
};
const validator2: FieldValidationFunctionAsync = () =>
Promise.resolve({
succeeded: false,
message: 'test message 2',
type: 'test type 2',
});
const fullFieldValidation2: FullFieldValidation = {
validator: validator2,
customArgs: { arg: 2 },
message: 'updated message 2',
};
const fieldValidationSchema: FieldValidationSchema = {
fieldId1: [fullFieldValidation1],
fieldId2: [fullFieldValidation2],
};
// Act
const result = mapToInternalFieldValidationSchema(fieldValidationSchema);
// Assert
const expectedResult: InternalFieldValidationSchema = {
fieldId1: [
{
validator: expect.any(Function),
customArgs: { arg: 1 },
message: 'updated message 1',
},
],
fieldId2: [
{
validator: expect.any(Function),
customArgs: { arg: 2 },
message: 'updated message 2',
},
],
};
expect(result).toEqual(expectedResult);
Promise.all([
result['fieldId1'][0].validator(null),
result['fieldId2'][0].validator(null),
]).then(validationResults => {
expect(validationResults[0]).toEqual({
succeeded: true,
message: 'test message 1',
type: 'test type 1',
});
expect(validationResults[1]).toEqual({
succeeded: false,
message: 'test message 2',
type: 'test type 2',
});
done();
});
});
it('spec #16: should return InternalFieldValidationSchema when it feeds fieldValidationSchema with two fields with one FullFieldValidation and the another one with validator object', done => {
// Arrange
const validator1: FieldValidationFunctionAsync = () =>
Promise.resolve({
succeeded: true,
message: 'test message 1',
type: 'test type 1',
});
const fullFieldValidation1: FullFieldValidation = {
validator: validator1,
customArgs: { arg: 1 },
message: 'updated message 1',
};
const validator2 = {
validator: () =>
Promise.resolve({
succeeded: false,
message: 'test message 2',
type: 'test type 2',
}),
};
const fullFieldValidation2: FullFieldValidation = {
validator: validator2,
customArgs: { arg: 2 },
message: 'updated message 2',
};
const fieldValidationSchema: FieldValidationSchema = {
fieldId1: [fullFieldValidation1],
fieldId2: [fullFieldValidation2],
};
// Act
const result = mapToInternalFieldValidationSchema(fieldValidationSchema);
// Assert
const expectedResult: InternalFieldValidationSchema = {
fieldId1: [
{
validator: expect.any(Function),
customArgs: { arg: 1 },
message: 'updated message 1',
},
],
fieldId2: [
{
validator: expect.any(Function),
customArgs: { arg: 2 },
message: 'updated message 2',
},
],
};
expect(result).toEqual(expectedResult);
Promise.all([
result['fieldId1'][0].validator(null),
result['fieldId2'][0].validator(null),
]).then(validationResults => {
expect(validationResults[0]).toEqual({
succeeded: true,
message: 'test message 1',
type: 'test type 1',
});
expect(validationResults[1]).toEqual({
succeeded: false,
message: 'test message 2',
type: 'test type 2',
});
done();
});
});
}); | the_stack |
namespace ts {
export function transformSystemModule(context: TransformationContext) {
interface DependencyGroup {
name: StringLiteral;
externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[];
}
const {
startLexicalEnvironment,
endLexicalEnvironment,
hoistVariableDeclaration
} = context;
const compilerOptions = context.getCompilerOptions();
const resolver = context.getEmitResolver();
const host = context.getEmitHost();
const previousOnSubstituteNode = context.onSubstituteNode;
const previousOnEmitNode = context.onEmitNode;
context.onSubstituteNode = onSubstituteNode;
context.onEmitNode = onEmitNode;
context.enableSubstitution(SyntaxKind.Identifier); // Substitutes expression identifiers for imported symbols.
context.enableSubstitution(SyntaxKind.BinaryExpression); // Substitutes assignments to exported symbols.
context.enableSubstitution(SyntaxKind.PrefixUnaryExpression); // Substitutes updates to exported symbols.
context.enableSubstitution(SyntaxKind.PostfixUnaryExpression); // Substitutes updates to exported symbols.
context.enableEmitNotification(SyntaxKind.SourceFile); // Restore state when substituting nodes in a file.
const moduleInfoMap: ExternalModuleInfo[] = []; // The ExternalModuleInfo for each file.
const deferredExports: Statement[][] = []; // Exports to defer until an EndOfDeclarationMarker is found.
const exportFunctionsMap: Identifier[] = []; // The export function associated with a source file.
const noSubstitutionMap: boolean[][] = []; // Set of nodes for which substitution rules should be ignored for each file.
let currentSourceFile: SourceFile; // The current file.
let moduleInfo: ExternalModuleInfo; // ExternalModuleInfo for the current file.
let exportFunction: Identifier; // The export function for the current file.
let contextObject: Identifier; // The context object for the current file.
let hoistedStatements: Statement[];
let enclosingBlockScopedContainer: Node;
let noSubstitution: boolean[]; // Set of nodes for which substitution rules should be ignored.
return transformSourceFile;
/**
* Transforms the module aspects of a SourceFile.
*
* @param node The SourceFile node.
*/
function transformSourceFile(node: SourceFile) {
if (isDeclarationFile(node)
|| !(isExternalModule(node)
|| compilerOptions.isolatedModules)) {
return node;
}
const id = getOriginalNodeId(node);
currentSourceFile = node;
enclosingBlockScopedContainer = node;
// System modules have the following shape:
//
// System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */})
//
// The parameter 'exports' here is a callback '<T>(name: string, value: T) => T' that
// is used to publish exported values. 'exports' returns its 'value' argument so in
// most cases expressions that mutate exported values can be rewritten as:
//
// expr -> exports('name', expr)
//
// The only exception in this rule is postfix unary operators,
// see comment to 'substitutePostfixUnaryExpression' for more details
// Collect information about the external module and dependency groups.
moduleInfo = moduleInfoMap[id] = collectExternalModuleInfo(node, resolver, compilerOptions);
// Make sure that the name of the 'exports' function does not conflict with
// existing identifiers.
exportFunction = createUniqueName("exports");
exportFunctionsMap[id] = exportFunction;
contextObject = createUniqueName("context");
// Add the body of the module.
const dependencyGroups = collectDependencyGroups(moduleInfo.externalImports);
const moduleBodyBlock = createSystemModuleBody(node, dependencyGroups);
const moduleBodyFunction = createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
[
createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction),
createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject)
],
/*type*/ undefined,
moduleBodyBlock
);
// Write the call to `System.register`
// Clear the emit-helpers flag for later passes since we'll have already used it in the module body
// So the helper will be emit at the correct position instead of at the top of the source-file
const moduleName = tryGetModuleNameFromFile(node, host, compilerOptions);
const dependencies = createArrayLiteral(map(dependencyGroups, dependencyGroup => dependencyGroup.name));
const updated = setEmitFlags(
updateSourceFileNode(
node,
setTextRange(
createNodeArray([
createStatement(
createCall(
createPropertyAccess(createIdentifier("System"), "register"),
/*typeArguments*/ undefined,
moduleName
? [moduleName, dependencies, moduleBodyFunction]
: [dependencies, moduleBodyFunction]
)
)
]),
node.statements
)
), EmitFlags.NoTrailingComments);
if (!(compilerOptions.outFile || compilerOptions.out)) {
moveEmitHelpers(updated, moduleBodyBlock, helper => !helper.scoped);
}
if (noSubstitution) {
noSubstitutionMap[id] = noSubstitution;
noSubstitution = undefined;
}
currentSourceFile = undefined;
moduleInfo = undefined;
exportFunction = undefined;
contextObject = undefined;
hoistedStatements = undefined;
enclosingBlockScopedContainer = undefined;
return aggregateTransformFlags(updated);
}
/**
* Collects the dependency groups for this files imports.
*
* @param externalImports The imports for the file.
*/
function collectDependencyGroups(externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[]) {
const groupIndices = createMap<number>();
const dependencyGroups: DependencyGroup[] = [];
for (let i = 0; i < externalImports.length; i++) {
const externalImport = externalImports[i];
const externalModuleName = getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions);
if (externalModuleName) {
const text = externalModuleName.text;
const groupIndex = groupIndices.get(text);
if (groupIndex !== undefined) {
// deduplicate/group entries in dependency list by the dependency name
dependencyGroups[groupIndex].externalImports.push(externalImport);
}
else {
groupIndices.set(text, dependencyGroups.length);
dependencyGroups.push({
name: externalModuleName,
externalImports: [externalImport]
});
}
}
}
return dependencyGroups;
}
/**
* Adds the statements for the module body function for the source file.
*
* @param node The source file for the module.
* @param dependencyGroups The grouped dependencies of the module.
*/
function createSystemModuleBody(node: SourceFile, dependencyGroups: DependencyGroup[]) {
// Shape of the body in system modules:
//
// function (exports) {
// <list of local aliases for imports>
// <hoisted variable declarations>
// <hoisted function declarations>
// return {
// setters: [
// <list of setter function for imports>
// ],
// execute: function() {
// <module statements>
// }
// }
// <temp declarations>
// }
//
// i.e:
//
// import {x} from 'file1'
// var y = 1;
// export function foo() { return y + x(); }
// console.log(y);
//
// Will be transformed to:
//
// function(exports) {
// function foo() { return y + file_1.x(); }
// exports("foo", foo);
// var file_1, y;
// return {
// setters: [
// function(v) { file_1 = v }
// ],
// execute(): function() {
// y = 1;
// console.log(y);
// }
// };
// }
const statements: Statement[] = [];
// We start a new lexical environment in this function body, but *not* in the
// body of the execute function. This allows us to emit temporary declarations
// only in the outer module body and not in the inner one.
startLexicalEnvironment();
// Add any prologue directives.
const ensureUseStrict = compilerOptions.alwaysStrict || (!compilerOptions.noImplicitUseStrict && isExternalModule(currentSourceFile));
const statementOffset = addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor);
// var __moduleName = context_1 && context_1.id;
statements.push(
createVariableStatement(
/*modifiers*/ undefined,
createVariableDeclarationList([
createVariableDeclaration(
"__moduleName",
/*type*/ undefined,
createLogicalAnd(
contextObject,
createPropertyAccess(contextObject, "id")
)
)
])
)
);
// Visit the synthetic external helpers import declaration if present
visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, isStatement);
// Visit the statements of the source file, emitting any transformations into
// the `executeStatements` array. We do this *before* we fill the `setters` array
// as we both emit transformations as well as aggregate some data used when creating
// setters. This allows us to reduce the number of times we need to loop through the
// statements of the source file.
const executeStatements = visitNodes(node.statements, sourceElementVisitor, isStatement, statementOffset);
// Emit early exports for function declarations.
addRange(statements, hoistedStatements);
// We emit hoisted variables early to align roughly with our previous emit output.
// Two key differences in this approach are:
// - Temporary variables will appear at the top rather than at the bottom of the file
addRange(statements, endLexicalEnvironment());
const exportStarFunction = addExportStarIfNeeded(statements);
const moduleObject = createObjectLiteral([
createPropertyAssignment("setters",
createSettersArray(exportStarFunction, dependencyGroups)
),
createPropertyAssignment("execute",
createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
/*parameters*/ [],
/*type*/ undefined,
createBlock(executeStatements, /*multiLine*/ true)
)
)
]);
moduleObject.multiLine = true;
statements.push(createReturn(moduleObject));
return createBlock(statements, /*multiLine*/ true);
}
/**
* Adds an exportStar function to a statement list if it is needed for the file.
*
* @param statements A statement list.
*/
function addExportStarIfNeeded(statements: Statement[]) {
if (!moduleInfo.hasExportStarsToExportValues) {
return;
}
// when resolving exports local exported entries/indirect exported entries in the module
// should always win over entries with similar names that were added via star exports
// to support this we store names of local/indirect exported entries in a set.
// this set is used to filter names brought by star expors.
// local names set should only be added if we have anything exported
if (!moduleInfo.exportedNames && moduleInfo.exportSpecifiers.size === 0) {
// no exported declarations (export var ...) or export specifiers (export {x})
// check if we have any non star export declarations.
let hasExportDeclarationWithExportClause = false;
for (const externalImport of moduleInfo.externalImports) {
if (externalImport.kind === SyntaxKind.ExportDeclaration && externalImport.exportClause) {
hasExportDeclarationWithExportClause = true;
break;
}
}
if (!hasExportDeclarationWithExportClause) {
// we still need to emit exportStar helper
const exportStarFunction = createExportStarFunction(/*localNames*/ undefined);
statements.push(exportStarFunction);
return exportStarFunction.name;
}
}
const exportedNames: ObjectLiteralElementLike[] = [];
if (moduleInfo.exportedNames) {
for (const exportedLocalName of moduleInfo.exportedNames) {
if (exportedLocalName.text === "default") {
continue;
}
// write name of exported declaration, i.e 'export var x...'
exportedNames.push(
createPropertyAssignment(
createLiteral(exportedLocalName),
createTrue()
)
);
}
}
for (const externalImport of moduleInfo.externalImports) {
if (externalImport.kind !== SyntaxKind.ExportDeclaration) {
continue;
}
const exportDecl = <ExportDeclaration>externalImport;
if (!exportDecl.exportClause) {
// export * from ...
continue;
}
for (const element of exportDecl.exportClause.elements) {
// write name of indirectly exported entry, i.e. 'export {x} from ...'
exportedNames.push(
createPropertyAssignment(
createLiteral((element.name || element.propertyName).text),
createTrue()
)
);
}
}
const exportedNamesStorageRef = createUniqueName("exportedNames");
statements.push(
createVariableStatement(
/*modifiers*/ undefined,
createVariableDeclarationList([
createVariableDeclaration(
exportedNamesStorageRef,
/*type*/ undefined,
createObjectLiteral(exportedNames, /*multiline*/ true)
)
])
)
);
const exportStarFunction = createExportStarFunction(exportedNamesStorageRef);
statements.push(exportStarFunction);
return exportStarFunction.name;
}
/**
* Creates an exportStar function for the file, with an optional set of excluded local
* names.
*
* @param localNames An optional reference to an object containing a set of excluded local
* names.
*/
function createExportStarFunction(localNames: Identifier | undefined) {
const exportStarFunction = createUniqueName("exportStar");
const m = createIdentifier("m");
const n = createIdentifier("n");
const exports = createIdentifier("exports");
let condition: Expression = createStrictInequality(n, createLiteral("default"));
if (localNames) {
condition = createLogicalAnd(
condition,
createLogicalNot(
createCall(
createPropertyAccess(localNames, "hasOwnProperty"),
/*typeArguments*/ undefined,
[n]
)
)
);
}
return createFunctionDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
exportStarFunction,
/*typeParameters*/ undefined,
[createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)],
/*type*/ undefined,
createBlock([
createVariableStatement(
/*modifiers*/ undefined,
createVariableDeclarationList([
createVariableDeclaration(
exports,
/*type*/ undefined,
createObjectLiteral([])
)
])
),
createForIn(
createVariableDeclarationList([
createVariableDeclaration(n, /*type*/ undefined)
]),
m,
createBlock([
setEmitFlags(
createIf(
condition,
createStatement(
createAssignment(
createElementAccess(exports, n),
createElementAccess(m, n)
)
)
),
EmitFlags.SingleLine
)
])
),
createStatement(
createCall(
exportFunction,
/*typeArguments*/ undefined,
[exports]
)
)
], /*multiline*/ true)
);
}
/**
* Creates an array setter callbacks for each dependency group.
*
* @param exportStarFunction A reference to an exportStarFunction for the file.
* @param dependencyGroups An array of grouped dependencies.
*/
function createSettersArray(exportStarFunction: Identifier, dependencyGroups: DependencyGroup[]) {
const setters: Expression[] = [];
for (const group of dependencyGroups) {
// derive a unique name for parameter from the first named entry in the group
const localName = forEach(group.externalImports, i => getLocalNameForExternalImport(i, currentSourceFile));
const parameterName = localName ? getGeneratedNameForNode(localName) : createUniqueName("");
const statements: Statement[] = [];
for (const entry of group.externalImports) {
const importVariableName = getLocalNameForExternalImport(entry, currentSourceFile);
switch (entry.kind) {
case SyntaxKind.ImportDeclaration:
if (!(<ImportDeclaration>entry).importClause) {
// 'import "..."' case
// module is imported only for side-effects, no emit required
break;
}
// falls through
case SyntaxKind.ImportEqualsDeclaration:
Debug.assert(importVariableName !== undefined);
// save import into the local
statements.push(
createStatement(
createAssignment(importVariableName, parameterName)
)
);
break;
case SyntaxKind.ExportDeclaration:
Debug.assert(importVariableName !== undefined);
if ((<ExportDeclaration>entry).exportClause) {
// export {a, b as c} from 'foo'
//
// emit as:
//
// exports_({
// "a": _["a"],
// "c": _["b"]
// });
const properties: PropertyAssignment[] = [];
for (const e of (<ExportDeclaration>entry).exportClause.elements) {
properties.push(
createPropertyAssignment(
createLiteral(e.name.text),
createElementAccess(
parameterName,
createLiteral((e.propertyName || e.name).text)
)
)
);
}
statements.push(
createStatement(
createCall(
exportFunction,
/*typeArguments*/ undefined,
[createObjectLiteral(properties, /*multiline*/ true)]
)
)
);
}
else {
// export * from 'foo'
//
// emit as:
//
// exportStar(foo_1_1);
statements.push(
createStatement(
createCall(
exportStarFunction,
/*typeArguments*/ undefined,
[parameterName]
)
)
);
}
break;
}
}
setters.push(
createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
[createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)],
/*type*/ undefined,
createBlock(statements, /*multiLine*/ true)
)
);
}
return createArrayLiteral(setters, /*multiLine*/ true);
}
//
// Top-level Source Element Visitors
//
/**
* Visit source elements at the top-level of a module.
*
* @param node The node to visit.
*/
function sourceElementVisitor(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.ImportDeclaration:
return visitImportDeclaration(<ImportDeclaration>node);
case SyntaxKind.ImportEqualsDeclaration:
return visitImportEqualsDeclaration(<ImportEqualsDeclaration>node);
case SyntaxKind.ExportDeclaration:
// ExportDeclarations are elided as they are handled via
// `appendExportsOfDeclaration`.
return undefined;
case SyntaxKind.ExportAssignment:
return visitExportAssignment(<ExportAssignment>node);
default:
return nestedElementVisitor(node);
}
}
/**
* Visits an ImportDeclaration node.
*
* @param node The node to visit.
*/
function visitImportDeclaration(node: ImportDeclaration): VisitResult<Statement> {
let statements: Statement[];
if (node.importClause) {
hoistVariableDeclaration(getLocalNameForExternalImport(node, currentSourceFile));
}
if (hasAssociatedEndOfDeclarationMarker(node)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
const id = getOriginalNodeId(node);
deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
}
else {
statements = appendExportsOfImportDeclaration(statements, node);
}
return singleOrMany(statements);
}
/**
* Visits an ImportEqualsDeclaration node.
*
* @param node The node to visit.
*/
function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): VisitResult<Statement> {
Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
let statements: Statement[];
hoistVariableDeclaration(getLocalNameForExternalImport(node, currentSourceFile));
if (hasAssociatedEndOfDeclarationMarker(node)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
const id = getOriginalNodeId(node);
deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
}
else {
statements = appendExportsOfImportEqualsDeclaration(statements, node);
}
return singleOrMany(statements);
}
/**
* Visits an ExportAssignment node.
*
* @param node The node to visit.
*/
function visitExportAssignment(node: ExportAssignment): VisitResult<Statement> {
if (node.isExportEquals) {
// Elide `export=` as it is illegal in a SystemJS module.
return undefined;
}
const expression = visitNode(node.expression, destructuringVisitor, isExpression);
const original = node.original;
if (original && hasAssociatedEndOfDeclarationMarker(original)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
const id = getOriginalNodeId(node);
deferredExports[id] = appendExportStatement(deferredExports[id], createIdentifier("default"), expression, /*allowComments*/ true);
}
else {
return createExportStatement(createIdentifier("default"), expression, /*allowComments*/ true);
}
}
/**
* Visits a FunctionDeclaration, hoisting it to the outer module body function.
*
* @param node The node to visit.
*/
function visitFunctionDeclaration(node: FunctionDeclaration): VisitResult<Statement> {
if (hasModifier(node, ModifierFlags.Export)) {
hoistedStatements = append(hoistedStatements,
updateFunctionDeclaration(
node,
node.decorators,
visitNodes(node.modifiers, modifierVisitor, isModifier),
node.asteriskToken,
getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
/*typeParameters*/ undefined,
visitNodes(node.parameters, destructuringVisitor, isParameterDeclaration),
/*type*/ undefined,
visitNode(node.body, destructuringVisitor, isBlock)));
}
else {
hoistedStatements = append(hoistedStatements, node);
}
if (hasAssociatedEndOfDeclarationMarker(node)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
const id = getOriginalNodeId(node);
deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
}
else {
hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node);
}
return undefined;
}
/**
* Visits a ClassDeclaration, hoisting its name to the outer module body function.
*
* @param node The node to visit.
*/
function visitClassDeclaration(node: ClassDeclaration): VisitResult<Statement> {
let statements: Statement[];
// Hoist the name of the class declaration to the outer module body function.
const name = getLocalName(node);
hoistVariableDeclaration(name);
// Rewrite the class declaration into an assignment of a class expression.
statements = append(statements,
setTextRange(
createStatement(
createAssignment(
name,
setTextRange(
createClassExpression(
/*modifiers*/ undefined,
node.name,
/*typeParameters*/ undefined,
visitNodes(node.heritageClauses, destructuringVisitor, isHeritageClause),
visitNodes(node.members, destructuringVisitor, isClassElement)
),
node
)
)
),
node
)
);
if (hasAssociatedEndOfDeclarationMarker(node)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
const id = getOriginalNodeId(node);
deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
}
else {
statements = appendExportsOfHoistedDeclaration(statements, node);
}
return singleOrMany(statements);
}
/**
* Visits a variable statement, hoisting declared names to the top-level module body.
* Each declaration is rewritten into an assignment expression.
*
* @param node The node to visit.
*/
function visitVariableStatement(node: VariableStatement): VisitResult<Statement> {
if (!shouldHoistVariableDeclarationList(node.declarationList)) {
return visitNode(node, destructuringVisitor, isStatement);
}
let expressions: Expression[];
const isExportedDeclaration = hasModifier(node, ModifierFlags.Export);
const isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node);
for (const variable of node.declarationList.declarations) {
if (variable.initializer) {
expressions = append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration));
}
else {
hoistBindingElement(variable);
}
}
let statements: Statement[];
if (expressions) {
statements = append(statements, setTextRange(createStatement(inlineExpressions(expressions)), node));
}
if (isMarkedDeclaration) {
// Defer exports until we encounter an EndOfDeclarationMarker node
const id = getOriginalNodeId(node);
deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration);
}
else {
statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false);
}
return singleOrMany(statements);
}
/**
* Hoists the declared names of a VariableDeclaration or BindingElement.
*
* @param node The declaration to hoist.
*/
function hoistBindingElement(node: VariableDeclaration | BindingElement): void {
if (isBindingPattern(node.name)) {
for (const element of node.name.elements) {
if (!isOmittedExpression(element)) {
hoistBindingElement(element);
}
}
}
else {
hoistVariableDeclaration(getSynthesizedClone(node.name));
}
}
/**
* Determines whether a VariableDeclarationList should be hoisted.
*
* @param node The node to test.
*/
function shouldHoistVariableDeclarationList(node: VariableDeclarationList) {
// hoist only non-block scoped declarations or block scoped declarations parented by source file
return (getEmitFlags(node) & EmitFlags.NoHoisting) === 0
&& (enclosingBlockScopedContainer.kind === SyntaxKind.SourceFile
|| (getOriginalNode(node).flags & NodeFlags.BlockScoped) === 0);
}
/**
* Transform an initialized variable declaration into an expression.
*
* @param node The node to transform.
* @param isExportedDeclaration A value indicating whether the variable is exported.
*/
function transformInitializedVariable(node: VariableDeclaration, isExportedDeclaration: boolean): Expression {
const createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment;
return isBindingPattern(node.name)
? flattenDestructuringAssignment(
node,
destructuringVisitor,
context,
FlattenLevel.All,
/*needsValue*/ false,
createAssignment
)
: createAssignment(node.name, visitNode(node.initializer, destructuringVisitor, isExpression));
}
/**
* Creates an assignment expression for an exported variable declaration.
*
* @param name The name of the variable.
* @param value The value of the variable's initializer.
* @param location The source map location for the assignment.
*/
function createExportedVariableAssignment(name: Identifier, value: Expression, location?: TextRange) {
return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ true);
}
/**
* Creates an assignment expression for a non-exported variable declaration.
*
* @param name The name of the variable.
* @param value The value of the variable's initializer.
* @param location The source map location for the assignment.
*/
function createNonExportedVariableAssignment(name: Identifier, value: Expression, location?: TextRange) {
return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ false);
}
/**
* Creates an assignment expression for a variable declaration.
*
* @param name The name of the variable.
* @param value The value of the variable's initializer.
* @param location The source map location for the assignment.
* @param isExportedDeclaration A value indicating whether the variable is exported.
*/
function createVariableAssignment(name: Identifier, value: Expression, location: TextRange, isExportedDeclaration: boolean) {
hoistVariableDeclaration(getSynthesizedClone(name));
return isExportedDeclaration
? createExportExpression(name, preventSubstitution(setTextRange(createAssignment(name, value), location)))
: preventSubstitution(setTextRange(createAssignment(name, value), location));
}
/**
* Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
* and transformed declaration.
*
* @param node The node to visit.
*/
function visitMergeDeclarationMarker(node: MergeDeclarationMarker): VisitResult<Statement> {
// For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
// declaration we do not emit a leading variable declaration. To preserve the
// begin/end semantics of the declararation and to properly handle exports
// we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
//
// To balance the declaration, we defer the exports of the elided variable
// statement until we visit this declaration's `EndOfDeclarationMarker`.
if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === SyntaxKind.VariableStatement) {
const id = getOriginalNodeId(node);
const isExportedDeclaration = hasModifier(node.original, ModifierFlags.Export);
deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], <VariableStatement>node.original, isExportedDeclaration);
}
return node;
}
/**
* Determines whether a node has an associated EndOfDeclarationMarker.
*
* @param node The node to test.
*/
function hasAssociatedEndOfDeclarationMarker(node: Node) {
return (getEmitFlags(node) & EmitFlags.HasEndOfDeclarationMarker) !== 0;
}
/**
* Visits a DeclarationMarker used as a placeholder for the end of a transformed
* declaration.
*
* @param node The node to visit.
*/
function visitEndOfDeclarationMarker(node: EndOfDeclarationMarker): VisitResult<Statement> {
// For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
// end of the transformed declaration. We use this marker to emit any deferred exports
// of the declaration.
const id = getOriginalNodeId(node);
const statements = deferredExports[id];
if (statements) {
delete deferredExports[id];
return append(statements, node);
}
return node;
}
/**
* Appends the exports of an ImportDeclaration to a statement list, returning the
* statement list.
*
* @param statements A statement list to which the down-level export statements are to be
* appended. If `statements` is `undefined`, a new array is allocated if statements are
* appended.
* @param decl The declaration whose exports are to be recorded.
*/
function appendExportsOfImportDeclaration(statements: Statement[], decl: ImportDeclaration) {
if (moduleInfo.exportEquals) {
return statements;
}
const importClause = decl.importClause;
if (!importClause) {
return statements;
}
if (importClause.name) {
statements = appendExportsOfDeclaration(statements, importClause);
}
const namedBindings = importClause.namedBindings;
if (namedBindings) {
switch (namedBindings.kind) {
case SyntaxKind.NamespaceImport:
statements = appendExportsOfDeclaration(statements, namedBindings);
break;
case SyntaxKind.NamedImports:
for (const importBinding of namedBindings.elements) {
statements = appendExportsOfDeclaration(statements, importBinding);
}
break;
}
}
return statements;
}
/**
* Appends the export of an ImportEqualsDeclaration to a statement list, returning the
* statement list.
*
* @param statements A statement list to which the down-level export statements are to be
* appended. If `statements` is `undefined`, a new array is allocated if statements are
* appended.
* @param decl The declaration whose exports are to be recorded.
*/
function appendExportsOfImportEqualsDeclaration(statements: Statement[], decl: ImportEqualsDeclaration): Statement[] | undefined {
if (moduleInfo.exportEquals) {
return statements;
}
return appendExportsOfDeclaration(statements, decl);
}
/**
* Appends the exports of a VariableStatement to a statement list, returning the statement
* list.
*
* @param statements A statement list to which the down-level export statements are to be
* appended. If `statements` is `undefined`, a new array is allocated if statements are
* appended.
* @param node The VariableStatement whose exports are to be recorded.
* @param exportSelf A value indicating whether to also export each VariableDeclaration of
* `nodes` declaration list.
*/
function appendExportsOfVariableStatement(statements: Statement[] | undefined, node: VariableStatement, exportSelf: boolean): Statement[] | undefined {
if (moduleInfo.exportEquals) {
return statements;
}
for (const decl of node.declarationList.declarations) {
if (decl.initializer || exportSelf) {
statements = appendExportsOfBindingElement(statements, decl, exportSelf);
}
}
return statements;
}
/**
* Appends the exports of a VariableDeclaration or BindingElement to a statement list,
* returning the statement list.
*
* @param statements A statement list to which the down-level export statements are to be
* appended. If `statements` is `undefined`, a new array is allocated if statements are
* appended.
* @param decl The declaration whose exports are to be recorded.
* @param exportSelf A value indicating whether to also export the declaration itself.
*/
function appendExportsOfBindingElement(statements: Statement[] | undefined, decl: VariableDeclaration | BindingElement, exportSelf: boolean): Statement[] | undefined {
if (moduleInfo.exportEquals) {
return statements;
}
if (isBindingPattern(decl.name)) {
for (const element of decl.name.elements) {
if (!isOmittedExpression(element)) {
statements = appendExportsOfBindingElement(statements, element, exportSelf);
}
}
}
else if (!isGeneratedIdentifier(decl.name)) {
let excludeName: string;
if (exportSelf) {
statements = appendExportStatement(statements, decl.name, getLocalName(decl));
excludeName = decl.name.text;
}
statements = appendExportsOfDeclaration(statements, decl, excludeName);
}
return statements;
}
/**
* Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
* returning the statement list.
*
* @param statements A statement list to which the down-level export statements are to be
* appended. If `statements` is `undefined`, a new array is allocated if statements are
* appended.
* @param decl The declaration whose exports are to be recorded.
*/
function appendExportsOfHoistedDeclaration(statements: Statement[] | undefined, decl: ClassDeclaration | FunctionDeclaration): Statement[] | undefined {
if (moduleInfo.exportEquals) {
return statements;
}
let excludeName: string;
if (hasModifier(decl, ModifierFlags.Export)) {
const exportName = hasModifier(decl, ModifierFlags.Default) ? createLiteral("default") : decl.name;
statements = appendExportStatement(statements, exportName, getLocalName(decl));
excludeName = exportName.text;
}
if (decl.name) {
statements = appendExportsOfDeclaration(statements, decl, excludeName);
}
return statements;
}
/**
* Appends the exports of a declaration to a statement list, returning the statement list.
*
* @param statements A statement list to which the down-level export statements are to be
* appended. If `statements` is `undefined`, a new array is allocated if statements are
* appended.
* @param decl The declaration to export.
* @param excludeName An optional name to exclude from exports.
*/
function appendExportsOfDeclaration(statements: Statement[] | undefined, decl: Declaration, excludeName?: string): Statement[] | undefined {
if (moduleInfo.exportEquals) {
return statements;
}
const name = getDeclarationName(decl);
const exportSpecifiers = moduleInfo.exportSpecifiers.get(name.text);
if (exportSpecifiers) {
for (const exportSpecifier of exportSpecifiers) {
if (exportSpecifier.name.text !== excludeName) {
statements = appendExportStatement(statements, exportSpecifier.name, name);
}
}
}
return statements;
}
/**
* Appends the down-level representation of an export to a statement list, returning the
* statement list.
*
* @param statements A statement list to which the down-level export statements are to be
* appended. If `statements` is `undefined`, a new array is allocated if statements are
* appended.
* @param exportName The name of the export.
* @param expression The expression to export.
* @param allowComments Whether to allow comments on the export.
*/
function appendExportStatement(statements: Statement[] | undefined, exportName: Identifier | StringLiteral, expression: Expression, allowComments?: boolean): Statement[] | undefined {
statements = append(statements, createExportStatement(exportName, expression, allowComments));
return statements;
}
/**
* Creates a call to the current file's export function to export a value.
*
* @param name The bound name of the export.
* @param value The exported value.
* @param allowComments An optional value indicating whether to emit comments for the statement.
*/
function createExportStatement(name: Identifier | StringLiteral, value: Expression, allowComments?: boolean) {
const statement = createStatement(createExportExpression(name, value));
startOnNewLine(statement);
if (!allowComments) {
setEmitFlags(statement, EmitFlags.NoComments);
}
return statement;
}
/**
* Creates a call to the current file's export function to export a value.
*
* @param name The bound name of the export.
* @param value The exported value.
*/
function createExportExpression(name: Identifier | StringLiteral, value: Expression) {
const exportName = isIdentifier(name) ? createLiteral(name) : name;
return createCall(exportFunction, /*typeArguments*/ undefined, [exportName, value]);
}
//
// Top-Level or Nested Source Element Visitors
//
/**
* Visit nested elements at the top-level of a module.
*
* @param node The node to visit.
*/
function nestedElementVisitor(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.VariableStatement:
return visitVariableStatement(<VariableStatement>node);
case SyntaxKind.FunctionDeclaration:
return visitFunctionDeclaration(<FunctionDeclaration>node);
case SyntaxKind.ClassDeclaration:
return visitClassDeclaration(<ClassDeclaration>node);
case SyntaxKind.ForStatement:
return visitForStatement(<ForStatement>node);
case SyntaxKind.ForInStatement:
return visitForInStatement(<ForInStatement>node);
case SyntaxKind.ForOfStatement:
return visitForOfStatement(<ForOfStatement>node);
case SyntaxKind.DoStatement:
return visitDoStatement(<DoStatement>node);
case SyntaxKind.WhileStatement:
return visitWhileStatement(<WhileStatement>node);
case SyntaxKind.LabeledStatement:
return visitLabeledStatement(<LabeledStatement>node);
case SyntaxKind.WithStatement:
return visitWithStatement(<WithStatement>node);
case SyntaxKind.SwitchStatement:
return visitSwitchStatement(<SwitchStatement>node);
case SyntaxKind.CaseBlock:
return visitCaseBlock(<CaseBlock>node);
case SyntaxKind.CaseClause:
return visitCaseClause(<CaseClause>node);
case SyntaxKind.DefaultClause:
return visitDefaultClause(<DefaultClause>node);
case SyntaxKind.TryStatement:
return visitTryStatement(<TryStatement>node);
case SyntaxKind.CatchClause:
return visitCatchClause(<CatchClause>node);
case SyntaxKind.Block:
return visitBlock(<Block>node);
case SyntaxKind.MergeDeclarationMarker:
return visitMergeDeclarationMarker(<MergeDeclarationMarker>node);
case SyntaxKind.EndOfDeclarationMarker:
return visitEndOfDeclarationMarker(<EndOfDeclarationMarker>node);
default:
return destructuringVisitor(node);
}
}
/**
* Visits the body of a ForStatement to hoist declarations.
*
* @param node The node to visit.
*/
function visitForStatement(node: ForStatement): VisitResult<Statement> {
const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
enclosingBlockScopedContainer = node;
node = updateFor(
node,
visitForInitializer(node.initializer),
visitNode(node.condition, destructuringVisitor, isExpression),
visitNode(node.incrementor, destructuringVisitor, isExpression),
visitNode(node.statement, nestedElementVisitor, isStatement)
);
enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
return node;
}
/**
* Visits the body of a ForInStatement to hoist declarations.
*
* @param node The node to visit.
*/
function visitForInStatement(node: ForInStatement): VisitResult<Statement> {
const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
enclosingBlockScopedContainer = node;
node = updateForIn(
node,
visitForInitializer(node.initializer),
visitNode(node.expression, destructuringVisitor, isExpression),
visitNode(node.statement, nestedElementVisitor, isStatement, liftToBlock)
);
enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
return node;
}
/**
* Visits the body of a ForOfStatement to hoist declarations.
*
* @param node The node to visit.
*/
function visitForOfStatement(node: ForOfStatement): VisitResult<Statement> {
const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
enclosingBlockScopedContainer = node;
node = updateForOf(
node,
node.awaitModifier,
visitForInitializer(node.initializer),
visitNode(node.expression, destructuringVisitor, isExpression),
visitNode(node.statement, nestedElementVisitor, isStatement, liftToBlock)
);
enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
return node;
}
/**
* Determines whether to hoist the initializer of a ForStatement, ForInStatement, or
* ForOfStatement.
*
* @param node The node to test.
*/
function shouldHoistForInitializer(node: ForInitializer): node is VariableDeclarationList {
return isVariableDeclarationList(node)
&& shouldHoistVariableDeclarationList(node);
}
/**
* Visits the initializer of a ForStatement, ForInStatement, or ForOfStatement
*
* @param node The node to visit.
*/
function visitForInitializer(node: ForInitializer): ForInitializer {
if (!node) {
return node;
}
if (shouldHoistForInitializer(node)) {
let expressions: Expression[];
for (const variable of node.declarations) {
expressions = append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false));
}
return expressions ? inlineExpressions(expressions) : createOmittedExpression();
}
else {
return visitEachChild(node, nestedElementVisitor, context);
}
}
/**
* Visits the body of a DoStatement to hoist declarations.
*
* @param node The node to visit.
*/
function visitDoStatement(node: DoStatement): VisitResult<Statement> {
return updateDo(
node,
visitNode(node.statement, nestedElementVisitor, isStatement, liftToBlock),
visitNode(node.expression, destructuringVisitor, isExpression)
);
}
/**
* Visits the body of a WhileStatement to hoist declarations.
*
* @param node The node to visit.
*/
function visitWhileStatement(node: WhileStatement): VisitResult<Statement> {
return updateWhile(
node,
visitNode(node.expression, destructuringVisitor, isExpression),
visitNode(node.statement, nestedElementVisitor, isStatement, liftToBlock)
);
}
/**
* Visits the body of a LabeledStatement to hoist declarations.
*
* @param node The node to visit.
*/
function visitLabeledStatement(node: LabeledStatement): VisitResult<Statement> {
return updateLabel(
node,
node.label,
visitNode(node.statement, nestedElementVisitor, isStatement, liftToBlock)
);
}
/**
* Visits the body of a WithStatement to hoist declarations.
*
* @param node The node to visit.
*/
function visitWithStatement(node: WithStatement): VisitResult<Statement> {
return updateWith(
node,
visitNode(node.expression, destructuringVisitor, isExpression),
visitNode(node.statement, nestedElementVisitor, isStatement, liftToBlock)
);
}
/**
* Visits the body of a SwitchStatement to hoist declarations.
*
* @param node The node to visit.
*/
function visitSwitchStatement(node: SwitchStatement): VisitResult<Statement> {
return updateSwitch(
node,
visitNode(node.expression, destructuringVisitor, isExpression),
visitNode(node.caseBlock, nestedElementVisitor, isCaseBlock)
);
}
/**
* Visits the body of a CaseBlock to hoist declarations.
*
* @param node The node to visit.
*/
function visitCaseBlock(node: CaseBlock): CaseBlock {
const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
enclosingBlockScopedContainer = node;
node = updateCaseBlock(
node,
visitNodes(node.clauses, nestedElementVisitor, isCaseOrDefaultClause)
);
enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
return node;
}
/**
* Visits the body of a CaseClause to hoist declarations.
*
* @param node The node to visit.
*/
function visitCaseClause(node: CaseClause): VisitResult<CaseOrDefaultClause> {
return updateCaseClause(
node,
visitNode(node.expression, destructuringVisitor, isExpression),
visitNodes(node.statements, nestedElementVisitor, isStatement)
);
}
/**
* Visits the body of a DefaultClause to hoist declarations.
*
* @param node The node to visit.
*/
function visitDefaultClause(node: DefaultClause): VisitResult<CaseOrDefaultClause> {
return visitEachChild(node, nestedElementVisitor, context);
}
/**
* Visits the body of a TryStatement to hoist declarations.
*
* @param node The node to visit.
*/
function visitTryStatement(node: TryStatement): VisitResult<Statement> {
return visitEachChild(node, nestedElementVisitor, context);
}
/**
* Visits the body of a CatchClause to hoist declarations.
*
* @param node The node to visit.
*/
function visitCatchClause(node: CatchClause): CatchClause {
const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
enclosingBlockScopedContainer = node;
node = updateCatchClause(
node,
node.variableDeclaration,
visitNode(node.block, nestedElementVisitor, isBlock)
);
enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
return node;
}
/**
* Visits the body of a Block to hoist declarations.
*
* @param node The node to visit.
*/
function visitBlock(node: Block): Block {
const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
enclosingBlockScopedContainer = node;
node = visitEachChild(node, nestedElementVisitor, context);
enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
return node;
}
//
// Destructuring Assignment Visitors
//
/**
* Visit nodes to flatten destructuring assignments to exported symbols.
*
* @param node The node to visit.
*/
function destructuringVisitor(node: Node): VisitResult<Node> {
if (node.transformFlags & TransformFlags.DestructuringAssignment
&& node.kind === SyntaxKind.BinaryExpression) {
return visitDestructuringAssignment(<DestructuringAssignment>node);
}
else if (node.transformFlags & TransformFlags.ContainsDestructuringAssignment) {
return visitEachChild(node, destructuringVisitor, context);
}
else {
return node;
}
}
/**
* Visits a DestructuringAssignment to flatten destructuring to exported symbols.
*
* @param node The node to visit.
*/
function visitDestructuringAssignment(node: DestructuringAssignment): VisitResult<Expression> {
if (hasExportedReferenceInDestructuringTarget(node.left)) {
return flattenDestructuringAssignment(
node,
destructuringVisitor,
context,
FlattenLevel.All,
/*needsValue*/ true
);
}
return visitEachChild(node, destructuringVisitor, context);
}
/**
* Determines whether the target of a destructuring assigment refers to an exported symbol.
*
* @param node The destructuring target.
*/
function hasExportedReferenceInDestructuringTarget(node: Expression | ObjectLiteralElementLike): boolean {
if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
return hasExportedReferenceInDestructuringTarget(node.left);
}
else if (isSpreadExpression(node)) {
return hasExportedReferenceInDestructuringTarget(node.expression);
}
else if (isObjectLiteralExpression(node)) {
return some(node.properties, hasExportedReferenceInDestructuringTarget);
}
else if (isArrayLiteralExpression(node)) {
return some(node.elements, hasExportedReferenceInDestructuringTarget);
}
else if (isShorthandPropertyAssignment(node)) {
return hasExportedReferenceInDestructuringTarget(node.name);
}
else if (isPropertyAssignment(node)) {
return hasExportedReferenceInDestructuringTarget(node.initializer);
}
else if (isIdentifier(node)) {
const container = resolver.getReferencedExportContainer(node);
return container !== undefined && container.kind === SyntaxKind.SourceFile;
}
else {
return false;
}
}
//
// Modifier Visitors
//
/**
* Visit nodes to elide module-specific modifiers.
*
* @param node The node to visit.
*/
function modifierVisitor(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.ExportKeyword:
case SyntaxKind.DefaultKeyword:
return undefined;
}
return node;
}
//
// Emit Notification
//
/**
* Hook for node emit notifications.
*
* @param hint A hint as to the intended usage of the node.
* @param node The node to emit.
* @param emitCallback A callback used to emit the node in the printer.
*/
function onEmitNode(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void {
if (node.kind === SyntaxKind.SourceFile) {
const id = getOriginalNodeId(node);
currentSourceFile = <SourceFile>node;
moduleInfo = moduleInfoMap[id];
exportFunction = exportFunctionsMap[id];
noSubstitution = noSubstitutionMap[id];
if (noSubstitution) {
delete noSubstitutionMap[id];
}
previousOnEmitNode(hint, node, emitCallback);
currentSourceFile = undefined;
moduleInfo = undefined;
exportFunction = undefined;
noSubstitution = undefined;
}
else {
previousOnEmitNode(hint, node, emitCallback);
}
}
//
// Substitutions
//
/**
* Hooks node substitutions.
*
* @param hint A hint as to the intended usage of the node.
* @param node The node to substitute.
*/
function onSubstituteNode(hint: EmitHint, node: Node) {
node = previousOnSubstituteNode(hint, node);
if (isSubstitutionPrevented(node)) {
return node;
}
if (hint === EmitHint.Expression) {
return substituteExpression(<Expression>node);
}
return node;
}
/**
* Substitute the expression, if necessary.
*
* @param node The node to substitute.
*/
function substituteExpression(node: Expression) {
switch (node.kind) {
case SyntaxKind.Identifier:
return substituteExpressionIdentifier(<Identifier>node);
case SyntaxKind.BinaryExpression:
return substituteBinaryExpression(<BinaryExpression>node);
case SyntaxKind.PrefixUnaryExpression:
case SyntaxKind.PostfixUnaryExpression:
return substituteUnaryExpression(<PrefixUnaryExpression | PostfixUnaryExpression>node);
}
return node;
}
/**
* Substitution for an Identifier expression that may contain an imported or exported symbol.
*
* @param node The node to substitute.
*/
function substituteExpressionIdentifier(node: Identifier): Expression {
if (getEmitFlags(node) & EmitFlags.HelperName) {
const externalHelpersModuleName = getExternalHelpersModuleName(currentSourceFile);
if (externalHelpersModuleName) {
return createPropertyAccess(externalHelpersModuleName, node);
}
return node;
}
// When we see an identifier in an expression position that
// points to an imported symbol, we should substitute a qualified
// reference to the imported symbol if one is needed.
//
// - We do not substitute generated identifiers for any reason.
// - We do not substitute identifiers tagged with the LocalName flag.
if (!isGeneratedIdentifier(node) && !isLocalName(node)) {
const importDeclaration = resolver.getReferencedImportDeclaration(node);
if (importDeclaration) {
if (isImportClause(importDeclaration)) {
return setTextRange(
createPropertyAccess(
getGeneratedNameForNode(importDeclaration.parent),
createIdentifier("default")
),
/*location*/ node
);
}
else if (isImportSpecifier(importDeclaration)) {
return setTextRange(
createPropertyAccess(
getGeneratedNameForNode(importDeclaration.parent.parent.parent),
getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name)
),
/*location*/ node
);
}
}
}
return node;
}
/**
* Substitution for a BinaryExpression that may contain an imported or exported symbol.
*
* @param node The node to substitute.
*/
function substituteBinaryExpression(node: BinaryExpression): Expression {
// When we see an assignment expression whose left-hand side is an exported symbol,
// we should ensure all exports of that symbol are updated with the correct value.
//
// - We do not substitute generated identifiers for any reason.
// - We do not substitute identifiers tagged with the LocalName flag.
// - We do not substitute identifiers that were originally the name of an enum or
// namespace due to how they are transformed in TypeScript.
// - We only substitute identifiers that are exported at the top level.
if (isAssignmentOperator(node.operatorToken.kind)
&& isIdentifier(node.left)
&& !isGeneratedIdentifier(node.left)
&& !isLocalName(node.left)
&& !isDeclarationNameOfEnumOrNamespace(node.left)) {
const exportedNames = getExports(node.left);
if (exportedNames) {
// For each additional export of the declaration, apply an export assignment.
let expression: Expression = node;
for (const exportName of exportedNames) {
expression = createExportExpression(exportName, preventSubstitution(expression));
}
return expression;
}
}
return node;
}
/**
* Substitution for a UnaryExpression that may contain an imported or exported symbol.
*
* @param node The node to substitute.
*/
function substituteUnaryExpression(node: PrefixUnaryExpression | PostfixUnaryExpression): Expression {
// When we see a prefix or postfix increment expression whose operand is an exported
// symbol, we should ensure all exports of that symbol are updated with the correct
// value.
//
// - We do not substitute generated identifiers for any reason.
// - We do not substitute identifiers tagged with the LocalName flag.
// - We do not substitute identifiers that were originally the name of an enum or
// namespace due to how they are transformed in TypeScript.
// - We only substitute identifiers that are exported at the top level.
if ((node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken)
&& isIdentifier(node.operand)
&& !isGeneratedIdentifier(node.operand)
&& !isLocalName(node.operand)
&& !isDeclarationNameOfEnumOrNamespace(node.operand)) {
const exportedNames = getExports(node.operand);
if (exportedNames) {
let expression: Expression = node.kind === SyntaxKind.PostfixUnaryExpression
? setTextRange(
createPrefix(
node.operator,
node.operand
),
node
)
: node;
for (const exportName of exportedNames) {
expression = createExportExpression(exportName, preventSubstitution(expression));
}
if (node.kind === SyntaxKind.PostfixUnaryExpression) {
expression = node.operator === SyntaxKind.PlusPlusToken
? createSubtract(preventSubstitution(expression), createLiteral(1))
: createAdd(preventSubstitution(expression), createLiteral(1));
}
return expression;
}
}
return node;
}
/**
* Gets the exports of a name.
*
* @param name The name.
*/
function getExports(name: Identifier) {
let exportedNames: Identifier[];
if (!isGeneratedIdentifier(name)) {
const valueDeclaration = resolver.getReferencedImportDeclaration(name)
|| resolver.getReferencedValueDeclaration(name);
if (valueDeclaration) {
const exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
if (exportContainer && exportContainer.kind === SyntaxKind.SourceFile) {
exportedNames = append(exportedNames, getDeclarationName(valueDeclaration));
}
exportedNames = addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)]);
}
}
return exportedNames;
}
/**
* Prevent substitution of a node for this transformer.
*
* @param node The node which should not be substituted.
*/
function preventSubstitution<T extends Node>(node: T): T {
if (noSubstitution === undefined) noSubstitution = [];
noSubstitution[getNodeId(node)] = true;
return node;
}
/**
* Determines whether a node should not be substituted.
*
* @param node The node to test.
*/
function isSubstitutionPrevented(node: Node) {
return noSubstitution && node.id && noSubstitution[node.id];
}
}
} | the_stack |
import { BigNumberish } from '@ethersproject/bignumber/lib/bignumber'
import { ethers } from 'ethers'
import { makeDebug } from './debug'
import { addCBORMapDelimiters, stripHexPrefix, toHex } from './helpers'
const debug = makeDebug('oracle')
/**
* Transaction options such as gasLimit, gasPrice, data, ...
*/
type TxOptions = Omit<ethers.providers.TransactionRequest, 'to' | 'from'>
/**
* A run request is an event emitted by `Oracle.sol` which triggers a job run
* on a receiving chainlink node watching for RunRequests coming from that
* specId + optionally requester.
*/
export interface RunRequest {
/**
* The ID of the job spec this request is targeting
*
* @solformat bytes32
*/
specId: string
/**
* The requester of the run
*
* @solformat address
*/
requester: string
/**
* The ID of the request, check Oracle.sol#oracleRequest to see how its computed
*
* @solformat bytes32
*/
requestId: string
/**
* The amount of LINK used for payment
*
* @solformat uint256
*/
payment: string
/**
* The address of the contract instance to callback with the fulfillment result
*
* @solformat address
*/
callbackAddr: string
/**
* The function selector of the method that the oracle should call after fulfillment
*
* @solformat bytes4
*/
callbackFunc: string
/**
* The expiration that the node should respond by before the requester can cancel
*
* @solformat uint256
*/
expiration: string
/**
* The specified data version
*
* @solformat uint256
*/
dataVersion: number
/**
* The CBOR encoded payload of the request
*
* @solformat bytes
*/
data: Buffer
/**
* The hash of the signature of the OracleRequest event.
* ```solidity
* event OracleRequest(
* bytes32 indexed specId,
* address requester,
* bytes32 requestId,
* uint256 payment,
* address callbackAddr,
* bytes4 callbackFunctionId,
* uint256 cancelExpiration,
* uint256 dataVersion,
* bytes data
* );
* ```
* Note: this is a property used for testing purposes only.
* It is not part of the actual run request.
*
* @solformat bytes32
*/
topic: string
}
/**
* Convert the javascript format of the parameters needed to call the
* ```solidity
* function fulfillOracleRequest(
* bytes32 _requestId,
* uint256 _payment,
* address _callbackAddress,
* bytes4 _callbackFunctionId,
* uint256 _expiration,
* bytes32 _data
* )
* ```
* method on an Oracle.sol contract.
*
* @param runRequest The run request to flatten into the correct order to perform the `fulfillOracleRequest` function
* @param response The response to fulfill the run request with, if it is an ascii string, it is converted to bytes32 string
* @param txOpts Additional ethereum tx options
*/
export function convertFufillParams(
runRequest: RunRequest,
response: string,
txOpts: TxOptions = {},
): [string, string, string, string, string, string, TxOptions] {
const d = debug.extend('fulfillOracleRequestParams')
d('Response param: %s', response)
const bytes32Len = 32 * 2 + 2
const convertedResponse =
response.length < bytes32Len
? ethers.utils.formatBytes32String(response)
: response
d('Converted Response param: %s', convertedResponse)
return [
runRequest.requestId,
runRequest.payment,
runRequest.callbackAddr,
runRequest.callbackFunc,
runRequest.expiration,
convertedResponse,
txOpts,
]
}
/**
* Convert the javascript format of the parameters needed to call the
* ```solidity
* function fulfillOracleRequest2(
* bytes32 _requestId,
* uint256 _payment,
* address _callbackAddress,
* bytes4 _callbackFunctionId,
* uint256 _expiration,
* bytes memory _data
* )
* ```
* method on an Oracle.sol contract.
*
* @param runRequest The run request to flatten into the correct order to perform the `fulfillOracleRequest` function
* @param response The response to fulfill the run request with, if it is an ascii string, it is converted to bytes32 string
* @param txOpts Additional ethereum tx options
*/
export function convertFulfill2Params(
runRequest: RunRequest,
responseTypes: string[],
responseValues: string[],
txOpts: TxOptions = {},
): [string, string, string, string, string, string, TxOptions] {
const d = debug.extend('fulfillOracleRequestParams')
d('Response param: %s', responseValues)
const types = [...responseTypes]
const values = [...responseValues]
types.unshift('bytes32')
values.unshift(runRequest.requestId)
const convertedResponse = ethers.utils.defaultAbiCoder.encode(types, values)
d('Encoded Response param: %s', convertedResponse)
return [
runRequest.requestId,
runRequest.payment,
runRequest.callbackAddr,
runRequest.callbackFunc,
runRequest.expiration,
convertedResponse,
txOpts,
]
}
/**
* Convert the javascript format of the parameters needed to call the
* ```solidity
* function cancelOracleRequest(
* bytes32 _requestId,
* uint256 _payment,
* bytes4 _callbackFunc,
* uint256 _expiration
* )
* ```
* method on an Oracle.sol contract.
*
* @param runRequest The run request to flatten into the correct order to perform the `cancelOracleRequest` function
* @param txOpts Additional ethereum tx options
*/
export function convertCancelParams(
runRequest: RunRequest,
txOpts: TxOptions = {},
): [string, string, string, string, TxOptions] {
return [
runRequest.requestId,
runRequest.payment,
runRequest.callbackFunc,
runRequest.expiration,
txOpts,
]
}
/**
* Convert the javascript format of the parameters needed to call the
* ```solidity
* function cancelOracleRequestByRequester(
* uint256 nonce,
* uint256 _payment,
* bytes4 _callbackFunc,
* uint256 _expiration
* )
* ```
* method on an Oracle.sol contract.
*
* @param nonce The nonce used to generate the request ID
* @param runRequest The run request to flatten into the correct order to perform the `cancelOracleRequest` function
* @param txOpts Additional ethereum tx options
*/
export function convertCancelByRequesterParams(
runRequest: RunRequest,
nonce: number,
txOpts: TxOptions = {},
): [number, string, string, string, TxOptions] {
return [
nonce,
runRequest.payment,
runRequest.callbackFunc,
runRequest.expiration,
txOpts,
]
}
/**
* Abi encode parameters to call the `oracleRequest` method on the Oracle.sol contract.
* ```solidity
* function oracleRequest(
* address _sender,
* uint256 _payment,
* bytes32 _specId,
* address _callbackAddress,
* bytes4 _callbackFunctionId,
* uint256 _nonce,
* uint256 _dataVersion,
* bytes _data
* )
* ```
*
* @param specId The Job Specification ID
* @param callbackAddr The callback contract address for the response
* @param callbackFunctionId The callback function id for the response
* @param nonce The nonce sent by the requester
* @param data The CBOR payload of the request
*/
export function encodeOracleRequest(
specId: string,
callbackAddr: string,
callbackFunctionId: string,
nonce: number,
data: BigNumberish,
dataVersion: BigNumberish = 1,
): string {
const oracleRequestSighash = '0x40429946'
return encodeRequest(
oracleRequestSighash,
specId,
callbackAddr,
callbackFunctionId,
nonce,
data,
dataVersion,
)
}
/**
* Abi encode parameters to call the `operatorRequest` method on the Operator.sol contract.
* ```solidity
* function operatorRequest(
* address _sender,
* uint256 _payment,
* bytes32 _specId,
* address _callbackAddress,
* bytes4 _callbackFunctionId,
* uint256 _nonce,
* uint256 _dataVersion,
* bytes _data
* )
* ```
*
* @param specId The Job Specification ID
* @param callbackAddr The callback contract address for the response
* @param callbackFunctionId The callback function id for the response
* @param nonce The nonce sent by the requester
* @param data The CBOR payload of the request
*/
export function encodeRequestOracleData(
specId: string,
callbackFunctionId: string,
nonce: number,
data: BigNumberish,
dataVersion: BigNumberish = 2,
): string {
const sendOperatorRequestSigHash = '0x3c6d41b9'
const requestInputs = [
{ name: '_sender', type: 'address' },
{ name: '_payment', type: 'uint256' },
{ name: '_specId', type: 'bytes32' },
{ name: '_callbackFunctionId', type: 'bytes4' },
{ name: '_nonce', type: 'uint256' },
{ name: '_dataVersion', type: 'uint256' },
{ name: '_data', type: 'bytes' },
]
const encodedParams = ethers.utils.defaultAbiCoder.encode(
requestInputs.map((i) => i.type),
[
ethers.constants.AddressZero,
0,
specId,
callbackFunctionId,
nonce,
dataVersion,
data,
],
)
return `${sendOperatorRequestSigHash}${stripHexPrefix(encodedParams)}`
}
function encodeRequest(
oracleRequestSighash: string,
specId: string,
callbackAddr: string,
callbackFunctionId: string,
nonce: number,
data: BigNumberish,
dataVersion: BigNumberish = 1,
): string {
const oracleRequestInputs = [
{ name: '_sender', type: 'address' },
{ name: '_payment', type: 'uint256' },
{ name: '_specId', type: 'bytes32' },
{ name: '_callbackAddress', type: 'address' },
{ name: '_callbackFunctionId', type: 'bytes4' },
{ name: '_nonce', type: 'uint256' },
{ name: '_dataVersion', type: 'uint256' },
{ name: '_data', type: 'bytes' },
]
const encodedParams = ethers.utils.defaultAbiCoder.encode(
oracleRequestInputs.map((i) => i.type),
[
ethers.constants.AddressZero,
0,
specId,
callbackAddr,
callbackFunctionId,
nonce,
dataVersion,
data,
],
)
return `${oracleRequestSighash}${stripHexPrefix(encodedParams)}`
}
/**
* Extract a javascript representation of a run request from the data
* contained within a EVM log.
* ```solidity
* event OracleRequest(
* bytes32 indexed specId,
* address requester,
* bytes32 requestId,
* uint256 payment,
* address callbackAddr,
* bytes4 callbackFunctionId,
* uint256 cancelExpiration,
* uint256 dataVersion,
* bytes data
* );
* ```
*
* @param log The log to extract the run request from
*/
export function decodeRunRequest(log?: ethers.providers.Log): RunRequest {
if (!log) {
throw Error('No logs found to decode')
}
const ORACLE_REQUEST_TYPES = [
'address',
'bytes32',
'uint256',
'address',
'bytes4',
'uint256',
'uint256',
'bytes',
]
const [
requester,
requestId,
payment,
callbackAddress,
callbackFunc,
expiration,
version,
data,
] = ethers.utils.defaultAbiCoder.decode(ORACLE_REQUEST_TYPES, log.data)
return {
specId: log.topics[1],
requester,
requestId: toHex(requestId),
payment: toHex(payment),
callbackAddr: callbackAddress,
callbackFunc: toHex(callbackFunc),
expiration: toHex(expiration),
data: addCBORMapDelimiters(Buffer.from(stripHexPrefix(data), 'hex')),
dataVersion: version.toNumber(),
topic: log.topics[0],
}
}
/**
* Extract a javascript representation of a ConcreteChainlinked#Request event
* from an EVM log.
* ```solidity
* event Request(
* bytes32 id,
* address callbackAddress,
* bytes4 callbackfunctionSelector,
* bytes data
* );
* ```
* The request event is emitted from the `ConcreteChainlinked.sol` testing contract.
*
* @param log The log to decode
*/
export function decodeCCRequest(
log: ethers.providers.Log,
): ethers.utils.Result {
const d = debug.extend('decodeRunABI')
d('params %o', log)
const REQUEST_TYPES = ['bytes32', 'address', 'bytes4', 'bytes']
const decodedValue = ethers.utils.defaultAbiCoder.decode(
REQUEST_TYPES,
log.data,
)
d('decoded value %o', decodedValue)
return decodedValue
} | the_stack |
import type {Proto, ObserverType} from "@swim/util";
import {FastenerOwner, FastenerInit, FastenerClass, Fastener} from "@swim/component";
import {AnyController, ControllerFactory, Controller} from "./Controller";
/** @internal */
export type ControllerRelationType<F extends ControllerRelation<any, any>> =
F extends ControllerRelation<any, infer C> ? C : never;
/** @public */
export interface ControllerRelationInit<C extends Controller = Controller> extends FastenerInit {
extends?: {prototype: ControllerRelation<any, any>} | string | boolean | null;
type?: ControllerFactory<C>;
binds?: boolean;
observes?: boolean;
initController?(controller: C): void;
willAttachController?(controller: C, target: Controller | null): void;
didAttachController?(controller: C, target: Controller | null): void;
deinitController?(controller: C): void;
willDetachController?(controller: C): void;
didDetachController?(controller: C): void;
parentController?: Controller | null;
insertChild?(parent: Controller, child: C, target: Controller | null, key: string | undefined): void;
detectController?(controller: Controller): C | null;
createController?(): C;
fromAny?(value: AnyController<C>): C;
}
/** @public */
export type ControllerRelationDescriptor<O = unknown, C extends Controller = Controller, I = {}> = ThisType<ControllerRelation<O, C> & I> & ControllerRelationInit<C> & Partial<I>;
/** @public */
export interface ControllerRelationClass<F extends ControllerRelation<any, any> = ControllerRelation<any, any>> extends FastenerClass<F> {
}
/** @public */
export interface ControllerRelationFactory<F extends ControllerRelation<any, any> = ControllerRelation<any, any>> extends ControllerRelationClass<F> {
extend<I = {}>(className: string, classMembers?: Partial<I> | null): ControllerRelationFactory<F> & I;
define<O, C extends Controller = Controller>(className: string, descriptor: ControllerRelationDescriptor<O, C>): ControllerRelationFactory<ControllerRelation<any, C>>;
define<O, C extends Controller = Controller>(className: string, descriptor: {observes: boolean} & ControllerRelationDescriptor<O, C, ObserverType<C>>): ControllerRelationFactory<ControllerRelation<any, C>>;
define<O, C extends Controller = Controller, I = {}>(className: string, descriptor: {implements: unknown} & ControllerRelationDescriptor<O, C, I>): ControllerRelationFactory<ControllerRelation<any, C> & I>;
define<O, C extends Controller = Controller, I = {}>(className: string, descriptor: {implements: unknown; observes: boolean} & ControllerRelationDescriptor<O, C, I & ObserverType<C>>): ControllerRelationFactory<ControllerRelation<any, C> & I>;
<O, C extends Controller = Controller>(descriptor: ControllerRelationDescriptor<O, C>): PropertyDecorator;
<O, C extends Controller = Controller>(descriptor: {observes: boolean} & ControllerRelationDescriptor<O, C, ObserverType<C>>): PropertyDecorator;
<O, C extends Controller = Controller, I = {}>(descriptor: {implements: unknown} & ControllerRelationDescriptor<O, C, I>): PropertyDecorator;
<O, C extends Controller = Controller, I = {}>(descriptor: {implements: unknown; observes: boolean} & ControllerRelationDescriptor<O, C, I & ObserverType<C>>): PropertyDecorator;
}
/** @public */
export interface ControllerRelation<O = unknown, C extends Controller = Controller> extends Fastener<O> {
/** @override */
get fastenerType(): Proto<ControllerRelation<any, any>>;
/** @protected */
initController(controller: C): void;
/** @protected */
willAttachController(controller: C, target: Controller | null): void;
/** @protected */
onAttachController(controller: C, target: Controller | null): void;
/** @protected */
didAttachController(controller: C, target: Controller | null): void;
/** @protected */
deinitController(controller: C): void;
/** @protected */
willDetachController(controller: C): void;
/** @protected */
onDetachController(controller: C): void;
/** @protected */
didDetachController(controller: C): void;
/** @internal @protected */
get parentController(): Controller | null;
/** @internal @protected */
insertChild(parent: Controller, child: C, target: Controller | null, key: string | undefined): void;
/** @internal */
bindController(controller: Controller, target: Controller | null): void;
/** @internal */
unbindController(controller: Controller): void;
detectController(controller: Controller): C | null;
createController(): C;
/** @internal @protected */
fromAny(value: AnyController<C>): C;
/** @internal @protected */
get type(): ControllerFactory<C> | undefined; // optional prototype property
/** @internal @protected */
get binds(): boolean | undefined; // optional prototype property
/** @internal @protected */
get observes(): boolean | undefined; // optional prototype property
/** @internal @override */
get lazy(): boolean; // prototype property
/** @internal @override */
get static(): string | boolean; // prototype property
}
/** @public */
export const ControllerRelation = (function (_super: typeof Fastener) {
const ControllerRelation: ControllerRelationFactory = _super.extend("ControllerRelation");
Object.defineProperty(ControllerRelation.prototype, "fastenerType", {
get: function (this: ControllerRelation): Proto<ControllerRelation<any, any>> {
return ControllerRelation;
},
configurable: true,
});
ControllerRelation.prototype.initController = function <C extends Controller>(this: ControllerRelation<unknown, C>, controller: C): void {
// hook
};
ControllerRelation.prototype.willAttachController = function <C extends Controller>(this: ControllerRelation<unknown, C>, controller: C, target: Controller | null): void {
// hook
};
ControllerRelation.prototype.onAttachController = function <C extends Controller>(this: ControllerRelation<unknown, C>, controller: C, target: Controller | null): void {
if (this.observes === true) {
controller.observe(this as ObserverType<C>);
}
};
ControllerRelation.prototype.didAttachController = function <C extends Controller>(this: ControllerRelation<unknown, C>, controller: C, target: Controller | null): void {
// hook
};
ControllerRelation.prototype.deinitController = function <C extends Controller>(this: ControllerRelation<unknown, C>, controller: C): void {
// hook
};
ControllerRelation.prototype.willDetachController = function <C extends Controller>(this: ControllerRelation<unknown, C>, controller: C): void {
// hook
};
ControllerRelation.prototype.onDetachController = function <C extends Controller>(this: ControllerRelation<unknown, C>, controller: C): void {
if (this.observes === true) {
controller.unobserve(this as ObserverType<C>);
}
};
ControllerRelation.prototype.didDetachController = function <C extends Controller>(this: ControllerRelation<unknown, C>, controller: C): void {
// hook
};
Object.defineProperty(ControllerRelation.prototype, "parentController", {
get(this: ControllerRelation): Controller | null {
const owner = this.owner;
return owner instanceof Controller ? owner : null;
},
configurable: true,
});
ControllerRelation.prototype.insertChild = function <C extends Controller>(this: ControllerRelation<unknown, C>, parent: Controller, child: C, target: Controller | null, key: string | undefined): void {
parent.insertChild(child, target, key);
};
ControllerRelation.prototype.bindController = function <C extends Controller>(this: ControllerRelation<unknown, C>, controller: Controller, target: Controller | null): void {
// hook
};
ControllerRelation.prototype.unbindController = function <C extends Controller>(this: ControllerRelation<unknown, C>, controller: Controller): void {
// hook
};
ControllerRelation.prototype.detectController = function <C extends Controller>(this: ControllerRelation<unknown, C>, controller: Controller): C | null {
return null;
};
ControllerRelation.prototype.createController = function <C extends Controller>(this: ControllerRelation<unknown, C>): C {
let controller: C | undefined;
const type = this.type;
if (type !== void 0) {
controller = type.create();
}
if (controller === void 0 || controller === null) {
let message = "Unable to create ";
if (this.name.length !== 0) {
message += this.name + " ";
}
message += "controller";
throw new Error(message);
}
return controller;
};
ControllerRelation.prototype.fromAny = function <C extends Controller>(this: ControllerRelation<unknown, C>, value: AnyController<C>): C {
const type = this.type;
if (type !== void 0) {
return type.fromAny(value);
} else {
return Controller.fromAny(value) as C;
}
};
Object.defineProperty(ControllerRelation.prototype, "lazy", {
get: function (this: ControllerRelation): boolean {
return false;
},
configurable: true,
});
Object.defineProperty(ControllerRelation.prototype, "static", {
get: function (this: ControllerRelation): string | boolean {
return true;
},
configurable: true,
});
ControllerRelation.construct = function <F extends ControllerRelation<any, any>>(fastenerClass: {prototype: F}, fastener: F | null, owner: FastenerOwner<F>): F {
fastener = _super.construct(fastenerClass, fastener, owner) as F;
return fastener;
};
ControllerRelation.define = function <O, C extends Controller>(className: string, descriptor: ControllerRelationDescriptor<O, C>): ControllerRelationFactory<ControllerRelation<any, C>> {
let superClass = descriptor.extends as ControllerRelationFactory | null | undefined;
const affinity = descriptor.affinity;
const inherits = descriptor.inherits;
delete descriptor.extends;
delete descriptor.implements;
delete descriptor.affinity;
delete descriptor.inherits;
if (superClass === void 0 || superClass === null) {
superClass = this;
}
const fastenerClass = superClass.extend(className, descriptor);
fastenerClass.construct = function (fastenerClass: {prototype: ControllerRelation<any, any>}, fastener: ControllerRelation<O, C> | null, owner: O): ControllerRelation<O, C> {
fastener = superClass!.construct(fastenerClass, fastener, owner);
if (affinity !== void 0) {
fastener.initAffinity(affinity);
}
if (inherits !== void 0) {
fastener.initInherits(inherits);
}
return fastener;
};
return fastenerClass;
};
return ControllerRelation;
})(Fastener); | the_stack |
import { Dispatch } from 'redux';
import {
Action,
ActionMeta,
createAction,
ActionFunction0,
ActionFunction1,
ActionFunction2,
ActionFunction3,
ActionFunction4,
ActionFunctionAny,
} from 'redux-actions';
import { FormSubmitHandler } from 'redux-form';
import { string } from 'prop-types';
export function routinePromiseWatcherSaga(): IterableIterator<any>;
export type RoutineStages = 'TRIGGER' | 'REQUEST' | 'SUCCESS' | 'FAILURE' | 'FULFILL';
export type ActionCreatorFunction<Payload = any, Meta = any> = ActionFunctionAny<
Action<Payload> | ActionMeta<Payload, Meta>
>;
export type Routine<
TTriggerActionCreator = ActionCreatorFunction,
TRequestActionCreator = ActionCreatorFunction,
TSuccessActionCreator = ActionCreatorFunction,
TFailureActionCreator = ActionCreatorFunction,
TFulfillActionCreator = ActionCreatorFunction
> = TTriggerActionCreator & {
[key in RoutineStages]: string;
} & {
trigger: TTriggerActionCreator;
request: TRequestActionCreator;
success: TSuccessActionCreator;
failure: TFailureActionCreator;
fulfill: TFulfillActionCreator;
};
export type UnifiedRoutine<TActionCreator = ActionCreatorFunction> = Routine<
TActionCreator,
TActionCreator,
TActionCreator,
TActionCreator,
TActionCreator
>;
export type ResolveFunctionReturnType<TFunction> =
TFunction extends (...args: any[]) => infer TReturn ? TReturn : undefined;
export type ResolveFunctionArg1Type<TFunction> =
TFunction extends (arg1: infer TArg1, ...args: any[]) => any ? TArg1 : undefined;
export type ResolveFunctionArg2Type<TFunction> =
TFunction extends (arg1: any, arg2: infer TArg1, ...args: any[]) => any ? TArg1 : undefined;
export type ResolveFunctionArg3Type<TFunction> =
TFunction extends (arg1: any, arg2: any, arg3: infer TArg1, ...args: any[]) => any ? TArg1 : undefined;
export type ResolveFunctionArg4Type<TFunction> =
TFunction extends (arg1: any, arg2: any, arg3: any, arg4: infer TArg1, ...args: any[]) => any ? TArg1 : undefined;
export type ResolveActionCreatorByPayload<
TPayloadCreator,
TPayload = ResolveFunctionReturnType<TPayloadCreator>,
TArg1 = ResolveFunctionArg1Type<TPayloadCreator>,
TArg2 = ResolveFunctionArg2Type<TPayloadCreator>,
TArg3 = ResolveFunctionArg3Type<TPayloadCreator>,
TArg4 = ResolveFunctionArg4Type<TPayloadCreator>
> =
TPayloadCreator extends ActionFunction0<TPayload> ? ActionFunction0<Action<TPayload>> :
TPayloadCreator extends ActionFunction1<TArg1, TPayload> ? ActionFunction1<TArg1, Action<TPayload>> :
TPayloadCreator extends ActionFunction2<TArg1, TArg2, TPayload> ? ActionFunction2<TArg1, TArg2, Action<TPayload>> :
TPayloadCreator extends ActionFunction3<TArg1, TArg2, TArg3, TPayload> ? ActionFunction3<TArg1, TArg2, TArg3, Action<TPayload>> :
TPayloadCreator extends ActionFunction4<TArg1, TArg2, TArg3, TArg4, TPayload> ? ActionFunction4<TArg1, TArg2, TArg3, TArg4, Action<TPayload>> : ActionFunctionAny<Action<TPayload>>;
export type ResolveActionCreatorByMeta<
TMetaCreator,
TMeta = ResolveFunctionReturnType<TMetaCreator>,
TArg1 = ResolveFunctionArg1Type<TMetaCreator>,
TArg2 = ResolveFunctionArg2Type<TMetaCreator>,
TArg3 = ResolveFunctionArg3Type<TMetaCreator>,
TArg4 = ResolveFunctionArg4Type<TMetaCreator>
> =
TMetaCreator extends ActionFunction0<TMeta> ? ActionFunction0<ActionMeta<any, TMeta>> :
TMetaCreator extends ActionFunction1<TArg1, TMeta> ? ActionFunction1<TArg1, ActionMeta<any, TMeta>> :
TMetaCreator extends ActionFunction2<TArg1, TArg2, TMeta> ? ActionFunction2<TArg1, TArg2, ActionMeta<any, TMeta>> :
TMetaCreator extends ActionFunction3<TArg1, TArg2, TArg3, TMeta> ? ActionFunction3<TArg1, TArg2, TArg3, ActionMeta<any, TMeta>> :
TMetaCreator extends ActionFunction4<TArg1, TArg2, TArg3, TArg4, TMeta> ? ActionFunction4<TArg1, TArg2, TArg3, TArg4, ActionMeta<any, TMeta>> : ActionFunctionAny<ActionMeta<any, TMeta>>;
export type ResolveActionCreatorByPayloadMeta<
TPayloadCreator,
TMetaCreator,
TPayload = ResolveFunctionReturnType<TPayloadCreator>,
TMeta = ResolveFunctionReturnType<TMetaCreator>,
TArg1 = ResolveFunctionArg1Type<TPayloadCreator>,
TArg2 = ResolveFunctionArg2Type<TPayloadCreator>,
TArg3 = ResolveFunctionArg3Type<TPayloadCreator>,
TArg4 = ResolveFunctionArg4Type<TPayloadCreator>
> =
TMetaCreator extends ActionFunction0<TMeta> ? ActionFunction0<ActionMeta<TPayload, TMeta>> :
TMetaCreator extends ActionFunction1<TArg1, TMeta> ? ActionFunction1<TArg1, ActionMeta<TPayload, TMeta>> :
TMetaCreator extends ActionFunction2<TArg1, TArg2, TMeta> ? ActionFunction2<TArg1, TArg2, ActionMeta<TPayload, TMeta>> :
TMetaCreator extends ActionFunction3<TArg1, TArg2, TArg3, TMeta> ? ActionFunction3<TArg1, TArg2, TArg3, ActionMeta<TPayload, TMeta>> :
TMetaCreator extends ActionFunction4<TArg1, TArg2, TArg3, TArg4, TMeta> ? ActionFunction4<TArg1, TArg2, TArg3, TArg4, ActionMeta<TPayload, TMeta>> : ActionFunctionAny<ActionMeta<TPayload, TMeta>>;
export interface ReduxFormPayload<TFormData = {}, TProps = {}> {
values: TFormData;
props: TProps;
}
export function bindRoutineToReduxForm<
TFormData = {},
TProps = {},
>(
routine: Routine<
ActionFunction1<ReduxFormPayload<TFormData, TProps>,
Action<ReduxFormPayload<TFormData, TProps>>>
> | Routine<
ActionFunction1<ReduxFormPayload<TFormData, TProps>,
ActionMeta<ReduxFormPayload<TFormData, TProps>, any>>
>,
noSuccessPayload?: boolean,
): FormSubmitHandler<TFormData, TProps>;
export type PromiseCreator<
TPayload = {},
> = (payload: TPayload, dispatch: Dispatch) => PromiseLike<any>;
export function promisifyRoutine(
routine: Routine,
): PromiseCreator;
export type BoundPromiseCreator<
TPayload = {},
> = (payload: TPayload) => PromiseLike<any>;
export function bindPromiseCreators<TPayload>(
promiseCreator: PromiseCreator<TPayload>,
dispatch: Dispatch,
): BoundPromiseCreator<TPayload>;
export function bindPromiseCreators(
promiseCreators: { [key: string]: PromiseCreator },
dispatch: Dispatch,
): { [key: string]: BoundPromiseCreator };
export function bindPromiseCreators(
promiseCreators: { [key: number]: PromiseCreator },
dispatch: Dispatch,
): { [key: number]: BoundPromiseCreator };
export const ROUTINE_PROMISE_ACTION: string;
// NOTE: Default payloadCreator is identity (x => x)
// NOTE: Same payloadCreator is used for all actions of the routine
export function createRoutine<
Payload = any
>(
typePrefix: string
): UnifiedRoutine<
(payload?: Payload) => Action<Payload | undefined>
>;
// NOTE: Same payloadCreator is used for all actions of the routine
export function createRoutine<
Payload
>(
typePrefix: string,
payloadCreator: ActionFunction0<Payload>
): UnifiedRoutine<
ActionFunction0<Action<Payload>>
>;
// NOTE: Same payloadCreator is used for all actions of the routine
export function createRoutine<
Payload,
Arg1
>(
typePrefix: string,
payloadCreator: ActionFunction1<Arg1, Payload>,
): UnifiedRoutine<
ActionFunction1<Arg1, Action<Payload>>
>;
// NOTE: Same payloadCreator is used for all actions of the routine
export function createRoutine<
Payload,
Arg1,
Arg2
>(
typePrefix: string,
payloadCreator: ActionFunction2<Arg1, Arg2, Payload>,
): UnifiedRoutine<
ActionFunction2<Arg1, Arg2, Action<Payload>>
>;
// NOTE: Same payloadCreator is used for all actions of the routine
export function createRoutine<
Payload,
Arg1,
Arg2,
Arg3
>(
typePrefix: string,
payloadCreator: ActionFunction3<Arg1, Arg2, Arg3, Payload>,
): UnifiedRoutine<
ActionFunction3<Arg1, Arg2, Arg3, Action<Payload>>
>;
// NOTE: Same payloadCreator is used for all actions of the routine
export function createRoutine<
Payload,
Arg1,
Arg2,
Arg3,
Arg4
>(
typePrefix: string,
payloadCreator: ActionFunction4<Arg1, Arg2, Arg3, Arg4, Payload>,
): UnifiedRoutine<
ActionFunction4<Arg1, Arg2, Arg3, Arg4, Action<Payload>>
>;
// NOTE: Default payloadCreator is identity (x => x)
// NOTE: Same payloadCreator is used for all actions of the routine
export function createRoutine<
Meta
>(
typePrefix: string,
payloadCreator: null | undefined,
metaCreator: ActionFunctionAny<Meta>,
): UnifiedRoutine<
(payload?: any) => ActionMeta<any, Meta>
>;
// NOTE: Same payloadCreator is used for all actions of the routine
export function createRoutine<
Payload,
Meta
>(
typePrefix: string,
payloadCreator: ActionFunctionAny<Payload>,
metaCreator: ActionFunctionAny<Meta>,
): UnifiedRoutine<
ActionFunctionAny<ActionMeta<Payload, Meta>>
>;
// NOTE: Same payloadCreator is used for all actions of the routine
export function createRoutine<
Payload,
Meta,
Arg1
>(
typePrefix: string,
payloadCreator: ActionFunction1<Arg1, Payload>,
metaCreator: ActionFunction1<Arg1, Meta>,
): UnifiedRoutine<
ActionFunction1<Arg1, ActionMeta<Payload, Meta>>
>;
// NOTE: Same payloadCreator is used for all actions of the routine
export function createRoutine<
Payload,
Meta,
Arg1,
Arg2
>(
typePrefix: string,
payloadCreator: ActionFunction2<Arg1, Arg2, Payload>,
metaCreator: ActionFunction2<Arg1, Arg2, Meta>,
): UnifiedRoutine<
ActionFunction2<Arg1, Arg2, ActionMeta<Payload, Meta>>
>;
// NOTE: Same payloadCreator is used for all actions of the routine
export function createRoutine<
Payload,
Meta,
Arg1,
Arg2,
Arg3
>(
typePrefix: string,
payloadCreator: ActionFunction3<Arg1, Arg2, Arg3, Payload>,
metaCreator: ActionFunction3<Arg1, Arg2, Arg3, Meta>,
): UnifiedRoutine<
ActionFunction3<Arg1, Arg2, Arg3, ActionMeta<Payload, Meta>>
>;
// NOTE: Same payloadCreator is used for all actions of the routine
export function createRoutine<
Payload,
Meta,
Arg1,
Arg2,
Arg3,
Arg4
>(
typePrefix: string,
payloadCreator: ActionFunction4<Arg1, Arg2, Arg3, Arg4, Payload>,
metaCreator: ActionFunction4<Arg1, Arg2, Arg3, Arg4, Meta>,
): UnifiedRoutine<
ActionFunction4<Arg1, Arg2, Arg3, Arg4, ActionMeta<Payload, Meta>>
>;
export function createRoutine<
TTriggerPayloadCreator,
TRequestPayloadCreator,
TSuccessPayloadCreator,
TFailurePayloadCreator,
TFulfillPayloadCreator
>(
typePrefix: string,
payloadCreator: {
TRIGGER?: TTriggerPayloadCreator,
trigger?: TTriggerPayloadCreator,
REQUEST?: TRequestPayloadCreator,
request?: TRequestPayloadCreator,
SUCCESS?: TSuccessPayloadCreator,
success?: TSuccessPayloadCreator,
FAILURE?: TFailurePayloadCreator,
failure?: TFailurePayloadCreator,
FULFILL?: TFulfillPayloadCreator,
fulfill?: TFulfillPayloadCreator
}
): Routine<
ResolveActionCreatorByPayload<TTriggerPayloadCreator>,
ResolveActionCreatorByPayload<TRequestPayloadCreator>,
ResolveActionCreatorByPayload<TSuccessPayloadCreator>,
ResolveActionCreatorByPayload<TFailurePayloadCreator>,
ResolveActionCreatorByPayload<TFulfillPayloadCreator>
>;
export function createRoutine<
TTriggerMetaCreator,
TRequestMetaCreator,
TSuccessMetaCreator,
TFailureMetaCreator,
TFulfillMetaCreator
>(
typePrefix: string,
payloadCreator: null | undefined,
metaCreator: {
TRIGGER?: TTriggerMetaCreator,
trigger?: TTriggerMetaCreator,
REQUEST?: TRequestMetaCreator,
request?: TRequestMetaCreator,
SUCCESS?: TSuccessMetaCreator,
success?: TSuccessMetaCreator,
FAILURE?: TFailureMetaCreator,
failure?: TFailureMetaCreator,
FULFILL?: TFulfillMetaCreator,
fulfill?: TFulfillMetaCreator
}
): Routine<
ResolveActionCreatorByMeta<TTriggerMetaCreator>,
ResolveActionCreatorByMeta<TRequestMetaCreator>,
ResolveActionCreatorByMeta<TSuccessMetaCreator>,
ResolveActionCreatorByMeta<TFailureMetaCreator>,
ResolveActionCreatorByMeta<TFulfillMetaCreator>
>;
export function createRoutine<
TTriggerPayloadCreator,
TRequestPayloadCreator,
TSuccessPayloadCreator,
TFailurePayloadCreator,
TFulfillPayloadCreator,
TTriggerMetaCreator,
TRequestMetaCreator,
TSuccessMetaCreator,
TFailureMetaCreator,
TFulfillMetaCreator
>(
typePrefix: string,
payloadCreator: {
TRIGGER?: TTriggerPayloadCreator,
trigger?: TTriggerPayloadCreator,
REQUEST?: TRequestPayloadCreator,
request?: TRequestPayloadCreator,
SUCCESS?: TSuccessPayloadCreator,
success?: TSuccessPayloadCreator,
FAILURE?: TFailurePayloadCreator,
failure?: TFailurePayloadCreator,
FULFILL?: TFulfillPayloadCreator,
fulfill?: TFulfillPayloadCreator
},
metaCreator: {
TRIGGER?: TTriggerMetaCreator,
trigger?: TTriggerMetaCreator,
REQUEST?: TRequestMetaCreator,
request?: TRequestMetaCreator,
SUCCESS?: TSuccessMetaCreator,
success?: TSuccessMetaCreator,
FAILURE?: TFailureMetaCreator,
failure?: TFailureMetaCreator,
FULFILL?: TFulfillMetaCreator,
fulfill?: TFulfillMetaCreator
}
): Routine<
ResolveActionCreatorByPayloadMeta<TTriggerPayloadCreator, TTriggerMetaCreator>,
ResolveActionCreatorByPayloadMeta<TRequestPayloadCreator, TRequestMetaCreator>,
ResolveActionCreatorByPayloadMeta<TSuccessPayloadCreator, TSuccessMetaCreator>,
ResolveActionCreatorByPayloadMeta<TFailurePayloadCreator, TFailureMetaCreator>,
ResolveActionCreatorByPayloadMeta<TFulfillPayloadCreator, TFulfillMetaCreator>
>; | the_stack |
import '@cds/core/toggle/register.js';
import { html } from 'lit';
import { getElementStorybookArgs, spreadProps } from '@cds/core/internal';
export default {
title: 'Stories/Toggle',
component: 'cds-toggle',
parameters: {
options: { showPanel: true },
design: {
type: 'figma',
url: 'https://www.figma.com/file/v2mkhzKQdhECXOx8BElgdA/Clarity-UI-Library---light-2.2.0?node-id=0%3A843',
},
},
};
export function API(args: any) {
return html`
<cds-toggle ...="${spreadProps(getElementStorybookArgs(args))}">
<label>toggle</label>
<input type="checkbox" />
<cds-control-message .status=${args.status}>message text</cds-control-message>
</cds-toggle>
`;
}
/** @website */
export function toggle() {
return html`
<cds-toggle>
<label>toggle</label>
<input type="checkbox" checked />
<cds-control-message>message text</cds-control-message>
</cds-toggle>
`;
}
/** @website */
export function status() {
return html`
<div cds-layout="vertical gap:lg">
<cds-toggle>
<label>toggle</label>
<input type="checkbox" checked />
<cds-control-message>message text</cds-control-message>
</cds-toggle>
<cds-toggle>
<label>disabled</label>
<input type="checkbox" disabled />
<cds-control-message>disabled text</cds-control-message>
</cds-toggle>
<cds-toggle>
<label>checked disabled</label>
<input type="checkbox" disabled checked />
<cds-control-message>disabled text</cds-control-message>
</cds-toggle>
<cds-toggle status="error">
<label>error</label>
<input type="checkbox" />
<cds-control-message status="error">error text</cds-control-message>
</cds-toggle>
<cds-toggle status="success">
<label>success</label>
<input type="checkbox" checked />
<cds-control-message status="success">success text</cds-control-message>
</cds-toggle>
</div>
`;
}
/** @website */
export function verticalGroup() {
return html`
<cds-form-group layout="vertical">
<cds-toggle-group>
<label>label</label>
<cds-toggle>
<label>toggle 1</label>
<input type="checkbox" checked />
</cds-toggle>
<cds-toggle>
<label>toggle 2</label>
<input type="checkbox" />
</cds-toggle>
<cds-toggle>
<label>toggle 3</label>
<input type="checkbox" />
</cds-toggle>
<cds-control-message>message text</cds-control-message>
</cds-toggle-group>
<!-- disable all controls within group or set disabled on input individually -->
<cds-toggle-group disabled>
<label>disabled</label>
<cds-toggle>
<label>toggle 1</label>
<input type="checkbox" checked disabled />
</cds-toggle>
<cds-toggle>
<label>toggle 2</label>
<input type="checkbox" disabled />
</cds-toggle>
<cds-toggle>
<label>toggle 3</label>
<input type="checkbox" disabled />
</cds-toggle>
<cds-control-message>message text</cds-control-message>
</cds-toggle-group>
<cds-toggle-group status="error">
<label>error</label>
<cds-toggle>
<label>toggle 1</label>
<input type="checkbox" checked />
</cds-toggle>
<cds-toggle>
<label>toggle 2</label>
<input type="checkbox" />
</cds-toggle>
<cds-toggle>
<label>toggle 3</label>
<input type="checkbox" />
</cds-toggle>
<cds-control-message status="error">message text</cds-control-message>
</cds-toggle-group>
<cds-toggle-group status="success">
<label>success</label>
<cds-toggle>
<label>toggle 1</label>
<input type="checkbox" checked />
</cds-toggle>
<cds-toggle>
<label>toggle 2</label>
<input type="checkbox" />
</cds-toggle>
<cds-toggle>
<label>toggle 3</label>
<input type="checkbox" />
</cds-toggle>
<cds-control-message status="success">message text</cds-control-message>
</cds-toggle-group>
</cds-form-group>
`;
}
/** @website */
export function verticalInlineGroup() {
return html`
<cds-form-group layout="vertical-inline">
<cds-toggle-group layout="vertical-inline">
<label>label</label>
<cds-toggle>
<label>toggle 1</label>
<input type="checkbox" checked />
</cds-toggle>
<cds-toggle>
<label>toggle 2</label>
<input type="checkbox" />
</cds-toggle>
<cds-toggle>
<label>toggle 3</label>
<input type="checkbox" />
</cds-toggle>
<cds-control-message>message text</cds-control-message>
</cds-toggle-group>
<cds-toggle-group layout="vertical-inline" disabled>
<label>disabled</label>
<cds-toggle>
<label>toggle 1</label>
<input type="checkbox" checked disabled />
</cds-toggle>
<cds-toggle>
<label>toggle 2</label>
<input type="checkbox" disabled />
</cds-toggle>
<cds-toggle>
<label>toggle 3</label>
<input type="checkbox" disabled />
</cds-toggle>
<cds-control-message>disabled message</cds-control-message>
</cds-toggle-group>
<cds-toggle-group layout="vertical-inline" status="error">
<label>error</label>
<cds-toggle>
<label>toggle 1</label>
<input type="checkbox" checked />
</cds-toggle>
<cds-toggle>
<label>toggle 2</label>
<input type="checkbox" />
</cds-toggle>
<cds-toggle>
<label>toggle 3</label>
<input type="checkbox" />
</cds-toggle>
<cds-control-message status="error">error message</cds-control-message>
</cds-toggle-group>
<cds-toggle-group layout="vertical-inline" status="success">
<label>success</label>
<cds-toggle>
<label>toggle 1</label>
<input type="checkbox" checked />
</cds-toggle>
<cds-toggle>
<label>toggle 2</label>
<input type="checkbox" />
</cds-toggle>
<cds-toggle>
<label>toggle 3</label>
<input type="checkbox" />
</cds-toggle>
<cds-control-message status="success">success message</cds-control-message>
</cds-toggle-group>
</cds-form-group>
`;
}
/** @website */
export function horizontalGroup() {
return html`
<cds-form-group layout="horizontal">
<cds-toggle-group layout="horizontal">
<label>label</label>
<cds-toggle>
<label>toggle 1</label>
<input type="checkbox" checked />
</cds-toggle>
<cds-toggle>
<label>toggle 2</label>
<input type="checkbox" />
</cds-toggle>
<cds-toggle>
<label>toggle 3</label>
<input type="checkbox" />
</cds-toggle>
<cds-control-message>message text</cds-control-message>
</cds-toggle-group>
<cds-toggle-group layout="horizontal" disabled>
<label>disabled</label>
<cds-toggle>
<label>toggle 1</label>
<input type="checkbox" checked disabled />
</cds-toggle>
<cds-toggle>
<label>toggle 2</label>
<input type="checkbox" disabled />
</cds-toggle>
<cds-toggle>
<label>toggle 3</label>
<input type="checkbox" disabled />
</cds-toggle>
<cds-control-message>disabled message</cds-control-message>
</cds-toggle-group>
<cds-toggle-group layout="horizontal" status="error">
<label>error</label>
<cds-toggle>
<label>toggle 1</label>
<input type="checkbox" checked />
</cds-toggle>
<cds-toggle>
<label>toggle 2</label>
<input type="checkbox" />
</cds-toggle>
<cds-toggle>
<label>toggle 3</label>
<input type="checkbox" />
</cds-toggle>
<cds-control-message status="error">error message</cds-control-message>
</cds-toggle-group>
<cds-toggle-group layout="horizontal" status="success">
<label>success</label>
<cds-toggle>
<label>toggle 1</label>
<input type="checkbox" checked />
</cds-toggle>
<cds-toggle>
<label>toggle 2</label>
<input type="checkbox" />
</cds-toggle>
<cds-toggle>
<label>toggle 3</label>
<input type="checkbox" />
</cds-toggle>
<cds-control-message status="success">success message</cds-control-message>
</cds-toggle-group>
</cds-form-group>
`;
}
/** @website */
export function horizontalInlineGroup() {
return html`
<cds-form-group layout="horizontal-inline">
<cds-toggle-group layout="horizontal-inline">
<label>label</label>
<cds-toggle>
<label>toggle 1</label>
<input type="checkbox" checked />
</cds-toggle>
<cds-toggle>
<label>toggle 2</label>
<input type="checkbox" />
</cds-toggle>
<cds-toggle>
<label>toggle 3</label>
<input type="checkbox" />
</cds-toggle>
<cds-control-message>message text</cds-control-message>
</cds-toggle-group>
<cds-toggle-group layout="horizontal-inline" disabled>
<label>disabled</label>
<cds-toggle>
<label>toggle 1</label>
<input type="checkbox" checked disabled />
</cds-toggle>
<cds-toggle>
<label>toggle 2</label>
<input type="checkbox" disabled />
</cds-toggle>
<cds-toggle>
<label>toggle 3</label>
<input type="checkbox" disabled />
</cds-toggle>
<cds-control-message>disabled message</cds-control-message>
</cds-toggle-group>
<cds-toggle-group layout="horizontal-inline" status="error">
<label>error</label>
<cds-toggle>
<label>toggle 1</label>
<input type="checkbox" checked />
</cds-toggle>
<cds-toggle>
<label>toggle 2</label>
<input type="checkbox" />
</cds-toggle>
<cds-toggle>
<label>toggle 3</label>
<input type="checkbox" />
</cds-toggle>
<cds-control-message status="error">error message</cds-control-message>
</cds-toggle-group>
<cds-toggle-group layout="horizontal-inline" status="success">
<label>success</label>
<cds-toggle>
<label>toggle 1</label>
<input type="checkbox" checked />
</cds-toggle>
<cds-toggle>
<label>toggle 2</label>
<input type="checkbox" />
</cds-toggle>
<cds-toggle>
<label>toggle 3</label>
<input type="checkbox" />
</cds-toggle>
<cds-control-message status="success">success message</cds-control-message>
</cds-toggle-group>
</cds-form-group>
`;
}
/** @website */
export function compactGroup() {
return html`
<cds-form-group layout="compact">
<cds-toggle-group layout="compact">
<label>label</label>
<cds-toggle>
<label>toggle 1</label>
<input type="checkbox" checked />
</cds-toggle>
<cds-toggle>
<label>toggle 2</label>
<input type="checkbox" />
</cds-toggle>
<cds-toggle>
<label>toggle 3</label>
<input type="checkbox" />
</cds-toggle>
<cds-control-message>message text</cds-control-message>
</cds-toggle-group>
<cds-toggle-group layout="compact" disabled>
<label>disabled</label>
<cds-toggle>
<label>toggle 1</label>
<input type="checkbox" checked disabled />
</cds-toggle>
<cds-toggle>
<label>toggle 2</label>
<input type="checkbox" disabled />
</cds-toggle>
<cds-toggle>
<label>toggle 3</label>
<input type="checkbox" disabled />
</cds-toggle>
<cds-control-message>disabled message</cds-control-message>
</cds-toggle-group>
<cds-toggle-group layout="compact" status="error">
<label>error</label>
<cds-toggle>
<label>toggle 1</label>
<input type="checkbox" checked />
</cds-toggle>
<cds-toggle>
<label>toggle 2</label>
<input type="checkbox" />
</cds-toggle>
<cds-toggle>
<label>toggle 3</label>
<input type="checkbox" />
</cds-toggle>
<cds-control-message status="error">error message</cds-control-message>
</cds-toggle-group>
<cds-toggle-group layout="compact" status="success">
<label>success</label>
<cds-toggle>
<label>toggle 1</label>
<input type="checkbox" checked />
</cds-toggle>
<cds-toggle>
<label>toggle 2</label>
<input type="checkbox" />
</cds-toggle>
<cds-toggle>
<label>toggle 3</label>
<input type="checkbox" />
</cds-toggle>
<cds-control-message status="success">success message</cds-control-message>
</cds-toggle-group>
</cds-form-group>
`;
}
/** @website */
export function toggleAlign() {
return html`
<div cds-layout="vertical gap:lg">
<cds-toggle>
<label>left</label>
<input type="checkbox" checked />
</cds-toggle>
<cds-toggle control-align="right">
<label>right</label>
<input type="checkbox" checked />
</cds-toggle>
<cds-toggle-group>
<label>Group Left</label>
<cds-toggle>
<label>toggle 1</label>
<input type="checkbox" checked />
</cds-toggle>
<cds-toggle>
<label>toggle 2</label>
<input type="checkbox" />
</cds-toggle>
</cds-toggle-group>
<cds-toggle-group control-align="right">
<label>Group Right</label>
<cds-toggle>
<label>toggle 1</label>
<input type="checkbox" checked />
</cds-toggle>
<cds-toggle>
<label>toggle 2</label>
<input type="checkbox" />
</cds-toggle>
</cds-toggle-group>
</div>
`;
}
/** @website */
export function darkTheme() {
return html`
<cds-form-group layout="horizontal-inline" cds-theme="dark">
<cds-toggle-group layout="horizontal-inline">
<label>label</label>
<cds-toggle>
<label>toggle 1</label>
<input type="checkbox" checked />
</cds-toggle>
<cds-toggle>
<label>toggle 2</label>
<input type="checkbox" />
</cds-toggle>
<cds-toggle>
<label>toggle 3</label>
<input type="checkbox" />
</cds-toggle>
<cds-control-message>message text</cds-control-message>
</cds-toggle-group>
<cds-toggle-group layout="horizontal-inline" disabled>
<label>disabled</label>
<cds-toggle>
<label>toggle 1</label>
<input type="checkbox" checked disabled />
</cds-toggle>
<cds-toggle>
<label>toggle 2</label>
<input type="checkbox" disabled />
</cds-toggle>
<cds-toggle>
<label>toggle 3</label>
<input type="checkbox" disabled />
</cds-toggle>
<cds-control-message>disabled message</cds-control-message>
</cds-toggle-group>
<cds-toggle-group layout="horizontal-inline" status="error">
<label>error</label>
<cds-toggle>
<label>toggle 1</label>
<input type="checkbox" checked />
</cds-toggle>
<cds-toggle>
<label>toggle 2</label>
<input type="checkbox" />
</cds-toggle>
<cds-toggle>
<label>toggle 3</label>
<input type="checkbox" />
</cds-toggle>
<cds-control-message status="error">error message</cds-control-message>
</cds-toggle-group>
<cds-toggle-group layout="horizontal-inline" status="success">
<label>success</label>
<cds-toggle>
<label>toggle 1</label>
<input type="checkbox" checked />
</cds-toggle>
<cds-toggle>
<label>toggle 2</label>
<input type="checkbox" />
</cds-toggle>
<cds-toggle>
<label>toggle 3</label>
<input type="checkbox" />
</cds-toggle>
<cds-control-message status="success">success message</cds-control-message>
</cds-toggle-group>
</cds-form-group>
`;
}
export function inlineGroupControlMessages() {
return html`
<div cds-layout="vertical gap:lg">
<cds-toggle-group>
<label>label</label>
<cds-toggle>
<label>toggle 1</label>
<input type="checkbox" checked />
</cds-toggle>
<cds-toggle>
<label>toggle 2</label>
<input type="checkbox" />
<cds-control-message><a cds-text="link" href="#">learn more</a></cds-control-message>
</cds-toggle>
<cds-toggle>
<label>toggle 3</label>
<input type="checkbox" />
</cds-toggle>
</cds-toggle-group>
</div>
`;
} | the_stack |
import { ILocation, WebDriver, WebElement } from '../';
import { Executor } from './command';
/**
* Defines the reference point from which to compute offsets for
* {@linkplain ./input.Pointer#move pointer move} actions.
*/
export enum Origin {
/** Compute offsets relative to the pointer's current position. */
POINTER = 'pointer',
/** Compute offsets relative to the viewport. */
VIEWPORT = 'viewport',
}
/**
* Enumeration of the buttons used in the advanced interactions API.
*/
export enum Button {
LEFT = 0,
MIDDLE = 1,
RIGHT = 2,
}
export interface IKey {
NULL: string;
CANCEL: string; // ^break
HELP: string;
BACK_SPACE: string;
TAB: string;
CLEAR: string;
RETURN: string;
ENTER: string;
SHIFT: string;
CONTROL: string;
ALT: string;
PAUSE: string;
ESCAPE: string;
SPACE: string;
PAGE_UP: string;
PAGE_DOWN: string;
END: string;
HOME: string;
ARROW_LEFT: string;
LEFT: string;
ARROW_UP: string;
UP: string;
ARROW_RIGHT: string;
RIGHT: string;
ARROW_DOWN: string;
DOWN: string;
INSERT: string;
DELETE: string;
SEMICOLON: string;
EQUALS: string;
NUMPAD0: string; // number pad keys
NUMPAD1: string;
NUMPAD2: string;
NUMPAD3: string;
NUMPAD4: string;
NUMPAD5: string;
NUMPAD6: string;
NUMPAD7: string;
NUMPAD8: string;
NUMPAD9: string;
MULTIPLY: string;
ADD: string;
SEPARATOR: string;
SUBTRACT: string;
DECIMAL: string;
DIVIDE: string;
F1: string; // function keys
F2: string;
F3: string;
F4: string;
F5: string;
F6: string;
F7: string;
F8: string;
F9: string;
F10: string;
F11: string;
F12: string;
COMMAND: string; // Apple command key
META: string; // alias for Windows key
/**
* Simulate pressing many keys at once in a 'chord'. Takes a sequence of
* keys or strings, appends each of the values to a string,
* and adds the chord termination key ({@link Key.NULL}) and returns
* the resulting string.
*
* Note: when the low-level webdriver key handlers see Keys.NULL, active
* modifier keys (CTRL/ALT/SHIFT/etc) release via a keyup event.
*
* @param {...string} var_args The key sequence to concatenate.
* @return {string} The null-terminated key sequence.
*/
chord(...var_args: Array<string|IKey>): string;
}
/**
* Representations of pressable keys that aren't text. These are stored in
* the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to
* http://www.google.com.au/search?&q=unicode+pua&btnG=Search
*
* @enum {string}
*/
export const Key: IKey;
export interface IDirection {
x?: number|undefined;
y?: number|undefined;
duration?: number|undefined;
origin?: Origin|WebElement|undefined;
}
export const INTERNAL_COMPUTE_OFFSET_SCRIPT: string;
export class Device { constructor(type: string, id: string); }
export class Pointer extends Device {}
export class Keyboard extends Device {}
/**
* Class for defining sequences of complex user interactions. Each sequence
* will not be executed until {@link #perform} is called.
*
* Example:
*
* new Actions(driver).
* keyDown(Key.SHIFT).
* click(element1).
* click(element2).
* dragAndDrop(element3, element4).
* keyUp(Key.SHIFT).
* perform();
*
*/
export class Actions {
// region Constructors
constructor(executor: Executor, options?: {async: boolean,
bridge: boolean}|{async: boolean}|{bridge: boolean});
// endregion
// region Methods
keyboard(): Keyboard;
mouse(): Pointer;
/**
* Executes this action sequence.
* @return {!Promise} A promise that will be resolved once
* this sequence has completed.
*/
clear(): Promise<void>;
/**
* Executes this action sequence.
* @return {!Promise} A promise that will be resolved once
* this sequence has completed.
*/
perform(): Promise<void>;
pause(duration?: number|Device, ...devices: Device[]): Actions;
/**
* Inserts an action to press a mouse button at the mouse's current location.
* Defaults to `LEFT`.
*/
press(button?: Button): Actions;
/**
* Inserts an action to release a mouse button at the mouse's current
* location. Defaults to `LEFT`.
*/
release(button?: Button): Actions;
/**
* Inserts an action for moving the mouse `x` and `y` pixels relative to the
* specified `origin`. The `origin` may be defined as the mouse's
* {@linkplain ./input.Origin.POINTER current position}, the
* {@linkplain ./input.Origin.VIEWPORT viewport}, or the center of a specific
* {@linkplain ./webdriver.WebElement WebElement}.
*
* You may adjust how long the remote end should take, in milliseconds, to
* perform the move using the `duration` parameter (defaults to 100 ms).
* The number of incremental move events generated over this duration is an
* implementation detail for the remote end.
*
* Defaults to moving the mouse to the top-left
* corner of the viewport over 100ms.
*/
move(direction: IDirection): Actions;
/**
* Moves the mouse. The location to move to may be specified in terms of the
* mouse's current location, an offset relative to the top-left corner of an
* element, or an element (in which case the middle of the element is used).
*
* @param {(!./WebElement|{x: number, y: number})} location The
* location to drag to, as either another WebElement or an offset in
* pixels.
* @param {{x: number, y: number}=} opt_offset If the target {@code location}
* is defined as a {@link ./WebElement}, this parameter defines
* an offset within that element. The offset should be specified in pixels
* relative to the top-left corner of the element's bounding box. If
* omitted, the element's center will be used as the target offset.
* @return {!Actions} A self reference.
*/
mouseMove(location: WebElement|ILocation, opt_offset?: ILocation): Actions;
/**
* Presses a mouse button. The mouse button will not be released until
* {@link #mouseUp} is called, regardless of whether that call is made in this
* sequence or another. The behavior for out-of-order events (e.g. mouseDown,
* click) is undefined.
*
* If an element is provided, the mouse will first be moved to the center
* of that element. This is equivalent to:
*
* sequence.mouseMove(element).mouseDown()
*
* Warning: this method currently only supports the left mouse button. See
* [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047).
*
* @param {(./WebElement|input.Button)=} opt_elementOrButton Either
* the element to interact with or the button to click with.
* Defaults to {@link input.Button.LEFT} if neither an element nor
* button is specified.
* @param {input.Button=} opt_button The button to use. Defaults to
* {@link input.Button.LEFT}. Ignored if a button is provided as the
* first argument.
* @return {!Actions} A self reference.
*/
mouseDown(opt_elementOrButton?: WebElement|string, opt_button?: string): Actions;
/**
* Releases a mouse button. Behavior is undefined for calling this function
* without a previous call to {@link #mouseDown}.
*
* If an element is provided, the mouse will first be moved to the center
* of that element. This is equivalent to:
*
* sequence.mouseMove(element).mouseUp()
*
* Warning: this method currently only supports the left mouse button. See
* [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047).
*
* @param {(./WebElement|input.Button)=} opt_elementOrButton Either
* the element to interact with or the button to click with.
* Defaults to {@link input.Button.LEFT} if neither an element nor
* button is specified.
* @param {input.Button=} opt_button The button to use. Defaults to
* {@link input.Button.LEFT}. Ignored if a button is provided as the
* first argument.
* @return {!Actions} A self reference.
*/
mouseUp(opt_elementOrButton?: WebElement|string, opt_button?: string): Actions;
/**
* Convenience function for performing a 'drag and drop' manuever. The target
* element may be moved to the location of another element, or by an offset (in
* pixels).
*/
dragAndDrop(from: WebElement, to?: WebElement|{x?: number | string, y?: number|string}|null):
Actions;
/**
* Clicks a mouse button.
*
* If an element is provided, the mouse will first be moved to the center
* of that element. This is equivalent to:
*
* sequence.mouseMove(element).click()
*
* @param {(./WebElement|input.Button)=} opt_elementOrButton Either
* the element to interact with or the button to click with.
* Defaults to {@link input.Button.LEFT} if neither an element nor
* button is specified.
* @param {input.Button=} opt_button The button to use. Defaults to
* {@link input.Button.LEFT}. Ignored if a button is provided as the
* first argument.
* @return {!Actions} A self reference.
*/
click(opt_elementOrButton?: WebElement|string, opt_button?: string): Actions;
/**
* Double-clicks a mouse button.
*
* If an element is provided, the mouse will first be moved to the center of
* that element. This is equivalent to:
*
* sequence.mouseMove(element).doubleClick()
*
* Warning: this method currently only supports the left mouse button. See
* [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047).
*
* @param {(./WebElement|input.Button)=} opt_elementOrButton Either
* the element to interact with or the button to click with.
* Defaults to {@link input.Button.LEFT} if neither an element nor
* button is specified.
* @param {input.Button=} opt_button The button to use. Defaults to
* {@link input.Button.LEFT}. Ignored if a button is provided as the
* first argument.
* @return {!Actions} A self reference.
*/
doubleClick(opt_elementOrButton?: WebElement|string, opt_button?: string): Actions;
/**
* Short-hand for performing a simple right-click (down/up) with the mouse.
*
* @param {./webdriver.WebElement=} element If specified, the mouse will
* first be moved to the center of the element before performing the
* click.
* @return {!Actions} a self reference.
*/
contextClick(opt_elementOrButton?: WebElement|string): Actions;
/**
* Performs a modifier key press. The modifier key is <em>not released</em>
* until {@link #keyUp} or {@link #sendKeys} is called. The key press will be
* targetted at the currently focused element.
* @param {!Key} key The modifier key to push. Must be one of
* {ALT, CONTROL, SHIFT, COMMAND, META}.
* @return {!Actions} A self reference.
* @throws {Error} If the key is not a valid modifier key.
*/
keyDown(key: string): Actions;
/**
* Performs a modifier key release. The release is targetted at the currently
* focused element.
* @param {!Key} key The modifier key to release. Must be one of
* {ALT, CONTROL, SHIFT, COMMAND, META}.
* @return {!Actions} A self reference.
* @throws {Error} If the key is not a valid modifier key.
*/
keyUp(key: string): Actions;
/**
* Simulates typing multiple keys. Each modifier key encountered in the
* sequence will not be released until it is encountered again. All key events
* will be targeted at the currently focused element.
*
* @param {...(string|!input.Key|!Array<(string|!input.Key)>)} var_args
* The keys to type.
* @return {!Actions} A self reference.
* @throws {Error} If the key is not a valid modifier key.
*/
sendKeys(...var_args: Array<string|Promise<string>>): Actions;
// endregion
} | the_stack |
import * as fs from 'fs';
import * as path from 'path';
import {
cleanHyperLink,
constructMatrixType,
constructParamTable,
filterByKind,
filterByTag,
getText,
ifEquals,
isSignatureValid,
renderMethodBracket,
renderMethodReturnType,
renderNewLine,
renderSourceLink,
searchInterface,
traverseArrayDefinition,
} from '../../docs/processor';
const docsJson = JSON.parse(fs.readFileSync(path.join(__dirname, './__snapshots__/docs.snapshot.json'), 'utf8'));
/**
* Mocking handlebar options
*/
const optionsMock = {
fn: (x) => ({
result: true,
payload: x,
}),
inverse: (x) => ({
result: false,
payload: x,
}),
};
describe('docs:helper', () => {
describe('ifEquals', () => {
it('should return fn when the inputs are 1 and 1', () => {
const result = ifEquals({}, 1, 1, optionsMock).result;
expect(result).toBe(true);
});
it('should return inverse when the inputs are 1 and 2', () => {
const result = ifEquals({}, 1, 2, optionsMock).result;
expect(result).toBe(false);
});
it('should return fn when the two input objects are same', () => {
const result = ifEquals({}, { z: 1 }, { z: 1 }, optionsMock).result;
expect(result).toBe(true);
});
it('should return inverse when the two input objects are not same', () => {
const result = ifEquals({}, { z: 1 }, { z: 2 }, optionsMock).result;
expect(result).toBe(false);
});
});
describe('filterByKind', () => {
const fakePayload = [
// Constructor
{
id: 724,
name: 'zzzz',
kind: 32,
kindString: 'Constructor',
flags: {},
comment: {
shortText: 'model training epochs',
},
sources: [
{
fileName: 'linear_model/stochastic_gradient.ts',
line: 126,
character: 10,
},
],
type: {
type: 'intrinsic',
name: 'number',
},
},
// Public var
{
id: 725,
name: 'weights',
kind: 32,
kindString: 'Variable',
flags: {
isPublic: true,
},
comment: {
shortText: 'Model training weights',
},
sources: [
{
fileName: 'linear_model/stochastic_gradient.ts',
line: 130,
character: 11,
},
],
type: {
type: 'array',
elementType: {
type: 'intrinsic',
name: 'number',
},
},
},
];
it('should filter all public Variables', () => {
const result = filterByKind(fakePayload, optionsMock, 'Variable');
expect(result).toMatchSnapshot();
});
it('should filter all constructor', () => {
const result = filterByKind(fakePayload, optionsMock, 'Constructor');
expect(result).toMatchSnapshot();
});
});
describe('filterByTag', () => {
const fakePayload = [
{
tag: 'example',
text:
"\nimport { SGDRegressor } from 'kalimdor/linear_model';\nconst reg = new SGDRegressor();\nconst X = [[0., 0.], [1., 1.]];\nconst y = [0, 1];\nreg.fit(X, y);\nreg.predict([[2., 2.]]); // result: [ 1.281828588248001 ]\n\n",
},
{
tag: 'test',
text: 'yo',
},
];
it('should find a tag example', () => {
const result = filterByTag(fakePayload, optionsMock, 'example');
expect(result).toMatchSnapshot();
});
it('should not find a tag zz', () => {
const result = filterByTag(fakePayload, optionsMock, 'zz');
expect(result.result).toBe(false);
});
});
describe('searchInterface', () => {
it('should find reference', () => {
const result = searchInterface(docsJson, 942);
const { id, name, kindString } = result;
expect(id).toBe(942);
expect(name).toBe('SVMOptions');
expect(kindString).toBe('Interface');
});
it('should invalid ID reference return null', () => {
const result = searchInterface(docsJson, 9999999);
expect(result).toBe(null);
});
});
describe('isSignatureValid', () => {
it('should return true for the 2nd child', () => {
const ele = docsJson.children[1].children[0].children[0];
const result = isSignatureValid(ele, optionsMock);
expect(result.result).toBe(true);
expect(result.payload).toMatchSnapshot();
});
it('should return false for the 1st child', () => {
const ele = docsJson.children[0];
const result = isSignatureValid(ele, optionsMock);
expect(result.result).toBe(false);
});
it('should return false for null input', () => {
expect(() => isSignatureValid(null, optionsMock)).toThrow("Cannot read property 'signatures' of null");
});
});
describe('traverseArrayDefinition', () => {
const dummy1 = {
type: 'array',
elementType: {
type: 'intrinsic',
name: 'string',
},
};
const dummy2 = {
type: 'array',
elementType: {
type: 'array',
elementType: {
type: 'intrinsic',
name: 'number',
},
},
};
it('should dummy1 return number[]', () => {
const result = traverseArrayDefinition(dummy1);
expect(result).toBe('string[]');
});
it('should dummy2 return number[][]', () => {
const result = traverseArrayDefinition(dummy2);
expect(result).toBe('number[][]');
});
it('should throw exceptions when invalid input is given', () => {
expect(() => traverseArrayDefinition(null)).toThrow("Cannot read property 'elementType' of null");
expect(() => traverseArrayDefinition(123)).toThrow("Cannot read property 'name' of undefined");
});
});
describe('constructMatrixType', () => {
it('should construct Type1DMatrix into number[]', () => {
const matrixType = constructMatrixType('Type1DMatrix', [{ name: 'number', type: 'number' }]);
expect(matrixType).toBe('number[]');
});
it('should construct Type2DMatrix into number[][]', () => {
const matrixType = constructMatrixType('Type2DMatrix', [{ name: 'number', type: 'number' }]);
expect(matrixType).toBe('number[][]');
});
it('should construct Type3DMatrix into number[][][]', () => {
const matrixType = constructMatrixType('Type3DMatrix', [{ name: 'number', type: 'number' }]);
expect(matrixType).toBe('number[][][]');
});
it('should construct Type4DMatrix into number[][][]', () => {
const matrixType = constructMatrixType('Type4DMatrix', [{ name: 'number', type: 'number' }]);
expect(matrixType).toBe('number[][][][]');
});
it('should throw an error on invalid inputs', () => {
expect(() => constructMatrixType(null, [{ name: 'number', type: 'number' }])).toThrow(
'dim should not be null or undefined',
);
expect(() => constructMatrixType('Type1DMatrix', null)).toThrow('types cannot be empty!');
});
});
describe('getText', () => {
const dummy1 = {
comment: {
text: 'dummy text',
shortText: 'dummy shortText',
},
};
const dummy2 = {
comment: {
text: null,
shortText: 'dummy shortText',
},
};
it('should dummy1 get text', () => {
const text = getText(dummy1);
expect(text).toBe('dummy text');
});
it('should dummy2 get shortText', () => {
const shortText = getText(dummy2);
expect(shortText).toBe('dummy shortText');
});
it('should throw an error for an invalid input', () => {
expect(() => getText(null)).toThrow('Param should not be null or undefined');
expect(() => getText(undefined)).toThrow('Param should not be null or undefined');
});
});
describe('constructParamTable', () => {
it('should build a table for param1', () => {
const params = docsJson.children[3].children[0].children[1].signatures[0].parameters;
const result = constructParamTable(params);
expect(result).toMatchSnapshot();
});
it('should build a table for params with Type1DMatrix', () => {
// Testing LinearRegression's fit function
const params = docsJson.children[16].children[0].children[0].signatures[0].parameters;
const result = constructParamTable(params);
expect(result).toMatchSnapshot();
});
it('should build table for params with Type2DMatrix', () => {
// Testing SGDClassifier's fit function
const params = docsJson.children[17].children[2].children[5].signatures[0].parameters;
const result = constructParamTable(params);
expect(result).toMatchSnapshot();
});
it('should build table for params with Type2DMatrix of multiple types', () => {
// Testing GaussianNB's fit function
const params = docsJson.children[23].children[0].children[1].signatures[0].parameters;
const result = constructParamTable(params);
expect(result).toMatchSnapshot();
});
});
describe('renderMethodReturnType', () => {
it('should build a return type for any[]', () => {
// Testing with random forest's predict
const type = docsJson.children[8].children[1].children[6].signatures[0].type;
const returnType = renderMethodReturnType(type);
expect(returnType).toEqual('any[]');
});
it('should build a return type for void', () => {
// Testing with random forest's fit
const type = docsJson.children[8].children[1].children[4].signatures[0].type;
const returnType = renderMethodReturnType(type);
expect(returnType).toEqual('void');
});
it('should build a toJSON return type', () => {
const type = docsJson.children[8].children[1].children[7].signatures[0].type;
const returnType = renderMethodReturnType(type);
expect(returnType).toMatchSnapshot();
});
});
describe('methodBracket', () => {
// TODO: renderMethodBracket should decompose all the namedParameters
it('should print a constructor parameter table', () => {
const parameters = docsJson.children[8].children[1].children[0].signatures[0].parameters;
const result = renderMethodBracket(parameters);
expect(result).toEqual('(__namedParameters: *`object`*)');
});
});
describe('renderSourceLink', () => {
const source1 = [
{
fileName: 'ensemble/forest.ts',
line: 80,
character: 15,
},
];
const source2 = [
{
fileName: 'svm/classes.ts',
line: 254,
character: 34,
},
];
it('should render sources for source1', () => {
const result = renderSourceLink(source1);
expect(result).toEqual(
'[ensemble/forest.ts:80](https://github.com/machinelearnjs/machinelearnjs/blob/master/src/lib/ensemble/forest.ts#L80)',
);
});
it('should render sources for source2', () => {
const result = renderSourceLink(source2);
expect(result).toEqual(
'[svm/classes.ts:254](https://github.com/machinelearnjs/machinelearnjs/blob/master/src/lib/svm/classes.ts#L254)',
);
});
it('should not render sources for null', () => {
const error = 'Sources cannot be empty';
expect(() => renderSourceLink(null)).toThrow(error);
expect(() => renderSourceLink(123)).toThrow(error);
});
});
describe('docs:test:renderNewLine', () => {
it('should render a newline upon calling the method', () => {
const result = renderNewLine();
expect(result).toMatchSnapshot();
});
});
describe('docs:test:cleanHyperLink', () => {
it('should clean "explained_variance"', () => {
// toJSON
const result = cleanHyperLink('explained_variance');
expect(result).toEqual('explained-variance');
});
it('should clean "toJSON"', () => {
const result = cleanHyperLink('toJSON');
expect(result).toEqual('tojson');
});
it('should not clean invalid values', () => {
expect(() => cleanHyperLink(null)).toThrow('Should not clean values other than strings');
expect(() => cleanHyperLink(123 as any)).toThrow('Should not clean values other than strings');
expect(() => cleanHyperLink(undefined)).toThrow('Should not clean values other than strings');
});
});
}); | the_stack |
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
import isBetween from 'dayjs/plugin/isBetween';
import isoWeek from 'dayjs/plugin/isoWeek';
import relativeTime from 'dayjs/plugin/relativeTime';
import throttle from 'lodash/throttle';
import { ConfigurationChangeEvent, Disposable, ExtensionContext, Range, TextDocument, TextEditorDecorationType, window, workspace } from 'vscode';
import { registerAllCommands } from './commands';
import { updateEditorDecorationStyle } from './decorations';
import { resetAllRecurringTasks } from './documentActions';
import { checkIfNeedResetRecurringTasks, onChangeActiveTextEditor } from './events';
import { parseDocument } from './parse';
import { StatusBar } from './statusBar';
import { TheTask } from './TheTask';
import { createAllTreeViews, groupAndSortTreeItems, updateAllTreeViews, updateArchivedTasks } from './treeViewProviders/treeViews';
import { ExtensionConfig, ItemForProvider, VscodeContext } from './types';
import { updateUserSuggestItems } from './userSuggestItems';
import { getActiveDocument, getDocumentForDefaultFile } from './utils/extensionUtils';
import { getEditorLineHeight, setContext } from './utils/vscodeUtils';
import { TasksWebviewViewProvider } from './webview/webviewView';
dayjs.extend(isBetween);
dayjs.extend(relativeTime);
dayjs.extend(isoWeek);
dayjs.extend(duration);
dayjs.Ls.en.weekStart = 1;
/**
* Things extension keeps a global reference to and uses extensively
*/
export abstract class extensionState {
/** All tasks (not as tree) */
static tasks: TheTask[] = [];
/** Tasks in a tree format (`task.subtasks` contains nested items) */
static tasksAsTree: TheTask[] = [];
/** All archived tasks */
static archivedTasks: TheTask[] = [];
/** All tags */
static tags: string[] = [];
/** All projects */
static projects: string[] = [];
/** All contexts */
static contexts: string[] = [];
static suggestTags: Record<string, string> = {};
static suggestProjects: Record<string, string> = {};
static suggestContexts: Record<string, string> = {};
/** Tags sorted and grouped for tags Tree View */
static tagsForTreeView: ItemForProvider[] = [];
/** Projects sorted and grouped for projects Tree View */
static projectsForTreeView: ItemForProvider[] = [];
/** Contexts sorted and grouped for contexts Tree View */
static contextsForTreeView: ItemForProvider[] = [];
/** Comment line ranges */
static commentLines: Range[] = [];
/** If active text editor matches `activatePattern` config */
static theRightFileOpened = false;
/** Last time file was opened (for resetting completion of recurring tasks) */
static lastVisitByFile: Record<string, Date> = {};
/** Current filter value of tasks Tree View */
static taskTreeViewFilterValue = '';
/** Reference to the extension context for access beyond the `activate()` function */
static extensionContext = {} as any as ExtensionContext;
/** Reference to active document. */
static activeDocument: TextDocument | undefined = undefined;
/** Used in parsing of nested tasks. */
static activeDocumentTabSize = 4;
/** Editor line height (in px) */
static editorLineHeight = 20;
}
export const enum Constants {
EXTENSION_NAME = 'todomd',
LAST_VISIT_BY_FILE_STORAGE_KEY = 'LAST_VISIT_BY_FILE_STORAGE_KEY',
tagsTreeViewId = 'todomd.tags',
projectsTreeViewId = 'todomd.projects',
contextsTreeViewId = 'todomd.contexts',
dueTreeViewId = 'todomd.due',
tasksTreeViewId = 'todomd.tasks',
archivedTreeViewId = 'todomd.archived',
generic1TreeViewId = 'todomd.generic1',
generic2TreeViewId = 'todomd.generic2',
generic3TreeViewId = 'todomd.generic3',
defaultFileSetting = 'todomd.defaultFile',
defaultArchiveFileSetting = 'todomd.defaultArchiveFile',
THROTTLE_EVERYTHING = 120,
}
export let extensionConfig = workspace.getConfiguration().get(Constants.EXTENSION_NAME) as ExtensionConfig;
export const statusBar = new StatusBar();
/**
* Global vscode variables (mostly disposables)
*/
export class Global {
static webviewProvider: TasksWebviewViewProvider;
static tagAutocompleteDisposable: Disposable;
static projectAutocompleteDisposable: Disposable;
static contextAutocompleteDisposable: Disposable;
static generalAutocompleteDisposable: Disposable;
static specialTagsAutocompleteDisposable: Disposable;
static setDueDateAutocompleteDisposable: Disposable;
static hoverDisposable: Disposable;
static documentHighlightsDisposable: Disposable;
static renameProviderDisposable: Disposable;
static referenceProviderDisposable: Disposable;
static changeTextDocumentDisposable: Disposable;
static changeActiveTextEditorDisposable: Disposable;
static completedTaskDecorationType: TextEditorDecorationType;
static commentDecorationType: TextEditorDecorationType;
static priorityADecorationType: TextEditorDecorationType;
static priorityBDecorationType: TextEditorDecorationType;
static priorityCDecorationType: TextEditorDecorationType;
static priorityDDecorationType: TextEditorDecorationType;
static priorityEDecorationType: TextEditorDecorationType;
static priorityFDecorationType: TextEditorDecorationType;
static tagsDecorationType: TextEditorDecorationType;
static tagWithDelimiterDecorationType: TextEditorDecorationType;
static tagsDelimiterDecorationType: TextEditorDecorationType;
static specialTagDecorationType: TextEditorDecorationType;
static projectDecorationType: TextEditorDecorationType;
static contextDecorationType: TextEditorDecorationType;
static notDueDecorationType: TextEditorDecorationType;
static dueDecorationType: TextEditorDecorationType;
static overdueDecorationType: TextEditorDecorationType;
static invalidDueDateDecorationType: TextEditorDecorationType;
static closestDueDateDecorationType: TextEditorDecorationType;
static nestedTasksCountDecorationType: TextEditorDecorationType;
static nestedTasksPieDecorationType: TextEditorDecorationType;
static userSpecifiedAdvancedTagDecorations: boolean;
}
export async function activate(extensionContext: ExtensionContext) {
extensionState.extensionContext = extensionContext;
const lastVisitByFile = extensionContext.globalState.get<typeof extensionState['lastVisitByFile'] | undefined>(Constants.LAST_VISIT_BY_FILE_STORAGE_KEY);
extensionState.lastVisitByFile = lastVisitByFile ? lastVisitByFile : {};
extensionState.editorLineHeight = getEditorLineHeight();
updateEditorDecorationStyle();
updateUserSuggestItems();
registerAllCommands();
createAllTreeViews();
const defaultFileDocument = await getDocumentForDefaultFile();
if (defaultFileDocument) {
const filePath = defaultFileDocument.uri.toString();
const needReset = checkIfNeedResetRecurringTasks(filePath);
if (needReset) {
await resetAllRecurringTasks(defaultFileDocument, needReset.lastVisit);
await updateLastVisitGlobalState(filePath, new Date());
}
}
onChangeActiveTextEditor(window.activeTextEditor);// Trigger on change event at activation
await updateState();
Global.webviewProvider = new TasksWebviewViewProvider(extensionState.extensionContext.extensionUri);
extensionState.extensionContext.subscriptions.push(
window.registerWebviewViewProvider(TasksWebviewViewProvider.viewType, Global.webviewProvider),
);
updateAllTreeViews();
updateArchivedTasks();
updateIsDevContext();
/**
* The event is fired twice quickly when closing an editor, also when swtitching to untitled file ???
*/
Global.changeActiveTextEditorDisposable = window.onDidChangeActiveTextEditor(throttle(onChangeActiveTextEditor, 20, {
leading: false,
}));
function onConfigChange(e: ConfigurationChangeEvent) {
if (!e.affectsConfiguration(Constants.EXTENSION_NAME)) {
return;
}
updateConfig();
}
function updateConfig() {
extensionConfig = workspace.getConfiguration().get(Constants.EXTENSION_NAME) as ExtensionConfig;
disposeEditorDisposables();
extensionState.editorLineHeight = getEditorLineHeight();
updateEditorDecorationStyle();
updateUserSuggestItems();
onChangeActiveTextEditor(window.activeTextEditor);
updateIsDevContext();
}
function updateIsDevContext() {
if (process.env.NODE_ENV === 'development' || extensionConfig.isDev) {
setContext(VscodeContext.isDev, true);
}
}
extensionContext.subscriptions.push(workspace.onDidChangeConfiguration(onConfigChange));
}
/**
* Update primary `state` properties, such as `tasks` or `tags`, based on provided document or based on default file
*/
export async function updateState() {
let document = await getActiveDocument();
if (!document) {
document = await getDocumentForDefaultFile();
}
if (!document) {
extensionState.tasks = [];
extensionState.tasksAsTree = [];
extensionState.tags = [];
extensionState.projects = [];
extensionState.contexts = [];
extensionState.tagsForTreeView = [];
extensionState.projectsForTreeView = [];
extensionState.contextsForTreeView = [];
extensionState.commentLines = [];
extensionState.theRightFileOpened = false;
extensionState.activeDocument = undefined;
return;
}
const parsedDocument = await parseDocument(document);
extensionState.tasks = parsedDocument.tasks;
extensionState.tasksAsTree = parsedDocument.tasksAsTree;
extensionState.commentLines = parsedDocument.commentLines;
const treeItems = groupAndSortTreeItems(extensionState.tasksAsTree);
extensionState.tagsForTreeView = treeItems.tagsForProvider;
extensionState.projectsForTreeView = treeItems.projectsForProvider;
extensionState.contextsForTreeView = treeItems.contextsForProvider;
extensionState.tags = treeItems.tags;
extensionState.projects = treeItems.projects;
extensionState.contexts = treeItems.contexts;
}
function disposeEditorDisposables() {
if (Global.completedTaskDecorationType) {
// if one set - that means that all decorations are set
Global.completedTaskDecorationType.dispose();
Global.commentDecorationType.dispose();
Global.priorityADecorationType.dispose();
Global.priorityBDecorationType.dispose();
Global.priorityCDecorationType.dispose();
Global.priorityDDecorationType.dispose();
Global.priorityEDecorationType.dispose();
Global.priorityFDecorationType.dispose();
Global.tagsDecorationType.dispose();
Global.tagWithDelimiterDecorationType.dispose();
Global.tagsDelimiterDecorationType.dispose();
Global.specialTagDecorationType.dispose();
Global.projectDecorationType.dispose();
Global.contextDecorationType.dispose();
Global.notDueDecorationType.dispose();
Global.dueDecorationType.dispose();
Global.overdueDecorationType.dispose();
Global.invalidDueDateDecorationType.dispose();
Global.closestDueDateDecorationType.dispose();
Global.nestedTasksCountDecorationType.dispose();
Global.nestedTasksPieDecorationType.dispose();
}
if (Global.changeTextDocumentDisposable) {
Global.changeTextDocumentDisposable.dispose();
}
}
/**
* Update global storage value of last visit by file
*/
export async function updateLastVisitGlobalState(stringUri: string, date: Date) {
extensionState.lastVisitByFile[stringUri] = date;
await extensionState.extensionContext.globalState.update(Constants.LAST_VISIT_BY_FILE_STORAGE_KEY, extensionState.lastVisitByFile);
}
export function deactivate() {
disposeEditorDisposables();
Global.tagAutocompleteDisposable.dispose();
Global.projectAutocompleteDisposable.dispose();
Global.contextAutocompleteDisposable.dispose();
Global.generalAutocompleteDisposable.dispose();
Global.specialTagsAutocompleteDisposable.dispose();
Global.setDueDateAutocompleteDisposable.dispose();
Global.changeTextDocumentDisposable.dispose();
Global.hoverDisposable.dispose();
Global.documentHighlightsDisposable.dispose();
Global.renameProviderDisposable.dispose();
Global.referenceProviderDisposable.dispose();
Global.changeActiveTextEditorDisposable.dispose();
} | the_stack |
import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types";
/**
* <p>You do not have permission to perform this action.</p>
*/
export interface AccessDeniedException extends __SmithyException, $MetadataBearer {
name: "AccessDeniedException";
$fault: "client";
message?: string;
}
export namespace AccessDeniedException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: AccessDeniedException): any => ({
...obj,
});
}
export interface DeleteReportDefinitionRequest {
/**
* <p>Required. ID of the report to delete.</p>
*/
reportId: string | undefined;
}
export namespace DeleteReportDefinitionRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DeleteReportDefinitionRequest): any => ({
...obj,
});
}
export interface DeleteReportDefinitionResult {
/**
* <p>ID of the report that was deleted.</p>
*/
reportId?: string;
}
export namespace DeleteReportDefinitionResult {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DeleteReportDefinitionResult): any => ({
...obj,
});
}
/**
* <p>An internal server error occurred. Retry your request.</p>
*/
export interface InternalServerException extends __SmithyException, $MetadataBearer {
name: "InternalServerException";
$fault: "server";
message?: string;
}
export namespace InternalServerException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InternalServerException): any => ({
...obj,
});
}
/**
* <p>The calls to AWS Application Cost Profiler API are throttled. The request was denied.</p>
*/
export interface ThrottlingException extends __SmithyException, $MetadataBearer {
name: "ThrottlingException";
$fault: "client";
message?: string;
}
export namespace ThrottlingException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ThrottlingException): any => ({
...obj,
});
}
/**
* <p>The input fails to satisfy the constraints for the API.</p>
*/
export interface ValidationException extends __SmithyException, $MetadataBearer {
name: "ValidationException";
$fault: "client";
message?: string;
}
export namespace ValidationException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ValidationException): any => ({
...obj,
});
}
export interface GetReportDefinitionRequest {
/**
* <p>ID of the report to retrieve.</p>
*/
reportId: string | undefined;
}
export namespace GetReportDefinitionRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetReportDefinitionRequest): any => ({
...obj,
});
}
/**
* <p>Represents the Amazon Simple Storage Service (Amazon S3) location where AWS Application Cost Profiler
* reports are generated and then written to.</p>
*/
export interface S3Location {
/**
* <p>Name of the S3 bucket.</p>
*/
bucket: string | undefined;
/**
* <p>Prefix for the location to write to.</p>
*/
prefix: string | undefined;
}
export namespace S3Location {
/**
* @internal
*/
export const filterSensitiveLog = (obj: S3Location): any => ({
...obj,
});
}
export enum Format {
CSV = "CSV",
PARQUET = "PARQUET",
}
export enum ReportFrequency {
ALL = "ALL",
DAILY = "DAILY",
MONTHLY = "MONTHLY",
}
export interface GetReportDefinitionResult {
/**
* <p>ID of the report retrieved.</p>
*/
reportId: string | undefined;
/**
* <p>Description of the report.</p>
*/
reportDescription: string | undefined;
/**
* <p>Cadence used to generate the report.</p>
*/
reportFrequency: ReportFrequency | string | undefined;
/**
* <p>Format of the generated report.</p>
*/
format: Format | string | undefined;
/**
* <p>Amazon Simple Storage Service (Amazon S3) location where the report is uploaded.</p>
*/
destinationS3Location: S3Location | undefined;
/**
* <p>Timestamp (milliseconds) when this report definition was created.</p>
*/
createdAt: Date | undefined;
/**
* <p>Timestamp (milliseconds) when this report definition was last updated.</p>
*/
lastUpdated: Date | undefined;
}
export namespace GetReportDefinitionResult {
/**
* @internal
*/
export const filterSensitiveLog = (obj: GetReportDefinitionResult): any => ({
...obj,
});
}
export enum S3BucketRegion {
AF_SOUTH_1 = "af-south-1",
AP_EAST_1 = "ap-east-1",
EU_SOUTH_1 = "eu-south-1",
ME_SOUTH_1 = "me-south-1",
}
/**
* <p>Represents the Amazon Simple Storage Service (Amazon S3) location where usage data is read
* from.</p>
*/
export interface SourceS3Location {
/**
* <p>Name of the bucket.</p>
*/
bucket: string | undefined;
/**
* <p>Key of the object.</p>
*/
key: string | undefined;
/**
* <p>Region of the bucket. Only required for Regions that are disabled by default.
* For more infomration about Regions that are disabled by default, see <a href="https://docs.aws.amazon.com/general/latest/gr/rande-manage.html#rande-manage-enable">
* Enabling a Region</a> in the <i>AWS General Reference guide</i>.</p>
*/
region?: S3BucketRegion | string;
}
export namespace SourceS3Location {
/**
* @internal
*/
export const filterSensitiveLog = (obj: SourceS3Location): any => ({
...obj,
});
}
export interface ImportApplicationUsageRequest {
/**
* <p>Amazon S3 location to import application usage data from.</p>
*/
sourceS3Location: SourceS3Location | undefined;
}
export namespace ImportApplicationUsageRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ImportApplicationUsageRequest): any => ({
...obj,
});
}
export interface ImportApplicationUsageResult {
/**
* <p>ID of the import request.</p>
*/
importId: string | undefined;
}
export namespace ImportApplicationUsageResult {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ImportApplicationUsageResult): any => ({
...obj,
});
}
export interface ListReportDefinitionsRequest {
/**
* <p>The token value from a previous call to access the next page of results.</p>
*/
nextToken?: string;
/**
* <p>The maximum number of results to return.</p>
*/
maxResults?: number;
}
export namespace ListReportDefinitionsRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListReportDefinitionsRequest): any => ({
...obj,
});
}
/**
* <p>The configuration of a report in AWS Application Cost Profiler.</p>
*/
export interface ReportDefinition {
/**
* <p>The ID of the report.</p>
*/
reportId?: string;
/**
* <p>Description of the report</p>
*/
reportDescription?: string;
/**
* <p>The cadence at which the report is generated.</p>
*/
reportFrequency?: ReportFrequency | string;
/**
* <p>The format used for the generated reports.</p>
*/
format?: Format | string;
/**
* <p>The location in Amazon Simple Storage Service (Amazon S3) the reports should be saved to.</p>
*/
destinationS3Location?: S3Location;
/**
* <p>Timestamp (milliseconds) when this report definition was created.</p>
*/
createdAt?: Date;
/**
* <p>Timestamp (milliseconds) when this report definition was last updated.</p>
*/
lastUpdatedAt?: Date;
}
export namespace ReportDefinition {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ReportDefinition): any => ({
...obj,
});
}
export interface ListReportDefinitionsResult {
/**
* <p>The retrieved reports.</p>
*/
reportDefinitions?: ReportDefinition[];
/**
* <p>The value of the next token, if it exists. Null if there are no more results.</p>
*/
nextToken?: string;
}
export namespace ListReportDefinitionsResult {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListReportDefinitionsResult): any => ({
...obj,
});
}
export interface PutReportDefinitionRequest {
/**
* <p>Required. ID of the report. You can choose any valid string matching the pattern for the
* ID.</p>
*/
reportId: string | undefined;
/**
* <p>Required. Description of the report.</p>
*/
reportDescription: string | undefined;
/**
* <p>Required. The cadence to generate the report.</p>
*/
reportFrequency: ReportFrequency | string | undefined;
/**
* <p>Required. The format to use for the generated report.</p>
*/
format: Format | string | undefined;
/**
* <p>Required. Amazon Simple Storage Service (Amazon S3) location where Application Cost Profiler uploads the
* report.</p>
*/
destinationS3Location: S3Location | undefined;
}
export namespace PutReportDefinitionRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: PutReportDefinitionRequest): any => ({
...obj,
});
}
export interface PutReportDefinitionResult {
/**
* <p>ID of the report.</p>
*/
reportId?: string;
}
export namespace PutReportDefinitionResult {
/**
* @internal
*/
export const filterSensitiveLog = (obj: PutReportDefinitionResult): any => ({
...obj,
});
}
/**
* <p>Your request exceeds one or more of the service quotas.</p>
*/
export interface ServiceQuotaExceededException extends __SmithyException, $MetadataBearer {
name: "ServiceQuotaExceededException";
$fault: "client";
message?: string;
}
export namespace ServiceQuotaExceededException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ServiceQuotaExceededException): any => ({
...obj,
});
}
export interface UpdateReportDefinitionRequest {
/**
* <p>Required. ID of the report to update.</p>
*/
reportId: string | undefined;
/**
* <p>Required. Description of the report.</p>
*/
reportDescription: string | undefined;
/**
* <p>Required. The cadence to generate the report.</p>
*/
reportFrequency: ReportFrequency | string | undefined;
/**
* <p>Required. The format to use for the generated report.</p>
*/
format: Format | string | undefined;
/**
* <p>Required. Amazon Simple Storage Service (Amazon S3) location where Application Cost Profiler uploads the
* report.</p>
*/
destinationS3Location: S3Location | undefined;
}
export namespace UpdateReportDefinitionRequest {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateReportDefinitionRequest): any => ({
...obj,
});
}
export interface UpdateReportDefinitionResult {
/**
* <p>ID of the report.</p>
*/
reportId?: string;
}
export namespace UpdateReportDefinitionResult {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UpdateReportDefinitionResult): any => ({
...obj,
});
} | the_stack |
import { IExpressionHydrator } from '@aurelia/runtime';
import * as AST from '@aurelia/runtime';
enum ASTExpressionTypes {
BindingBehaviorExpression = 'BindingBehaviorExpression',
ValueConverterExpression = 'ValueConverterExpression',
AssignExpression = 'AssignExpression',
ConditionalExpression = 'ConditionalExpression',
AccessThisExpression = 'AccessThisExpression',
AccessScopeExpression = 'AccessScopeExpression',
AccessMemberExpression = 'AccessMemberExpression',
AccessKeyedExpression = 'AccessKeyedExpression',
CallScopeExpression = 'CallScopeExpression',
CallMemberExpression = 'CallMemberExpression',
CallFunctionExpression = 'CallFunctionExpression',
BinaryExpression = 'BinaryExpression',
UnaryExpression = 'UnaryExpression',
PrimitiveLiteralExpression = 'PrimitiveLiteralExpression',
ArrayLiteralExpression = 'ArrayLiteralExpression',
ObjectLiteralExpression = 'ObjectLiteralExpression',
TemplateExpression = 'TemplateExpression',
TaggedTemplateExpression = 'TaggedTemplateExpression',
ArrayBindingPattern = 'ArrayBindingPattern',
ObjectBindingPattern = 'ObjectBindingPattern',
BindingIdentifier = 'BindingIdentifier',
ForOfStatement = 'ForOfStatement',
Interpolation = 'Interpolation',
DestructuringAssignment = 'DestructuringAssignment',
DestructuringSingleAssignment = 'DestructuringSingleAssignment',
DestructuringRestAssignment = 'DestructuringRestAssignment',
}
export class Deserializer implements IExpressionHydrator {
public static deserialize(serializedExpr: string): AST.IsExpressionOrStatement {
const deserializer = new Deserializer();
const raw = JSON.parse(serializedExpr);
return deserializer.hydrate(raw);
}
public hydrate(raw: any): any {
switch (raw.$TYPE) {
case ASTExpressionTypes.AccessMemberExpression: {
const expr: Pick<AST.AccessMemberExpression, 'object' | 'name'> = raw;
return new AST.AccessMemberExpression(this.hydrate(expr.object), expr.name);
}
case ASTExpressionTypes.AccessKeyedExpression: {
const expr: Pick<AST.AccessKeyedExpression, 'object' | 'key'> = raw;
return new AST.AccessKeyedExpression(this.hydrate(expr.object), this.hydrate(expr.key));
}
case ASTExpressionTypes.AccessThisExpression: {
const expr: Pick<AST.AccessThisExpression, 'ancestor'> = raw;
return new AST.AccessThisExpression(expr.ancestor);
}
case ASTExpressionTypes.AccessScopeExpression: {
const expr: Pick<AST.AccessScopeExpression, 'name' | 'ancestor'> = raw;
return new AST.AccessScopeExpression(expr.name, expr.ancestor);
}
case ASTExpressionTypes.ArrayLiteralExpression: {
const expr: Pick<AST.ArrayLiteralExpression, 'elements'> = raw;
return new AST.ArrayLiteralExpression(this.hydrate(expr.elements));
}
case ASTExpressionTypes.ObjectLiteralExpression: {
const expr: Pick<AST.ObjectLiteralExpression, 'keys' | 'values'> = raw;
return new AST.ObjectLiteralExpression(this.hydrate(expr.keys), this.hydrate(expr.values));
}
case ASTExpressionTypes.PrimitiveLiteralExpression: {
const expr: Pick<AST.PrimitiveLiteralExpression, 'value'> = raw;
return new AST.PrimitiveLiteralExpression(this.hydrate(expr.value));
}
case ASTExpressionTypes.CallFunctionExpression: {
const expr: Pick<AST.CallFunctionExpression, 'func' | 'args'> = raw;
return new AST.CallFunctionExpression(this.hydrate(expr.func), this.hydrate(expr.args));
}
case ASTExpressionTypes.CallMemberExpression: {
const expr: Pick<AST.CallMemberExpression, 'object' | 'name' | 'args'> = raw;
return new AST.CallMemberExpression(this.hydrate(expr.object), expr.name, this.hydrate(expr.args));
}
case ASTExpressionTypes.CallScopeExpression: {
const expr: Pick<AST.CallScopeExpression, 'name' | 'args' | 'ancestor'> = raw;
return new AST.CallScopeExpression(expr.name, this.hydrate(expr.args), expr.ancestor);
}
case ASTExpressionTypes.TemplateExpression: {
const expr: Pick<AST.TemplateExpression, 'cooked' | 'expressions'> = raw;
return new AST.TemplateExpression(this.hydrate(expr.cooked), this.hydrate(expr.expressions));
}
case ASTExpressionTypes.TaggedTemplateExpression: {
const expr: Pick<AST.TaggedTemplateExpression, 'cooked' | 'func' | 'expressions'> & {
raw: any;
} = raw;
return new AST.TaggedTemplateExpression(this.hydrate(expr.cooked), this.hydrate(expr.raw), this.hydrate(expr.func), this.hydrate(expr.expressions));
}
case ASTExpressionTypes.UnaryExpression: {
const expr: Pick<AST.UnaryExpression, 'operation' | 'expression'> = raw;
return new AST.UnaryExpression(expr.operation, this.hydrate(expr.expression));
}
case ASTExpressionTypes.BinaryExpression: {
const expr: Pick<AST.BinaryExpression, 'operation' | 'left' | 'right'> = raw;
return new AST.BinaryExpression(expr.operation, this.hydrate(expr.left), this.hydrate(expr.right));
}
case ASTExpressionTypes.ConditionalExpression: {
const expr: Pick<AST.ConditionalExpression, 'condition' | 'yes' | 'no'> = raw;
return new AST.ConditionalExpression(this.hydrate(expr.condition), this.hydrate(expr.yes), this.hydrate(expr.no));
}
case ASTExpressionTypes.AssignExpression: {
const expr: Pick<AST.AssignExpression, 'target' | 'value'> = raw;
return new AST.AssignExpression(this.hydrate(expr.target), this.hydrate(expr.value));
}
case ASTExpressionTypes.ValueConverterExpression: {
const expr: Pick<AST.ValueConverterExpression, 'expression' | 'name' | 'args'> = raw;
return new AST.ValueConverterExpression(this.hydrate(expr.expression), expr.name, this.hydrate(expr.args));
}
case ASTExpressionTypes.BindingBehaviorExpression: {
const expr: Pick<AST.BindingBehaviorExpression, 'expression' | 'name' | 'args'> = raw;
return new AST.BindingBehaviorExpression(this.hydrate(expr.expression), expr.name, this.hydrate(expr.args));
}
case ASTExpressionTypes.ArrayBindingPattern: {
const expr: Pick<AST.ArrayBindingPattern, 'elements'> = raw;
return new AST.ArrayBindingPattern(this.hydrate(expr.elements));
}
case ASTExpressionTypes.ObjectBindingPattern: {
const expr: Pick<AST.ObjectBindingPattern, 'keys' | 'values'> = raw;
return new AST.ObjectBindingPattern(this.hydrate(expr.keys), this.hydrate(expr.values));
}
case ASTExpressionTypes.BindingIdentifier: {
const expr: Pick<AST.BindingIdentifier, 'name'> = raw;
return new AST.BindingIdentifier(expr.name);
}
case ASTExpressionTypes.ForOfStatement: {
const expr: Pick<AST.ForOfStatement, 'declaration' | 'iterable'> = raw;
return new AST.ForOfStatement(this.hydrate(expr.declaration), this.hydrate(expr.iterable));
}
case ASTExpressionTypes.Interpolation: {
const expr: {
cooked: any;
expressions: any;
} = raw;
return new AST.Interpolation(this.hydrate(expr.cooked), this.hydrate(expr.expressions));
}
case ASTExpressionTypes.DestructuringAssignment: {
return new AST.DestructuringAssignmentExpression(this.hydrate(raw.$kind), this.hydrate(raw.list), this.hydrate(raw.source), this.hydrate(raw.initializer));
}
case ASTExpressionTypes.DestructuringSingleAssignment: {
return new AST.DestructuringAssignmentSingleExpression(this.hydrate(raw.target), this.hydrate(raw.source), this.hydrate(raw.initializer));
}
case ASTExpressionTypes.DestructuringRestAssignment: {
return new AST.DestructuringAssignmentRestExpression(this.hydrate(raw.target), this.hydrate(raw.indexOrProperties));
}
default:
if (Array.isArray(raw)) {
if (typeof raw[0] === 'object') {
return this.deserializeExpressions(raw);
} else {
return raw.map(deserializePrimitive);
}
} else if (typeof raw !== 'object') {
return deserializePrimitive(raw);
}
throw new Error(`unable to deserialize the expression: ${raw}`); // TODO use reporter/logger
}
}
private deserializeExpressions(exprs: unknown[]) {
const expressions: AST.IsExpressionOrStatement[] = [];
for (const expr of exprs) {
expressions.push(this.hydrate(expr));
}
return expressions;
}
}
export class Serializer implements AST.IVisitor<string> {
public static serialize(expr: AST.IsExpressionOrStatement): string {
const visitor = new Serializer();
if (expr == null || typeof expr.accept !== 'function') {
return `${expr}`;
}
return expr.accept(visitor);
}
public visitAccessMember(expr: AST.AccessMemberExpression): string {
return `{"$TYPE":"${ASTExpressionTypes.AccessMemberExpression}","name":"${expr.name}","object":${expr.object.accept(this)}}`;
}
public visitAccessKeyed(expr: AST.AccessKeyedExpression): string {
return `{"$TYPE":"${ASTExpressionTypes.AccessKeyedExpression}","object":${expr.object.accept(this)},"key":${expr.key.accept(this)}}`;
}
public visitAccessThis(expr: AST.AccessThisExpression): string {
return `{"$TYPE":"${ASTExpressionTypes.AccessThisExpression}","ancestor":${expr.ancestor}}`;
}
public visitAccessScope(expr: AST.AccessScopeExpression): string {
return `{"$TYPE":"${ASTExpressionTypes.AccessScopeExpression}","name":"${expr.name}","ancestor":${expr.ancestor}}`;
}
public visitArrayLiteral(expr: AST.ArrayLiteralExpression): string {
return `{"$TYPE":"${ASTExpressionTypes.ArrayLiteralExpression}","elements":${this.serializeExpressions(expr.elements)}}`;
}
public visitObjectLiteral(expr: AST.ObjectLiteralExpression): string {
return `{"$TYPE":"${ASTExpressionTypes.ObjectLiteralExpression}","keys":${serializePrimitives(expr.keys)},"values":${this.serializeExpressions(expr.values)}}`;
}
public visitPrimitiveLiteral(expr: AST.PrimitiveLiteralExpression): string {
return `{"$TYPE":"${ASTExpressionTypes.PrimitiveLiteralExpression}","value":${serializePrimitive(expr.value)}}`;
}
public visitCallFunction(expr: AST.CallFunctionExpression): string {
return `{"$TYPE":"${ASTExpressionTypes.CallFunctionExpression}","func":${expr.func.accept(this)},"args":${this.serializeExpressions(expr.args)}}`;
}
public visitCallMember(expr: AST.CallMemberExpression): string {
return `{"$TYPE":"${ASTExpressionTypes.CallMemberExpression}","name":"${expr.name}","object":${expr.object.accept(this)},"args":${this.serializeExpressions(expr.args)}}`;
}
public visitCallScope(expr: AST.CallScopeExpression): string {
return `{"$TYPE":"${ASTExpressionTypes.CallScopeExpression}","name":"${expr.name}","ancestor":${expr.ancestor},"args":${this.serializeExpressions(expr.args)}}`;
}
public visitTemplate(expr: AST.TemplateExpression): string {
return `{"$TYPE":"${ASTExpressionTypes.TemplateExpression}","cooked":${serializePrimitives(expr.cooked)},"expressions":${this.serializeExpressions(expr.expressions)}}`;
}
public visitTaggedTemplate(expr: AST.TaggedTemplateExpression): string {
return `{"$TYPE":"${ASTExpressionTypes.TaggedTemplateExpression}","cooked":${serializePrimitives(expr.cooked)},"raw":${serializePrimitives(expr.cooked.raw as readonly unknown[])},"func":${expr.func.accept(this)},"expressions":${this.serializeExpressions(expr.expressions)}}`;
}
public visitUnary(expr: AST.UnaryExpression): string {
return `{"$TYPE":"${ASTExpressionTypes.UnaryExpression}","operation":"${expr.operation}","expression":${expr.expression.accept(this)}}`;
}
public visitBinary(expr: AST.BinaryExpression): string {
return `{"$TYPE":"${ASTExpressionTypes.BinaryExpression}","operation":"${expr.operation}","left":${expr.left.accept(this)},"right":${expr.right.accept(this)}}`;
}
public visitConditional(expr: AST.ConditionalExpression): string {
return `{"$TYPE":"${ASTExpressionTypes.ConditionalExpression}","condition":${expr.condition.accept(this)},"yes":${expr.yes.accept(this)},"no":${expr.no.accept(this)}}`;
}
public visitAssign(expr: AST.AssignExpression): string {
return `{"$TYPE":"${ASTExpressionTypes.AssignExpression}","target":${expr.target.accept(this)},"value":${expr.value.accept(this)}}`;
}
public visitValueConverter(expr: AST.ValueConverterExpression): string {
return `{"$TYPE":"${ASTExpressionTypes.ValueConverterExpression}","name":"${expr.name}","expression":${expr.expression.accept(this)},"args":${this.serializeExpressions(expr.args)}}`;
}
public visitBindingBehavior(expr: AST.BindingBehaviorExpression): string {
return `{"$TYPE":"${ASTExpressionTypes.BindingBehaviorExpression}","name":"${expr.name}","expression":${expr.expression.accept(this)},"args":${this.serializeExpressions(expr.args)}}`;
}
public visitArrayBindingPattern(expr: AST.ArrayBindingPattern): string {
return `{"$TYPE":"${ASTExpressionTypes.ArrayBindingPattern}","elements":${this.serializeExpressions(expr.elements)}}`;
}
public visitObjectBindingPattern(expr: AST.ObjectBindingPattern): string {
return `{"$TYPE":"${ASTExpressionTypes.ObjectBindingPattern}","keys":${serializePrimitives(expr.keys)},"values":${this.serializeExpressions(expr.values)}}`;
}
public visitBindingIdentifier(expr: AST.BindingIdentifier): string {
return `{"$TYPE":"${ASTExpressionTypes.BindingIdentifier}","name":"${expr.name}"}`;
}
public visitHtmlLiteral(_expr: AST.HtmlLiteralExpression): string { throw new Error('visitHtmlLiteral'); }
public visitForOfStatement(expr: AST.ForOfStatement): string {
return `{"$TYPE":"${ASTExpressionTypes.ForOfStatement}","declaration":${expr.declaration.accept(this)},"iterable":${expr.iterable.accept(this)}}`;
}
public visitInterpolation(expr: AST.Interpolation): string {
return `{"$TYPE":"${ASTExpressionTypes.Interpolation}","cooked":${serializePrimitives(expr.parts)},"expressions":${this.serializeExpressions(expr.expressions)}}`;
}
public visitDestructuringAssignmentExpression(expr: AST.DestructuringAssignmentExpression): string {
return `{"$TYPE":"${ASTExpressionTypes.DestructuringAssignment}","$kind":${serializePrimitive(expr.$kind)},"list":${this.serializeExpressions(expr.list)},"source":${expr.source === void 0 ? serializePrimitive(expr.source) : expr.source.accept(this)},"initializer":${expr.initializer === void 0 ? serializePrimitive(expr.initializer) : expr.initializer.accept(this)}}`;
}
public visitDestructuringAssignmentSingleExpression(expr: AST.DestructuringAssignmentSingleExpression): string {
return `{"$TYPE":"${ASTExpressionTypes.DestructuringSingleAssignment}","source":${expr.source.accept(this)},"target":${expr.target.accept(this)},"initializer":${expr.initializer === void 0 ? serializePrimitive(expr.initializer) : expr.initializer.accept(this)}}`;
}
public visitDestructuringAssignmentRestExpression(expr: AST.DestructuringAssignmentRestExpression): string {
return `{"$TYPE":"${ASTExpressionTypes.DestructuringRestAssignment}","target":${expr.target.accept(this)},"indexOrProperties":${Array.isArray(expr.indexOrProperties) ? serializePrimitives(expr.indexOrProperties) : serializePrimitive(expr.indexOrProperties)}}`;
}
private serializeExpressions(args: readonly AST.IsExpressionOrStatement[]): string {
let text = '[';
for (let i = 0, ii = args.length; i < ii; ++i) {
if (i !== 0) {
text += ',';
}
text += args[i].accept(this);
}
text += ']';
return text;
}
}
export function serializePrimitives(values: readonly unknown[]): string {
let text = '[';
for (let i = 0, ii = values.length; i < ii; ++i) {
if (i !== 0) {
text += ',';
}
text += serializePrimitive(values[i]);
}
text += ']';
return text;
}
export function serializePrimitive(value: unknown): string {
if (typeof value === 'string') {
return `"\\"${escapeString(value)}\\""`;
} else if (value == null) {
return `"${value}"`;
} else {
return `${value}`;
}
}
function escapeString(str: string): string {
let ret = '';
for (let i = 0, ii = str.length; i < ii; ++i) {
ret += escape(str.charAt(i));
}
return ret;
}
function escape(ch: string): string {
switch (ch) {
case '\b': return '\\b';
case '\t': return '\\t';
case '\n': return '\\n';
case '\v': return '\\v';
case '\f': return '\\f';
case '\r': return '\\r';
case '"': return '\\"';
// case '\'': return '\\\''; /* when used in serialization context, escaping `'` (single quote) is not needed as the string is wrapped in a par of `"` (double quote) */
case '\\': return '\\\\';
default: return ch;
}
}
export function deserializePrimitive(value: unknown): any {
if (typeof value === 'string') {
if (value === 'null') { return null; }
if (value === 'undefined') { return undefined; }
return value.substring(1, value.length - 1);
} else {
return value;
}
} | the_stack |
import * as events from "events";
import {defaultAttributes, createChar, Char} from "./Char";
import * as i from "./Interfaces";
import * as e from "./Enums";
import {List} from "immutable";
import {Color, Weight, Brightness, KeyCode, LogLevel, BufferType, ScreenMode} from "./Enums";
import {Attributes, TerminalLikeDevice, ColorCode} from "./Interfaces";
import {print, error, info, csi, times} from "./utils/Common";
import * as _ from "lodash";
const ansiParserConstructor: typeof AnsiParser = require("node-ansiparser");
interface HandlerResult {
status: string;
description: string;
longDescription?: string;
url: string;
}
interface SavedState {
cursorRowIndex: number;
cursorColumnIndex: number;
attributes: i.Attributes;
designatedCharacterSets: DesignatedCharacterSets;
selectedCharacterSet: SelectedCharacterSet;
}
/**
* @link http://vt100.net/docs/vt220-rm/chapter4.html
*/
enum CharacterSets {
ASCIIGraphics,
SupplementalGraphics,
}
interface DesignatedCharacterSets {
G0: CharacterSets;
G1: CharacterSets;
G2: CharacterSets;
G3: CharacterSets;
}
type SelectedCharacterSet = keyof DesignatedCharacterSets;
function or1(value: number | undefined) {
if (value === undefined) {
return 1;
} else {
return value;
}
}
function logPosition(buffer: Buffer) {
const position = {rowIndex: buffer.cursorRowIndex, columnIndex: buffer.cursorColumnIndex};
const char = buffer.at(position);
const value = char ? char.value : "NULL";
info(`%crow: ${position.rowIndex + 1}\tcolumn: ${buffer.cursorColumnIndex + 1}\t value: ${value}, rows: ${buffer.size}`, "color: grey");
}
/**
* Copied from xterm.js
* @link https://github.com/sourcelair/xterm.js/blob/master/src/Charsets.ts
*/
const graphicCharset: Dictionary<string> = {
"`": "\u25c6", // "◆"
"a": "\u2592", // "▒"
"b": "\u0009", // "\t"
"c": "\u000c", // "\f"
"d": "\u000d", // "\r"
"e": "\u000a", // "\n"
"f": "\u00b0", // "°"
"g": "\u00b1", // "±"
"h": "\u2424", // "\u2424" (NL)
"i": "\u000b", // "\v"
"j": "\u2518", // "┘"
"k": "\u2510", // "┐"
"l": "\u250c", // "┌"
"m": "\u2514", // "└"
"n": "\u253c", // "┼"
"o": "\u23ba", // "⎺"
"p": "\u23bb", // "⎻"
"q": "\u2500", // "─"
"r": "\u23bc", // "⎼"
"s": "\u23bd", // "⎽"
"t": "\u251c", // "├"
"u": "\u2524", // "┤"
"v": "\u2534", // "┴"
"w": "\u252c", // "┬"
"x": "\u2502", // "│"
"y": "\u2264", // "≤"
"z": "\u2265", // "≥"
"{": "\u03c0", // "π"
"|": "\u2260", // "≠"
"}": "\u00a3", // "£"
"~": "\u00b7", // "·"
};
const SGR: { [indexer: string]: (attributes: Attributes) => Attributes } = {
0: (_attributes: Attributes) => defaultAttributes,
1: (attributes: Attributes) => ({...attributes, brightness: Brightness.Bright}),
2: (attributes: Attributes) => ({...attributes, weight: Weight.Faint}),
4: (attributes: Attributes) => ({...attributes, underline: true}),
7: (attributes: Attributes) => ({...attributes, inverse: true}),
22: (attributes: Attributes) => ({...attributes, weight: Weight.Normal}),
24: (attributes: Attributes) => ({...attributes, underline: false}),
27: (attributes: Attributes) => ({...attributes, inverse: false}),
30: (attributes: Attributes) => ({...attributes, color: <ColorCode>Color.Black}),
31: (attributes: Attributes) => ({...attributes, color: <ColorCode>Color.Red}),
32: (attributes: Attributes) => ({...attributes, color: <ColorCode>Color.Green}),
33: (attributes: Attributes) => ({...attributes, color: <ColorCode>Color.Yellow}),
34: (attributes: Attributes) => ({...attributes, color: <ColorCode>Color.Blue}),
35: (attributes: Attributes) => ({...attributes, color: <ColorCode>Color.Magenta}),
36: (attributes: Attributes) => ({...attributes, color: <ColorCode>Color.Cyan}),
37: (attributes: Attributes) => ({...attributes, color: <ColorCode>Color.White}),
39: (attributes: Attributes) => ({...attributes, color: <ColorCode>Color.White}),
40: (attributes: Attributes) => ({...attributes, backgroundColor: <ColorCode>Color.Black}),
41: (attributes: Attributes) => ({...attributes, backgroundColor: <ColorCode>Color.Red}),
42: (attributes: Attributes) => ({...attributes, backgroundColor: <ColorCode>Color.Green}),
43: (attributes: Attributes) => ({...attributes, backgroundColor: <ColorCode>Color.Yellow}),
44: (attributes: Attributes) => ({...attributes, backgroundColor: <ColorCode>Color.Blue}),
45: (attributes: Attributes) => ({...attributes, backgroundColor: <ColorCode>Color.Magenta}),
46: (attributes: Attributes) => ({...attributes, backgroundColor: <ColorCode>Color.Cyan}),
47: (attributes: Attributes) => ({...attributes, backgroundColor: <ColorCode>Color.White}),
49: (attributes: Attributes) => ({...attributes, backgroundColor: <ColorCode>Color.Black}),
90: (attributes: Attributes) => ({...attributes, brightness: Brightness.Bright, color: <ColorCode>Color.Black}),
91: (attributes: Attributes) => ({...attributes, brightness: Brightness.Bright, color: <ColorCode>Color.Red}),
92: (attributes: Attributes) => ({...attributes, brightness: Brightness.Bright, color: <ColorCode>Color.Green}),
93: (attributes: Attributes) => ({...attributes, brightness: Brightness.Bright, color: <ColorCode>Color.Yellow}),
94: (attributes: Attributes) => ({...attributes, brightness: Brightness.Bright, color: <ColorCode>Color.Blue}),
95: (attributes: Attributes) => ({...attributes, brightness: Brightness.Bright, color: <ColorCode>Color.Magenta}),
96: (attributes: Attributes) => ({...attributes, brightness: Brightness.Bright, color: <ColorCode>Color.Cyan}),
97: (attributes: Attributes) => ({...attributes, brightness: Brightness.Bright, color: <ColorCode>Color.White}),
100: (attributes: Attributes) => ({...attributes, brightness: Brightness.Bright, backgroundColor: <ColorCode>Color.Black}),
101: (attributes: Attributes) => ({...attributes, brightness: Brightness.Bright, backgroundColor: <ColorCode>Color.Red}),
102: (attributes: Attributes) => ({...attributes, brightness: Brightness.Bright, backgroundColor: <ColorCode>Color.Green}),
103: (attributes: Attributes) => ({...attributes, brightness: Brightness.Bright, backgroundColor: <ColorCode>Color.Yellow}),
104: (attributes: Attributes) => ({...attributes, brightness: Brightness.Bright, backgroundColor: <ColorCode>Color.Blue}),
105: (attributes: Attributes) => ({...attributes, brightness: Brightness.Bright, backgroundColor: <ColorCode>Color.Magenta}),
106: (attributes: Attributes) => ({...attributes, brightness: Brightness.Bright, backgroundColor: <ColorCode>Color.Cyan}),
107: (attributes: Attributes) => ({...attributes, brightness: Brightness.Bright, backgroundColor: <ColorCode>Color.White}),
};
const CSI = {
erase: {
toEnd: 0,
toBeginning: 1,
entire: 2,
entireSsh: 3,
},
};
const colorFormatCodes = {
format8bit: 5,
formatTrueColor: 2,
};
export class Output extends events.EventEmitter {
public activeBufferType = e.BufferType.Normal;
public isCursorKeysModeSet = false;
public screenMode = ScreenMode.Dark;
private normalBuffer: Buffer;
private alternateBuffer: Buffer;
private parser: AnsiParser;
constructor(private terminalDevice: TerminalLikeDevice, public dimensions: Dimensions) {
super();
this.normalBuffer = new Buffer(this, 200);
this.alternateBuffer = new Buffer(this, 0);
this.parser = new ansiParserConstructor({
inst_p: (text: string) => {
info("text", text, text.split("").map(letter => letter.charCodeAt(0)));
for (let i = 0; i !== text.length; ++i) {
this.activeBuffer.writeOne(text.charAt(i));
}
logPosition(this.activeBuffer);
},
inst_o: function (s: any) {
error("osc", s);
},
inst_x: (flag: string) => {
this.activeBuffer.writeOne(flag);
print((KeyCode[flag.charCodeAt(0)] ? LogLevel.Log : LogLevel.Error), ["char", flag.split("").map((_, index) => flag.charCodeAt(index))]);
logPosition(this.activeBuffer);
},
/**
* CSI handler.
*/
inst_c: (collected: any, params: Array<number>, flag: string) => {
let handlerResult: HandlerResult;
if (collected === "?") {
if (params.length !== 1) {
return error(`CSI private mode has ${params.length} parameters: ${params}`);
}
if (flag !== "h" && flag !== "l") {
return error(`CSI private mode has an incorrect flag: ${flag}`);
}
const mode = params[0];
handlerResult = this.decPrivateModeHandler(mode, flag);
if (handlerResult.status === "handled") {
info(`%cCSI ? ${mode} ${flag}`, "color: blue", handlerResult.description, handlerResult.url);
} else {
error(`%cCSI ? ${mode} ${flag}`, "color: blue", handlerResult.description, handlerResult.url);
}
} else {
handlerResult = this.csiHandler(collected, params, flag);
if (handlerResult.status === "handled") {
info(`%cCSI ${params} ${flag}`, "color: blue", handlerResult.description, handlerResult.url);
} else {
error(`%cCSI ${params} ${flag}`, "color: blue", handlerResult.description, handlerResult.url);
}
}
logPosition(this.activeBuffer);
},
/**
* ESC handler.
*/
inst_e: (collected: any, flag: string) => {
const handlerResult = this.escapeHandler(collected, flag);
if (handlerResult.status === "handled") {
info(`%cESC ${collected} ${flag}`, "color: blue", handlerResult.description, handlerResult.url);
} else {
error(`%cESC ${collected} ${flag}`, "color: blue", handlerResult.description, handlerResult.url);
}
logPosition(this.activeBuffer);
},
});
}
write(ansiString: string) {
this.parser.parse(ansiString);
this.emit("data");
}
toLines() {
return this.activeBuffer.toLines();
}
toString(): string {
return this.toLines().join("\n");
}
isEmpty(): boolean {
return this.activeBuffer.size === 0;
}
get activeBuffer() {
if (this.activeBufferType === e.BufferType.Normal) {
return this.normalBuffer;
} else {
return this.alternateBuffer;
}
}
private escapeHandler(collected: any, flag: string) {
let short = "";
let long = "";
let url = "";
let status = "handled";
if (collected) {
if (collected === "#" && flag === "8") {
short = "DEC Screen Alignment Test (DECALN).";
url = "http://www.vt100.net/docs/vt510-rm/DECALN";
const dimensions = this.activeBuffer.dimensions;
for (let i = 0; i !== dimensions.rows; ++i) {
this.activeBuffer.moveCursorAbsolute({rowIndex: i, columnIndex: 0});
this.write(Array(dimensions.columns).join("E"));
}
this.activeBuffer.moveCursorAbsolute({rowIndex: 0, columnIndex: 0});
} else if (collected === "(" && flag === "0") {
short = "Designate Graphic Charset to G0";
this.activeBuffer.designatedCharacterSets.G0 = CharacterSets.SupplementalGraphics;
} else if (collected === "(" && flag === "B") {
short = "Designate ASCII Charset to G0";
this.activeBuffer.designatedCharacterSets.G0 = CharacterSets.ASCIIGraphics;
} else if (collected === ")" && flag === "0") {
short = "Designate Graphic Charset to G1";
this.activeBuffer.designatedCharacterSets.G1 = CharacterSets.SupplementalGraphics;
} else if (collected === ")" && flag === "B") {
short = "Designate ASCII Charset to G1";
this.activeBuffer.designatedCharacterSets.G1 = CharacterSets.ASCIIGraphics;
} else {
status = "unhandled";
}
} else {
switch (flag) {
case "A":
short = "Cursor up.";
this.activeBuffer.moveCursorRelative({vertical: -1});
break;
case "B":
short = "Cursor down.";
this.activeBuffer.moveCursorRelative({vertical: 1});
break;
case "C":
short = "Cursor right.";
this.activeBuffer.moveCursorRelative({horizontal: 1});
break;
case "D":
short = "Index (IND).";
url = "http://www.vt100.net/docs/vt510-rm/IND";
this.activeBuffer.moveCursorRelative({vertical: 1});
break;
case "H":
short = "Horizontal Tab Set (HTS).";
url = "http://www.vt100.net/docs/vt510-rm/HTS";
this.activeBuffer.setTabStop();
break;
case "M":
short = "Reverse Index (RI).";
/* tslint:disable:max-line-length */
long = "Move the active position to the same horizontal position on the preceding line if the active position is at the top margin, a scroll down is performed.";
if (this.activeBuffer.cursorRowIndex === this.activeBuffer.marginTop) {
this.activeBuffer.scrollDown(1);
} else {
this.activeBuffer.moveCursorRelative({vertical: -1});
}
break;
case "E":
short = "Next Line (NEL).";
/* tslint:disable:max-line-length */
long = "This sequence causes the active position to move to the first position on the next line downward. If the active position is at the bottom margin, a scroll up is performed.";
this.activeBuffer.moveCursorRelative({vertical: 1});
this.activeBuffer.moveCursorAbsolute({columnIndex: 0});
break;
case "7":
long = "Save current state (cursor coordinates, attributes, character sets pointed at by G0, G1).";
this.activeBuffer.saveCurrentState();
break;
case "8":
long = "Restore state most recently saved by ESC 7.";
this.activeBuffer.restoreCurrentState();
break;
default:
status = "unhandled";
}
}
return {
status: status,
description: short,
longDescription: long,
url: url,
};
}
private decPrivateModeHandler(ps: number, flag: "h" | "l"): HandlerResult {
let description = "";
let url = "";
let status: "handled" | "unhandled" = "handled";
let shouldSet = flag === "h";
// noinspection FallThroughInSwitchStatementJS
switch (ps) {
case 1:
description = "Cursor Keys Mode.";
url = "http://www.vt100.net/docs/vt510-rm/DECCKM";
this.isCursorKeysModeSet = shouldSet;
break;
case 3:
url = "http://www.vt100.net/docs/vt510-rm/DECCOLM";
if (shouldSet) {
description = "132 Column Mode (DECCOLM).";
this.dimensions = {columns: 132, rows: this.activeBuffer.dimensions.rows};
} else {
description = "80 Column Mode (DECCOLM).";
this.dimensions = {columns: 80, rows: this.activeBuffer.dimensions.rows};
}
this.activeBuffer.clear();
// TODO
// If you change the DECCOLM setting, the terminal:
// Sets the left, right, top and bottom scrolling margins to their default positions.
// Erases all data in page memory.
// DECCOLM resets vertical split screen mode (DECLRMM) to unavailabl
// DECCOLM clears data from the status line if the status line is set to host-writabl
break;
case 5:
description = "Reverse Video (DECSCNM).";
url = "http://www.vt100.net/docs/vt510-rm/DECSCNM";
this.screenMode = (shouldSet ? ScreenMode.Light : ScreenMode.Dark);
break;
case 6:
description = "Origin Mode (DECOM).";
url = "http://www.vt100.net/docs/vt510-rm/DECOM";
this.activeBuffer.isOriginModeSet = shouldSet;
break;
case 7:
description = "Wraparound Mode (DECAWM).";
url = "http://www.vt100.net/docs/vt510-rm/DECAWM";
this.activeBuffer.isAutowrapModeSet = shouldSet;
break;
case 12:
if (shouldSet) {
description = "Start Blinking Cursor (att610).";
this.activeBuffer.blinkCursor(true);
} else {
description = "Stop Blinking Cursor (att610).";
this.activeBuffer.blinkCursor(false);
}
break;
case 25:
url = "http://www.vt100.net/docs/vt510-rm/DECTCEM";
if (shouldSet) {
description = "Show Cursor (DECTCEM).";
this.activeBuffer.showCursor(true);
} else {
description = "Hide Cursor (DECTCEM).";
this.activeBuffer.showCursor(false);
}
break;
case 1049:
if (shouldSet) {
/* tslint:disable:max-line-length */
description = "Save cursor as in DECSC and use Alternate Screen Buffer, clearing it first. (This may be disabled by the titeInhibit resource). This combines the effects of the 1047 and 1048 modes. Use this with terminfo-based applications rather than the 47 mod";
this.activeBufferType = BufferType.Alternate;
} else {
// TODO: Add Implementation
status = "unhandled";
}
break;
case 2004:
if (shouldSet) {
description = "Set bracketed paste mod";
} else {
// TODO: Add Implementation
status = "unhandled";
}
break;
default:
status = "unhandled";
}
return {
status: status,
description: description,
url: url,
};
}
private csiHandler(_collected: any, rawParams: number[] | number, flag: string): HandlerResult {
let short = "";
let long = "";
let url = "";
let status = "handled";
let params: number[] = Array.isArray(rawParams) ? rawParams : [];
const param: number = params[0] || 0;
switch (flag) {
case "A":
short = "Cursor Up Ps Times (default = 1) (CUU).";
this.activeBuffer.moveCursorRelative({vertical: -(param || 1)});
break;
case "B":
short = "Cursor Down Ps Times (default = 1) (CUD).";
this.activeBuffer.moveCursorRelative({vertical: (param || 1)});
break;
case "C":
short = "Cursor Forward Ps Times (default = 1) (CUF).";
this.activeBuffer.moveCursorRelative({horizontal: (param || 1)});
break;
case "D":
short = "Cursor Backward Ps Times (default = 1) (CUB).";
this.activeBuffer.moveCursorRelative({horizontal: -(param || 1)});
break;
// CSI Ps E Cursor Next Line Ps Times (default = 1) (CNL).
// CSI Ps F Cursor Preceding Line Ps Times (default = 1) (CPL).
case "G":
short = "Cursor Character Absolute [column] (default = [row,1]) (CHA)";
url = "http://www.vt100.net/docs/vt510-rm/CHA";
this.activeBuffer.moveCursorAbsolute({columnIndex: or1(param || 1) - 1});
break;
case "H":
short = "Cursor Position [row;column] (default = [1,1]) (CUP).";
url = "http://www.vt100.net/docs/vt510-rm/CUP";
this.activeBuffer.moveCursorAbsolute({rowIndex: or1(params[0]) - 1, columnIndex: or1(params[1]) - 1});
break;
case "J":
url = "http://www.vt100.net/docs/vt510-rm/ED";
switch (param) {
case CSI.erase.entire:
case CSI.erase.entireSsh:
short = "Erase Entire Display (ED).";
this.activeBuffer.clear();
break;
case CSI.erase.toEnd:
short = "Erase Display Below (ED).";
this.activeBuffer.clearToEnd();
break;
case CSI.erase.toBeginning:
short = "Erase Display Above (ED).";
this.activeBuffer.clearToBeginning();
break;
default:
throw `Unknown CSI erase: "${param}".`;
}
break;
case "K":
url = "http://www.vt100.net/docs/vt510-rm/DECSEL";
switch (param) {
case CSI.erase.entire:
short = "Erase the Line (DECSEL).";
this.activeBuffer.clearRow();
break;
case CSI.erase.toEnd:
short = "Erase Line to Right (DECSEL).";
this.activeBuffer.clearRowToEnd();
break;
case CSI.erase.toBeginning:
short = "Erase Line to Left (DECSEL).";
this.activeBuffer.clearRowToBeginning();
break;
default:
throw `Unknown CSI erase: "${param}".`;
}
break;
case "L":
url = "http://www.vt100.net/docs/vt510-rm/IL";
short = "Inserts one or more blank lines, starting at the cursor. (DL)";
this.activeBuffer.scrollDown(param || 1);
break;
case "M":
url = "http://www.vt100.net/docs/vt510-rm/DL";
short = "Deletes one or more lines in the scrolling region, starting with the line that has the cursor. (DL)";
this.activeBuffer.scrollUp(param || 1, this.activeBuffer.cursorRowIndex);
break;
case "P":
url = "http://www.vt100.net/docs/vt510-rm/DCH.html";
short = "Deletes one or more characters from the cursor position to the right.";
this.activeBuffer.deleteRight(param);
break;
case "X":
short = "Erase P s Character(s) (default = 1) (ECH)";
url = "http://www.vt100.net/docs/vt510-rm/ECH";
this.activeBuffer.eraseRight(param || 1);
break;
case "c":
short = "Send Device Attributes (Primary DA)";
this.terminalDevice.write("\x1b>1;2;");
break;
case "d":
short = "Line Position Absolute [row] (default = [1,column]) (VPA).";
url = "http://www.vt100.net/docs/vt510-rm/VPA";
this.activeBuffer.moveCursorAbsolute({rowIndex: or1(param || 1) - 1});
break;
case "f":
short = "Horizontal and Vertical Position [row;column] (default = [1,1]) (HVP).";
url = "http://www.vt100.net/docs/vt510-rm/HVP";
this.activeBuffer.moveCursorAbsolute({rowIndex: or1(params[0]) - 1, columnIndex: or1(params[1]) - 1});
break;
case "g":
url = "http://www.vt100.net/docs/vt510-rm/TBC";
switch (param) {
case 0:
short = "Clear Tab Stop At Current Column (TBC).";
this.activeBuffer.clearTabStop();
break;
case 3:
short = "Clear All Tab Stops (TBC).";
this.activeBuffer.clearAllTabStops();
break;
default:
error(`Unknown tab clear parameter "${param}", ignoring.`);
}
break;
case "m":
short = `SGR: ${params}`;
if (params.length === 0) {
short = "Reset SGR";
this.activeBuffer.resetAttributes();
break;
}
while (params.length !== 0) {
const sgr = params.shift()!;
if (sgr === 38 || sgr === 48) {
const colorFormat = params.shift();
if (colorFormat === colorFormatCodes.format8bit) {
const color = params.shift();
if (color) {
this.setColor(sgr, color);
} else {
error("sgr", sgr, colorFormat, params);
}
} else if (colorFormat === colorFormatCodes.formatTrueColor) {
this.setColor(sgr, params);
params = [];
} else {
error("sgr", sgr, colorFormat, params);
}
} else {
const attributesUpdater = SGR[sgr];
if (attributesUpdater) {
this.activeBuffer.setAttributes(attributesUpdater(this.activeBuffer.attributes));
} else {
error("sgr", sgr, params);
}
}
}
break;
case "n":
if (param === 6) {
url = "http://www.vt100.net/docs/vt510-rm/CPR";
short = "Report Cursor Position (CPR) [row;column] as CSI r ; c R";
this.terminalDevice.write(csi(`${this.activeBuffer.cursorRowIndex + 1};${this.activeBuffer.cursorColumnIndex + 1}R`));
} else {
status = "unhandled";
}
break;
case "r":
url = "http://www.vt100.net/docs/vt510-rm/DECSTBM";
short = "Set Scrolling Region [top;bottom] (default = full size of window) (DECSTBM).";
const top = <number>(params[0] ? params[0] - 1 : undefined);
const bottom = <number>(params[1] ? params[1] - 1 : undefined);
this.activeBuffer.margins = {top: top, bottom: bottom};
this.activeBuffer.moveCursorAbsolute({rowIndex: 0, columnIndex: 0});
break;
case "@":
url = "http://www.vt100.net/docs/vt510-rm/ICH.html";
short = "Inserts one or more space (SP) characters starting at the cursor position.";
this.activeBuffer.insertSpaceRight(param);
break;
default:
status = "unhandled";
}
return {
status: status,
description: short,
longDescription: long,
url: url,
};
}
private setColor(sgr: number, color: ColorCode): void {
if (sgr === 38) {
this.activeBuffer.setAttributes({...this.activeBuffer.attributes, color: color});
} else {
this.activeBuffer.setAttributes({...this.activeBuffer.attributes, backgroundColor: color});
}
}
}
class Buffer {
public cursorRowIndex = 0;
public cursorColumnIndex = 0;
public _showCursor = true;
public _blinkCursor = true;
public designatedCharacterSets: DesignatedCharacterSets = {
G0: CharacterSets.ASCIIGraphics,
G1: CharacterSets.ASCIIGraphics,
G2: CharacterSets.ASCIIGraphics,
G3: CharacterSets.ASCIIGraphics,
};
public selectedCharacterSet: SelectedCharacterSet = "G0";
public isOriginModeSet = false;
public isAutowrapModeSet = true;
private scrollback = List<List<Char>>();
private page = List<List<Char>>();
private _attributes: i.Attributes = {...defaultAttributes, color: e.Color.White, weight: e.Weight.Normal};
private _margins: Margins = {top: 0, left: 0};
private savedState: SavedState | undefined;
private tabStopIndices = _.range(8, 300, 8);
constructor(private output: Output, private maxScrollbackSize: number) {
this.ensureCursorRowExists();
}
map<T>(callback: (row: List<Char>, index: number) => T): T[] {
const result: T[] = [];
let index = 0;
this.scrollback.forEach(row => {
result.push(callback(row!, index));
++index;
});
this.page.forEach(row => {
result.push(callback(row!, index));
++index;
});
return result;
}
writeOne(char: string): void {
const charCode = char.charCodeAt(0);
/**
* Is a special symbol.
* TODO: take into account C1 and DELETE.
* @link http://www.asciitable.com/index/asciifull.gif
*/
if (charCode < 32) {
switch (charCode) {
case e.KeyCode.Bell:
break;
case e.KeyCode.Backspace:
this.moveCursorRelative({horizontal: -1});
break;
case e.KeyCode.Tab:
this.moveCursorAbsolute({columnIndex: this.nextTabStopIndex});
break;
case e.KeyCode.NewLine:
case e.KeyCode.VerticalTab:
if (this.cursorRowIndex === this._margins.bottom) {
this.scrollUp(1);
} else {
this.moveCursorRelative({vertical: 1});
}
break;
case e.KeyCode.CarriageReturn:
this.moveCursorAbsolute({columnIndex: 0});
break;
case e.KeyCode.ShiftIn:
this.selectedCharacterSet = "G0";
break;
case e.KeyCode.ShiftOut:
this.selectedCharacterSet = "G1";
break;
default:
error(`Couldn't write a special char with code ${charCode}.`);
}
} else {
const charFromCharset = this.charFromCharset(char);
const charObject = createChar(charFromCharset, this.attributes);
if (this.cursorColumnIndex === this.dimensions.columns) {
if (this.isAutowrapModeSet) {
this.moveCursorAbsolute({columnIndex: 0});
this.moveCursorRelative({vertical: 1});
} else {
this.moveCursorRelative({horizontal: -1});
}
}
this.set(charObject);
this.moveCursorRelative({horizontal: 1});
}
}
scrollDown(count: number) {
times(count, () => this.page = this.page.delete(this.marginBottom));
times(count, () => this.page = this.page.insert(this.cursorRowIndex, this.emptyLine));
}
scrollUp(count: number, deletedLine = this._margins.top) {
times(count, () => this.page = this.page.splice((this._margins.bottom || 0) + 1, 0, this.emptyLine).toList());
this.page = this.page.splice(deletedLine, count).toList();
}
get attributes(): i.Attributes {
return this._attributes;
}
resetAttributes(): void {
this._attributes = defaultAttributes;
}
setAttributes(attributes: i.Attributes): void {
this._attributes = {...this._attributes, ...attributes};
}
toLines(): string[] {
return this.map(row => row.map(char => char!.value).join(""));
}
showCursor(state: boolean): void {
this._showCursor = state;
}
blinkCursor(state: boolean): void {
this._blinkCursor = state;
}
moveCursorRelative(advancement: Advancement): this {
const unboundRowIndex = this.cursorRowIndex + (advancement.vertical || 0);
const boundRowIndex = this._margins.bottom ? Math.min(this.marginBottom, unboundRowIndex) : unboundRowIndex;
// Cursor might be hanging after the last column.
const boundColumnIndex = Math.min(this.lastColumnIndex, this.cursorColumnIndex);
this.cursorRowIndex = Math.max(0, boundRowIndex);
this.cursorColumnIndex = Math.min(this.dimensions.columns, Math.max(0, boundColumnIndex + (advancement.horizontal || 0)));
this.ensureCursorRowExists();
return this;
}
moveCursorAbsolute(position: Partial<RowColumn>): this {
if (typeof position.columnIndex === "number") {
this.cursorColumnIndex = Math.max(position.columnIndex, 0) + this.homePosition.columnIndex;
}
if (typeof position.rowIndex === "number") {
this.cursorRowIndex = Math.max(position.rowIndex, 0) + this.homePosition.rowIndex;
}
this.ensureCursorRowExists();
return this;
}
deleteRight(n: number) {
this.page = this.page.update(
this.cursorRowIndex,
row => row.splice(this.cursorColumnIndex, n).concat(this.spaces(n)).toList(),
);
}
insertSpaceRight(n: number) {
this.page = this.page.update(
this.cursorRowIndex,
row => row.splice(this.cursorColumnIndex, 0, this.spaces(n)).toList(),
);
}
eraseRight(n: number) {
this.page = this.page.update(
this.cursorRowIndex,
row => row.take(this.cursorColumnIndex)
.concat(this.spaces(n), row.skip(this.cursorColumnIndex + n))
.toList(),
);
}
clearRow() {
this.page = this.page.set(this.cursorRowIndex, this.emptyLine);
}
clearRowToEnd() {
const oldRow = this.page.get(this.cursorRowIndex);
const charsToDeleteCount = this.dimensions.columns - this.cursorColumnIndex;
const newHead = oldRow.splice(this.cursorColumnIndex, charsToDeleteCount);
const newTail = this.spaces(charsToDeleteCount);
const newRow = newHead.concat(newTail).toList();
this.page = this.page.set(this.cursorRowIndex, newRow);
}
clearRowToBeginning() {
const count = this.cursorColumnIndex + 1;
this.page = this.page.update(
this.cursorRowIndex,
row => this.spaces(count).concat(row.skip(count)).toList());
}
clear() {
this.page = List<List<Char>>();
this.moveCursorAbsolute({rowIndex: 0, columnIndex: 0});
}
clearToBeginning() {
this.clearRowToBeginning();
const replacement = Array(this.cursorRowIndex).fill(this.emptyLine);
this.page = this.page.splice(0, this.cursorRowIndex, ...replacement).toList();
}
clearToEnd() {
this.clearRowToEnd();
this.page = this.page.splice(this.cursorRowIndex + 1, this.size - this.cursorRowIndex).toList();
}
get scrollbackSize(): number {
return this.scrollback.size;
}
get size(): number {
return this.page.size;
}
set margins(margins: Partial<Margins>) {
this._margins = {...this._margins, ...margins};
}
get marginTop(): number {
return this._margins.top;
}
get marginBottom(): number {
if (this._margins.bottom) {
return this._margins.bottom;
} else {
return this.dimensions.rows - 1;
}
}
at(position: RowColumn): Char {
return this.page.getIn([position.rowIndex, position.columnIndex]);
}
saveCurrentState() {
this.savedState = {
cursorRowIndex: this.cursorRowIndex,
cursorColumnIndex: this.cursorColumnIndex,
attributes: {...this.attributes},
designatedCharacterSets: {...this.designatedCharacterSets},
selectedCharacterSet: this.selectedCharacterSet,
};
}
restoreCurrentState() {
if (this.savedState) {
this.moveCursorAbsolute({rowIndex: this.savedState.cursorRowIndex, columnIndex: this.savedState.cursorColumnIndex});
this.setAttributes(this.savedState.attributes);
this.selectedCharacterSet = this.savedState.selectedCharacterSet;
this.designatedCharacterSets = this.savedState.designatedCharacterSets;
} else {
console.error("No state to restore.");
}
}
setTabStop() {
this.tabStopIndices = _.sortBy(_.union(this.tabStopIndices, [this.cursorColumnIndex]));
}
clearTabStop() {
this.tabStopIndices = _.without(this.tabStopIndices, this.cursorColumnIndex);
}
clearAllTabStops() {
this.tabStopIndices = [];
}
get nextTabStopIndex() {
const unboundTabStopIndex = this.tabStopIndices.find(index => index > this.cursorColumnIndex) || this.cursorColumnIndex;
return Math.min(unboundTabStopIndex, this.lastColumnIndex);
}
private get homePosition(): RowColumn {
if (this.isOriginModeSet) {
return {rowIndex: this._margins.top || 0, columnIndex: this._margins.left || 0};
} else {
return {rowIndex: 0, columnIndex: 0};
}
}
private set(char: Char): void {
this.ensureCursorRowExists();
this.page = this.page.setIn([this.cursorRowIndex, this.cursorColumnIndex], char);
}
private ensureCursorRowExists(): void {
for (let index = this.cursorRowIndex; index >= 0; --index) {
if (!this.page.get(index)) {
this.page = this.page.set(index, this.spaces(this.dimensions.columns, defaultAttributes));
} else {
break;
}
}
if (this.size > this.dimensions.rows) {
const newStorage = this.page.takeLast(this.dimensions.rows).toList();
const rowsToMoveToScrollback = this.page.skipLast(this.dimensions.rows).toList();
this.scrollback = this.scrollback.concat(rowsToMoveToScrollback).takeLast(this.maxScrollbackSize).toList();
this.page = newStorage;
this.cursorRowIndex = this.size - 1;
}
}
private charFromCharset(char: string) {
if (this.designatedCharacterSets[this.selectedCharacterSet] === CharacterSets.ASCIIGraphics) {
return char;
} else {
return graphicCharset[char] || char;
}
}
private get lastColumnIndex() {
return this.dimensions.columns - 1;
}
private get emptyLine() {
return this.spaces(this.dimensions.columns);
}
private spaces(n: number, attributes = this.attributes) {
return List.of(...Array(n).fill(createChar(" ", attributes)));
}
get dimensions() {
return this.output.dimensions;
}
} | the_stack |
import 'vs/css!./notebookDiff';
import { IListMouseEvent, IListRenderer, IListVirtualDelegate } from 'vs/base/browser/ui/list/list';
import * as DOM from 'vs/base/browser/dom';
import { IListOptions, IListStyles, isMonacoEditor, IStyleController, MouseController } from 'vs/base/browser/ui/list/listWidget';
import { DisposableStore, IDisposable } from 'vs/base/common/lifecycle';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IListService, IWorkbenchListOptions, WorkbenchList } from 'vs/platform/list/browser/listService';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { DiffElementViewModelBase, SideBySideDiffElementViewModel, SingleSideDiffElementViewModel } from 'vs/workbench/contrib/notebook/browser/diff/diffElementViewModel';
import { CellDiffSideBySideRenderTemplate, CellDiffSingleSideRenderTemplate, DIFF_CELL_MARGIN, INotebookTextDiffEditor } from 'vs/workbench/contrib/notebook/browser/diff/notebookDiffEditorBrowser';
import { isMacintosh } from 'vs/base/common/platform';
import { DeletedElement, fixedDiffEditorOptions, fixedEditorOptions, getOptimizedNestedCodeEditorWidgetOptions, InsertElement, ModifiedElement } from 'vs/workbench/contrib/notebook/browser/diff/diffComponents';
import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget';
import { DiffEditorWidget } from 'vs/editor/browser/widget/diffEditorWidget';
import { ToolBar } from 'vs/base/browser/ui/toolbar/toolbar';
import { IMenuService, MenuItemAction } from 'vs/platform/actions/common/actions';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { CodiconActionViewItem } from 'vs/workbench/contrib/notebook/browser/view/cellParts/cellActionView';
import { IMouseWheelEvent } from 'vs/base/browser/mouseEvent';
import { IEditorOptions } from 'vs/editor/common/config/editorOptions';
import { BareFontInfo } from 'vs/editor/common/config/fontInfo';
import { PixelRatio } from 'vs/base/browser/browser';
export class NotebookCellTextDiffListDelegate implements IListVirtualDelegate<DiffElementViewModelBase> {
private readonly lineHeight: number;
constructor(
@IConfigurationService readonly configurationService: IConfigurationService
) {
const editorOptions = this.configurationService.getValue<IEditorOptions>('editor');
this.lineHeight = BareFontInfo.createFromRawSettings(editorOptions, PixelRatio.value).lineHeight;
}
getHeight(element: DiffElementViewModelBase): number {
return element.getHeight(this.lineHeight);
}
hasDynamicHeight(element: DiffElementViewModelBase): boolean {
return false;
}
getTemplateId(element: DiffElementViewModelBase): string {
switch (element.type) {
case 'delete':
case 'insert':
return CellDiffSingleSideRenderer.TEMPLATE_ID;
case 'modified':
case 'unchanged':
return CellDiffSideBySideRenderer.TEMPLATE_ID;
}
}
}
export class CellDiffSingleSideRenderer implements IListRenderer<SingleSideDiffElementViewModel, CellDiffSingleSideRenderTemplate | CellDiffSideBySideRenderTemplate> {
static readonly TEMPLATE_ID = 'cell_diff_single';
constructor(
readonly notebookEditor: INotebookTextDiffEditor,
@IInstantiationService protected readonly instantiationService: IInstantiationService
) { }
get templateId() {
return CellDiffSingleSideRenderer.TEMPLATE_ID;
}
renderTemplate(container: HTMLElement): CellDiffSingleSideRenderTemplate {
const body = DOM.$('.cell-body');
DOM.append(container, body);
const diffEditorContainer = DOM.$('.cell-diff-editor-container');
DOM.append(body, diffEditorContainer);
const diagonalFill = DOM.append(body, DOM.$('.diagonal-fill'));
const sourceContainer = DOM.append(diffEditorContainer, DOM.$('.source-container'));
const editor = this._buildSourceEditor(sourceContainer);
const metadataHeaderContainer = DOM.append(diffEditorContainer, DOM.$('.metadata-header-container'));
const metadataInfoContainer = DOM.append(diffEditorContainer, DOM.$('.metadata-info-container'));
const outputHeaderContainer = DOM.append(diffEditorContainer, DOM.$('.output-header-container'));
const outputInfoContainer = DOM.append(diffEditorContainer, DOM.$('.output-info-container'));
const borderContainer = DOM.append(body, DOM.$('.border-container'));
const leftBorder = DOM.append(borderContainer, DOM.$('.left-border'));
const rightBorder = DOM.append(borderContainer, DOM.$('.right-border'));
const topBorder = DOM.append(borderContainer, DOM.$('.top-border'));
const bottomBorder = DOM.append(borderContainer, DOM.$('.bottom-border'));
return {
body,
container,
diffEditorContainer,
diagonalFill,
sourceEditor: editor,
metadataHeaderContainer,
metadataInfoContainer,
outputHeaderContainer,
outputInfoContainer,
leftBorder,
rightBorder,
topBorder,
bottomBorder,
elementDisposables: new DisposableStore()
};
}
private _buildSourceEditor(sourceContainer: HTMLElement) {
const editorContainer = DOM.append(sourceContainer, DOM.$('.editor-container'));
const editor = this.instantiationService.createInstance(CodeEditorWidget, editorContainer, {
...fixedEditorOptions,
dimension: {
width: (this.notebookEditor.getLayoutInfo().width - 2 * DIFF_CELL_MARGIN) / 2 - 18,
height: 0
},
automaticLayout: false,
overflowWidgetsDomNode: this.notebookEditor.getOverflowContainerDomNode()
}, {});
return editor;
}
renderElement(element: SingleSideDiffElementViewModel, index: number, templateData: CellDiffSingleSideRenderTemplate, height: number | undefined): void {
templateData.body.classList.remove('left', 'right', 'full');
switch (element.type) {
case 'delete':
templateData.elementDisposables.add(this.instantiationService.createInstance(DeletedElement, this.notebookEditor, element, templateData));
return;
case 'insert':
templateData.elementDisposables.add(this.instantiationService.createInstance(InsertElement, this.notebookEditor, element, templateData));
return;
default:
break;
}
}
disposeTemplate(templateData: CellDiffSingleSideRenderTemplate): void {
templateData.container.innerText = '';
templateData.sourceEditor.dispose();
}
disposeElement(element: SingleSideDiffElementViewModel, index: number, templateData: CellDiffSingleSideRenderTemplate): void {
templateData.elementDisposables.clear();
}
}
export class CellDiffSideBySideRenderer implements IListRenderer<SideBySideDiffElementViewModel, CellDiffSideBySideRenderTemplate> {
static readonly TEMPLATE_ID = 'cell_diff_side_by_side';
constructor(
readonly notebookEditor: INotebookTextDiffEditor,
@IInstantiationService protected readonly instantiationService: IInstantiationService,
@IContextMenuService protected readonly contextMenuService: IContextMenuService,
@IKeybindingService protected readonly keybindingService: IKeybindingService,
@IMenuService protected readonly menuService: IMenuService,
@IContextKeyService protected readonly contextKeyService: IContextKeyService,
@INotificationService protected readonly notificationService: INotificationService,
@IThemeService protected readonly themeService: IThemeService,
) { }
get templateId() {
return CellDiffSideBySideRenderer.TEMPLATE_ID;
}
renderTemplate(container: HTMLElement): CellDiffSideBySideRenderTemplate {
const body = DOM.$('.cell-body');
DOM.append(container, body);
const diffEditorContainer = DOM.$('.cell-diff-editor-container');
DOM.append(body, diffEditorContainer);
const sourceContainer = DOM.append(diffEditorContainer, DOM.$('.source-container'));
const { editor, editorContainer } = this._buildSourceEditor(sourceContainer);
const inputToolbarContainer = DOM.append(sourceContainer, DOM.$('.editor-input-toolbar-container'));
const cellToolbarContainer = DOM.append(inputToolbarContainer, DOM.$('div.property-toolbar'));
const toolbar = new ToolBar(cellToolbarContainer, this.contextMenuService, {
actionViewItemProvider: action => {
if (action instanceof MenuItemAction) {
const item = new CodiconActionViewItem(action, this.keybindingService, this.notificationService, this.contextKeyService, this.themeService);
return item;
}
return undefined;
}
});
const metadataHeaderContainer = DOM.append(diffEditorContainer, DOM.$('.metadata-header-container'));
const metadataInfoContainer = DOM.append(diffEditorContainer, DOM.$('.metadata-info-container'));
const outputHeaderContainer = DOM.append(diffEditorContainer, DOM.$('.output-header-container'));
const outputInfoContainer = DOM.append(diffEditorContainer, DOM.$('.output-info-container'));
const borderContainer = DOM.append(body, DOM.$('.border-container'));
const leftBorder = DOM.append(borderContainer, DOM.$('.left-border'));
const rightBorder = DOM.append(borderContainer, DOM.$('.right-border'));
const topBorder = DOM.append(borderContainer, DOM.$('.top-border'));
const bottomBorder = DOM.append(borderContainer, DOM.$('.bottom-border'));
return {
body,
container,
diffEditorContainer,
sourceEditor: editor,
editorContainer,
inputToolbarContainer,
toolbar,
metadataHeaderContainer,
metadataInfoContainer,
outputHeaderContainer,
outputInfoContainer,
leftBorder,
rightBorder,
topBorder,
bottomBorder,
elementDisposables: new DisposableStore()
};
}
private _buildSourceEditor(sourceContainer: HTMLElement) {
const editorContainer = DOM.append(sourceContainer, DOM.$('.editor-container'));
const editor = this.instantiationService.createInstance(DiffEditorWidget, editorContainer, {
...fixedDiffEditorOptions,
padding: {
top: 24,
bottom: 12
},
overflowWidgetsDomNode: this.notebookEditor.getOverflowContainerDomNode(),
originalEditable: false,
ignoreTrimWhitespace: false,
automaticLayout: false,
dimension: {
height: 0,
width: 0
}
}, {
originalEditor: getOptimizedNestedCodeEditorWidgetOptions(),
modifiedEditor: getOptimizedNestedCodeEditorWidgetOptions()
});
return {
editor,
editorContainer
};
}
renderElement(element: SideBySideDiffElementViewModel, index: number, templateData: CellDiffSideBySideRenderTemplate, height: number | undefined): void {
templateData.body.classList.remove('left', 'right', 'full');
switch (element.type) {
case 'unchanged':
templateData.elementDisposables.add(this.instantiationService.createInstance(ModifiedElement, this.notebookEditor, element, templateData));
return;
case 'modified':
templateData.elementDisposables.add(this.instantiationService.createInstance(ModifiedElement, this.notebookEditor, element, templateData));
return;
default:
break;
}
}
disposeTemplate(templateData: CellDiffSideBySideRenderTemplate): void {
templateData.container.innerText = '';
templateData.sourceEditor.dispose();
templateData.toolbar?.dispose();
}
disposeElement(element: SideBySideDiffElementViewModel, index: number, templateData: CellDiffSideBySideRenderTemplate): void {
templateData.elementDisposables.clear();
}
}
export class NotebookMouseController<T> extends MouseController<T> {
protected override onViewPointer(e: IListMouseEvent<T>): void {
if (isMonacoEditor(e.browserEvent.target as HTMLElement)) {
const focus = typeof e.index === 'undefined' ? [] : [e.index];
this.list.setFocus(focus, e.browserEvent);
} else {
super.onViewPointer(e);
}
}
}
export class NotebookTextDiffList extends WorkbenchList<DiffElementViewModelBase> implements IDisposable, IStyleController {
private styleElement?: HTMLStyleElement;
get rowsContainer(): HTMLElement {
return this.view.containerDomNode;
}
constructor(
listUser: string,
container: HTMLElement,
delegate: IListVirtualDelegate<DiffElementViewModelBase>,
renderers: IListRenderer<DiffElementViewModelBase, CellDiffSingleSideRenderTemplate | CellDiffSideBySideRenderTemplate>[],
contextKeyService: IContextKeyService,
options: IWorkbenchListOptions<DiffElementViewModelBase>,
@IListService listService: IListService,
@IThemeService themeService: IThemeService,
@IConfigurationService configurationService: IConfigurationService,
@IKeybindingService keybindingService: IKeybindingService) {
super(listUser, container, delegate, renderers, options, contextKeyService, listService, themeService, configurationService, keybindingService);
}
protected override createMouseController(options: IListOptions<DiffElementViewModelBase>): MouseController<DiffElementViewModelBase> {
return new NotebookMouseController(this);
}
getAbsoluteTopOfElement(element: DiffElementViewModelBase): number {
const index = this.indexOf(element);
// if (index === undefined || index < 0 || index >= this.length) {
// this._getViewIndexUpperBound(element);
// throw new ListError(this.listUser, `Invalid index ${index}`);
// }
return this.view.elementTop(index);
}
getScrollHeight() {
return this.view.scrollHeight;
}
triggerScrollFromMouseWheelEvent(browserEvent: IMouseWheelEvent) {
this.view.triggerScrollFromMouseWheelEvent(browserEvent);
}
clear() {
super.splice(0, this.length);
}
updateElementHeight2(element: DiffElementViewModelBase, size: number) {
const viewIndex = this.indexOf(element);
const focused = this.getFocus();
this.view.updateElementHeight(viewIndex, size, focused.length ? focused[0] : null);
}
override style(styles: IListStyles) {
const selectorSuffix = this.view.domId;
if (!this.styleElement) {
this.styleElement = DOM.createStyleSheet(this.view.domNode);
}
const suffix = selectorSuffix && `.${selectorSuffix}`;
const content: string[] = [];
if (styles.listBackground) {
if (styles.listBackground.isOpaque()) {
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows { background: ${styles.listBackground}; }`);
} else if (!isMacintosh) { // subpixel AA doesn't exist in macOS
console.warn(`List with id '${selectorSuffix}' was styled with a non-opaque background color. This will break sub-pixel antialiasing.`);
}
}
if (styles.listFocusBackground) {
content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused { background-color: ${styles.listFocusBackground}; }`);
content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused:hover { background-color: ${styles.listFocusBackground}; }`); // overwrite :hover style in this case!
}
if (styles.listFocusForeground) {
content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused { color: ${styles.listFocusForeground}; }`);
}
if (styles.listActiveSelectionBackground) {
content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected { background-color: ${styles.listActiveSelectionBackground}; }`);
content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected:hover { background-color: ${styles.listActiveSelectionBackground}; }`); // overwrite :hover style in this case!
}
if (styles.listActiveSelectionForeground) {
content.push(`.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected { color: ${styles.listActiveSelectionForeground}; }`);
}
if (styles.listFocusAndSelectionBackground) {
content.push(`
.monaco-drag-image,
.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected.focused { background-color: ${styles.listFocusAndSelectionBackground}; }
`);
}
if (styles.listFocusAndSelectionForeground) {
content.push(`
.monaco-drag-image,
.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected.focused { color: ${styles.listFocusAndSelectionForeground}; }
`);
}
if (styles.listInactiveFocusBackground) {
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused { background-color: ${styles.listInactiveFocusBackground}; }`);
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused:hover { background-color: ${styles.listInactiveFocusBackground}; }`); // overwrite :hover style in this case!
}
if (styles.listInactiveSelectionBackground) {
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected { background-color: ${styles.listInactiveSelectionBackground}; }`);
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected:hover { background-color: ${styles.listInactiveSelectionBackground}; }`); // overwrite :hover style in this case!
}
if (styles.listInactiveSelectionForeground) {
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected { color: ${styles.listInactiveSelectionForeground}; }`);
}
if (styles.listHoverBackground) {
content.push(`.monaco-list${suffix}:not(.drop-target) > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:hover:not(.selected):not(.focused) { background-color: ${styles.listHoverBackground}; }`);
}
if (styles.listHoverForeground) {
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:hover:not(.selected):not(.focused) { color: ${styles.listHoverForeground}; }`);
}
if (styles.listSelectionOutline) {
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.selected { outline: 1px dotted ${styles.listSelectionOutline}; outline-offset: -1px; }`);
}
if (styles.listFocusOutline) {
content.push(`
.monaco-drag-image,
.monaco-list${suffix}:focus > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused { outline: 1px solid ${styles.listFocusOutline}; outline-offset: -1px; }
`);
}
if (styles.listInactiveFocusOutline) {
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row.focused { outline: 1px dotted ${styles.listInactiveFocusOutline}; outline-offset: -1px; }`);
}
if (styles.listHoverOutline) {
content.push(`.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows > .monaco-list-row:hover { outline: 1px dashed ${styles.listHoverOutline}; outline-offset: -1px; }`);
}
if (styles.listDropBackground) {
content.push(`
.monaco-list${suffix}.drop-target,
.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-rows.drop-target,
.monaco-list${suffix} > div.monaco-scrollable-element > .monaco-list-row.drop-target { background-color: ${styles.listDropBackground} !important; color: inherit !important; }
`);
}
if (styles.listFilterWidgetBackground) {
content.push(`.monaco-list-type-filter { background-color: ${styles.listFilterWidgetBackground} }`);
}
if (styles.listFilterWidgetOutline) {
content.push(`.monaco-list-type-filter { border: 1px solid ${styles.listFilterWidgetOutline}; }`);
}
if (styles.listFilterWidgetNoMatchesOutline) {
content.push(`.monaco-list-type-filter.no-matches { border: 1px solid ${styles.listFilterWidgetNoMatchesOutline}; }`);
}
if (styles.listMatchesShadow) {
content.push(`.monaco-list-type-filter { box-shadow: 1px 1px 1px ${styles.listMatchesShadow}; }`);
}
const newStyles = content.join('\n');
if (newStyles !== this.styleElement.textContent) {
this.styleElement.textContent = newStyles;
}
}
} | the_stack |
import NetRegexes from '../../../../../resources/netregexes';
import { Responses } from '../../../../../resources/responses';
import ZoneId from '../../../../../resources/zone_id';
import { RaidbossData } from '../../../../../types/data';
import { TriggerSet } from '../../../../../types/trigger';
// TODO: Lyssa Frostbite and Seek
// TODO: Ladon Lord cleave directions
// TODO: Hermes correct meteor
// TODO: Hermes mirror dodge direction
export interface Data extends RaidbossData {
isHermes?: boolean;
}
const triggerSet: TriggerSet<Data> = {
zoneId: ZoneId.KtisisHyperboreia,
timelineFile: 'ktisis_hyperboreia.txt',
triggers: [
{
id: 'Ktisis Lyssa Skull Dasher',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '625E', source: 'Lyssa' }),
netRegexDe: NetRegexes.startsUsing({ id: '625E', source: 'Lyssa' }),
netRegexFr: NetRegexes.startsUsing({ id: '625E', source: 'Lyssa' }),
netRegexJa: NetRegexes.startsUsing({ id: '625E', source: 'リッサ' }),
response: Responses.tankBuster(),
},
{
id: 'Ktisis Lyssa Frigid Stomp',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '625D', source: 'Lyssa', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '625D', source: 'Lyssa', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '625D', source: 'Lyssa', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '625D', source: 'リッサ', capture: false }),
response: Responses.aoe(),
},
{
id: 'Ktisis Lyssa Heavy Smash',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '625C', source: 'Lyssa' }),
netRegexDe: NetRegexes.startsUsing({ id: '625C', source: 'Lyssa' }),
netRegexFr: NetRegexes.startsUsing({ id: '625C', source: 'Lyssa' }),
netRegexJa: NetRegexes.startsUsing({ id: '625C', source: 'リッサ' }),
response: Responses.stackMarkerOn(),
},
{
id: 'Ktisis Ladon Lord Scratch',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '648F', source: 'Ladon Lord' }),
netRegexDe: NetRegexes.startsUsing({ id: '648F', source: 'Ladon-Lord' }),
netRegexFr: NetRegexes.startsUsing({ id: '648F', source: 'Seigneur Ladon' }),
netRegexJa: NetRegexes.startsUsing({ id: '648F', source: 'ラドンロード' }),
response: Responses.tankBuster(),
},
{
id: 'Ktisis Ladon Lord Intimidation',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '648D', source: 'Ladon Lord', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '648D', source: 'Ladon-Lord', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '648D', source: 'Seigneur Ladon', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '648D', source: 'ラドンロード', capture: false }),
response: Responses.aoe(),
},
{
id: 'Ktisis Ladon Lord Pyric Blast',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '648E', source: 'Ladon Lord' }),
netRegexDe: NetRegexes.startsUsing({ id: '648E', source: 'Ladon-Lord' }),
netRegexFr: NetRegexes.startsUsing({ id: '648E', source: 'Seigneur Ladon' }),
netRegexJa: NetRegexes.startsUsing({ id: '648E', source: 'ラドンロード' }),
response: Responses.stackMarkerOn(),
},
{
id: 'Ktisis Hermes Trimegistos',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '651E', source: 'Hermes', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '651E', source: 'Hermes', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '651E', source: 'Hermès', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '651E', source: 'ヘルメス', capture: false }),
response: Responses.aoe(),
run: (data) => data.isHermes = true,
},
{
id: 'Ktisis Hermes True Tornado',
// StartsUsing line is self-targeted.
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '00DA' }),
// This headmarker is used for the first two bosses but only Hermes cleaves.
condition: (data) => data.isHermes,
response: Responses.tankCleave('alert'),
},
{
id: 'Ktisis Hermes True Aero',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '652B', source: 'Hermes', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '652B', source: 'Hermes', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '652B', source: 'Hermès', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '652B', source: 'ヘルメス', capture: false }),
response: Responses.spread(),
},
{
id: 'Ktisis Hermes True Bravery',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '6533', source: 'Hermes' }),
netRegexDe: NetRegexes.startsUsing({ id: '6533', source: 'Hermes' }),
netRegexFr: NetRegexes.startsUsing({ id: '6533', source: 'Hermès' }),
netRegexJa: NetRegexes.startsUsing({ id: '6533', source: 'ヘルメス' }),
condition: (data) => data.CanSilence(),
response: Responses.interrupt(),
},
{
id: 'Ktisis Hermes Meteor Cosmic Kiss',
type: 'Ability',
netRegex: NetRegexes.ability({ id: '6523', source: 'Meteor', capture: false }),
netRegexDe: NetRegexes.ability({ id: '6523', source: 'Meteor', capture: false }),
netRegexFr: NetRegexes.ability({ id: '6523', source: 'Météore', capture: false }),
netRegexJa: NetRegexes.ability({ id: '6523', source: 'メテオ', capture: false }),
suppressSeconds: 5,
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Hide behind unbroken meteor',
de: 'Hinter einem nicht zerbrochenen Meteor verstecken',
fr: 'Cachez-vous derrière le météore intact',
ko: '금이 안 간 돌 뒤에 숨기',
},
},
},
],
timelineReplace: [
{
'locale': 'de',
'replaceSync': {
'Concept Review': 'Konzeptbewertung',
'Hermes': 'Hermes',
'Ice Pillar': 'Eissäule',
'Karukeion': 'Kerykeion',
'Ladon Lord': 'Ladon-Lord',
'Lyssa': 'Lyssa',
'Meteor': 'Meteor',
'Pyric Sphere': 'Pyrische Sphäre',
'The Celestial Sphere': 'Astralzone',
'The Frozen Sphere': 'Kaltzone',
},
'replaceText': {
'Cosmic Kiss': 'Einschlag',
'Double': 'Doppel',
'Frigid Stomp': 'Froststampfer',
'Frostbite and Seek': 'In eisige Winde gehüllt',
'Heavy Smash': 'Schwerer Klopfer',
'Hermetica': 'Hermetika',
'Ice Pillar': 'Eissäule',
'Icicall': 'Eiszapfen-Brüller',
'Inhale': 'Inhalieren',
'Intimidation': 'Einschüchterungsversuch',
'Meteor': 'Meteor',
'Pillar Pierce': 'Säulendurchschlag',
'Punishing Slice': 'Strafender Schlitzer',
'Pyric Blast': 'Pyrischer Rumms',
'Pyric Breath': 'Pyrischer Atem',
'Pyric Sphere': 'Pyrische Sphäre',
'Quadruple': 'Quadrupel',
'Scratch': 'Schramme',
'Skull Dasher': 'Schädelzertrümmerer',
'Trismegistos': 'Trismegistus',
'True Aero(?! I)': 'Vollkommener Wind',
'True Aero II': 'Vollkommenes Windra',
'True Aero IV': 'Vollkommenes Windka',
'True Tornado': 'Vollkommener Tornado',
},
},
{
'locale': 'fr',
'replaceSync': {
'Concept Review': 'Salle d\'évaluation',
'Hermes': 'Hermès',
'Ice Pillar': 'Pilier de glace',
'Karukeion': 'kerykeion',
'Ladon Lord': 'seigneur Ladon',
'Lyssa': 'Lyssa',
'Meteor': 'Météore',
'Pyric Sphere': 'Sphère pyrogène',
'The Celestial Sphere': 'Voûte céleste',
'The Frozen Sphere': 'Glacier artificiel',
},
'replaceText': {
'Cosmic Kiss': 'Impact de canon',
'Double': 'Double',
'Frigid Stomp': 'Piétinement glacial',
'Frostbite and Seek': 'Gelure furtive',
'Heavy Smash': 'Fracas violent',
'Hermetica': 'Hermética',
'Ice Pillar': 'Pilier de glace',
'Icicall': 'Stalactite rugissante',
'Inhale': 'Inhalation',
'Intimidation': 'Intimidation',
'Meteor': 'Météore',
'Pillar Pierce': 'Empalement',
'Punishing Slice': 'Tranchage punitif',
'Pyric Blast': 'Souffle pyrogène',
'Pyric Breath': 'Bouffée pyrogène',
'Pyric Sphere': 'Sphère pyrogène',
'Quadruple': 'Quadruple',
'Scratch': 'Griffade',
'Skull Dasher': 'Charge du crâne',
'Trismegistos': 'Trismégistos',
'True Aero(?! I)': 'Vent véritable',
'True Aero II': 'Extra Vent véritable',
'True Aero IV': 'Giga Vent véritable',
'True Tornado': 'Tornade véritable',
},
},
{
'locale': 'ja',
'replaceSync': {
'Concept Review': '創造生物評価室',
'Hermes': 'ヘルメス',
'Ice Pillar': '氷柱',
'Karukeion': 'ケリュケイオン',
'Ladon Lord': 'ラドンロード',
'Lyssa': 'リッサ',
'Meteor': 'メテオ',
'Pyric Sphere': 'パイリックスフィア',
'The Celestial Sphere': '天脈創造環境',
'The Frozen Sphere': '寒冷創造環境',
},
'replaceText': {
'Cosmic Kiss': '着弾',
'Double': 'ダブル',
'Frigid Stomp': 'フリジッドストンプ',
'Frostbite and Seek': 'フロストバイト・アンドシーク',
'Heavy Smash': 'ヘビースマッシュ',
'Hermetica': 'ヘルメチカ',
'Ice Pillar': '氷柱',
'Icicall': 'アイシクルロア',
'Inhale': 'インヘイル',
'Intimidation': 'インティミデーション',
'Meteor': 'メテオ',
'Pillar Pierce': '激突',
'Punishing Slice': 'パニッシングスライス',
'Pyric Blast': 'パイリックブラスト',
'Pyric Breath': 'パイリックブレス',
'Pyric Sphere': 'パイリックスフィア',
'Quadruple': 'クアドラプル',
'Scratch': 'スクラッチ',
'Skull Dasher': 'スカルダッシャー',
'Trismegistos': 'トリスメギストス',
'True Aero(?! I)': 'トゥルー・エアロ',
'True Aero II': 'トゥルー・エアロラ',
'True Aero IV': 'トゥルー・エアロジャ',
'True Tornado': 'トゥルー・トルネド',
},
},
],
};
export default triggerSet; | the_stack |
import {
Component, NgModule, Input, ViewChildren, QueryList, forwardRef, AfterViewInit, Renderer2, ElementRef, EventEmitter, OnDestroy, OnInit,
NgZone,
} from "@angular/core";
import {CommonModule} from "@angular/common";
import {AbstractJigsawComponent} from "../../common/common";
import {fadeIn} from "../../common/components/animations/fade-in";
import {CallbackRemoval} from "../../common/core/utils/common-utils";
import {SimpleTreeData, TreeData} from "../../common/core/data/tree-data";
import {JigsawTrustedHtmlModule} from "../../common/directive/trusted-html/trusted-html";
/**
* 标准鱼骨图组件,鱼骨图常常用于对问题的根因做分析,或者做目标分解
*
* $demo = fish-bone/full
*/
@Component({
selector: 'j-fish-bone, jigsaw-fish-bone',
templateUrl: './fish-bone.html',
host: {
'[class.jigsaw-fish-bone]': 'true',
'[class.jigsaw-fish-bone-left]': 'direction === "left"',
'[class.jigsaw-fish-bone-right]': 'direction === "right"',
'[class.jigsaw-fish-bone-light]': 'theme === "light"',
'[class.jigsaw-fish-bone-dark]': 'theme === "dark"',
'[style.width]': 'width'
}
})
export class JigsawFishBone extends AbstractJigsawComponent implements AfterViewInit, OnDestroy, OnInit {
constructor(private _renderer: Renderer2, private _elementRef: ElementRef, protected _zone: NgZone) {
super(_zone);
}
private _dataCallbackRemoval: CallbackRemoval;
private _data: SimpleTreeData | TreeData;
/**
* 图形数据,是一个树状结构的数据,对于鱼骨图展示目标不同,对树状结构的各分支页有不同的理解,分别为:
* - 鱼骨图用于做根因分析时:
* - 树根代表着根因;
* - 树的各支代表着各个主要原因及其次要原因
* - 鱼骨图用于做目标分解时
* - 树根代表着目标;
* - 树的各支代表着为各个达成目标而必须完成的主要及次要任务;
*
* @NoMarkForCheckRequired
*
* $demo = fish-bone/full
*/
@Input()
get data(): SimpleTreeData | TreeData {
return this._data;
}
set data(value: SimpleTreeData | TreeData) {
this._data = value;
if (this._dataCallbackRemoval) {
this._dataCallbackRemoval();
}
this._dataCallbackRemoval = this._data.onRefresh(()=>{
this.runAfterMicrotasks(() => {
this._zone.run(() => {
this.ngAfterViewInit();
})
})
});
}
/**
* 鱼骨图鱼头的朝向,默认是朝左。
*
* @NoMarkForCheckRequired
*
* $demo = fish-bone/full
*/
@Input()
public direction: 'left' | 'right' = 'left';
/**
* 鱼骨图的整体色调,默认是白色调
*
* @NoMarkForCheckRequired
*
* $demo = fish-bone/full
*/
@Input()
public theme: 'light' | 'dark' = 'light';
@ViewChildren(forwardRef(() => JigsawFishBoneItem))
private _firstLevelBones: QueryList<JigsawFishBoneItem>;
private _allFishBones: Array<JigsawFishBoneItem> = [];
/**
*
* 按照子到父的顺序存储节点
* */
private _cacheFishBoneItems(fishBoneItems) {
fishBoneItems.forEach(fishBoneItem => {
fishBoneItem.rectifyEvent.subscribe(() => {
this._allFishBones.push(fishBoneItem);
});
this._cacheFishBoneItems(fishBoneItem.childBones);
})
}
/**
*
* 按照子到父的顺序设置节点的偏移量和宽度
* 节点的偏移前一个同级节点的 left + rangeHeight
* 父节点的宽度依赖最后一个子节点的 left + rangHeight
*
* */
private _setAllBoneAttribute() {
this._allFishBones.forEach(fishBoneItem => {
fishBoneItem.setBoneAttribute();
})
}
/**
*
* 计算最外层的父节点的偏移
*/
private _setFirstLevelBoneOffset(fishBoneMainChildren) {
const fishBoneMainArray = fishBoneMainChildren.toArray();
fishBoneMainChildren.forEach((fishBoneItem, index) => {
if (index <= 1) {
// 最外层的鱼骨 前面两个偏移0px
fishBoneItem.left = 0;
} else {
// 最外层的鱼骨是上下排列的,所以用前前节点计算
fishBoneItem.calculateOffsetLeft(fishBoneMainArray[index - 2]);
}
})
}
private _getMaxRangeHeight(cb) {
return Math.max(...this._firstLevelBones.filter(cb).reduce((arr, fishBoneItem) => {
const lastChild = fishBoneItem.childBones.last;
if (lastChild) {
// 有子节点
arr.push(lastChild.rangeHeight + lastChild.left);
} else {
// 没有子节点
arr.push(fishBoneItem.itemEl.offsetWidth);
}
return arr
}, []));
}
private _setRangeHeight() {
// 上部的高度
const upHeight = Math.cos(30 * 0.017453293) * this._getMaxRangeHeight((fishBoneItem, index) => {
return (index + 1) % 2 === 1;
}) + 30;
// 下部的高度
const downHeight = Math.cos(30 * 0.017453293) * this._getMaxRangeHeight((fishBoneItem, index) => {
return (index + 1) % 2 === 0;
}) + 30;
const host = this._elementRef.nativeElement;
// 横向的主骨
const mainBone = host.querySelector('.jigsaw-fish-bone-main');
// 鱼骨的范围框,和整个鱼骨的宽度和高度相同
const fishBoneRange = host.querySelector('.jigsaw-fish-bone-range');
// 鱼骨组件的外框,和组件设置的宽高相同
const fishBoneFramework = host.querySelector('.jigsaw-fish-bone-framework');
this._renderer.setStyle(fishBoneRange, 'height', upHeight + downHeight + 'px');
// 设置主骨在范围框中的位置
this._renderer.setStyle(mainBone, 'top', upHeight + 'px');
if (this.height) {
// 组件设置高度,加上外框的滚动条
this._renderer.setStyle(fishBoneFramework, 'overflow-y', 'scroll');
} else {
// 组件不设置高度,去掉外框的滚动条,组件自适应范围框的高度
this._renderer.setStyle(host, 'height', upHeight + downHeight + 'px');
this._renderer.setStyle(fishBoneFramework, 'overflow-y', 'hidden');
}
}
private _setRangeWidth() {
const maxOffsetBone = this._firstLevelBones.toArray().sort((item1, item2) => item2.left - item1.left)[0];
const host = this._elementRef.nativeElement;
const mainBone = host.querySelector('.jigsaw-fish-bone-main');
const fishBoneRange = host.querySelector('.jigsaw-fish-bone-range');
const fishBoneFramework = host.querySelector('.jigsaw-fish-bone-framework');
const hostWidth = host.offsetWidth;
if (maxOffsetBone) {
// 主骨的最小宽度
const boneWidth = maxOffsetBone.left + maxOffsetBone.rangeHeight;
// 组件范围框的宽度,主骨宽度+鱼头+鱼尾
const rangeWidth = boneWidth + 146 + 80;
if (rangeWidth > hostWidth) {
// 范围宽度大于组件宽度,即溢出
// 主骨宽度等于主骨最小宽度
this._renderer.setStyle(mainBone, 'width', boneWidth + 'px');
// 鱼骨范围宽度
this._renderer.setStyle(fishBoneRange, 'width', rangeWidth + 'px');
// 加上外框的滚动条
this._renderer.setStyle(fishBoneFramework, 'overflow-x', 'scroll');
} else {
// 范围宽度小于组件宽度
// 主骨宽度等于组件宽度-鱼头-鱼尾,即自适应组件宽度
this._renderer.setStyle(mainBone, 'width', hostWidth - 80 - 146 + 'px');
// 范围宽度等于组件宽度
this._renderer.setStyle(fishBoneRange, 'width', hostWidth + 'px');
// 去掉外框的滚动条
this._renderer.setStyle(fishBoneFramework, 'overflow-x', 'hidden');
}
}
}
private _removeWindowListener: CallbackRemoval;
ngAfterViewInit() {
this._cacheFishBoneItems(this._firstLevelBones);
this.runAfterMicrotasks(() => {
this._zone.run(() => {
this._setAllBoneAttribute();
this._setFirstLevelBoneOffset(this._firstLevelBones);
this._setRangeHeight();
this._setRangeWidth();
})
});
this._zone.runOutsideAngular(() => {
this._removeWindowListener = this._renderer.listen('window',
'resize', () => this._setRangeWidth());
});
}
ngOnDestroy() {
super.ngOnDestroy();
if (this._removeWindowListener) {
this._removeWindowListener();
}
if (this._dataCallbackRemoval) {
this._dataCallbackRemoval();
}
}
}
/**
* @internal
*/
@Component({
selector: 'j-fish-bone-item, jigsaw-fish-bone-item',
templateUrl: './fish-bone-item.html',
host: {
'[class.jigsaw-fish-bone-item]': 'true',
},
animations: [
fadeIn
]
})
export class JigsawFishBoneItem extends AbstractJigsawComponent implements AfterViewInit {
public itemEl: HTMLElement;
private _itemContent: HTMLElement;
private _itemDescription: HTMLElement;
constructor(private _renderer: Renderer2, elementRef: ElementRef, protected _zone: NgZone) {
super(_zone);
this.itemEl = elementRef.nativeElement;
}
/**
* @NoMarkForCheckRequired
*/
@Input()
public data: SimpleTreeData | TreeData;
/**
* @NoMarkForCheckRequired
*/
@Input()
public childRotate: string;
@ViewChildren(forwardRef(() => JigsawFishBoneItem))
public childBones: QueryList<JigsawFishBoneItem>;
/**
* @NoMarkForCheckRequired
*/
@Input()
public parentBone: JigsawFishBoneItem;
/**
* @NoMarkForCheckRequired
*/
@Input()
public level: number = 0;
/**
* @NoMarkForCheckRequired
*/
@Input()
public index: number = 0;
/**
* @NoMarkForCheckRequired
*/
@Input()
public firstLevelRotate: string;
public rangeHeight: number = 0;
// 默认偏移50,后面只有第一个节点是默认值
private _left: number = 50;
public get left(): number {
return this._left;
}
public set left(value: number) {
this._left = value;
// 用setStyle保持同步,绑定[style.left]是异步的
this._renderer.setStyle(this.itemEl, 'left', value + 'px');
}
/**
* @internal
*/
public _$state;
/**
* 获取最大范围高度
* 比较各子节点伸展高度
* 伸展高度:子节点有子节点,并且最后一个子节点的rangeHeight不等于0,取其最后一个子节点的rangeHeight + left;
* 其他取子节点自身的宽度
* */
private _setRangeHeight() {
if (this.childBones.length) {
this.rangeHeight = Math.max(...this.childBones.reduce((arr, fishBoneItem) => {
let childRange = 0;
const lastChild = fishBoneItem.childBones.last;
if (lastChild && lastChild.rangeHeight > 30) {
childRange = lastChild.rangeHeight + lastChild.left;
} else {
if (this.firstLevelRotate == 'down') {
// 主骨在下面,需要考虑内容的伸展
childRange = fishBoneItem.itemEl.offsetWidth + fishBoneItem._itemContent.offsetHeight / Math.tan(60 * 0.017453293);
} else {
// 主骨在上面
childRange = fishBoneItem.itemEl.offsetWidth;
}
}
arr.push(childRange);
return arr;
}, []));
} else {
// 没有子节点
if (this.firstLevelRotate == 'up') {
// 主骨在上面
this.rangeHeight = this._itemContent.offsetHeight / Math.sin(60 * 0.017453293);
} else if (this.firstLevelRotate == 'down') {
// 主骨在下面
this.rangeHeight = this._itemDescription.offsetHeight;
}
}
}
/**
* 计算偏移并设置样式
*
*/
private _setOffset() {
if (this.level !== 0) {
// 最外层的父节点另外计算
if (this.firstLevelRotate == 'down' && this.childBones.length === 0) {
// 主骨在下面,没有子节点
if (this.index === 0) {
// 第一个如果内容大于默认值,则由内容撑开
const contentHeight = this._itemContent.offsetHeight / Math.sin(60 * 0.017453293) + 30;
this.left = contentHeight > 50 ? contentHeight : 50;
} else {
// 后面的也要加上自身内容
const preBone = this.parentBone.childBones.toArray()[this.index - 1];
this.left = preBone.left + preBone.rangeHeight + 30 + this._itemContent.offsetHeight / Math.sin(60 * 0.017453293);
}
} else {
if (this.index === 0) {
// 第一个节点是默认偏移50px,写在css里面
this.left = this._itemDescription.offsetHeight + 30 > 50 ? this._itemDescription.offsetHeight + 30 : 50;
} else {
this.calculateOffsetLeft(this.parentBone.childBones.toArray()[this.index - 1]);
}
}
}
}
/**
* 计算偏移的通用方法
* @param fishBoneItem
*/
public calculateOffsetLeft(fishBoneItem) {
// fishBoneItem.rangeHeight 为0时,取30
const rangeHeight = fishBoneItem.rangeHeight > 30 ? fishBoneItem.rangeHeight : 30;
this.left = fishBoneItem.left + rangeHeight + this._itemDescription.offsetHeight + 30;
}
/**
* 计算宽度并设置样式
*
*/
private _setWidth() {
if (this.childBones.last) {
// 取其最后一个子节点的left偏移值 + 30px
this.width = this.childBones.last.left + 30 + 'px';
// 有子节点时,内容宽度设成和鱼骨宽度相同
this._renderer.setStyle(this._itemContent, 'width', '100%');
} else {
if (this.firstLevelRotate == 'down') {
// 主骨在下面, 没有子节点
this.width = this._itemContent.offsetWidth + 'px';
} else if (this.firstLevelRotate == 'up') {
// 主骨在上面,没有子节点,宽度为内容的宽度+高度,内容的最小宽度为100px,写在css里
this.width = this._itemContent.offsetHeight / Math.tan(60 * 0.017453293) + this._itemContent.offsetWidth + 'px';
// 纠正内容和鱼骨交叉
this._renderer.setStyle(this._itemContent, 'left', this._itemContent.offsetHeight / Math.tan(60 * 0.017453293) + 'px');
}
}
// 设置鱼骨宽度样式
this._renderer.setStyle(this.itemEl, 'width', this.width);
}
/**
* 设置范围高度
* 设置偏移
* 设置宽度
*/
public setBoneAttribute() {
this._setRangeHeight();
this._setOffset();
this._setWidth();
}
public rectifyEvent = new EventEmitter();
ngOnInit() {
super.ngOnInit();
this._$state = 'in';
this._itemContent = <HTMLElement>this.itemEl.querySelector('.jigsaw-fish-bone-item-content');
this._itemDescription = <HTMLElement>this.itemEl.querySelector('.jigsaw-fish-bone-item-description');
}
ngAfterViewInit() {
// 宽度由最后一个子节点的left值决定,所以要先计算各节点的left偏移量,left偏移量等于前一个同级节点的偏移加rangeHeight
// 如果是第一个节点,默认偏移50,写在css里
// 没有子节点时,默认宽度为100,写在css里
// rangeHeight依赖子节点的宽度
// 先渲染最里面的子节点,逐层向上渲染
// 异步发送事件,为了最外面的父组件能够在ngAfterViewInit中订阅到子组件的事件
// 如果立即发送事件,则父组件订阅不到事件
this.runAfterMicrotasks(() => {
this._zone.run(() => {
this.rectifyEvent.emit();
})
});
// 标识没有子节点的,没有子节点的节点文本放在上面
if (!this.childBones.length) {
this._renderer.addClass(this.itemEl, 'jigsaw-fish-bone-item-no-child');
}
}
}
@NgModule({
imports: [CommonModule, JigsawTrustedHtmlModule],
declarations: [JigsawFishBone, JigsawFishBoneItem],
exports: [JigsawFishBone]
})
export class JigsawFishBoneModule {
} | the_stack |
import useGqlHandler from "./useGqlHandler";
import { Page } from "~/types";
jest.setTimeout(100000);
describe("versioning and publishing pages", () => {
const {
createCategory,
createPage,
publishPage,
updatePage,
deletePage,
unpublishPage,
listPages,
listPublishedPages,
getPublishedPage,
until
} = useGqlHandler();
test("try publishing and unpublishing pages / revisions", async () => {
let [response] = await createCategory({
data: {
slug: `slug`,
name: `name`,
url: `/some-url/`,
layout: `layout`
}
});
const category = response.data.pageBuilder.createCategory.data.slug;
// A dummy page, with which we later ensure only updates on a specific pages are made, not multiple.
await createPage({ category });
// Now this is the page we're gonna work with in the following lines.
// 1. Create p1v1.
const [createP1V1Response] = await createPage({ category });
const p1v1 = createP1V1Response.data.pageBuilder.createPage.data;
expect(p1v1).toMatchObject({
id: /^[a-f0-9]{24}#1$/,
version: 1,
createdFrom: null
});
await until(
() => listPublishedPages({ sort: ["createdOn_DESC"] }),
([res]: any) => res.data.pageBuilder.listPublishedPages.data.length === 0,
{
name: "list published pages after create two pages"
}
);
await until(
() => listPages({ sort: ["createdOn_DESC"] }),
([res]: any) => res.data.pageBuilder.listPages.data.length === 2,
{
name: "list after create two pages"
}
);
const [listResponse] = await listPages({
sort: ["createdOn_DESC"]
});
expect(listResponse).toMatchObject({
data: {
pageBuilder: {
listPages: {
data: [
{
id: p1v1.id,
status: "draft"
},
{
id: expect.any(String),
status: "draft"
}
],
error: null
}
}
}
});
// 2. Create p1v2 from p1v1.
const [createP1V2Response] = await createPage({ from: p1v1.id });
const p1v2 = createP1V2Response.data.pageBuilder.createPage.data;
const [p1v1UniqueId] = p1v1.id.split("#");
expect(p1v2).toMatchObject({
id: p1v1UniqueId + "#0002",
createdFrom: p1v1.id,
version: 2
});
await until(
() => listPublishedPages({ sort: ["createdOn_DESC"] }),
([res]: any) => res.data.pageBuilder.listPublishedPages.data.length === 0,
{
name: "list published pages after create p1v2"
}
).then(([res]) => expect(res.data.pageBuilder.listPublishedPages.error).toBe(null));
await until(
() => listPages({ sort: ["createdOn_DESC"] }),
([res]: any) => res.data.pageBuilder.listPages.data[0].id === p1v2.id,
{
name: `list pages after create p1v2: ${p1v2.id}`
}
).then(([res]) => {
expect(res.data.pageBuilder.listPages.data.length).toBe(2);
expect(res.data.pageBuilder.listPages.data[0]).toMatchObject({
id: p1v2.id,
status: "draft"
});
});
// 3. Create p1v3 from p1v1 as well.
const p1v3 = await createPage({ from: p1v1.id }).then(
([res]) => res.data.pageBuilder.createPage.data
);
expect(p1v3).toMatchObject({
id: p1v1UniqueId + "#0003",
createdFrom: p1v1.id,
version: 3
});
await until(
() => listPublishedPages({ sort: ["createdOn_DESC"] }),
([res]: any) => res.data.pageBuilder.listPublishedPages.data.length === 0,
{
name: "list published pages after create p1v3"
}
).then(([res]) => expect(res.data.pageBuilder.listPublishedPages.error).toBe(null));
await until(
() => listPages({ sort: ["createdOn_DESC"] }),
([res]: any) => res.data.pageBuilder.listPages.data[0].id === p1v3.id,
{
name: "list pages after create create p1v3"
}
).then(([res]) => {
expect(res.data.pageBuilder.listPages.data.length).toBe(2);
expect(res.data.pageBuilder.listPages.data[0]).toMatchObject({
id: p1v3.id,
status: "draft"
});
});
// 4. Let's try publishing the p1v2.
const [p1v2PublishResponse] = await publishPage({ id: p1v2.id });
expect(p1v2PublishResponse).toMatchObject({
data: {
pageBuilder: {
publishPage: {
data: {
id: p1v2.id,
status: "published",
publishedOn: expect.stringMatching(/^20/),
category: {
slug: "slug"
},
version: 2,
title: "Untitled"
},
error: null
}
}
}
});
const [listPagesAfterPublishP1V2Response] = await until(
() => listPages({ sort: ["createdOn_DESC"] }),
([res]: any) => res.data.pageBuilder.listPages.data.length === 2,
{
name: "list pages after publish p1v2"
}
);
expect(listPagesAfterPublishP1V2Response).toEqual({
data: {
pageBuilder: {
listPages: {
data: [expect.any(Object), expect.any(Object)],
error: null,
meta: expect.any(Object)
}
}
}
});
const [listPublishedPagesAfterPublishP1V2Response] = await until(
() => listPublishedPages({ sort: ["createdOn_DESC"] }),
([res]: any) => res.data.pageBuilder.listPublishedPages.data[0].id === p1v2.id,
{
name: "list published pages after publish p1v2"
}
);
expect(
listPublishedPagesAfterPublishP1V2Response.data.pageBuilder.listPublishedPages.data
.length
).toBe(1);
expect(
listPublishedPagesAfterPublishP1V2Response.data.pageBuilder.listPublishedPages.data[0]
).toMatchObject({
id: p1v2.id,
status: "published"
});
// 5. Let's try creating a new version (v4) from published p1v2 and publish that.
[response] = await createPage({ from: p1v2.id });
const p1v4 = response.data.pageBuilder.createPage.data;
expect(p1v4).toMatchObject({
id: p1v1UniqueId + "#0004",
createdFrom: p1v2.id,
version: 4
});
await until(
() => listPages({ sort: ["createdOn_DESC"] }),
([res]: any) => {
return res.data.pageBuilder.listPages.data.some((page: Page) => {
return page.id === p1v4.id;
});
},
{
name: "make sure list includes new p1v4 page"
}
);
// 5.2. Make sure published pages doesn't include the new p1v4 page in the list.
const [listPublishedPagesNoP1V4Response] = await until(
() => listPublishedPages({ sort: ["createdOn_DESC"] }),
([res]: any) => {
return res.data.pageBuilder.listPublishedPages.data.every((page: Page) => {
return page.id !== p1v4.id;
});
},
{
name: "make sure published list does not include new p1v4 page"
}
);
expect(
listPublishedPagesNoP1V4Response.data.pageBuilder.listPublishedPages.data.length
).toBe(1);
// 5.3. Let's publish and check the lists again.
const [publishP1V4Response] = await publishPage({ id: p1v4.id });
expect(publishP1V4Response).toMatchObject({
data: {
pageBuilder: {
publishPage: {
data: {
id: p1v4.id,
status: "published",
publishedOn: expect.stringMatching(/^20/),
category: {
slug: "slug"
},
version: 4,
title: "Untitled"
},
error: null
}
}
}
});
await until(
() => listPages({ sort: ["createdOn_DESC"] }),
([res]: any) => {
return res.data.pageBuilder.listPages.data.some((page: Page) => {
return page.id === p1v4.id;
});
},
{
name: "make sure list includes new p1v4 page #2 run"
}
);
const [listPublishedIncludesP1V4] = await until(
() => listPublishedPages({ sort: ["createdOn_DESC"] }),
([res]: any) => {
return res.data.pageBuilder.listPublishedPages.data.some((page: Page) => {
return page.id === p1v4.id;
});
},
{
name: "make sure published list includes new p1v4 page"
}
);
expect(listPublishedIncludesP1V4.data.pageBuilder.listPublishedPages.data.length).toBe(1);
expect(listPublishedIncludesP1V4.data.pageBuilder.listPublishedPages.data[0].id).toBe(
p1v4.id
);
// 6. Let's try to un-publish the page. First, the wrong one, then the correct one.
const [unpublishP1V3Response] = await unpublishPage({ id: p1v3.id });
expect(unpublishP1V3Response).toEqual({
data: {
pageBuilder: {
unpublishPage: {
data: null,
error: {
code: "",
data: null,
message: `Page is not published.`
}
}
}
}
});
// Now let's try the correct one.
const [unpublishP1V4Response] = await unpublishPage({ id: p1v4.id });
expect(unpublishP1V4Response).toMatchObject({
data: {
pageBuilder: {
unpublishPage: {
data: {
id: p1v4.id,
status: "unpublished",
publishedOn: expect.stringMatching(/^20/),
category: {
slug: "slug"
},
version: 4,
title: "Untitled"
},
error: null
}
}
}
});
await until(
() => listPublishedPages({ sort: ["createdOn_DESC"] }),
([res]: any) => {
return res.data.pageBuilder.listPublishedPages.data.length === 0;
},
{
name: "make sure published list does not contain any pages"
}
);
});
test("must be able to publish a page with the same URL as an already previously-published page", async () => {
await createCategory({
data: {
slug: `slug`,
name: `name`,
url: `/some-url/`,
layout: `layout`
}
});
const p1 = await createPage({ category: "slug" }).then(
async ([res]) => res.data.pageBuilder.createPage.data
);
await updatePage({ id: p1.id, data: { path: "/pages-test" } }).then(([res]) =>
expect(res.data.pageBuilder.updatePage.data.id).toBe(p1.id)
);
const p2 = await createPage({ category: "slug" }).then(
async ([res]) => res.data.pageBuilder.createPage.data
);
await updatePage({ id: p2.id, data: { path: "/pages-test" } }).then(([res]) =>
expect(res.data.pageBuilder.updatePage.data.id).toBe(p2.id)
);
// Try publishing 2nd page, it should work.
await publishPage({ id: p2.id });
await getPublishedPage({ path: "/pages-test" }).then(([res]) => {
expect(res.data.pageBuilder.getPublishedPage.data.id).toBe(p2.id);
});
// Now, if we try to publish 1st page, we should still be able to do it.
await publishPage({ id: p1.id });
await getPublishedPage({ path: "/pages-test" }).then(([res]) =>
expect(res.data.pageBuilder.getPublishedPage.data.id).toBe(p1.id)
);
});
test("upon publishing, if the path of the page has changed, previously published URL must not exist", async () => {
await createCategory({
data: {
slug: `slug`,
name: `name`,
url: `/some-url/`,
layout: `layout`
}
});
const p1v1 = await createPage({ category: "slug" }).then(
([res]) => res.data.pageBuilder.createPage.data
);
await updatePage({ id: p1v1.id, data: { path: "/pages-test" } }).then(([res]) =>
expect(res.data.pageBuilder.updatePage.data.id).toBe(p1v1.id)
);
// Try publishing 2nd page, it should work.
await publishPage({ id: p1v1.id });
await getPublishedPage({ path: "/pages-test" }).then(([res]) => {
expect(res.data.pageBuilder.getPublishedPage.data.id).toBe(p1v1.id);
});
const p1v2 = await createPage({ from: p1v1.id }).then(
async ([res]) => res.data.pageBuilder.createPage.data
);
await updatePage({
id: p1v2.id,
data: { path: "/pages-test-updated" }
}).then(([res]) => {
expect(res.data.pageBuilder.updatePage.data.id).toBe(p1v2.id);
});
// Now, if we try to publish 1st page, we should still be able to do it.
await publishPage({ id: p1v2.id });
await getPublishedPage({ path: "/pages-test-updated" }).then(([res]) => {
expect(res.data.pageBuilder.getPublishedPage.data.id).toBe(p1v2.id);
});
// This one should not return any results - it's an old URL.
await getPublishedPage({ path: "/pages-test" }).then(([res]) =>
expect(res).toEqual({
data: {
pageBuilder: {
getPublishedPage: {
data: null,
error: {
code: "NOT_FOUND",
data: null,
message: "Page not found."
}
}
}
}
})
);
});
test("once a page has been deleted, it should not be available via the previous published path", async () => {
await createCategory({
data: {
slug: `slug`,
name: `name`,
url: `/some-url/`,
layout: `layout`
}
});
const p1v1 = await createPage({ category: "slug" }).then(
([res]) => res.data.pageBuilder.createPage.data
);
await updatePage({ id: p1v1.id, data: { path: "/pages-test" } }).then(([res]) =>
expect(res.data.pageBuilder.updatePage.data.id).toBe(p1v1.id)
);
// Try publishing 2nd page, it should work.
await publishPage({ id: p1v1.id });
await deletePage({ id: p1v1.id });
// This one should not return any results - it's an old URL.
await getPublishedPage({ path: "/pages-test" }).then(([res]) =>
expect(res).toEqual({
data: {
pageBuilder: {
getPublishedPage: {
data: null,
error: {
code: "NOT_FOUND",
data: null,
message: "Page not found."
}
}
}
}
})
);
});
test("once a page has been unpublished, it should not be available via the previous published path", async () => {
await createCategory({
data: {
slug: `slug`,
name: `name`,
url: `/some-url/`,
layout: `layout`
}
});
const p1v1 = await createPage({ category: "slug" }).then(
([res]) => res.data.pageBuilder.createPage.data
);
await updatePage({
id: p1v1.id,
data: { path: "/pages-test" }
}).then(([res]) => expect(res.data.pageBuilder.updatePage.data.id).toBe(p1v1.id));
// Try publishing 2nd page, it should work.
await publishPage({ id: p1v1.id });
const [getPublishedResponse] = await getPublishedPage({ path: "/pages-test" });
expect(getPublishedResponse).toMatchObject({
data: {
pageBuilder: {
getPublishedPage: {
data: {
category: {
slug: "slug"
},
locked: true,
path: "/pages-test",
settings: {
general: {
image: null,
layout: "layout",
snippet: null,
tags: null
},
seo: {
description: null,
meta: [],
title: null
},
social: {
description: null,
image: null,
meta: [],
title: null
}
},
status: "published",
title: "Untitled",
url: "/pages-test",
version: 1
},
error: null
}
}
}
});
await unpublishPage({ id: p1v1.id });
// This one should not return any results - it's an old URL.
const [getPublishedPageAfterUnpublishedResponse] = await getPublishedPage({
path: "/pages-test"
});
expect(getPublishedPageAfterUnpublishedResponse).toEqual({
data: {
pageBuilder: {
getPublishedPage: {
data: null,
error: {
code: "NOT_FOUND",
data: null,
message: "Page not found."
}
}
}
}
});
});
}); | the_stack |
import { Match, Template } from '@aws-cdk/assertions';
import { Stack } from '@aws-cdk/core';
import * as apigw from '../lib';
/* eslint-disable quote-props */
describe('resource', () => {
test('ProxyResource defines a "{proxy+}" resource with ANY method', () => {
// GIVEN
const stack = new Stack();
const api = new apigw.RestApi(stack, 'api');
// WHEN
new apigw.ProxyResource(stack, 'proxy', {
parent: api.root,
});
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Resource', {
'ParentId': {
'Fn::GetAtt': [
'apiC8550315',
'RootResourceId',
],
},
'PathPart': '{proxy+}',
'RestApiId': {
'Ref': 'apiC8550315',
},
});
Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Method', {
'HttpMethod': 'ANY',
'ResourceId': {
'Ref': 'proxy3A1DA9C7',
},
'RestApiId': {
'Ref': 'apiC8550315',
},
'AuthorizationType': 'NONE',
'Integration': {
'Type': 'MOCK',
},
});
});
test('if "anyMethod" is false, then an ANY method will not be defined', () => {
// GIVEN
const stack = new Stack();
const api = new apigw.RestApi(stack, 'api');
// WHEN
const proxy = new apigw.ProxyResource(stack, 'proxy', {
parent: api.root,
anyMethod: false,
});
proxy.addMethod('GET');
// THEN
Template.fromStack(stack).resourceCountIs('AWS::ApiGateway::Resource', 1);
Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Method', { 'HttpMethod': 'GET' });
Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Method', Match.not({ 'HttpMethod': 'ANY' }));
});
test('addProxy can be used on any resource to attach a proxy from that route', () => {
// GIVEN
const stack = new Stack();
const api = new apigw.RestApi(stack, 'api', {
deploy: false,
cloudWatchRole: false,
});
const v2 = api.root.addResource('v2');
v2.addProxy();
Template.fromStack(stack).templateMatches({
'Resources': {
'apiC8550315': {
'Type': 'AWS::ApiGateway::RestApi',
'Properties': {
'Name': 'api',
},
},
'apiv25206B108': {
'Type': 'AWS::ApiGateway::Resource',
'Properties': {
'ParentId': {
'Fn::GetAtt': [
'apiC8550315',
'RootResourceId',
],
},
'PathPart': 'v2',
'RestApiId': {
'Ref': 'apiC8550315',
},
},
},
'apiv2proxyAEA4DAC8': {
'Type': 'AWS::ApiGateway::Resource',
'Properties': {
'ParentId': {
'Ref': 'apiv25206B108',
},
'PathPart': '{proxy+}',
'RestApiId': {
'Ref': 'apiC8550315',
},
},
},
'apiv2proxyANY889F4CE1': {
'Type': 'AWS::ApiGateway::Method',
'Properties': {
'HttpMethod': 'ANY',
'ResourceId': {
'Ref': 'apiv2proxyAEA4DAC8',
},
'RestApiId': {
'Ref': 'apiC8550315',
},
'AuthorizationType': 'NONE',
'Integration': {
'Type': 'MOCK',
},
},
},
},
});
});
test('if proxy is added to root, proxy methods are automatically duplicated (with integration and options)', () => {
// GIVEN
const stack = new Stack();
const api = new apigw.RestApi(stack, 'api');
const proxy = api.root.addProxy({
anyMethod: false,
});
const deleteInteg = new apigw.MockIntegration({
requestParameters: {
foo: 'bar',
},
});
// WHEN
proxy.addMethod('DELETE', deleteInteg, {
operationName: 'DeleteMe',
});
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Method', {
HttpMethod: 'DELETE',
ResourceId: { Ref: 'apiproxy4EA44110' },
Integration: {
RequestParameters: { foo: 'bar' },
Type: 'MOCK',
},
OperationName: 'DeleteMe',
});
Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Method', {
HttpMethod: 'DELETE',
ResourceId: { 'Fn::GetAtt': ['apiC8550315', 'RootResourceId'] },
Integration: {
RequestParameters: { foo: 'bar' },
Type: 'MOCK',
},
OperationName: 'DeleteMe',
});
});
test('if proxy is added to root, proxy methods are only added if they are not defined already on the root resource', () => {
// GIVEN
const stack = new Stack();
const api = new apigw.RestApi(stack, 'api');
api.root.addMethod('POST');
const proxy = api.root.addProxy({ anyMethod: false });
// WHEN
proxy.addMethod('POST');
// THEN
});
test('url for a resource', () => {
// GIVEN
const stack = new Stack();
const api = new apigw.RestApi(stack, 'api');
// WHEN
const aResource = api.root.addResource('a');
const cResource = aResource.addResource('b').addResource('c');
// THEN
expect(stack.resolve(api.urlForPath(aResource.path))).toEqual({
'Fn::Join': [
'',
[
'https://',
{ Ref: 'apiC8550315' },
'.execute-api.',
{ Ref: 'AWS::Region' },
'.',
{ Ref: 'AWS::URLSuffix' },
'/',
{ Ref: 'apiDeploymentStageprod896C8101' },
'/a',
],
],
});
expect(stack.resolve(api.urlForPath(cResource.path))).toEqual({
'Fn::Join': [
'',
[
'https://',
{ Ref: 'apiC8550315' },
'.execute-api.',
{ Ref: 'AWS::Region' },
'.',
{ Ref: 'AWS::URLSuffix' },
'/',
{ Ref: 'apiDeploymentStageprod896C8101' },
'/a/b/c',
],
],
});
});
test('fromResourceAttributes()', () => {
// GIVEN
const stack = new Stack();
const resourceId = 'resource-id';
const api = new apigw.RestApi(stack, 'MyRestApi');
// WHEN
const imported = apigw.Resource.fromResourceAttributes(stack, 'imported-resource', {
resourceId,
restApi: api,
path: 'some-path',
});
imported.addMethod('GET');
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::ApiGateway::Method', {
HttpMethod: 'GET',
ResourceId: resourceId,
});
});
describe('getResource', () => {
describe('root resource', () => {
test('returns undefined if not found', () => {
// GIVEN
const stack = new Stack();
const api = new apigw.RestApi(stack, 'MyRestApi');
// THEN
expect(api.root.getResource('boom')).toBeUndefined();
});
test('returns the resource if found', () => {
// GIVEN
const stack = new Stack();
const api = new apigw.RestApi(stack, 'MyRestApi');
// WHEN
const r1 = api.root.addResource('hello');
const r2 = api.root.addResource('world');
// THEN
expect(api.root.getResource('hello')).toEqual(r1);
expect(api.root.getResource('world')).toEqual(r2);
});
test('returns the resource even if it was created using "new"', () => {
// GIVEN
const stack = new Stack();
const api = new apigw.RestApi(stack, 'MyRestApi');
// WHEN
const r1 = new apigw.Resource(stack, 'child', {
parent: api.root,
pathPart: 'yello',
});
// THEN
expect(api.root.getResource('yello')).toEqual(r1);
});
});
describe('non-root', () => {
test('returns undefined if not found', () => {
// GIVEN
const stack = new Stack();
const api = new apigw.RestApi(stack, 'MyRestApi');
const res = api.root.addResource('boom');
// THEN
expect(res.getResource('child-of-boom')).toBeUndefined();
});
test('returns the resource if found', () => {
// GIVEN
const stack = new Stack();
const api = new apigw.RestApi(stack, 'MyRestApi');
const child = api.root.addResource('boom');
// WHEN
const r1 = child.addResource('hello');
const r2 = child.addResource('world');
// THEN
expect(child.getResource('hello')).toEqual(r1);
expect(child.getResource('world')).toEqual(r2);
});
test('returns the resource even if created with "new"', () => {
// GIVEN
const stack = new Stack();
const api = new apigw.RestApi(stack, 'MyRestApi');
const child = api.root.addResource('boom');
// WHEN
const r1 = child.addResource('hello');
const r2 = new apigw.Resource(stack, 'world', {
parent: child,
pathPart: 'outside-world',
});
// THEN
expect(child.getResource('hello')).toEqual(r1);
expect(child.getResource('outside-world')).toEqual(r2);
});
});
describe('resourceForPath', () => {
test('empty path or "/" (on root) returns this', () => {
// GIVEN
const stack = new Stack();
const api = new apigw.RestApi(stack, 'MyRestApi');
// THEN
expect(api.root.resourceForPath('')).toEqual(api.root);
expect(api.root.resourceForPath('/')).toEqual(api.root);
expect(api.root.resourceForPath('///')).toEqual(api.root);
});
test('returns a resource for that path', () => {
// GIVEN
const stack = new Stack();
const api = new apigw.RestApi(stack, 'MyRestApi');
// WHEN
const resource = api.root.resourceForPath('/boom/trach');
// THEN
expect(resource.path).toEqual('/boom/trach');
});
test('resources not created if not needed', () => {
// GIVEN
const stack = new Stack();
const api = new apigw.RestApi(stack, 'MyRestApi');
// WHEN
const trach = api.root.resourceForPath('/boom/trach');
const bam1 = api.root.resourceForPath('/boom/bam');
// THEN
const parent = api.root.getResource('boom');
expect(parent).toBeDefined();
expect(parent!.path).toEqual('/boom');
expect(trach.parentResource).toBe(parent);
expect(trach.parentResource!.path).toEqual('/boom');
const bam2 = api.root.resourceForPath('/boom/bam');
expect(bam1).toBe(bam2);
expect(bam1.parentResource!.path).toEqual('/boom');
});
});
});
}); | the_stack |
import {Spec, Test, Exam} from "@swim/unit";
import {DateTime, TimeInterval} from "@swim/time";
export class TimeIntervalSpec extends Spec {
@Test
testRoundYearFloor(exam: Exam): void {
exam.equal(TimeInterval.year.floor(DateTime.fromInit({year: 2018})).toString(), "2018-01-01T00:00:00.000Z");
}
@Test
testRoundYearCeil(exam: Exam): void {
exam.equal(TimeInterval.year.ceil(DateTime.fromInit({year: 2018})).toString(), "2018-01-01T00:00:00.000Z");
}
@Test
testRoundMonthYearCeil(exam: Exam): void {
exam.equal(TimeInterval.year.ceil(DateTime.fromInit({year: 2018, month: 0, day: 2})).toString(), "2019-01-01T00:00:00.000Z");
}
@Test
testRoundMonthFloor(exam: Exam): void {
exam.equal(TimeInterval.month.floor(DateTime.fromInit({year: 2018, month: 8})).toString(), "2018-09-01T00:00:00.000Z");
}
@Test
testRoundMonthCeil(exam: Exam): void {
exam.equal(TimeInterval.month.ceil(DateTime.fromInit({year: 2018, month: 8, day: 2})).toString(), "2018-10-01T00:00:00.000Z");
}
@Test
testRoundDayFloor(exam: Exam): void {
exam.equal(TimeInterval.day.floor(DateTime.fromInit({year: 2018, month: 8, day: 15})).toString(), "2018-09-15T00:00:00.000Z");
}
@Test
testRoundDayCeil(exam: Exam): void {
exam.equal(TimeInterval.day.ceil(DateTime.fromInit({year: 2018, month: 8, day: 15, hour: 1})).toString(), "2018-09-16T00:00:00.000Z");
}
@Test
testYearFloor(exam: Exam): void {
exam.equal(TimeInterval.year.floor(DateTime.fromInit({year: 2018, month: 5, day: 30})).toString(), "2018-01-01T00:00:00.000Z");
}
@Test
testYearCeil(exam: Exam): void {
exam.equal(TimeInterval.year.ceil(DateTime.fromInit({year: 2018, month: 5, day: 30})).toString(), "2019-01-01T00:00:00.000Z");
}
@Test
testMonthFloorHalf(exam: Exam): void {
exam.equal(TimeInterval.month.floor(DateTime.fromInit({year: 2018, month: 5, day: 15})).toString(), "2018-06-01T00:00:00.000Z");
}
@Test
testMonthFloor(exam: Exam): void {
exam.equal(TimeInterval.month.floor(DateTime.fromInit({year: 2018, month: 5, day: 30})).toString(), "2018-06-01T00:00:00.000Z");
}
@Test
testMonthCeil(exam: Exam): void {
exam.equal(TimeInterval.month.ceil(DateTime.fromInit({year: 2018, month: 5, day: 30})).toString(), "2018-07-01T00:00:00.000Z");
}
@Test
testWeekFloor(exam: Exam): void {
exam.equal(TimeInterval.week.floor(DateTime.fromInit({year: 2018, month: 6, day: 16})).toString(), "2018-07-15T00:00:00.000Z");
}
@Test
testWeekCeil(exam: Exam): void {
exam.equal(TimeInterval.week.ceil(DateTime.fromInit({year: 2018, month: 6, day: 16})).toString(), "2018-07-22T00:00:00.000Z");
}
@Test
testSecondWeekCeil(exam: Exam): void {
exam.equal(TimeInterval.week.ceil(DateTime.fromInit({year: 2018, month: 4, day: 10})).toString(), "2018-05-13T00:00:00.000Z");
}
@Test
testDayFloor(exam: Exam): void {
exam.equal(TimeInterval.day.floor(DateTime.fromInit({year: 2018, month: 5, day: 15, hour: 5, minute: 16, second: 10})).toString(), "2018-06-15T00:00:00.000Z");
}
@Test
testDayCeil(exam: Exam): void {
exam.equal(TimeInterval.day.ceil(DateTime.fromInit({year: 2018, month: 5, day: 15, hour: 5, minute: 16, second: 10})).toString(), "2018-06-16T00:00:00.000Z");
}
@Test
testHourFloor(exam: Exam): void {
exam.equal(TimeInterval.hour.floor(DateTime.fromInit({year: 2018, month: 5, day: 15, hour: 5, minute: 16, second: 10})).toString(), "2018-06-15T05:00:00.000Z");
}
@Test
testHourCeil(exam: Exam): void {
exam.equal(TimeInterval.hour.ceil(DateTime.fromInit({year: 2018, month: 5, day: 15, hour: 5, minute: 16, second: 10})).toString(), "2018-06-15T06:00:00.000Z");
}
@Test
testMinuteFloor(exam: Exam): void {
exam.equal(TimeInterval.minute.floor(DateTime.fromInit({year: 2018, month: 5, day: 15, hour: 5, minute: 16, second: 10})).toString(), "2018-06-15T05:16:00.000Z");
}
@Test
testMinuteCeil(exam: Exam): void {
exam.equal(TimeInterval.minute.ceil(DateTime.fromInit({year: 2018, month: 5, day: 15, hour: 5, minute: 16, second: 10})).toString(), "2018-06-15T05:17:00.000Z");
}
@Test
testSecondFloor(exam: Exam): void {
exam.equal(TimeInterval.minute.floor(DateTime.fromInit({year: 2018, month: 5, day: 15, hour: 5, minute: 16, second: 10, millisecond: 500})).toString(), "2018-06-15T05:16:00.000Z");
}
@Test
testSecondCeil(exam: Exam): void {
exam.equal(TimeInterval.minute.ceil(DateTime.fromInit({year: 2018, month: 5, day: 15, hour: 5, minute: 16, second: 10, millisecond: 500})).toString(), "2018-06-15T05:17:00.000Z");
}
@Test
testYears(exam: Exam): void {
exam.equal(TimeInterval.years(DateTime.fromInit({year: 2011}), DateTime.fromInit({year: 2014})), [
DateTime.parse("2011-01-01T00:00:00.000Z"),
DateTime.parse("2012-01-01T00:00:00.000Z"),
DateTime.parse("2013-01-01T00:00:00.000Z"),
]);
}
@Test
testMonths(exam: Exam): void {
exam.equal(TimeInterval.months(DateTime.fromInit({year: 2011}), DateTime.fromInit({year: 2012})), [
DateTime.parse("2011-01-01T00:00:00.000Z"),
DateTime.parse("2011-02-01T00:00:00.000Z"),
DateTime.parse("2011-03-01T00:00:00.000Z"),
DateTime.parse("2011-04-01T00:00:00.000Z"),
DateTime.parse("2011-05-01T00:00:00.000Z"),
DateTime.parse("2011-06-01T00:00:00.000Z"),
DateTime.parse("2011-07-01T00:00:00.000Z"),
DateTime.parse("2011-08-01T00:00:00.000Z"),
DateTime.parse("2011-09-01T00:00:00.000Z"),
DateTime.parse("2011-10-01T00:00:00.000Z"),
DateTime.parse("2011-11-01T00:00:00.000Z"),
DateTime.parse("2011-12-01T00:00:00.000Z"),
]);
}
@Test
testYearWeekInterval(exam: Exam): void {
exam.equal(TimeInterval.weeks(DateTime.fromInit({year: 2012}), DateTime.fromInit({year: 2013})), [
DateTime.parse("2012-01-01T00:00:00.000Z"),
DateTime.parse("2012-01-08T00:00:00.000Z"),
DateTime.parse("2012-01-15T00:00:00.000Z"),
DateTime.parse("2012-01-22T00:00:00.000Z"),
DateTime.parse("2012-01-29T00:00:00.000Z"),
DateTime.parse("2012-02-05T00:00:00.000Z"),
DateTime.parse("2012-02-12T00:00:00.000Z"),
DateTime.parse("2012-02-19T00:00:00.000Z"),
DateTime.parse("2012-02-26T00:00:00.000Z"),
DateTime.parse("2012-03-04T00:00:00.000Z"),
DateTime.parse("2012-03-11T00:00:00.000Z"),
DateTime.parse("2012-03-18T00:00:00.000Z"),
DateTime.parse("2012-03-25T00:00:00.000Z"),
DateTime.parse("2012-04-01T00:00:00.000Z"),
DateTime.parse("2012-04-08T00:00:00.000Z"),
DateTime.parse("2012-04-15T00:00:00.000Z"),
DateTime.parse("2012-04-22T00:00:00.000Z"),
DateTime.parse("2012-04-29T00:00:00.000Z"),
DateTime.parse("2012-05-06T00:00:00.000Z"),
DateTime.parse("2012-05-13T00:00:00.000Z"),
DateTime.parse("2012-05-20T00:00:00.000Z"),
DateTime.parse("2012-05-27T00:00:00.000Z"),
DateTime.parse("2012-06-03T00:00:00.000Z"),
DateTime.parse("2012-06-10T00:00:00.000Z"),
DateTime.parse("2012-06-17T00:00:00.000Z"),
DateTime.parse("2012-06-24T00:00:00.000Z"),
DateTime.parse("2012-07-01T00:00:00.000Z"),
DateTime.parse("2012-07-08T00:00:00.000Z"),
DateTime.parse("2012-07-15T00:00:00.000Z"),
DateTime.parse("2012-07-22T00:00:00.000Z"),
DateTime.parse("2012-07-29T00:00:00.000Z"),
DateTime.parse("2012-08-05T00:00:00.000Z"),
DateTime.parse("2012-08-12T00:00:00.000Z"),
DateTime.parse("2012-08-19T00:00:00.000Z"),
DateTime.parse("2012-08-26T00:00:00.000Z"),
DateTime.parse("2012-09-02T00:00:00.000Z"),
DateTime.parse("2012-09-09T00:00:00.000Z"),
DateTime.parse("2012-09-16T00:00:00.000Z"),
DateTime.parse("2012-09-23T00:00:00.000Z"),
DateTime.parse("2012-09-30T00:00:00.000Z"),
DateTime.parse("2012-10-07T00:00:00.000Z"),
DateTime.parse("2012-10-14T00:00:00.000Z"),
DateTime.parse("2012-10-21T00:00:00.000Z"),
DateTime.parse("2012-10-28T00:00:00.000Z"),
DateTime.parse("2012-11-04T00:00:00.000Z"),
DateTime.parse("2012-11-11T00:00:00.000Z"),
DateTime.parse("2012-11-18T00:00:00.000Z"),
DateTime.parse("2012-11-25T00:00:00.000Z"),
DateTime.parse("2012-12-02T00:00:00.000Z"),
DateTime.parse("2012-12-09T00:00:00.000Z"),
DateTime.parse("2012-12-16T00:00:00.000Z"),
DateTime.parse("2012-12-23T00:00:00.000Z"),
DateTime.parse("2012-12-30T00:00:00.000Z"),
]);
}
@Test
testMonthWeekInterval(exam: Exam): void {
exam.equal(TimeInterval.weeks(DateTime.fromInit({year: 2018, month: 0}), DateTime.fromInit({year: 2018, month: 1})), [
DateTime.parse("2018-01-07T00:00:00.000Z"),
DateTime.parse("2018-01-14T00:00:00.000Z"),
DateTime.parse("2018-01-21T00:00:00.000Z"),
DateTime.parse("2018-01-28T00:00:00.000Z"),
]);
}
@Test
testDays(exam: Exam): void {
exam.equal(TimeInterval.days(DateTime.fromInit({year: 2011, month: 0}), DateTime.fromInit({year: 2011, month: 1})), [
DateTime.parse("2011-01-01T00:00:00.000Z"),
DateTime.parse("2011-01-02T00:00:00.000Z"),
DateTime.parse("2011-01-03T00:00:00.000Z"),
DateTime.parse("2011-01-04T00:00:00.000Z"),
DateTime.parse("2011-01-05T00:00:00.000Z"),
DateTime.parse("2011-01-06T00:00:00.000Z"),
DateTime.parse("2011-01-07T00:00:00.000Z"),
DateTime.parse("2011-01-08T00:00:00.000Z"),
DateTime.parse("2011-01-09T00:00:00.000Z"),
DateTime.parse("2011-01-10T00:00:00.000Z"),
DateTime.parse("2011-01-11T00:00:00.000Z"),
DateTime.parse("2011-01-12T00:00:00.000Z"),
DateTime.parse("2011-01-13T00:00:00.000Z"),
DateTime.parse("2011-01-14T00:00:00.000Z"),
DateTime.parse("2011-01-15T00:00:00.000Z"),
DateTime.parse("2011-01-16T00:00:00.000Z"),
DateTime.parse("2011-01-17T00:00:00.000Z"),
DateTime.parse("2011-01-18T00:00:00.000Z"),
DateTime.parse("2011-01-19T00:00:00.000Z"),
DateTime.parse("2011-01-20T00:00:00.000Z"),
DateTime.parse("2011-01-21T00:00:00.000Z"),
DateTime.parse("2011-01-22T00:00:00.000Z"),
DateTime.parse("2011-01-23T00:00:00.000Z"),
DateTime.parse("2011-01-24T00:00:00.000Z"),
DateTime.parse("2011-01-25T00:00:00.000Z"),
DateTime.parse("2011-01-26T00:00:00.000Z"),
DateTime.parse("2011-01-27T00:00:00.000Z"),
DateTime.parse("2011-01-28T00:00:00.000Z"),
DateTime.parse("2011-01-29T00:00:00.000Z"),
DateTime.parse("2011-01-30T00:00:00.000Z"),
DateTime.parse("2011-01-31T00:00:00.000Z"),
]);
}
@Test
testNextYear(exam: Exam): void {
exam.equal(TimeInterval.year.next(DateTime.fromInit({year: 2017, month: 7, day: 15})).toString(), "2018-01-01T00:00:00.000Z");
}
@Test
testNextTwoYear(exam: Exam): void {
exam.equal(TimeInterval.year.next(DateTime.fromInit({year: 2017}), 2).toString(), "2019-01-01T00:00:00.000Z");
}
@Test
testNextMonth(exam: Exam): void {
exam.equal(TimeInterval.month.next(DateTime.fromInit({year: 2018, month: 5})).toString(), "2018-07-01T00:00:00.000Z");
}
@Test
testNextThreeMonth(exam: Exam): void {
exam.equal(TimeInterval.month.next(DateTime.fromInit({year: 2018, month: 5}), 3).toString(), "2018-09-01T00:00:00.000Z");
}
@Test
testNextWeek(exam: Exam): void {
exam.equal(TimeInterval.week.next(DateTime.fromInit({year:2018, month: 4, day: 19})).toString(), "2018-05-20T00:00:00.000Z");
}
@Test
testNextDay(exam: Exam): void {
exam.equal(TimeInterval.day.next(DateTime.fromInit({year: 2018, month: 5, day: 15})).toString(), "2018-06-16T00:00:00.000Z");
}
@Test
testNextFourDay(exam: Exam): void {
exam.equal(TimeInterval.day.next(DateTime.fromInit({year: 2018, month: 5, day: 27}), 4).toString(), "2018-07-01T00:00:00.000Z");
}
@Test
testDay(exam: Exam): void {
exam.equal(TimeInterval.day.next(DateTime.fromInit({year: 2018, month: 5, day: 45})).toString(), "2018-07-16T00:00:00.000Z");
}
@Test
testNextHour(exam: Exam): void {
exam.equal(TimeInterval.hour.next(DateTime.fromInit({year: 2018, month: 5, day: 20, hour: 6})).toString(), "2018-06-20T07:00:00.000Z");
}
@Test
testNextMinute(exam: Exam): void {
exam.equal(TimeInterval.minute.next(DateTime.fromInit({year: 2018, month: 5, day: 20, hour: 6, minute: 30, second: 0})).toString(), "2018-06-20T06:31:00.000Z");
}
@Test
testNextSecond(exam: Exam): void {
exam.equal(TimeInterval.second.next(DateTime.fromInit({year: 2018, month: 5, day: 20, hour: 6, minute: 30, second: 0})).toString(), "2018-06-20T06:30:01.000Z");
}
@Test
textNextMillionSecond(exam: Exam): void {
exam.equal(TimeInterval.millisecond.next(DateTime.fromInit({year:2018, month: 5, day: 20, hour: 6, minute: 30, millisecond: 500})).toString(), "2018-06-20T06:30:00.501Z");
}
@Test
testRoundYearDown(exam: Exam): void {
exam.equal(TimeInterval.year.round(DateTime.fromInit({year: 2018, month: 2})).toString(), "2018-01-01T00:00:00.000Z");
}
@Test
testRoundYearUp(exam: Exam): void {
exam.equal(TimeInterval.year.round(DateTime.fromInit({year: 2018, month: 7, day: 1})).toString(), "2019-01-01T00:00:00.000Z");
}
@Test
testRoundMonthDown(exam: Exam): void {
exam.equal(TimeInterval.month.round(DateTime.fromInit({year: 2018, month: 1, day: 11})).toString(), "2018-02-01T00:00:00.000Z");
}
@Test
testRoundMonthUp(exam: Exam): void {
exam.equal(TimeInterval.month.round(DateTime.fromInit({year: 2018, month: 1, day: 22})).toString(), "2018-03-01T00:00:00.000Z");
}
@Test
testRoundDayDown(exam: Exam): void {
exam.equal(TimeInterval.day.round(DateTime.fromInit({year: 2018, month: 4, day: 25, hour: 6})).toString(), "2018-05-25T00:00:00.000Z");
}
@Test
testRoundDayUp(exam: Exam): void {
exam.equal(TimeInterval.day.round(DateTime.fromInit({year: 2018, month: 4, day: 25, hour: 14})).toString(), "2018-05-26T00:00:00.000Z");
}
@Test
testRoundHourDown(exam: Exam): void {
exam.equal(TimeInterval.hour.round(DateTime.fromInit({year: 2018, month: 4, day: 25, hour: 7, minute: 29})).toString(), "2018-05-25T07:00:00.000Z");
}
@Test
testRoundHourUp(exam: Exam): void {
exam.equal(TimeInterval.hour.round(DateTime.fromInit({year: 2018, month: 4, day: 25, hour: 7, minute: 40})).toString(), "2018-05-25T08:00:00.000Z");
}
@Test
testRoundMinuteDown(exam: Exam): void {
exam.equal( TimeInterval.minute.round(DateTime.fromInit({year: 2018, month: 4, day: 25, hour: 7, minute: 29, second: 28, millisecond: 400})).toString(), "2018-05-25T07:29:00.000Z");
}
@Test
testRoundMinuteUp(exam: Exam): void {
exam.equal(TimeInterval.minute.round(DateTime.fromInit({year: 2018, month: 4, day: 25, hour: 7, minute: 29, second: 31, millisecond: 400})).toString(), "2018-05-25T07:30:00.000Z");
}
@Test
testRoundSecondDown(exam: Exam): void {
exam.equal(TimeInterval.second.round(DateTime.fromInit({year: 2018, month: 4, day: 25, hour: 7, minute: 29, second: 31, millisecond: 400})).toString(), "2018-05-25T07:29:31.000Z");
}
@Test
testRoundSecondUp(exam: Exam): void {
exam.equal(TimeInterval.second.round(DateTime.fromInit({year: 2018, month: 4, day: 25, hour: 7, minute: 29, second: 31, millisecond: 500})).toString(), "2018-05-25T07:29:32.000Z");
}
@Test
testYearOffset(exam: Exam): void {
exam.equal(TimeInterval.year.offset(DateTime.fromInit({year: 2015, month: 4, day: 6})).toString(), "2016-05-06T00:00:00.000Z");
}
@Test
testLeapYearOffset(exam: Exam): void {
exam.equal(TimeInterval.year.offset(DateTime.fromInit({year: 2020, month: 1, day: 29})).toString(), "2021-03-01T00:00:00.000Z");
}
@Test
test2YearOffset(exam: Exam): void {
exam.equal(TimeInterval.year.offset(DateTime.fromInit({year: 2018, month: 6, day: 15, hour: 8, minute: 45, second: 11, millisecond: 800}), 2).toString(), "2020-07-15T08:45:11.800Z");
}
@Test
testMonthOffset(exam: Exam): void {
exam.equal(TimeInterval.month.offset(DateTime.fromInit({year: 2017, month: 7, day: 9})).toString(), "2017-09-09T00:00:00.000Z");
}
@Test
testWeekOffset(exam: Exam): void {
exam.equal(TimeInterval.week.offset(DateTime.fromInit({year: 2017, month: 7, day: 9})).toString(), "2017-08-16T00:00:00.000Z");
}
@Test
testDayOffset(exam: Exam): void {
exam.equal(TimeInterval.day.offset(DateTime.fromInit({year: 2018, month: 4, day: 30})).toString(), "2018-05-31T00:00:00.000Z");
}
@Test
test15DaysOffset(exam: Exam): void {
exam.equal(TimeInterval.day.offset(DateTime.fromInit({year: 2018, month: 6, day: 16, hour: 8, minute: 45, second: 11, millisecond: 800}), 15).toString(), "2018-07-31T08:45:11.800Z");
}
@Test
testHourOffset(exam: Exam): void {
exam.equal(TimeInterval.hour.offset(DateTime.fromInit({year: 2018, month: 6, day: 15, hour: 8, minute: 45, second: 11, millisecond: 800})).toString(), "2018-07-15T09:45:11.800Z");
}
@Test
test16HourOffset(exam: Exam): void {
exam.equal(TimeInterval.hour.offset(DateTime.fromInit({year: 2018, month: 6, day: 15, hour: 8, minute: 45, second: 11, millisecond: 800}), 16).toString(), "2018-07-16T00:45:11.800Z");
}
@Test
testMinuteOffset(exam: Exam): void {
exam.equal(TimeInterval.minute.offset(DateTime.fromInit({year: 2018, month: 6, day: 15, hour: 8, minute: 45, second: 11, millisecond: 800})).toString(), "2018-07-15T08:46:11.800Z");
}
@Test
testSecondOffset(exam: Exam): void {
exam.equal(TimeInterval.second.offset(DateTime.fromInit({year: 2018, month: 6, day: 15, hour: 8, minute: 45, second: 11, millisecond: 800})).toString(), "2018-07-15T08:45:12.800Z");
}
@Test
test20SecondOffset(exam: Exam): void {
exam.equal(TimeInterval.second.offset(DateTime.fromInit({year: 2018, month: 6, day: 15, hour: 8, minute: 45, second: 11, millisecond: 800}), 20).toString(), "2018-07-15T08:45:31.800Z");
}
@Test
testMilisecondOffset(exam: Exam): void {
exam.equal(TimeInterval.millisecond.offset(DateTime.fromInit({year: 2018, month: 6, day: 15, hour: 8, minute: 45, second: 11, millisecond: 800})).toString(), "2018-07-15T08:45:11.801Z");
}
@Test
test200MilisecondOffset(exam: Exam): void {
exam.equal(TimeInterval.millisecond.offset(DateTime.fromInit({year: 2018, month: 6, day: 15, hour: 8, minute: 45, second: 11, millisecond: 800}), 200).toString(), "2018-07-15T08:45:12.000Z");
}
@Test
testYearRange(exam: Exam): void {
exam.equal(TimeInterval.year.range(DateTime.fromInit({year: 2018, month: 6, day: 15, hour: 8, minute: 45, second: 11, millisecond: 800}), DateTime.fromInit({year: 2020, month: 6, day: 15, hour: 8, minute: 45, second: 11, millisecond: 800})), [
DateTime.parse("2019-01-01T00:00:00.000Z"),
DateTime.parse("2020-01-01T00:00:00.000Z"),
]);
}
@Test
testMonthRange(exam: Exam): void {
exam.equal(TimeInterval.month.range(DateTime.fromInit({year: 2018, month: 6, day: 15, hour: 8, minute: 45, second: 11, millisecond: 800}), DateTime.fromInit({year: 2019, month: 6, day: 15, hour: 8, minute: 45, second: 11, millisecond: 800})), [
DateTime.parse("2018-08-01T00:00:00.000Z"),
DateTime.parse("2018-09-01T00:00:00.000Z"),
DateTime.parse("2018-10-01T00:00:00.000Z"),
DateTime.parse("2018-11-01T00:00:00.000Z"),
DateTime.parse("2018-12-01T00:00:00.000Z"),
DateTime.parse("2019-01-01T00:00:00.000Z"),
DateTime.parse("2019-02-01T00:00:00.000Z"),
DateTime.parse("2019-03-01T00:00:00.000Z"),
DateTime.parse("2019-04-01T00:00:00.000Z"),
DateTime.parse("2019-05-01T00:00:00.000Z"),
DateTime.parse("2019-06-01T00:00:00.000Z"),
DateTime.parse("2019-07-01T00:00:00.000Z"),
]);
}
@Test
testDayRange(exam: Exam): void {
exam.equal(TimeInterval.day.range(DateTime.fromInit({year: 2018, month: 6, day: 15, hour: 8, minute: 45, second: 11, millisecond: 800}), DateTime.fromInit({year: 2018, month: 7, day: 15, hour: 8, minute: 45, second: 11, millisecond: 800})), [
DateTime.parse("2018-07-16T00:00:00.000Z"),
DateTime.parse("2018-07-17T00:00:00.000Z"),
DateTime.parse("2018-07-18T00:00:00.000Z"),
DateTime.parse("2018-07-19T00:00:00.000Z"),
DateTime.parse("2018-07-20T00:00:00.000Z"),
DateTime.parse("2018-07-21T00:00:00.000Z"),
DateTime.parse("2018-07-22T00:00:00.000Z"),
DateTime.parse("2018-07-23T00:00:00.000Z"),
DateTime.parse("2018-07-24T00:00:00.000Z"),
DateTime.parse("2018-07-25T00:00:00.000Z"),
DateTime.parse("2018-07-26T00:00:00.000Z"),
DateTime.parse("2018-07-27T00:00:00.000Z"),
DateTime.parse("2018-07-28T00:00:00.000Z"),
DateTime.parse("2018-07-29T00:00:00.000Z"),
DateTime.parse("2018-07-30T00:00:00.000Z"),
DateTime.parse("2018-07-31T00:00:00.000Z"),
DateTime.parse("2018-08-01T00:00:00.000Z"),
DateTime.parse("2018-08-02T00:00:00.000Z"),
DateTime.parse("2018-08-03T00:00:00.000Z"),
DateTime.parse("2018-08-04T00:00:00.000Z"),
DateTime.parse("2018-08-05T00:00:00.000Z"),
DateTime.parse("2018-08-06T00:00:00.000Z"),
DateTime.parse("2018-08-07T00:00:00.000Z"),
DateTime.parse("2018-08-08T00:00:00.000Z"),
DateTime.parse("2018-08-09T00:00:00.000Z"),
DateTime.parse("2018-08-10T00:00:00.000Z"),
DateTime.parse("2018-08-11T00:00:00.000Z"),
DateTime.parse("2018-08-12T00:00:00.000Z"),
DateTime.parse("2018-08-13T00:00:00.000Z"),
DateTime.parse("2018-08-14T00:00:00.000Z"),
DateTime.parse("2018-08-15T00:00:00.000Z"),
]);
exam.equal(TimeInterval.day.range(DateTime.fromInit({year: 2018, month: 6, day: 15, hour: 8, minute: 45, second: 11, millisecond: 800}), DateTime.fromInit({year: 2018, month: 7, day: 15})), [
DateTime.parse("2018-07-16T00:00:00.000Z"),
DateTime.parse("2018-07-17T00:00:00.000Z"),
DateTime.parse("2018-07-18T00:00:00.000Z"),
DateTime.parse("2018-07-19T00:00:00.000Z"),
DateTime.parse("2018-07-20T00:00:00.000Z"),
DateTime.parse("2018-07-21T00:00:00.000Z"),
DateTime.parse("2018-07-22T00:00:00.000Z"),
DateTime.parse("2018-07-23T00:00:00.000Z"),
DateTime.parse("2018-07-24T00:00:00.000Z"),
DateTime.parse("2018-07-25T00:00:00.000Z"),
DateTime.parse("2018-07-26T00:00:00.000Z"),
DateTime.parse("2018-07-27T00:00:00.000Z"),
DateTime.parse("2018-07-28T00:00:00.000Z"),
DateTime.parse("2018-07-29T00:00:00.000Z"),
DateTime.parse("2018-07-30T00:00:00.000Z"),
DateTime.parse("2018-07-31T00:00:00.000Z"),
DateTime.parse("2018-08-01T00:00:00.000Z"),
DateTime.parse("2018-08-02T00:00:00.000Z"),
DateTime.parse("2018-08-03T00:00:00.000Z"),
DateTime.parse("2018-08-04T00:00:00.000Z"),
DateTime.parse("2018-08-05T00:00:00.000Z"),
DateTime.parse("2018-08-06T00:00:00.000Z"),
DateTime.parse("2018-08-07T00:00:00.000Z"),
DateTime.parse("2018-08-08T00:00:00.000Z"),
DateTime.parse("2018-08-09T00:00:00.000Z"),
DateTime.parse("2018-08-10T00:00:00.000Z"),
DateTime.parse("2018-08-11T00:00:00.000Z"),
DateTime.parse("2018-08-12T00:00:00.000Z"),
DateTime.parse("2018-08-13T00:00:00.000Z"),
DateTime.parse("2018-08-14T00:00:00.000Z"),
]);
}
@Test
testHourRange(exam: Exam): void {
exam.equal(TimeInterval.hour.range(DateTime.fromInit({year: 2018, month: 6, day: 15, hour: 8, minute: 45, second: 11, millisecond: 800}), DateTime.fromInit({year: 2018, month: 6, day: 16, hour: 8, minute: 45, second: 11, millisecond: 800})), [
DateTime.parse("2018-07-15T09:00:00.000Z"),
DateTime.parse("2018-07-15T10:00:00.000Z"),
DateTime.parse("2018-07-15T11:00:00.000Z"),
DateTime.parse("2018-07-15T12:00:00.000Z"),
DateTime.parse("2018-07-15T13:00:00.000Z"),
DateTime.parse("2018-07-15T14:00:00.000Z"),
DateTime.parse("2018-07-15T15:00:00.000Z"),
DateTime.parse("2018-07-15T16:00:00.000Z"),
DateTime.parse("2018-07-15T17:00:00.000Z"),
DateTime.parse("2018-07-15T18:00:00.000Z"),
DateTime.parse("2018-07-15T19:00:00.000Z"),
DateTime.parse("2018-07-15T20:00:00.000Z"),
DateTime.parse("2018-07-15T21:00:00.000Z"),
DateTime.parse("2018-07-15T22:00:00.000Z"),
DateTime.parse("2018-07-15T23:00:00.000Z"),
DateTime.parse("2018-07-16T00:00:00.000Z"),
DateTime.parse("2018-07-16T01:00:00.000Z"),
DateTime.parse("2018-07-16T02:00:00.000Z"),
DateTime.parse("2018-07-16T03:00:00.000Z"),
DateTime.parse("2018-07-16T04:00:00.000Z"),
DateTime.parse("2018-07-16T05:00:00.000Z"),
DateTime.parse("2018-07-16T06:00:00.000Z"),
DateTime.parse("2018-07-16T07:00:00.000Z"),
DateTime.parse("2018-07-16T08:00:00.000Z"),
]);
}
@Test
testMinuteRange(exam: Exam): void {
exam.equal(TimeInterval.minute.range(DateTime.fromInit({year: 2018, month: 6, day: 15, hour: 8, minute: 45, second: 11, millisecond: 800}), DateTime.fromInit({year: 2018, month: 6, day: 15, hour: 9, minute: 45, second: 11, millisecond: 800})), [
DateTime.parse("2018-07-15T08:46:00.000Z"),
DateTime.parse("2018-07-15T08:47:00.000Z"),
DateTime.parse("2018-07-15T08:48:00.000Z"),
DateTime.parse("2018-07-15T08:49:00.000Z"),
DateTime.parse("2018-07-15T08:50:00.000Z"),
DateTime.parse("2018-07-15T08:51:00.000Z"),
DateTime.parse("2018-07-15T08:52:00.000Z"),
DateTime.parse("2018-07-15T08:53:00.000Z"),
DateTime.parse("2018-07-15T08:54:00.000Z"),
DateTime.parse("2018-07-15T08:55:00.000Z"),
DateTime.parse("2018-07-15T08:56:00.000Z"),
DateTime.parse("2018-07-15T08:57:00.000Z"),
DateTime.parse("2018-07-15T08:58:00.000Z"),
DateTime.parse("2018-07-15T08:59:00.000Z"),
DateTime.parse("2018-07-15T09:00:00.000Z"),
DateTime.parse("2018-07-15T09:01:00.000Z"),
DateTime.parse("2018-07-15T09:02:00.000Z"),
DateTime.parse("2018-07-15T09:03:00.000Z"),
DateTime.parse("2018-07-15T09:04:00.000Z"),
DateTime.parse("2018-07-15T09:05:00.000Z"),
DateTime.parse("2018-07-15T09:06:00.000Z"),
DateTime.parse("2018-07-15T09:07:00.000Z"),
DateTime.parse("2018-07-15T09:08:00.000Z"),
DateTime.parse("2018-07-15T09:09:00.000Z"),
DateTime.parse("2018-07-15T09:10:00.000Z"),
DateTime.parse("2018-07-15T09:11:00.000Z"),
DateTime.parse("2018-07-15T09:12:00.000Z"),
DateTime.parse("2018-07-15T09:13:00.000Z"),
DateTime.parse("2018-07-15T09:14:00.000Z"),
DateTime.parse("2018-07-15T09:15:00.000Z"),
DateTime.parse("2018-07-15T09:16:00.000Z"),
DateTime.parse("2018-07-15T09:17:00.000Z"),
DateTime.parse("2018-07-15T09:18:00.000Z"),
DateTime.parse("2018-07-15T09:19:00.000Z"),
DateTime.parse("2018-07-15T09:20:00.000Z"),
DateTime.parse("2018-07-15T09:21:00.000Z"),
DateTime.parse("2018-07-15T09:22:00.000Z"),
DateTime.parse("2018-07-15T09:23:00.000Z"),
DateTime.parse("2018-07-15T09:24:00.000Z"),
DateTime.parse("2018-07-15T09:25:00.000Z"),
DateTime.parse("2018-07-15T09:26:00.000Z"),
DateTime.parse("2018-07-15T09:27:00.000Z"),
DateTime.parse("2018-07-15T09:28:00.000Z"),
DateTime.parse("2018-07-15T09:29:00.000Z"),
DateTime.parse("2018-07-15T09:30:00.000Z"),
DateTime.parse("2018-07-15T09:31:00.000Z"),
DateTime.parse("2018-07-15T09:32:00.000Z"),
DateTime.parse("2018-07-15T09:33:00.000Z"),
DateTime.parse("2018-07-15T09:34:00.000Z"),
DateTime.parse("2018-07-15T09:35:00.000Z"),
DateTime.parse("2018-07-15T09:36:00.000Z"),
DateTime.parse("2018-07-15T09:37:00.000Z"),
DateTime.parse("2018-07-15T09:38:00.000Z"),
DateTime.parse("2018-07-15T09:39:00.000Z"),
DateTime.parse("2018-07-15T09:40:00.000Z"),
DateTime.parse("2018-07-15T09:41:00.000Z"),
DateTime.parse("2018-07-15T09:42:00.000Z"),
DateTime.parse("2018-07-15T09:43:00.000Z"),
DateTime.parse("2018-07-15T09:44:00.000Z"),
DateTime.parse("2018-07-15T09:45:00.000Z"),
]);
}
@Test
testSecondRange(exam: Exam): void {
exam.equal(TimeInterval.second.range(DateTime.fromInit({year: 2018, month: 6, day: 15, hour: 8, minute: 45, second: 11, millisecond: 800}), DateTime.fromInit({year: 2018, month: 6, day: 15, hour: 8, minute: 45, second: 20, millisecond: 800})), [
DateTime.parse("2018-07-15T08:45:12.000Z"),
DateTime.parse("2018-07-15T08:45:13.000Z"),
DateTime.parse("2018-07-15T08:45:14.000Z"),
DateTime.parse("2018-07-15T08:45:15.000Z"),
DateTime.parse("2018-07-15T08:45:16.000Z"),
DateTime.parse("2018-07-15T08:45:17.000Z"),
DateTime.parse("2018-07-15T08:45:18.000Z"),
DateTime.parse("2018-07-15T08:45:19.000Z"),
DateTime.parse("2018-07-15T08:45:20.000Z"),
]);
}
@Test
testMiliSecondRange(exam: Exam): void {
exam.equal(TimeInterval.millisecond.range(DateTime.fromInit({year: 2018, month: 6, day: 15, hour: 8, minute: 45, second: 11, millisecond: 800}), DateTime.fromInit({year: 2018, month: 6, day: 15, hour: 8, minute: 45, second: 11, millisecond: 810})), [
DateTime.parse("2018-07-15T08:45:11.800Z"),
DateTime.parse("2018-07-15T08:45:11.801Z"),
DateTime.parse("2018-07-15T08:45:11.802Z"),
DateTime.parse("2018-07-15T08:45:11.803Z"),
DateTime.parse("2018-07-15T08:45:11.804Z"),
DateTime.parse("2018-07-15T08:45:11.805Z"),
DateTime.parse("2018-07-15T08:45:11.806Z"),
DateTime.parse("2018-07-15T08:45:11.807Z"),
DateTime.parse("2018-07-15T08:45:11.808Z"),
DateTime.parse("2018-07-15T08:45:11.809Z"),
]);
}
@Test
testEvery(exam: Exam): void {
exam.equal(TimeInterval.month.every(1).range(DateTime.fromInit({year: 2018, month: 4, day:16}), DateTime.fromInit({year: 2018, month: 11, day: 16})), [
DateTime.parse("2018-06-01T00:00:00.000Z"),
DateTime.parse("2018-07-01T00:00:00.000Z"),
DateTime.parse("2018-08-01T00:00:00.000Z"),
DateTime.parse("2018-09-01T00:00:00.000Z"),
DateTime.parse("2018-10-01T00:00:00.000Z"),
DateTime.parse("2018-11-01T00:00:00.000Z"),
DateTime.parse("2018-12-01T00:00:00.000Z"),
]);
}
@Test
testYearFilterEquals(exam: Exam): void {
exam.equal(TimeInterval.years(DateTime.fromInit({year: 2018}), DateTime.fromInit({year: 2021})).filter((x) => x.equals(DateTime.fromInit({year: 2019}))).toString(), "2019-01-01T00:00:00.000Z");
}
@Test
testYearFilterLess(exam: Exam): void {
exam.equal(TimeInterval.years(DateTime.fromInit({year: 2018}), DateTime.fromInit({year: 2021})).filter((x) => x < (DateTime.fromInit({year: 2019}))).toString(), "2018-01-01T00:00:00.000Z");
}
@Test
testYearFilterGreater(exam: Exam): void {
exam.equal(TimeInterval.years(DateTime.fromInit({year: 2018}), DateTime.fromInit({year: 2021})).filter((x) => x > (DateTime.fromInit({year: 2019}))).toString(), "2020-01-01T00:00:00.000Z");
}
} | the_stack |
import {
ApplicationDataListByFarmerIdParameters,
ApplicationDataListParameters,
ApplicationDataGetParameters,
ApplicationDataCreateOrUpdateParameters,
ApplicationDataDeleteParameters,
AttachmentsListByFarmerIdParameters,
AttachmentsGetParameters,
AttachmentsCreateOrUpdateParameters,
AttachmentsDeleteParameters,
AttachmentsDownloadParameters,
BoundariesListByFarmerIdParameters,
BoundariesSearchByFarmerIdParameters,
BoundariesListParameters,
BoundariesSearchParameters,
BoundariesGetCascadeDeleteJobDetailsParameters,
BoundariesCreateCascadeDeleteJobParameters,
BoundariesGetParameters,
BoundariesCreateOrUpdateParameters,
BoundariesDeleteParameters,
BoundariesGetOverlapParameters,
CropsListParameters,
CropsGetParameters,
CropsCreateOrUpdateParameters,
CropsDeleteParameters,
CropVarietiesListByCropIdParameters,
CropVarietiesListParameters,
CropVarietiesGetParameters,
CropVarietiesCreateOrUpdateParameters,
CropVarietiesDeleteParameters,
FarmersListParameters,
FarmersGetParameters,
FarmersCreateOrUpdateParameters,
FarmersDeleteParameters,
FarmersGetCascadeDeleteJobDetailsParameters,
FarmersCreateCascadeDeleteJobParameters,
FarmOperationsCreateDataIngestionJobParameters,
FarmOperationsGetDataIngestionJobDetailsParameters,
FarmsListByFarmerIdParameters,
FarmsListParameters,
FarmsGetParameters,
FarmsCreateOrUpdateParameters,
FarmsDeleteParameters,
FarmsGetCascadeDeleteJobDetailsParameters,
FarmsCreateCascadeDeleteJobParameters,
FieldsListByFarmerIdParameters,
FieldsListParameters,
FieldsGetParameters,
FieldsCreateOrUpdateParameters,
FieldsDeleteParameters,
FieldsGetCascadeDeleteJobDetailsParameters,
FieldsCreateCascadeDeleteJobParameters,
HarvestDataListByFarmerIdParameters,
HarvestDataListParameters,
HarvestDataGetParameters,
HarvestDataCreateOrUpdateParameters,
HarvestDataDeleteParameters,
ImageProcessingCreateRasterizeJobParameters,
ImageProcessingGetRasterizeJobParameters,
OAuthProvidersListParameters,
OAuthProvidersGetParameters,
OAuthProvidersCreateOrUpdateParameters,
OAuthProvidersDeleteParameters,
OAuthTokensListParameters,
OAuthTokensGetOAuthConnectionLinkParameters,
OAuthTokensGetCascadeDeleteJobDetailsParameters,
OAuthTokensCreateCascadeDeleteJobParameters,
PlantingDataListByFarmerIdParameters,
PlantingDataListParameters,
PlantingDataGetParameters,
PlantingDataCreateOrUpdateParameters,
PlantingDataDeleteParameters,
ScenesListParameters,
ScenesCreateSatelliteDataIngestionJobParameters,
ScenesGetSatelliteDataIngestionJobDetailsParameters,
ScenesDownloadParameters,
SeasonalFieldsListByFarmerIdParameters,
SeasonalFieldsListParameters,
SeasonalFieldsGetParameters,
SeasonalFieldsCreateOrUpdateParameters,
SeasonalFieldsDeleteParameters,
SeasonalFieldsGetCascadeDeleteJobDetailsParameters,
SeasonalFieldsCreateCascadeDeleteJobParameters,
SeasonsListParameters,
SeasonsGetParameters,
SeasonsCreateOrUpdateParameters,
SeasonsDeleteParameters,
TillageDataListByFarmerIdParameters,
TillageDataListParameters,
TillageDataGetParameters,
TillageDataCreateOrUpdateParameters,
TillageDataDeleteParameters,
WeatherListParameters,
WeatherGetDataIngestionJobDetailsParameters,
WeatherCreateDataIngestionJobParameters,
WeatherGetDataDeleteJobDetailsParameters,
WeatherCreateDataDeleteJobParameters
} from "./parameters";
import {
ApplicationDataListByFarmerId200Response,
ApplicationDataListByFarmerIddefaultResponse,
ApplicationDataList200Response,
ApplicationDataListdefaultResponse,
ApplicationDataGet200Response,
ApplicationDataGetdefaultResponse,
ApplicationDataCreateOrUpdate200Response,
ApplicationDataCreateOrUpdate201Response,
ApplicationDataCreateOrUpdatedefaultResponse,
ApplicationDataDelete204Response,
ApplicationDataDeletedefaultResponse,
AttachmentsListByFarmerId200Response,
AttachmentsListByFarmerIddefaultResponse,
AttachmentsGet200Response,
AttachmentsGetdefaultResponse,
AttachmentsCreateOrUpdate200Response,
AttachmentsCreateOrUpdate201Response,
AttachmentsCreateOrUpdatedefaultResponse,
AttachmentsDelete204Response,
AttachmentsDeletedefaultResponse,
AttachmentsDownload200Response,
AttachmentsDownloaddefaultResponse,
BoundariesListByFarmerId200Response,
BoundariesListByFarmerIddefaultResponse,
BoundariesSearchByFarmerId200Response,
BoundariesSearchByFarmerIddefaultResponse,
BoundariesList200Response,
BoundariesListdefaultResponse,
BoundariesSearch200Response,
BoundariesSearchdefaultResponse,
BoundariesGetCascadeDeleteJobDetails200Response,
BoundariesGetCascadeDeleteJobDetailsdefaultResponse,
BoundariesCreateCascadeDeleteJob202Response,
BoundariesCreateCascadeDeleteJobdefaultResponse,
BoundariesGet200Response,
BoundariesGetdefaultResponse,
BoundariesCreateOrUpdate200Response,
BoundariesCreateOrUpdate201Response,
BoundariesCreateOrUpdatedefaultResponse,
BoundariesDelete204Response,
BoundariesDeletedefaultResponse,
BoundariesGetOverlap200Response,
BoundariesGetOverlapdefaultResponse,
CropsList200Response,
CropsListdefaultResponse,
CropsGet200Response,
CropsGetdefaultResponse,
CropsCreateOrUpdate200Response,
CropsCreateOrUpdate201Response,
CropsCreateOrUpdatedefaultResponse,
CropsDelete204Response,
CropsDeletedefaultResponse,
CropVarietiesListByCropId200Response,
CropVarietiesListByCropIddefaultResponse,
CropVarietiesList200Response,
CropVarietiesListdefaultResponse,
CropVarietiesGet200Response,
CropVarietiesGetdefaultResponse,
CropVarietiesCreateOrUpdate200Response,
CropVarietiesCreateOrUpdate201Response,
CropVarietiesCreateOrUpdatedefaultResponse,
CropVarietiesDelete204Response,
CropVarietiesDeletedefaultResponse,
FarmersList200Response,
FarmersListdefaultResponse,
FarmersGet200Response,
FarmersGetdefaultResponse,
FarmersCreateOrUpdate200Response,
FarmersCreateOrUpdate201Response,
FarmersCreateOrUpdatedefaultResponse,
FarmersDelete204Response,
FarmersDeletedefaultResponse,
FarmersGetCascadeDeleteJobDetails200Response,
FarmersGetCascadeDeleteJobDetailsdefaultResponse,
FarmersCreateCascadeDeleteJob202Response,
FarmersCreateCascadeDeleteJobdefaultResponse,
FarmOperationsCreateDataIngestionJob202Response,
FarmOperationsCreateDataIngestionJobdefaultResponse,
FarmOperationsGetDataIngestionJobDetails200Response,
FarmOperationsGetDataIngestionJobDetailsdefaultResponse,
FarmsListByFarmerId200Response,
FarmsListByFarmerIddefaultResponse,
FarmsList200Response,
FarmsListdefaultResponse,
FarmsGet200Response,
FarmsGetdefaultResponse,
FarmsCreateOrUpdate200Response,
FarmsCreateOrUpdate201Response,
FarmsCreateOrUpdatedefaultResponse,
FarmsDelete204Response,
FarmsDeletedefaultResponse,
FarmsGetCascadeDeleteJobDetails200Response,
FarmsGetCascadeDeleteJobDetailsdefaultResponse,
FarmsCreateCascadeDeleteJob202Response,
FarmsCreateCascadeDeleteJobdefaultResponse,
FieldsListByFarmerId200Response,
FieldsListByFarmerIddefaultResponse,
FieldsList200Response,
FieldsListdefaultResponse,
FieldsGet200Response,
FieldsGetdefaultResponse,
FieldsCreateOrUpdate200Response,
FieldsCreateOrUpdate201Response,
FieldsCreateOrUpdatedefaultResponse,
FieldsDelete204Response,
FieldsDeletedefaultResponse,
FieldsGetCascadeDeleteJobDetails200Response,
FieldsGetCascadeDeleteJobDetailsdefaultResponse,
FieldsCreateCascadeDeleteJob202Response,
FieldsCreateCascadeDeleteJobdefaultResponse,
HarvestDataListByFarmerId200Response,
HarvestDataListByFarmerIddefaultResponse,
HarvestDataList200Response,
HarvestDataListdefaultResponse,
HarvestDataGet200Response,
HarvestDataGetdefaultResponse,
HarvestDataCreateOrUpdate200Response,
HarvestDataCreateOrUpdate201Response,
HarvestDataCreateOrUpdatedefaultResponse,
HarvestDataDelete204Response,
HarvestDataDeletedefaultResponse,
ImageProcessingCreateRasterizeJob202Response,
ImageProcessingCreateRasterizeJobdefaultResponse,
ImageProcessingGetRasterizeJob200Response,
OAuthProvidersList200Response,
OAuthProvidersListdefaultResponse,
OAuthProvidersGet200Response,
OAuthProvidersGetdefaultResponse,
OAuthProvidersCreateOrUpdate200Response,
OAuthProvidersCreateOrUpdate201Response,
OAuthProvidersCreateOrUpdatedefaultResponse,
OAuthProvidersDelete204Response,
OAuthProvidersDeletedefaultResponse,
OAuthTokensList200Response,
OAuthTokensListdefaultResponse,
OAuthTokensGetOAuthConnectionLink200Response,
OAuthTokensGetOAuthConnectionLinkdefaultResponse,
OAuthTokensGetCascadeDeleteJobDetails200Response,
OAuthTokensGetCascadeDeleteJobDetailsdefaultResponse,
OAuthTokensCreateCascadeDeleteJob202Response,
OAuthTokensCreateCascadeDeleteJobdefaultResponse,
PlantingDataListByFarmerId200Response,
PlantingDataListByFarmerIddefaultResponse,
PlantingDataList200Response,
PlantingDataListdefaultResponse,
PlantingDataGet200Response,
PlantingDataGetdefaultResponse,
PlantingDataCreateOrUpdate200Response,
PlantingDataCreateOrUpdate201Response,
PlantingDataCreateOrUpdatedefaultResponse,
PlantingDataDelete204Response,
PlantingDataDeletedefaultResponse,
ScenesList200Response,
ScenesListdefaultResponse,
ScenesCreateSatelliteDataIngestionJob202Response,
ScenesCreateSatelliteDataIngestionJobdefaultResponse,
ScenesGetSatelliteDataIngestionJobDetails200Response,
ScenesGetSatelliteDataIngestionJobDetailsdefaultResponse,
ScenesDownload200Response,
ScenesDownloaddefaultResponse,
SeasonalFieldsListByFarmerId200Response,
SeasonalFieldsListByFarmerIddefaultResponse,
SeasonalFieldsList200Response,
SeasonalFieldsListdefaultResponse,
SeasonalFieldsGet200Response,
SeasonalFieldsGetdefaultResponse,
SeasonalFieldsCreateOrUpdate200Response,
SeasonalFieldsCreateOrUpdate201Response,
SeasonalFieldsCreateOrUpdatedefaultResponse,
SeasonalFieldsDelete204Response,
SeasonalFieldsDeletedefaultResponse,
SeasonalFieldsGetCascadeDeleteJobDetails200Response,
SeasonalFieldsGetCascadeDeleteJobDetailsdefaultResponse,
SeasonalFieldsCreateCascadeDeleteJob202Response,
SeasonalFieldsCreateCascadeDeleteJobdefaultResponse,
SeasonsList200Response,
SeasonsListdefaultResponse,
SeasonsGet200Response,
SeasonsGetdefaultResponse,
SeasonsCreateOrUpdate200Response,
SeasonsCreateOrUpdate201Response,
SeasonsCreateOrUpdatedefaultResponse,
SeasonsDelete204Response,
SeasonsDeletedefaultResponse,
TillageDataListByFarmerId200Response,
TillageDataListByFarmerIddefaultResponse,
TillageDataList200Response,
TillageDataListdefaultResponse,
TillageDataGet200Response,
TillageDataGetdefaultResponse,
TillageDataCreateOrUpdate200Response,
TillageDataCreateOrUpdate201Response,
TillageDataCreateOrUpdatedefaultResponse,
TillageDataDelete204Response,
TillageDataDeletedefaultResponse,
WeatherList200Response,
WeatherListdefaultResponse,
WeatherGetDataIngestionJobDetails200Response,
WeatherGetDataIngestionJobDetailsdefaultResponse,
WeatherCreateDataIngestionJob202Response,
WeatherCreateDataIngestionJobdefaultResponse,
WeatherGetDataDeleteJobDetails200Response,
WeatherGetDataDeleteJobDetailsdefaultResponse,
WeatherCreateDataDeleteJob202Response,
WeatherCreateDataDeleteJobdefaultResponse
} from "./responses";
import { getClient, ClientOptions, Client } from "@azure-rest/core-client";
import { TokenCredential } from "@azure/core-auth";
export interface ApplicationDataListByFarmerId {
/** Returns a paginated list of application data resources under a particular farm. */
get(
options?: ApplicationDataListByFarmerIdParameters
): Promise<
| ApplicationDataListByFarmerId200Response
| ApplicationDataListByFarmerIddefaultResponse
>;
}
export interface ApplicationDataList {
/** Returns a paginated list of application data resources across all farmers. */
get(
options?: ApplicationDataListParameters
): Promise<
ApplicationDataList200Response | ApplicationDataListdefaultResponse
>;
}
export interface ApplicationDataGet {
/** Get a specified application data resource under a particular farmer. */
get(
options?: ApplicationDataGetParameters
): Promise<ApplicationDataGet200Response | ApplicationDataGetdefaultResponse>;
/** Creates or updates an application data resource under a particular farmer. */
patch(
options?: ApplicationDataCreateOrUpdateParameters
): Promise<
| ApplicationDataCreateOrUpdate200Response
| ApplicationDataCreateOrUpdate201Response
| ApplicationDataCreateOrUpdatedefaultResponse
>;
/** Deletes a specified application data resource under a particular farmer. */
delete(
options?: ApplicationDataDeleteParameters
): Promise<
ApplicationDataDelete204Response | ApplicationDataDeletedefaultResponse
>;
}
export interface AttachmentsListByFarmerId {
/** Returns a paginated list of attachment resources under a particular farmer. */
get(
options?: AttachmentsListByFarmerIdParameters
): Promise<
| AttachmentsListByFarmerId200Response
| AttachmentsListByFarmerIddefaultResponse
>;
}
export interface AttachmentsGet {
/** Gets a specified attachment resource under a particular farmer. */
get(
options?: AttachmentsGetParameters
): Promise<AttachmentsGet200Response | AttachmentsGetdefaultResponse>;
/** Creates or updates an attachment resource under a particular farmer. */
patch(
options?: AttachmentsCreateOrUpdateParameters
): Promise<
| AttachmentsCreateOrUpdate200Response
| AttachmentsCreateOrUpdate201Response
| AttachmentsCreateOrUpdatedefaultResponse
>;
/** Deletes a specified attachment resource under a particular farmer. */
delete(
options?: AttachmentsDeleteParameters
): Promise<AttachmentsDelete204Response | AttachmentsDeletedefaultResponse>;
}
export interface AttachmentsDownload {
/** Downloads and returns attachment as response for the given input filePath. */
get(
options?: AttachmentsDownloadParameters
): Promise<
AttachmentsDownload200Response | AttachmentsDownloaddefaultResponse
>;
}
export interface BoundariesListByFarmerId {
/** Returns a paginated list of boundary resources under a particular farmer. */
get(
options?: BoundariesListByFarmerIdParameters
): Promise<
| BoundariesListByFarmerId200Response
| BoundariesListByFarmerIddefaultResponse
>;
/** Search for boundaries by fields and intersecting geometry. */
post(
options?: BoundariesSearchByFarmerIdParameters
): Promise<
| BoundariesSearchByFarmerId200Response
| BoundariesSearchByFarmerIddefaultResponse
>;
}
export interface BoundariesList {
/** Returns a paginated list of boundary resources across all farmers. */
get(
options?: BoundariesListParameters
): Promise<BoundariesList200Response | BoundariesListdefaultResponse>;
/** Search for boundaries across all farmers by fields and intersecting geometry. */
post(
options?: BoundariesSearchParameters
): Promise<BoundariesSearch200Response | BoundariesSearchdefaultResponse>;
}
export interface BoundariesGetCascadeDeleteJobDetails {
/** Get cascade delete job for specified boundary. */
get(
options?: BoundariesGetCascadeDeleteJobDetailsParameters
): Promise<
| BoundariesGetCascadeDeleteJobDetails200Response
| BoundariesGetCascadeDeleteJobDetailsdefaultResponse
>;
/** Create a cascade delete job for specified boundary. */
put(
options: BoundariesCreateCascadeDeleteJobParameters
): Promise<
| BoundariesCreateCascadeDeleteJob202Response
| BoundariesCreateCascadeDeleteJobdefaultResponse
>;
}
export interface BoundariesGet {
/** Gets a specified boundary resource under a particular farmer. */
get(
options?: BoundariesGetParameters
): Promise<BoundariesGet200Response | BoundariesGetdefaultResponse>;
/** Creates or updates a boundary resource. */
patch(
options?: BoundariesCreateOrUpdateParameters
): Promise<
| BoundariesCreateOrUpdate200Response
| BoundariesCreateOrUpdate201Response
| BoundariesCreateOrUpdatedefaultResponse
>;
/** Deletes a specified boundary resource under a particular farmer. */
delete(
options?: BoundariesDeleteParameters
): Promise<BoundariesDelete204Response | BoundariesDeletedefaultResponse>;
}
export interface BoundariesGetOverlap {
/** Returns overlapping acreage between two boundary Ids. */
get(
options: BoundariesGetOverlapParameters
): Promise<
BoundariesGetOverlap200Response | BoundariesGetOverlapdefaultResponse
>;
}
export interface CropsList {
/** Returns a paginated list of crop resources. */
get(
options?: CropsListParameters
): Promise<CropsList200Response | CropsListdefaultResponse>;
}
export interface CropsGet {
/** Gets a specified crop resource. */
get(
options?: CropsGetParameters
): Promise<CropsGet200Response | CropsGetdefaultResponse>;
/** Creates or updates a crop resource. */
patch(
options?: CropsCreateOrUpdateParameters
): Promise<
| CropsCreateOrUpdate200Response
| CropsCreateOrUpdate201Response
| CropsCreateOrUpdatedefaultResponse
>;
/** Deletes Crop for given crop id. */
delete(
options?: CropsDeleteParameters
): Promise<CropsDelete204Response | CropsDeletedefaultResponse>;
}
export interface CropVarietiesListByCropId {
/** Returns a paginated list of crop variety resources under a particular crop. */
get(
options?: CropVarietiesListByCropIdParameters
): Promise<
| CropVarietiesListByCropId200Response
| CropVarietiesListByCropIddefaultResponse
>;
}
export interface CropVarietiesList {
/** Returns a paginated list of crop variety resources across all crops. */
get(
options?: CropVarietiesListParameters
): Promise<CropVarietiesList200Response | CropVarietiesListdefaultResponse>;
}
export interface CropVarietiesGet {
/** Gets a specified crop variety resource under a particular crop. */
get(
options?: CropVarietiesGetParameters
): Promise<CropVarietiesGet200Response | CropVarietiesGetdefaultResponse>;
/** Creates or updates a crop variety resource. */
patch(
options?: CropVarietiesCreateOrUpdateParameters
): Promise<
| CropVarietiesCreateOrUpdate200Response
| CropVarietiesCreateOrUpdate201Response
| CropVarietiesCreateOrUpdatedefaultResponse
>;
/** Deletes a specified crop variety resource under a particular crop. */
delete(
options?: CropVarietiesDeleteParameters
): Promise<
CropVarietiesDelete204Response | CropVarietiesDeletedefaultResponse
>;
}
export interface FarmersList {
/** Returns a paginated list of farmer resources. */
get(
options?: FarmersListParameters
): Promise<FarmersList200Response | FarmersListdefaultResponse>;
}
export interface FarmersGet {
/** Gets a specified farmer resource. */
get(
options?: FarmersGetParameters
): Promise<FarmersGet200Response | FarmersGetdefaultResponse>;
/** Creates or updates a farmer resource. */
patch(
options?: FarmersCreateOrUpdateParameters
): Promise<
| FarmersCreateOrUpdate200Response
| FarmersCreateOrUpdate201Response
| FarmersCreateOrUpdatedefaultResponse
>;
/** Deletes a specified farmer resource. */
delete(
options?: FarmersDeleteParameters
): Promise<FarmersDelete204Response | FarmersDeletedefaultResponse>;
}
export interface FarmersGetCascadeDeleteJobDetails {
/** Get a cascade delete job for specified farmer. */
get(
options?: FarmersGetCascadeDeleteJobDetailsParameters
): Promise<
| FarmersGetCascadeDeleteJobDetails200Response
| FarmersGetCascadeDeleteJobDetailsdefaultResponse
>;
/** Create a cascade delete job for specified farmer. */
put(
options: FarmersCreateCascadeDeleteJobParameters
): Promise<
| FarmersCreateCascadeDeleteJob202Response
| FarmersCreateCascadeDeleteJobdefaultResponse
>;
}
export interface FarmOperationsCreateDataIngestionJob {
/** Create a farm operation data ingestion job. */
put(
options?: FarmOperationsCreateDataIngestionJobParameters
): Promise<
| FarmOperationsCreateDataIngestionJob202Response
| FarmOperationsCreateDataIngestionJobdefaultResponse
>;
/** Get a farm operation data ingestion job. */
get(
options?: FarmOperationsGetDataIngestionJobDetailsParameters
): Promise<
| FarmOperationsGetDataIngestionJobDetails200Response
| FarmOperationsGetDataIngestionJobDetailsdefaultResponse
>;
}
export interface FarmsListByFarmerId {
/** Returns a paginated list of farm resources under a particular farmer. */
get(
options?: FarmsListByFarmerIdParameters
): Promise<
FarmsListByFarmerId200Response | FarmsListByFarmerIddefaultResponse
>;
}
export interface FarmsList {
/** Returns a paginated list of farm resources across all farmers. */
get(
options?: FarmsListParameters
): Promise<FarmsList200Response | FarmsListdefaultResponse>;
}
export interface FarmsGet {
/** Gets a specified farm resource under a particular farmer. */
get(
options?: FarmsGetParameters
): Promise<FarmsGet200Response | FarmsGetdefaultResponse>;
/** Creates or updates a farm resource under a particular farmer. */
patch(
options?: FarmsCreateOrUpdateParameters
): Promise<
| FarmsCreateOrUpdate200Response
| FarmsCreateOrUpdate201Response
| FarmsCreateOrUpdatedefaultResponse
>;
/** Deletes a specified farm resource under a particular farmer. */
delete(
options?: FarmsDeleteParameters
): Promise<FarmsDelete204Response | FarmsDeletedefaultResponse>;
}
export interface FarmsGetCascadeDeleteJobDetails {
/** Get a cascade delete job for specified farm. */
get(
options?: FarmsGetCascadeDeleteJobDetailsParameters
): Promise<
| FarmsGetCascadeDeleteJobDetails200Response
| FarmsGetCascadeDeleteJobDetailsdefaultResponse
>;
/** Create a cascade delete job for specified farm. */
put(
options: FarmsCreateCascadeDeleteJobParameters
): Promise<
| FarmsCreateCascadeDeleteJob202Response
| FarmsCreateCascadeDeleteJobdefaultResponse
>;
}
export interface FieldsListByFarmerId {
/** Returns a paginated list of field resources under a particular farmer. */
get(
options?: FieldsListByFarmerIdParameters
): Promise<
FieldsListByFarmerId200Response | FieldsListByFarmerIddefaultResponse
>;
}
export interface FieldsList {
/** Returns a paginated list of field resources across all farmers. */
get(
options?: FieldsListParameters
): Promise<FieldsList200Response | FieldsListdefaultResponse>;
}
export interface FieldsGet {
/** Gets a specified field resource under a particular farmer. */
get(
options?: FieldsGetParameters
): Promise<FieldsGet200Response | FieldsGetdefaultResponse>;
/** Creates or Updates a field resource under a particular farmer. */
patch(
options?: FieldsCreateOrUpdateParameters
): Promise<
| FieldsCreateOrUpdate200Response
| FieldsCreateOrUpdate201Response
| FieldsCreateOrUpdatedefaultResponse
>;
/** Deletes a specified field resource under a particular farmer. */
delete(
options?: FieldsDeleteParameters
): Promise<FieldsDelete204Response | FieldsDeletedefaultResponse>;
}
export interface FieldsGetCascadeDeleteJobDetails {
/** Get a cascade delete job for specified field. */
get(
options?: FieldsGetCascadeDeleteJobDetailsParameters
): Promise<
| FieldsGetCascadeDeleteJobDetails200Response
| FieldsGetCascadeDeleteJobDetailsdefaultResponse
>;
/** Create a cascade delete job for specified field. */
put(
options: FieldsCreateCascadeDeleteJobParameters
): Promise<
| FieldsCreateCascadeDeleteJob202Response
| FieldsCreateCascadeDeleteJobdefaultResponse
>;
}
export interface HarvestDataListByFarmerId {
/** Returns a paginated list of harvest data resources under a particular farm. */
get(
options?: HarvestDataListByFarmerIdParameters
): Promise<
| HarvestDataListByFarmerId200Response
| HarvestDataListByFarmerIddefaultResponse
>;
}
export interface HarvestDataList {
/** Returns a paginated list of harvest data resources across all farmers. */
get(
options?: HarvestDataListParameters
): Promise<HarvestDataList200Response | HarvestDataListdefaultResponse>;
}
export interface HarvestDataGet {
/** Get a specified harvest data resource under a particular farmer. */
get(
options?: HarvestDataGetParameters
): Promise<HarvestDataGet200Response | HarvestDataGetdefaultResponse>;
/** Creates or updates harvest data resource under a particular farmer. */
patch(
options?: HarvestDataCreateOrUpdateParameters
): Promise<
| HarvestDataCreateOrUpdate200Response
| HarvestDataCreateOrUpdate201Response
| HarvestDataCreateOrUpdatedefaultResponse
>;
/** Deletes a specified harvest data resource under a particular farmer. */
delete(
options?: HarvestDataDeleteParameters
): Promise<HarvestDataDelete204Response | HarvestDataDeletedefaultResponse>;
}
export interface ImageProcessingCreateRasterizeJob {
/** Create a ImageProcessing Rasterize job. */
put(
options?: ImageProcessingCreateRasterizeJobParameters
): Promise<
| ImageProcessingCreateRasterizeJob202Response
| ImageProcessingCreateRasterizeJobdefaultResponse
>;
/** Get ImageProcessing Rasterize job's details. */
get(
options?: ImageProcessingGetRasterizeJobParameters
): Promise<ImageProcessingGetRasterizeJob200Response>;
}
export interface OAuthProvidersList {
/** Returns a paginated list of oauthProvider resources. */
get(
options?: OAuthProvidersListParameters
): Promise<OAuthProvidersList200Response | OAuthProvidersListdefaultResponse>;
}
export interface OAuthProvidersGet {
/** Get a specified oauthProvider resource. */
get(
options?: OAuthProvidersGetParameters
): Promise<OAuthProvidersGet200Response | OAuthProvidersGetdefaultResponse>;
/** Creates or updates an oauthProvider resource. */
patch(
options?: OAuthProvidersCreateOrUpdateParameters
): Promise<
| OAuthProvidersCreateOrUpdate200Response
| OAuthProvidersCreateOrUpdate201Response
| OAuthProvidersCreateOrUpdatedefaultResponse
>;
/** Deletes an specified oauthProvider resource. */
delete(
options?: OAuthProvidersDeleteParameters
): Promise<
OAuthProvidersDelete204Response | OAuthProvidersDeletedefaultResponse
>;
}
export interface OAuthTokensList {
/** Returns a list of OAuthToken documents. */
get(
options?: OAuthTokensListParameters
): Promise<OAuthTokensList200Response | OAuthTokensListdefaultResponse>;
}
export interface OAuthTokensGetOAuthConnectionLink {
/** Returns Connection link needed in the OAuth flow. */
post(
options?: OAuthTokensGetOAuthConnectionLinkParameters
): Promise<
| OAuthTokensGetOAuthConnectionLink200Response
| OAuthTokensGetOAuthConnectionLinkdefaultResponse
>;
}
export interface OAuthTokensGetCascadeDeleteJobDetails {
/** Get cascade delete job details for OAuth tokens for specified job ID. */
get(
options?: OAuthTokensGetCascadeDeleteJobDetailsParameters
): Promise<
| OAuthTokensGetCascadeDeleteJobDetails200Response
| OAuthTokensGetCascadeDeleteJobDetailsdefaultResponse
>;
/** Create a cascade delete job for OAuth tokens. */
put(
options: OAuthTokensCreateCascadeDeleteJobParameters
): Promise<
| OAuthTokensCreateCascadeDeleteJob202Response
| OAuthTokensCreateCascadeDeleteJobdefaultResponse
>;
}
export interface PlantingDataListByFarmerId {
/** Returns a paginated list of planting data resources under a particular farm. */
get(
options?: PlantingDataListByFarmerIdParameters
): Promise<
| PlantingDataListByFarmerId200Response
| PlantingDataListByFarmerIddefaultResponse
>;
}
export interface PlantingDataList {
/** Returns a paginated list of planting data resources across all farmers. */
get(
options?: PlantingDataListParameters
): Promise<PlantingDataList200Response | PlantingDataListdefaultResponse>;
}
export interface PlantingDataGet {
/** Get a specified planting data resource under a particular farmer. */
get(
options?: PlantingDataGetParameters
): Promise<PlantingDataGet200Response | PlantingDataGetdefaultResponse>;
/** Creates or updates an planting data resource under a particular farmer. */
patch(
options?: PlantingDataCreateOrUpdateParameters
): Promise<
| PlantingDataCreateOrUpdate200Response
| PlantingDataCreateOrUpdate201Response
| PlantingDataCreateOrUpdatedefaultResponse
>;
/** Deletes a specified planting data resource under a particular farmer. */
delete(
options?: PlantingDataDeleteParameters
): Promise<PlantingDataDelete204Response | PlantingDataDeletedefaultResponse>;
}
export interface ScenesList {
/** Returns a paginated list of scene resources. */
get(
options: ScenesListParameters
): Promise<ScenesList200Response | ScenesListdefaultResponse>;
}
export interface ScenesCreateSatelliteDataIngestionJob {
/** Create a satellite data ingestion job. */
put(
options?: ScenesCreateSatelliteDataIngestionJobParameters
): Promise<
| ScenesCreateSatelliteDataIngestionJob202Response
| ScenesCreateSatelliteDataIngestionJobdefaultResponse
>;
/** Get a satellite data ingestion job. */
get(
options?: ScenesGetSatelliteDataIngestionJobDetailsParameters
): Promise<
| ScenesGetSatelliteDataIngestionJobDetails200Response
| ScenesGetSatelliteDataIngestionJobDetailsdefaultResponse
>;
}
export interface ScenesDownload {
/** Downloads and returns file stream as response for the given input filePath. */
get(
options: ScenesDownloadParameters
): Promise<ScenesDownload200Response | ScenesDownloaddefaultResponse>;
}
export interface SeasonalFieldsListByFarmerId {
/** Returns a paginated list of seasonal field resources under a particular farmer. */
get(
options?: SeasonalFieldsListByFarmerIdParameters
): Promise<
| SeasonalFieldsListByFarmerId200Response
| SeasonalFieldsListByFarmerIddefaultResponse
>;
}
export interface SeasonalFieldsList {
/** Returns a paginated list of seasonal field resources across all farmers. */
get(
options?: SeasonalFieldsListParameters
): Promise<SeasonalFieldsList200Response | SeasonalFieldsListdefaultResponse>;
}
export interface SeasonalFieldsGet {
/** Gets a specified seasonal field resource under a particular farmer. */
get(
options?: SeasonalFieldsGetParameters
): Promise<SeasonalFieldsGet200Response | SeasonalFieldsGetdefaultResponse>;
/** Creates or Updates a seasonal field resource under a particular farmer. */
patch(
options?: SeasonalFieldsCreateOrUpdateParameters
): Promise<
| SeasonalFieldsCreateOrUpdate200Response
| SeasonalFieldsCreateOrUpdate201Response
| SeasonalFieldsCreateOrUpdatedefaultResponse
>;
/** Deletes a specified seasonal-field resource under a particular farmer. */
delete(
options?: SeasonalFieldsDeleteParameters
): Promise<
SeasonalFieldsDelete204Response | SeasonalFieldsDeletedefaultResponse
>;
}
export interface SeasonalFieldsGetCascadeDeleteJobDetails {
/** Get cascade delete job for specified seasonal field. */
get(
options?: SeasonalFieldsGetCascadeDeleteJobDetailsParameters
): Promise<
| SeasonalFieldsGetCascadeDeleteJobDetails200Response
| SeasonalFieldsGetCascadeDeleteJobDetailsdefaultResponse
>;
/** Create a cascade delete job for specified seasonal field. */
put(
options: SeasonalFieldsCreateCascadeDeleteJobParameters
): Promise<
| SeasonalFieldsCreateCascadeDeleteJob202Response
| SeasonalFieldsCreateCascadeDeleteJobdefaultResponse
>;
}
export interface SeasonsList {
/** Returns a paginated list of season resources. */
get(
options?: SeasonsListParameters
): Promise<SeasonsList200Response | SeasonsListdefaultResponse>;
}
export interface SeasonsGet {
/** Gets a specified season resource. */
get(
options?: SeasonsGetParameters
): Promise<SeasonsGet200Response | SeasonsGetdefaultResponse>;
/** Creates or updates a season resource. */
patch(
options?: SeasonsCreateOrUpdateParameters
): Promise<
| SeasonsCreateOrUpdate200Response
| SeasonsCreateOrUpdate201Response
| SeasonsCreateOrUpdatedefaultResponse
>;
/** Deletes a specified season resource. */
delete(
options?: SeasonsDeleteParameters
): Promise<SeasonsDelete204Response | SeasonsDeletedefaultResponse>;
}
export interface TillageDataListByFarmerId {
/** Returns a paginated list of tillage data resources under a particular farm. */
get(
options?: TillageDataListByFarmerIdParameters
): Promise<
| TillageDataListByFarmerId200Response
| TillageDataListByFarmerIddefaultResponse
>;
}
export interface TillageDataList {
/** Returns a paginated list of tillage data resources across all farmers. */
get(
options?: TillageDataListParameters
): Promise<TillageDataList200Response | TillageDataListdefaultResponse>;
}
export interface TillageDataGet {
/** Get a specified tillage data resource under a particular farmer. */
get(
options?: TillageDataGetParameters
): Promise<TillageDataGet200Response | TillageDataGetdefaultResponse>;
/** Creates or updates an tillage data resource under a particular farmer. */
patch(
options?: TillageDataCreateOrUpdateParameters
): Promise<
| TillageDataCreateOrUpdate200Response
| TillageDataCreateOrUpdate201Response
| TillageDataCreateOrUpdatedefaultResponse
>;
/** Deletes a specified tillage data resource under a particular farmer. */
delete(
options?: TillageDataDeleteParameters
): Promise<TillageDataDelete204Response | TillageDataDeletedefaultResponse>;
}
export interface WeatherList {
/** Returns a paginated list of weather data. */
get(
options: WeatherListParameters
): Promise<WeatherList200Response | WeatherListdefaultResponse>;
}
export interface WeatherGetDataIngestionJobDetails {
/** Get weather ingestion job. */
get(
options?: WeatherGetDataIngestionJobDetailsParameters
): Promise<
| WeatherGetDataIngestionJobDetails200Response
| WeatherGetDataIngestionJobDetailsdefaultResponse
>;
/** Create a weather data ingestion job. */
put(
options?: WeatherCreateDataIngestionJobParameters
): Promise<
| WeatherCreateDataIngestionJob202Response
| WeatherCreateDataIngestionJobdefaultResponse
>;
}
export interface WeatherGetDataDeleteJobDetails {
/** Get weather data delete job. */
get(
options?: WeatherGetDataDeleteJobDetailsParameters
): Promise<
| WeatherGetDataDeleteJobDetails200Response
| WeatherGetDataDeleteJobDetailsdefaultResponse
>;
/** Create a weather data delete job. */
put(
options?: WeatherCreateDataDeleteJobParameters
): Promise<
| WeatherCreateDataDeleteJob202Response
| WeatherCreateDataDeleteJobdefaultResponse
>;
}
export interface Routes {
/** Resource for '/farmers/\{farmerId\}/application-data' has methods for the following verbs: get */
(
path: "/farmers/{farmerId}/application-data",
farmerId: string
): ApplicationDataListByFarmerId;
/** Resource for '/application-data' has methods for the following verbs: get */
(path: "/application-data"): ApplicationDataList;
/** Resource for '/farmers/\{farmerId\}/application-data/\{applicationDataId\}' has methods for the following verbs: get, patch, delete */
(
path: "/farmers/{farmerId}/application-data/{applicationDataId}",
farmerId: string,
applicationDataId: string
): ApplicationDataGet;
/** Resource for '/farmers/\{farmerId\}/attachments' has methods for the following verbs: get */
(
path: "/farmers/{farmerId}/attachments",
farmerId: string
): AttachmentsListByFarmerId;
/** Resource for '/farmers/\{farmerId\}/attachments/\{attachmentId\}' has methods for the following verbs: get, patch, delete */
(
path: "/farmers/{farmerId}/attachments/{attachmentId}",
farmerId: string,
attachmentId: string
): AttachmentsGet;
/** Resource for '/farmers/\{farmerId\}/attachments/\{attachmentId\}/file' has methods for the following verbs: get */
(
path: "/farmers/{farmerId}/attachments/{attachmentId}/file",
farmerId: string,
attachmentId: string
): AttachmentsDownload;
/** Resource for '/farmers/\{farmerId\}/boundaries' has methods for the following verbs: get, post */
(
path: "/farmers/{farmerId}/boundaries",
farmerId: string
): BoundariesListByFarmerId;
/** Resource for '/boundaries' has methods for the following verbs: get, post */
(path: "/boundaries"): BoundariesList;
/** Resource for '/boundaries/cascade-delete/\{jobId\}' has methods for the following verbs: get, put */
(
path: "/boundaries/cascade-delete/{jobId}",
jobId: string
): BoundariesGetCascadeDeleteJobDetails;
/** Resource for '/farmers/\{farmerId\}/boundaries/\{boundaryId\}' has methods for the following verbs: get, patch, delete */
(
path: "/farmers/{farmerId}/boundaries/{boundaryId}",
farmerId: string,
boundaryId: string
): BoundariesGet;
/** Resource for '/farmers/\{farmerId\}/boundaries/\{boundaryId\}/overlap' has methods for the following verbs: get */
(
path: "/farmers/{farmerId}/boundaries/{boundaryId}/overlap",
farmerId: string,
boundaryId: string
): BoundariesGetOverlap;
/** Resource for '/crops' has methods for the following verbs: get */
(path: "/crops"): CropsList;
/** Resource for '/crops/\{cropId\}' has methods for the following verbs: get, patch, delete */
(path: "/crops/{cropId}", cropId: string): CropsGet;
/** Resource for '/crops/\{cropId\}/crop-varieties' has methods for the following verbs: get */
(
path: "/crops/{cropId}/crop-varieties",
cropId: string
): CropVarietiesListByCropId;
/** Resource for '/crop-varieties' has methods for the following verbs: get */
(path: "/crop-varieties"): CropVarietiesList;
/** Resource for '/crops/\{cropId\}/crop-varieties/\{cropVarietyId\}' has methods for the following verbs: get, patch, delete */
(
path: "/crops/{cropId}/crop-varieties/{cropVarietyId}",
cropId: string,
cropVarietyId: string
): CropVarietiesGet;
/** Resource for '/farmers' has methods for the following verbs: get */
(path: "/farmers"): FarmersList;
/** Resource for '/farmers/\{farmerId\}' has methods for the following verbs: get, patch, delete */
(path: "/farmers/{farmerId}", farmerId: string): FarmersGet;
/** Resource for '/farmers/cascade-delete/\{jobId\}' has methods for the following verbs: get, put */
(
path: "/farmers/cascade-delete/{jobId}",
jobId: string
): FarmersGetCascadeDeleteJobDetails;
/** Resource for '/farm-operations/ingest-data/\{jobId\}' has methods for the following verbs: put, get */
(
path: "/farm-operations/ingest-data/{jobId}",
jobId: string
): FarmOperationsCreateDataIngestionJob;
/** Resource for '/farmers/\{farmerId\}/farms' has methods for the following verbs: get */
(path: "/farmers/{farmerId}/farms", farmerId: string): FarmsListByFarmerId;
/** Resource for '/farms' has methods for the following verbs: get */
(path: "/farms"): FarmsList;
/** Resource for '/farmers/\{farmerId\}/farms/\{farmId\}' has methods for the following verbs: get, patch, delete */
(
path: "/farmers/{farmerId}/farms/{farmId}",
farmerId: string,
farmId: string
): FarmsGet;
/** Resource for '/farms/cascade-delete/\{jobId\}' has methods for the following verbs: get, put */
(
path: "/farms/cascade-delete/{jobId}",
jobId: string
): FarmsGetCascadeDeleteJobDetails;
/** Resource for '/farmers/\{farmerId\}/fields' has methods for the following verbs: get */
(path: "/farmers/{farmerId}/fields", farmerId: string): FieldsListByFarmerId;
/** Resource for '/fields' has methods for the following verbs: get */
(path: "/fields"): FieldsList;
/** Resource for '/farmers/\{farmerId\}/fields/\{fieldId\}' has methods for the following verbs: get, patch, delete */
(
path: "/farmers/{farmerId}/fields/{fieldId}",
farmerId: string,
fieldId: string
): FieldsGet;
/** Resource for '/fields/cascade-delete/\{jobId\}' has methods for the following verbs: get, put */
(
path: "/fields/cascade-delete/{jobId}",
jobId: string
): FieldsGetCascadeDeleteJobDetails;
/** Resource for '/farmers/\{farmerId\}/harvest-data' has methods for the following verbs: get */
(
path: "/farmers/{farmerId}/harvest-data",
farmerId: string
): HarvestDataListByFarmerId;
/** Resource for '/harvest-data' has methods for the following verbs: get */
(path: "/harvest-data"): HarvestDataList;
/** Resource for '/farmers/\{farmerId\}/harvest-data/\{harvestDataId\}' has methods for the following verbs: get, patch, delete */
(
path: "/farmers/{farmerId}/harvest-data/{harvestDataId}",
farmerId: string,
harvestDataId: string
): HarvestDataGet;
/** Resource for '/image-processing/rasterize/\{jobId\}' has methods for the following verbs: put, get */
(
path: "/image-processing/rasterize/{jobId}",
jobId: string
): ImageProcessingCreateRasterizeJob;
/** Resource for '/oauth/providers' has methods for the following verbs: get */
(path: "/oauth/providers"): OAuthProvidersList;
/** Resource for '/oauth/providers/\{oauthProviderId\}' has methods for the following verbs: get, patch, delete */
(
path: "/oauth/providers/{oauthProviderId}",
oauthProviderId: string
): OAuthProvidersGet;
/** Resource for '/oauth/tokens' has methods for the following verbs: get */
(path: "/oauth/tokens"): OAuthTokensList;
/** Resource for '/oauth/tokens/:connect' has methods for the following verbs: post */
(path: "/oauth/tokens/:connect"): OAuthTokensGetOAuthConnectionLink;
/** Resource for '/oauth/tokens/remove/\{jobId\}' has methods for the following verbs: get, put */
(
path: "/oauth/tokens/remove/{jobId}",
jobId: string
): OAuthTokensGetCascadeDeleteJobDetails;
/** Resource for '/farmers/\{farmerId\}/planting-data' has methods for the following verbs: get */
(
path: "/farmers/{farmerId}/planting-data",
farmerId: string
): PlantingDataListByFarmerId;
/** Resource for '/planting-data' has methods for the following verbs: get */
(path: "/planting-data"): PlantingDataList;
/** Resource for '/farmers/\{farmerId\}/planting-data/\{plantingDataId\}' has methods for the following verbs: get, patch, delete */
(
path: "/farmers/{farmerId}/planting-data/{plantingDataId}",
farmerId: string,
plantingDataId: string
): PlantingDataGet;
/** Resource for '/scenes' has methods for the following verbs: get */
(path: "/scenes"): ScenesList;
/** Resource for '/scenes/satellite/ingest-data/\{jobId\}' has methods for the following verbs: put, get */
(
path: "/scenes/satellite/ingest-data/{jobId}",
jobId: string
): ScenesCreateSatelliteDataIngestionJob;
/** Resource for '/scenes/downloadFiles' has methods for the following verbs: get */
(path: "/scenes/downloadFiles"): ScenesDownload;
/** Resource for '/farmers/\{farmerId\}/seasonal-fields' has methods for the following verbs: get */
(
path: "/farmers/{farmerId}/seasonal-fields",
farmerId: string
): SeasonalFieldsListByFarmerId;
/** Resource for '/seasonal-fields' has methods for the following verbs: get */
(path: "/seasonal-fields"): SeasonalFieldsList;
/** Resource for '/farmers/\{farmerId\}/seasonal-fields/\{seasonalFieldId\}' has methods for the following verbs: get, patch, delete */
(
path: "/farmers/{farmerId}/seasonal-fields/{seasonalFieldId}",
farmerId: string,
seasonalFieldId: string
): SeasonalFieldsGet;
/** Resource for '/seasonal-fields/cascade-delete/\{jobId\}' has methods for the following verbs: get, put */
(
path: "/seasonal-fields/cascade-delete/{jobId}",
jobId: string
): SeasonalFieldsGetCascadeDeleteJobDetails;
/** Resource for '/seasons' has methods for the following verbs: get */
(path: "/seasons"): SeasonsList;
/** Resource for '/seasons/\{seasonId\}' has methods for the following verbs: get, patch, delete */
(path: "/seasons/{seasonId}", seasonId: string): SeasonsGet;
/** Resource for '/farmers/\{farmerId\}/tillage-data' has methods for the following verbs: get */
(
path: "/farmers/{farmerId}/tillage-data",
farmerId: string
): TillageDataListByFarmerId;
/** Resource for '/tillage-data' has methods for the following verbs: get */
(path: "/tillage-data"): TillageDataList;
/** Resource for '/farmers/\{farmerId\}/tillage-data/\{tillageDataId\}' has methods for the following verbs: get, patch, delete */
(
path: "/farmers/{farmerId}/tillage-data/{tillageDataId}",
farmerId: string,
tillageDataId: string
): TillageDataGet;
/** Resource for '/weather' has methods for the following verbs: get */
(path: "/weather"): WeatherList;
/** Resource for '/weather/ingest-data/\{jobId\}' has methods for the following verbs: get, put */
(
path: "/weather/ingest-data/{jobId}",
jobId: string
): WeatherGetDataIngestionJobDetails;
/** Resource for '/weather/delete-data/\{jobId\}' has methods for the following verbs: get, put */
(
path: "/weather/delete-data/{jobId}",
jobId: string
): WeatherGetDataDeleteJobDetails;
}
export type AzureAgriFoodPlatformDataPlaneServiceRestClient = Client & {
path: Routes;
};
export default function AzureAgriFoodPlatformDataPlaneService(
Endpoint: string,
credentials: TokenCredential,
options: ClientOptions = {}
): AzureAgriFoodPlatformDataPlaneServiceRestClient {
const baseUrl = options.baseUrl ?? `${Endpoint}`;
options.apiVersion = options.apiVersion ?? "2021-03-31-preview";
const client = getClient(
baseUrl,
options
) as AzureAgriFoodPlatformDataPlaneServiceRestClient;
return client;
} | the_stack |
import type { CSSProperties, ExtractPropTypes, PropType } from 'vue';
import { watchEffect, defineComponent, ref, watch, toRaw } from 'vue';
import PropTypes from '../_util/vue-types';
import { getPropsSlot } from '../_util/props-util';
import classNames from '../_util/classNames';
import List from './list';
import Operation from './operation';
import LocaleReceiver from '../locale-provider/LocaleReceiver';
import defaultLocale from '../locale-provider/default';
import type { RenderEmptyHandler } from '../config-provider';
import type { VueNode } from '../_util/type';
import { withInstall } from '../_util/type';
import useConfigInject from '../_util/hooks/useConfigInject';
import type { TransferListBodyProps } from './ListBody';
import type { PaginationType } from './interface';
import { useInjectFormItemContext } from '../form/FormItemContext';
export type { TransferListProps } from './list';
export type { TransferOperationProps } from './operation';
export type { TransferSearchProps } from './search';
export type TransferDirection = 'left' | 'right';
export interface RenderResultObject {
label: VueNode;
value: string;
}
export type RenderResult = VueNode | RenderResultObject | string | null;
export interface TransferItem {
key?: string;
title?: string;
description?: string;
disabled?: boolean;
[name: string]: any;
}
export type KeyWise<T> = T & { key: string };
export type KeyWiseTransferItem = KeyWise<TransferItem>;
type TransferRender<RecordType> = (item: RecordType) => RenderResult;
export interface ListStyle {
direction: TransferDirection;
}
export type SelectAllLabel =
| VueNode
| ((info: { selectedCount: number; totalCount: number }) => VueNode);
export interface TransferLocale {
titles: VueNode[];
notFoundContent?: VueNode;
searchPlaceholder: string;
itemUnit: string;
itemsUnit: string;
remove: string;
selectAll: string;
selectCurrent: string;
selectInvert: string;
removeAll: string;
removeCurrent: string;
}
export const transferProps = {
id: String,
prefixCls: String,
dataSource: { type: Array as PropType<TransferItem[]>, default: [] },
disabled: { type: Boolean, default: undefined },
targetKeys: { type: Array as PropType<string[]>, default: undefined },
selectedKeys: { type: Array as PropType<string[]>, default: undefined },
render: { type: Function as PropType<TransferRender<TransferItem>> },
listStyle: {
type: [Function, Object] as PropType<((style: ListStyle) => CSSProperties) | CSSProperties>,
default: () => ({}),
},
operationStyle: PropTypes.style,
titles: { type: Array as PropType<string[]> },
operations: { type: Array as PropType<string[]> },
showSearch: { type: Boolean, default: false },
filterOption: { type: Function as PropType<(inputValue: string, item: TransferItem) => boolean> },
searchPlaceholder: String,
notFoundContent: PropTypes.any,
locale: { type: Object as PropType<Partial<TransferLocale>>, default: () => ({}) },
rowKey: { type: Function as PropType<(record: TransferItem) => string> },
showSelectAll: { type: Boolean, default: undefined },
selectAllLabels: { type: Array as PropType<SelectAllLabel[]> },
children: { type: Function as PropType<(props: TransferListBodyProps) => VueNode> },
oneWay: { type: Boolean, default: undefined },
pagination: { type: [Object, Boolean] as PropType<PaginationType>, default: undefined },
};
export type TransferProps = Partial<ExtractPropTypes<typeof transferProps>>;
const Transfer = defineComponent({
name: 'ATransfer',
inheritAttrs: false,
props: transferProps,
slots: [
'leftTitle',
'rightTitle',
'children',
'render',
'notFoundContent',
'leftSelectAllLabel',
'rightSelectAllLabel',
'footer',
],
emits: ['update:targetKeys', 'update:selectedKeys', 'change', 'search', 'scroll', 'selectChange'],
setup(props, { emit, attrs, slots, expose }) {
const { configProvider, prefixCls, direction } = useConfigInject('transfer', props);
const sourceSelectedKeys = ref([]);
const targetSelectedKeys = ref([]);
const formItemContext = useInjectFormItemContext();
watch(
() => props.selectedKeys,
() => {
sourceSelectedKeys.value =
props.selectedKeys?.filter(key => props.targetKeys.indexOf(key) === -1) || [];
targetSelectedKeys.value =
props.selectedKeys?.filter(key => props.targetKeys.indexOf(key) > -1) || [];
},
{ immediate: true },
);
const getLocale = (transferLocale: TransferLocale, renderEmpty: RenderEmptyHandler) => {
// Keep old locale props still working.
const oldLocale: { notFoundContent?: any; searchPlaceholder?: string } = {
notFoundContent: renderEmpty('Transfer'),
};
const notFoundContent = getPropsSlot(slots, props, 'notFoundContent');
if (notFoundContent) {
oldLocale.notFoundContent = notFoundContent;
}
if (props.searchPlaceholder !== undefined) {
oldLocale.searchPlaceholder = props.searchPlaceholder;
}
return { ...transferLocale, ...oldLocale, ...props.locale };
};
const moveTo = (direction: TransferDirection) => {
const { targetKeys = [], dataSource = [] } = props;
const moveKeys = direction === 'right' ? sourceSelectedKeys.value : targetSelectedKeys.value;
// filter the disabled options
const newMoveKeys = moveKeys.filter(
key => !dataSource.some(data => !!(key === data.key && data.disabled)),
);
// move items to target box
const newTargetKeys =
direction === 'right'
? newMoveKeys.concat(targetKeys)
: targetKeys.filter(targetKey => newMoveKeys.indexOf(targetKey) === -1);
// empty checked keys
const oppositeDirection = direction === 'right' ? 'left' : 'right';
direction === 'right' ? (sourceSelectedKeys.value = []) : (targetSelectedKeys.value = []);
emit('update:targetKeys', newTargetKeys);
handleSelectChange(oppositeDirection, []);
emit('change', newTargetKeys, direction, newMoveKeys);
formItemContext.onFieldChange();
};
const moveToLeft = () => {
moveTo('left');
};
const moveToRight = () => {
moveTo('right');
};
const onItemSelectAll = (direction: TransferDirection, selectedKeys: string[]) => {
handleSelectChange(direction, selectedKeys);
};
const onLeftItemSelectAll = (selectedKeys: string[]) => {
return onItemSelectAll('left', selectedKeys);
};
const onRightItemSelectAll = (selectedKeys: string[]) => {
return onItemSelectAll('right', selectedKeys);
};
const handleSelectChange = (direction: TransferDirection, holder: string[]) => {
if (direction === 'left') {
if (!props.selectedKeys) {
sourceSelectedKeys.value = holder;
}
emit('update:selectedKeys', [...holder, ...targetSelectedKeys.value]);
emit('selectChange', holder, toRaw(targetSelectedKeys.value));
} else {
if (!props.selectedKeys) {
targetSelectedKeys.value = holder;
}
emit('update:selectedKeys', [...holder, ...sourceSelectedKeys.value]);
emit('selectChange', toRaw(sourceSelectedKeys.value), holder);
}
};
const handleFilter = (direction: TransferDirection, e) => {
const value = e.target.value;
emit('search', direction, value);
};
const handleLeftFilter = (e: Event) => {
handleFilter('left', e);
};
const handleRightFilter = (e: Event) => {
handleFilter('right', e);
};
const handleClear = (direction: TransferDirection) => {
emit('search', direction, '');
};
const handleLeftClear = () => {
handleClear('left');
};
const handleRightClear = () => {
handleClear('right');
};
const onItemSelect = (direction: TransferDirection, selectedKey: string, checked: boolean) => {
const holder =
direction === 'left' ? [...sourceSelectedKeys.value] : [...targetSelectedKeys.value];
const index = holder.indexOf(selectedKey);
if (index > -1) {
holder.splice(index, 1);
}
if (checked) {
holder.push(selectedKey);
}
handleSelectChange(direction, holder);
};
const onLeftItemSelect = (selectedKey: string, checked: boolean) => {
return onItemSelect('left', selectedKey, checked);
};
const onRightItemSelect = (selectedKey: string, checked: boolean) => {
return onItemSelect('right', selectedKey, checked);
};
const onRightItemRemove = (targetedKeys: string[]) => {
const { targetKeys = [] } = props;
const newTargetKeys = targetKeys.filter(key => !targetedKeys.includes(key));
emit('update:targetKeys', newTargetKeys);
emit('change', newTargetKeys, 'left', [...targetedKeys]);
};
const handleScroll = (direction: TransferDirection, e: Event) => {
emit('scroll', direction, e);
};
const handleLeftScroll = (e: Event) => {
handleScroll('left', e);
};
const handleRightScroll = (e: Event) => {
handleScroll('right', e);
};
const handleListStyle = (
listStyle: ((style: ListStyle) => CSSProperties) | CSSProperties,
direction: TransferDirection,
) => {
if (typeof listStyle === 'function') {
return listStyle({ direction });
}
return listStyle;
};
const leftDataSource = ref([]);
const rightDataSource = ref([]);
watchEffect(() => {
const { dataSource, rowKey, targetKeys = [] } = props;
const ld = [];
const rd = new Array(targetKeys.length);
dataSource.forEach(record => {
if (rowKey) {
record.key = rowKey(record);
}
// rightDataSource should be ordered by targetKeys
// leftDataSource should be ordered by dataSource
const indexOfKey = targetKeys.indexOf(record.key);
if (indexOfKey !== -1) {
rd[indexOfKey] = record;
} else {
ld.push(record);
}
});
leftDataSource.value = ld;
rightDataSource.value = rd;
});
expose({ handleSelectChange });
const renderTransfer = (transferLocale: TransferLocale) => {
const {
disabled,
operations = [],
showSearch,
listStyle,
operationStyle,
filterOption,
showSelectAll,
selectAllLabels = [],
oneWay,
pagination,
id = formItemContext.id.value,
} = props;
const { class: className, style } = attrs;
const children = slots.children;
const mergedPagination = !children && pagination;
const renderEmpty = configProvider.renderEmpty;
const locale = getLocale(transferLocale, renderEmpty);
const { footer } = slots;
const renderItem = props.render || slots.render;
const leftActive = targetSelectedKeys.value.length > 0;
const rightActive = sourceSelectedKeys.value.length > 0;
const cls = classNames(prefixCls.value, className, {
[`${prefixCls.value}-disabled`]: disabled,
[`${prefixCls.value}-customize-list`]: !!children,
});
const titles = props.titles;
const leftTitle =
(titles && titles[0]) ?? slots.leftTitle?.() ?? (locale.titles || ['', ''])[0];
const rightTitle =
(titles && titles[1]) ?? slots.rightTitle?.() ?? (locale.titles || ['', ''])[1];
return (
<div class={cls} style={style} id={id}>
<List
key="leftList"
prefixCls={`${prefixCls.value}-list`}
dataSource={leftDataSource.value}
filterOption={filterOption}
style={handleListStyle(listStyle, 'left')}
checkedKeys={sourceSelectedKeys.value}
handleFilter={handleLeftFilter}
handleClear={handleLeftClear}
onItemSelect={onLeftItemSelect}
onItemSelectAll={onLeftItemSelectAll}
renderItem={renderItem}
showSearch={showSearch}
renderList={children}
onScroll={handleLeftScroll}
disabled={disabled}
direction="left"
showSelectAll={showSelectAll}
selectAllLabel={selectAllLabels[0] || slots.leftSelectAllLabel}
pagination={mergedPagination}
{...locale}
v-slots={{ titleText: () => leftTitle, footer }}
/>
<Operation
key="operation"
class={`${prefixCls.value}-operation`}
rightActive={rightActive}
rightArrowText={operations[0]}
moveToRight={moveToRight}
leftActive={leftActive}
leftArrowText={operations[1]}
moveToLeft={moveToLeft}
style={operationStyle}
disabled={disabled}
direction={direction.value}
oneWay={oneWay}
/>
<List
key="rightList"
prefixCls={`${prefixCls.value}-list`}
dataSource={rightDataSource.value}
filterOption={filterOption}
style={handleListStyle(listStyle, 'right')}
checkedKeys={targetSelectedKeys.value}
handleFilter={handleRightFilter}
handleClear={handleRightClear}
onItemSelect={onRightItemSelect}
onItemSelectAll={onRightItemSelectAll}
onItemRemove={onRightItemRemove}
renderItem={renderItem}
showSearch={showSearch}
renderList={children}
onScroll={handleRightScroll}
disabled={disabled}
direction="right"
showSelectAll={showSelectAll}
selectAllLabel={selectAllLabels[1] || slots.rightSelectAllLabel}
showRemove={oneWay}
pagination={mergedPagination}
{...locale}
v-slots={{ titleText: () => rightTitle, footer }}
/>
</div>
);
};
return () => (
<LocaleReceiver
componentName="Transfer"
defaultLocale={defaultLocale.Transfer}
children={renderTransfer}
/>
);
},
});
export default withInstall(Transfer); | the_stack |
import wk, { WorkerTransfer } from './node-worker';
type SymbolMap = Record<symbol, number>;
export type Context = [string, Array<string | [string, unknown]>, unknown[]];
export type DepList = () => unknown[];
export type Environment = {
s: SymbolMap;
r: symbol | string;
};
const abvList: Function[] = [
Int8Array,
Uint8Array,
Uint8ClampedArray,
Int16Array,
Uint16Array,
Int32Array,
Float32Array,
Float64Array
];
const setExists = typeof Set != 'undefined';
const mapExists = typeof Map != 'undefined';
if (setExists && !Set.prototype.values) wk.c.push(Set);
if (mapExists && !Map.prototype.entries) wk.c.push(Map);
if (typeof BigInt64Array != 'undefined') abvList.push(BigInt64Array);
if (typeof BigUint64Array != 'undefined') abvList.push(BigUint64Array);
const rand = () => Math.ceil(Math.random() * 1073741823);
const iwInternalRE = /^__iw(.*)__$/;
const getAllPropertyKeys = (o: object) => {
let keys: (string | symbol)[] = Object.getOwnPropertyNames(o).filter(
name => !iwInternalRE.test(name)
);
if (Object.getOwnPropertySymbols) {
keys = keys.concat(
Object.getOwnPropertySymbols(o).filter(
sym => !iwInternalRE.test(Symbol.keyFor(sym))
)
);
}
return keys;
};
const bannedFunctionKeys = getAllPropertyKeys(Function.prototype).concat(
'prototype'
);
const toReplace = '/*r*/null';
const toReplaceRE = /\/\*r\*\/null/;
const renderCtx = (
ctx: (string | number | symbol)[],
ab: WorkerTransfer[],
m: SymbolMap
) => {
let out = 'self';
for (const key of ctx) {
out += `[${encoder[typeof key as 'string' | 'number' | 'symbol'](
key as never,
ab,
m
)}]`;
}
return out;
};
const vDescriptors = (
v: unknown,
keys: (string | symbol)[],
ab: WorkerTransfer[],
m: SymbolMap,
g: GetGBN,
s: SetGBN,
ctx: (string | symbol | number)[],
dat: Array<string | [string, unknown]>
) => {
let out = '';
const renderedCtx = renderCtx(ctx, ab, m);
for (const t of keys) {
const {
enumerable,
configurable,
get,
set,
writable,
value
} = Object.getOwnPropertyDescriptor(v, t);
const keyEnc = encoder[typeof t as 'string' | 'symbol'](t as never, ab, m);
let desc = '{',
res: string;
const enc =
typeof writable == 'boolean' &&
encoder[typeof value](value as never, ab, m, g, s, ctx.concat(t), dat);
const replaced = enc == toReplace;
let obj = 'v';
if (replaced) {
obj = renderedCtx;
dat.pop();
}
if (enc) {
if (writable && configurable && enumerable)
res = `${obj}[${keyEnc}]=${enc}`;
else desc += `writable:${writable},value:${enc}`;
} else
desc += `get:${
get ? encoder.function(get, ab, m, g, s, ctx, dat) : 'void 0'
},set:${set ? encoder.function(set, ab, m, g, s, ctx, dat) : 'void 0'}`;
if (!res) {
desc += `,enumerable:${enumerable},configurable:${configurable}}`;
res = `Object.defineProperty(${obj}, ${encoder[
typeof t as 'string' | 'symbol'
](t as never, ab, m)}, ${desc})`;
}
if (replaced) dat.push([`${res};`, value]);
else out += `;${res}`;
}
if (Object.isSealed(v)) dat.push(`Object.seal(${renderedCtx});`);
if (!Object.isExtensible(v))
dat.push(`Object.preventExtensions(${renderedCtx});`);
if (Object.isFrozen(v)) dat.push(`Object.freeze(${renderedCtx});`);
return out;
};
type GetGBN = (v: unknown) => string;
type SetGBN = (v: unknown, w: string) => string;
const encoder = {
undefined: () => 'void 0',
bigint: (v: BigInt) => v + 'n',
string: (v: string) => JSON.stringify(v),
boolean: (v: boolean) => v + '',
number: (v: number) => v + '',
symbol: (v: symbol, _: unknown, m: SymbolMap) => {
const key = Symbol.keyFor(v);
if (key) return `Symbol.for(${encoder.string(key)})`;
let gbn = m[v];
if (gbn) return `self[${gbn}]`;
gbn = m[v] = rand();
return `(self[${gbn}]=Symbol(${encoder.string(
v.toString().slice(7, -1)
)}))`;
},
function: (
v: Function,
ab: WorkerTransfer[],
m: SymbolMap,
g: GetGBN,
s: SetGBN,
ctx: (string | symbol | number)[],
dat: Array<string | [string, unknown]>
) => {
let st = v.toString();
const proto = v.prototype;
if (st.indexOf('[native code]', 12) != -1) return v.name;
if (st[0] != '(' && !proto) {
const headMatch = st.match(/^(.+?)(?=\()/g);
if (headMatch) st = 'function' + st.slice(headMatch[0].length);
else throw new TypeError(`failed to find function body in ${st}`);
}
const vd = vDescriptors(
v,
getAllPropertyKeys(v).filter(
key => bannedFunctionKeys.indexOf(key) == -1
),
ab,
m,
g,
s,
ctx,
dat
);
const gbn = g(v);
if (gbn) return `(function(){var v=${gbn}${vd};return v})()`;
if (proto) {
const superCtr = Object.getPrototypeOf(proto).constructor;
// TODO: Avoid duplicating methods for ES6 classes
const base = '(function(){';
if (superCtr == Object) st = `${base}var v=${st}`;
else {
const superEnc = encoder.function(
superCtr,
ab,
m,
g,
s,
ctx.concat('prototype'),
dat
);
if (st[0] == 'c') {
const superName = st.match(
/(?<=^class(.*?)extends(.*?)(\s+))(.+?)(?=(\s*){)/g
);
if (!superName)
throw new TypeError(`failed to find superclass in ${st}`);
st = `${base}var ${superName[0]}=${superEnc};var v=${st}`;
} else st = `${base}var v=${st};v.prototype=Object.create(${superEnc})`;
}
for (const t of getAllPropertyKeys(proto)) {
const val = proto[t];
if (t != 'constructor') {
const key = encoder[typeof t as 'string' | 'symbol'](
t as never,
ab,
m
);
st += `;v.prototype[${key}]=${encoder[typeof val](
val as never,
ab,
m,
g,
s,
ctx.concat('prototype', key),
dat
)}`;
}
}
st += `${vd};return v})()`;
} else if (vd.length) st = `(function(){var v=${st}${vd};return v})()`;
return s(v, st);
},
object: (
v: object,
ab: WorkerTransfer[],
m: SymbolMap,
g: GetGBN,
s: SetGBN,
ctx: (string | symbol | number)[],
dat: Array<string | [string, unknown]>
) => {
if (v == null) return 'null';
const proto = Object.getPrototypeOf(v),
ctr = proto.constructor;
let cln = 0;
if (abvList.indexOf(ctr) != -1) cln = ab.push((v as Uint8Array).buffer);
else if (wk.t.indexOf(ctr) != -1) cln = ab.push(v as WorkerTransfer);
else if (wk.c.indexOf(ctr) != -1) cln = 1;
if (cln) {
dat.push([`${renderCtx(ctx, ab, m)}=${toReplace};`, v]);
return toReplace;
}
const gbn = g(v);
if (gbn) return gbn;
let out = '(function(){var v=';
let keys = getAllPropertyKeys(v);
if (ctr == Object) out += `{}`;
else if (ctr == Array) {
let arrStr = '';
for (let i = 0; i < (v as unknown[]).length; ++i) {
if (i in v) {
const val = v[i];
arrStr += encoder[typeof val](
val as never,
ab,
m,
g,
s,
ctx.concat(i),
dat
);
}
arrStr += ',';
}
keys = keys.filter(k => {
return isNaN(+(k as string)) && k != 'length';
});
out += `[${arrStr.slice(0, -1)}]`;
} else if (setExists && ctr == Set) {
let setStr = '';
let getsSets = '';
const it = (v as Set<unknown>).values();
for (let i = 0, v = it.next(); !v.done; ++i, v = it.next()) {
const dl = dat.length;
const sn = `__iwinit${i}__`;
setStr += `${encoder[typeof v.value](
v.value as never,
ab,
m,
g,
s,
ctx.concat(sn),
dat
)},`;
if (dat.length != dl)
getsSets += `;Object.defineProperty(v,"${sn}",{get:function(){return i[${i}]},set:function(n){v.delete(i[${i}]);v.add(i[${i}]=n)}})`;
}
out += `0;var i=[${setStr.slice(0, -1)}];v=new Set(i)${getsSets}`;
} else if (mapExists && ctr == Map) {
let mapStr = '';
let getsSets = '';
const it = (v as Map<unknown, unknown>).entries();
for (let i = 0, v = it.next(); !v.done; ++i, v = it.next()) {
const [key, val] = v.value;
const dl = dat.length;
const sn = `__iwinit${i}__`;
mapStr += `[${encoder[typeof key](
key as never,
ab,
m,
g,
s,
ctx.concat(sn, 0),
dat
)},${encoder[typeof val](
val as never,
ab,
m,
g,
s,
ctx.concat(sn, 1),
dat
)}],`;
if (dat.length != dl)
getsSets += `;Object.defineProperty(v,"${sn}",{value:{get 0(){return i[${i}][0]},set 0(n){v.delete(i[${i}][0]);v.set(i[${i}][0]=n,i[${i}][1])},get 1(){return i[${i}][1]},set 1(n){v.set(i[${i}][0],i[${i}][1]=n)}}})`;
}
out += `0;var i=[${mapStr.slice(0, -1)}];v=new Map(i)${getsSets}`;
} else if (ctr == Date) out += `new Date(${(v as Date).getTime()})`;
else
out += `Object.create((${encoder.function(
ctr,
ab,
m,
g,
s,
ctx.concat('constructor'),
dat
)}).prototype)`;
return out + vDescriptors(v, keys, ab, m, g, s, ctx, dat) + ';return v})()';
}
};
const ccRaw = (
depNames: string[],
depValues: unknown[],
env: Environment
): Context => {
let out = '';
const dat: Array<string | [string, unknown]> = [];
const ab: WorkerTransfer[] = [];
const gbnKey = env.r;
const getGBN = (obj: unknown) => {
const gbn: string = obj[gbnKey];
if (gbn) return `self[${gbn}]`;
};
const setGBN = (obj: unknown, wrap: string) => {
const gbn = rand();
Object.defineProperty(obj, gbnKey, {
value: gbn
});
return `(self[${gbn}]=${wrap})`;
};
for (let i = 0; i < depValues.length; ++i) {
const key = depNames[i],
value = depValues[i];
const v = encoder[typeof value](
value as never,
ab,
env.s,
getGBN,
setGBN,
[key],
dat
);
const parts = key
.replace(/\\/, '')
.match(/^(.*?)(?=(\.|\[|$))|\[(.*?)\]|(\.(.*?))(?=(\.|\[|$))/g);
let pfx = 'self.' + parts[0];
let chain = pfx;
for (let i = 1; i < parts.length; ++i) {
chain = `(${chain}||(${pfx}={}))${parts[i]}`;
pfx += parts[i];
}
out += `${chain}=${v};`;
}
for (let i = 0; i < ab.length; ++i) {
const buf = ab[i];
if (buf[gbnKey] == -1) ab.splice(i--, 1);
else buf[gbnKey] = -1;
}
return [out, dat, ab];
};
/**
* Creates a context for a worker execution environment
* @param depList The dependencies in the worker environment
* @param env The environment to use for the worker. If this object was used
* before, `isoworker` will use certain optimizations to avoid code
* duplication. This is useful for sending a serialized message to
* a worker to be dynamically evaluated, in which case you may want
* to avoid duplicating existing function declarations.
* @returns An environment that can be built to a Worker. Note the fourth
* element of the tuple, the global element registry, is currently not useful.
*/
export function createContext(
depList: DepList | DepList[],
env: Partial<Environment> = {}
): Context {
let depNames: string[] = [];
let depValues: unknown[] = [];
if (!env.r) {
const base = `__iwgbn${rand()}__`;
env.r = typeof Symbol == 'undefined' ? base : Symbol.for(base);
}
if (!env.s) env.s = {};
for (const dl of depList instanceof Array ? depList : [depList]) {
const dlStr = dl.toString();
depNames = depNames.concat(
dlStr
.slice(dlStr.indexOf('[') + 1, dlStr.lastIndexOf(']'))
.replace(/\s/g, '')
.split(',')
);
depValues = depValues.concat(dl());
}
return ccRaw(depNames, depValues, env as Environment);
}
const findTransferables = (vals: unknown[]) => {
const tfKeyBase = `__iwtf${rand()}__`;
const tfKey =
typeof Symbol == 'undefined' ? tfKeyBase : Symbol.for(tfKeyBase);
return vals.reduce<WorkerTransfer[]>((a, v) => {
const proto = Object.getPrototypeOf(v),
ctr = proto.constructor;
if (abvList.indexOf(ctr) != -1) {
const buf = (v as Uint8Array).buffer;
if (!buf[tfKey]) {
buf[tfKey] = 1;
a.push(buf);
}
} else if (wk.t.indexOf(ctr) != -1 && !v[tfKey]) {
v[tfKey] = 1;
a.push(v as WorkerTransfer);
}
return a;
}, []);
};
/**
* A RegExp that matches the placeholder used in isoworker's initial message code.
* Used after loading structured-cloneable data onto the worker thread in order to
* finalize the context creation.
*/
export const dataPlaceholder = toReplaceRE;
/**
* A workerized function (from arguments and return type)
*/
export type Workerized<A extends unknown[], R> = ((
...args: [...A, (err: Error, res: R) => unknown]
) => void) & {
/**
* Kills the worker associated with this workerized function.
* Subsequent calls will fail.
*/
close(): void;
};
const globalEnv =
typeof globalThis == 'undefined'
? typeof window == 'undefined'
? typeof self == 'undefined'
? typeof global == 'undefined'
? {}
: global
: self
: window
: globalThis;
/**
* Converts a function with dependencies into a worker
* @param fn The function to workerize
* @param deps The dependencies to add. This should include sub-dependencies.
* For example, if you are workerizing a function that calls
* another function, put any dependencies of the other function
* here as well.
* @param replaceTransfer The list of objects to replace the default transfer
* list with. If you provide an array of transferable
* items, they will be used; if you provide the value
* `true`, `isoworker` will refrain from the default
* behavior of automatically transferring everything
* it can.
* @returns A function that accepts parameters and, as the last argument, a
* callback to use when the worker returns.
*/
export function workerize<TA extends unknown[], TR>(
fn: (...args: TA) => TR,
deps: DepList | DepList[],
serializeArgs?: boolean,
replaceTransfer?: unknown[] | boolean
): Workerized<TA, TR> {
const env: Partial<Environment> = {};
const [str, exec, tfl] = createContext(deps, env);
let currentCb: (err: Error, res: unknown) => void;
let runCount = 0;
let callCount = 0;
let assignStr = '';
const transfer = (replaceTransfer
? replaceTransfer instanceof Array
? replaceTransfer
: []
: tfl) as WorkerTransfer[];
const msg: unknown[] = [];
for (let cmd of exec) {
if (typeof cmd != 'string') {
cmd = cmd[0].replace(toReplaceRE, `e.data[${msg.push(cmd[1]) - 1}]`);
}
assignStr += cmd;
}
const fixArgs = serializeArgs
? 'var b=e.data[1];eval(e.data[0]);d=self.__iwargs__;'
: '';
const worker = wk(
`${str}onmessage=function(e){${assignStr}var v=${fn};var _p=function(d){d?typeof d.then=='function'?d.then(_p,_e):postMessage(d,d.__transfer):postMessage(d)};var _e=function(e){!(e instanceof Error)&&(e=new Error(e));postMessage({__iwerr__:{s:e.stack,m:e.message,n:e.name}})};onmessage=function(e){var d=e.data;${fixArgs}try{_p(v.apply(self,d))}catch(e){_e(e)}}}`,
msg,
transfer,
(err, res) => {
++runCount;
const rtErr =
res &&
(res as { __iwerr__?: { n: string; s: string; m: string } }).__iwerr__;
if (rtErr) {
err = new (globalEnv[rtErr.n] || Error)();
err.message = rtErr.m;
err.name = rtErr.n;
err.stack = rtErr.s;
currentCb(err, null);
} else if (err) {
for (; runCount <= callCount; ++runCount) currentCb(err, res);
wfn.close();
} else currentCb(err, res);
}
);
let closed = false;
const wfn: Workerized<TA, TR> = (...args) => {
const cb = args.pop() as (err: Error, res: TR) => unknown;
if (typeof cb != 'function') throw new TypeError('no callback provided');
if (closed) {
cb(new Error('worker thread closed'), null);
return;
}
const lastCb = currentCb;
const startCount = ++callCount;
currentCb = (err, r) => {
if (runCount == startCount) cb(err, r as TR);
else lastCb(err, r);
};
if (serializeArgs) {
let [code, ext, mtfl] = ccRaw(['__iwargs__'], [args], env as Environment);
const rawMsg: unknown[] = [];
for (let cmd of ext) {
if (typeof cmd != 'string') {
cmd = cmd[0].replace(toReplaceRE, `b[${rawMsg.push(cmd[1]) - 1}]`);
}
code += cmd;
}
worker.postMessage([code, rawMsg], mtfl as WorkerTransfer[]);
} else worker.postMessage(args, findTransferables(args));
};
wfn.close = () => {
worker.terminate();
closed = true;
};
return wfn;
} | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace Formmsdyn_livechatconfig_Information {
interface Header extends DevKit.Controls.IHeader {
/** Date and time when the record was created. */
CreatedOn: DevKit.Controls.DateTime;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
}
interface tab_AutomatedMessages_tab_Sections {
tab_9_section_1: DevKit.Controls.Section;
}
interface tab_tab_3_Sections {
offline_messagingsection: DevKit.Controls.Section;
offline_section: DevKit.Controls.Section;
online_section: DevKit.Controls.Section;
}
interface tab_tab_4_Sections {
Chat_Transcripts: DevKit.Controls.Section;
File_attachments: DevKit.Controls.Section;
tab_4_section_1: DevKit.Controls.Section;
tab_4_section_3: DevKit.Controls.Section;
tab_4_section_5: DevKit.Controls.Section;
tab_4_section_6: DevKit.Controls.Section;
tab_4_section_6_2: DevKit.Controls.Section;
tab_4_section_8: DevKit.Controls.Section;
tab_4_section_9: DevKit.Controls.Section;
}
interface tab_tab_5_Sections {
Survey_section_1: DevKit.Controls.Section;
tab_5_section_1: DevKit.Controls.Section;
}
interface tab_tab_6_Sections {
location_tracking: DevKit.Controls.Section;
tab_4_section_2: DevKit.Controls.Section;
tab_4_section_4: DevKit.Controls.Section;
}
interface tab_tab_7_Sections {
tab_7_section_1: DevKit.Controls.Section;
}
interface tab_tab_8_Sections {
tab_8_section_1: DevKit.Controls.Section;
tab_8_section_2: DevKit.Controls.Section;
}
interface tab_AutomatedMessages_tab extends DevKit.Controls.ITab {
Section: tab_AutomatedMessages_tab_Sections;
}
interface tab_tab_3 extends DevKit.Controls.ITab {
Section: tab_tab_3_Sections;
}
interface tab_tab_4 extends DevKit.Controls.ITab {
Section: tab_tab_4_Sections;
}
interface tab_tab_5 extends DevKit.Controls.ITab {
Section: tab_tab_5_Sections;
}
interface tab_tab_6 extends DevKit.Controls.ITab {
Section: tab_tab_6_Sections;
}
interface tab_tab_7 extends DevKit.Controls.ITab {
Section: tab_tab_7_Sections;
}
interface tab_tab_8 extends DevKit.Controls.ITab {
Section: tab_tab_8_Sections;
}
interface Tabs {
AutomatedMessages_tab: tab_AutomatedMessages_tab;
tab_3: tab_tab_3;
tab_4: tab_tab_4;
tab_5: tab_tab_5;
tab_6: tab_tab_6;
tab_7: tab_tab_7;
tab_8: tab_tab_8;
}
interface Body {
Tab: Tabs;
/** Configure agent name to be displayed in the chat widget */
msdyn_agentDisplayName: DevKit.Controls.OptionSet;
/** Unique identifier for Authentication settings associated with Chat widget. */
msdyn_AuthsettingsId: DevKit.Controls.Lookup;
/** Indicates if the chat widget should automatically detect user locale. */
msdyn_AutoDetectLanguage: DevKit.Controls.Boolean;
/** Chat logo */
msdyn_avatarUrl: DevKit.Controls.String;
/** Indicates whether display of wait time is enabled */
msdyn_averagewaittime_enabled: DevKit.Controls.Boolean;
/** List of calling options available for the chat widget */
msdyn_callingoptions: DevKit.Controls.OptionSet;
/** Select a co-browse provider */
msdyn_cobrowseprovider: DevKit.Controls.String;
/** Indicates the conversation mode of the chat widget */
msdyn_conversationmode: DevKit.Controls.OptionSet;
msdyn_conversationmodedisclaimer: DevKit.Controls.ActionCards;
/** Email Template */
msdyn_EmailTemplate: DevKit.Controls.String;
/** This will let customers reconnect to their previous session. */
msdyn_enablechatreconnect: DevKit.Controls.Boolean;
/** Allow download of transcript */
msdyn_Enablechattranscriptdownload: DevKit.Controls.Boolean;
/** Allow email of transcript */
msdyn_Enablechattranscriptemail: DevKit.Controls.Boolean;
/** Co-browse allows agent and customer to interact on the same web page in real time */
msdyn_enablecobrowse: DevKit.Controls.Boolean;
/** Enable file attachments for agents */
msdyn_Enablefileattachmentsforagents: DevKit.Controls.Boolean;
/** Enable file attachments for customers */
msdyn_Enablefileattachmentsforcustomers: DevKit.Controls.Boolean;
/** Enable Screen sharing */
msdyn_enablescreensharing: DevKit.Controls.Boolean;
msdyn_FormsProButton: DevKit.Controls.WebResource;
msdyn_generalsubheading: DevKit.Controls.ActionCards;
/** Display Agent Generic Name */
msdyn_genericagentdisplayname: DevKit.Controls.String;
/** Label string indicating user to save the record to add location information */
msdyn_infolabel: DevKit.Controls.String;
msdyn_livechattext: DevKit.Controls.ActionCards;
/** Work Stream Identifier */
msdyn_liveworkstreamid: DevKit.Controls.Lookup;
/** The mailbox where your email transcripts will be sent from. */
msdyn_Mailbox: DevKit.Controls.String;
/** The name of the custom entity. */
msdyn_name: DevKit.Controls.String;
/** Geo Location Provider API Key */
msdyn_oc_geolocationprovider: DevKit.Controls.Lookup;
/** The language of the chat widget. */
msdyn_ocWidgetLanguage: DevKit.Controls.Lookup;
/** Description for offline widget subtitle attribute */
msdyn_offlinewidgetsubtitle: DevKit.Controls.String;
/** Description for offline widget theme color attribute */
msdyn_offlinewidgetthemecolor: DevKit.Controls.OptionSet;
/** Description for offline widget title attribute */
msdyn_offlinewidgettitle: DevKit.Controls.String;
/** Unique identifier for Operating hour associated with Chat widget. */
msdyn_operatinghourid: DevKit.Controls.Lookup;
msdyn_persistentchattext: DevKit.Controls.ActionCards;
/** Provide a link to the web portal where your chat is hosted. */
msdyn_portalurl: DevKit.Controls.String;
/** Enable Position In Queue feature */
msdyn_positioninqueue_enabled: DevKit.Controls.Boolean;
/** Enable Post-Chat (Deprecated) */
msdyn_postchatenabled: DevKit.Controls.Boolean;
/** Lookup to Dynamics 365 Customer Voice survey field */
msdyn_PostConversationSurvey: DevKit.Controls.Lookup;
/** To enable or disable post conversation survey */
msdyn_PostConversationSurveyEnable: DevKit.Controls.Boolean;
/** Prefix text for survey link message that will be sent to the user. */
msdyn_PostConversationSurveyMessageText: DevKit.Controls.String;
/** Mode of the survey to be sent */
msdyn_PostConversationSurveyMode: DevKit.Controls.OptionSet;
/** Enable Pre-chat survey feature */
msdyn_PrechatEnabled: DevKit.Controls.Boolean;
/** Enable Proactive chat for this chat widget */
msdyn_proactivechatenabled: DevKit.Controls.Boolean;
/** We'll redirect customers to this webpage. */
msdyn_redirectionurl: DevKit.Controls.String;
/** Enable Visitor Location Feature */
msdyn_requestvisitorlocation: DevKit.Controls.Boolean;
/** Select a screen sharing provider */
msdyn_screensharingprovider: DevKit.Controls.String;
/** Description for show/hide offline widget attribute */
msdyn_Showwidgetduringofflinehours: DevKit.Controls.Boolean;
/** The previous agent's capacity will be held for this time period. */
msdyn_timetoreconnectwithpreviousagent: DevKit.Controls.Integer;
/** Widget App Identifier used to identify the chat widget */
msdyn_widgetAppId: DevKit.Controls.String;
/** The language of the chat widget. */
msdyn_WidgetLocale: DevKit.Controls.Lookup;
/** Chat position relative to the page */
msdyn_widgetPosition: DevKit.Controls.OptionSet;
/** Javascript snippet which can be embedded in a webpage */
msdyn_WidgetSnippet: DevKit.Controls.String;
/** Enable sound notifications for new incoming messages */
msdyn_widgetsoundnotification: DevKit.Controls.Boolean;
/** Subtitle for the chat widget */
msdyn_widgetSubtitle: DevKit.Controls.String;
/** Theme color for the chat widget */
msdyn_widgetThemeColor: DevKit.Controls.OptionSet;
/** Title for the chat widget */
msdyn_widgetTitle: DevKit.Controls.String;
/** Enable visual indicators for unread messages */
msdyn_widgetvisualnotification: DevKit.Controls.Boolean;
WebResource_Disclaimer: DevKit.Controls.WebResource;
WebResource_ocpreviewterms: DevKit.Controls.WebResource;
WebResource_postconversationsurveydisclaimer: DevKit.Controls.WebResource;
}
interface quickForm_msdyn_reconnecttimelimit_Body {
msdyn_AutoCloseAfterInactivity: DevKit.Controls.QuickView;
}
interface quickForm_msdyn_reconnecttimelimit extends DevKit.Controls.IQuickView {
Body: quickForm_msdyn_reconnecttimelimit_Body;
}
interface QuickForm {
msdyn_reconnecttimelimit: quickForm_msdyn_reconnecttimelimit;
}
interface Grid {
instance_CustomSystemMessage: DevKit.Controls.Grid;
PrechatUnauthenticatedQuestions: DevKit.Controls.Grid;
CustomOOOHMessages: DevKit.Controls.Grid;
includeDomain: DevKit.Controls.Grid;
PostchatUnauthenticatedQuestions: DevKit.Controls.Grid;
}
}
class Formmsdyn_livechatconfig_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form msdyn_livechatconfig_Information
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form msdyn_livechatconfig_Information */
Body: DevKit.Formmsdyn_livechatconfig_Information.Body;
/** The Header section of form msdyn_livechatconfig_Information */
Header: DevKit.Formmsdyn_livechatconfig_Information.Header;
/** The QuickForm of form msdyn_livechatconfig_Information */
QuickForm: DevKit.Formmsdyn_livechatconfig_Information.QuickForm;
/** The Grid of form msdyn_livechatconfig_Information */
Grid: DevKit.Formmsdyn_livechatconfig_Information.Grid;
}
class msdyn_livechatconfigApi {
/**
* DynamicsCrm.DevKit msdyn_livechatconfigApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Unique identifier of the user who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was created. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who created the record. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier of the user who modified the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was modified. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who modified the record. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Configure agent name to be displayed in the chat widget */
msdyn_agentDisplayName: DevKit.WebApi.OptionSetValue;
/** Unique identifier for Authentication settings associated with Chat widget. */
msdyn_AuthsettingsId: DevKit.WebApi.LookupValue;
/** Indicates if the chat widget should automatically detect user locale. */
msdyn_AutoDetectLanguage: DevKit.WebApi.BooleanValue;
/** Chat logo */
msdyn_avatarUrl: DevKit.WebApi.StringValue;
/** Indicates whether display of wait time is enabled */
msdyn_averagewaittime_enabled: DevKit.WebApi.BooleanValue;
/** List of calling options available for the chat widget */
msdyn_callingoptions: DevKit.WebApi.OptionSetValue;
/** Select a co-browse provider */
msdyn_cobrowseprovider: DevKit.WebApi.StringValue;
/** Indicates the conversation mode of the chat widget */
msdyn_conversationmode: DevKit.WebApi.OptionSetValue;
/** (Deprecated) During non-operating hours */
msdyn_Duringnonoperatinghours: DevKit.WebApi.StringValue;
/** Email Template */
msdyn_EmailTemplate: DevKit.WebApi.StringValue;
/** This will let customers reconnect to their previous session. */
msdyn_enablechatreconnect: DevKit.WebApi.BooleanValue;
/** Allow download of transcript */
msdyn_Enablechattranscriptdownload: DevKit.WebApi.BooleanValue;
/** Allow email of transcript */
msdyn_Enablechattranscriptemail: DevKit.WebApi.BooleanValue;
/** Co-browse allows agent and customer to interact on the same web page in real time */
msdyn_enablecobrowse: DevKit.WebApi.BooleanValue;
/** Enable file attachments for agents */
msdyn_Enablefileattachmentsforagents: DevKit.WebApi.BooleanValue;
/** Enable file attachments for customers */
msdyn_Enablefileattachmentsforcustomers: DevKit.WebApi.BooleanValue;
/** Enable Screen sharing */
msdyn_enablescreensharing: DevKit.WebApi.BooleanValue;
/** Display Agent Generic Name */
msdyn_genericagentdisplayname: DevKit.WebApi.StringValue;
/** Label string indicating user to save the record to add location information */
msdyn_infolabel: DevKit.WebApi.StringValue;
/** Language in which chat widget is rendered */
msdyn_Language: DevKit.WebApi.OptionSetValue;
/** Unique identifier for entity instances */
msdyn_livechatconfigId: DevKit.WebApi.GuidValue;
/** Work Stream Identifier */
msdyn_liveworkstreamid: DevKit.WebApi.LookupValue;
/** The mailbox where your email transcripts will be sent from. */
msdyn_Mailbox: DevKit.WebApi.StringValue;
/** The name of the custom entity. */
msdyn_name: DevKit.WebApi.StringValue;
/** Geo Location Provider API Key */
msdyn_oc_geolocationprovider: DevKit.WebApi.LookupValue;
/** The language of the chat widget. */
msdyn_ocWidgetLanguage: DevKit.WebApi.LookupValue;
/** Description for offline widget subtitle attribute */
msdyn_offlinewidgetsubtitle: DevKit.WebApi.StringValue;
/** Description for offline widget theme color attribute */
msdyn_offlinewidgetthemecolor: DevKit.WebApi.OptionSetValue;
/** Description for offline widget title attribute */
msdyn_offlinewidgettitle: DevKit.WebApi.StringValue;
/** Unique identifier for Operating hour associated with Chat widget. */
msdyn_operatinghourid: DevKit.WebApi.LookupValue;
/** Provide a link to the web portal where your chat is hosted. */
msdyn_portalurl: DevKit.WebApi.StringValue;
/** Enable Position In Queue feature */
msdyn_positioninqueue_enabled: DevKit.WebApi.BooleanValue;
/** Enable Post-Chat (Deprecated) */
msdyn_postchatenabled: DevKit.WebApi.BooleanValue;
/** Lookup to Dynamics 365 Customer Voice survey field */
msdyn_PostConversationSurvey: DevKit.WebApi.LookupValue;
/** To enable or disable post conversation survey */
msdyn_PostConversationSurveyEnable: DevKit.WebApi.BooleanValue;
/** Prefix text for survey link message that will be sent to the user. */
msdyn_PostConversationSurveyMessageText: DevKit.WebApi.StringValue;
/** Mode of the survey to be sent */
msdyn_PostConversationSurveyMode: DevKit.WebApi.OptionSetValue;
/** Enable Pre-chat survey feature */
msdyn_PrechatEnabled: DevKit.WebApi.BooleanValue;
/** Prechat Question set for authenticated users */
msdyn_PreChatQuestionnaireAuthenticated: DevKit.WebApi.LookupValue;
/** Prechat Question set for unauthenticated users */
msdyn_PreChatQuestionnaireUnauthenticated: DevKit.WebApi.LookupValue;
/** Enable Proactive chat for this chat widget */
msdyn_proactivechatenabled: DevKit.WebApi.BooleanValue;
/** We'll redirect customers to this webpage. */
msdyn_redirectionurl: DevKit.WebApi.StringValue;
/** Enable Visitor Location Feature */
msdyn_requestvisitorlocation: DevKit.WebApi.BooleanValue;
/** Select a screen sharing provider */
msdyn_screensharingprovider: DevKit.WebApi.StringValue;
/** Agent Display Name configuration for the chat widget */
msdyn_showagentname: DevKit.WebApi.BooleanValue;
/** Description for show/hide offline widget attribute */
msdyn_Showwidgetduringofflinehours: DevKit.WebApi.BooleanValue;
/** The previous agent's capacity will be held for this time period. */
msdyn_timetoreconnectwithpreviousagent: DevKit.WebApi.IntegerValue;
/** Widget App Identifier used to identify the chat widget */
msdyn_widgetAppId: DevKit.WebApi.StringValue;
/** The language of the chat widget. */
msdyn_WidgetLocale: DevKit.WebApi.LookupValue;
/** Chat position relative to the page */
msdyn_widgetPosition: DevKit.WebApi.OptionSetValue;
/** Javascript snippet which can be embedded in a webpage */
msdyn_WidgetSnippet: DevKit.WebApi.StringValue;
/** Enable sound notifications for new incoming messages */
msdyn_widgetsoundnotification: DevKit.WebApi.BooleanValue;
/** Subtitle for the chat widget */
msdyn_widgetSubtitle: DevKit.WebApi.StringValue;
/** Theme color for the chat widget */
msdyn_widgetThemeColor: DevKit.WebApi.OptionSetValue;
/** Title for the chat widget */
msdyn_widgetTitle: DevKit.WebApi.StringValue;
/** Enable visual indicators for unread messages */
msdyn_widgetvisualnotification: DevKit.WebApi.BooleanValue;
/** Date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValue;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValue;
/** Unique identifier for the business unit that owns the record */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the team that owns the record. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the user that owns the record. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Status of the Chat widget */
statecode: DevKit.WebApi.OptionSetValue;
/** Reason for the status of the Chat widget */
statuscode: DevKit.WebApi.OptionSetValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version Number */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
}
}
declare namespace OptionSet {
namespace msdyn_livechatconfig {
enum msdyn_agentDisplayName {
/** 192350001 */
First_name,
/** 192350000 */
Full_name,
/** 192350002 */
Last_name,
/** 192350003 */
Nick_name
}
enum msdyn_callingoptions {
/** 192350000 */
No_calling,
/** 192350001 */
Video_and_voice_calling,
/** 192350002 */
Voice_only
}
enum msdyn_conversationmode {
/** 192350000 */
Live_Chat,
/** 192350001 */
Persistent_Chat
}
enum msdyn_Language {
/** 192350000 */
Auto_Detect,
/** 192360014 */
English
}
enum msdyn_offlinewidgetthemecolor {
/** 19236004 */
Black,
/** 19236002 */
Blue,
/** 192350005 */
Brown,
/** 192350006 */
Clay,
/** 19236003 */
Green,
/** 192350003 */
Grey,
/** 192350001 */
Orange,
/** 192350002 */
Pink,
/** 192350007 */
Purple,
/** 19236001 */
Red,
/** 192360017 */
Teal,
/** 192350004 */
Violet
}
enum msdyn_PostConversationSurveyMode {
/** 192350000 */
Insert_survey_in_conversation,
/** 192350001 */
Send_survey_link_to_conversation
}
enum msdyn_widgetPosition {
/** 192236011 */
Bottom_left,
/** 192236010 */
Bottom_right
}
enum msdyn_widgetThemeColor {
/** 19236004 */
Black,
/** 19236002 */
Blue,
/** 192350005 */
Brown,
/** 192350006 */
Clay,
/** 19236003 */
Green,
/** 192350003 */
Grey,
/** 192350001 */
Orange,
/** 192350002 */
Pink,
/** 192350007 */
Purple,
/** 19236001 */
Red,
/** 192360017 */
Teal,
/** 192350004 */
Violet
}
enum statecode {
/** 0 */
Active,
/** 1 */
Inactive
}
enum statuscode {
/** 1 */
Active,
/** 2 */
Inactive
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import TelegramBot from 'node-telegram-bot-api';
import {
UrbanSyntheticEvent,
UrbanSyntheticEventVoice,
UrbanSyntheticEventText,
UrbanSyntheticEventDice,
UrbanSyntheticEventVideo,
UrbanSyntheticEventPoll,
UrbanSyntheticEventImage,
UrbanSyntheticEventLocation,
UrbanSyntheticEventInvoice,
UrbanSyntheticEventCommand,
UrbanSyntheticEventSticker,
UrbanSyntheticEventFile,
UrbanSyntheticEventContact,
UrbanSyntheticEventAudio,
UrbanSyntheticEventAnimation,
UrbanSyntheticEventAction,
UrbanSyntheticEventType,
UrbanSyntheticEventCommon,
UrbanBot,
UrbanExistingMessage,
UrbanMessage,
UrbanCommand,
UrbanParseMode,
UrbanExistingMessageByType,
UrbanSyntheticEventVideoNote,
} from '@urban-bot/core';
import {
EditMessageOptions,
formatParamsForExistingMessage,
formatParamsForNewMessage,
getTelegramMedia,
} from './format';
import {
TelegramMessageMeta,
TelegramPayload,
TelegramBotMessage,
TELEGRAM,
InputMediaAudio,
InputMediaFile,
InputMediaAnimation,
} from './types';
import express from 'express';
export type UrbanNativeEventTelegram<Payload = TelegramPayload> = {
type: TELEGRAM;
payload?: Payload;
};
export type UrbanBotTelegramType<Payload = TelegramPayload> = {
NativeEvent: UrbanNativeEventTelegram<Payload>;
MessageMeta: TelegramMessageMeta;
};
export type TelegramOptions = {
token: string;
isPolling?: boolean;
pathnamePrefix?: string;
[key: string]: any;
};
export class UrbanBotTelegram implements UrbanBot<UrbanBotTelegramType> {
static TYPE = 'TELEGRAM' as const;
type = UrbanBotTelegram.TYPE;
defaultParseMode: UrbanParseMode = 'HTML';
commandPrefix = '/';
client: TelegramBot;
constructor(public options: TelegramOptions) {
const { isPolling, token, ...otherOptions } = options;
this.client = new TelegramBot(token, isPolling ? { polling: true, ...otherOptions } : undefined);
this.client.on('text', (ctx) => this.handleMessage('text', ctx));
this.client.on('callback_query', this.handleCallbackQuery);
this.client.on('sticker', (ctx) => this.handleMessage('sticker', ctx));
this.client.on('animation', (ctx) => this.handleMessage('animation', ctx));
this.client.on('audio', (ctx) => this.handleMessage('audio', ctx));
this.client.on('contact', (ctx) => this.handleMessage('contact', ctx));
this.client.on('document', (ctx) => this.handleMessage('file', ctx));
this.client.on('invoice', (ctx) => this.handleMessage('invoice', ctx));
this.client.on('location', (ctx) => this.handleMessage('location', ctx));
this.client.on('photo', (ctx) => this.handleMessage('image', ctx));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this.client.on('poll' as any, (ctx) => this.handleMessage('poll', (ctx as unknown) as TelegramBotMessage));
this.client.on('video', (ctx) => this.handleMessage('video', ctx));
this.client.on('voice', (ctx) => this.handleMessage('voice', ctx));
this.client.on('video_note', (ctx) => this.handleMessage('video_note', ctx));
this.client.on('message', (ctx) => {
const ctxWithDice: TelegramBotMessage = ctx;
if (ctxWithDice.dice !== undefined) {
this.handleMessage('dice', ctxWithDice);
return;
}
});
}
initializeServer(expressApp: express.Express) {
if (this.options.isPolling) {
return;
}
const pathnamePrefix = this.options.pathnamePrefix ?? '';
expressApp.use(`${pathnamePrefix}/telegram/*`, express.json());
expressApp.post(`${pathnamePrefix}/telegram/bot${this.options.token}`, (req, res) => {
this.client.processUpdate(req.body);
res.sendStatus(200);
});
}
processUpdate(_event: UrbanSyntheticEvent<UrbanBotTelegramType>) {
throw new Error('this method must be overridden');
}
handleMessage = (type: UrbanSyntheticEventType<UrbanBotTelegramType>, ctx: TelegramBotMessage) => {
if (!ctx.chat) {
console.error("Chat information didn't come from Telegram event");
console.error('Message type', type);
console.error('Message context', ctx);
return;
}
const common: UrbanSyntheticEventCommon<UrbanBotTelegramType> = {
chat: {
id: String(ctx.chat.id),
type: ctx.chat.type,
title: ctx.chat.title,
username: ctx.chat.username,
firstName: ctx.chat.first_name,
lastName: ctx.chat.last_name,
description: ctx.chat.description,
inviteLink: ctx.chat.invite_link,
},
from: {
id: String(ctx.from?.id),
username: ctx.from?.username,
firstName: ctx.from?.first_name,
lastName: ctx.from?.last_name,
isBot: ctx.from?.is_bot,
},
nativeEvent: {
type: UrbanBotTelegram.TYPE,
payload: ctx,
},
};
switch (type) {
case 'text': {
if (ctx.text === undefined) {
break;
}
if (ctx.text[0] === this.commandPrefix) {
const [command, ...args] = ctx.text.split(' ');
const adaptedContext: UrbanSyntheticEventCommand<UrbanBotTelegramType> = {
...common,
type: 'command',
payload: {
command,
argument: args.join(' '),
},
};
this.processUpdate(adaptedContext);
} else {
const adaptedContext: UrbanSyntheticEventText<UrbanBotTelegramType> = {
...common,
type: 'text',
payload: {
text: ctx.text,
},
};
this.processUpdate(adaptedContext);
}
break;
}
case 'dice': {
if (ctx.dice === undefined) {
break;
}
const adaptedContext: UrbanSyntheticEventDice<UrbanBotTelegramType> = {
...common,
type: 'dice',
payload: {
value: ctx.dice.value,
},
};
this.processUpdate(adaptedContext);
break;
}
case 'poll': {
if (ctx.poll === undefined) {
break;
}
const adaptedContext: UrbanSyntheticEventPoll<UrbanBotTelegramType> = {
...common,
type: 'poll',
payload: {
id: ctx.poll.id,
question: ctx.poll.question,
options: ctx.poll.options.map((option) => {
return { text: option.text, count: option.voter_count };
}),
},
};
this.processUpdate(adaptedContext);
break;
}
case 'sticker': {
if (ctx.sticker === undefined) {
break;
}
const adaptedContext: UrbanSyntheticEventSticker<UrbanBotTelegramType> = {
...common,
type: 'sticker',
payload: {
emoji: ctx.sticker.emoji,
id: ctx.sticker.file_id,
width: ctx.sticker.width,
height: ctx.sticker.height,
name: ctx.sticker.set_name,
},
};
this.processUpdate(adaptedContext);
break;
}
case 'animation': {
if (ctx.animation === undefined) {
break;
}
const adaptedContext: UrbanSyntheticEventAnimation<UrbanBotTelegramType> = {
...common,
type: 'animation',
payload: {
duration: ctx.animation.duration,
name: ctx.animation.file_name,
mimeType: ctx.animation.mime_type,
},
};
this.processUpdate(adaptedContext);
break;
}
case 'audio': {
if (ctx.audio === undefined) {
break;
}
const name = `${ctx.audio.performer ?? ''} ${ctx.audio.title ?? ''}`.trim();
const adaptedContext: UrbanSyntheticEventAudio<UrbanBotTelegramType> = {
...common,
type: 'audio',
payload: {
files: [
{
duration: ctx.audio.duration,
id: ctx.audio.file_id,
size: ctx.audio.file_size,
name,
mimeType: ctx.audio.mime_type,
},
],
},
};
this.processUpdate(adaptedContext);
break;
}
case 'contact': {
if (ctx.contact === undefined) {
break;
}
const adaptedContext: UrbanSyntheticEventContact<UrbanBotTelegramType> = {
...common,
type: 'contact',
payload: {
firstName: ctx.contact.first_name,
phoneNumber: ctx.contact.phone_number,
lastName: ctx.contact.last_name,
userId: ctx.contact.user_id,
},
};
this.processUpdate(adaptedContext);
break;
}
case 'file': {
if (ctx.document === undefined) {
break;
}
const adaptedContext: UrbanSyntheticEventFile<UrbanBotTelegramType> = {
...common,
type: 'file',
payload: {
files: [
{
id: ctx.document.file_id,
name: ctx.document.file_name,
size: ctx.document.file_size,
mimeType: ctx.document.mime_type,
},
],
},
};
this.processUpdate(adaptedContext);
break;
}
case 'invoice': {
if (ctx.invoice === undefined) {
break;
}
const adaptedContext: UrbanSyntheticEventInvoice<UrbanBotTelegramType> = {
...common,
type: 'invoice',
payload: {
currency: ctx.invoice.currency,
description: ctx.invoice.description,
title: ctx.invoice.title,
startParameter: ctx.invoice.start_parameter,
totalAmount: ctx.invoice.total_amount,
},
};
this.processUpdate(adaptedContext);
break;
}
case 'location': {
if (ctx.location === undefined) {
break;
}
const adaptedContext: UrbanSyntheticEventLocation<UrbanBotTelegramType> = {
...common,
type: 'location',
payload: {
latitude: ctx.location.latitude,
longitude: ctx.location.longitude,
},
};
this.processUpdate(adaptedContext);
break;
}
case 'image': {
if (ctx.photo === undefined) {
break;
}
const adaptedContext: UrbanSyntheticEventImage<UrbanBotTelegramType> = {
...common,
type: 'image',
payload: {
files: ctx.photo.map((photo) => ({
id: photo.file_id,
size: photo.file_size,
width: photo.width,
height: photo.height,
})),
},
};
this.processUpdate(adaptedContext);
break;
}
case 'video': {
if (ctx.video === undefined) {
break;
}
const adaptedContext: UrbanSyntheticEventVideo<UrbanBotTelegramType> = {
...common,
type: 'video',
payload: {
files: [
{
duration: ctx.video.duration,
id: ctx.video.file_id,
size: ctx.video.file_size,
mimeType: ctx.video.mime_type,
},
],
},
};
this.processUpdate(adaptedContext);
break;
}
case 'voice': {
if (ctx.voice === undefined) {
break;
}
const adaptedContext: UrbanSyntheticEventVoice<UrbanBotTelegramType> = {
...common,
type: 'voice',
payload: {
duration: ctx.voice.duration,
mimeType: ctx.voice.mime_type,
},
};
this.processUpdate(adaptedContext);
break;
}
case 'video_note': {
if (ctx.video_note === undefined) {
break;
}
const adaptedContext: UrbanSyntheticEventVideoNote<UrbanBotTelegramType> = {
...common,
type: 'video_note',
payload: {
duration: ctx.video_note.duration,
length: ctx.video_note.length,
},
};
this.processUpdate(adaptedContext);
break;
}
}
};
handleCallbackQuery = (ctx: TelegramBot.CallbackQuery) => {
if (ctx.message?.chat !== undefined && ctx.data !== undefined) {
const adaptedContext: UrbanSyntheticEventAction<UrbanBotTelegramType> = {
type: 'action',
chat: {
id: String(ctx.message.chat.id),
type: ctx.message.chat.type,
title: ctx.message.chat.title,
username: ctx.message.chat.username,
firstName: ctx.message.chat.first_name,
lastName: ctx.message.chat.last_name,
description: ctx.message.chat.description,
inviteLink: ctx.message.chat.invite_link,
},
from: {
id: String(ctx.from?.id),
username: ctx.from?.username,
firstName: ctx.from?.first_name,
lastName: ctx.from?.last_name,
},
payload: {
actionId: ctx.data,
},
nativeEvent: {
type: UrbanBotTelegram.TYPE,
payload: ctx,
},
};
this.processUpdate(adaptedContext);
}
};
async sendMessage(message: UrbanMessage) {
await this.simulateTyping(message.chat.id, message.data.simulateTyping);
switch (message.nodeName) {
case 'urban-text': {
const params = formatParamsForNewMessage(message);
return this.client.sendMessage(message.chat.id, message.data.text, params);
}
case 'urban-img': {
const params = formatParamsForNewMessage(message);
return this.client.sendPhoto(message.chat.id, message.data.file, {
...params,
caption: message.data.title,
});
}
case 'urban-buttons': {
const params = formatParamsForNewMessage(message);
if (!message.data.title) {
throw new Error('@urban-bot/telegram Specify title prop to ButtonGroup');
}
return this.client.sendMessage(message.chat.id, message.data.title, params);
}
case 'urban-audio': {
const params = formatParamsForNewMessage(message);
return this.client.sendAudio(message.chat.id, message.data.file, {
...params,
caption: message.data.title,
duration: message.data.duration,
performer: message.data.author,
title: message.data.name,
});
}
case 'urban-video': {
const params = formatParamsForNewMessage(message);
return this.client.sendVideo(message.chat.id, message.data.file, {
...params,
caption: message.data.title,
duration: message.data.duration,
width: message.data.width,
height: message.data.height,
});
}
case 'urban-animation': {
const params = formatParamsForNewMessage(message);
return (
this.client
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore @types/node-telegram-bot-api bug. Doesn't have sendAnimation type
.sendAnimation(message.chat.id, message.data.file, {
...params,
file_name: message.data.name,
caption: message.data.title,
duration: message.data.duration,
width: message.data.width,
height: message.data.height,
})
);
}
case 'urban-file': {
const params = formatParamsForNewMessage(message);
return this.client.sendDocument(message.chat.id, message.data.file, {
...params,
caption: message.data.title,
});
}
case 'urban-location': {
const params = formatParamsForNewMessage(message);
return this.client.sendLocation(message.chat.id, message.data.latitude, message.data.longitude, {
...params,
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore @types/node-telegram-bot-api bug. live_period is existed
live_period: message.data.livePeriodSeconds,
});
}
case 'urban-media': {
const params = formatParamsForNewMessage(message);
const media = message.data.files.map((fileData) => {
const { type, file, title, ...other } = fileData;
const common = {
media: file,
parse_mode: message.data.parseMode,
caption: title,
...other,
} as const;
switch (type) {
case 'image': {
return {
type: 'photo',
...common,
} as const;
}
case 'video': {
return {
type: 'video',
...common,
} as const;
}
default: {
throw new Error(`urban-media type '${type}' doesn't support`);
}
}
});
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore @types/node-telegram-bot-api bug. File could be not only string
return this.client.sendMediaGroup(message.chat.id, media, params);
}
case 'urban-contact': {
const params = formatParamsForNewMessage(message);
return this.client.sendContact(
message.chat.id,
String(message.data.phoneNumber),
message.data.firstName ?? '',
{
...params,
last_name: message.data.lastName,
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore @types/node-telegram-bot-api bug. Doesn't have vcard type
vcard: message.data.vCard,
},
);
}
case 'urban-poll': {
const params = formatParamsForNewMessage(message);
const options = message.data.options.map(({ text }) => text);
return (
this.client
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore @types/node-telegram-bot-api bug. Doesn't have sendPoll type
.sendPoll(message.chat.id, message.data.question, options, {
...params,
is_anonymous: message.data.isAnonymous,
type: message.data.type,
allows_multiple_answers: message.data.withMultipleAnswers,
correct_option_id: message.data.rightOption,
explanation: message.data.explanation,
explanation_parse_mode: params.parse_mode,
open_period: message.data.livePeriodSeconds,
close_date: message.data.close_time,
})
);
}
default: {
throw new Error(
`Tag '${
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(message as any).nodeName
}' is not supported. Please don't use it with telegram bot or add this logic to @urban-bot/telegram.`,
);
}
}
}
updateMessage(message: UrbanExistingMessage<UrbanBotTelegramType>) {
if (message.data.isReplyButtons === true) {
throw new Error('Reply buttons can not edited. You could send a new message every time for this message.');
}
switch (message.nodeName) {
case 'urban-text': {
const metaToEdit = {
chat_id: message.meta.chat.id,
message_id: message.meta.message_id,
};
const params = formatParamsForExistingMessage(message);
this.client.editMessageText(message.data.text, { ...params, ...metaToEdit });
break;
}
case 'urban-img': {
this.editMedia(message);
break;
}
case 'urban-audio': {
this.editMedia(message);
break;
}
case 'urban-video': {
this.editMedia(message);
break;
}
case 'urban-animation': {
this.editMedia(message);
break;
}
case 'urban-file': {
this.editMedia(message);
break;
}
case 'urban-buttons': {
const metaToEdit = {
chat_id: message.meta.chat.id,
message_id: message.meta.message_id,
};
const params = formatParamsForExistingMessage(message);
this.client.editMessageText(message.data.title, { ...params, ...metaToEdit });
break;
}
case 'urban-location': {
const metaToEdit = {
chat_id: message.meta.chat.id,
message_id: message.meta.message_id,
};
const params = formatParamsForExistingMessage(message);
this.client.editMessageLiveLocation(message.data.latitude, message.data.longitude, {
...params,
...metaToEdit,
});
break;
}
default: {
throw new Error(
`Tag '${
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(message as any).nodeName
}' is not supported to update the message for @urban-bot/telegram. You could send a new message every time for this tag.`,
);
}
}
}
deleteMessage(message: UrbanExistingMessage<UrbanBotTelegramType>) {
this.client.deleteMessage(message.meta.chat.id, String(message.meta.message_id));
}
editMedia(
message: UrbanExistingMessageByType<
UrbanBotTelegramType,
'urban-img' | 'urban-audio' | 'urban-video' | 'urban-file' | 'urban-animation'
>,
) {
const metaToEdit = {
chat_id: message.meta.chat.id,
message_id: message.meta.message_id,
} as const;
const params = formatParamsForExistingMessage(message);
const media = getTelegramMedia(message, 'parse_mode' in params ? params.parse_mode : undefined);
if (typeof message.data.file !== 'string') {
try {
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
const fileData = this.client._formatSendData('file', message.data.file);
const { file } = fileData[0];
this.editMessageMedia({ ...media, media: `attach://file` }, { ...params, ...metaToEdit }, { file });
} catch (e) {
console.error('Something wrong with edit file message.');
console.error(e);
}
return;
}
this.editMessageMedia({ ...media, media: message.data.file }, { ...params, ...metaToEdit });
}
initializeCommands(commands: UrbanCommand[]) {
// FIXME this methods should be fixed in node-telegram-bot-api
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
return this.client._request('setMyCommands', {
form: {
commands: JSON.stringify(commands),
},
});
}
// FIXME this methods should be fixed in node-telegram-bot-api
editMessageMedia(
media: TelegramBot.InputMedia | InputMediaAudio | InputMediaAnimation | InputMediaFile,
options: EditMessageOptions,
formData?: unknown,
) {
const qs = { ...options, media: JSON.stringify(media) };
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
return this.client._request('editMessageMedia', { qs, formData });
}
simulateTyping(chatId: string, simulateTyping?: number) {
return new Promise<void>((resolve) => {
if (typeof simulateTyping === 'number') {
this.client.sendChatAction(chatId, 'typing').catch((e) => {
console.error('Error with simulate typing');
console.error(e);
resolve();
});
setTimeout(resolve, simulateTyping);
} else {
resolve();
}
});
}
} | the_stack |
import { extend, getValue, select } from '@syncfusion/ej2-base';
import { Grid } from '../../../src/grid/base/grid';
import { Filter } from '../../../src/grid/actions/filter';
import { Edit } from '../../../src/grid/actions/edit';
import { Group } from '../../../src/grid/actions/group';
import { Sort } from '../../../src/grid/actions/sort';
import { Reorder } from '../../../src/grid/actions/reorder';
import { Page } from '../../../src/grid/actions/page';
import { Toolbar } from '../../../src/grid/actions/toolbar';
import { Selection } from '../../../src/grid/actions/selection';
import { filterData, data } from '../base/datasource.spec';import { ColumnMenu} from '../../../src/grid/actions/column-menu';
import { ContextMenu } from '../../../src/grid/actions/context-menu';
import { ContextMenuOpenEventArgs } from '../../../src/grid/base/interface';
import { ColumnMenuOpenEventArgs } from '../../../src/grid/base/interface';
import { createGrid, destroy } from '../base/specutil.spec';
import '../../../node_modules/es6-promise/dist/es6-promise';
import {profile , inMB, getMemoryProfile} from '../base/common.spec';
Grid.Inject(Filter, Page, Selection, Group, Edit, Sort, Reorder, Toolbar, ColumnMenu, ContextMenu);
describe('Dialog Editing module', () => {
let dataSource: Function = (): Object[] => {
let data: Object[] = [];
for (let i = 0; i < filterData.length; i++) {
data.push(extend({}, {}, filterData[i], true));
}
return data;
};
let dialogData: Object[] = dataSource();
describe('Dialog editing render => ', () => {
let gridObj: Grid;
let actionBegin: () => void;
let actionComplete: () => void;
beforeAll((done: Function) => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
}
gridObj = createGrid(
{
dataSource: dialogData,
allowFiltering: true,
allowGrouping: true,
editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, mode: 'Dialog', showConfirmDialog: false, showDeleteConfirmDialog: false },
toolbar: ['Add', 'Edit', 'Delete', 'Update', 'Cancel'],
allowPaging: false,
columns: [
{ field: 'OrderID', type: 'number', isPrimaryKey: true, visible: true, validationRules: { required: true } },
{ field: 'CustomerID', type: 'string' },
{ field: 'EmployeeID', type: 'number', allowEditing: false },
{ field: 'Freight', format: 'C2', type: 'number', editType: 'numericedit' },
{ field: 'ShipCity' },
{ field: 'Verified', type: 'boolean', editType: 'booleanedit' },
{ field: 'ShipName', isIdentity: true },
{ field: 'ShipCountry', type: 'string', editType: 'dropdownedit' },
{ field: 'ShipRegion', type: 'string' },
{ field: 'ShipAddress', allowFiltering: true, visible: false },
{ field: 'OrderDate', format: { skeleton: 'yMd', type: 'date' }, type: 'date', editType: 'datepickeredit' }
],
actionBegin: actionBegin,
actionComplete: actionComplete
}, done);
});
it('Edit start', (done: Function) => {
actionComplete = (args?: any): void => {
if (args.requestType === 'beginEdit') {
expect(document.querySelectorAll('.e-editedrow').length).toBe(1);
expect(document.querySelectorAll('.e-gridform').length).toBe(1);
expect(document.querySelectorAll('form').length).toBe(1);
let cells = document.querySelector('.e-editedrow').querySelectorAll('.e-rowcell');
expect(cells.length).toBe(gridObj.getVisibleColumns().length);
//primary key check
expect(cells[0].querySelectorAll('input.e-disabled').length).toBe(1);
// allow Editing false
expect(cells[2].querySelectorAll('input.e-disabled').length).toBe(1);
// isIdentity check
expect(cells[6].querySelectorAll('input.e-disabled').length).toBe(1);
//focus check
expect(document.activeElement.id).toBe(gridObj.element.id + 'CustomerID');
//toolbar status check
expect(gridObj.element.querySelectorAll('.e-overlay').length).toBe(4);
expect(gridObj.isEdit).toBeTruthy();
done();
}
};
actionBegin = (args?: any): void => {
if (args.requestType === 'beginEdit') {
expect(gridObj.isEdit).toBeFalsy();
}
};
gridObj.actionComplete = actionComplete;
gridObj.actionBegin = actionBegin;
//toolbar status check
expect(gridObj.element.querySelectorAll('.e-overlay').length).toBe(3);
gridObj.clearSelection();
gridObj.selectRow(0, true);
(<any>gridObj.toolbarModule).toolbarClickHandler({ item: { id: gridObj.element.id + '_edit' } });
});
it('Edit complete', (done: Function) => {
actionComplete = (args?: any): void => {
if (args.requestType === 'save') {
//updatated data cehck
expect((gridObj.currentViewData[0] as any).CustomerID).toBe('updated');
//row count check
expect(gridObj.getContent().querySelectorAll('.e-row').length).toBe(71);
//record count check
expect(gridObj.currentViewData.length).toBe(71);
expect(gridObj.isEdit).toBeFalsy();
done();
}
};
actionBegin = (args?: any): void => {
if (args.requestType === 'save') {
expect(gridObj.isEdit).toBeTruthy();
}
};
gridObj.actionComplete = actionComplete;
gridObj.actionBegin = actionBegin;
(select('#' + gridObj.element.id + 'CustomerID', document) as any).value = 'updated';
(select('#'+gridObj.element.id+'_dialogEdit_wrapper', document).querySelectorAll('button') as any)[1].click();
});
it('Add start', (done: Function) => {
//last action check
expect(document.querySelectorAll('.e-gridform').length).toBe(0);
//form destroy check
expect(gridObj.editModule.formObj.isDestroyed).toBeTruthy();
expect(document.querySelectorAll('form').length).toBe(0);
actionComplete = (args?: any): void => {
if (args.requestType === 'add') {
expect(document.querySelectorAll('.e-insertedrow').length).toBe(1);
expect(document.querySelectorAll('.e-gridform').length).toBe(1);
expect(document.querySelectorAll('form').length).toBe(1);
let cells = document.querySelector('.e-insertedrow').querySelectorAll('.e-rowcell');
expect(cells.length).toBe(gridObj.getVisibleColumns().length);
//primary key check
expect(cells[0].querySelectorAll('input.e-disabled').length).toBe(0);
// allow Editing false
expect(cells[2].querySelectorAll('input.e-disabled').length).toBe(1);
// isIdentity check
expect(cells[6].querySelectorAll('input.e-disabled').length).toBe(1);
//focus check
expect(document.activeElement.id).toBe(gridObj.element.id + 'OrderID');
//toolbar status check
expect(gridObj.element.querySelectorAll('.e-overlay').length).toBe(4);
expect(gridObj.isEdit).toBeTruthy();
done();
}
};
actionBegin = (args?: any): void => {
if (args.requestType === 'add') {
expect(gridObj.isEdit).toBeFalsy();
}
};
gridObj.actionComplete = actionComplete;
gridObj.actionBegin = actionBegin;
//toolbar status check for last action
expect(gridObj.element.querySelectorAll('.e-overlay').length).toBe(3);
//edited class check for last action
expect(document.querySelectorAll('.e-editedrow').length).toBe(0);
gridObj.clearSelection();
gridObj.selectRow(0, true);
(<any>gridObj.toolbarModule).toolbarClickHandler({ item: { id: gridObj.element.id + '_add' } });
});
it('Add complete', (done: Function) => {
actionComplete = (args?: any): void => {
if (args.requestType === 'save') {
expect(document.querySelectorAll('.e-gridform').length).toBe(0);
expect(document.querySelectorAll('form').length).toBe(0);
//form destroy check
expect(gridObj.editModule.formObj.isDestroyed).toBeTruthy();
//updatated data cehck
expect((gridObj.currentViewData[0] as any).OrderID).toBe(10247);
expect((gridObj.currentViewData[0] as any).CustomerID).toBe('updated');
//row count check
expect(gridObj.getContent().querySelectorAll('.e-row').length).toBe(72);
//record count check
expect(gridObj.currentViewData.length).toBe(72);
expect(gridObj.isEdit).toBeFalsy();
done();
}
};
actionBegin = (args?: any): void => {
if (args.requestType === 'save') {
expect(gridObj.isEdit).toBeTruthy();
}
};
gridObj.actionComplete = actionComplete;
gridObj.actionBegin = actionBegin;
(select('#'+ gridObj.element.id +'OrderID', document) as any).value = 10247;
(select('#'+ gridObj.element.id +'CustomerID', document) as any).value = 'updated';
(select('#'+ gridObj.element.id +'_dialogEdit_wrapper', document).querySelectorAll('button') as any)[1].click();
});
it('Delete action', (done: Function) => {
actionComplete = (args?: any): void => {
if (args.requestType === 'delete') {
//row count check
expect(gridObj.getContent().querySelectorAll('.e-row').length).toBe(71);
//record count check
expect(gridObj.currentViewData.length).toBe(71);
//toolbar status check
expect(gridObj.element.querySelectorAll('.e-overlay').length).toBe(3);
expect(gridObj.isEdit).toBeFalsy();
done();
}
};
actionBegin = (args?: any): void => {
if (args.requestType === 'delete') {
expect(gridObj.isEdit).toBeFalsy();
}
};
gridObj.actionComplete = actionComplete;
gridObj.actionBegin = actionBegin;
//toolbar status check for last action
expect(gridObj.element.querySelectorAll('.e-overlay').length).toBe(3);
//added class check for last action
expect(document.querySelectorAll('.e-insertedrow').length).toBe(0);
gridObj.clearSelection();
gridObj.selectRow(0, true);
(<any>gridObj.toolbarModule).toolbarClickHandler({ item: { id: gridObj.element.id + '_delete' } });
});
it('Edit-cancel start', (done: Function) => {
actionComplete = (args?: any): void => {
if (args.requestType === 'beginEdit') {
expect(document.querySelectorAll('.e-editedrow').length).toBe(1);
expect(gridObj.isEdit).toBeTruthy();
done();
}
};
actionBegin = (args?: any): void => {
if (args.requestType === 'beginEdit') {
expect(gridObj.isEdit).toBeFalsy();
}
};
gridObj.actionComplete = actionComplete;
gridObj.actionBegin = actionBegin;
//toolbar status check
expect(gridObj.element.querySelectorAll('.e-overlay').length).toBe(3);
gridObj.clearSelection();
gridObj.selectRow(0, true);
(<any>gridObj.toolbarModule).toolbarClickHandler({ item: { id: gridObj.element.id + '_edit' } });
});
it('Edit-cancel complete', (done: Function) => {
actionComplete = (args?: any): void => {
if (args.requestType === 'cancel') {
//form destroy check
expect(gridObj.editModule.formObj.isDestroyed).toBeTruthy();
//updatated data cehck
expect((gridObj.currentViewData[0] as any).CustomerID).not.toBe('updatednew');
//row count check
expect(gridObj.getContent().querySelectorAll('.e-row').length).toBe(71);
//record count check
expect(gridObj.currentViewData.length).toBe(71);
expect(gridObj.isEdit).toBeFalsy();
done();
}
};
actionBegin = (args?: any): void => {
if (args.requestType === 'cancel') {
expect(gridObj.isEdit).toBeTruthy();
}
};
gridObj.actionComplete = actionComplete;
gridObj.actionBegin = actionBegin;
//toolbar status check
expect(gridObj.element.querySelectorAll('.e-overlay').length).toBe(4);
(select('#'+ gridObj.element.id +'CustomerID', document) as any).value = 'updatednew';
(select('#'+ gridObj.element.id +'_dialogEdit_wrapper', document).querySelectorAll('button') as any)[2].click();
});
it('Add-cancel start', (done: Function) => {
//last action check
expect(gridObj.element.querySelectorAll('.e-gridform').length).toBe(0);
expect(gridObj.element.querySelectorAll('form').length).toBe(0);
actionComplete = (args?: any): void => {
if (args.requestType === 'add') {
expect(document.querySelectorAll('.e-insertedrow').length).toBe(1);
expect(gridObj.isEdit).toBeTruthy();
done();
}
};
actionBegin = (args?: any): void => {
if (args.requestType === 'add') {
expect(gridObj.isEdit).toBeFalsy();
}
};
gridObj.actionComplete = actionComplete;
gridObj.actionBegin = actionBegin;
//toolbar status check
expect(gridObj.element.querySelectorAll('.e-overlay').length).toBe(3);
gridObj.clearSelection();
gridObj.selectRow(0, true);
(<any>gridObj.toolbarModule).toolbarClickHandler({ item: { id: gridObj.element.id + '_add' } });
});
it('Add-cancel complete', (done: Function) => {
actionComplete = (args?: any): void => {
if (args.requestType === 'cancel') {
//form destroy check
expect(gridObj.editModule.formObj.isDestroyed).toBeTruthy();
//updatated data cehck
expect((gridObj.currentViewData[0] as any).OrderID).not.toBe(10247);
expect((gridObj.currentViewData[0] as any).CustomerID).not.toBe('updatednew');
//row count check
expect(gridObj.getContent().querySelectorAll('.e-row').length).toBe(71);
//record count check
expect(gridObj.currentViewData.length).toBe(71);
expect(gridObj.isEdit).toBeFalsy();
done();
}
};
actionBegin = (args?: any): void => {
if (args.requestType === 'cancel') {
expect(gridObj.isEdit).toBeTruthy();
}
};
gridObj.actionComplete = actionComplete;
gridObj.actionBegin = actionBegin;
//toolbar status check
expect(gridObj.element.querySelectorAll('.e-overlay').length).toBe(4);
(select('#'+ gridObj.element.id +'OrderID', document) as any).value = 10247;
(select('#'+ gridObj.element.id +'CustomerID', document) as any).value = 'updatednew';
(select('#'+ gridObj.element.id +'_dialogEdit_wrapper', document).querySelectorAll('button') as any)[2].click();
});
it('toolbar status check', () => {
expect(document.querySelectorAll('.e-gridform').length).toBe(0);
expect(document.querySelectorAll('form').length).toBe(0);
expect(gridObj.element.querySelectorAll('.e-overlay').length).toBe(3);
});
it('dbl edit start', (done: Function) => {
actionComplete = (args?: any): void => {
if (args.requestType === 'beginEdit') {
expect(document.querySelectorAll('.e-editedrow').length).toBe(1);
expect(document.querySelectorAll('.e-gridform').length).toBe(1);
expect(gridObj.isEdit).toBeTruthy();
done();
}
};
gridObj.actionComplete = actionComplete;
gridObj.actionBegin = null;
(gridObj as any).dblClickHandler({ target: gridObj.element.querySelectorAll('.e-row')[1].firstElementChild });
});
it('click another row edit complete', (done: Function) => {
actionComplete = (args?: any): void => {
if (args.requestType === 'save') {
expect((gridObj.currentViewData[1] as any).CustomerID).toBe('updated');
//row count check
expect(gridObj.getContent().querySelectorAll('.e-row').length).toBe(71);
done();
}
};
gridObj.actionComplete = actionComplete;
(select('#' + gridObj.element.id + 'CustomerID', document) as any).value = 'updated';
(select('#'+ gridObj.element.id +'_dialogEdit_wrapper', document).querySelectorAll('button') as any)[1].click();
});
it('check row selection on dialog close by esc and close icon', (done: Function) => {
actionComplete = (args?: any): void => {
if (args.requestType === 'beginEdit') {
let td = (select('#' + gridObj.element.id + '_dialogEdit_wrapper', document).querySelectorAll('td.e-rowcell') as any)[0];
expect((td as HTMLElement).style.textAlign === 'left').toBe(true);
(select('#' + gridObj.element.id + '_dialogEdit_wrapper', document).querySelectorAll('.e-dlg-closeicon-btn') as any)[0].click();
}
if (args.requestType === 'cancel') {
expect(gridObj.getSelectedRecords().length).toBe(1);
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj as any).dblClickHandler({ target: gridObj.element.querySelectorAll('.e-row')[1].firstElementChild });
});
it('check row selection when edit dialog is open', (done: Function) => {
actionComplete = (args?: any): void => {
if (args.requestType === 'beginEdit') {
expect(gridObj.getSelectedRecords().length).toBe(1);
(select('#' + gridObj.element.id + '_dialogEdit_wrapper', document).querySelectorAll('.e-dlg-closeicon-btn') as any)[0].click();
done();
}
};
gridObj.actionComplete = actionComplete;
(gridObj as any).dblClickHandler({ target: gridObj.element.querySelectorAll('.e-row')[1].firstElementChild });
});
it('enableRtl alignment check', (done: Function) => {
actionComplete = (args?: any): void => {
if (args.requestType === 'beginEdit') {
let td = (select('#' + gridObj.element.id + '_dialogEdit_wrapper', document).querySelectorAll('td.e-rowcell') as any)[0];
expect((td as HTMLElement).style.textAlign === 'right').toBe(true);
done();
}
};
gridObj.enableRtl = true;
gridObj.dataBind();
gridObj.actionComplete = actionComplete;
(gridObj as any).dblClickHandler({ target: gridObj.element.querySelectorAll('.e-row')[1].firstElementChild });
});
afterAll((done) => {
gridObj.notify('tooltip-destroy', {});
destroy(gridObj);
setTimeout(function () {
done();
}, 1000);
gridObj = actionBegin = actionComplete = null;
});
});
describe('grid css class functionalities', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
allowSelection: true,
showColumnMenu: true,
allowGrouping: true,
selectionSettings: { type: 'Multiple' },
toolbar:['Add','Delete','Edit','ColumnChooser'],
editSettings:{allowEditing:true ,allowAdding:true,allowDeleting:true , mode:"Dialog"},
enableHover: false,
allowFiltering: true,
showColumnChooser: true,
filterSettings:{type:"Excel"},
contextMenuItems: ['AutoFit', 'AutoFitAll', 'SortAscending', 'SortDescending',
'Copy', 'Edit', 'Delete', 'Save', 'Cancel',
'PdfExport', 'ExcelExport', 'CsvExport', 'FirstPage', 'PrevPage',
'LastPage', 'NextPage'],
columns: [
{
field: 'OrderID', isPrimaryKey: true, headerText: 'Order ID', textAlign: 'Right', width: 120, defaultValue: ''
},
{
field: 'CustomerID', headerText: 'Customer ID', width: 140, defaultValue: ''
},
{
field: 'Freight', headerText: 'Freight', textAlign: 'Right',
width: 120, format: 'C2'
},
{
field: 'OrderDate', headerText: 'Order Date',
format: 'yMd', width: 170
},
{
field: 'ShipCountry', headerText: 'Ship Country', width: 150
}],
}, done);
gridObj.element.classList.add('e-bigger');
});
it('context menu CSS class Test', (done: Function) => {
gridObj.contextMenuOpen = function (args: ContextMenuOpenEventArgs) {
done();
}
let eventArgs = { target: gridObj.getHeaderTable().querySelector('th') };
let e = {
event: eventArgs,
items: gridObj.contextMenuModule.contextMenu.items,
parentItem: document.querySelector('tr.edoas')
};
(gridObj.contextMenuModule as any).contextMenuBeforeOpen(e);
expect((gridObj.contextMenuModule as any).element.parentElement.classList.contains('e-bigger')).toBeTruthy();
(gridObj.contextMenuModule as any).contextMenu.close();
});
it('dialog-css class Test', () => {
(gridObj as any).dblClickHandler({ target: gridObj.element.querySelectorAll('.e-row')[1].firstElementChild });
expect(document.getElementById(gridObj.element.id +'_dialogEdit_wrapper').parentElement.classList.contains('e-bigger')).toBeTruthy();
gridObj.editModule.closeEdit();
});
it('column menu open', (done: Function) => {
gridObj.columnMenuOpen = function(args: ColumnMenuOpenEventArgs){
done();
}
gridObj.dataBind();
(gridObj.getHeaderContent().querySelector('.e-columnmenu') as HTMLBRElement).click();
expect((gridObj.columnMenuModule as any).element.parentElement.classList.contains('e-bigger')).toBeTruthy();
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
describe('Dialog editing render => ', () => {
let gridObj: Grid;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: dialogData,
editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true,
mode: 'Dialog', dialog: { params : {height: '500px', width: '400px'} }},
toolbar: ['Add', 'Edit', 'Delete', 'Update', 'Cancel'],
columns: [
{ field: 'OrderID', type: 'number', isPrimaryKey: true, visible: true, validationRules: { required: true } },
{ field: 'CustomerID', type: 'string' },
{ field: 'EmployeeID', type: 'number', allowEditing: false },
{ field: 'Freight', format: 'C2', type: 'number', editType: 'numericedit' }
]
}, done);
});
it('DialogEdit start', () => {
(gridObj as any).dblClickHandler({ target: gridObj.element.querySelectorAll('.e-row')[1].firstElementChild });
});
it('Check the dialog height', () => {
expect((document.querySelectorAll('.e-popup-open')[0] as any).style.height).toBe('500px');
expect((document.querySelectorAll('.e-popup-open')[0] as any).style.width).toBe('400px');
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
});
afterAll((done) => {
destroy(gridObj);
setTimeout(function () {
done();
}, 1000);
gridObj = dialogData = dataSource = null;
});
});
describe('EJ2-47615 - Throws script error while updating the data in Dialog editing => ', () => {
let gridObj: Grid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
allowSelection: false,
editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, mode: 'Dialog'},
toolbar: ['Add', 'Edit', 'Delete', 'Update', 'Cancel'],
columns: [
{ field: 'OrderID', type: 'number', isPrimaryKey: true, visible: true },
{ field: 'CustomerID', type: 'string' },
{ field: 'EmployeeID', type: 'number' },
{ field: 'Freight', format: 'C2', type: 'number', editType: 'numericedit' }
]
}, done);
});
it('open dialog', () => {
(gridObj as any).dblClickHandler({ target: gridObj.element.querySelectorAll('.e-row')[1].firstElementChild });
});
it('save the data', (done: Function) => {
actionComplete = (args?: any): void => {
if (args.requestType === 'save') {
done();
}
};
gridObj.actionComplete = actionComplete;
(select('#'+ gridObj.element.id +'_dialogEdit_wrapper', document).querySelectorAll('button') as any)[1].click();
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
describe('EJ2-50266 - Validation rules for grouped field columns are not working => ', () => {
let gridObj: Grid;
let actionComplete: () => void;
beforeAll((done: Function) => {
gridObj = createGrid(
{
dataSource: data,
editSettings: { allowEditing: true, allowAdding: true, allowDeleting: true, mode: 'Dialog' },
allowGrouping: true,
groupSettings: { columns: ['CustomerID'] },
allowPaging: true,
pageSettings: { pageCount: 5 },
toolbar: ['Add', 'Edit', 'Delete'],
columns: [
{ field: 'OrderID', isPrimaryKey: true, headerText: 'Order ID', textAlign: 'Right', width: 120 },
{ field: 'CustomerID', headerText: 'Customer ID', width: 140, validationRules: { required: true } },
{ field: 'Freight', headerText: 'Freight', textAlign: 'Right', editType: 'numericedit', width: 120, format: 'C2' },
{ field: 'OrderDate', headerText: 'Order Date', editType: 'datepickeredit', format: 'yMd', width: 170 },
{ field: 'ShipCountry', headerText: 'Ship Country', editType: 'dropdownedit', width: 150,
edit: { params: { popupHeight: '300px' } } }
]
}, done);
});
it('Add Record', (done: Function) => {
actionComplete = (args?: any): void => {
if (args.requestType === 'add') {
done();
}
};
gridObj.actionComplete = actionComplete;
(<any>gridObj.toolbarModule).toolbarClickHandler({ item: { id: gridObj.element.id + '_add' } });
});
it('Check the validation message', () => {
(select('#'+ gridObj.element.id +'_dialogEdit_wrapper', document).querySelectorAll('button') as any)[1].click();
expect(document.querySelectorAll('.e-griderror').length).toBe(1);
});
afterAll(() => {
destroy(gridObj);
gridObj = null;
});
});
}); | the_stack |
import {
_SharePointQueryableInstance,
ISharePointQueryable,
spInvokableFactory,
} from "../sharepointqueryable.js";
import { defaultPath } from "../decorators.js";
import { hOP, IFetchOptions } from "@pnp/common";
import { metadata } from "../utils/metadata.js";
import { body, IQueryable } from "@pnp/odata";
import { spPost } from "../operations.js";
import { tag } from "../telemetry.js";
@defaultPath("_api/social.following")
export class _Social extends _SharePointQueryableInstance implements ISocial {
public get my(): IMySocial {
return MySocial(this);
}
@tag("soc.getFollowedSitesUri")
public async getFollowedSitesUri(): Promise<string> {
const r = await this.clone(SocialCloneFactory, "FollowedSitesUri").get();
return r.FollowedSitesUri || r;
}
@tag("soc.getFollowedDocumentsUri")
public async getFollowedDocumentsUri(): Promise<string> {
const r = await this.clone(SocialCloneFactory, "FollowedDocumentsUri").get();
return r.FollowedDocumentsUri || r;
}
@tag("soc.follow")
public async follow(actorInfo: ISocialActorInfo): Promise<SocialFollowResult> {
return await spPost(this.clone(SocialCloneFactory, "follow"), this.createSocialActorInfoRequestBody(actorInfo));
}
@tag("soc.isFollowed")
public async isFollowed(actorInfo: ISocialActorInfo): Promise<boolean> {
return await spPost(this.clone(SocialCloneFactory, "isfollowed"), this.createSocialActorInfoRequestBody(actorInfo));
}
@tag("soc.stopFollowing")
public async stopFollowing(actorInfo: ISocialActorInfo): Promise<void> {
return await spPost(this.clone(SocialCloneFactory, "stopfollowing"), this.createSocialActorInfoRequestBody(actorInfo));
}
private createSocialActorInfoRequestBody(actorInfo: ISocialActorInfo): IFetchOptions {
return body({
"actor":
Object.assign(metadata("SP.Social.SocialActorInfo"), {
Id: null,
}, actorInfo),
});
}
}
/**
* Describes the public methods for the Social interface
*/
export interface ISocial {
/**
* Access to the curren't user's social data
*/
readonly my: IMySocial;
/**
* Get a list of followed sites for the current user.
*/
getFollowedSitesUri(): Promise<string>;
/**
* Get a list of followed documents for the current user.
*/
getFollowedDocumentsUri(): Promise<string>;
/**
* Follow an actor for the current user.
*
* @param actorInfo Provide the actor to follow.
*/
follow(actorInfo: ISocialActorInfo): Promise<SocialFollowResult>;
/**
* Check if the current user is following the actor.
*
* @param actorInfo Provide the actor to check.
*/
isFollowed(actorInfo: ISocialActorInfo): Promise<boolean>;
/**
* Stop following an actor for the current user.
*
* @param actorInfo Provide the actor to stop following.
*/
stopFollowing(actorInfo: ISocialActorInfo): Promise<void>;
}
/**
* Get a new Social instance for the particular Url
*/
export const Social = (baseUrl: string | ISharePointQueryable): ISocial & Pick<IQueryable<any>, "configure" | "setRuntime" | "getRuntime"> => new _Social(baseUrl);
const SocialCloneFactory = (baseUrl: string | ISharePointQueryable, paths?: string): ISocial & ISharePointQueryable => new _Social(baseUrl, paths);
/**
* Current user's Social instance
*/
@defaultPath("my")
export class _MySocial extends _SharePointQueryableInstance implements IMySocial {
@tag("msoc.followed")
public async followed(types: SocialActorTypes): Promise<ISocialActor[]> {
const r = await this.clone(MySocialCloneFactory, `followed(types=${types})`)();
return hOP(r, "Followed") ? r.Followed.results : r;
}
@tag("msoc.followedCount")
public async followedCount(types: SocialActorTypes): Promise<number> {
const r = await this.clone(MySocialCloneFactory, `followedcount(types=${types})`)();
return r.FollowedCount || r;
}
@tag("msoc.followers")
public async followers(): Promise<ISocialActor[]> {
const r = await this.clone(MySocialCloneFactory, "followers")();
return hOP(r, "Followers") ? r.Followers.results : r;
}
@tag("msoc.suggestions")
public async suggestions(): Promise<ISocialActor[]> {
const r = await this.clone(MySocialCloneFactory, "suggestions")();
return hOP(r, "Suggestions") ? r.Suggestions.results : r;
}
}
/**
* Defines the public methods exposed by the my endpoint
*/
export interface IMySocial {
/**
* Allow access to the v2 invokable
*/
(this: IMySocial): Promise<IMySocialData>;
/**
* Gets this user's data
*/
get(): Promise<IMySocialData>;
/**
* Gets users, documents, sites, and tags that the current user is following.
*
* @param types Bitwise set of SocialActorTypes to retrieve
*/
followed(types: SocialActorTypes): Promise<ISocialActor[]>;
/**
* Gets the count of users, documents, sites, and tags that the current user is following.
*
* @param types Bitwise set of SocialActorTypes to retrieve
*/
followedCount(types: SocialActorTypes): Promise<number>;
/**
* Gets the users who are following the current user.
*/
followers(): Promise<ISocialActor[]>;
/**
* Gets users who the current user might want to follow.
*/
suggestions(): Promise<ISocialActor[]>;
}
/**
* Invokable factory for IMySocial instances
*/
export const MySocial = spInvokableFactory<IMySocial>(_MySocial);
const MySocialCloneFactory = (baseUrl: string | ISharePointQueryable, path?: string): IMySocial & ISharePointQueryable => <any>MySocial(baseUrl, path);
/**
* Social actor info
*
*/
export interface ISocialActorInfo {
AccountName?: string;
ActorType: SocialActorType;
ContentUri?: string;
Id?: string;
TagGuid?: string;
}
/**
* Social actor type
*
*/
export const enum SocialActorType {
User,
Document,
Site,
Tag,
}
/**
* Social actor type
*
*/
/* eslint-disable no-bitwise */
export const enum SocialActorTypes {
None = 0,
User = 1 << SocialActorType.User,
Document = 1 << SocialActorType.Document,
Site = 1 << SocialActorType.Site,
Tag = 1 << SocialActorType.Tag,
/**
* The set excludes documents and sites that do not have feeds.
*/
ExcludeContentWithoutFeeds = 268435456,
/**
* The set includes group sites
*/
IncludeGroupsSites = 536870912,
/**
* The set includes only items created within the last 24 hours
*/
WithinLast24Hours = 1073741824,
}
/* eslint-enable no-bitwise */
/**
* Result from following
*
*/
export const enum SocialFollowResult {
Ok = 0,
AlreadyFollowing = 1,
LimitReached = 2,
InternalError = 3,
}
/**
* Specifies an exception or status code.
*/
export const enum SocialStatusCode {
/**
* The operation completed successfully
*/
OK,
/**
* The request is invalid.
*/
InvalidRequest,
/**
* The current user is not authorized to perform the operation.
*/
AccessDenied,
/**
* The target of the operation was not found.
*/
ItemNotFound,
/**
* The operation is invalid for the target's current state.
*/
InvalidOperation,
/**
* The operation completed without modifying the target.
*/
ItemNotModified,
/**
* The operation failed because an internal error occurred.
*/
InternalError,
/**
* The operation failed because the server could not access the distributed cache.
*/
CacheReadError,
/**
* The operation succeeded but the server could not update the distributed cache.
*/
CacheUpdateError,
/**
* No personal site exists for the current user, and no further information is available.
*/
PersonalSiteNotFound,
/**
* No personal site exists for the current user, and a previous attempt to create one failed.
*/
FailedToCreatePersonalSite,
/**
* No personal site exists for the current user, and a previous attempt to create one was not authorized.
*/
NotAuthorizedToCreatePersonalSite,
/**
* No personal site exists for the current user, and no attempt should be made to create one.
*/
CannotCreatePersonalSite,
/**
* The operation was rejected because an internal limit had been reached.
*/
LimitReached,
/**
* The operation failed because an error occurred during the processing of the specified attachment.
*/
AttachmentError,
/**
* The operation succeeded with recoverable errors; the returned data is incomplete.
*/
PartialData,
/**
* A required SharePoint feature is not enabled.
*/
FeatureDisabled,
/**
* The site's storage quota has been exceeded.
*/
StorageQuotaExceeded,
/**
* The operation failed because the server could not access the database.
*/
DatabaseError,
}
export interface ISocialActor {
/**
* Gets the actor type.
*/
ActorType: SocialActorType;
/**
* Gets the actor's unique identifier.
*/
Id: string;
/**
* Gets the actor's canonical URI.
*/
Uri: string;
/**
* Gets the actor's display name.
*/
Name: string;
/**
* Returns true if the current user is following the actor, false otherwise.
*/
IsFollowed: boolean;
/**
* Gets a code that indicates recoverable errors that occurred during actor retrieval
*/
Status: SocialStatusCode;
/**
* Returns true if the Actor can potentially be followed, false otherwise.
*/
CanFollow: boolean;
/**
* Gets the actor's image URI. Only valid when ActorType is User, Document, or Site
*/
ImageUri: string;
/**
* Gets the actor's account name. Only valid when ActorType is User
*/
AccountName: string;
/**
* Gets the actor's email address. Only valid when ActorType is User
*/
EmailAddress: string;
/**
* Gets the actor's title. Only valid when ActorType is User
*/
Title: string;
/**
* Gets the text of the actor's most recent post. Only valid when ActorType is User
*/
StatusText: string;
/**
* Gets the URI of the actor's personal site. Only valid when ActorType is User
*/
PersonalSiteUri: string;
/**
* Gets the URI of the actor's followed content folder. Only valid when this represents the current user
*/
FollowedContentUri: string;
/**
* Gets the actor's content URI. Only valid when ActorType is Document, or Site
*/
ContentUri: string;
/**
* Gets the actor's library URI. Only valid when ActorType is Document
*/
LibraryUri: string;
/**
* Gets the actor's tag GUID. Only valid when ActorType is Tag
*/
TagGuid: string;
}
/**
* Defines the properties returned from the my endpoint
*/
export interface IMySocialData {
SocialActor: ISocialActor;
MyFollowedDocumentsUri: string;
MyFollowedSitesUri: string;
} | the_stack |
namespace $ {
export type $mol_style_properties = Partial< $mol_type_override< CSSStyleDeclaration , Overrides > >
type Common = 'inherit' | 'initial' | 'unset'
type Color =
| 'aliceblue' | 'antiquewhite' | 'aqua' | 'aquamarine' | 'azure'
| 'beige' | 'bisque' | 'black' | 'blanchedalmond' | 'blue' | 'blueviolet'| 'brown' | 'burlywood'
| 'cadetblue' | 'chartreuse' | 'chocolate' | 'coral' | 'cornflowerblue' | 'cornsilk' | 'crimson' | 'cyan'
| 'darkblue' | 'darkcyan' | 'darkgoldenrod' | 'darkgray' | 'darkgreen' | 'darkgrey'
| 'darkkhaki' | 'darkmagenta' | 'darkolivegreen' | 'darkorange' | 'darkorchid' | 'darkred'
| 'darksalmon' | 'darkseagreen' | 'darkslateblue' | 'darkslategrey' | 'darkturquoise' | 'darkviolet'
| 'deeppink' | 'deepskyblue' | 'dimgray' | 'dimgrey' | 'dodgerblue'
| 'firebrick' | 'floralwhite' | 'forestgreen' | 'fuchsia'
| 'gainsboro' | 'ghostwhite' | 'gold' | 'goldenrod' | 'gray' | 'green' | 'greenyellow' | 'grey'
| 'honeydew' | 'hotpink' | 'indianred' | 'indigo' | 'ivory' | 'khaki'
| 'lavender' | 'lavenderblush' | 'lawngreen' | 'lemonchiffon'
| 'lightblue' | 'lightcoral' | 'lightcyan' | 'lightgoldenrodyellow' | 'lightgray'
| 'lightgreen' | 'lightgrey' | 'lightpink' | 'lightsalmon' | 'lightseagreen'
| 'lightskyblue' | 'lightslategray' | 'lightslategrey' | 'lightsteelblue' | 'lightyellow'
| 'lime' | 'limegreen' | 'linen' | 'magenta' | 'maroon'
| 'mediumaquamarine' | 'mediumblue' | 'mediumorchid' | 'mediumpurple' | 'mediumseagreen'
| 'mediumslateblue' | 'mediumspringgreen' | 'mediumturquoise' | 'mediumvioletred'
| 'midnightblue' | 'mintcream' | 'mistyrose' | 'moccasin'
| 'navajowhite' | 'navy'
| 'oldlace' | 'olive' | 'olivedrab' | 'orange' | 'orangered' | 'orchid'
| 'palegoldenrod' | 'palegreen' | 'paleturquoise' | 'palevioletred' | 'papayawhip'
| 'peachpuff' | 'peru' | 'pink' | 'plum' | 'powderblue' | 'purple'
| 'rebeccapurple' | 'red' | 'rosybrown' | 'royalblue'
| 'saddlebrown' | 'salmon' | 'sandybrown' | 'seagreen' | 'seashell' | 'sienna' | 'silver'
| 'skyblue' | 'slateblue' | 'slategray' | 'slategrey' | 'snow' | 'springgreen' | 'steelblue'
| 'tan' | 'teal' | 'thistle' | 'tomato' | 'turquoise'
| 'violet' | 'wheat' | 'white' | 'whitesmoke' | 'yellow' | 'yellowgreen'
| 'transparent' | 'currentcolor'
| $mol_style_func< 'hsla' | 'rgba' | 'var' >
| `#${string}`
type Length = 0 | $mol_style_unit< $mol_style_unit_length > | $mol_style_func< 'calc' | 'var' >
type Size =
| 'auto' | 'max-content' | 'min-content' | 'fit-content'
| Length | Common
type Directions< Value > =
| Value
| readonly [ Value , Value ]
| {
top?: Value ,
right?: Value ,
bottom?: Value ,
left?: Value ,
}
type Span_align = 'none' | 'start' | 'end' | 'center'
type Snap_axis = 'x' | 'y' | 'block' | 'inline' | 'both'
type Overflow = 'visible' | 'hidden' | 'clip' | 'scroll' | 'auto' | 'overlay' | Common
type ContainRule = 'size' | 'layout' | 'style' | 'paint'
type Repeat = 'repeat-x' | 'repeat-y' | 'repeat' | 'space' | 'round' | 'no-repeat'
type BG_size = Length | 'auto' | 'contain' | 'cover'
interface Overrides {
/** Distribution of space between and around content items along a flexbox's cross-axis or a grid's block axis. */
alignContent? :
| 'baseline' | 'start' | 'end' | 'flex-start' | 'flex-end'
| 'center' | 'normal' | 'space-between' | 'space-around' | 'space-evenly' | 'stretch'
| readonly [ 'first' | 'last' , 'baseline' ]
| readonly [ 'safe' | 'unsafe' , 'start' | 'end' | 'flex-start' | 'flex-end' ]
| Common
/** How the browser distributes space between and around content items along the main-axis of a flex container, and the inline axis of a grid container. */
justifyContent?:
| 'start' | 'end'
| 'flex-start' | 'flex-end'
| 'left' | 'right'
| 'space-between' | 'space-around' | 'space-evenly'
| 'normal' | 'stretch' | 'center'
| Common
/** All background style properties. */
background?:
| 'none'
| {
/** Background color. */
color?: Color | Common
/** Background images. */
image?:
| readonly( readonly [ $mol_style_func<'url'> ] )[]
| 'none' | Common
/** How background images are repeated. */
repeat?: Repeat | [ Repeat, Repeat ] | Common
// @TODO add more variants
position?: 'left' | 'right' | 'top' | 'bottom' | 'center'
size?: ( BG_size | [ BG_size, BG_size ] )[]
}
box?: {
/** Shadow effects around an element's frame. */
shadow?:
| readonly {
inset?: boolean
x: Length
y: Length
blur: Length
spread: Length
color: Color
}[]
| 'none' | Common
}
font?: {
/** Whether a font should be styled. */
style?: 'normal' | 'italic' | Common
/** Weight (or boldness) of the font. */
weight?:
| 'normal' | 'bold' | 'lighter' | 'bolder'
| 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900
| Common
/** Size of the font. Changing the font size also updates the sizes of the font size-relative length units. */
size?:
| 'xx-small' | 'x-small' | 'small' | 'medium'
| 'large' | 'x-large' | 'xx-large' | 'xxx-large'
| 'smaller' | 'larger'
| Length
| Common
/** Prioritized list of one or more font family names and/or generic family names. */
family?:
| 'serif' | 'sans-serif' | 'monospace'
| 'cursive' | 'fantasy'
| 'system-ui' | 'ui-serif' | 'ui-sans-serif' | 'ui-monospace' | 'ui-rounded'
| 'emoji' | 'math' | 'fangsong'
| Common
}
/** Foreground color value of text and text decorations, and sets the `currentcolor` value. */
color?: Color | Common
/** Whether an element is treated as a block or inline element and the layout used for its children, such as flow layout, grid or flex. */
display?:
| 'block' | 'inline' | 'run-in' | 'list-item' | 'none'
| 'flow' | 'flow-root' | 'table' | 'flex' | 'grid'
| 'contents'
| 'table-row-group' | 'table-header-group' | 'table-footer-group' | 'table-column-group'
| 'table-row' | 'table-cell' | 'table-column' | 'table-caption'
| 'inline-block' | 'inline-table' | 'inline-flex' | 'inline-grid'
| 'ruby' | 'ruby-base' | 'ruby-text' | 'ruby-base-container' | 'ruby-text-container'
| Common
/** What to do when an element's content is too big to fit in its block formatting context. It is a shorthand for `overflowX` and `overflowY`. */
overflow?: Overflow | {
/** What shows when content overflows a block-level element's left and right edges. */
x?: Overflow | Common
/** What shows when content overflows a block-level element's top and bottom edges. */
y?: Overflow | Common
/** A way to opt out of the browser's scroll anchoring behavior, which adjusts scroll position to minimize content shifts. */
anchor?: 'auto' | 'none' | Common
}
/** Indicate that an element and its contents are, as much as possible, independent of the rest of the document tree. This allows the browser to recalculate layout, style, paint, size, or any combination of them for a limited area of the DOM and not the entire page, leading to obvious performance benefits. */
contain?:
| 'none' | 'strict' | 'content'
| ContainRule | readonly ContainRule[]
| Common
/** How white space inside an element is handled. */
whiteSpace?:
| 'normal' | 'nowrap' | 'break-spaces'
| 'pre' | 'pre-wrap' | 'pre-line'
| Common
webkitOverflowScrolling?: 'auto' | 'touch'
scrollbar?: {
color?: readonly [ Color , Color ] | 'dark' | 'light' | 'auto' | Common
}
scroll?: {
snap?: {
/** How strictly snap points are enforced on the scroll container in case there is one. */
type:
| 'none'
| Snap_axis
| readonly [ Snap_axis , 'mandatory' | 'proximity' ]
| Common
/** Whether the scroll container is allowed to "pass over" possible snap positions. */
stop: 'normal' | 'always' | Common
/** The box’s snap position as an alignment of its snap area (as the alignment subject) within its snap container’s snapport (as the alignment container). The two values specify the snapping alignment in the block axis and inline axis, respectively. If only one value is specified, the second value defaults to the same value. */
align: Span_align | readonly [ Span_align , Span_align ] | Common
}
}
/** Element's width. By default, it sets the width of the content area, but if `boxSizing` is set to `border-box`, it sets the width of the border area. */
width?: Size
/** Minimum width of an element. It prevents the used value of the `width` property from becoming smaller than the value specified for `minWidth`. */
minWidth?: Size
/** Maximum width of an element. It prevents the used value of the `width` property from becoming larger than the value specified for `maxWidth`. */
maxWidth?: Size
/** Height of an element. By default, the property defines the height of the content area. If box-sizing is set to border-box, however, it instead determines the height of the border area. */
height?: Size
/** Minimum height of an element. It prevents the used value of the `height` property from becoming smaller than the value specified for `minHeight`. */
minHeight?: Size
/** Maximum height of an element. It prevents the used value of the `height` property from becoming larger than the value specified for `maxHeight`. */
maxHeight?: Size
/** Margin area on all four sides of an element. */
margin?: Directions< Length | 'auto' >
/** Padding area on all four sides of an element. */
padding?: Directions< Length | 'auto' >
/** How an element is positioned in a document. The `top`, `right`, `bottom`, and `left` properties determine the final location of positioned elements. */
position?: 'static' | 'relative' | 'absolute' | 'sticky' | 'fixed'
top?: Length | 'auto' | Common
right?: Length | 'auto' | Common
bottom?: Length | 'auto' | Common
left?: Length | 'auto' | Common
border?: {
/** Rounds the corners of an element's outer border edge. You can set a single radius to make circular corners, or two radii to make elliptical corners. */
radius?: Length | [ Length, Length ]
/** Line style for all four sides of an element's border. */
style?:
| 'none' | 'hidden'
| 'dotted' | 'dashed'
| 'solid' | 'double'
| 'groove' | 'ridge'
| 'inset' | 'outset'
| Common
/** Color of element's border. */
color?: Directions< Color > | Common
/** Width of element's border. */
width?: Directions< Length > | Common
}
/** How a flex item will grow or shrink to fit the space available in its flex container. It is a shorthand for `flexGrow`, `flexShrink`, and `flexBasis`. */
flex?:
| 'none' | 'auto'
| {
/** Growing weight of the flex item. Negative values are considered invalid. Defaults to 1 when omitted. */
grow?: number | Common
/** Shrinking weight of the flex item. Negative values are considered invalid. Defaults to 1 when omitted. */
shrink?: number | Common
/** Preferred size of the flex item. A value of 0 must have a unit to avoid being interpreted as a flexibility. Defaults to 0 when omitted. */
basis?: Size
/** How flex items are placed in the flex container defining the main axis and the direction (normal or reversed). */
direction?: 'row' | 'row-reverse' | 'column' | 'column-reverse'
/** Whether flex items are forced onto one line or can wrap onto multiple lines. If wrapping is allowed, it sets the direction that lines are stacked. */
wrap?: 'wrap' | 'nowrap' | 'wrap-reverse' | Common
}
/** Z-order of a positioned element and its descendants or flex items. Overlapping elements with a larger z-index cover those with a smaller one. */
zIndex: number
/** Degree to which content behind an element is hidden, and is the opposite of transparency. */
opacity: number
}
} | the_stack |
import * as winston from 'winston'
import * as fs from 'fs'
import * as process from 'process'
import * as Ajv from 'ajv'
import { getDriverClass, logger } from './utils'
import { DriverModel, DriverConstructor } from './driverModel'
import { AZ_CONFIG_TYPE } from './drivers/AzDriver'
import { DISK_CONFIG_TYPE } from './drivers/diskDriver'
import { GC_CONFIG_TYPE } from './drivers/GcDriver'
import { S3_CONFIG_TYPE } from './drivers/S3Driver'
export type DriverName = 'aws' | 'azure' | 'disk' | 'google-cloud'
export type LogLevel = 'error' | 'warn' | 'info' | 'verbose' | 'debug'
export const enum HttpsOption {
cert_files = 'cert_files',
acme = 'acme'
}
export interface LoggingConfigInterface {
timestamp?: boolean;
colorize?: boolean;
json?: boolean;
level?: LogLevel;
handleExceptions?: boolean;
}
// LoggingConfig defaults
class LoggingConfig implements LoggingConfigInterface {
/**
* @default warn
*/
level? = 'warn' as LogLevel;
handleExceptions? = true;
timestamp? = true;
colorize? = true;
json? = false;
}
export interface ProofCheckerConfigInterface {
proofsRequired?: number;
}
// ProofCheckerConfig defaults
class ProofCheckerConfig implements ProofCheckerConfigInterface {
/**
* @TJS-type integer
*/
proofsRequired? = 0;
}
export interface AcmeConfigInterface {
/**
* The email address of the ACME user / hosting provider.
*/
email: string;
/**
* Accept Let's Encrypt(TM) v2 Agreement. You must accept the ToS as the host which handles the certs.
* See the subscriber agreement at https://letsencrypt.org/repository/
*/
agreeTos: boolean;
/**
* Writable directory where certs will be saved.
* @default "~/.config/acme/"
*/
configDir?: string;
/**
* Join the Greenlock community to get notified of important updates.
* @default false
*/
communityMember?: boolean;
/**
* Important and mandatory notices from Greenlock, related to security or breaking API changes.
* @default true
*/
securityUpdates: boolean;
/**
* Contribute telemetry data to the project.
* @default false
*/
telemetry?: boolean;
/**
* The default servername to use when the client doesn't specify.
* Example: "example.com"
*/
servername?: string;
/**
* Array of allowed domains such as `[ "example.com", "www.example.com" ]`
*/
approveDomains?: string[];
/**
* @default "https://acme-v02.api.letsencrypt.org/directory"
*/
server?: string;
/**
* The ACME version to use. `v02`/`draft-12` is for Let's Encrypt v2 otherwise known as ACME draft 12.
* @default "v02"
*/
version?: string;
/**
* @default false
*/
debug?: boolean;
}
export interface TlsPemCert {
/**
* Either the path to the PEM formatted private key file, or the string content of the file.
* The file usually has the extension `.key` or `.pem`.
* If the content string is specified, it should include the escaped EOL characters, e.g.
* `"-----BEGIN RSA PRIVATE KEY-----\n{lines of base64 data}\n-----END RSA PRIVATE KEY-----"`.
*/
keyFile: string;
/**
* Either the path to the PEM formatted certification chain file, or the string content of the file.
* The file usually has the extension `.cert`, `.cer`, `.crt`, or `.pem`.
* If the content string is specified, it should include the escaped EOL characters, e.g.
* `"-----BEGIN CERTIFICATE-----\n{lines of base64 data}\n-----END CERTIFICATE-----"`.
*/
certFile: string;
/**
* The string passphrase for the key file. If provided, the passphrase is used to decrypt the file.
* If not provided, the key is assumed to be unencrypted.
*/
keyPassphrase?: string;
}
export interface TlsPfxCert {
/**
* Either the path to the PFX or PKCS12 encoded private key and certificate chain file,
* or the base64 encoded content of the file.
* The file usually has the extension `.pfx` or `.p12`.
*/
pfxFile: string;
/**
* The string passphrase for the key file. If provided, the passphrase is used to decrypt the file.
* If not provided, the key is assumed to be unencrypted.
*/
pfxPassphrase?: string;
}
export type TlsCertConfigInterface = TlsPemCert | TlsPfxCert | undefined;
type SubType<T, K extends keyof T> = K extends keyof T ? T[K] : never;
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface HubConfigInterface extends HubConfig { }
// This class is responsible for:
// A) Specifying default config values.
// B) Used for generating the config-schema.json file.
// The undefined values are explicitly specified so the schema generator
// will pick them up.
// Having the config params and their default values specified here is useful
// for providing a single-source-of-truth for both the schema and the actual code.
export class HubConfig {
/**
* Required if `driver` is `azure`
*/
azCredentials?: SubType<AZ_CONFIG_TYPE, 'azCredentials'>;
/**
* Required if `driver` is `disk`
*/
diskSettings?: SubType<DISK_CONFIG_TYPE, 'diskSettings'>;
/**
* Required if `driver` is `google-cloud`
*/
gcCredentials?: SubType<GC_CONFIG_TYPE, 'gcCredentials'>;
/**
* Required if `driver` is `aws`
*/
awsCredentials?: SubType<S3_CONFIG_TYPE, 'awsCredentials'>;
argsTransport? = new LoggingConfig();
proofsConfig? = new ProofCheckerConfig();
requireCorrectHubUrl? = false;
/**
* Domain name used for auth/signing challenges.
* If `requireCorrectHubUrl` is true then this must match the hub url in an auth payload.
*/
serverName? = 'gaia-0';
bucket? = 'hub';
/**
* @minimum 1
* @maximum 4096
* @TJS-type integer
*/
pageSize? = 100;
cacheControl? = 'no-cache';
/**
* The maximum allowed POST body size in megabytes.
* The content-size header is checked, and the POST body stream
* is monitoring while streaming from the client.
* [Recommended] Minimum 100KB (or approximately 0.1MB)
* @minimum 0.1
*/
maxFileUploadSize? = 20;
/**
* @TJS-type integer
*/
authTimestampCacheSize? = 50000;
driver = undefined as DriverName;
/**
* @minimum 0
* @maximum 65535
* @TJS-type integer
*/
port = 3000;
/**
* Requires `enableHttps` to be set.
* @default 443
* @minimum 0
* @maximum 65535
* @TJS-type integer
*/
httpsPort? = 443;
/**
* Disabled by default.
* If set to `cert_files` then `tlsCertConfig` must be set.
* If set to `acme` then `acmeConfig` must be set.
*/
enableHttps? = undefined as HttpsOption;
/**
* Options for Automatic Certificate Management Environment client.
* Requires `enableHttps` to be set to `acme`.
* See https://www.npmjs.com/package/greenlock-express
* See https://tools.ietf.org/html/rfc8555
* See https://github.com/ietf-wg-acme/acme
*/
acmeConfig?: AcmeConfigInterface;
/**
* Options for configuring the Node.js `https` server.
* Requires `enableHttps` to be set to `tlsCertConfig`.
* See https://nodejs.org/docs/latest-v10.x/api/https.html#https_https_createserver_options_requestlistener
* See https://nodejs.org/docs/latest-v10.x/api/tls.html#tls_tls_createsecurecontext_options
*/
tlsCertConfig?: TlsCertConfigInterface;
/**
* List of ID addresses allowed to use this hub. Specifying this makes the hub private
* and only accessible to the specified addresses. Leaving this unspecified makes the hub
* publicly usable by any ID.
*/
whitelist?: string[]
readURL?: string;
/**
* If `requireCorrectHubUrl` is true then the hub specified in an auth payload can also be
* contained within in array.
*/
validHubUrls?: string[];
/**
* Only used in tests
* @private
* @ignore
*/
driverInstance?: DriverModel;
/**
* Only used in tests
* @private
* @ignore
*/
driverClass?: DriverConstructor;
}
type EnvVarTypeInfo = [string, 'list' | 'int' | 'boolean' ]
type EnvVarType = string | EnvVarTypeInfo
type EnvVarProp = EnvVarType | EnvVarObj
interface EnvVarObj {
[key: string]: EnvVarProp
}
const globalEnvVars: EnvVarObj = {
whitelist: ['GAIA_WHITELIST', 'list'],
readURL: 'GAIA_READ_URL',
driver: 'GAIA_DRIVER',
validHubUrls: ['GAIA_VALID_HUB_URLS', 'list'],
requireCorrectHubUrl: ['GAIA_REQUIRE_CORRECT_HUB_URL', 'int'],
serverName: 'GAIA_SERVER_NAME',
bucket: 'GAIA_BUCKET_NAME',
pageSize: ['GAIA_PAGE_SIZE', 'int'],
cacheControl: 'GAIA_CACHE_CONTROL',
port: ['GAIA_PORT', 'int'],
httpsPort: ['GAIA_HTTPS_PORT', 'int'],
enableHttps: 'GAIA_ENABLE_HTTPS',
acmeConfig: {
email: 'GAIA_ACME_CONFIG_EMAIL',
agreeTos: ['GAIA_ACME_CONFIG_AGREE_TOS', 'boolean'],
configDir: 'GAIA_ACME_CONFIG_CONFIG_DIR',
securityUpdates: ['GAIA_ACME_CONFIG_SECURITY_UPDATES', 'boolean'],
servername: 'GAIA_ACME_CONFIG_SERVERNAME',
approveDomains: ['GAIA_ACME_CONFIG_APPROVE_DOMAINS', 'list']
},
tlsCertConfig: {
keyFile: 'GAIA_TLS_CERT_CONFIG_KEY_FILE',
certFile: 'GAIA_TLS_CERT_CONFIG_CERT_FILE',
keyPassphrase: 'GAIA_TLS_CERT_CONFIG_KEY_PASSPHRASE',
pfxFile: 'GAIA_TLS_CERT_CONFIG_PFX_FILE',
pfxPassphrase: 'GAIA_TLS_CERT_CONFIG_PFX_PASSPHRASE'
}
}
function getConfigEnv(envVars: EnvVarObj) {
const configEnv: Record<string, any> = {}
function hasTypeInfo(value: EnvVarObj | EnvVarTypeInfo): value is EnvVarTypeInfo {
return Array.isArray(value)
}
const detectedEnvVars: string[] = []
function populateObj(getTarget: () => Record<string, any>, envVarProp: EnvVarObj){
for (const [name, value] of Object.entries(envVarProp)) {
if (typeof value === 'string') {
if (process.env[value]) {
detectedEnvVars.push(value)
getTarget()[name] = process.env[value]
}
} else if (hasTypeInfo(value)) {
if (process.env[value[0]]) {
detectedEnvVars.push(value[0])
if (value[1] === 'int') {
const intVar = parseInt(process.env[value[0]])
if (isNaN(intVar)) {
throw new Error(`Passed a non-number input to: ${value[0]}`)
}
getTarget()[name] = intVar
} else if (value[1] === 'list') {
getTarget()[name] = process.env[value[0]].split(',').map(x => x.trim())
} else if (value[1] === 'boolean') {
let boolVal: boolean
const envVar = process.env[value[0]].toLowerCase().trim()
if (envVar === 'true') {
boolVal = true
} else if (envVar === 'false') {
boolVal = false
} else {
throw new Error(`Passed a invalid boolean input to: ${value[0]}, must be "true" or "false"`)
}
getTarget()[name] = boolVal
}
}
} else {
populateObj(() => {
const innerTarget = getTarget()
if (!innerTarget[name]) {
innerTarget[name] = {}
}
return innerTarget[name]
}, value)
}
}
}
populateObj(() => configEnv, envVars)
if (detectedEnvVars.length > 0) {
console.log(`Using env vars: ${detectedEnvVars.join(',')}`)
}
return configEnv
}
// we deep merge so that if someone sets { field: {subfield: foo} }, it doesn't remove
// { field: {subfieldOther: bar} }
function deepMerge<T>(target: T, ...sources: T[]): T {
function isObject(item: any) {
return (item && typeof item === 'object' && !Array.isArray(item))
}
if (sources.length === 0) {
return target
}
const source = sources.shift()
if (isObject(target) && isObject(source)) {
for (const key in source) {
if (isObject(source[key])) {
if (!target[key]) Object.assign(target, { [key]: {} })
deepMerge(target[key], source[key])
} else {
Object.assign(target, { [key]: source[key] })
}
}
}
return deepMerge(target, ...sources)
}
export function getConfigDefaults(): HubConfigInterface {
const configDefaults = new HubConfig()
// Remove explicit `undefined` values and empty objects
function removeEmptyOrUndefined(obj: any) {
Object.entries(obj).forEach(([key, val]) => {
if (typeof val === 'undefined') {
delete obj[key]
} else if (typeof val === 'object' && val !== null) {
removeEmptyOrUndefined(val)
if (Object.keys(val).length === 0) {
delete obj[key]
}
}
})
}
removeEmptyOrUndefined(configDefaults)
return configDefaults
}
export function validateConfigSchema(
schemaFilePath: string,
configObj: any,
warnCallback: (msg: string) => void = (msg => console.error(msg))
) {
try {
const ajv = new Ajv({
allErrors: true,
strictDefaults: true,
verbose: true,
errorDataPath: 'property'
})
if (!fs.existsSync(schemaFilePath)) {
warnCallback(`Could not find config schema file at ${schemaFilePath}`)
return
}
let schemaJson: any
try {
schemaJson = JSON.parse(fs.readFileSync(schemaFilePath, { encoding: 'utf8' }))
} catch (error) {
warnCallback(`Error reading config schema JSON file: ${error}`)
return
}
const valid = ajv.validate(schemaJson, configObj)
if (!valid) {
const errorText = ajv.errorsText(ajv.errors, {
dataVar: 'config'
})
warnCallback(`Config schema validation warning: ${errorText}`)
}
} catch (error) {
warnCallback(`Error validating config schema JSON file: ${error}`)
}
}
export function getConfig() {
const configPath = process.env.CONFIG_PATH || process.argv[2] || './config.json'
let configJSON
try {
configJSON = JSON.parse(fs.readFileSync(configPath, { encoding: 'utf8' }))
} catch (err) {
configJSON = {}
}
if (configJSON.servername) {
if (!configJSON.serverName) {
configJSON.serverName = configJSON.servername
}
delete configJSON.servername
}
const configENV = getConfigEnv(globalEnvVars) as any
const configDefaults = getConfigDefaults()
const configGlobal = deepMerge<HubConfigInterface>({} as any, configDefaults, configJSON, configENV)
let config = configGlobal
if (config.driver) {
const driverClass = getDriverClass(config.driver)
const driverConfigInfo = driverClass.getConfigInformation()
config = deepMerge<HubConfigInterface>({} as any, driverConfigInfo.defaults, configGlobal, driverConfigInfo.envVars)
}
const formats = [
config.argsTransport.colorize ? winston.format.colorize() : null,
config.argsTransport.timestamp ?
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }) : null,
config.argsTransport.json ? winston.format.json() : winston.format.simple()
].filter(f => f !== null)
const format = formats.length ? winston.format.combine(...formats) : null
logger.configure({
format: format,
transports: [new winston.transports.Console(config.argsTransport)]
})
return config
} | the_stack |
interface LtacProfTactic {
name: string,
statistics: {total: number; local: number; num_calls: number; max_total: number},
tactics: LtacProfTactic[],
}
interface LtacProfResults {
total_time: number,
tactics: LtacProfTactic[],
}
function getQueryStringValue(key:string) : string {
return decodeURI(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURI(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}
function importStyles(doc: Document) {
var parentStyleSheets = doc.styleSheets as any as CSSStyleSheet[];
var cssString = "";
for (var i = 0, count = parentStyleSheets.length; i < count; ++i) {
if (parentStyleSheets[i].cssRules) {
var cssRules = parentStyleSheets[i].cssRules;
for (var j = 0, countJ = cssRules.length; j < countJ; ++j)
cssString += cssRules[j].cssText;
}
else
cssString += parentStyleSheets[i].cssText; // IE8 and earlier
}
var style = document.createElement("style");
style.type = "text/css";
style.innerHTML = cssString;
// message(cssString);
document.getElementsByTagName("head")[0].appendChild(style);
}
function inheritStyles(p: Window) {
if (p) {
importStyles(p.document);
const pp = p.parent;
if(pp !== p)
inheritStyles(pp);
}
}
var connection : WebSocket|null = null;
function load() {
if(parent.parent === parent)
document.body.style.backgroundColor = 'black';
var address = `ws://${getQueryStringValue('host')}:${getQueryStringValue('port')}`;
connection = new WebSocket(address);
// connection.onopen = function (event) {
// document.getElementById('stdout').innerHTML = "connected";
// }
// connection.onclose = function (event) {
// document.getElementById('stdout').innerHTML = "connection closed";
// }
// connection.onerror = function (event) {
// document.getElementById('stdout').innerHTML = "connection error";
// }
connection.onmessage = function (event) {
const results = <LtacProfResults>JSON.parse(event.data);
addResults(results);
}
}
// interface TreeGridSettings {
// treeColumn?: number, // 0 Number of column using for tree
// initialState?: string, // expanded Initial state of tree
// // 'expanded' - all nodes will be expanded
// // 'collapsed' - all nodes will be collapsed
// saveState?: boolean, // false If true you can reload page and tree state was saved
// saveStateMethod?: string, // cookie 'cookie' - save state to cookie
// // 'hash' - save state to hash
// saveStateName?: string, // tree-grid-state Name of cookie or hash to save state.
// expanderTemplate?: string, // <span class="treegrid-expander"></span> HTML Element when you click on that will be collapse/expand branches
// expanderExpandedClass?: string, // treegrid-expander-expanded Class using for expander element when it expanded
// expanderCollapsedClass?: string, // treegrid-expander-collapsed Class using for expander element when it collapsed
// indentTemplate?: string, // <span class="treegrid-indent"></span> HTML Element that will be placed as padding, depending on the depth of nesting node
// onCollapse?: ()=>void, // null Function, which will be executed when one of node will be collapsed
// onExpand?: ()=>void, // null Function, which will be executed when one of node will be expanded
// onChange?: ()=>void, // null Function, which will be executed when one of node will be expanded or collapsed
// }
// interface FloatTHeadSettings {
// position?: string, // 'auto'
// scrollContainer?: (()=>any) | boolean, // null
// responsiveContainer?: ()=>any, // null
// headerCellSelector?: string, // 'tr:first>th:visible'
// floatTableClass?: string, // 'floatThead-table'
// floatContainerClass?: string, // 'floatThead-container'
// top?: (()=>any) | number, // 0
// bottom?: (()=>any) | number, // 0
// zIndex?: number, // 1001
// debug?: boolean, // false
// getSizingRow?: ()=>any, // undefined
// copyTableClass?: boolean, // true
// enableAria?: boolean, // false
// autoReflow?: boolean, // false
// }
// interface StickySettings {
// topSpacing?: number, // 0 -- Pixels between the page top and the element's top.
// bottomSpacing?: number, // 0 -- Pixels between the page bottom and the element's bottom.
// className?: string, // 'is-sticky' -- CSS class added to the element's wrapper when "sticked".
// wrapperClassName?: string, // 'sticky-wrapper' -- CSS class added to the wrapper.
// center?: boolean, // false -- Boolean determining whether the sticky element should be horizontally centered in the page.
// getWidthFrom?: string, // '' -- Selector of element referenced to set fixed width of "sticky" element.
// widthFromWrapper?: boolean, // true -- Boolean determining whether width of the "sticky" element should be updated to match the wrapper's width. Wrapper is a placeholder for "sticky" element while it is fixed (out of static elements flow), and its width depends on the context and CSS rules. Works only as long getWidthForm isn't set.
// responsiveWidth?: boolean, // false -- Boolean determining whether widths will be recalculated on window resize (using getWidthfrom).
// zIndex?: number | string, // auto -- controls z-index of the sticked element.
// }
// implement cycleNext
// (function($) { $.fn.cycleNext = function() {
// const siblings = $(this).parent().children();
// return siblings.eq((siblings.index($(this))+1)%siblings.length);
// } })(jQuery);
// interface JQuery {
// // treegrid() : JQuery;
// // treegrid(settings: TreeGridSettings): JQuery;
// // treegrid(methodName:'initTree',data: string): JQuery;
// // treegrid(methodName: string, data: string): JQuery;
// tbltree() : JQuery;
// tbltree(settings: TblTreeSettings);
// tbltree(methodName:'expand', id: JQuery|string, user?: number): JQuery;
// tbltree(methodName:'collapse', id: JQuery|string, user?: number): JQuery;
// tbltree(methodName:'toggle', id: JQuery|string): JQuery;
// tbltree(methodName:'getRow', id: string): JQuery;
// tbltree(methodName:'getId', row: JQuery): string;
// tbltree(methodName:'getParentID', row: JQuery): string;
// tbltree(methodName:'getTreeCell', row: JQuery): JQuery;
// tbltree(methodName:'_getChildren', row: JQuery): JQuery;
// tbltree(methodName:'isLeaf', row: JQuery): boolean;
// tbltree(methodName:'isExpanded', row: JQuery): boolean;
// tbltree(methodName:'isCollapsed', row: JQuery): boolean;
// tbltree(methodName:string, param: JQuery|string): any;
// tbltree(methodName:'getRootNodes'): JQuery;
// // floatThead() : JQuery;
// // floatThead(settings: FloatTHeadSettings) : JQuery;
// // tablesorter(): JQuery;
// // sticky() : JQuery;
// // sticky(settings: StickySettings) : JQuery;
// // sticky(methodName:'update') : JQuery;
// // resizableColumns() : JQuery;
// colResizable() : JQuery;
// colResizable(settings: {resizeMode?: string, disable?: boolean, disabledColumns?: number[], liveDrag?: boolean, postbackSafe?: boolean, partialRefresh?: boolean, headerOnly?: boolean, innerGripHtml?: string, draggingClass?: string, minWidth?: number, hoverCursor?: string, dragCursor?: string, flush?: boolean, marginLeft?: string, marginRight?: string, onResize?: (e:JQueryEventObject)=>void, onDrag?: ()=>void}) : JQuery;
// cycleNext(): JQuery;
// }
function sleepFor(sleepDuration: number) : void{
var now = new Date().getTime();
while(new Date().getTime() < now + sleepDuration){ /* do nothing */ }
}
function loadResultsTable(results: LtacProfResults, tbody: JQuery) {
let currentId = 0;
let totalTime = results.total_time;
function buildTime(time: number, total: number, name: string) {
if(time == 0)
return $(document.createElement('td')).text("");
else {
const seconds = time.toFixed(3);
const minutes = (time/60).toFixed(1);
const hh = Math.floor(time/3600);
const mm = Math.floor((time - hh*3600)/60);
const ss = time - mm*60;
const hhmmss = `${hh}:${mm}:${ss.toFixed(1)}`;
const percent = (time/totalTime*100).toFixed(1) + "%";
return $(document.createElement('td'))
.append($(document.createElement('span')).addClass(name).addClass('seconds').text(seconds).hide())
.append($(document.createElement('span')).addClass(name).addClass('minutes').text(minutes).hide())
.append($(document.createElement('span')).addClass(name).addClass('hhmmss').text(hhmmss).hide())
.append($(document.createElement('span')).addClass(name).addClass('percent').text(percent).show());
// return $(document.createElement('td')).text(time);
// const percent = ((0.0+time) / (0.0 + totalTime)).toFixed(3);
// return $(document.createElement('td')).text(percent);
}
}
function* buildTacticResultRow(parentId: number, tactic: LtacProfTactic) : IterableIterator<JQuery> {
++currentId;
yield $(document.createElement('tr'))
// .addClass('treegrid-'+ this.currentId)
// .addClass(`treegrid-${currentId}` + (parentId > 0 ? ` treegrid-parent-${parentId}` : ''))
.attr('row-id',currentId)
// .map(() => { if(parentId>0) return $(this).attr('parent-id', parentId); else return $(this); })
.map((idx,elm) => parentId > 0 ? $(elm).attr('parent-id',parentId).get() : elm)
// .attr('parent-id',parentId)
.attr('tabindex',currentId)
// .map((idx,element) => parentId > 0 ? $(element).addClass('treegrid-parent-'+parentId) : $(element))
.append($(document.createElement('td')).text(tactic.name))
.append(buildTime(tactic.statistics.local,totalTime,'local'))
.append(buildTime(tactic.statistics.total,totalTime,'total'))
.append($(document.createElement('td')).text(tactic.statistics.num_calls))
.append($(document.createElement('td')).text(tactic.statistics.max_total.toFixed(3)));
yield* buildTacticsResults(currentId,tactic.tactics);
}
function* buildTacticsResults(parentId: number, tactics: LtacProfTactic[]) : IterableIterator<JQuery> {
for(let tactic of tactics) {
yield* buildTacticResultRow(parentId, tactic);
}
}
console.time('load');
for(let entry of buildTacticsResults(0,results.tactics))
tbody.append(entry);
console.timeEnd('load');
// setTimeout(() => {
// for(let entry of buildResults(0,result.results)) {
// setTimeout(() => {
// tbody.append(entry);
// // sleepFor(100);
// }, 100);
// }
// }, 10);
}
function getDescendants(node: JQuery) : JQuery {
const level = node.attr('level');
return node.nextUntil(`[level=${level}]`,'tr');
}
function expandNode(node: JQuery, recursive: boolean) : JQuery {
// node.treegrid(recursive ? 'expandRecursive' : 'expand');
if(recursive) {
getDescendants(node)
.removeClass('tbltree-collapsed')
.addClass('tbltree-expanded');
}
return $('#results').tbltree('expand', node, 1);
}
function collapseNode(node: JQuery, recursive: boolean) : JQuery {
// node.treegrid(recursive ? 'collapseRecursive' : 'collapse');
if(recursive) {
getDescendants(node)
.addClass('tbltree-collapsed')
.removeClass('tbltree-expanded');
}
return $('#results').tbltree('collapse', node, 1);
}
function isExpanded(node: JQuery) : boolean {
// node.treegrid(recursive ? 'collapseRecursive' : 'collapse');
return $('#results').tbltree('isExpanded',node);
}
function getParentNode(node: JQuery) : JQuery {
// return node.treegrid)'getParentNode');
return $('#results').tbltree('getRow',$('#results').tbltree('getParentID', node));
}
let updateResultsAlternatingBackgroundTimer : number;
function updateResultsAlternatingBackground(delay?: number) {
if(updateResultsAlternatingBackgroundTimer)
clearTimeout(updateResultsAlternatingBackgroundTimer);
if(delay)
updateResultsAlternatingBackgroundTimer = setTimeout(() => updateResultsAlternatingBackground(), delay);
else {
$('#results tr:visible:even').removeClass('result-odd');
$('#results tr:visible:odd').addClass('result-odd');
}
}
const currentResults : LtacProfResults = {total_time: 0, tactics: []};
function clearResults() {
currentResults.total_time = 0;
currentResults.tactics = []
let tbody = $('#results tbody');
if(tbody.length > 0)
tbody.empty();
}
// function calculateTotalTime(tactic: LtacProfTactic) {
// tactic.statistics.total
// }
function addResults(results: LtacProfResults) {
if(results.total_time === 0) {
// This could be 0 because of a bug in Coq 8.6 :/
// Recompute the total by hand...
currentResults.total_time = results.tactics.map(x=>x.statistics.total).reduce((s,v) => s+v, 0);
}
currentResults.total_time += results.total_time;
currentResults.tactics = currentResults.tactics.concat(results.tactics);
updateResults();
}
function onKeyDown(e: JQueryKeyEventObject) {
const f = $(':focus');
switch(e.which)
{
case 39: // right
expandNode(f, e.shiftKey);
break;
case 37: // left
if(isExpanded(f))
collapseNode(f, e.shiftKey);
else {
getParentNode(f).focus();
collapseNode(getParentNode(f), e.shiftKey);
}
break;
case 38: // up
f.prevAll('tr:visible').first().focus();
break;
case 40: //down
f.nextAll('tr:visible').first().focus();
break;
default:
return;
}
e.preventDefault();
}
function updateResults() {
let tbody = $('#results tbody');
if(tbody.length > 0)
tbody.empty();
else {// Set up the table
tbody = $('<tbody>');
$('#results').append(tbody);
$('#results').keydown(onKeyDown);
$('#local-unit').change((ev: JQueryEventObject) => {
const tag = $('#local-unit option:selected').val();
$('#results span.local').not('.'+tag).hide();
$('#results span.local').filter('.'+tag).show();
});
$('#total-unit').change((ev: JQueryEventObject) => {
const tag = $('#total-unit option:selected').val();
$('#results span.total').not('.'+tag).hide();
$('#results span.total').filter('.'+tag).show();
});
$('#local-column').click((ev:JQueryEventObject) => {
if(ev.target === $('#local-column').get(0))
$('#local-unit option:selected').prop('selected',false).cycleNext().prop('selected', true); $('#local-unit').change()
});
$('#total-column').click((ev:JQueryEventObject) => {
if(ev.target === $('#total-column').get(0))
$('#total-unit option:selected').prop('selected',false).cycleNext().prop('selected', true); $('#total-unit').change()
});
}
loadResultsTable(currentResults, tbody);
// time('treegrid', () => {
// $('#results').treegrid({
// initialState: 'collapsed',
// saveState: false,
// onChange: () => {
// $('#results tr:visible:even').removeClass('result-odd');
// $('#results tr:visible:odd').addClass('result-odd');
// }
// });
// });
console.time('tbltree');
$('#results').tbltree({
initState: 'collapsed',
saveState: false,
change: () => updateResultsAlternatingBackground(50),
});
console.timeEnd('tbltree');
// time('resizable', () => {
// $('#results')
// .css('table-layout','auto')
// .resizableColumns()
// .css('table-layout','fixed');
// });
// time('resizable', () => {
// $('#results')
// .css('table-layout','auto')
// .colResizable({
// resizeMode: 'fit', liveDrag: true,
// // onResize: (e:JQueryEventObject) => {
// // console.log('resize');
// // // $('#sticky-results-header').remove('thead'); //.append($('results thead'));
// // }
// })
// .css('table-layout','fixed');
// });
// $('#results').floatThead('reflow');
// time('floatThead', () => {
// $('#results').floatThead({})
// });
// time('sticky', () => {
// $('#results thead').sticky({topSpacing: 0, getWidthFrom: '#results'});
// $('#results thead').sticky('update');
// });
// $('#results tr:visible:even').removeClass('result-odd');
// $('#results tr:visible:odd').addClass('result-odd');
updateResultsAlternatingBackground(0);
} | the_stack |
import { BigNumber } from "bignumber.js";
import * as moment from "moment";
import * as Web3 from "web3";
// Utils
import * as Units from "../../../../../utils/units";
import { Web3Utils } from "../../../../../utils/web3_utils";
// Scenarios
import { ReturnCollateralScenario, SeizeCollateralScenario } from "../scenarios";
// Adapters
import {
ERC721CollateralizedSimpleInterestLoanAdapter,
ERC721CollateralizedTermsContractParameters,
} from "../../../../../src/adapters/erc721_collateralized_simple_interest/loan_adapter";
// Wrappers
import {
DebtKernelContract,
DummyTokenContract,
ERC721CollateralizedSimpleInterestTermsContractContract,
ERC721TokenContract,
RepaymentRouterContract,
TokenTransferProxyContract,
} from "../../../../../src/wrappers";
// APIs
import { ContractsAPI, OrderAPI, ServicingAPI, SignerAPI, TokenAPI } from "../../../../../src/apis";
// Types
import { DebtOrderData } from "../../../../../src/types";
// Accounts
import { ACCOUNTS } from "../../../../accounts";
const CONTRACT_OWNER = ACCOUNTS[0];
const DEBTOR = ACCOUNTS[1];
const CREDITOR = ACCOUNTS[2];
const UNDERWRITER = ACCOUNTS[3];
const RELAYER = ACCOUNTS[4];
const TX_DEFAULTS = { from: CONTRACT_OWNER.address, gas: 4712388 };
export interface APIs {
orderApi: OrderAPI;
signerApi: SignerAPI;
servicingApi: ServicingAPI;
contractsApi: ContractsAPI;
tokenApi: TokenAPI;
}
export abstract class BaseCollateralRunner {
protected adapter: ERC721CollateralizedSimpleInterestLoanAdapter;
protected debtKernel: DebtKernelContract;
protected repaymentRouter: RepaymentRouterContract;
protected principalToken: DummyTokenContract;
protected collateralToken: ERC721TokenContract;
protected termsContract: ERC721CollateralizedSimpleInterestTermsContractContract;
protected orderApi: OrderAPI;
protected signerApi: SignerAPI;
protected tokenTransferProxy: TokenTransferProxyContract;
protected web3: Web3;
protected web3Utils: Web3Utils;
protected servicingApi: ServicingAPI;
protected contractsApi: ContractsAPI;
protected tokenApi: TokenAPI;
protected snapshotId: number;
protected debtOrderData: DebtOrderData;
constructor(web3: Web3, adapter: ERC721CollateralizedSimpleInterestLoanAdapter, apis: APIs) {
this.web3 = web3;
this.orderApi = apis.orderApi;
this.signerApi = apis.signerApi;
this.servicingApi = apis.servicingApi;
this.contractsApi = apis.contractsApi;
this.tokenApi = apis.tokenApi;
this.adapter = adapter;
this.web3Utils = new Web3Utils(web3);
this.testScenario = this.testScenario.bind(this);
this.revertToSavedSnapshot = this.revertToSavedSnapshot.bind(this);
}
public async saveSnapshotAsync() {
this.snapshotId = await this.web3Utils.saveTestSnapshot();
}
public async revertToSavedSnapshot() {
await this.web3Utils.revertToSnapshot(this.snapshotId);
}
public abstract testScenario(scenario: ReturnCollateralScenario | SeizeCollateralScenario);
// Increases EVM time to a given new time in seconds since unix epoch.
protected async increaseTime(newTime: number): Promise<void> {
const secondsUntilNewTime = newTime - (await this.web3Utils.getCurrentBlockTime());
await this.web3Utils.increaseTime(secondsUntilNewTime + 1);
}
protected async setBalances(
scenario: ReturnCollateralScenario | SeizeCollateralScenario,
): Promise<void> {
// The debtor has more than enough of the principal token to repay debts.
await this.principalToken.setBalance.sendTransactionAsync(
DEBTOR.address,
scenario.simpleTerms.principalAmount.mul(2),
{
from: CONTRACT_OWNER.address,
},
);
// 2. Set up creditor balances.
// The creditor has exactly the amount necessary to loan to the debtor,
// as well as to pay for the creditor fee.
await this.principalToken.setBalance.sendTransactionAsync(
CREDITOR.address,
scenario.simpleTerms.principalAmount.add(this.debtOrderData.creditorFee),
{
from: CONTRACT_OWNER.address,
},
);
// 3. Set up underwriter balances.
// The underwriter has enough balance to pay the underwriter fee.
await this.principalToken.setBalance.sendTransactionAsync(
UNDERWRITER.address,
this.debtOrderData.underwriterFee,
{
from: CONTRACT_OWNER.address,
},
);
}
protected async setApprovals(
scenario: ReturnCollateralScenario | SeizeCollateralScenario,
): Promise<void> {
const { debtor, creditor, principalAmount } = this.debtOrderData;
// The debtor grants the transfer proxy some sufficient allowance for making repayments.
await this.tokenApi.setProxyAllowanceAsync(
this.principalToken.address,
principalAmount.mul(2),
{ from: debtor },
);
// The creditor grants allowance of the principal token being loaned,
// as well as the creditor fee.
await this.tokenApi.setProxyAllowanceAsync(
this.principalToken.address,
principalAmount.add(this.debtOrderData.creditorFee),
{ from: creditor },
);
}
protected async signOrder(): Promise<void> {
this.debtOrderData.debtorSignature = await this.signerApi.asDebtor(
this.debtOrderData,
false,
);
this.debtOrderData.creditorSignature = await this.signerApi.asCreditor(
this.debtOrderData,
false,
);
this.debtOrderData.underwriterSignature = await this.signerApi.asUnderwriter(
this.debtOrderData,
false,
);
}
protected async repayDebt(agreementId, termEnd): Promise<void> {
const amount = await this.termsContract.getExpectedRepaymentValue.callAsync(
agreementId,
termEnd,
);
await this.servicingApi.makeRepayment(agreementId, amount, this.principalToken.address, {
from: this.debtOrderData.debtor,
});
}
protected generateDebtOrderData(
scenario: ReturnCollateralScenario | SeizeCollateralScenario,
): DebtOrderData {
const termsParams = this.adapter.packParameters(
scenario.simpleTerms,
scenario.collateralTerms,
);
return {
kernelVersion: this.debtKernel.address,
issuanceVersion: this.repaymentRouter.address,
principalAmount: scenario.simpleTerms.principalAmount,
principalToken: this.principalToken.address,
debtor: DEBTOR.address,
debtorFee: Units.ether(0.001),
creditor: CREDITOR.address,
creditorFee: Units.ether(0.002),
relayer: RELAYER.address,
relayerFee: Units.ether(0.0015),
termsContract: this.termsContract.address,
termsContractParameters: termsParams,
expirationTimestampInSec: new BigNumber(
moment()
.add(7, "days")
.unix(),
),
underwriter: UNDERWRITER.address,
underwriterFee: Units.ether(0.0015),
underwriterRiskRating: new BigNumber(1350),
salt: new BigNumber(0),
};
}
protected async generateAndFillOrder(
scenario: ReturnCollateralScenario | SeizeCollateralScenario,
collateralTerms: ERC721CollateralizedTermsContractParameters,
): Promise<void> {
scenario.collateralTerms = collateralTerms;
this.debtOrderData = this.generateDebtOrderData(scenario);
await this.signOrder();
await this.setBalances(scenario);
await this.setApprovals(scenario);
await this.orderApi.fillAsync(this.debtOrderData, {
from: CREDITOR.address,
// NOTE: Using the maximum gas here, to prevent potentially confusing
// reverts due to insufficient gas. This wouldn't be applied in practice.
gas: 4712388,
});
}
protected async initializeWrappers(
scenario: ReturnCollateralScenario | SeizeCollateralScenario,
): Promise<ERC721CollateralizedTermsContractParameters> {
this.debtKernel = await DebtKernelContract.deployed(this.web3);
this.repaymentRouter = await RepaymentRouterContract.deployed(this.web3);
this.termsContract = await this.contractsApi.loadERC721CollateralizedSimpleInterestTermsContract(
TX_DEFAULTS,
);
const principalTokenSymbol = await this.contractsApi.getTokenSymbolByIndexAsync(
scenario.simpleTerms.principalTokenIndex,
);
const erc721Symbol = "MET";
const erc721TokenIndex = await this.contractsApi.getERC721IndexBySymbolAsync(erc721Symbol);
this.principalToken = await DummyTokenContract.at(
(await this.contractsApi.loadTokenBySymbolAsync(principalTokenSymbol)).address,
this.web3,
TX_DEFAULTS,
);
this.collateralToken = await this.contractsApi.loadERC721BySymbolAsync(erc721Symbol);
// Mint a collateral token for the debtor. We can do this because we assume that the
// collateral token is a Mintable ER721 Token.
const mintableERC721Contract = await this.contractsApi.loadMintableERC721ContractAsync(
TX_DEFAULTS,
);
const tokenId = await mintableERC721Contract.totalSupply.callAsync();
await mintableERC721Contract.mint.sendTransactionAsync(DEBTOR.address, tokenId);
const collateralizerContract = await this.contractsApi.loadERC721CollateralizerAsync();
// Grant permission to the collateralizer.
await mintableERC721Contract.approve.sendTransactionAsync(
collateralizerContract.address,
tokenId,
{ ...TX_DEFAULTS, from: DEBTOR.address },
);
this.tokenTransferProxy = await this.contractsApi.loadTokenTransferProxyAsync();
return {
tokenReference: tokenId,
erc721ContractIndex: erc721TokenIndex,
isEnumerable: new BigNumber(1),
};
}
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { PollerLike, PollOperationState } from "@azure/core-lro";
import {
SqlDatabaseGetResults,
SqlResourcesListSqlDatabasesOptionalParams,
SqlContainerGetResults,
SqlResourcesListSqlContainersOptionalParams,
SqlStoredProcedureGetResults,
SqlResourcesListSqlStoredProceduresOptionalParams,
SqlUserDefinedFunctionGetResults,
SqlResourcesListSqlUserDefinedFunctionsOptionalParams,
SqlTriggerGetResults,
SqlResourcesListSqlTriggersOptionalParams,
SqlResourcesGetSqlDatabaseOptionalParams,
SqlResourcesGetSqlDatabaseResponse,
SqlDatabaseCreateUpdateParameters,
SqlResourcesCreateUpdateSqlDatabaseOptionalParams,
SqlResourcesCreateUpdateSqlDatabaseResponse,
SqlResourcesDeleteSqlDatabaseOptionalParams,
SqlResourcesGetSqlDatabaseThroughputOptionalParams,
SqlResourcesGetSqlDatabaseThroughputResponse,
ThroughputSettingsUpdateParameters,
SqlResourcesUpdateSqlDatabaseThroughputOptionalParams,
SqlResourcesUpdateSqlDatabaseThroughputResponse,
SqlResourcesGetSqlContainerOptionalParams,
SqlResourcesGetSqlContainerResponse,
SqlContainerCreateUpdateParameters,
SqlResourcesCreateUpdateSqlContainerOptionalParams,
SqlResourcesCreateUpdateSqlContainerResponse,
SqlResourcesDeleteSqlContainerOptionalParams,
SqlResourcesGetSqlContainerThroughputOptionalParams,
SqlResourcesGetSqlContainerThroughputResponse,
SqlResourcesUpdateSqlContainerThroughputOptionalParams,
SqlResourcesUpdateSqlContainerThroughputResponse,
SqlResourcesGetSqlStoredProcedureOptionalParams,
SqlResourcesGetSqlStoredProcedureResponse,
SqlStoredProcedureCreateUpdateParameters,
SqlResourcesCreateUpdateSqlStoredProcedureOptionalParams,
SqlResourcesCreateUpdateSqlStoredProcedureResponse,
SqlResourcesDeleteSqlStoredProcedureOptionalParams,
SqlResourcesGetSqlUserDefinedFunctionOptionalParams,
SqlResourcesGetSqlUserDefinedFunctionResponse,
SqlUserDefinedFunctionCreateUpdateParameters,
SqlResourcesCreateUpdateSqlUserDefinedFunctionOptionalParams,
SqlResourcesCreateUpdateSqlUserDefinedFunctionResponse,
SqlResourcesDeleteSqlUserDefinedFunctionOptionalParams,
SqlResourcesGetSqlTriggerOptionalParams,
SqlResourcesGetSqlTriggerResponse,
SqlTriggerCreateUpdateParameters,
SqlResourcesCreateUpdateSqlTriggerOptionalParams,
SqlResourcesCreateUpdateSqlTriggerResponse,
SqlResourcesDeleteSqlTriggerOptionalParams
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Interface representing a SqlResources. */
export interface SqlResources {
/**
* Lists the SQL databases under an existing Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param options The options parameters.
*/
listSqlDatabases(
resourceGroupName: string,
accountName: string,
options?: SqlResourcesListSqlDatabasesOptionalParams
): PagedAsyncIterableIterator<SqlDatabaseGetResults>;
/**
* Lists the SQL container under an existing Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param options The options parameters.
*/
listSqlContainers(
resourceGroupName: string,
accountName: string,
databaseName: string,
options?: SqlResourcesListSqlContainersOptionalParams
): PagedAsyncIterableIterator<SqlContainerGetResults>;
/**
* Lists the SQL storedProcedure under an existing Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param containerName Cosmos DB container name.
* @param options The options parameters.
*/
listSqlStoredProcedures(
resourceGroupName: string,
accountName: string,
databaseName: string,
containerName: string,
options?: SqlResourcesListSqlStoredProceduresOptionalParams
): PagedAsyncIterableIterator<SqlStoredProcedureGetResults>;
/**
* Lists the SQL userDefinedFunction under an existing Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param containerName Cosmos DB container name.
* @param options The options parameters.
*/
listSqlUserDefinedFunctions(
resourceGroupName: string,
accountName: string,
databaseName: string,
containerName: string,
options?: SqlResourcesListSqlUserDefinedFunctionsOptionalParams
): PagedAsyncIterableIterator<SqlUserDefinedFunctionGetResults>;
/**
* Lists the SQL trigger under an existing Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param containerName Cosmos DB container name.
* @param options The options parameters.
*/
listSqlTriggers(
resourceGroupName: string,
accountName: string,
databaseName: string,
containerName: string,
options?: SqlResourcesListSqlTriggersOptionalParams
): PagedAsyncIterableIterator<SqlTriggerGetResults>;
/**
* Gets the SQL database under an existing Azure Cosmos DB database account with the provided name.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param options The options parameters.
*/
getSqlDatabase(
resourceGroupName: string,
accountName: string,
databaseName: string,
options?: SqlResourcesGetSqlDatabaseOptionalParams
): Promise<SqlResourcesGetSqlDatabaseResponse>;
/**
* Create or update an Azure Cosmos DB SQL database
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param createUpdateSqlDatabaseParameters The parameters to provide for the current SQL database.
* @param options The options parameters.
*/
beginCreateUpdateSqlDatabase(
resourceGroupName: string,
accountName: string,
databaseName: string,
createUpdateSqlDatabaseParameters: SqlDatabaseCreateUpdateParameters,
options?: SqlResourcesCreateUpdateSqlDatabaseOptionalParams
): Promise<
PollerLike<
PollOperationState<SqlResourcesCreateUpdateSqlDatabaseResponse>,
SqlResourcesCreateUpdateSqlDatabaseResponse
>
>;
/**
* Create or update an Azure Cosmos DB SQL database
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param createUpdateSqlDatabaseParameters The parameters to provide for the current SQL database.
* @param options The options parameters.
*/
beginCreateUpdateSqlDatabaseAndWait(
resourceGroupName: string,
accountName: string,
databaseName: string,
createUpdateSqlDatabaseParameters: SqlDatabaseCreateUpdateParameters,
options?: SqlResourcesCreateUpdateSqlDatabaseOptionalParams
): Promise<SqlResourcesCreateUpdateSqlDatabaseResponse>;
/**
* Deletes an existing Azure Cosmos DB SQL database.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param options The options parameters.
*/
beginDeleteSqlDatabase(
resourceGroupName: string,
accountName: string,
databaseName: string,
options?: SqlResourcesDeleteSqlDatabaseOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Deletes an existing Azure Cosmos DB SQL database.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param options The options parameters.
*/
beginDeleteSqlDatabaseAndWait(
resourceGroupName: string,
accountName: string,
databaseName: string,
options?: SqlResourcesDeleteSqlDatabaseOptionalParams
): Promise<void>;
/**
* Gets the RUs per second of the SQL database under an existing Azure Cosmos DB database account with
* the provided name.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param options The options parameters.
*/
getSqlDatabaseThroughput(
resourceGroupName: string,
accountName: string,
databaseName: string,
options?: SqlResourcesGetSqlDatabaseThroughputOptionalParams
): Promise<SqlResourcesGetSqlDatabaseThroughputResponse>;
/**
* Update RUs per second of an Azure Cosmos DB SQL database
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param updateThroughputParameters The parameters to provide for the RUs per second of the current
* SQL database.
* @param options The options parameters.
*/
beginUpdateSqlDatabaseThroughput(
resourceGroupName: string,
accountName: string,
databaseName: string,
updateThroughputParameters: ThroughputSettingsUpdateParameters,
options?: SqlResourcesUpdateSqlDatabaseThroughputOptionalParams
): Promise<
PollerLike<
PollOperationState<SqlResourcesUpdateSqlDatabaseThroughputResponse>,
SqlResourcesUpdateSqlDatabaseThroughputResponse
>
>;
/**
* Update RUs per second of an Azure Cosmos DB SQL database
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param updateThroughputParameters The parameters to provide for the RUs per second of the current
* SQL database.
* @param options The options parameters.
*/
beginUpdateSqlDatabaseThroughputAndWait(
resourceGroupName: string,
accountName: string,
databaseName: string,
updateThroughputParameters: ThroughputSettingsUpdateParameters,
options?: SqlResourcesUpdateSqlDatabaseThroughputOptionalParams
): Promise<SqlResourcesUpdateSqlDatabaseThroughputResponse>;
/**
* Gets the SQL container under an existing Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param containerName Cosmos DB container name.
* @param options The options parameters.
*/
getSqlContainer(
resourceGroupName: string,
accountName: string,
databaseName: string,
containerName: string,
options?: SqlResourcesGetSqlContainerOptionalParams
): Promise<SqlResourcesGetSqlContainerResponse>;
/**
* Create or update an Azure Cosmos DB SQL container
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param containerName Cosmos DB container name.
* @param createUpdateSqlContainerParameters The parameters to provide for the current SQL container.
* @param options The options parameters.
*/
beginCreateUpdateSqlContainer(
resourceGroupName: string,
accountName: string,
databaseName: string,
containerName: string,
createUpdateSqlContainerParameters: SqlContainerCreateUpdateParameters,
options?: SqlResourcesCreateUpdateSqlContainerOptionalParams
): Promise<
PollerLike<
PollOperationState<SqlResourcesCreateUpdateSqlContainerResponse>,
SqlResourcesCreateUpdateSqlContainerResponse
>
>;
/**
* Create or update an Azure Cosmos DB SQL container
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param containerName Cosmos DB container name.
* @param createUpdateSqlContainerParameters The parameters to provide for the current SQL container.
* @param options The options parameters.
*/
beginCreateUpdateSqlContainerAndWait(
resourceGroupName: string,
accountName: string,
databaseName: string,
containerName: string,
createUpdateSqlContainerParameters: SqlContainerCreateUpdateParameters,
options?: SqlResourcesCreateUpdateSqlContainerOptionalParams
): Promise<SqlResourcesCreateUpdateSqlContainerResponse>;
/**
* Deletes an existing Azure Cosmos DB SQL container.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param containerName Cosmos DB container name.
* @param options The options parameters.
*/
beginDeleteSqlContainer(
resourceGroupName: string,
accountName: string,
databaseName: string,
containerName: string,
options?: SqlResourcesDeleteSqlContainerOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Deletes an existing Azure Cosmos DB SQL container.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param containerName Cosmos DB container name.
* @param options The options parameters.
*/
beginDeleteSqlContainerAndWait(
resourceGroupName: string,
accountName: string,
databaseName: string,
containerName: string,
options?: SqlResourcesDeleteSqlContainerOptionalParams
): Promise<void>;
/**
* Gets the RUs per second of the SQL container under an existing Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param containerName Cosmos DB container name.
* @param options The options parameters.
*/
getSqlContainerThroughput(
resourceGroupName: string,
accountName: string,
databaseName: string,
containerName: string,
options?: SqlResourcesGetSqlContainerThroughputOptionalParams
): Promise<SqlResourcesGetSqlContainerThroughputResponse>;
/**
* Update RUs per second of an Azure Cosmos DB SQL container
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param containerName Cosmos DB container name.
* @param updateThroughputParameters The parameters to provide for the RUs per second of the current
* SQL container.
* @param options The options parameters.
*/
beginUpdateSqlContainerThroughput(
resourceGroupName: string,
accountName: string,
databaseName: string,
containerName: string,
updateThroughputParameters: ThroughputSettingsUpdateParameters,
options?: SqlResourcesUpdateSqlContainerThroughputOptionalParams
): Promise<
PollerLike<
PollOperationState<SqlResourcesUpdateSqlContainerThroughputResponse>,
SqlResourcesUpdateSqlContainerThroughputResponse
>
>;
/**
* Update RUs per second of an Azure Cosmos DB SQL container
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param containerName Cosmos DB container name.
* @param updateThroughputParameters The parameters to provide for the RUs per second of the current
* SQL container.
* @param options The options parameters.
*/
beginUpdateSqlContainerThroughputAndWait(
resourceGroupName: string,
accountName: string,
databaseName: string,
containerName: string,
updateThroughputParameters: ThroughputSettingsUpdateParameters,
options?: SqlResourcesUpdateSqlContainerThroughputOptionalParams
): Promise<SqlResourcesUpdateSqlContainerThroughputResponse>;
/**
* Gets the SQL storedProcedure under an existing Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param containerName Cosmos DB container name.
* @param storedProcedureName Cosmos DB storedProcedure name.
* @param options The options parameters.
*/
getSqlStoredProcedure(
resourceGroupName: string,
accountName: string,
databaseName: string,
containerName: string,
storedProcedureName: string,
options?: SqlResourcesGetSqlStoredProcedureOptionalParams
): Promise<SqlResourcesGetSqlStoredProcedureResponse>;
/**
* Create or update an Azure Cosmos DB SQL storedProcedure
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param containerName Cosmos DB container name.
* @param storedProcedureName Cosmos DB storedProcedure name.
* @param createUpdateSqlStoredProcedureParameters The parameters to provide for the current SQL
* storedProcedure.
* @param options The options parameters.
*/
beginCreateUpdateSqlStoredProcedure(
resourceGroupName: string,
accountName: string,
databaseName: string,
containerName: string,
storedProcedureName: string,
createUpdateSqlStoredProcedureParameters: SqlStoredProcedureCreateUpdateParameters,
options?: SqlResourcesCreateUpdateSqlStoredProcedureOptionalParams
): Promise<
PollerLike<
PollOperationState<SqlResourcesCreateUpdateSqlStoredProcedureResponse>,
SqlResourcesCreateUpdateSqlStoredProcedureResponse
>
>;
/**
* Create or update an Azure Cosmos DB SQL storedProcedure
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param containerName Cosmos DB container name.
* @param storedProcedureName Cosmos DB storedProcedure name.
* @param createUpdateSqlStoredProcedureParameters The parameters to provide for the current SQL
* storedProcedure.
* @param options The options parameters.
*/
beginCreateUpdateSqlStoredProcedureAndWait(
resourceGroupName: string,
accountName: string,
databaseName: string,
containerName: string,
storedProcedureName: string,
createUpdateSqlStoredProcedureParameters: SqlStoredProcedureCreateUpdateParameters,
options?: SqlResourcesCreateUpdateSqlStoredProcedureOptionalParams
): Promise<SqlResourcesCreateUpdateSqlStoredProcedureResponse>;
/**
* Deletes an existing Azure Cosmos DB SQL storedProcedure.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param containerName Cosmos DB container name.
* @param storedProcedureName Cosmos DB storedProcedure name.
* @param options The options parameters.
*/
beginDeleteSqlStoredProcedure(
resourceGroupName: string,
accountName: string,
databaseName: string,
containerName: string,
storedProcedureName: string,
options?: SqlResourcesDeleteSqlStoredProcedureOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Deletes an existing Azure Cosmos DB SQL storedProcedure.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param containerName Cosmos DB container name.
* @param storedProcedureName Cosmos DB storedProcedure name.
* @param options The options parameters.
*/
beginDeleteSqlStoredProcedureAndWait(
resourceGroupName: string,
accountName: string,
databaseName: string,
containerName: string,
storedProcedureName: string,
options?: SqlResourcesDeleteSqlStoredProcedureOptionalParams
): Promise<void>;
/**
* Gets the SQL userDefinedFunction under an existing Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param containerName Cosmos DB container name.
* @param userDefinedFunctionName Cosmos DB userDefinedFunction name.
* @param options The options parameters.
*/
getSqlUserDefinedFunction(
resourceGroupName: string,
accountName: string,
databaseName: string,
containerName: string,
userDefinedFunctionName: string,
options?: SqlResourcesGetSqlUserDefinedFunctionOptionalParams
): Promise<SqlResourcesGetSqlUserDefinedFunctionResponse>;
/**
* Create or update an Azure Cosmos DB SQL userDefinedFunction
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param containerName Cosmos DB container name.
* @param userDefinedFunctionName Cosmos DB userDefinedFunction name.
* @param createUpdateSqlUserDefinedFunctionParameters The parameters to provide for the current SQL
* userDefinedFunction.
* @param options The options parameters.
*/
beginCreateUpdateSqlUserDefinedFunction(
resourceGroupName: string,
accountName: string,
databaseName: string,
containerName: string,
userDefinedFunctionName: string,
createUpdateSqlUserDefinedFunctionParameters: SqlUserDefinedFunctionCreateUpdateParameters,
options?: SqlResourcesCreateUpdateSqlUserDefinedFunctionOptionalParams
): Promise<
PollerLike<
PollOperationState<
SqlResourcesCreateUpdateSqlUserDefinedFunctionResponse
>,
SqlResourcesCreateUpdateSqlUserDefinedFunctionResponse
>
>;
/**
* Create or update an Azure Cosmos DB SQL userDefinedFunction
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param containerName Cosmos DB container name.
* @param userDefinedFunctionName Cosmos DB userDefinedFunction name.
* @param createUpdateSqlUserDefinedFunctionParameters The parameters to provide for the current SQL
* userDefinedFunction.
* @param options The options parameters.
*/
beginCreateUpdateSqlUserDefinedFunctionAndWait(
resourceGroupName: string,
accountName: string,
databaseName: string,
containerName: string,
userDefinedFunctionName: string,
createUpdateSqlUserDefinedFunctionParameters: SqlUserDefinedFunctionCreateUpdateParameters,
options?: SqlResourcesCreateUpdateSqlUserDefinedFunctionOptionalParams
): Promise<SqlResourcesCreateUpdateSqlUserDefinedFunctionResponse>;
/**
* Deletes an existing Azure Cosmos DB SQL userDefinedFunction.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param containerName Cosmos DB container name.
* @param userDefinedFunctionName Cosmos DB userDefinedFunction name.
* @param options The options parameters.
*/
beginDeleteSqlUserDefinedFunction(
resourceGroupName: string,
accountName: string,
databaseName: string,
containerName: string,
userDefinedFunctionName: string,
options?: SqlResourcesDeleteSqlUserDefinedFunctionOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Deletes an existing Azure Cosmos DB SQL userDefinedFunction.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param containerName Cosmos DB container name.
* @param userDefinedFunctionName Cosmos DB userDefinedFunction name.
* @param options The options parameters.
*/
beginDeleteSqlUserDefinedFunctionAndWait(
resourceGroupName: string,
accountName: string,
databaseName: string,
containerName: string,
userDefinedFunctionName: string,
options?: SqlResourcesDeleteSqlUserDefinedFunctionOptionalParams
): Promise<void>;
/**
* Gets the SQL trigger under an existing Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param containerName Cosmos DB container name.
* @param triggerName Cosmos DB trigger name.
* @param options The options parameters.
*/
getSqlTrigger(
resourceGroupName: string,
accountName: string,
databaseName: string,
containerName: string,
triggerName: string,
options?: SqlResourcesGetSqlTriggerOptionalParams
): Promise<SqlResourcesGetSqlTriggerResponse>;
/**
* Create or update an Azure Cosmos DB SQL trigger
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param containerName Cosmos DB container name.
* @param triggerName Cosmos DB trigger name.
* @param createUpdateSqlTriggerParameters The parameters to provide for the current SQL trigger.
* @param options The options parameters.
*/
beginCreateUpdateSqlTrigger(
resourceGroupName: string,
accountName: string,
databaseName: string,
containerName: string,
triggerName: string,
createUpdateSqlTriggerParameters: SqlTriggerCreateUpdateParameters,
options?: SqlResourcesCreateUpdateSqlTriggerOptionalParams
): Promise<
PollerLike<
PollOperationState<SqlResourcesCreateUpdateSqlTriggerResponse>,
SqlResourcesCreateUpdateSqlTriggerResponse
>
>;
/**
* Create or update an Azure Cosmos DB SQL trigger
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param containerName Cosmos DB container name.
* @param triggerName Cosmos DB trigger name.
* @param createUpdateSqlTriggerParameters The parameters to provide for the current SQL trigger.
* @param options The options parameters.
*/
beginCreateUpdateSqlTriggerAndWait(
resourceGroupName: string,
accountName: string,
databaseName: string,
containerName: string,
triggerName: string,
createUpdateSqlTriggerParameters: SqlTriggerCreateUpdateParameters,
options?: SqlResourcesCreateUpdateSqlTriggerOptionalParams
): Promise<SqlResourcesCreateUpdateSqlTriggerResponse>;
/**
* Deletes an existing Azure Cosmos DB SQL trigger.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param containerName Cosmos DB container name.
* @param triggerName Cosmos DB trigger name.
* @param options The options parameters.
*/
beginDeleteSqlTrigger(
resourceGroupName: string,
accountName: string,
databaseName: string,
containerName: string,
triggerName: string,
options?: SqlResourcesDeleteSqlTriggerOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Deletes an existing Azure Cosmos DB SQL trigger.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param containerName Cosmos DB container name.
* @param triggerName Cosmos DB trigger name.
* @param options The options parameters.
*/
beginDeleteSqlTriggerAndWait(
resourceGroupName: string,
accountName: string,
databaseName: string,
containerName: string,
triggerName: string,
options?: SqlResourcesDeleteSqlTriggerOptionalParams
): Promise<void>;
} | the_stack |
export type RegistryCtor = new (url: string) => RegistryUrl;
export function lookup(url: string, registries: RegistryCtor[]):
| RegistryUrl
| undefined {
for (const R of registries) {
const u = new R(url);
if (u.regexp.test(url)) {
return u;
}
}
}
export interface RegistryUrl {
url: string;
// all versions of the url
all: () => Promise<string[]>;
// url at a given version
at(version: string): RegistryUrl;
// current version of url
version: () => string;
// is url valid for this RegistryUrl
regexp: RegExp;
}
export function defaultAt(that: RegistryUrl, version: string): string {
return that.url.replace(/@(.*?)(\/|$)/, `@${version}/`);
}
export function defaultVersion(that: RegistryUrl): string {
const v = that.url.match(/\@([^\/]+)[\/$]?/);
if (v === null) {
throw Error(`Unable to find version in ${that.url}`);
}
return v[1];
}
export function defaultName(that: RegistryUrl): string {
const n = that.url.match(/([^\/\"\']*?)\@[^\'\"]*/);
if (n === null) {
throw new Error(`Package name not found in ${that.url}`);
}
return n[1];
}
async function githubDownloadReleases(
owner: string,
repo: string,
lastVersion: string | undefined = undefined,
): Promise<string[]> {
let url = `https://github.com/${owner}/${repo}/releases.atom`;
if (lastVersion) {
url += `?after=${lastVersion}`;
}
// FIXME do we need to handle 404?
const page = await fetch(url);
const text = await page.text();
return [
...text.matchAll(
/\<id\>tag\:github\.com\,2008\:Repository\/\d+\/(.*?)\<\/id\>/g,
),
].map((x) => x[1]);
}
// export for testing purposes
// FIXME this should really be lazy, we shouldn't always iterate everything...
export const GR_CACHE: Map<string, string[]> = new Map<string, string[]>();
async function githubReleases(
owner: string,
repo: string,
cache: Map<string, string[]> = GR_CACHE,
): Promise<string[]> {
const cacheKey = `${owner}/${repo}`;
if (cache.has(cacheKey)) {
return cache.get(cacheKey)!;
}
const versions = await githubDownloadReleases(owner, repo);
if (versions.length === 10) {
let lastVersion: string | undefined = undefined;
// arbitrarily we're going to limit to 5 pages...?
let i = 0;
while (lastVersion !== versions[versions.length - 1] && i < 5) {
i++;
lastVersion = versions[versions.length - 1];
versions.push(...await githubDownloadReleases(owner, repo, lastVersion));
}
}
cache.set(cacheKey, versions);
return versions;
}
interface VersionsJson {
latest?: string;
versions?: string[];
}
const DL_CACHE: Map<string, string[]> = new Map<string, string[]>();
export class DenoLand implements RegistryUrl {
url: string;
constructor(url: string) {
this.url = url;
}
name(): string {
const [, stdGroup, xGroup] = this.url.match(
/deno\.land\/(?:(std)|x\/([^/@]*))/,
)!;
return stdGroup ?? xGroup;
}
async all(): Promise<string[]> {
const name = this.name();
if (DL_CACHE.has(name)) {
return DL_CACHE.get(name)!;
}
try {
const json: VersionsJson =
await (await fetch(`https://cdn.deno.land/${name}/meta/versions.json`))
.json();
if (!json.versions) {
throw new Error(`versions.json for ${name} has incorrect format`);
}
DL_CACHE.set(name, json.versions);
return json.versions;
} catch(err) {
// TODO this could be a permissions error e.g. no --allow-net...
throw new Error(`error getting versions for ${name}`);
}
}
at(version: string): RegistryUrl {
const url = defaultAt(this, version);
return new DenoLand(url);
}
version(): string {
return defaultVersion(this);
}
regexp = /https?:\/\/deno.land\/(?:std\@[^\'\"]*|x\/[^\/\"\']*?\@[^\'\"]*)/;
}
async function unpkgVersions(name: string): Promise<string[]> {
const page = await fetch(`https://unpkg.com/browse/${name}/`);
const text = await page.text();
// naively, we grab all the options
const m = [...text.matchAll(/\<option[^\<\>]* value\=\"(.*?)\"\>/g)];
m.reverse();
return m.map((x) => x[1]);
}
export class Unpkg implements RegistryUrl {
url: string;
name(): string {
return defaultName(this);
}
constructor(url: string) {
this.url = url;
}
async all(): Promise<string[]> {
return await unpkgVersions(this.name());
}
at(version: string): RegistryUrl {
const url = defaultAt(this, version);
return new Unpkg(url);
}
version(): string {
return defaultVersion(this);
}
regexp = /https?:\/\/unpkg.com\/[^\/\"\']*?\@[^\'\"]*/;
}
export class Jspm implements RegistryUrl {
url: string;
name(): string {
return defaultName(this);
}
constructor(url: string) {
this.url = url;
}
async all(): Promise<string[]> {
return await unpkgVersions(this.name());
}
at(version: string): RegistryUrl {
const url = defaultAt(this, version);
return new Jspm(url);
}
version(): string {
return defaultVersion(this);
}
regexp = /https?:\/\/dev.jspm.io\/[^\/\"\']*?\@[^\'\"]*/;
}
export class Denopkg implements RegistryUrl {
url: string;
owner(): string {
return this.url.split("/")[3];
}
repo(): string {
return defaultName(this);
}
constructor(url: string) {
this.url = url;
}
async all(): Promise<string[]> {
return await githubReleases(this.owner(), this.repo());
}
at(version: string): RegistryUrl {
const url = defaultAt(this, version);
return new Denopkg(url);
}
version(): string {
return defaultVersion(this);
}
regexp = /https?:\/\/denopkg.com\/[^\/\"\']*?\/[^\/\"\']*?\@[^\'\"]*/;
}
export class Pika implements RegistryUrl {
url: string;
name(): string {
return defaultName(this);
}
constructor(url: string) {
this.url = url;
}
async all(): Promise<string[]> {
return await unpkgVersions(this.name());
}
at(version: string): RegistryUrl {
const url = defaultAt(this, version);
return new Pika(url);
}
version(): string {
return defaultVersion(this);
}
regexp = /https?:\/\/cdn.pika.dev(\/\_)?\/[^\/\"\']*?\@[^\'\"]*/;
}
export class Skypack implements RegistryUrl {
url: string;
name(): string {
return defaultName(this);
}
constructor(url: string) {
this.url = url;
}
async all(): Promise<string[]> {
return await unpkgVersions(this.name());
}
at(version: string): RegistryUrl {
const url = defaultAt(this, version);
return new Skypack(url);
}
version(): string {
return defaultVersion(this);
}
regexp = /https?:\/\/cdn.skypack.dev(\/\_)?\/[^\/\"\']*?\@[^\'\"]*/;
}
export class GithubRaw implements RegistryUrl {
url: string;
constructor(url: string) {
this.url = url;
}
all(): Promise<string[]> {
const [, , , user, repo] = this.url.split("/");
return githubReleases(user, repo);
}
at(version: string): RegistryUrl {
const parts = this.url.split("/");
parts[5] = version;
return new GithubRaw(parts.join("/"));
}
version(): string {
const v = this.url.split("/")[5];
if (v === undefined) {
throw Error(`Unable to find version in ${this.url}`);
}
return v;
}
regexp =
/https?:\/\/raw\.githubusercontent\.com\/[^\/\"\']+\/[^\/\"\']+\/(?!master)[^\/\"\']+\/[^\'\"]*/;
}
export class JsDelivr implements RegistryUrl {
url: string;
constructor(url: string) {
this.url = url;
}
parts(): { parts: string[]; repo: string; user: string; version: string } {
const parts = this.url.split("/");
const [repo, version] = parts[5].split("@");
return {
user: parts[4],
repo,
version,
parts,
};
}
all(): Promise<string[]> {
const { user, repo } = this.parts();
return githubReleases(user, repo);
}
at(version: string): RegistryUrl {
const { parts, repo } = this.parts();
parts[5] = `${repo}@${version}`;
return new GithubRaw(parts.join("/"));
}
version(): string {
const { version } = this.parts();
if (version === undefined) {
throw Error(`Unable to find version in ${this.url}`);
}
return version;
}
regexp =
/https?:\/\/cdn\.jsdelivr\.net\/gh\/[^\/\"\']+\/[^\/\"\']+@(?!master)[^\/\"\']+\/[^\'\"]*/;
}
async function gitlabDownloadReleases(
owner: string,
repo: string,
page: number,
): Promise<string[]> {
const url =
`https://gitlab.com/${owner}/${repo}/-/tags?format=atom&page=${page}`;
const text = await (await fetch(url)).text();
return [
...text.matchAll(
/\<id\>https\:\/\/gitlab.com.+\/-\/tags\/(.+?)\<\/id\>/g,
),
].map((x) => x[1]);
}
// export for testing purposes
// FIXME this should really be lazy, we shouldn't always iterate everything...
export const GL_CACHE: Map<string, string[]> = new Map<string, string[]>();
async function gitlabReleases(
owner: string,
repo: string,
cache: Map<string, string[]> = GL_CACHE,
): Promise<string[]> {
const cacheKey = `${owner}/${repo}`;
if (cache.has(cacheKey)) {
return cache.get(cacheKey)!;
}
// to roughly match GitHub above (5 pages, 10 releases each), we'll
// limit to 3 pages, 20 releases each
let i = 1;
const versions = await gitlabDownloadReleases(owner, repo, i);
if (versions.length === 20) {
let lastVersion: string | undefined = undefined;
while (lastVersion !== versions[versions.length - 1] && i <= 3) {
i++;
lastVersion = versions[versions.length - 1];
versions.push(...await gitlabDownloadReleases(owner, repo, i));
}
}
cache.set(cacheKey, versions);
return versions;
}
export class GitlabRaw implements RegistryUrl {
url: string;
constructor(url: string) {
this.url = url;
}
all(): Promise<string[]> {
const [, , , user, repo] = this.url.split("/");
return gitlabReleases(user, repo);
}
at(version: string): RegistryUrl {
const parts = this.url.split("/");
parts[7] = version;
return new GithubRaw(parts.join("/"));
}
version(): string {
const v = this.url.split("/")[7];
if (v === undefined) {
throw Error(`Unable to find version in ${this.url}`);
}
return v;
}
regexp =
/https?:\/\/gitlab\.com\/[^\/\"\']+\/[^\/\"\']+\/-\/raw\/(?!master)[^\/\"\']+\/[^\'\"]*/;
}
interface NestLandResponse {
// a list of names of the form "<repo>@<version>"
packageUploadNames?: string[];
}
const NL_CACHE: Map<string, string[]> = new Map<string, string[]>();
async function nestlandReleases(
repo: string,
cache: Map<string, string[]> = NL_CACHE,
): Promise<string[]> {
if (cache.has(repo)) {
return cache.get(repo)!;
}
const url = `https://x.nest.land/api/package/${repo}`;
const { packageUploadNames }: NestLandResponse = await (await fetch(url))
.json();
if (!packageUploadNames) {
return [];
}
// reverse so newest versions are first
return packageUploadNames.map((name) => name.split("@")[1]).reverse();
}
export class NestLand implements RegistryUrl {
url: string;
constructor(url: string) {
this.url = url;
}
all(): Promise<string[]> {
const parts = this.url.split("/");
return nestlandReleases(parts[3].split("@")[0]);
}
at(version: string): RegistryUrl {
const url = defaultAt(this, version);
return new NestLand(url);
}
version(): string {
return defaultVersion(this);
}
regexp =
/https?:\/\/x\.nest\.land\/[^\/\"\']+@(?!master)[^\/\"\']+\/[^\'\"]*/;
}
export const REGISTRIES = [
DenoLand,
Unpkg,
Denopkg,
Jspm,
Pika,
Skypack,
GithubRaw,
GitlabRaw,
JsDelivr,
NestLand,
]; | the_stack |
import { CubicModelRendererConfigPub } from "../componentConfigs/CubicModelRendererConfig";
import CubicModelAsset from "../data/CubicModelAsset";
export default class CubicModelRendererEditor {
tbody: HTMLTableSectionElement;
projectClient: SupClient.ProjectClient;
editConfig: any;
cubicModelAssetId: string;
animationId: string;
shaderAssetId: string;
cubicModelFieldSubscriber: SupClient.table.AssetFieldSubscriber;
// animationSelectBox: HTMLSelectElement;
// horizontalFlipField: HTMLInputElement;
// verticalFlipField: HTMLInputElement;
// castShadowField: HTMLInputElement;
// receiveShadowField: HTMLInputElement;
// colorField: HTMLInputElement;
// colorPicker: HTMLInputElement;
// overrideOpacityField: HTMLInputElement;
// transparentField: HTMLInputElement;
// opacityField: HTMLInputElement;
// materialSelectBox: HTMLSelectElement;
// shaderTextField: HTMLInputElement;
// shaderButtonElt: HTMLButtonElement;
asset: CubicModelAsset;
constructor(tbody: HTMLTableSectionElement, config: CubicModelRendererConfigPub, projectClient: SupClient.ProjectClient, editConfig: any) {
this.tbody = tbody;
this.projectClient = projectClient;
this.editConfig = editConfig;
this.cubicModelAssetId = config.cubicModelAssetId;
// this.animationId = config.animationId;
// this.shaderAssetId = config.shaderAssetId;
const cubicModelRow = SupClient.table.appendRow(tbody, SupClient.i18n.t("componentEditors:CubicModelRenderer.cubicModel"));
this.cubicModelFieldSubscriber = SupClient.table.appendAssetField(cubicModelRow.valueCell, this.cubicModelAssetId, "cubicModel", projectClient);
this.cubicModelFieldSubscriber.on("select", (assetId: string) => {
this.editConfig("setProperty", "cubicModelAssetId", assetId);
// this.editConfig("setProperty", "animationId", null);
});
/*
const animationRow = SupClient.table.appendRow(tbody, "Animation");
this.animationSelectBox = SupClient.table.appendSelectBox(animationRow.valueCell, { "": "(None)" });
this.animationSelectBox.addEventListener("change", this._onChangeCubicModelAnimation);
this.animationSelectBox.disabled = true;
const flipRow = SupClient.table.appendRow(tbody, "Flip");
const flipDiv = document.createElement("div") as HTMLDivElement;
flipDiv.classList.add("inputs");
flipRow.valueCell.appendChild(flipDiv);
const horizontalSpan = document.createElement("span");
horizontalSpan.style.marginLeft = "5px";
horizontalSpan.textContent = "H";
flipDiv.appendChild(horizontalSpan);
this.horizontalFlipField = SupClient.table.appendBooleanField(flipDiv, config.horizontalFlip);
this.horizontalFlipField.addEventListener("change", (event: any) => {
this.editConfig("setProperty", "horizontalFlip", event.target.checked);
});
const verticalSpan = document.createElement("span");
verticalSpan.style.marginLeft = "5px";
verticalSpan.textContent = "V";
flipDiv.appendChild(verticalSpan);
this.verticalFlipField = SupClient.table.appendBooleanField(flipDiv, config.verticalFlip);
this.verticalFlipField.addEventListener("change", (event: any) => {
this.editConfig("setProperty", "verticalFlip", event.target.checked);
});
const shadowRow = SupClient.table.appendRow(tbody, "Shadow");
const shadowDiv = document.createElement("div") as HTMLDivElement;
shadowDiv.classList.add("inputs");
shadowRow.valueCell.appendChild(shadowDiv);
const castSpan = document.createElement("span");
castSpan.style.marginLeft = "5px";
castSpan.textContent = "Cast";
shadowDiv.appendChild(castSpan);
this.castShadowField = SupClient.table.appendBooleanField(shadowDiv, config.castShadow);
this.castShadowField.addEventListener("change", (event: any) => {
this.editConfig("setProperty", "castShadow", event.target.checked);
});
this.castShadowField.disabled = true;
const receiveSpan = document.createElement("span");
receiveSpan.style.marginLeft = "5px";
receiveSpan.textContent = "Receive";
shadowDiv.appendChild(receiveSpan);
this.receiveShadowField = SupClient.table.appendBooleanField(shadowDiv, config.receiveShadow);
this.receiveShadowField.addEventListener("change", (event: any) => {
this.editConfig("setProperty", "receiveShadow", event.target.checked);
});
this.receiveShadowField.disabled = true;
const colorRow = SupClient.table.appendRow(tbody, "Color");
const colorInputs = SupClient.table.appendColorField(colorRow.valueCell, config.color);
this.colorField = colorInputs.textField;
this.colorField.addEventListener("change", (event: any) => {
this.editConfig("setProperty", "color", event.target.value);
});
this.colorField.disabled = true;
this.colorPicker = colorInputs.pickerField;
this.colorPicker.addEventListener("change", (event: any) => {
this.editConfig("setProperty", "color", event.target.value.slice(1));
});
this.colorPicker.disabled = true;
const opacityRow = SupClient.table.appendRow(tbody, "Opacity", { checkbox: true } );
this.overrideOpacityField = opacityRow.checkbox;
this.overrideOpacityField.checked = config.overrideOpacity;
this.overrideOpacityField.addEventListener("change", (event: any) => {
this.editConfig("setProperty", "overrideOpacity", event.target.checked);
});
const opacityParent = document.createElement("div");
opacityParent.style.display = "flex";
opacityParent.style.alignItems = "center";
opacityRow.valueCell.appendChild(opacityParent);
this.transparentField = SupClient.table.appendBooleanField(<any>opacityParent, config.opacity != null);
this.transparentField.style.width = "50%";
this.transparentField.style.borderRight = "1px solid #ccc";
this.transparentField.addEventListener("change", (event: any) => {
const opacity = (event.target.checked) ? 1 : null;
this.editConfig("setProperty", "opacity", opacity);
});
this.transparentField.disabled = !config.overrideOpacity;
this.opacityField = SupClient.table.appendNumberField(<any>opacityParent, config.opacity, { min: 0, max: 1 });
this.opacityField.addEventListener("input", (event: any) => {
this.editConfig("setProperty", "opacity", parseFloat(event.target.value));
});
this.opacityField.step = "0.1";
this.opacityField.disabled = !config.overrideOpacity;
const materialRow = SupClient.table.appendRow(tbody, "Material");
this.materialSelectBox = SupClient.table.appendSelectBox(materialRow.valueCell, { "basic": "Basic", "phong": "Phong", "shader": "Shader" }, config.materialType);
this.materialSelectBox.addEventListener("change", (event: any) => {
this.editConfig("setProperty", "materialType", event.target.value);
})
this.materialSelectBox.disabled = true;
const shaderRow = SupClient.table.appendRow(tbody, "Shader");
const shaderFields = SupClient.table.appendAssetField(shaderRow.valueCell, "");
this.shaderTextField = shaderFields.textField;
this.shaderTextField.addEventListener("input", this._onChangeShaderAsset);
this.shaderTextField.disabled = true;
this.shaderButtonElt = shaderFields.buttonElt;
this.shaderButtonElt.addEventListener("click", (event) => {
SupClient.openEntry(this.shaderAssetId);
});
this.shaderButtonElt.disabled = this.shaderAssetId == null;
this._updateShaderField(config.materialType);*/
}
destroy() {
this.cubicModelFieldSubscriber.destroy();
if (this.cubicModelAssetId != null) this.projectClient.unsubAsset(this.cubicModelAssetId, this);
}
config_setProperty(path: string, value: any) {
if (this.projectClient.entries == null) return;
switch (path) {
case "cubicModelAssetId":
if (this.cubicModelAssetId != null) {
this.projectClient.unsubAsset(this.cubicModelAssetId, this);
this.asset = null;
}
this.cubicModelAssetId = value;
// this.animationSelectBox.disabled = true;
if (this.cubicModelAssetId != null) this.projectClient.subAsset(this.cubicModelAssetId, "cubicModel", this);
this.cubicModelFieldSubscriber.onChangeAssetId(this.cubicModelAssetId);
break;
/*case "animationId":
if (!this.animationSelectBox.disabled) this.animationSelectBox.value = (value != null) ? value : "";
this.animationId = value;
break;
case "horizontalFlip":
this.horizontalFlipField.checked = value;
break;
case "verticalFlip":
this.verticalFlipField.checked = value;
break;
case "castShadow":
this.castShadowField.checked = value;
break;
case "receiveShadow":
this.receiveShadowField.checked = value;
break;
case "color":
this.colorField.value = value;
this.colorPicker.value = `#${value}`;
break;
case "overrideOpacity":
this.overrideOpacityField.checked = value;
this.transparentField.disabled = !value;
this.transparentField.checked = false;
this.opacityField.value = null;
this.opacityField.disabled = true;
break;
case "opacity":
this.transparentField.checked = value != null;
this.opacityField.disabled = value == null;
this.opacityField.value = value;
break;
case "materialType":
this.materialSelectBox.value = value;
this._updateShaderField(value);
break;
case "shaderAssetId":
this.shaderAssetId = value;
this.shaderButtonElt.disabled = this.shaderAssetId == null;
if (value != null) this.shaderTextField.value = this.projectClient.entries.getPathFromId(value);
else this.shaderTextField.value = "";
break;*/
}
}
// Network callbacks
onAssetReceived(assetId: string, asset: any) {
if (assetId !== this.cubicModelAssetId) return;
this.asset = asset;
/*
this._clearAnimations();
for (const animation of this.asset.pub.animations) {
SupClient.table.appendSelectOption(this.animationSelectBox, animation.id, animation.name);
}
this.animationSelectBox.value = (this.animationId != null) ? this.animationId : "";
this.animationSelectBox.disabled = false;*/
}
onAssetEdited(assetId: string, command: string, ...args: any[]) {
if (assetId !== this.cubicModelAssetId) return;
if (command.indexOf("Animation") === -1) return;
/*const animationId = this.animationSelectBox.value;
this._clearAnimations();
for (const animation of this.asset.pub.animations) {
SupClient.table.appendSelectOption(this.animationSelectBox, animation.id, animation.name);
}
if (animationId != null && this.asset.animations.byId[animationId] != null) this.animationSelectBox.value = animationId;
else this.editConfig("setProperty", "animationId", "");*/
}
onAssetTrashed() {
this.asset = null;
this.clearAnimations();
// this.animationSelectBox.value = "";
// this.animationSelectBox.disabled = true;
}
// User interface
private clearAnimations() {
/*while (true) {
const child = this.animationSelectBox.children[1];
if (child == null) break;
this.animationSelectBox.removeChild(child);
}*/
}
// private updateShaderField(materialType: string) {
// const shaderRow = this.shaderTextField.parentElement.parentElement.parentElement;
// if (materialType === "shader") {
// if (shaderRow.parentElement == null) this.tbody.appendChild(shaderRow);
// } else if (shaderRow.parentElement != null) shaderRow.parentElement.removeChild(shaderRow);
// }
// private onChangeCubicModelAnimation = (event: any) => {
// const animationId = (event.target.value === "") ? null : event.target.value;
// this.editConfig("setProperty", "animationId", animationId);
// };
// private onChangeShaderAsset = (event: any) => {
// if (event.target.value === "") this.editConfig("setProperty", "shaderAssetId", null);
// else {
// const entry = SupClient.findEntryByPath(this.projectClient.entries.pub, event.target.value);
// if (entry != null && entry.type === "shader") this.editConfig("setProperty", "shaderAssetId", entry.id);
// }
// };
} | the_stack |
import { CoreFilepool } from '@services/filepool';
import { CoreFileSizeSum, CorePluginFileDelegate } from '@services/plugin-file-delegate';
import { CoreSites } from '@services/sites';
import { CoreWSFile } from '@services/ws';
import { CoreCourse, CoreCourseAnyModuleData, CoreCourseModuleContentFile } from '../services/course';
import { CoreCourseModulePrefetchHandler } from '../services/module-prefetch-delegate';
/**
* Base prefetch handler to be registered in CoreCourseModulePrefetchDelegate. Prefetch handlers should inherit either
* from CoreCourseModuleActivityPrefetchHandlerBase or CoreCourseModuleResourcePrefetchHandlerBase, depending on whether
* they are an activity or a resource. It's not recommended to inherit from this class directly.
*/
export class CoreCourseModulePrefetchHandlerBase implements CoreCourseModulePrefetchHandler {
/**
* Name of the handler.
*/
name = 'CoreCourseModulePrefetchHandler';
/**
* Name of the module. It should match the "modname" of the module returned in core_course_get_contents.
*/
modName = 'default';
/**
* The handler's component.
*/
component = 'core_module';
/**
* The RegExp to check updates. If a module has an update whose name matches this RegExp, the module will be marked
* as outdated. This RegExp is ignored if hasUpdates function is defined.
*/
updatesNames = /^.*files$/;
/**
* If true, this module will be ignored when determining the status of a list of modules. The module will
* still be downloaded when downloading the section/course, it only affects whether the button should be displayed.
*/
skipListStatus = false;
/**
* List of download promises to prevent downloading the module twice at the same time.
*/
protected downloadPromises: { [s: string]: { [s: string]: Promise<void> } } = {};
/**
* Add an ongoing download to the downloadPromises list. When the promise finishes it will be removed.
*
* @param id Unique identifier per component.
* @param promise Promise to add.
* @param siteId Site ID. If not defined, current site.
* @return Promise of the current download.
*/
async addOngoingDownload(id: number, promise: Promise<void>, siteId?: string): Promise<void> {
siteId = siteId || CoreSites.getCurrentSiteId();
const uniqueId = this.getUniqueId(id);
if (!this.downloadPromises[siteId]) {
this.downloadPromises[siteId] = {};
}
this.downloadPromises[siteId][uniqueId] = promise;
try {
return await this.downloadPromises[siteId][uniqueId];
} finally {
delete this.downloadPromises[siteId][uniqueId];
}
}
/**
* Download the module.
*
* @param module The module object returned by WS.
* @param courseId Course ID.
* @param dirPath Path of the directory where to store all the content files.
* @return Promise resolved when all content is downloaded.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async download(module: CoreCourseAnyModuleData, courseId: number, dirPath?: string): Promise<void> {
// To be overridden.
return;
}
/**
* Returns a list of content files that can be downloaded.
*
* @param module The module object returned by WS.
* @return List of files.
*/
getContentDownloadableFiles(module: CoreCourseAnyModuleData): CoreCourseModuleContentFile[] {
if (!module.contents?.length) {
return [];
}
return module.contents.filter((content) => this.isFileDownloadable(content));
}
/**
* Get the download size of a module.
*
* @param module Module.
* @param courseId Course ID the module belongs to.
* @param single True if we're downloading a single module, false if we're downloading a whole section.
* @return Promise resolved with the size.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async getDownloadSize(module: CoreCourseAnyModuleData, courseId: number, single?: boolean): Promise<CoreFileSizeSum> {
try {
const files = await this.getFiles(module, courseId);
return await CorePluginFileDelegate.getFilesDownloadSize(files);
} catch {
return { size: -1, total: false };
}
}
/**
* Get the downloaded size of a module. If not defined, we'll use getFiles to calculate it (it can be slow).
*
* @param module Module.
* @param courseId Course ID the module belongs to.
* @return Size, or promise resolved with the size.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async getDownloadedSize(module: CoreCourseAnyModuleData, courseId: number): Promise<number> {
const siteId = CoreSites.getCurrentSiteId();
return CoreFilepool.getFilesSizeByComponent(siteId, this.component, module.id);
}
/**
* Get list of files. If not defined, we'll assume they're in module.contents.
*
* @param module Module.
* @param courseId Course ID the module belongs to.
* @param single True if we're downloading a single module, false if we're downloading a whole section.
* @return Promise resolved with the list of files.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async getFiles(module: CoreCourseAnyModuleData, courseId: number, single?: boolean): Promise<CoreWSFile[]> {
// To be overridden.
return [];
}
/**
* Returns module intro files.
*
* @param module The module object returned by WS.
* @param courseId Course ID.
* @param ignoreCache True if it should ignore cached data (it will always fail in offline or server down).
* @return Promise resolved with list of intro files.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async getIntroFiles(module: CoreCourseAnyModuleData, courseId: number, ignoreCache?: boolean): Promise<CoreWSFile[]> {
return this.getIntroFilesFromInstance(module);
}
/**
* Returns module intro files from instance.
*
* @param module The module object returned by WS.
* @param instance The instance to get the intro files (book, assign, ...). If not defined, module will be used.
* @return List of intro files.
*/
getIntroFilesFromInstance(module: CoreCourseAnyModuleData, instance?: ModuleInstance): CoreWSFile[] {
if (instance) {
if (typeof instance.introfiles != 'undefined') {
return instance.introfiles;
} else if (instance.intro) {
return CoreFilepool.extractDownloadableFilesFromHtmlAsFakeFileObjects(instance.intro);
}
}
if ('description' in module && module.description) {
return CoreFilepool.extractDownloadableFilesFromHtmlAsFakeFileObjects(module.description);
}
return [];
}
/**
* If there's an ongoing download for a certain identifier return it.
*
* @param id Unique identifier per component.
* @param siteId Site ID. If not defined, current site.
* @return Promise of the current download.
*/
async getOngoingDownload(id: number, siteId?: string): Promise<void> {
siteId = siteId || CoreSites.getCurrentSiteId();
if (this.isDownloading(id, siteId)) {
// There's already a download ongoing, return the promise.
return this.downloadPromises[siteId][this.getUniqueId(id)];
}
}
/**
* Create unique identifier using component and id.
*
* @param id Unique ID inside component.
* @return Unique ID.
*/
getUniqueId(id: number): string {
return this.component + '#' + id;
}
/**
* Invalidate the prefetched content.
*
* @param moduleId The module ID.
* @param courseId The course ID the module belongs to.
* @return Promise resolved when the data is invalidated.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async invalidateContent(moduleId: number, courseId: number): Promise<void> {
// To be overridden.
return;
}
/**
* Invalidate WS calls needed to determine module status (usually, to check if module is downloadable).
* It doesn't need to invalidate check updates. It should NOT invalidate files nor all the prefetched data.
*
* @param module Module.
* @param courseId Course ID the module belongs to.
* @return Promise resolved when invalidated.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
invalidateModule(module: CoreCourseAnyModuleData, courseId: number): Promise<void> {
return CoreCourse.invalidateModule(module.id);
}
/**
* Check if a module can be downloaded. If the function is not defined, we assume that all modules are downloadable.
*
* @param module Module.
* @param courseId Course ID the module belongs to.
* @return Whether the module can be downloaded. The promise should never be rejected.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async isDownloadable(module: CoreCourseAnyModuleData, courseId: number): Promise<boolean> {
// By default, mark all instances as downloadable.
return true;
}
/**
* Check if a there's an ongoing download for the given identifier.
*
* @param id Unique identifier per component.
* @param siteId Site ID. If not defined, current site.
* @return True if downloading, false otherwise.
*/
isDownloading(id: number, siteId?: string): boolean {
siteId = siteId || CoreSites.getCurrentSiteId();
return !!(this.downloadPromises[siteId] && this.downloadPromises[siteId][this.getUniqueId(id)]);
}
/**
* Whether or not the handler is enabled on a site level.
*
* @return A boolean, or a promise resolved with a boolean, indicating if the handler is enabled.
*/
async isEnabled(): Promise<boolean> {
return true;
}
/**
* Check if a file is downloadable.
*
* @param file File to check.
* @return Whether the file is downloadable.
*/
isFileDownloadable(file: CoreCourseModuleContentFile): boolean {
return file.type === 'file';
}
/**
* Load module contents into module.contents if they aren't loaded already.
*
* @param module Module to load the contents.
* @param courseId The course ID. Recommended to speed up the process and minimize data usage.
* @param ignoreCache True if it should ignore cached data (it will always fail in offline or server down).
* @return Promise resolved when loaded.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async loadContents(module: CoreCourseAnyModuleData, courseId: number, ignoreCache?: boolean): Promise<void> {
// To be overridden.
return;
}
/**
* Prefetch a module.
*
* @param module Module.
* @param courseId Course ID the module belongs to.
* @param single True if we're downloading a single module, false if we're downloading a whole section.
* @param dirPath Path of the directory where to store all the content files.
* @return Promise resolved when done.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async prefetch(module: CoreCourseAnyModuleData, courseId?: number, single?: boolean, dirPath?: string): Promise<void> {
// To be overridden.
return;
}
/**
* Remove module downloaded files. If not defined, we'll use getFiles to remove them (slow).
*
* @param module Module.
* @param courseId Course ID the module belongs to.
* @return Promise resolved when done.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
removeFiles(module: CoreCourseAnyModuleData, courseId: number): Promise<void> {
return CoreFilepool.removeFilesByComponent(CoreSites.getCurrentSiteId(), this.component, module.id);
}
}
/**
* Properties a module instance should have to be able to retrieve its intro files.
*/
type ModuleInstance = {
introfiles?: CoreWSFile[];
intro?: string;
}; | the_stack |
'use strict';
// tslint:disable no-unused-expression
import * as vscode from 'vscode';
import * as chai from 'chai';
import * as sinon from 'sinon';
import * as sinonChai from 'sinon-chai';
import { TestUtil } from '../TestUtil';
import { VSCodeBlockchainOutputAdapter } from '../../extension/logging/VSCodeBlockchainOutputAdapter';
import { ExtensionCommands } from '../../ExtensionCommands';
import { VSCodeBlockchainDockerOutputAdapter } from '../../extension/logging/VSCodeBlockchainDockerOutputAdapter';
import { FabricEnvironmentConnection } from 'ibm-blockchain-platform-environment-v1';
import { Reporter } from '../../extension/util/Reporter';
import { FabricEnvironmentManager, ConnectedState } from '../../extension/fabric/environments/FabricEnvironmentManager';
import { FabricEnvironmentRegistryEntry, FabricRuntimeUtil, LogType, EnvironmentType, FabricSmartContractDefinition } from 'ibm-blockchain-platform-common';
import { SettingConfigurations } from '../../extension/configurations';
import { ExtensionUtil } from '../../extension/util/ExtensionUtil';
chai.use(sinonChai);
describe('ApproveCommand', () => {
const mySandBox: sinon.SinonSandbox = sinon.createSandbox();
before(async () => {
await TestUtil.setupTests(mySandBox);
});
describe('approveSmartContract', () => {
let fabricRuntimeMock: sinon.SinonStubbedInstance<FabricEnvironmentConnection>;
let executeCommandStub: sinon.SinonStub;
let logSpy: sinon.SinonSpy;
let dockerLogsOutputSpy: sinon.SinonSpy;
let sendTelemetryEventStub: sinon.SinonStub;
let environmentConnectionStub: sinon.SinonStub;
let environmentRegistryStub: sinon.SinonStub;
let getSettingsStub: sinon.SinonStub;
let getConfigurationStub: sinon.SinonStub;
beforeEach(async () => {
executeCommandStub = mySandBox.stub(vscode.commands, 'executeCommand');
executeCommandStub.withArgs(ExtensionCommands.CONNECT_TO_ENVIRONMENT).resolves();
executeCommandStub.withArgs(ExtensionCommands.REFRESH_GATEWAYS).resolves();
executeCommandStub.withArgs(ExtensionCommands.REFRESH_ENVIRONMENTS).resolves();
executeCommandStub.callThrough();
fabricRuntimeMock = mySandBox.createStubInstance(FabricEnvironmentConnection);
fabricRuntimeMock.connect.resolves();
fabricRuntimeMock.approveSmartContractDefinition.resolves(true);
getSettingsStub = mySandBox.stub();
getSettingsStub.withArgs(SettingConfigurations.FABRIC_CLIENT_TIMEOUT).returns(9000);
getConfigurationStub = mySandBox.stub(vscode.workspace, 'getConfiguration');
getConfigurationStub.returns({
get: getSettingsStub,
update: mySandBox.stub().callThrough()
});
environmentConnectionStub = mySandBox.stub(FabricEnvironmentManager.instance(), 'getConnection').returns((fabricRuntimeMock));
const environmentRegistryEntry: FabricEnvironmentRegistryEntry = new FabricEnvironmentRegistryEntry();
environmentRegistryEntry.name = FabricRuntimeUtil.LOCAL_FABRIC;
environmentRegistryEntry.managedRuntime = true;
environmentRegistryEntry.environmentType = EnvironmentType.LOCAL_MICROFAB_ENVIRONMENT;
environmentRegistryStub = mySandBox.stub(FabricEnvironmentManager.instance(), 'getEnvironmentRegistryEntry').returns(environmentRegistryEntry);
mySandBox.stub(FabricEnvironmentManager.instance(), 'getState').returns(ConnectedState.CONNECTED);
logSpy = mySandBox.spy(VSCodeBlockchainOutputAdapter.instance(), 'log');
dockerLogsOutputSpy = mySandBox.spy(VSCodeBlockchainDockerOutputAdapter.instance(FabricRuntimeUtil.LOCAL_FABRIC), 'show');
sendTelemetryEventStub = mySandBox.stub(Reporter.instance(), 'sendTelemetryEvent');
});
afterEach(async () => {
mySandBox.restore();
});
it('should approve the smart contract through the command', async () => {
const orgMap: Map<string, string[]> = new Map<string, string[]>();
orgMap.set('Org1MSP', ['peerOne']);
orgMap.set('Org2MSP', ['peerTwo', 'peerThree']);
await vscode.commands.executeCommand(ExtensionCommands.APPROVE_SMART_CONTRACT, 'myOrderer', 'mychannel', orgMap, new FabricSmartContractDefinition('mySmartContract', '0.0.1', 1, 'myPackageId'));
fabricRuntimeMock.approveSmartContractDefinition.getCall(0).should.have.been.calledWithExactly('myOrderer', 'mychannel', ['peerOne'], new FabricSmartContractDefinition('mySmartContract', '0.0.1', 1, 'myPackageId'), 9000000);
fabricRuntimeMock.approveSmartContractDefinition.getCall(1).should.have.been.calledWithExactly('myOrderer', 'mychannel', ['peerTwo', 'peerThree'], new FabricSmartContractDefinition('mySmartContract', '0.0.1', 1, 'myPackageId'), 9000000);
dockerLogsOutputSpy.should.have.been.called;
logSpy.getCall(0).should.have.been.calledWith(LogType.INFO, undefined, 'approveSmartContract');
logSpy.getCall(1).should.have.been.calledWith(LogType.SUCCESS, 'Successfully approved smart contract definition');
executeCommandStub.should.have.been.calledWith(ExtensionCommands.REFRESH_GATEWAYS);
executeCommandStub.should.have.been.calledWith(ExtensionCommands.REFRESH_ENVIRONMENTS);
sendTelemetryEventStub.should.have.been.calledOnceWithExactly('approveCommand');
});
it('should approve the smart contract through the command when timeout is not provided in user settings', async () => {
const orgMap: Map<string, string[]> = new Map<string, string[]>();
orgMap.set('Org1MSP', ['peerOne']);
orgMap.set('Org2MSP', ['peerTwo', 'peerThree']);
getSettingsStub.withArgs(SettingConfigurations.FABRIC_CLIENT_TIMEOUT).returns(undefined);
getConfigurationStub.returns({
get: getSettingsStub,
update: mySandBox.stub().callThrough()
});
await vscode.commands.executeCommand(ExtensionCommands.APPROVE_SMART_CONTRACT, 'myOrderer', 'mychannel', orgMap, new FabricSmartContractDefinition('mySmartContract', '0.0.1', 1, 'myPackageId'));
fabricRuntimeMock.approveSmartContractDefinition.getCall(0).should.have.been.calledWithExactly('myOrderer', 'mychannel', ['peerOne'], new FabricSmartContractDefinition('mySmartContract', '0.0.1', 1, 'myPackageId'), undefined);
fabricRuntimeMock.approveSmartContractDefinition.getCall(1).should.have.been.calledWithExactly('myOrderer', 'mychannel', ['peerTwo', 'peerThree'], new FabricSmartContractDefinition('mySmartContract', '0.0.1', 1, 'myPackageId'), undefined);
dockerLogsOutputSpy.should.have.been.called;
logSpy.getCall(0).should.have.been.calledWith(LogType.INFO, undefined, 'approveSmartContract');
logSpy.getCall(1).should.have.been.calledWith(LogType.SUCCESS, 'Successfully approved smart contract definition');
executeCommandStub.should.have.been.calledWith(ExtensionCommands.REFRESH_GATEWAYS);
executeCommandStub.should.have.been.calledWith(ExtensionCommands.REFRESH_ENVIRONMENTS);
sendTelemetryEventStub.should.have.been.calledOnceWithExactly('approveCommand');
});
it('should approve the smart contract through the command with endorsement policy', async () => {
const orgMap: Map<string, string[]> = new Map<string, string[]>();
orgMap.set('Org1MSP', ['peerOne']);
await vscode.commands.executeCommand(ExtensionCommands.APPROVE_SMART_CONTRACT, 'myOrderer', 'mychannel', orgMap, new FabricSmartContractDefinition('mySmartContract', '0.0.1', 1, 'myPackageId', `OR('Org1.member', 'Org2.member')`));
fabricRuntimeMock.approveSmartContractDefinition.should.have.been.calledOnceWithExactly('myOrderer', 'mychannel', ['peerOne'], new FabricSmartContractDefinition('mySmartContract', '0.0.1', 1, 'myPackageId', `OR('Org1.member', 'Org2.member')`), 9000000);
dockerLogsOutputSpy.should.have.been.called;
logSpy.getCall(0).should.have.been.calledWith(LogType.INFO, undefined, 'approveSmartContract');
logSpy.getCall(1).should.have.been.calledWith(LogType.SUCCESS, 'Successfully approved smart contract definition');
executeCommandStub.should.have.been.calledWith(ExtensionCommands.REFRESH_GATEWAYS);
executeCommandStub.should.have.been.calledWith(ExtensionCommands.REFRESH_ENVIRONMENTS);
sendTelemetryEventStub.should.have.been.calledOnceWithExactly('approveCommand');
});
it('should approve the smart contract through the command when not connected', async () => {
const orgMap: Map<string, string[]> = new Map<string, string[]>();
orgMap.set('Org1MSP', ['peerOne']);
environmentConnectionStub.resetHistory();
environmentConnectionStub.onFirstCall().returns(undefined);
await vscode.commands.executeCommand(ExtensionCommands.APPROVE_SMART_CONTRACT, 'myOrderer', 'mychannel', orgMap, new FabricSmartContractDefinition('mySmartContract', '0.0.1', 1, 'myPackageId'));
fabricRuntimeMock.approveSmartContractDefinition.should.have.been.calledWithExactly('myOrderer', 'mychannel', ['peerOne'], new FabricSmartContractDefinition('mySmartContract', '0.0.1', 1, 'myPackageId'), 9000000);
dockerLogsOutputSpy.should.have.been.called;
logSpy.getCall(0).should.have.been.calledWith(LogType.INFO, undefined, 'approveSmartContract');
logSpy.getCall(1).should.have.been.calledWith(LogType.SUCCESS, 'Successfully approved smart contract definition');
executeCommandStub.should.have.been.calledWith(ExtensionCommands.CONNECT_TO_ENVIRONMENT);
executeCommandStub.should.have.been.calledWith(ExtensionCommands.REFRESH_GATEWAYS);
executeCommandStub.should.have.been.calledWith(ExtensionCommands.REFRESH_ENVIRONMENTS);
sendTelemetryEventStub.should.have.been.calledOnceWithExactly('approveCommand');
});
it('should not show docker logs if not managed runtime', async () => {
const orgMap: Map<string, string[]> = new Map<string, string[]>();
orgMap.set('Org1MSP', ['peerOne']);
const registryEntry: FabricEnvironmentRegistryEntry = new FabricEnvironmentRegistryEntry();
registryEntry.name = 'myFabric';
registryEntry.managedRuntime = false;
environmentRegistryStub.returns(registryEntry);
await vscode.commands.executeCommand(ExtensionCommands.APPROVE_SMART_CONTRACT, 'myOrderer', 'mychannel', orgMap, new FabricSmartContractDefinition('mySmartContract', '0.0.1', 1, 'myPackageId'));
fabricRuntimeMock.approveSmartContractDefinition.should.have.been.calledWithExactly('myOrderer', 'mychannel', ['peerOne'], new FabricSmartContractDefinition('mySmartContract', '0.0.1', 1, 'myPackageId'), 9000000);
dockerLogsOutputSpy.should.not.have.been.called;
logSpy.getCall(0).should.have.been.calledWith(LogType.INFO, undefined, 'approveSmartContract');
logSpy.getCall(1).should.have.been.calledWith(LogType.SUCCESS, 'Successfully approved smart contract definition');
executeCommandStub.should.have.been.calledWith(ExtensionCommands.REFRESH_GATEWAYS);
executeCommandStub.should.have.been.calledWith(ExtensionCommands.REFRESH_ENVIRONMENTS);
sendTelemetryEventStub.should.have.been.calledOnceWithExactly('approveCommand');
});
it('should return if no connection', async () => {
const orgMap: Map<string, string[]> = new Map<string, string[]>();
orgMap.set('Org1MSP', ['peerOne']);
environmentConnectionStub.returns(undefined);
await vscode.commands.executeCommand(ExtensionCommands.APPROVE_SMART_CONTRACT, 'myOrderer', 'mychannel', orgMap, new FabricSmartContractDefinition('mySmartContract', '0.0.1', 1, 'myPackageId'));
fabricRuntimeMock.approveSmartContractDefinition.should.not.have.been.called;
logSpy.getCall(0).should.have.been.calledWith(LogType.INFO, undefined, 'approveSmartContract');
});
it('should handle error from approving smart contract', async () => {
const orgMap: Map<string, string[]> = new Map<string, string[]>();
orgMap.set('Org1MSP', ['peerOne']);
const error: Error = new Error('some error');
fabricRuntimeMock.approveSmartContractDefinition.throws(error);
await ExtensionUtil.executeCommandInternal(ExtensionCommands.APPROVE_SMART_CONTRACT, 'myOrderer', 'mychannel', orgMap, new FabricSmartContractDefinition('mySmartContract', '0.0.1', 1, 'myPackageId')).should.eventually.be.rejectedWith(/some error/);
fabricRuntimeMock.approveSmartContractDefinition.should.have.been.calledWithExactly('myOrderer', 'mychannel', ['peerOne'], new FabricSmartContractDefinition('mySmartContract', '0.0.1', 1, 'myPackageId'), 9000000);
dockerLogsOutputSpy.should.have.been.called;
logSpy.getCall(0).should.have.been.calledWith(LogType.INFO, undefined, 'approveSmartContract');
logSpy.getCall(1).should.have.been.calledWith(LogType.ERROR, `Error approving smart contract: ${error.message}`, `Error approving smart contract: ${error.toString()}`);
sendTelemetryEventStub.should.not.have.been.called;
});
it('should inform user if smart contract already approved and ready for commit', async () => {
const orgMap: Map<string, string[]> = new Map<string, string[]>();
orgMap.set('Org1MSP', ['peerOne']);
environmentConnectionStub.resetHistory();
environmentConnectionStub.onFirstCall().returns(undefined);
fabricRuntimeMock.approveSmartContractDefinition.resolves(false);
await vscode.commands.executeCommand(ExtensionCommands.APPROVE_SMART_CONTRACT, 'myOrderer', 'mychannel', orgMap, new FabricSmartContractDefinition('mySmartContract', '0.0.1', 1, 'myPackageId'));
fabricRuntimeMock.approveSmartContractDefinition.should.have.been.calledWithExactly('myOrderer', 'mychannel', ['peerOne'], new FabricSmartContractDefinition('mySmartContract', '0.0.1', 1, 'myPackageId'), 9000000);
dockerLogsOutputSpy.should.have.been.called;
logSpy.getCall(0).should.have.been.calledWith(LogType.INFO, undefined, 'approveSmartContract');
logSpy.getCall(1).should.have.been.calledWith(LogType.INFO, 'Smart contract definition alreay approved by organisation Org1MSP');
executeCommandStub.should.have.been.calledWith(ExtensionCommands.CONNECT_TO_ENVIRONMENT);
executeCommandStub.should.have.not.been.calledWith(ExtensionCommands.REFRESH_GATEWAYS);
executeCommandStub.should.have.not.been.calledWith(ExtensionCommands.REFRESH_ENVIRONMENTS);
sendTelemetryEventStub.should.have.been.calledOnceWithExactly('approveCommand');
});
});
}); | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { Tasks } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { SecurityCenter } from "../securityCenter";
import {
SecurityTask,
TasksListNextOptionalParams,
TasksListOptionalParams,
TasksListByHomeRegionNextOptionalParams,
TasksListByHomeRegionOptionalParams,
TasksListByResourceGroupNextOptionalParams,
TasksListByResourceGroupOptionalParams,
TasksListResponse,
TasksListByHomeRegionResponse,
TasksGetSubscriptionLevelTaskOptionalParams,
TasksGetSubscriptionLevelTaskResponse,
Enum15,
TasksUpdateSubscriptionLevelTaskStateOptionalParams,
TasksListByResourceGroupResponse,
TasksGetResourceGroupLevelTaskOptionalParams,
TasksGetResourceGroupLevelTaskResponse,
TasksUpdateResourceGroupLevelTaskStateOptionalParams,
TasksListNextResponse,
TasksListByHomeRegionNextResponse,
TasksListByResourceGroupNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing Tasks operations. */
export class TasksImpl implements Tasks {
private readonly client: SecurityCenter;
/**
* Initialize a new instance of the class Tasks class.
* @param client Reference to the service client
*/
constructor(client: SecurityCenter) {
this.client = client;
}
/**
* Recommended tasks that will help improve the security of the subscription proactively
* @param options The options parameters.
*/
public list(
options?: TasksListOptionalParams
): PagedAsyncIterableIterator<SecurityTask> {
const iter = this.listPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listPagingPage(options);
}
};
}
private async *listPagingPage(
options?: TasksListOptionalParams
): AsyncIterableIterator<SecurityTask[]> {
let result = await this._list(options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listNext(continuationToken, options);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listPagingAll(
options?: TasksListOptionalParams
): AsyncIterableIterator<SecurityTask> {
for await (const page of this.listPagingPage(options)) {
yield* page;
}
}
/**
* Recommended tasks that will help improve the security of the subscription proactively
* @param options The options parameters.
*/
public listByHomeRegion(
options?: TasksListByHomeRegionOptionalParams
): PagedAsyncIterableIterator<SecurityTask> {
const iter = this.listByHomeRegionPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByHomeRegionPagingPage(options);
}
};
}
private async *listByHomeRegionPagingPage(
options?: TasksListByHomeRegionOptionalParams
): AsyncIterableIterator<SecurityTask[]> {
let result = await this._listByHomeRegion(options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByHomeRegionNext(continuationToken, options);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByHomeRegionPagingAll(
options?: TasksListByHomeRegionOptionalParams
): AsyncIterableIterator<SecurityTask> {
for await (const page of this.listByHomeRegionPagingPage(options)) {
yield* page;
}
}
/**
* Recommended tasks that will help improve the security of the subscription proactively
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param options The options parameters.
*/
public listByResourceGroup(
resourceGroupName: string,
options?: TasksListByResourceGroupOptionalParams
): PagedAsyncIterableIterator<SecurityTask> {
const iter = this.listByResourceGroupPagingAll(resourceGroupName, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByResourceGroupPagingPage(resourceGroupName, options);
}
};
}
private async *listByResourceGroupPagingPage(
resourceGroupName: string,
options?: TasksListByResourceGroupOptionalParams
): AsyncIterableIterator<SecurityTask[]> {
let result = await this._listByResourceGroup(resourceGroupName, options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByResourceGroupNext(
resourceGroupName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByResourceGroupPagingAll(
resourceGroupName: string,
options?: TasksListByResourceGroupOptionalParams
): AsyncIterableIterator<SecurityTask> {
for await (const page of this.listByResourceGroupPagingPage(
resourceGroupName,
options
)) {
yield* page;
}
}
/**
* Recommended tasks that will help improve the security of the subscription proactively
* @param options The options parameters.
*/
private _list(options?: TasksListOptionalParams): Promise<TasksListResponse> {
return this.client.sendOperationRequest({ options }, listOperationSpec);
}
/**
* Recommended tasks that will help improve the security of the subscription proactively
* @param options The options parameters.
*/
private _listByHomeRegion(
options?: TasksListByHomeRegionOptionalParams
): Promise<TasksListByHomeRegionResponse> {
return this.client.sendOperationRequest(
{ options },
listByHomeRegionOperationSpec
);
}
/**
* Recommended tasks that will help improve the security of the subscription proactively
* @param taskName Name of the task object, will be a GUID
* @param options The options parameters.
*/
getSubscriptionLevelTask(
taskName: string,
options?: TasksGetSubscriptionLevelTaskOptionalParams
): Promise<TasksGetSubscriptionLevelTaskResponse> {
return this.client.sendOperationRequest(
{ taskName, options },
getSubscriptionLevelTaskOperationSpec
);
}
/**
* Recommended tasks that will help improve the security of the subscription proactively
* @param taskName Name of the task object, will be a GUID
* @param taskUpdateActionType Type of the action to do on the task
* @param options The options parameters.
*/
updateSubscriptionLevelTaskState(
taskName: string,
taskUpdateActionType: Enum15,
options?: TasksUpdateSubscriptionLevelTaskStateOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ taskName, taskUpdateActionType, options },
updateSubscriptionLevelTaskStateOperationSpec
);
}
/**
* Recommended tasks that will help improve the security of the subscription proactively
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param options The options parameters.
*/
private _listByResourceGroup(
resourceGroupName: string,
options?: TasksListByResourceGroupOptionalParams
): Promise<TasksListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, options },
listByResourceGroupOperationSpec
);
}
/**
* Recommended tasks that will help improve the security of the subscription proactively
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param taskName Name of the task object, will be a GUID
* @param options The options parameters.
*/
getResourceGroupLevelTask(
resourceGroupName: string,
taskName: string,
options?: TasksGetResourceGroupLevelTaskOptionalParams
): Promise<TasksGetResourceGroupLevelTaskResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, taskName, options },
getResourceGroupLevelTaskOperationSpec
);
}
/**
* Recommended tasks that will help improve the security of the subscription proactively
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param taskName Name of the task object, will be a GUID
* @param taskUpdateActionType Type of the action to do on the task
* @param options The options parameters.
*/
updateResourceGroupLevelTaskState(
resourceGroupName: string,
taskName: string,
taskUpdateActionType: Enum15,
options?: TasksUpdateResourceGroupLevelTaskStateOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ resourceGroupName, taskName, taskUpdateActionType, options },
updateResourceGroupLevelTaskStateOperationSpec
);
}
/**
* ListNext
* @param nextLink The nextLink from the previous successful call to the List method.
* @param options The options parameters.
*/
private _listNext(
nextLink: string,
options?: TasksListNextOptionalParams
): Promise<TasksListNextResponse> {
return this.client.sendOperationRequest(
{ nextLink, options },
listNextOperationSpec
);
}
/**
* ListByHomeRegionNext
* @param nextLink The nextLink from the previous successful call to the ListByHomeRegion method.
* @param options The options parameters.
*/
private _listByHomeRegionNext(
nextLink: string,
options?: TasksListByHomeRegionNextOptionalParams
): Promise<TasksListByHomeRegionNextResponse> {
return this.client.sendOperationRequest(
{ nextLink, options },
listByHomeRegionNextOperationSpec
);
}
/**
* ListByResourceGroupNext
* @param resourceGroupName The name of the resource group within the user's subscription. The name is
* case insensitive.
* @param nextLink The nextLink from the previous successful call to the ListByResourceGroup method.
* @param options The options parameters.
*/
private _listByResourceGroupNext(
resourceGroupName: string,
nextLink: string,
options?: TasksListByResourceGroupNextOptionalParams
): Promise<TasksListByResourceGroupNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, nextLink, options },
listByResourceGroupNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const listOperationSpec: coreClient.OperationSpec = {
path: "/subscriptions/{subscriptionId}/providers/Microsoft.Security/tasks",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SecurityTaskList
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.filter, Parameters.apiVersion6],
urlParameters: [Parameters.$host, Parameters.subscriptionId],
headerParameters: [Parameters.accept],
serializer
};
const listByHomeRegionOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.Security/locations/{ascLocation}/tasks",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SecurityTaskList
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.filter, Parameters.apiVersion6],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.ascLocation
],
headerParameters: [Parameters.accept],
serializer
};
const getSubscriptionLevelTaskOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.Security/locations/{ascLocation}/tasks/{taskName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SecurityTask
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion6],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.ascLocation,
Parameters.taskName
],
headerParameters: [Parameters.accept],
serializer
};
const updateSubscriptionLevelTaskStateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.Security/locations/{ascLocation}/tasks/{taskName}/{taskUpdateActionType}",
httpMethod: "POST",
responses: {
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion6],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.ascLocation,
Parameters.taskName,
Parameters.taskUpdateActionType
],
headerParameters: [Parameters.accept],
serializer
};
const listByResourceGroupOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Security/locations/{ascLocation}/tasks",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SecurityTaskList
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.filter, Parameters.apiVersion6],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.ascLocation
],
headerParameters: [Parameters.accept],
serializer
};
const getResourceGroupLevelTaskOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Security/locations/{ascLocation}/tasks/{taskName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SecurityTask
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion6],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.ascLocation,
Parameters.taskName
],
headerParameters: [Parameters.accept],
serializer
};
const updateResourceGroupLevelTaskStateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Security/locations/{ascLocation}/tasks/{taskName}/{taskUpdateActionType}",
httpMethod: "POST",
responses: {
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion6],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.ascLocation,
Parameters.taskName,
Parameters.taskUpdateActionType
],
headerParameters: [Parameters.accept],
serializer
};
const listNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SecurityTaskList
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.filter, Parameters.apiVersion6],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
};
const listByHomeRegionNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SecurityTaskList
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.filter, Parameters.apiVersion6],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.nextLink,
Parameters.ascLocation
],
headerParameters: [Parameters.accept],
serializer
};
const listByResourceGroupNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SecurityTaskList
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.filter, Parameters.apiVersion6],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.nextLink,
Parameters.ascLocation
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import React, { useEffect, useState } from 'react'
import { makeStyles } from '@material-ui/core/styles'
import {
Button,
CircularProgress,
Checkbox,
FormControlLabel,
TextField,
Typography,
Dialog,
DialogContent,
DialogTitle,
IconButton,
} from '@material-ui/core'
import { ConfigurationSchema, getConf } from '@jbrowse/core/configuration'
import AdapterType from '@jbrowse/core/pluggableElementTypes/AdapterType'
import DisplayType from '@jbrowse/core/pluggableElementTypes/DisplayType'
import { Feature } from '@jbrowse/core/util/simpleFeature'
import {
createBaseTrackConfig,
createBaseTrackModel,
} from '@jbrowse/core/pluggableElementTypes/models'
import TrackType from '@jbrowse/core/pluggableElementTypes/TrackType'
import Plugin from '@jbrowse/core/Plugin'
import PluginManager from '@jbrowse/core/PluginManager'
import {
AbstractSessionModel,
getSession,
getContainingView,
getContainingTrack,
isAbstractMenuManager,
} from '@jbrowse/core/util'
import {
MismatchParser,
LinearPileupDisplayModel,
} from '@jbrowse/plugin-alignments'
import { getRpcSessionId } from '@jbrowse/core/util/tracks'
import { PluggableElementType } from '@jbrowse/core/pluggableElementTypes'
import ViewType from '@jbrowse/core/pluggableElementTypes/ViewType'
// icons
import CloseIcon from '@material-ui/icons/Close'
import AddIcon from '@material-ui/icons/Add'
import CalendarIcon from '@material-ui/icons/CalendarViewDay'
// locals
//
import {
configSchemaFactory as linearComparativeDisplayConfigSchemaFactory,
ReactComponent as LinearComparativeDisplayReactComponent,
stateModelFactory as linearComparativeDisplayStateModelFactory,
} from './LinearComparativeDisplay'
import LinearComparativeViewFactory from './LinearComparativeView'
import {
configSchemaFactory as linearSyntenyDisplayConfigSchemaFactory,
stateModelFactory as linearSyntenyDisplayStateModelFactory,
} from './LinearSyntenyDisplay'
import LinearSyntenyRenderer, {
configSchema as linearSyntenyRendererConfigSchema,
ReactComponent as LinearSyntenyRendererReactComponent,
} from './LinearSyntenyRenderer'
import LinearSyntenyViewFactory from './LinearSyntenyView'
import {
AdapterClass as MCScanAnchorsAdapter,
configSchema as MCScanAnchorsConfigSchema,
} from './MCScanAnchorsAdapter'
const { parseCigar } = MismatchParser
function getLengthOnRef(cigar: string) {
const cigarOps = parseCigar(cigar)
let lengthOnRef = 0
for (let i = 0; i < cigarOps.length; i += 2) {
const len = +cigarOps[i]
const op = cigarOps[i + 1]
if (op !== 'H' && op !== 'S' && op !== 'I') {
lengthOnRef += len
}
}
return lengthOnRef
}
function getLength(cigar: string) {
const cigarOps = parseCigar(cigar)
let length = 0
for (let i = 0; i < cigarOps.length; i += 2) {
const len = +cigarOps[i]
const op = cigarOps[i + 1]
if (op !== 'D' && op !== 'N') {
length += len
}
}
return length
}
function getLengthSansClipping(cigar: string) {
const cigarOps = parseCigar(cigar)
let length = 0
for (let i = 0; i < cigarOps.length; i += 2) {
const len = +cigarOps[i]
const op = cigarOps[i + 1]
if (op !== 'H' && op !== 'S' && op !== 'D' && op !== 'N') {
length += len
}
}
return length
}
function getClip(cigar: string, strand: number) {
return strand === -1
? +(cigar.match(/(\d+)[SH]$/) || [])[1] || 0
: +(cigar.match(/^(\d+)([SH])/) || [])[1] || 0
}
interface ReducedFeature {
refName: string
start: number
clipPos: number
end: number
strand: number
seqLength: number
syntenyId?: number
uniqueId: string
mate: {
refName: string
start: number
end: number
syntenyId?: number
uniqueId?: string
}
}
const useStyles = makeStyles(theme => ({
root: {
width: 300,
},
closeButton: {
position: 'absolute',
right: theme.spacing(1),
top: theme.spacing(1),
color: theme.palette.grey[500],
},
}))
function getTag(f: Feature, tag: string) {
const tags = f.get('tags')
return tags ? tags[tag] : f.get(tag)
}
function mergeIntervals<T extends { start: number; end: number }>(
intervals: T[],
w = 5000,
) {
// test if there are at least 2 intervals
if (intervals.length <= 1) {
return intervals
}
const stack = []
let top = null
// sort the intervals based on their start values
intervals = intervals.sort((a, b) => a.start - b.start)
// push the 1st interval into the stack
stack.push(intervals[0])
// start from the next interval and merge if needed
for (let i = 1; i < intervals.length; i++) {
// get the top element
top = stack[stack.length - 1]
// if the current interval doesn't overlap with the
// stack top element, push it to the stack
if (top.end + w < intervals[i].start - w) {
stack.push(intervals[i])
}
// otherwise update the end value of the top element
// if end of current interval is higher
else if (top.end < intervals[i].end) {
top.end = Math.max(top.end, intervals[i].end)
stack.pop()
stack.push(top)
}
}
return stack
}
interface BasicFeature {
end: number
start: number
refName: string
}
// hashmap of refName->array of features
type FeaturesPerRef = { [key: string]: BasicFeature[] }
function gatherOverlaps(regions: BasicFeature[]) {
const groups = regions.reduce((memo, x) => {
if (!memo[x.refName]) {
memo[x.refName] = []
}
memo[x.refName].push(x)
return memo
}, {} as FeaturesPerRef)
return Object.values(groups)
.map(group => mergeIntervals(group.sort((a, b) => a.start - b.start)))
.flat()
}
function WindowSizeDlg(props: {
feature: Feature
handleClose: () => void
track: any
}) {
const classes = useStyles()
const { track, feature: preFeature, handleClose } = props
// window size stored as string, because it corresponds to a textfield which
// is parsed as number on submit
const [windowSizeText, setWindowSize] = useState('0')
const [error, setError] = useState<unknown>()
const [primaryFeature, setPrimaryFeature] = useState<Feature>()
const [qualTrack, setQualTrack] = useState(false)
const windowSize = +windowSizeText
// we need to fetch the primary alignment if the selected feature is 2048.
// this should be the first in the list of the SA tag
useEffect(() => {
let done = false
;(async () => {
try {
if (preFeature.get('flags') & 2048) {
const SA: string = getTag(preFeature, 'SA') || ''
const primaryAln = SA.split(';')[0]
const [saRef, saStart] = primaryAln.split(',')
const { rpcManager } = getSession(track)
const adapterConfig = getConf(track, 'adapter')
const sessionId = getRpcSessionId(track)
const feats = (await rpcManager.call(sessionId, 'CoreGetFeatures', {
adapterConfig,
sessionId,
region: { refName: saRef, start: +saStart - 1, end: +saStart },
})) as Feature[]
const result = feats.find(
f =>
f.get('name') === preFeature.get('name') &&
!(f.get('flags') & 2048),
)
if (result) {
if (!done) {
setPrimaryFeature(result)
}
} else {
throw new Error('primary feature not found')
}
} else {
setPrimaryFeature(preFeature)
}
} catch (e) {
console.error(e)
setError(e)
}
})()
return () => {
done = true
}
}, [preFeature, track])
function onSubmit() {
try {
if (!primaryFeature) {
return
}
const feature = primaryFeature
const session = getSession(track)
const view = getContainingView(track)
const cigar = feature.get('CIGAR')
const clipPos = getClip(cigar, 1)
const flags = feature.get('flags')
const qual = feature.get('qual') as string
const origStrand = feature.get('strand')
const SA: string = getTag(feature, 'SA') || ''
const readName = feature.get('name')
const readAssembly = `${readName}_assembly_${Date.now()}`
const [trackAssembly] = getConf(track, 'assemblyNames')
const assemblyNames = [trackAssembly, readAssembly]
const trackId = `track-${Date.now()}`
const trackName = `${readName}_vs_${trackAssembly}`
// get the canonical refname for the read because if the
// read.get('refName') is chr1 and the actual fasta refName is 1 then no
// tracks can be opened on the top panel of the linear read vs ref
const { assemblyManager } = session
const assembly = assemblyManager.get(trackAssembly)
const supplementaryAlignments = SA.split(';')
.filter(aln => !!aln)
.map((aln, index) => {
const [saRef, saStart, saStrand, saCigar] = aln.split(',')
const saLengthOnRef = getLengthOnRef(saCigar)
const saLength = getLength(saCigar)
const saLengthSansClipping = getLengthSansClipping(saCigar)
const saStrandNormalized = saStrand === '-' ? -1 : 1
const saClipPos = getClip(saCigar, saStrandNormalized * origStrand)
const saRealStart = +saStart - 1
return {
refName: saRef,
start: saRealStart,
end: saRealStart + saLengthOnRef,
seqLength: saLength,
clipPos: saClipPos,
CIGAR: saCigar,
assemblyName: trackAssembly,
strand: origStrand * saStrandNormalized,
uniqueId: `${feature.id()}_SA${index}`,
mate: {
start: saClipPos,
end: saClipPos + saLengthSansClipping,
refName: readName,
},
}
})
const feat = feature.toJSON()
feat.clipPos = clipPos
feat.strand = 1
feat.mate = {
refName: readName,
start: clipPos,
end: clipPos + getLengthSansClipping(cigar),
}
// if secondary alignment or supplementary, calculate length from SA[0]'s
// CIGAR which is the primary alignments. otherwise it is the primary
// alignment just use seq.length if primary alignment
const totalLength =
flags & 2048
? getLength(supplementaryAlignments[0].CIGAR)
: getLength(cigar)
const features = [feat, ...supplementaryAlignments] as ReducedFeature[]
features.forEach((f, index) => {
f.refName = assembly?.getCanonicalRefName(f.refName) || f.refName
f.syntenyId = index
f.mate.syntenyId = index
f.mate.uniqueId = `${f.uniqueId}_mate`
})
features.sort((a, b) => a.clipPos - b.clipPos)
const featSeq = feature.get('seq')
// the config feature store includes synthetic mate features
// mapped to the read assembly
const configFeatureStore = features.concat(
// @ts-ignore
features.map(f => f.mate),
)
const expand = 2 * windowSize
const refLength = features.reduce(
(a, f) => a + f.end - f.start + expand,
0,
)
const seqTrackId = `${readName}_${Date.now()}`
const sequenceTrackConf = getConf(assembly, 'sequence')
const lgvRegions = gatherOverlaps(
features.map(f => ({
...f,
start: Math.max(0, f.start - windowSize),
end: f.end + windowSize,
assemblyName: trackAssembly,
})),
)
session.addAssembly?.({
name: `${readAssembly}`,
sequence: {
type: 'ReferenceSequenceTrack',
trackId: seqTrackId,
assemblyNames: [readAssembly],
adapter: {
type: 'FromConfigSequenceAdapter',
noAssemblyManager: true,
features: [
{
start: 0,
end: totalLength,
seq: featSeq,
refName: readName,
uniqueId: `${Math.random()}`,
},
],
},
},
})
session.addView('LinearSyntenyView', {
type: 'LinearSyntenyView',
views: [
{
type: 'LinearGenomeView',
hideHeader: true,
offsetPx: 0,
bpPerPx: refLength / view.width,
displayedRegions: lgvRegions,
tracks: [
{
id: `${Math.random()}`,
type: 'ReferenceSequenceTrack',
assemblyNames: [trackAssembly],
configuration: sequenceTrackConf.trackId,
displays: [
{
id: `${Math.random()}`,
type: 'LinearReferenceSequenceDisplay',
showReverse: true,
showTranslation: false,
height: 35,
configuration: `${seqTrackId}-LinearReferenceSequenceDisplay`,
},
],
},
],
},
{
type: 'LinearGenomeView',
hideHeader: true,
offsetPx: 0,
bpPerPx: totalLength / view.width,
displayedRegions: [
{
assemblyName: readAssembly,
start: 0,
end: totalLength,
refName: readName,
},
],
tracks: [
{
id: `${Math.random()}`,
type: 'ReferenceSequenceTrack',
configuration: seqTrackId,
displays: [
{
id: `${Math.random()}`,
type: 'LinearReferenceSequenceDisplay',
showReverse: true,
showTranslation: false,
height: 35,
configuration: `${seqTrackId}-LinearReferenceSequenceDisplay`,
},
],
},
...(qualTrack
? [
{
id: `${Math.random()}`,
type: 'QuantitativeTrack',
configuration: {
trackId: 'qualTrack',
assemblyNames: [readAssembly],
name: 'Read quality',
type: 'QuantitativeTrack',
adapter: {
type: 'FromConfigAdapter',
noAssemblyManager: true,
features: qual.split(' ').map((score, index) => {
return {
start: index,
end: index + 1,
refName: readName,
score: +score,
uniqueId: `feat_${index}`,
}
}),
},
},
displays: [
{
id: `${Math.random()}`,
type: 'LinearWiggleDisplay',
height: 100,
},
],
},
]
: []),
],
},
],
viewTrackConfigs: [
{
type: 'SyntenyTrack',
assemblyNames,
adapter: {
type: 'FromConfigAdapter',
features: configFeatureStore,
},
trackId,
name: trackName,
},
],
tracks: [
{
configuration: trackId,
type: 'SyntenyTrack',
displays: [
{
type: 'LinearSyntenyDisplay',
configuration: `${trackId}-LinearSyntenyDisplay`,
},
],
},
],
displayName: `${readName} vs ${trackAssembly}`,
})
handleClose()
} catch (e) {
console.error(e)
setError(e)
}
}
return (
<Dialog
open
onClose={handleClose}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<DialogTitle id="alert-dialog-title">
Set window size
<IconButton
aria-label="close"
className={classes.closeButton}
onClick={handleClose}
>
<CloseIcon />
</IconButton>
</DialogTitle>
<DialogContent>
{!primaryFeature ? (
<div>
<Typography>
To accurately perform comparison we are fetching the primary
alignment. Loading primary feature...
</Typography>
<CircularProgress />
</div>
) : (
<div className={classes.root}>
<Typography>
Show an extra window size around each part of the split alignment.
Using a larger value can allow you to see more genomic context.
</Typography>
{error ? <Typography color="error">{`${error}`}</Typography> : null}
<TextField
value={window}
onChange={event => {
setWindowSize(event.target.value)
}}
label="Set window size"
/>
<FormControlLabel
control={
<Checkbox
checked={qualTrack}
onChange={() => setQualTrack(val => !val)}
/>
}
label="Show qual track"
/>
<Button
variant="contained"
color="primary"
style={{ marginLeft: 20 }}
onClick={onSubmit}
>
Submit
</Button>
</div>
)}
</DialogContent>
</Dialog>
)
}
export default class extends Plugin {
name = 'LinearComparativeViewPlugin'
install(pluginManager: PluginManager) {
pluginManager.addViewType(() =>
pluginManager.jbrequire(LinearComparativeViewFactory),
)
pluginManager.addViewType(() =>
pluginManager.jbrequire(LinearSyntenyViewFactory),
)
pluginManager.addTrackType(() => {
const configSchema = ConfigurationSchema(
'SyntenyTrack',
{},
{ baseConfiguration: createBaseTrackConfig(pluginManager) },
)
return new TrackType({
name: 'SyntenyTrack',
configSchema,
stateModel: createBaseTrackModel(
pluginManager,
'SyntenyTrack',
configSchema,
),
})
})
pluginManager.addDisplayType(() => {
const configSchema =
linearComparativeDisplayConfigSchemaFactory(pluginManager)
return new DisplayType({
name: 'LinearComparativeDisplay',
configSchema,
stateModel: linearComparativeDisplayStateModelFactory(configSchema),
trackType: 'SyntenyTrack',
viewType: 'LinearComparativeView',
ReactComponent: LinearComparativeDisplayReactComponent,
})
})
pluginManager.addDisplayType(() => {
const configSchema =
linearSyntenyDisplayConfigSchemaFactory(pluginManager)
return new DisplayType({
name: 'LinearSyntenyDisplay',
configSchema,
stateModel: linearSyntenyDisplayStateModelFactory(configSchema),
trackType: 'SyntenyTrack',
viewType: 'LinearSyntenyView',
ReactComponent: LinearComparativeDisplayReactComponent,
})
})
pluginManager.addAdapterType(
() =>
new AdapterType({
name: 'MCScanAnchorsAdapter',
configSchema: MCScanAnchorsConfigSchema,
adapterMetadata: {
category: null,
hiddenFromGUI: true,
displayName: null,
description: null,
},
AdapterClass: MCScanAnchorsAdapter,
}),
)
pluginManager.addRendererType(
() =>
new LinearSyntenyRenderer({
name: 'LinearSyntenyRenderer',
configSchema: linearSyntenyRendererConfigSchema,
ReactComponent: LinearSyntenyRendererReactComponent,
pluginManager,
}),
)
pluginManager.addToExtensionPoint(
'Core-extendPluggableElement',
(pluggableElement: PluggableElementType) => {
if (pluggableElement.name === 'LinearPileupDisplay') {
const { stateModel } = pluggableElement as ViewType
const newStateModel = stateModel.extend(
(self: LinearPileupDisplayModel) => {
const superContextMenuItems = self.contextMenuItems
return {
views: {
contextMenuItems() {
const feature = self.contextMenuFeature
if (!feature) {
return superContextMenuItems()
}
const newMenuItems = [
...superContextMenuItems(),
{
label: 'Linear read vs ref',
icon: AddIcon,
onClick: () => {
getSession(self).queueDialog(
(doneCallback: Function) => [
WindowSizeDlg,
{
track: getContainingTrack(self),
feature,
handleClose: doneCallback,
},
],
)
},
},
]
return newMenuItems
},
},
}
},
)
;(pluggableElement as DisplayType).stateModel = newStateModel
}
return pluggableElement
},
)
}
configure(pluginManager: PluginManager) {
if (isAbstractMenuManager(pluginManager.rootModel)) {
pluginManager.rootModel.appendToSubMenu(['Add'], {
label: 'Linear synteny view',
icon: CalendarIcon,
onClick: (session: AbstractSessionModel) => {
session.addView('LinearSyntenyView', {})
},
})
}
}
} | the_stack |
import { ChainFactory } from './ChainFactory';
import { MethodInvocation } from './Invocation/MethodInvocation';
import { InterceptorInvocation } from './Invocation/InterceptorInvocation';
import { ParameterInterceptor } from './Invocation/ParameterInterceptor';
import { PropertyInfo } from '../Interfaces/PropertyInfo';
import { define } from '../Helpers/Prototype';
import { GetterSetterInvocation } from './Invocation/GetterSetterInvocation';
import { AgentFrameworkError } from '../Error/AgentFrameworkError';
import { HasInterceptor } from '../Helpers/CustomInterceptor';
import { Attribute } from '../Interfaces/Attribute';
export class OnDemandClassCompiler {
static upgrade(
proxy: object | Function,
properties: Map<PropertyKey, PropertyInfo>,
target: Function,
receiver?: Function
): any {
const map: any = {};
// only proxy property contains interceptor
// property without interceptor is metadata only attribute
for (const [key, property] of properties.entries()) {
const descriptor = property.descriptor;
if (descriptor) {
map[key] = OnDemandClassCompiler.makeProperty(property, descriptor, receiver || target);
} else {
map[key] = OnDemandClassCompiler.makeField(property, receiver || target);
}
}
// use define properties is a little bit faster then define the property one by one
Object.defineProperties(proxy, map);
return map;
}
// /**
// * Create interceptor for the getter
// */
// private static createGetterInterceptor(origin: PropertyInvocation): Invocation {
// // console.log('createGetterInterceptor', origin.target.name, origin.design.name);
// const property = origin.design;
// const attributes = property.findOwnAttributes(HasInterceptor);
// //.concat(property.getter.findOwnAttributes(HasInterceptor));
// return ChainFactory.chainInterceptorAttributes(origin, attributes);
// }
//
// /**
// * Create interceptor for the setter
// */
// private static createSetterInterceptor(origin: PropertyInvocation): Invocation {
// // console.log('createSetterInterceptor', origin.target.name, origin.design.name);
// const property = origin.design;
// const attributes = property.findOwnAttributes(HasInterceptor);
// //.concat(property.setter.findOwnAttributes(HasInterceptor));
// return ChainFactory.chainInterceptorAttributes(origin, attributes);
// }
// /**
// * Create method interceptor
// */
// static createMethodInterceptor(origin: PropertyInvocation): Invocation {
// // console.log('createMethodInterceptor', origin.target.name, origin.design.name);
// const property = origin.design;
//
// //
// const attributes = property.findOwnAttributes(HasInterceptor);
// //.concat(property.value.findOwnAttributes(HasInterceptor));
//
// // create interceptor
// const intercepted = ChainFactory.chainInterceptorAttributes(origin, attributes);
//
// // create a extra parameter invocation if have
// return new InterceptorInvocation(intercepted, new ParameterInterceptor(property));
// }
// static createParameterInterceptor(origin: IParameterInvocation, interceptors): IInvocation {
// const design = origin.design;
//
// const interceptors = design.getInterceptors(); // get all interceptors
//
// // create interceptor
// return ChainFactory.chainInterceptorAttributes(origin, interceptors);
// }
/**
* Create interceptor for field initializer
*/
private static findOwnPropertyInterceptors(property: PropertyInfo): Array<Attribute> {
const attributes = property.findOwnAttributes(HasInterceptor);
//.concat(property.value.findOwnAttributes(HasInterceptor));
return attributes;
}
/**
* Field will only call interceptor for only 1 time
*/
private static makeField(field: PropertyInfo, receiver: Function): PropertyDescriptor {
const key = field.key;
const fieldInvoker = new GetterSetterInvocation(field);
return {
get() {
const attributes = OnDemandClassCompiler.findOwnPropertyInterceptors(field);
const chain = ChainFactory.chainInterceptorAttributes(fieldInvoker, attributes);
const descriptor = {
get() {
return chain.invoke([], this);
// return set(this, key, chain.invoke([undefined], this));
},
set(this: any) {
descriptor.set = function (this: any) {
chain.invoke(arguments, this);
};
define(receiver.prototype, key, descriptor);
chain.invoke(arguments, this);
},
configurable: true,
};
define(receiver.prototype, key, descriptor);
return chain.invoke([], this);
// return set(this, key, chain.invoke([undefined], this));
},
set(this: any) {
const attributes = OnDemandClassCompiler.findOwnPropertyInterceptors(field);
const chain = ChainFactory.chainInterceptorAttributes(fieldInvoker, attributes);
const descriptor = {
get() {
descriptor.get = function () {
return chain.invoke([], this);
// return set(this, key, chain.invoke([undefined], this));
};
define(receiver.prototype, key, descriptor);
return chain.invoke([], this);
// return set(this, key, chain.invoke([undefined], this));
},
set(this: any) {
return chain.invoke(arguments, this);
},
configurable: true,
};
define(receiver.prototype, key, descriptor);
return chain.invoke(arguments, this);
},
configurable: true,
};
}
private static makeProperty(
property: PropertyInfo,
descriptor: PropertyDescriptor,
receiver: Function
): PropertyDescriptor {
const key = property.key;
let propertyDescriptor = Object.create(descriptor);
// user can change this property
propertyDescriptor.configurable = true;
const method = descriptor.value;
const getterMethod = descriptor.get;
const setterMethod = descriptor.set;
if (method != null) {
// if (typeof method === 'function') {
// typeof method === 'function'
// value only
if (typeof method === 'function') {
propertyDescriptor.value = function (this: any) {
const origin = new MethodInvocation(property, method);
const attributes = OnDemandClassCompiler.findOwnPropertyInterceptors(property);
const chain = new InterceptorInvocation(
ChainFactory.chainInterceptorAttributes(origin, attributes),
new ParameterInterceptor(property)
);
propertyDescriptor.value = function (this: any) {
return chain.invoke(arguments, this);
};
define(receiver.prototype, key, propertyDescriptor);
return chain.invoke(arguments, this);
};
} else {
propertyDescriptor = {
enumerable: descriptor.enumerable,
configurable: true,
};
const propertyInvoker = new GetterSetterInvocation(property);
// getter and setter
propertyDescriptor.get = function (this: any) {
const attributes = OnDemandClassCompiler.findOwnPropertyInterceptors(property);
const chain = ChainFactory.chainInterceptorAttributes(propertyInvoker, attributes);
const descriptor = {
get() {
return chain.invoke([], this);
},
set(value: any) {
const attributes = OnDemandClassCompiler.findOwnPropertyInterceptors(property);
const chain = ChainFactory.chainInterceptorAttributes(propertyInvoker, attributes);
descriptor.set = function () {
chain.invoke(arguments, this);
};
define(receiver.prototype, key, descriptor);
chain.invoke(arguments, this);
},
configurable: true,
};
define(receiver.prototype, key, descriptor);
return chain.invoke([], this);
};
propertyDescriptor.set = function (this: any) {
const attributes = OnDemandClassCompiler.findOwnPropertyInterceptors(property);
const chain = ChainFactory.chainInterceptorAttributes(propertyInvoker, attributes);
const descriptor = {
get() {
const attributes = OnDemandClassCompiler.findOwnPropertyInterceptors(property);
const chain = ChainFactory.chainInterceptorAttributes(propertyInvoker, attributes);
descriptor.get = function () {
return chain.invoke([], this);
};
define(receiver.prototype, key, descriptor);
return chain.invoke([], this);
},
set(this: any) {
return chain.invoke(arguments, this);
},
configurable: true,
};
// console.log('called set', receiver, Reflect.getOwnPropertyDescriptor(receiver.prototype, key));
define(receiver.prototype, key, descriptor);
return chain.invoke(arguments, this);
};
}
} else {
// getter or setter
if (typeof getterMethod === 'function') {
if (typeof setterMethod === 'function') {
// getter and setter
propertyDescriptor.get = function (this: any) {
const origin = new MethodInvocation(property, getterMethod);
const attributes = OnDemandClassCompiler.findOwnPropertyInterceptors(property);
const chain = ChainFactory.chainInterceptorAttributes(origin, attributes);
const descriptor = {
get() {
return chain.invoke([], this);
},
set(value: any) {
const origin = new MethodInvocation(property, setterMethod);
const attributes = OnDemandClassCompiler.findOwnPropertyInterceptors(property);
const chain = ChainFactory.chainInterceptorAttributes(origin, attributes);
descriptor.set = function () {
chain.invoke(arguments, this);
};
define(receiver.prototype, key, descriptor);
chain.invoke(arguments, this);
},
configurable: true,
};
define(receiver.prototype, key, descriptor);
return chain.invoke([], this);
};
propertyDescriptor.set = function (this: any) {
const origin = new MethodInvocation(property, setterMethod);
const attributes = OnDemandClassCompiler.findOwnPropertyInterceptors(property);
const chain = ChainFactory.chainInterceptorAttributes(origin, attributes);
const descriptor = {
get() {
const origin = new MethodInvocation(property, getterMethod);
const attributes = OnDemandClassCompiler.findOwnPropertyInterceptors(property);
const chain = ChainFactory.chainInterceptorAttributes(origin, attributes);
descriptor.get = function () {
return chain.invoke([undefined], this);
};
define(receiver.prototype, key, descriptor);
return chain.invoke([undefined], this);
},
set(this: any) {
return chain.invoke(arguments, this);
},
configurable: true,
};
define(receiver.prototype, key, descriptor);
return chain.invoke(arguments, this);
};
} else {
// getter, no setter
propertyDescriptor.get = function (this: any) {
const origin = new MethodInvocation(property, getterMethod);
const attributes = OnDemandClassCompiler.findOwnPropertyInterceptors(property);
const chain = ChainFactory.chainInterceptorAttributes(origin, attributes);
propertyDescriptor.get = function (this: any) {
return chain.invoke([], this);
};
define(receiver.prototype, key, propertyDescriptor);
return chain.invoke([], this);
};
}
} else if (typeof setterMethod === 'function') {
// setter
propertyDescriptor.set = function (this: any) {
const origin = new MethodInvocation(property, setterMethod);
const attributes = OnDemandClassCompiler.findOwnPropertyInterceptors(property);
const chain = ChainFactory.chainInterceptorAttributes(origin, attributes);
propertyDescriptor.set = function (this: any) {
return chain.invoke(arguments, this);
};
define(receiver.prototype, key, propertyDescriptor);
return chain.invoke(arguments, this);
};
} else {
throw new AgentFrameworkError('InvalidProperty: ' + property.declaringType.name + '.' + key.toString());
}
}
// console.log('descriptor', descriptor);
// console.log('propertyDescriptor', propertyDescriptor);
return propertyDescriptor;
}
} | the_stack |
import { createElement, EmitType } from '@syncfusion/ej2-base';
import { HeatMap } from '../../src/heatmap/heatmap';
import { Title } from '../../src/heatmap/model/base';
import { ILoadedEventArgs } from '../../src/heatmap/model/interface';
import { Legend, LegendSettings } from '../../src/heatmap/legend/legend';
import { Tooltip } from '../../src/heatmap/utils/tooltip';
import { MouseEvents } from '../base/event.spec'
import { profile , inMB, getMemoryProfile } from '../../spec/common.spec';
import { CellSettings } from '../../src';
import { ILegendRenderEventArgs } from '../../src/heatmap/model/interface';
HeatMap.Inject(Legend, Tooltip);
// export class MouseEvents {
// public mousemoveEvent(element: Element, sx: number, sy: number, cx: number, cy: number): void {
// let mousemove: MouseEvent = document.createEvent('MouseEvent');
// mousemove.initMouseEvent('mousemove', true, false, window, 1, sx, sy, cx, cy, false, false, false, false, 0, null);
// element.dispatchEvent(mousemove);
// }
// }
describe('Heatmap Control', () => {
beforeAll(() => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
});
describe('Heatmap Legend', () => {
let heatmap: HeatMap;
let legend: Legend = new Legend(heatmap);
let ele: HTMLElement;
let tempElement: HTMLElement;
let legendElement: Element;
let created: EmitType<Object>;
let trigger: MouseEvents = new MouseEvents();
beforeAll((): void => {
ele = createElement('div', { id: 'heatmapContainer' });
document.body.appendChild(ele);
heatmap = new HeatMap({
width: '100%',
height: '300px',
xAxis: {
title: { text: 'Weekdays' },
},
yAxis: {
title: { text: 'YAxis' },
},
dataSource: [[10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]],
paletteSettings: {
palette: [{ 'value': 100, 'color': 'rgb(255, 255, 153)', 'label': 'excellent' },
{ 'value': 70, 'color': 'rgb(153, 255, 187)', 'label': 'good' },
{ 'value': 25, 'color': 'rgb(153, 153, 255)', 'label': 'average' },
{ 'value': 0, 'color': 'rgb(255, 159, 128)', 'label': 'poor' },
],
type: 'Gradient'
},
legendSettings: {
visible: true,
},
showTooltip: false,
});
});
afterAll((): void => {
heatmap.destroy();
});
it('Checking heatmap instance creation', (done: Function) => {
created = (args: Object): void => {
expect(heatmap != null).toBe(true);
done();
};
heatmap.created = created;
heatmap.appendTo('#heatmapContainer');
});
it('Changing legend position to left', () => {
heatmap.legendSettings.position = 'Left';
heatmap.refresh();
tempElement = document.getElementById('heatmapContainer_Gradient_Legend');
expect(tempElement.getAttribute('x') == '20').toBe(true);
});
it('Changing legend position to Top', () => {
heatmap.legendSettings.position = 'Top';
heatmap.refresh();
tempElement = document.getElementById('heatmapContainer_Gradient_Legend');
expect(tempElement.getAttribute('y') == '26').toBe(true);
});
it('Changing legend position to Bottom', () => {
heatmap.legendSettings.position = 'Bottom';
heatmap.refresh();
tempElement = document.getElementById('heatmapContainer_Gradient_Legend');
expect(tempElement.getAttribute('y') == '248' || tempElement.getAttribute('y') == '249').toBe(true);
});
it('Right Position with near alignment', () => {
heatmap.legendSettings = {
position : 'Right',
height :'50%',
alignment : 'Near'
};
heatmap.refresh();
tempElement = document.getElementById('heatmapContainer_Gradient_Legend');
expect(tempElement.getAttribute('y') == '20').toBe(true);
});
it('Right Position with alignment far', () => {
heatmap.legendSettings = {
height :'50%',
alignment : 'Far'
};
heatmap.refresh();
tempElement = document.getElementById('heatmapContainer_Gradient_Legend');
expect(tempElement.getAttribute('y') == '134' || tempElement.getAttribute('y') == '135').toBe(true);
});
it('Right Position with center alignment', () => {
heatmap.legendSettings = {
height :'50%',
alignment : 'Center'
};
heatmap.refresh();
tempElement = document.getElementById('heatmapContainer_Gradient_Legend');
expect(tempElement.getAttribute('y') == '77' || tempElement.getAttribute('y') == '77.5').toBe(true);
});
it('Checking label text when no labels are present', () => {
heatmap.paletteSettings.palette = [
{ 'value': 100, 'color': 'rgb(255, 255, 153)', 'label': 'excellent' },
{ 'value': 75, 'color': 'rgb(153, 255, 187)' },
{ 'value': 25, 'color': 'rgb(153, 153, 255)', 'label': 'average' },
{ 'value': 0, 'color': 'rgb(255, 159, 128)' }
];
heatmap.refresh();
expect(document.getElementById('heatmapContainer_Legend_Label2').textContent == '75').toBe(true);
expect(document.getElementById('heatmapContainer_Legend_Label3').textContent == 'excellent').toBe(true);
});
it('Checking trim support in vertical direction', () => {
heatmap.legendSettings.textStyle.textOverflow = 'Trim';
heatmap.legendSettings.height = '';
heatmap.refresh();
let element : Element = document.getElementById('heatmapContainer_Legend_Label3');
expect(element.textContent == 'ex...' || element.textContent == 'exc...').toBe(true);
});
it('Checking wrap support in vertical direction', () => {
heatmap.paletteSettings.palette = [
{ 'value': 100, 'color': 'rgb(255, 255, 153)', 'label': 'text4text4text4' },
{ 'value': 70, 'color': 'rgb(153, 255, 187)', 'label': 'good' },
{ 'value': 25, 'color': 'rgb(153, 153, 255)', 'label': 'average' },
{ 'value': 0, 'color': 'rgb(255, 159, 128)', 'label': 'text1 text1 text1' },
];
heatmap.legendSettings.textStyle.textOverflow = 'Wrap';
heatmap.refresh();
expect(document.getElementById('heatmapContainer_Legend_Label0').textContent == 'tex...tex...tex...' || document.getElementById('heatmapContainer_Legend_Label0').textContent == 'text1text1text1').toBe(true);
});
it('Checking trim support in horizontal direction', () => {
heatmap.legendSettings.position = 'Bottom';
heatmap.legendSettings.width = '20%';
heatmap.legendSettings.textStyle.textOverflow = 'Trim';
heatmap.refresh();
expect(document.getElementById('heatmapContainer_Legend_Label1').textContent == 'a...').toBe(true);
});
it('Checking wrap support in horizontal direction', function () {
tempElement = document.getElementById('heatmapContainer_LegendBound');
expect(tempElement.getAttribute('height') == '58' || tempElement.getAttribute('height') == '57').toBe(true);
heatmap.legendSettings.textStyle.textOverflow = 'Wrap';
heatmap.refresh();
tempElement = document.getElementById('heatmapContainer_LegendBound');
expect(tempElement.getAttribute('height') == '90' || tempElement.getAttribute('height') == '87').toBe(true);
});
it('Checking wrap support in top position', function () {
heatmap.legendSettings.position = 'Top';
heatmap.refresh();
tempElement = document.getElementById('heatmapContainer_LegendBound');
expect(tempElement.getAttribute('height') == '90' || tempElement.getAttribute('height') == '87').toBe(true);
});
it('Checking legend label tooltip', () => {
heatmap.legendSettings.textStyle.textOverflow = 'Trim';
heatmap.refresh();
legendElement = document.getElementById('heatmapContainer_Legend_Label1');
trigger.mousemoveEvent(legendElement, 5, 5, 715, 73, false);
trigger.mousemoveEvent(legendElement, 5, 5, 715, 100, false);
trigger.mousemoveEvent(legendElement, 5, 5, 715, 73, false);
expect(document.getElementById('heatmapContainer_LegendLabel_Tooltip').textContent == 'average').toBe(true);
});
it('Checking Gradient pointer position in horizontal direction', () => {
heatmap.legendSettings = {
height : '',
width : '',
};
heatmap.width = '100%';
heatmap.refresh();
legendElement = document.getElementById('heatmapContainer_HeatMapRect_26');
trigger.mousemoveEvent(legendElement, 10, 10, 646, 179, false);
tempElement = document.getElementById('heatmapContainer_Gradient_Pointer');
expect(heatmap.legendModule.gradientPointer != null).toBe(true);
});
it('Checking list type legend in horizontal direction', () => {
heatmap.paletteSettings.type = 'Fixed';
heatmap.refresh();
tempElement = document.getElementById('heatmapContainer_LegendBound');
expect(heatmap.legendModule.listPerPage).toBe(1);
});
it('Checking list type legend in vertical direction', () => {
heatmap.paletteSettings.type = 'Fixed';
heatmap.legendSettings.height = '50%';
heatmap.legendSettings.position = 'Right';
heatmap.legendSettings.textStyle.textOverflow = 'None';
heatmap.paletteSettings.palette = [
{ 'value': 80, 'color': 'rgb(0,91,162)', 'label': 'text8 text8 text8 text8' },
{ 'value': 70, 'color': 'rgb(19,171,17)', 'label': 'text7 text7 text7 text7' },
{ 'value': 60, 'color': 'rgb(255,255,1)', 'label': 'text6 text6 text6 text6' },
{ 'value': 50, 'color': 'rgb(254,0,2)', 'label': 'text5 text5 text5 text5 text5' },
{ 'value': 40, 'color': 'rgb(255, 255, 153)', 'label': 'text4 text4 text4 text4' },
{ 'value': 30, 'color': 'rgb(153, 255, 187)', 'label': 'text3 text3 text3 text3' },
{ 'value': 20, 'color': 'rgb(153, 153, 255)', 'label': 'text2 text2' },
{ 'value': 10, 'color': 'rgb(255, 159, 128)', 'label': 'text1 text1' },
];
heatmap.refresh();
tempElement = document.getElementById('heatmapContainer_LegendBound');
expect(tempElement.getAttribute('y') == '67' || tempElement.getAttribute('y') == '67.5').toBe(true);
});
it('Checking list type legend in horizontal direction', function () {
heatmap.legendSettings.width = '30%';
heatmap.legendSettings.position = 'Bottom';
heatmap.refresh();
tempElement = document.getElementById('heatmapContainer_LegendBound');
expect(tempElement.getAttribute('width') == '208.8' || tempElement.getAttribute('width') == '212.4' ).toBe(true);
});
it('List type legend with paging', () => {
heatmap.paletteSettings.type = 'Fixed';
heatmap.legendSettings.position = 'Bottom';
heatmap.legendSettings.height = '';
heatmap.legendSettings.width = '50%';
heatmap.width = '500px';
heatmap.refresh();
legendElement = document.getElementById('heatmapContainer_rightArrow');
let element:ClientRect = legendElement.getBoundingClientRect();
trigger.clickEvent(legendElement, 0, 0, element.left + 2, element.top + 2);
tempElement = document.getElementById('heatmapContainer_paging');
expect(tempElement.textContent == '2/4').toBe(true);
let leftArrow:HTMLElement = document.getElementById('heatmapContainer_leftArrow');
let leftArrowelement:ClientRect = leftArrow.getBoundingClientRect();
trigger.clickEvent(leftArrow, 0, 0, leftArrowelement.left + 2, leftArrowelement.top + 2);
tempElement = document.getElementById('heatmapContainer_paging');
expect(tempElement.textContent == '1/4').toBe(true);
});
it('List type legend with paging in canvas render mode', () => {
heatmap.renderingMode = 'Canvas';
heatmap.refresh();
legendElement = document.getElementById('heatmapContainer_canvas');
trigger.clickEvent(legendElement, 0, 0, 370.25, 285);
expect(heatmap.legendModule.currentPage).toBe(2);
});
it('Checking list type legend in canvas render mode', () => {
heatmap.legendSettings.position = 'Right';
heatmap.refresh();
expect(heatmap.legendModule.labelCollections.length).toBe(8);
});
it('Checking list type legend with trim support in canvas ', () => {
heatmap.renderingMode = 'Canvas';
heatmap.legendSettings.width = '';
heatmap.legendSettings.position = 'Right';
heatmap.legendSettings.textStyle.textOverflow = 'Trim';
heatmap.refresh();
expect(heatmap.legendModule.legendLabelTooltip.length).not.toBe(0);
});
it('Hide the previously rendered gradient pointer', () => {
heatmap.paletteSettings.type = 'Gradient';
heatmap.renderingMode = 'SVG';
heatmap.refresh();
legendElement = document.getElementById('heatmapContainer_svg');
trigger.mousemoveEvent(legendElement, 5, 5, 100, 73, false);
trigger.mousemoveEvent(legendElement, 5, 5, 400, 640, false);
let pointerElement : HTMLElement = document.getElementById('heatmapContainer_Gradient_Pointer')
expect(pointerElement.style.visibility == 'hidden');
});
it('Remove previously rendered gradient pointer in canvas in vertical direction', () => {
heatmap.paletteSettings.type = 'Gradient';
heatmap.renderingMode = 'Canvas';
heatmap.refresh();
legendElement = document.getElementById('heatmapContainer_canvas');
trigger.mousemoveEvent(legendElement, 5, 5, 100, 73, false);
trigger.mousemoveEvent(legendElement, 5, 5, 400, 40, false);
expect(heatmap.legendModule.previousOptions.pathX1 == 707 && heatmap.legendModule.previousOptions.pathX2 == 700);
});
it('Remove previously rendered gradient pointer in canvas in horizontal direction', () => {
heatmap.legendSettings.position = 'Bottom';
heatmap.refresh();
legendElement = document.getElementById('heatmapContainer_canvas');
trigger.mousemoveEvent(legendElement, 5, 5, 400, 73, false);
trigger.mousemoveEvent(legendElement, 5, 5, 100, 40, false);
expect(heatmap.legendModule.previousOptions.pathX1 === 648 && heatmap.legendModule.previousOptions.pathY1 === 413);
});
it('Disabling showLabel', function () {
heatmap.legendSettings.position = 'Bottom';
heatmap.legendSettings.textStyle.textOverflow = 'None';
heatmap.paletteSettings.type = 'Fixed';
heatmap.legendSettings.showLabel = false;
heatmap.dataBind();
tempElement = document.getElementById('heatmapContainer_Heatmap_LegendLabel');
expect(tempElement == null).toBe(true);
});
it('Disabling showLabel', () => {
heatmap.legendSettings.position = 'Right';
heatmap.legendSettings.textStyle.textOverflow = 'None';
heatmap.paletteSettings.type = 'Fixed';
heatmap.legendSettings.showLabel = false;
heatmap.dataBind();
tempElement = document.getElementById('heatmapContainer_Heatmap_LegendLabel');
expect(tempElement == null).toBe(true);
});
it('Disabling showLabel', () => {
heatmap.legendSettings.position = 'Right';
heatmap.legendSettings.textStyle.textOverflow = 'None';
heatmap.paletteSettings.type = 'Gradient';
heatmap.legendSettings.showLabel = false;
heatmap.dataBind();
tempElement = document.getElementById('heatmapContainer_Heatmap_LegendLabel');
expect(tempElement == null).toBe(true);
});
it('Check legend position with out axis title', function () {
heatmap.legendSettings.position = 'Bottom';
heatmap.legendSettings.textStyle.textOverflow = 'None';
heatmap.renderingMode = "SVG";
heatmap.paletteSettings.type = 'Gradient';
heatmap.legendSettings.showLabel = true;
heatmap.xAxis.title.text = '';
heatmap.dataBind();
tempElement = document.getElementById('heatmapContainer_Gradient_Legend');
expect(tempElement.getAttribute('y') == '248' || tempElement.getAttribute('y') == '249').toBe(true);
});
it('Check legend position with out axis title', function () {
heatmap.legendSettings.position = 'Left';
heatmap.legendSettings.textStyle.textOverflow = 'None';
heatmap.renderingMode = "SVG";
heatmap.paletteSettings.type = 'Gradient';
heatmap.legendSettings.showLabel = true;
heatmap.yAxis.title.text = '';
heatmap.dataBind();
tempElement = document.getElementById('heatmapContainer_Gradient_Legend');
expect(tempElement.getAttribute('x') == '20' || tempElement.getAttribute('x') == '20').toBe(true);
});
it('Checking smart legend for fixed palette type', function () {
heatmap.paletteSettings.type = 'Fixed';
heatmap.legendSettings.enableSmartLegend = true;
heatmap.legendSettings.labelDisplayType = 'None';
heatmap.dataBind();
legendElement = document.getElementById('heatmapContainer_Smart_Legend0');
trigger.mousemoveEvent(legendElement, 5, 5, 30, 35, false);
trigger.mousemoveEvent(legendElement, 5, 5, 130, 135, false);
trigger.mousemoveEvent(legendElement, 5, 5, 30, 35, false);
let tooltip: Element = document.getElementById('heatmapContainerlegendLabelTooltipContainer_text');
expect(tooltip.textContent == 'text1 text1');
});
it('Rendering smart legend in canvas rendering', function () {
heatmap.renderingMode = 'Canvas';
heatmap.dataBind();
legendElement = document.getElementById('heatmapContainer_canvas');
trigger.mousemoveEvent(legendElement, 5, 5, 30, 35, false);
let tooltip: Element = document.getElementById('heatmapContainerlegendLabelTooltipContainer_text');
expect(tooltip.textContent == 'text1 text1');
});
it('Rendering smart legend with edge label display', function () {
heatmap.legendSettings.labelDisplayType = 'Edge';
heatmap.legendSettings.textStyle.textOverflow = 'Wrap';
heatmap.dataBind();
legendElement = document.getElementById('heatmapContainer_Smart_Legend1');
expect(legendElement == null).toBe(true);
});
it('Rendering smart legend in horizontal direcrion', function () {
heatmap.legendSettings.position = 'Bottom';
heatmap.renderingMode = 'SVG';
heatmap.dataBind();
legendElement = document.getElementById('heatmapContainer_Smart_Legend0');
expect(legendElement.getAttribute('width') == '55.375' );
});
it('Checking label format', function () {
heatmap.paletteSettings.palette = [
{ 'value': 100, 'color': 'rgb(255, 255, 153)'},
{ 'value': 70, 'color': 'rgb(153, 255, 187)' },
{ 'value': 25, 'color': 'rgb(153, 153, 255)' },
{ 'value': 0, 'color': 'rgb(255, 159, 128)' },
];
heatmap.legendSettings.labelFormat = '{value} %'
heatmap.dataBind();
legendElement = document.getElementById('heatmapContainer_Legend_Label3');
expect(legendElement.textContent == '100 %');
});
it('Checking legend label customization', function () {
heatmap.legendRender = function (args:ILegendRenderEventArgs) {
args.cancel = true;
};
heatmap.refresh();
heatmap.legendRender = function (args:ILegendRenderEventArgs) {
args.cancel = false;
};
heatmap.refresh();
legendElement = document.getElementById('heatmapContainer_Legend_Label0');
if(heatmap.paletteSettings.type == 'Gradient'){
if (heatmap.legendRender) {
expect(legendElement.textContent == '0 %').toBe(true);
} else{
expect(legendElement.textContent == '').toBe(true);
}
} else {
if (heatmap.legendRender) {
expect(legendElement.textContent == '0 %').toBe(true);
}else{
expect(legendElement.textContent == '').toBe(true);
}
}
});
it('Checking cell toggle for smart legend', function () {
legendElement = document.getElementById('heatmapContainer_Smart_Legend1');
let element:ClientRect = legendElement.getBoundingClientRect();
trigger.clickEvent(legendElement, 0, 0, element.left + 2, element.top + 2);
expect(legendElement.getAttribute('fill') == 'rgb(153, 153, 255)');
});
it('Checking cell toggle based on legend selection', function () {
heatmap.legendSettings.enableSmartLegend = false;
heatmap.refresh();
legendElement = document.getElementById('heatmapContainer_legend_list3');
let element:ClientRect = legendElement.getBoundingClientRect();
trigger.clickEvent(legendElement, 0, 0, element.left + 2, element.top + 2);
expect(heatmap.legendModule.visibilityCollections[3]).toBe(false);
});
it('Checking toggled cell color after resizing', (done: Function) => {
heatmap.heatMapResize(event);
expect(heatmap.legendModule.visibilityCollections[3]).toBe(false);
setTimeout(done, 1600);
});
it('Checking cell toggle based on legend selection in canvas rendering', function () {
heatmap.renderingMode = 'Canvas';
heatmap.refresh();
legendElement = document.getElementById('heatmapContainer_canvas');
trigger.clickEvent(legendElement, 0, 0, 317, 266);
expect(heatmap.legendModule.visibilityCollections[3]).toBe(false);
});
it('Checking cell toggle based on legend selection in Canvas', function () {
heatmap.legendSettings.enableSmartLegend = true;
heatmap.renderingMode = 'Canvas';
heatmap.refresh();
legendElement = document.getElementById('heatmapContainer_canvas');
trigger.clickEvent(legendElement, 0, 0, 317, 266);
expect(heatmap.legendModule.visibilityCollections[2]).toBe(false);
});
it('Checking cell toggle when only colors are given in the palette collections', function () {
heatmap.renderingMode = 'SVG';
heatmap.legendSettings.enableSmartLegend = true;
heatmap.legendSettings.labelDisplayType = 'All';
heatmap.paletteSettings.palette = [
{ color: '#DCD57E' },
{ color: '#A6DC7E' },
{ color: '#7EDCA2' },
{ color: '#6EB5D0' }
],
heatmap.refresh();
legendElement = document.getElementById('heatmapContainer_Legend_Label3');
let region:ClientRect = legendElement.getBoundingClientRect();
trigger.clickEvent(legendElement, 0, 0, region.left + 2, region.top +5);
expect(heatmap.legendModule.visibilityCollections[4]).toBe(false);
});
it('Checking cell toggle for smart legend for bubble type size and color', function () {
heatmap.cellSettings.tileType = 'Bubble';
heatmap.cellSettings.bubbleType = 'SizeAndColor';
legendElement = document.getElementById('heatmapContainer_Smart_Legend1');
let element:ClientRect = legendElement.getBoundingClientRect();
trigger.clickEvent(legendElement, 0, 0, element.left + 2, element.top + 2);
expect(legendElement.getAttribute('fill') == 'rgb(153, 153, 255)');
});
it('Checking the pages per list when title size is increased', () => {
heatmap.legendSettings.position = 'Top';
heatmap.legendSettings.title.textStyle.color = 'Red';
heatmap.legendSettings.width = '50px';
heatmap.paletteSettings.type = 'Fixed';
heatmap.legendSettings.enableSmartLegend = false;
heatmap.dataBind();
let tempElement = document.getElementById('heatmapContainer_LegendBound');
expect(heatmap.legendModule.listPerPage).toBe(2);
});
it('Checking the text in bottom position of the heatmap when the width is not provided', () => {
heatmap.legendSettings.position = 'Bottom';
heatmap.legendSettings.width = '';
heatmap.paletteSettings.type = 'Gradient';
heatmap.legendSettings.title.textStyle.size = '11px';
heatmap.legendSettings.title.text = 'Sample';
heatmap.refresh();
heatmap.legendSettings.title.textStyle.textOverflow = 'None';
let element = document.getElementById('heatmapContainer_legendTitle');
expect(element.textContent == 'Sample').toBe(true);
});
it('Checking the height of the heatmap when the size is changed for the legend title in the Left position', () => {
heatmap.legendSettings.width = '';
heatmap.legendSettings.title.text = 'Sample';
heatmap.legendSettings.title.textStyle.textOverflow = 'None';
heatmap.legendSettings.title.textStyle.size = '67px';
heatmap.paletteSettings.type = 'Fixed';
heatmap.legendSettings.position = 'Left';
heatmap.legendSettings.enableSmartLegend = true;
heatmap.refresh();
expect(heatmap.height == '300px').toBe(true);
});
it('Checking the height of the heatmap when the size is changed for the legend title in the Right position', () => {
heatmap.legendSettings.width = '';
heatmap.legendSettings.title.textStyle.textOverflow = 'None';
heatmap.legendSettings.title.textStyle.size = '56px';
heatmap.paletteSettings.type = 'Fixed';
heatmap.legendSettings.position = 'Right';
heatmap.legendSettings.enableSmartLegend = true;
heatmap.refresh();
expect(heatmap.width == '500px').toBe(true);
});
it('Checking the height of the heatmap when the size is changed for the legend title in the Left position without smartlegend', () => {
heatmap.legendSettings.width = '';
heatmap.legendSettings.title.textStyle.textOverflow = 'None';
heatmap.legendSettings.title.textStyle.size = '56px';
heatmap.paletteSettings.type = 'Fixed';
heatmap.legendSettings.position = 'Right';
heatmap.legendSettings.enableSmartLegend = false;
heatmap.refresh();
expect(heatmap.width == '500px').toBe(true);
});
it('Checking the width when title size is changed in the Left direction', () => {
heatmap.legendSettings.width = '';
heatmap.legendSettings.title.textStyle.textOverflow = 'None';
heatmap.legendSettings.title.textStyle.size = '89px';
heatmap.paletteSettings.type = 'Fixed';
heatmap.legendSettings.position = 'Left';
heatmap.legendSettings.enableSmartLegend = true;
heatmap.refresh();
expect(heatmap.width == '500px').toBe(true);
});
it('Rendering SVG tooltip for legend title', () => {
heatmap.legendSettings.width = '5%';
heatmap.legendSettings.title.textStyle.textOverflow = 'Trim';
heatmap.refresh();
legendElement = document.getElementById('heatmapContainer_legendTitle');
trigger.mousemoveEvent(legendElement, 5, 5, 715, 73, false);
trigger.mousemoveEvent(legendElement, 5, 5, 715, 100, false);
trigger.mousemoveEvent(legendElement, 5, 5, 715, 73, false);
expect(document.getElementById('heatmapContainer_legendTitle_Tooltip').textContent == 'Sample').toBe(true);
});
it('Rendering canvas tooltip for legend title', function () {
heatmap.renderingMode = 'Canvas';
heatmap.legendSettings.position = 'Left';
heatmap.refresh();
legendElement = document.getElementById('heatmapContainer_canvas');
trigger.mousemoveEvent(legendElement, 5, 5, 30, 35, false);
let tooltip = document.getElementById('heatmapContainer_canvas_Tooltip');
expect(tooltip.textContent == 'Sample').toBe(true);
});
it('Rendering canvas tooltip for legend title', function () {
heatmap.renderingMode = 'Canvas';
heatmap.legendSettings.title.textStyle.size = '24px';
heatmap.legendSettings.width = '500px'
heatmap.legendSettings.position = 'Top';
heatmap.refresh();
legendElement = document.getElementById('heatmapContainer_canvas');
trigger.mousemoveEvent(legendElement, 5, 5, 75, 35, false);
trigger.mousemoveEvent(legendElement, 5, 5, 85, 35, false);
trigger.mousemoveEvent(legendElement, 5, 5, 65, 35, false);
trigger.mousemoveEvent(legendElement, 5, 5, 95, 35, false);
let tooltip = document.getElementById('heatmapContainer_canvas_Tooltip');
expect(tooltip.textContent == 'Sample').toBe(true);
});
it('Checking with showlabel set as false', function () {
heatmap.renderingMode = 'SVG';
heatmap.legendSettings.position = 'Bottom';
heatmap.legendSettings.title.text = 'Sample';
heatmap.paletteSettings.type = 'Fixed';
heatmap.legendSettings.title.textStyle.size = '14px';
heatmap.legendSettings.title.textStyle.textOverflow = 'None';
heatmap.legendSettings.alignment = 'Center';
heatmap.legendSettings.enableSmartLegend = false;
heatmap.legendSettings.showLabel = false;
heatmap.refresh();
tempElement = document.getElementById('heatmapContainer_Heatmap_LegendLabel');
expect(tempElement == null).toBe(true);
});
it('Checking with showlabel set as false', function () {
heatmap.renderingMode = 'SVG';
heatmap.legendSettings.position = 'Left';
heatmap.legendSettings.title.text = 'Sample';
heatmap.paletteSettings.type = 'Fixed';
heatmap.legendSettings.width = '';
heatmap.legendSettings.title.textStyle.size = '14px';
heatmap.legendSettings.title.textStyle.textOverflow = 'None';
heatmap.legendSettings.alignment = 'Center';
heatmap.legendSettings.enableSmartLegend = true;
heatmap.legendSettings.showLabel = true;
heatmap.refresh();
tempElement = document.getElementById('heatmapContainer_legendTitle');
expect(tempElement.textContent == 'Sample').toBe(true);
heatmap.legendSettings.position = 'Right';
heatmap.legendSettings.labelDisplayType = 'None';
heatmap.legendSettings.textStyle.textOverflow = 'Trim';
heatmap.refresh();
heatmap.legendRender = function (args:ILegendRenderEventArgs) {
args.cancel = true;
};
heatmap.paletteSettings.type = 'Gradient';
heatmap.refresh();
});
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
})
}); | the_stack |
import Koa from 'koa';
import config from 'config';
import autoBind from 'auto-bind';
import Logger from '@cardstack/logger';
import { inject } from '@cardstack/di';
import { OrderStatus, OrderState } from '../services/order';
import { WyreOrder, WyreTransfer, WyreWallet } from '../services/wyre';
import Web3 from 'web3';
import * as Sentry from '@sentry/node';
import { captureSentryMessage } from './utils/sentry';
const { toChecksumAddress } = Web3.utils;
let log = Logger('route:wyre-callback');
const env = config.get('hubEnvironment') as string;
interface WyreCallbackRequest {
id: string;
source: string;
dest: string;
currency: string;
amount: number;
status: WyreTransfer['status'];
createdAt: number;
}
interface ValidatedWalletReceiveRequest {
order: WyreOrder;
transfer: WyreTransfer;
wallet: WyreWallet;
}
interface ValidatedWalletSendRequest {
orderId: string;
reservationId: string | null;
userAddress: string;
transfer: WyreTransfer;
}
export const adminWalletName = `admin`;
export default class WyreCallbackRoute {
adminWalletId: string | undefined;
wyre = inject('wyre');
order = inject('order');
databaseManager = inject('database-manager', { as: 'databaseManager' });
constructor() {
autoBind(this);
}
async post(ctx: Koa.Context) {
let request = ctx.request.body;
log.info(`Received wyre callback: ${JSON.stringify(request, null, 2)}`);
try {
assertWyreCallbackRequest(request);
} catch (err) {
let message = `ignoring wyre callback that doesn't match the expected shape of a wyre callback request: ${JSON.stringify(
request,
null,
2
)}`;
log.info(message);
captureSentryMessage(message, ctx);
ctx.status = 400;
return;
}
let [sourceType] = request.source.split(':');
let [destType] = request.dest.split(':');
// keep in mind these are server callbacks so we should be pretty forgiving
// with erronous data and just log extensively
if (sourceType === 'transfer' && destType === 'wallet') {
Sentry.addBreadcrumb({ message: `wyre callback - custodial wallet receive: ${JSON.stringify(request)}` });
await this.processWalletReceive(request, ctx);
} else if (sourceType === 'wallet' && destType === 'transfer') {
Sentry.addBreadcrumb({ message: `wyre callback - custodial wallet send: ${JSON.stringify(request)}` });
await this.processWalletSend(request, ctx);
} else {
// this is some other thing we don't care about
Sentry.addBreadcrumb({ message: `wyre callback - unknown reason: ${JSON.stringify(request)}` });
log.info(`ignoring wyre callback with source ${request.source} and dest ${request.dest}`);
}
// we return no content because we don't want to leak any info to the caller
// about our wallets/transfers/orders or any internal state.
ctx.status = 204;
}
private async processWalletReceive(request: WyreCallbackRequest, ctx: Koa.Context) {
let validatedRequest = await this.validateWalletReceive(request);
if (!validatedRequest) {
captureSentryMessage(`wyre callback request failed validation: ${JSON.stringify(request)}`, ctx);
return;
}
let { wallet, transfer, order } = validatedRequest;
let { name: userAddress } = wallet;
let { id: custodialTransferId } = await this.wyre.transfer(
wallet.id,
await this.getAdminWalletId(),
transfer.destAmount,
transfer.destCurrency
);
let db = await this.databaseManager.getClient();
let { status: nextStatus } = await this.order.nextOrderStatus('wyre-receive-funds', order.id);
// We use an upsert as there will be no guarantee you'll get the order
// ID/reservation ID correlation from the card wallet before wyre calls the
// webhook
try {
await db.query(
`INSERT INTO wallet_orders (
order_id, user_address, wallet_id, custodial_transfer_id, status
) VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (order_id)
DO UPDATE SET
user_address = $2,
wallet_id = $3,
custodial_transfer_id = $4,
status = $5,
updated_at = now()`,
[order.id, userAddress.toLowerCase(), wallet.id, custodialTransferId, nextStatus]
);
} catch (err) {
let message = `Error: Failed to upsert wallet-orders row for the ${request.dest} receive of ${
transfer.source
}. Error is ${err.toString()}. request is: ${JSON.stringify(request, null, 2)}`;
log.error(message, err);
captureSentryMessage(message, ctx);
return;
}
}
private async processWalletSend(request: WyreCallbackRequest, ctx: Koa.Context) {
let validatedRequest = await this.validateWalletSend(request);
if (!validatedRequest) {
captureSentryMessage(`wyre callback request failed validation: ${JSON.stringify(request)}`, ctx);
return;
}
let { orderId, transfer } = validatedRequest;
let state: OrderState, status: OrderStatus;
try {
({ state, status } = await this.order.updateOrderStatus(orderId, 'wyre-send-funds'));
} catch (err) {
let message = `Error: Failed to locate wallet_orders record for ${request.dest} receive of ${
transfer.source
}. Error is ${err.toString()}. request is: ${JSON.stringify(request, null, 2)}`;
log.error(message, err);
captureSentryMessage(message, ctx);
return;
}
if (status === 'provisioning') {
let { reservationId } = state;
if (!reservationId) {
let message = `Encountered order ${orderId} in state provisioning without a reservation ID`;
log.error(message);
captureSentryMessage(message, ctx);
return;
}
try {
Sentry.addBreadcrumb({ message: `provisioning prepaid card for reservationId=${reservationId}` });
await this.order.provisionPrepaidCard(reservationId);
} catch (err) {
let message = `Could not provision prepaid card for reservationId ${reservationId}! Received error from relay server: ${err.toString()}`;
log.error(message, err);
captureSentryMessage(message, ctx);
return;
}
await this.order.updateOrderStatus(orderId, 'provision-mined');
}
}
private async validateWalletReceive(
request: WyreCallbackRequest
): Promise<ValidatedWalletReceiveRequest | undefined> {
let walletId = request.dest.split(':')[1];
let wallet = await this.wyre.getWalletById(walletId);
if (!wallet) {
let message = `while processing ${request.dest} receive, could not resolve user address for wyre wallet ID ${walletId}`;
log.info(message);
Sentry.addBreadcrumb({ message });
return;
}
let transferId = request.source.split(':')[1];
let transfer = await this.wyre.getTransfer(transferId);
if (!transfer) {
let message = `while processing ${request.dest} receive, could not find transfer for transferId ${request.source}`;
log.info(message);
Sentry.addBreadcrumb({ message });
return;
}
if (transfer.status !== 'COMPLETED') {
let message = `while processing ${request.dest} receive, transfer status for transferId ${request.source} is not COMPLETED it is ${transfer.status}`;
log.info(message);
Sentry.addBreadcrumb({ message });
return;
}
let orderId = transfer.source.split(':')[1];
// all wyre wallet order ID's start with "WO_"
if (!orderId.startsWith('WO_')) {
let message = `while processing ${request.dest} receive, source for ${transferId} is not a wallet order, ${transfer.source}. skipping`;
log.trace(message);
Sentry.addBreadcrumb({ message });
return;
}
let db = await this.databaseManager.getClient();
try {
let result = await db.query(
`SELECT status FROM wallet_orders WHERE order_id = $1 AND status != 'waiting-for-order'`,
[orderId]
);
if (result.rows.length > 0) {
let message = `while processing ${request.dest} receive, transfer ${request.source}'s order ${orderId} has already been processed. skipping`;
log.info(message);
Sentry.addBreadcrumb({ message });
return;
}
result = await db.query(`SELECT user_address FROM wallet_orders WHERE order_id = $1`, [orderId]);
if (result.rows.length > 0) {
let {
rows: [{ user_address: userAddress }],
} = result;
if (userAddress.toLowerCase() !== wallet.name.toLowerCase()) {
let message = `while processing ${request.dest} receive, transfer ${request.source}'s order ${orderId}, the related wallet ${wallet.id} is associated to a user address ${wallet.name} that is different than the user address the client already informed us about ${userAddress}. skipping`;
log.info(message);
Sentry.addBreadcrumb({ message });
return;
}
}
} catch (err) {
let message = `Error: while processing ${
request.dest
} receive, failed to query for wallet_orders record with an order ID of ${orderId}, for ${
request.dest
} receive of ${transfer.source}. Error: ${err.toString()}. request is: ${JSON.stringify(request, null, 2)}`;
log.error(message, err);
Sentry.addBreadcrumb({ message });
return;
}
let order = await this.wyre.getOrder(orderId);
if (!order) {
let message = `while processing ${request.dest} receive, could not find order for orderId ${transfer.source}`;
log.info(message);
Sentry.addBreadcrumb({ message });
return;
}
if (!request.source.endsWith(order.transferId)) {
// this is could be a spoofed callback from wyre
let message = `while processing ${request.dest} receive, ignoring wallet receive for transfer, transfer ${request.source} does not match ${transfer.source}'s transferId ${order.transferId}`;
log.info(message);
Sentry.addBreadcrumb({ message });
return;
}
let { depositAddresses } = wallet;
if (!depositAddresses || !order.dest.toLowerCase().endsWith(depositAddresses.ETH.toLowerCase())) {
// this is could be a spoofed callback from wyre
let message = `while processing ${request.dest} receive, ignoring wallet receive for wallet order whose destination ${order.dest} does not match the custodial wallet deposit address ${depositAddresses?.ETH}`;
log.info(message);
Sentry.addBreadcrumb({ message });
return;
}
return {
order,
transfer,
wallet,
};
}
private async validateWalletSend(request: WyreCallbackRequest): Promise<ValidatedWalletSendRequest | undefined> {
let transferId = request.dest.split(':')[1];
let transfer = await this.wyre.getTransfer(transferId);
if (!transfer) {
let message = `while processing ${request.source} send, could not find transfer for transferId ${request.dest}`;
log.info(message);
Sentry.addBreadcrumb({ message });
return;
}
if (transfer.status !== 'COMPLETED') {
let message = `while processing ${request.source} send, transfer status for transferId ${request.dest} is not COMPLETED, it is: ${transfer.status}`;
log.info(message);
Sentry.addBreadcrumb({ message });
return;
}
if (!(transfer.dest.endsWith(await this.getAdminWalletId()) && transfer.source === request.source)) {
// this is some other thing we don't care about or a spoofed callback
let message = `while processing ${request.source} send, ignoring wallet send for transfer ${request.dest}`;
log.info(message);
Sentry.addBreadcrumb({ message });
return;
}
let db = await this.databaseManager.getClient();
let orders: { id: string; reservationId: string; userAddress: string }[] = [];
try {
let result = await db.query(
`SELECT order_id, reservation_id, user_address FROM wallet_orders WHERE custodial_transfer_id = $1 AND status = 'received-order'`,
[transferId]
);
orders = result.rows.map((row) => ({
id: row.order_id,
reservationId: row.reservation_id,
userAddress: toChecksumAddress(row.user_address),
}));
} catch (err) {
let message = `Error: Failed to locate wallet_orders record for ${request.dest} receive of ${
transfer.source
}. Error is ${err.toString()}. request is: ${JSON.stringify(request.source, null, 2)}`;
log.error(message, err);
Sentry.addBreadcrumb({ message });
return;
}
let [order] = orders;
if (!order) {
let message = `while processing ${
request.source
} send to admin account, could not find wallet_orders with a status of "received-order" that correlate to the request with custodial transfer ID of ${transferId}. request is: ${JSON.stringify(
request,
null,
2
)}`;
log.info(message);
Sentry.addBreadcrumb({ message });
return;
}
return {
orderId: order.id,
reservationId: order.reservationId,
userAddress: order.userAddress,
transfer,
};
}
private async getAdminWalletId(): Promise<string> {
if (!this.adminWalletId) {
let adminWallet = await this.wyre.getWalletByUserAddress(adminWalletName); // this address has a very special name
this.adminWalletId = adminWallet?.id;
}
if (!this.adminWalletId) {
let message = `Error: Wyre admin wallet has not been created! Please create a wyre admin wallet with the name "${env}_${adminWalletName}" that has no callback URL.`;
log.error(message);
Sentry.addBreadcrumb({ message });
throw new Error(`Wyre admin wallet, ${env}_${adminWalletName}, has not been created`);
}
return this.adminWalletId;
}
}
function assertWyreCallbackRequest(request: any): asserts request is WyreCallbackRequest {
if (typeof request !== 'object') {
throw new Error(`object is not WyreCallbackRequest, expecting type object but was ${typeof request}`);
}
if (
!('source' in request) ||
!('dest' in request) ||
!('currency' in request) ||
!('amount' in request) ||
!('status' in request)
) {
let message = `object is not WyreCallbackRequest, expecting to find properties: "source", "dest", "currency", "amount", "status" but found: ${Object.keys(
request
).join(', ')}`;
Sentry.addBreadcrumb({ message });
throw new Error(message);
}
}
declare module '@cardstack/di' {
interface KnownServices {
'wyre-callback-route': WyreCallbackRoute;
}
} | the_stack |
import { Activity, Channels, RoleTypes, StatusCodes } from 'botframework-schema';
import { AuthenticateRequestResult } from './authenticateRequestResult';
import type { AuthenticationConfiguration } from './authenticationConfiguration';
import { AuthenticationConstants } from './authenticationConstants';
import { AuthenticationError } from './authenticationError';
import { BotFrameworkAuthentication } from './botFrameworkAuthentication';
import { ConnectorClientOptions } from '../connectorApi/models';
import type { ConnectorFactory } from './connectorFactory';
import { ConnectorFactoryImpl } from './connectorFactoryImpl';
import type { BotFrameworkClient } from '../skills';
import { BotFrameworkClientImpl } from './botFrameworkClientImpl';
import { Claim, ClaimsIdentity } from './claimsIdentity';
import { EmulatorValidation } from './emulatorValidation';
import { JwtTokenExtractor } from './jwtTokenExtractor';
import { JwtTokenValidation } from './jwtTokenValidation';
import type { ServiceClientCredentialsFactory } from './serviceClientCredentialsFactory';
import { SkillValidation } from './skillValidation';
import { ToBotFromBotOrEmulatorTokenValidationParameters } from './tokenValidationParameters';
import { UserTokenClientImpl } from './userTokenClientImpl';
import type { UserTokenClient } from './userTokenClient';
import { VerifyOptions } from 'jsonwebtoken';
function getAppId(claimsIdentity: ClaimsIdentity): string | undefined {
// For requests from channel App Id is in Audience claim of JWT token. For emulator it is in AppId claim. For
// unauthenticated requests we have anonymous claimsIdentity provided auth is disabled.
// For Activities coming from Emulator AppId claim contains the Bot's AAD AppId.
return (
claimsIdentity.getClaimValue(AuthenticationConstants.AudienceClaim) ??
claimsIdentity.getClaimValue(AuthenticationConstants.AppIdClaim) ??
undefined
);
}
// Internal
export class ParameterizedBotFrameworkAuthentication extends BotFrameworkAuthentication {
constructor(
private readonly validateAuthority: boolean,
private readonly toChannelFromBotLoginUrl: string,
private readonly toChannelFromBotOAuthScope: string,
private readonly toBotFromChannelTokenIssuer: string,
private readonly oAuthUrl: string,
private readonly toBotFromChannelOpenIdMetadataUrl: string,
private readonly toBotFromEmulatorOpenIdMetadataUrl: string,
private readonly callerId: string,
private readonly credentialsFactory: ServiceClientCredentialsFactory,
private readonly authConfiguration: AuthenticationConfiguration,
private readonly botFrameworkClientFetch?: (input: RequestInfo, init?: RequestInit) => Promise<Response>,
private readonly connectorClientOptions: ConnectorClientOptions = {}
) {
super();
}
getOriginatingAudience(): string {
return this.toChannelFromBotOAuthScope;
}
async authenticateChannelRequest(authHeader: string): Promise<ClaimsIdentity> {
if (!authHeader.trim()) {
const isAuthDisabled = await this.credentialsFactory.isAuthenticationDisabled();
if (!isAuthDisabled) {
throw new AuthenticationError(
'Unauthorized Access. Request is not authorized',
StatusCodes.UNAUTHORIZED
);
}
// In the scenario where auth is disabled, we still want to have the isAuthenticated flag set in the
// ClaimsIdentity. To do this requires adding in an empty claim. Since ChannelServiceHandler calls are
// always a skill callback call, we set the skill claim too.
return SkillValidation.createAnonymousSkillClaim();
}
return this.JwtTokenValidation_validateAuthHeader(authHeader, 'unknown', null);
}
async authenticateRequest(activity: Activity, authHeader: string): Promise<AuthenticateRequestResult> {
const claimsIdentity = await this.JwtTokenValidation_authenticateRequest(activity, authHeader);
const outboundAudience = SkillValidation.isSkillClaim(claimsIdentity.claims)
? JwtTokenValidation.getAppIdFromClaims(claimsIdentity.claims)
: this.toChannelFromBotOAuthScope;
const callerId = await this.generateCallerId(this.credentialsFactory, claimsIdentity, this.callerId);
const connectorFactory = new ConnectorFactoryImpl(
getAppId(claimsIdentity),
this.toChannelFromBotOAuthScope,
this.toChannelFromBotLoginUrl,
this.validateAuthority,
this.credentialsFactory
);
return {
audience: outboundAudience,
callerId,
claimsIdentity,
connectorFactory,
};
}
async authenticateStreamingRequest(
authHeader: string,
channelIdHeader: string
): Promise<AuthenticateRequestResult> {
if (!channelIdHeader?.trim() && !(await this.credentialsFactory.isAuthenticationDisabled())) {
throw new AuthenticationError("'channelIdHeader' required.", StatusCodes.UNAUTHORIZED);
}
const claimsIdentity = await this.JwtTokenValidation_validateAuthHeader(authHeader, channelIdHeader, null);
const outboundAudience = SkillValidation.isSkillClaim(claimsIdentity.claims)
? JwtTokenValidation.getAppIdFromClaims(claimsIdentity.claims)
: this.toChannelFromBotOAuthScope;
const callerId = await this.generateCallerId(this.credentialsFactory, claimsIdentity, this.callerId);
return { audience: outboundAudience, callerId, claimsIdentity };
}
async createUserTokenClient(claimsIdentity: ClaimsIdentity): Promise<UserTokenClient> {
const appId = getAppId(claimsIdentity);
const credentials = await this.credentialsFactory.createCredentials(
appId,
this.toChannelFromBotOAuthScope,
this.toChannelFromBotLoginUrl,
this.validateAuthority
);
return new UserTokenClientImpl(appId, credentials, this.oAuthUrl, this.connectorClientOptions);
}
createConnectorFactory(claimsIdentity: ClaimsIdentity): ConnectorFactory {
return new ConnectorFactoryImpl(
getAppId(claimsIdentity),
this.toChannelFromBotOAuthScope,
this.toChannelFromBotLoginUrl,
this.validateAuthority,
this.credentialsFactory
);
}
createBotFrameworkClient(): BotFrameworkClient {
return new BotFrameworkClientImpl(
this.credentialsFactory,
this.toChannelFromBotLoginUrl,
this.botFrameworkClientFetch
);
}
private async JwtTokenValidation_authenticateRequest(
activity: Partial<Activity>,
authHeader: string
): Promise<ClaimsIdentity> {
if (!authHeader.trim()) {
const isAuthDisabled = await this.credentialsFactory.isAuthenticationDisabled();
if (!isAuthDisabled) {
throw new AuthenticationError(
'Unauthorized Access. Request is not authorized',
StatusCodes.UNAUTHORIZED
);
}
// Check if the activity is for a skill call and is coming from the Emulator.
if (activity.channelId === Channels.Emulator && activity.recipient?.role === RoleTypes.Skill) {
return SkillValidation.createAnonymousSkillClaim();
}
// In the scenario where Auth is disabled, we still want to have the
// IsAuthenticated flag set in the ClaimsIdentity. To do this requires
// adding in an empty claim.
return new ClaimsIdentity([], AuthenticationConstants.AnonymousAuthType);
}
const claimsIdentity: ClaimsIdentity = await this.JwtTokenValidation_validateAuthHeader(
authHeader,
activity.channelId,
activity.serviceUrl
);
return claimsIdentity;
}
private async JwtTokenValidation_validateAuthHeader(
authHeader: string,
channelId: string,
serviceUrl = ''
): Promise<ClaimsIdentity> {
const identity = await this.JwtTokenValidation_authenticateToken(authHeader, channelId, serviceUrl);
await this.JwtTokenValidation_validateClaims(identity.claims);
return identity;
}
private async JwtTokenValidation_validateClaims(claims: Claim[] = []): Promise<void> {
if (this.authConfiguration.validateClaims) {
// Call the validation method if defined (it should throw an exception if the validation fails)
await this.authConfiguration.validateClaims(claims);
} else if (SkillValidation.isSkillClaim(claims)) {
// Skill claims must be validated using AuthenticationConfiguration validateClaims
throw new AuthenticationError(
'Unauthorized Access. Request is not authorized. Skill Claims require validation.',
StatusCodes.UNAUTHORIZED
);
}
}
private async JwtTokenValidation_authenticateToken(
authHeader: string,
channelId: string,
serviceUrl: string
): Promise<ClaimsIdentity | undefined> {
if (SkillValidation.isSkillToken(authHeader)) {
return this.SkillValidation_authenticateChannelToken(authHeader, channelId);
}
if (EmulatorValidation.isTokenFromEmulator(authHeader)) {
return this.EmulatorValidation_authenticateEmulatorToken(authHeader, channelId);
}
// Handle requests from BotFramework Channels
return this.ChannelValidation_authenticateChannelToken(authHeader, serviceUrl, channelId);
}
private async SkillValidation_authenticateChannelToken(
authHeader: string,
channelId: string
): Promise<ClaimsIdentity> {
// Add allowed token issuers from configuration.
const verifyOptions: VerifyOptions = {
...ToBotFromBotOrEmulatorTokenValidationParameters,
issuer: [
...ToBotFromBotOrEmulatorTokenValidationParameters.issuer,
...(this.authConfiguration.validTokenIssuers ?? []),
],
};
const tokenExtractor = new JwtTokenExtractor(
verifyOptions,
this.toBotFromEmulatorOpenIdMetadataUrl,
AuthenticationConstants.AllowedSigningAlgorithms
);
const parts: string[] = authHeader.split(' ');
const identity = await tokenExtractor.getIdentity(
parts[0],
parts[1],
channelId,
this.authConfiguration.requiredEndorsements
);
await this.SkillValidation_ValidateIdentity(identity);
return identity;
}
private async SkillValidation_ValidateIdentity(identity: ClaimsIdentity): Promise<void> {
if (!identity) {
// No valid identity. Not Authorized.
throw new AuthenticationError(
'SkillValidation.validateIdentity(): Invalid identity',
StatusCodes.UNAUTHORIZED
);
}
if (!identity.isAuthenticated) {
// The token is in some way invalid. Not Authorized.
throw new AuthenticationError(
'SkillValidation.validateIdentity(): Token not authenticated',
StatusCodes.UNAUTHORIZED
);
}
const versionClaim = identity.getClaimValue(AuthenticationConstants.VersionClaim);
if (!versionClaim) {
// No version claim
throw new AuthenticationError(
`SkillValidation.validateIdentity(): '${AuthenticationConstants.VersionClaim}' claim is required on skill Tokens.`,
StatusCodes.UNAUTHORIZED
);
}
// Look for the "aud" claim, but only if issued from the Bot Framework
const audienceClaim = identity.getClaimValue(AuthenticationConstants.AudienceClaim);
if (!audienceClaim) {
// Claim is not present or doesn't have a value. Not Authorized.
throw new AuthenticationError(
`SkillValidation.validateIdentity(): '${AuthenticationConstants.AudienceClaim}' claim is required on skill Tokens.`,
StatusCodes.UNAUTHORIZED
);
}
if (!(await this.credentialsFactory.isValidAppId(audienceClaim))) {
// The AppId is not valid. Not Authorized.
throw new AuthenticationError(
'SkillValidation.validateIdentity(): Invalid audience.',
StatusCodes.UNAUTHORIZED
);
}
const appId = JwtTokenValidation.getAppIdFromClaims(identity.claims);
if (!appId) {
// Invalid appId
throw new AuthenticationError(
'SkillValidation.validateIdentity(): Invalid appId.',
StatusCodes.UNAUTHORIZED
);
}
}
private async EmulatorValidation_authenticateEmulatorToken(
authHeader: string,
channelId: string
): Promise<ClaimsIdentity> {
// Add allowed token issuers from configuration.
const verifyOptions: VerifyOptions = {
...ToBotFromBotOrEmulatorTokenValidationParameters,
issuer: [
...ToBotFromBotOrEmulatorTokenValidationParameters.issuer,
...(this.authConfiguration.validTokenIssuers ?? []),
],
};
const tokenExtractor: JwtTokenExtractor = new JwtTokenExtractor(
verifyOptions,
this.toBotFromEmulatorOpenIdMetadataUrl,
AuthenticationConstants.AllowedSigningAlgorithms
);
const identity: ClaimsIdentity = await tokenExtractor.getIdentityFromAuthHeader(
authHeader,
channelId,
this.authConfiguration.requiredEndorsements
);
if (!identity) {
// No valid identity. Not Authorized.
throw new AuthenticationError('Unauthorized. No valid identity.', StatusCodes.UNAUTHORIZED);
}
if (!identity.isAuthenticated) {
// The token is in some way invalid. Not Authorized.
throw new AuthenticationError('Unauthorized. Is not authenticated', StatusCodes.UNAUTHORIZED);
}
// Now check that the AppID in the claimset matches
// what we're looking for. Note that in a multi-tenant bot, this value
// comes from developer code that may be reaching out to a service, hence the
// Async validation.
const versionClaim: string = identity.getClaimValue(AuthenticationConstants.VersionClaim);
if (versionClaim === null) {
throw new AuthenticationError(
'Unauthorized. "ver" claim is required on Emulator Tokens.',
StatusCodes.UNAUTHORIZED
);
}
let appId = '';
// The Emulator, depending on Version, sends the AppId via either the
// appid claim (Version 1) or the Authorized Party claim (Version 2).
if (!versionClaim || versionClaim === '1.0') {
// either no Version or a version of "1.0" means we should look for
// the claim in the "appid" claim.
const appIdClaim: string = identity.getClaimValue(AuthenticationConstants.AppIdClaim);
if (!appIdClaim) {
// No claim around AppID. Not Authorized.
throw new AuthenticationError(
'Unauthorized. "appid" claim is required on Emulator Token version "1.0".',
StatusCodes.UNAUTHORIZED
);
}
appId = appIdClaim;
} else if (versionClaim === '2.0') {
// Emulator, "2.0" puts the AppId in the "azp" claim.
const appZClaim: string = identity.getClaimValue(AuthenticationConstants.AuthorizedParty);
if (!appZClaim) {
// No claim around AppID. Not Authorized.
throw new AuthenticationError(
'Unauthorized. "azp" claim is required on Emulator Token version "2.0".',
StatusCodes.UNAUTHORIZED
);
}
appId = appZClaim;
} else {
// Unknown Version. Not Authorized.
throw new AuthenticationError(
`Unauthorized. Unknown Emulator Token version "${versionClaim}".`,
StatusCodes.UNAUTHORIZED
);
}
if (!(await this.credentialsFactory.isValidAppId(appId))) {
throw new AuthenticationError(
`Unauthorized. Invalid AppId passed on token: ${appId}`,
StatusCodes.UNAUTHORIZED
);
}
return identity;
}
private async ChannelValidation_authenticateChannelToken(
authHeader: string,
serviceUrl: string,
channelId: string
): Promise<ClaimsIdentity> {
const tokenValidationParameters = this.ChannelValidation_GetTokenValidationParameters();
const tokenExtractor: JwtTokenExtractor = new JwtTokenExtractor(
tokenValidationParameters,
this.toBotFromChannelOpenIdMetadataUrl,
AuthenticationConstants.AllowedSigningAlgorithms
);
const identity: ClaimsIdentity = await tokenExtractor.getIdentityFromAuthHeader(
authHeader,
channelId,
this.authConfiguration.requiredEndorsements
);
return this.governmentChannelValidation_ValidateIdentity(identity, serviceUrl);
}
private ChannelValidation_GetTokenValidationParameters(): VerifyOptions {
return {
issuer: [this.toBotFromChannelTokenIssuer],
audience: undefined, // Audience validation takes place manually in code.
clockTolerance: 5 * 60,
ignoreExpiration: false,
};
}
private async governmentChannelValidation_ValidateIdentity(
identity: ClaimsIdentity,
serviceUrl: string
): Promise<ClaimsIdentity> {
if (!identity) {
// No valid identity. Not Authorized.
throw new AuthenticationError('Unauthorized. No valid identity.', StatusCodes.UNAUTHORIZED);
}
if (!identity.isAuthenticated) {
// The token is in some way invalid. Not Authorized.
throw new AuthenticationError('Unauthorized. Is not authenticated', StatusCodes.UNAUTHORIZED);
}
// Now check that the AppID in the claimset matches
// what we're looking for. Note that in a multi-tenant bot, this value
// comes from developer code that may be reaching out to a service, hence the
// Async validation.
// Look for the "aud" claim, but only if issued from the Bot Framework
if (identity.getClaimValue(AuthenticationConstants.IssuerClaim) !== this.toBotFromChannelTokenIssuer) {
// The relevant Audiance Claim MUST be present. Not Authorized.
throw new AuthenticationError('Unauthorized. Issuer Claim MUST be present.', StatusCodes.UNAUTHORIZED);
}
// The AppId from the claim in the token must match the AppId specified by the developer.
// In this case, the token is destined for the app, so we find the app ID in the audience claim.
const audClaim: string = identity.getClaimValue(AuthenticationConstants.AudienceClaim);
if (!(await this.credentialsFactory.isValidAppId(audClaim || ''))) {
// The AppId is not valid or not present. Not Authorized.
throw new AuthenticationError(
`Unauthorized. Invalid AppId passed on token: ${audClaim}`,
StatusCodes.UNAUTHORIZED
);
}
if (serviceUrl) {
const serviceUrlClaim = identity.getClaimValue(AuthenticationConstants.ServiceUrlClaim);
if (serviceUrlClaim !== serviceUrl) {
// Claim must match. Not Authorized.
throw new AuthenticationError('Unauthorized. ServiceUrl claim do not match.', StatusCodes.UNAUTHORIZED);
}
}
return identity;
}
} | the_stack |
import Vue from 'vue';
import {SnotifyToast} from './components/toast.model';
import {ToastDefaults} from './toastDefaults';
import {SnotifyToastConfig, Snotify, SnotifyDefaults} from './interfaces';
import {SnotifyStyle} from './enums';
import {SnotifyType} from './types';
import {TransformArgument} from './decorators/transform-argument.decorator';
import {mergeDeep, uuid} from './utils';
import {SetToastType} from './decorators/set-toast-type.decorator';
/**
* this - create, remove, config toasts
*/
// tslint:disable:unified-signatures
export class SnotifyService {
readonly emitter = new Vue();
notifications: SnotifyToast[] = [];
config: SnotifyDefaults = ToastDefaults;
/**
* emit changes in notifications array
*/
emit(): void {
this.emitter.$emit('snotify', this.notifications.slice());
}
/**
* returns SnotifyToast object
* @param id {Number}
* @return {SnotifyToast|undefined}
*/
get(id: number): SnotifyToast {
return this.notifications.find(toast => toast.id === id);
}
/**
* add SnotifyToast to notifications array
* @param toast {SnotifyToast}
*/
add(toast: SnotifyToast): void {
if (this.config.global.newOnTop) {
this.notifications.unshift(toast);
} else {
this.notifications.push(toast);
}
this.emit();
}
/**
* If ID passed, emits toast animation remove, if ID & REMOVE passed, removes toast from notifications array
* @param id {number}
* @param remove {boolean}
*/
remove(id?: number| string, remove?: boolean): void {
if (!id) {
return this.clear();
} else if (remove) {
this.notifications = this.notifications.filter(toast => toast.id !== id);
return this.emit();
}
this.emitter.$emit('remove', id);
}
/**
* Clear notifications array
*/
clear(): void {
this.notifications = [];
this.emit();
}
button(text: string, closeOnClick: boolean = true, action: (toast?: SnotifyToast) => void = null, bold: boolean = false) {
return {
text,
action: closeOnClick ? (toast: SnotifyToast) => {
action(toast);
this.remove(toast.id);
} : action,
bold
};
}
/**
* Creates toast and add it to array, returns toast id
* @param snotify {Snotify}
* @return {number}
*/
create(snotify: Snotify): SnotifyToast {
if (this.config.global.oneAtTime && this.notifications.length !== 0) return;
if (this.config.global.preventDuplicates
&& this.notifications.filter(t => t.config.type === snotify.config.type).length === 1) return;
const config =
mergeDeep(this.config.toast, this.config.type[snotify.config.type], snotify.config) as SnotifyToastConfig;
const toast = new SnotifyToast(
config.id ? config.id : uuid(),
snotify.title,
snotify.body,
config
);
this.add(toast);
return toast;
}
setDefaults(defaults: SnotifyDefaults): SnotifyDefaults {
return this.config = mergeDeep(this.config, defaults) as SnotifyDefaults;
}
/**
* Create toast with simple style returns toast id;
* @param body {String}
* @returns {number}
*/
simple(body: string): SnotifyToast;
/**
* Create toast with simple style returns toast id;
* @param body {String}
* @param title {String}
* @returns {number}
*/
simple(body: string, title: string): SnotifyToast;
/**
* Create toast with simple style returns toast id;
* @param body {String}
* @param config {SnotifyToastConfig}
* @returns {number}
*/
simple(body: string, config: SnotifyToastConfig): SnotifyToast;
/**
* Create toast with simple style returns toast id;
* @param [body] {String}
* @param [title] {String}
* @param [config] {SnotifyToastConfig}
* @returns {number}
*/
simple(body: string, title: string, config: SnotifyToastConfig): SnotifyToast;
/**
* Transform toast arguments into {Snotify} object
*/
@TransformArgument
/**
* Determines current toast type and collects default configuration
*/
@SetToastType
simple(args: any): SnotifyToast {
return this.create(args);
}
/**
* Create toast with success style returns toast id;
* @param body {String}
* @returns {number}
*/
success(body: string): SnotifyToast;
/**
* Create toast with success style returns toast id;
* @param body {String}
* @param title {String}
* @returns {number}
*/
success(body: string, title: string): SnotifyToast;
/**
* Create toast with success style returns toast id;
* @param body {String}
* @param config {SnotifyToastConfig}
* @returns {number}
*/
success(body: string, config: SnotifyToastConfig): SnotifyToast;
/**
* Create toast with success style returns toast id;
* @param [body] {String}
* @param [title] {String}
* @param [config] {SnotifyToastConfig}
* @returns {number}
*/
success(body: string, title: string, config: SnotifyToastConfig): SnotifyToast;
/**
* Transform toast arguments into {Snotify} object
*/
@TransformArgument
/**
* Determines current toast type and collects default configuration
*/
@SetToastType
success(args: any): SnotifyToast {
return this.create(args);
}
/**
* Create toast with error style returns toast id;
* @param body {String}
* @returns {number}
*/
error(body: string): SnotifyToast;
/**
* Create toast with error style returns toast id;
* @param body {String}
* @param title {String}
* @returns {number}
*/
error(body: string, title: string): SnotifyToast;
/**
* Create toast with error style returns toast id;
* @param body {String}
* @param config {SnotifyToastConfig}
* @returns {number}
*/
error(body: string, config: SnotifyToastConfig): SnotifyToast;
/**
* Create toast with error style returns toast id;
* @param [body] {String}
* @param [title] {String}
* @param [config] {SnotifyToastConfig}
* @returns {number}
*/
error(body: string, title: string, config: SnotifyToastConfig): SnotifyToast;
/**
* Transform toast arguments into {Snotify} object
*/
@TransformArgument
/**
* Determines current toast type and collects default configuration
*/
@SetToastType
error(args: any): SnotifyToast {
return this.create(args);
}
/**
* Create toast with info style returns toast id;
* @param body {String}
* @returns {number}
*/
info(body: string): SnotifyToast;
/**
* Create toast with info style returns toast id;
* @param body {String}
* @param title {String}
* @returns {number}
*/
info(body: string, title: string): SnotifyToast;
/**
* Create toast with info style returns toast id;
* @param body {String}
* @param config {SnotifyToastConfig}
* @returns {number}
*/
info(body: string, config: SnotifyToastConfig): SnotifyToast;
/**
* Create toast with info style returns toast id;
* @param [body] {String}
* @param [title] {String}
* @param [config] {SnotifyToastConfig}
* @returns {number}
*/
info(body: string, title: string, config: SnotifyToastConfig): SnotifyToast;
/**
* Transform toast arguments into {Snotify} object
*/
@TransformArgument
/**
* Determines current toast type and collects default configuration
*/
@SetToastType
info(args: any): SnotifyToast {
return this.create(args);
}
/**
* Create toast with warning style returns toast id;
* @param body {String}
* @returns {number}
*/
warning(body: string): SnotifyToast;
/**
* Create toast with warning style returns toast id;
* @param body {String}
* @param title {String}
* @returns {number}
*/
warning(body: string, title: string): SnotifyToast;
/**
* Create toast with warning style returns toast id;
* @param body {String}
* @param config {SnotifyToastConfig}
* @returns {number}
*/
warning(body: string, config: SnotifyToastConfig): SnotifyToast;
/**
* Create toast with warning style returns toast id;
* @param [body] {String}
* @param [title] {String}
* @param [config] {SnotifyToastConfig}
* @returns {number}
*/
warning(body: string, title: string, config: SnotifyToastConfig): SnotifyToast;
/**
* Transform toast arguments into {Snotify} object
*/
@TransformArgument
/**
* Determines current toast type and collects default configuration
*/
@SetToastType
warning(args: any): SnotifyToast {
return this.create(args);
}
/**
* Create toast with confirm style returns toast id;
* @param body {String}
* @returns {number}
*/
confirm(body: string): SnotifyToast;
/**
* Create toast with confirm style returns toast id;
* @param body {String}
* @param title {String}
* @returns {number}
*/
confirm(body: string, title: string): SnotifyToast;
/**
* Create toast with confirm style returns toast id;
* @param body {String}
* @param config {SnotifyToastConfig}
* @returns {number}
*/
confirm(body: string, config: SnotifyToastConfig): SnotifyToast;
/**
* Create toast with confirm style returns toast id;
* @param [body] {String}
* @param [title] {String}
* @param [config] {SnotifyToastConfig}
* @returns {number}
*/
confirm(body: string, title: string, config: SnotifyToastConfig): SnotifyToast;
/**
* Transform toast arguments into {Snotify} object
*/
@TransformArgument
/**
* Determines current toast type and collects default configuration
*/
@SetToastType
confirm(args: any): SnotifyToast {
return this.create(args);
}
/**
* Create toast with Prompt style {with two buttons}, returns toast id;
* @param body {String}
* @returns {number}
*/
prompt(body: string): SnotifyToast;
/**
* Create toast with Prompt style {with two buttons}, returns toast id;
* @param body {String}
* @param title {String}
* @returns {number}
*/
prompt(body: string, title: string): SnotifyToast;
/**
* Create toast with Prompt style {with two buttons}, returns toast id;
* @param body {String}
* @param config {SnotifyToastConfig}
* @returns {number}
*/
prompt(body: string, config: SnotifyToastConfig): SnotifyToast;
/**
* Create toast with Prompt style {with two buttons}, returns toast id;
* @param [body] {String}
* @param [title] {String}
* @param [config] {SnotifyToastConfig}
* @returns {number}
*/
prompt(body: string, title: string, config: SnotifyToastConfig): SnotifyToast;
/**
* Transform toast arguments into {Snotify} object
*/
@TransformArgument
/**
* Determines current toast type and collects default configuration
*/
@SetToastType
prompt(args: any): SnotifyToast {
return this.create(args);
}
/**
* Creates async toast with Info style. Pass action, and resolve or reject it.
* @param body {String}
* @param action {() => Promise<Snotify>}
* @returns {number}
*/
async(body: string, action: () => Promise<Snotify>): SnotifyToast;
/**
* Creates async toast with Info style. Pass action, and resolve or reject it.
* @param body {String}
* @param title {String}
* @param action {() => Promise<Snotify>}
* @returns {number}
*/
async(body: string, title: string, action: () => Promise<Snotify>): SnotifyToast;
/**
* Creates async toast with Info style. Pass action, and resolve or reject it.
* @param body {String}
* @param action {() => Promise<Snotify>}
* @param [config] {SnotifyToastConfig}
* @returns {number}
*/
async(body: string, action: () => Promise<Snotify>, config: SnotifyToastConfig): SnotifyToast;
/**
* Creates async toast with Info style. Pass action, and resolve or reject it.
* @param body {String}
* @param title {String}
* @param action {() => Promise<Snotify>}
* @param [config] {SnotifyToastConfig}
* @returns {number}
*/
async(body: string, title: string, action: () => Promise<Snotify>, config: SnotifyToastConfig): SnotifyToast;
/**
* Transform toast arguments into {Snotify} object
*/
@TransformArgument
/**
* Determines current toast type and collects default configuration
*/
@SetToastType
async(args: any): SnotifyToast {
let async = args.action;
const toast = this.create(args);
toast.on('mounted',
() => {
async()
.then((next: Snotify) => this.mergeToast(toast, next, SnotifyStyle.success))
.catch((error?: Snotify) => this.mergeToast(toast, error, SnotifyStyle.error));
}
);
return toast;
}
mergeToast(toast, next, type?: SnotifyType) {
if (next.body) {
toast.body = next.body;
}
if (next.title) {
toast.title = next.title;
}
if (type) {
toast.config = mergeDeep(toast.config, this.config.global, this.config.toast[type], {type}, next.config);
} else {
toast.config = mergeDeep(toast.config, next.config);
}
if (next.html) {
toast.config.html = next.html;
}
this.emit();
this.emitter.$emit('toastChanged', toast);
}
/**
* Creates empty toast with html string inside
* @param {string} html
* @param {SnotifyToastConfig} config
* @returns {number}
*/
html(html: string, config?: SnotifyToastConfig): SnotifyToast {
return this.create({
title: null,
body: null,
config: {
...config,
...{html}
}
});
}
} | the_stack |
export as namespace nerdamer
export = nerdamer
declare function nerdamer(
expression: nerdamer.ExpressionParam,
subs?: { [name: string]: string },
option?: keyof nerdamer.Options | (keyof nerdamer.Options)[],
location?: nerdamer.int): nerdamer.Expression
declare namespace nerdamer {
export type ExpressionParam = Expression | string
export interface Options {
numer: never, expand: never
}
type int = number
/**
* Returns the current version of nerdamer.
*/
export function version(): string
/**
* Sets a constant value which nerdamer will automatically substitute when parsing expression/equation
* @param name The variable to be set as the constant.
* @param value The value for the expression to be set to.
*/
export function setConstant(name: string, value: number | string): typeof nerdamer
/**
* Sets a function which can then be called using nerdamer.
* @param function_name The function name
* @param param_array The parameter array in the order in which the arguments are to be passed
* @param function_body The body of the function
* @example
* nerdamer.setFunction('f', ['x', 'y'], 'x^2+y')
* var x = nerdamer('f(4, 7)').toString()
* console.log(x.toString())
* nerdamer.setFunction('g', ['z', 'x', 'y'], '2*x+3*y+4*z')
* x = nerdamer('g(3, 1, 2)')
* console.log(x.toString())
*/
export function setFunction(function_name: string, param_array: string[], function_body: string): typeof nerdamer
/**
* Returns the nerdamer core object. This object contains all the core functions of nerdamer and houses the parser.
* @example
* Object.keys(nerdamer.getCore())
*/
export function getCore(): any
/**
* Gets the list of reserved names. This is a list of names already in use by nerdamer excluding variable names. This is not a static list.
* @param asArray Pass in true to get the list back as an array instead of as an object.
*/
export function reserved(asArray: true): string[]
export function reserved(asArray?: false): any
/**
* Clears all stored expressions.
* @example
* var x = nerdamer('x*x')
console.log(nerdamer.expressions())
nerdamer.flush() //clear all expressions
console.log(nerdamer.expressions())
*/
export function flush(): typeof nerdamer
/**
* Converts and expression to LaTeX without evaluating expression.
* @param expression The expression being converted.
*/
export function convertToLaTeX(expression: string): string
/**
* Each time an expression is parsed nerdamer stores the result. Use this method to get back stored expressions.
* @param asObject Pass in true to get expressions as numbered object with 1 as starting index
* @param asLatex Pass in the string "LaTeX" to get the expression to LaTeX, otherwise expressions come back as strings
*/
export function expressions(asObject?: boolean, asLatex?: 'LaTeX'): string[]
/**
* Registers a module function with nerdamer. The object needs to contain at a minimum, a name property (text), a numargs property (int), this is -1 for variable arguments or an array containing the min and max arguments, the visible property (bool) which allows use of this function through nerdamer, defaults to true, and a build property containing a function which returns the function to be used. This function is also handy for creating aliases to functions. See below how the alias D was created for the diff function).
* @param o
*/
export interface ModuleFunction {
/**
* Name of function.
*/
name: string,
/**
* Number of function arguments, -1 for variable arguments or an tuple containing minimum and maximum number of arguments.
*/
numargs: int | [int, int],
/**
* Allows use of this function through nerdamer. Defaults to true.
*/
visible?: boolean,
/**
* Return the function to be used.
*/
build(): (...args: number[]) => number
}
/**
* Registers one or more module functions with nerdamer.
* @param f
* @example
* var core = nerdamer.getCore()
var _ = core.PARSER
function f(a, b) {
//use clone for safety since a or b might be returned
var sum = _.add(a.clone(), b.clone())
var product = _.multiply(a.clone(), b.clone())
return _.multiply(sum, product)
}
//register the function with nerdamer
nerdamer.register({
name: 'myFunction',
numargs: 2,
visible: true,
build: function(){ return f }
})
//create an alias for the diff function
var core = nerdamer.getCore()
nerdamer.register({
name: 'D',
visible: true,
numargs: [1, 3],
build: function(){ return core.Calculus.diff }
})
*/
export function register(f: ModuleFunction | ModuleFunction[]): typeof nerdamer
/**
* This method can be used to check that the variable meets variable name requirements for nerdamer. Variable names Must start with a letter or underscore and may contains any combination of numbers, letters, and underscores after that.
* @param variable_name The variable name being validated.
* @example
* nerdamer.validVarName('cos') // false
* nerdamer.validVarName('chicken1') // true
* nerdamer.validVarName('1chicken') // false
* nerdamer.validVarName('_') // true
*/
export function validVarName(variable_name: string): boolean
/**
* Sets a known value in nerdamer. This differs from setConstant as the value can be overridden trough the scope. See example.
* @param name The known value to be set.
* @param value The value for the expression to be set to
* @example
* nerdamer.setVar('x', '11')
* nerdamer('x*x') // == 121
* // nerdamer will use 13 instead of 11:
* nerdamer('x*x', {x: 13}) // == 169
* // the value will be 121 again since the known value isn't being overridden:
* nerdamer('x*x') // == 121
* nerdamer.setVar('x', 'delete')
* // since there no longer is a known value it will just be evaluated symbolically:
* nerdamer('x*x') // == x^2
*/
export function setVar(name: string, value: number | string | 'delete'): void
/**
* Clears all previously set variables.
*/
export function clearVars(): typeof nerdamer
/**
* Gets all previously set variables.
* @param option Use "LaTeX" to get as LaTeX. Defaults to text.
*/
export function getVars(option: 'LaTeX' | 'text'): { [name: string]: string }
/**
* Sets the value of a nerdamer setting. Currently PARSE2NUMBER and IMAGINARY. Setting PARSE2NUMBER to true will let nerdamer always try to return a number whenenver possible. IMAGINARY allows you to change the variable used for imaginary to j for instance.
* @param setting The setting to be changed
* @param value The value to set the setting to.
* @example
* nerdamer.set('PARSE2NUMBER', true)
* nerdamer('cos(9)+1') // == 14846499/167059106
* nerdamer.set('IMAGINARY', 'j')
* nerdamer('sqrt(-1)') // == j
*/
export function set(setting: 'PARSE2NUMBER', value: boolean): typeof nerdamer
export function set(setting: 'IMAGINARY', value: string | 'i'): typeof nerdamer
export function set(setting: 'POWER_OPERATOR', value: '**' | '^'): typeof nerdamer
export interface Expression {
/**
* Generates a JavaScript function given the expression. This is perfect for plotting and filtering user input. Plotting for the demo is accomplished using this. The order of the parameters is in alphabetical order by default but an argument array can be provided with the desired order.
* @param args_array The argument array with the order in which they are preferred.
*/
buildFunction(args_array: string[]): (...args: number[]) => number
/**
* Forces evaluation of the expression.
* @example
* const x = nerdamer('sin(9+5)')
* //the expression is simplified but the functions aren't called:
* x.toString() // == sin(14)
* // force function calls with evaluate:
* x.evaluate().toString() // == 127690464/128901187
*/
evaluate(): Expression
/**
* Substitutes a given value for another given value
* @param value The value being substituted.
* @param for_value The value to substitute for.
*/
sub(value: string, for_value: string): Expression
/**
* Get a list of the variables contained within the expression.
*/
variables(): string[]
/**
* Gets expression as LaTeX
*/
toTeX(): string
/**
* Gets the list of reserved names. This is a list of names already in use by nerdamer excluding variable names. This is not a static list.
* @param outputType Pass in the string 'decimals' to always get back numers as decimals. Pass in the string 'fractions' to always get back number as fractions. Defaults to decimals.
*/
text(outputType?: 'decimals' | 'fractions'): string
/**
* This method requires that the Solve, Calculus, and Algebra add-ons are loaded. It will attempt to solve an equation. If solutions no solutions are found then an empty array is returned. It can solve for multivariate polynomials up to the third degree. After which it can solve numerically for polynomials up to the the 100th degree. If it's a univariate equation it will attempt to solve it using numerical methods.
* @param variable The variable to solve for.
* @example
* nerdamer('a*x^2+b*x=y').evaluate({y: 'x-7'}) // == ??
* eq.solveFor('x') // ?? TODO
*/
solveFor(variable: string): Expression
}
////////// CALCULUS
/**
* Gets the GCD of 2 polynomials
* @param expression Returns the appropriate value if possible otherwise it returns the function with the simplified expression.
* @param index The index of summation.
* @param lower Starting index.
* @param upper Ending index.
*/
export function sum(expression: ExpressionParam,
index: string,
lower: ExpressionParam,
upper: ExpressionParam): Expression
/**
*
* @param expression Returns the appropriate value if possible otherwise it returns the function with the simplified expression.
* @param variable The variable with respect to which to integrate.
*/
export function integrate(expression: ExpressionParam, variable: string): Expression
/**
*
* @param expression Returns the appropriate value if possible otherwise it returns the function with the simplified expression.
* @param variable The variable with respect to which to differentiate.
* @param n Calculate the nth derivative.
*/
export function diff(expression: ExpressionParam, variable: string, n?: int): Expression
////////// ALGEBRA
/**
* Divides 2 polynominals.
* @param expression Returns the appropriate value if possible otherwise it returns the function with the simplified expression.
*/
export function divide(expression: ExpressionParam): Expression
/**
* Factor an expression.
* @param expression Returns the appropriate value if possible otherwise it returns the function with the simplified expression.
*/
export function factor(expression: ExpressionParam): Expression
/**
* Gets the GCD of 2 polynomials.
* @param expression Returns the appropriate value if possible otherwise it returns the function with the simplified expression.
*/
export function gcd(expression: ExpressionParam): Expression
/**
* Finds the roots of a univariate polynomial.
* @param expression
*/
export function factor(expression: ExpressionParam): Expression
} | the_stack |
import * as svg from './svgUtil'
import { SideBarHost, SideBar } from './sidebar';
import { SpriteHeaderHost, SpriteHeader } from './header';
import { CanvasGrid } from './canvasGrid';
import { ReporterBar } from './reporterBar';
import {
Edit, PaintTool, getPaintToolShortcut,
PaintEdit, OutlineEdit, LineEdit, CircleEdit, FillEdit, MarqueeEdit
} from './tools';
import { Bitmap, resizeBitmap } from './bitmap';
import { CanvasState } from './canvasState';
import { TextButton, UndoRedoGroup } from './buttons';
import { tickEvent } from '../telemetry/appinsights';
export const TOTAL_HEIGHT = 465;
const PADDING = 10;
const DROP_DOWN_PADDING = 4;
// Height of toolbar (the buttons above the canvas)
export const HEADER_HEIGHT = 0;
// Spacing between the toolbar and the canvas
const HEADER_CANVAS_MARGIN = 10;
// Height of the bar that displays editor size and info below the canvas
const REPORTER_BAR_HEIGHT = 31;
// Spacing between the canvas and reporter bar
const REPORTER_BAR_CANVAS_MARGIN = 5;
// Spacing between palette and paint surface
const SIDEBAR_CANVAS_MARGIN = 10;
const SIDEBAR_WIDTH = 65;
// Total allowed height of paint surface
const CANVAS_HEIGHT = 500 - HEADER_HEIGHT - HEADER_CANVAS_MARGIN
- REPORTER_BAR_HEIGHT - REPORTER_BAR_CANVAS_MARGIN - PADDING + DROP_DOWN_PADDING * 2;
const WIDTH = PADDING + SIDEBAR_WIDTH + SIDEBAR_CANVAS_MARGIN + CANVAS_HEIGHT + PADDING - DROP_DOWN_PADDING * 2;
export const COLORS = [
"#ffffff",
"#ff2121",
"#ff93c4",
"#ff8135",
"#fff609",
"#249ca3",
"#78dc52",
"#003fad",
"#87f2ff",
"#8e2ec4",
"#a4839f",
"#5c406c",
"#e5cdc4",
"#91463d",
"#000000"
];
export class SpriteEditor implements SideBarHost, SpriteHeaderHost {
private group: svg.Group;
private toolbarRoot: svg.SVG;
private paintSurface: CanvasGrid;
private sidebar: SideBar;
private header: SpriteHeader;
// private bottomBar: ReporterBar;
// private gallery: Gallery;
private state: CanvasState;
// When changing the size, keep the old bitmap around so that we can restore it
private cachedState: CanvasState;
private edit: Edit;
private activeTool: PaintTool = PaintTool.Normal;
private toolWidth = 1;
public color = 1;
private cursorCol = 0;
private cursorRow = 0;
private undoStack: CanvasState[] = [];
private redoStack: CanvasState[] = [];
private undoRedo: UndoRedoGroup = undefined;
private columns: number = 16;
private rows: number = 16;
private shiftDown: boolean = false;
private altDown: boolean = false;
private mouseDown: boolean = false;
private closeHandler: () => void;
public paintGestureCount: number = 0;
public paintGestureInterval: any;
constructor(bitmap: Bitmap, blocksInfo?: {}, protected lightMode = false, public scale = 1) {
this.columns = bitmap.width;
this.rows = bitmap.height;
this.state = new CanvasState(bitmap.copy())
this.toolbarRoot = new svg.SVG();
this.toolbarRoot.setClass("sprite-canvas-controls");
this.group = this.toolbarRoot.group();
this.createDefs();
this.paintSurface = new CanvasGrid(COLORS, this.state.copy(), this.lightMode, this.scale);
this.paintSurface.drag((col, row) => {
this.debug("gesture (" + PaintTool[this.activeTool] + ")");
if (!this.altDown) {
this.setCell(col, row, this.color, false);
}
// this.bottomBar.updateCursor(col, row);
});
this.paintGestureInterval = setInterval(this.logEvents, 5000);
this.paintSurface.up((col, row) => {
this.debug("gesture end (" + PaintTool[this.activeTool] + ")");
this.paintGestureCount += 1;
if (this.altDown) {
const color = this.state.image.get(col, row);
this.sidebar.setColor(color);
} else {
this.paintSurface.onEditEnd(col, row, this.edit);
if (this.state.floatingLayer && !this.paintSurface.state.floatingLayer) {
this.pushState(true);
this.state = this.paintSurface.state.copy();
this.rePaint();
}
this.commit();
this.shiftAction();
}
this.mouseDown = false;
});
this.paintSurface.down((col, row) => {
if (!this.altDown) {
this.setCell(col, row, this.color, false);
}
this.mouseDown = true;
});
this.paintSurface.move((col, row) => {
this.drawCursor(col, row);
this.shiftAction()
// this.bottomBar.updateCursor(col, row);
});
this.paintSurface.leave(() => {
if (this.edit) {
this.rePaint();
if (this.edit.isStarted && !this.shiftDown) {
this.commit();
}
}
// this.bottomBar.hideCursor();
});
this.sidebar = new SideBar(['url("#alpha-background")'].concat(COLORS), this, this.group);
this.sidebar.setColor(COLORS.length >= 3 ? 3 : 1); // colors omits 0
// this.header = new SpriteHeader(this);
// this.gallery = new Gallery(blocksInfo);
// this.bottomBar = new ReporterBar(this.group, this, REPORTER_BAR_HEIGHT);
this.updateUndoRedo();
// Sets canvas scale
this.scale = scale;
}
setSidebarColor(color: number) {
this.sidebar.setColor(color);
}
setCell(col: number, row: number, color: number, commit: boolean): void {
if (commit) {
this.state.image.set(col, row, color);
this.paintCell(col, row, color);
}
else if (this.edit) {
if (!this.edit.isStarted) {
this.paintSurface.onEditStart(col, row, this.edit);
if (this.state.floatingLayer && !this.paintSurface.state.floatingLayer) {
this.pushState(true);
this.state = this.paintSurface.state.copy();
}
}
this.edit.update(col, row);
this.cursorCol = col;
this.cursorRow = row;
this.paintEdit(this.edit, col, row);
}
}
render(el: HTMLDivElement): void {
// el.appendChild(this.header.getElement());
// el.appendChild(this.gallery.getElement());
el.appendChild(this.toolbarRoot.el);
this.layout();
// this.toolbarRoot.attr({ "width": `${65}px`, "height": this.outerHeight() + "px" });
// this.toolbarRoot.el.style.position = "absolute";
// this.toolbarRoot.el.style.top = "0px";
// this.toolbarRoot.el.style.left = "0px";
let canvasHolder = document.createElement("div")
canvasHolder.setAttribute("class", "sprite-canvas-container")
el.appendChild(canvasHolder)
this.paintSurface.render(canvasHolder);
}
layout(): void {
if (!this.toolbarRoot) {
return;
}
this.paintSurface.setGridDimensions(CANVAS_HEIGHT);
// The width of the palette + editor
const paintAreaTop = (HEADER_HEIGHT + HEADER_CANVAS_MARGIN);
const paintAreaLeft = (PADDING + SIDEBAR_WIDTH + SIDEBAR_CANVAS_MARGIN);
// this.sidebar.translate(PADDING, paintAreaTop);
// TODO(dz): hacky scaling
this.paintSurface.updateBounds(paintAreaTop, paintAreaLeft, CANVAS_HEIGHT, CANVAS_HEIGHT);
// this.bottomBar.layout(
// HEADER_HEIGHT + HEADER_CANVAS_MARGIN + (CANVAS_HEIGHT + REPORTER_BAR_CANVAS_MARGIN),
// PADDING + SIDEBAR_WIDTH + SIDEBAR_CANVAS_MARGIN, CANVAS_HEIGHT);
// this.gallery.layout(0, HEADER_HEIGHT, TOTAL_HEIGHT - HEADER_HEIGHT);
// this.header.layout();
}
rePaint() {
this.paintSurface.repaint();
}
setActiveColor(color: number, setPalette = false) {
if (setPalette) {
}
else if (this.color != color) {
this.color = color;
// If the user is erasing, go back to pencil
if (this.activeTool === PaintTool.Erase) {
this.sidebar.setTool(PaintTool.Normal);
} else {
this.updateEdit();
}
}
}
setActiveTool(tool: PaintTool) {
if (this.activeTool != tool) {
this.activeTool = tool;
this.updateEdit()
}
}
setToolWidth(width: number) {
if (this.toolWidth != width) {
this.toolWidth = width;
this.updateEdit();
}
}
initializeUndoRedo(undoStack: CanvasState[], redoStack: CanvasState[]) {
if (undoStack) {
this.undoStack = undoStack;
}
if (redoStack) {
this.redoStack = redoStack;
}
this.updateUndoRedo();
}
getUndoStack() {
return this.undoStack.slice();
}
getRedoStack() {
return this.redoStack.slice();
}
undo() {
if (this.undoStack.length) {
this.debug("undo");
tickEvent("shareExperiment.mod.undo");
const todo = this.undoStack.pop();
this.pushState(false);
// The current state is at the top of the stack unless the user has pressed redo, so
// we need to discard it
if (todo.equals(this.state)) {
this.undo();
return;
}
this.restore(todo);
}
this.updateUndoRedo();
}
redo() {
if (this.redoStack.length) {
this.debug("redo");
tickEvent("shareExperiment.mod.redo");
const todo = this.redoStack.pop();
this.pushState(true);
this.restore(todo);
}
this.updateUndoRedo();
}
resize(width: number, height: number) {
if (!this.cachedState) {
this.cachedState = this.state.copy();
this.undoStack.push(this.cachedState)
this.redoStack = [];
}
this.state.image = resizeBitmap(this.cachedState.image, width, height);
this.afterResize(true);
}
setSizePresets(presets: [number, number][]) {
// this.bottomBar.setSizePresets(presets, this.columns, this.rows);
}
canvasWidth() {
return this.columns;
}
canvasHeight() {
return this.rows;
}
outerWidth() {
return WIDTH;
}
outerHeight() {
return TOTAL_HEIGHT;
}
bitmap() {
return this.state;
}
showGallery() {
/*
this.gallery.show((result: Bitmap, err?: string) => {
if (err && err !== "cancelled") {
console.error(err);
}
else if (result) {
this.redoStack = [];
this.pushState(true);
this.restore(new CanvasState(result));
this.hideGallery();
this.header.toggle.toggle(true);
}
});*/
}
hideGallery() {
//this.gallery.hide();
}
closeEditor() {
if (this.closeHandler) {
const ch = this.closeHandler;
this.closeHandler = undefined;
ch();
}
if (this.state.floatingLayer) {
this.state.mergeFloatingLayer();
this.pushState(true);
}
}
onClose(handler: () => void) {
this.closeHandler = handler;
}
switchIconTo(tool: PaintTool) {
if (this.activeTool === tool) return;
const btn = this.sidebar.getButtonForTool(tool) as TextButton;
switch (tool) {
case PaintTool.Rectangle:
updateIcon(btn, "\uf096", ("Rectangle"));
break;
case PaintTool.Circle:
updateIcon(btn, "\uf10c", ("Circle"));
break;
case PaintTool.Normal:
updateIcon(btn, "\uf040", ("Pencil"));
break;
case PaintTool.Line:
updateIcon(btn, "\uf07e", ("Line"));
break;
default: // no alternate icon, do not change
return;
}
btn.onClick(() => {
if (tool != PaintTool.Circle && tool != PaintTool.Line) {
this.setIconsToDefault();
this.sidebar.setTool(tool);
}
});
function updateIcon(button: TextButton, text: string, title: string) {
const shortcut = getPaintToolShortcut(tool);
button.setText(text);
button.title(title);
button.shortcut(shortcut);
}
}
setIconsToDefault() {
this.switchIconTo(PaintTool.Rectangle);
this.switchIconTo(PaintTool.Normal);
}
logEvents = () => {
if (this.paintGestureCount > 0) {
tickEvent("shareExperiment.mod.paintGestureUp", {"count": this.paintGestureCount});
this.paintGestureCount = 0;
}
}
cleanupInterval = () => {
clearInterval(this.paintGestureInterval);
this.paintGestureInterval = null;
}
private keyDown = (event: KeyboardEvent) => {
if (event.keyCode == 16) { // Shift
this.shiftDown = true;
this.shiftAction();
}
if (event.keyCode === 18) { // Alt
this.discardEdit();
this.paintSurface.setEyedropperMouse(true);
this.altDown = true;
}
if (this.state.floatingLayer) {
let didSomething = true;
switch (event.keyCode) {
case 8: // backspace
case 46: // delete
event.preventDefault();
event.stopPropagation();
this.state.floatingLayer = undefined;
break;
case 37: // Left arrow
this.state.layerOffsetX--;
break;
case 38: // Up arrow
this.state.layerOffsetY--;
break;
case 39: // Right arrow
this.state.layerOffsetX++;
break;
case 40: // Down arrow
this.state.layerOffsetY++;
break;
default:
didSomething = false;
}
if (didSomething) {
this.updateEdit();
this.pushState(true);
this.paintSurface.restore(this.state, true);
}
}
const tools = [
PaintTool.Fill,
PaintTool.Normal,
PaintTool.Rectangle,
PaintTool.Erase,
PaintTool.Circle,
PaintTool.Line,
PaintTool.Marquee
]
tools.forEach(tool => {
if (event.key === getPaintToolShortcut(tool)) {
this.setIconsToDefault();
this.switchIconTo(tool);
this.sidebar.setTool(tool);
}
});
const zeroKeyCode = 48;
const nineKeyCode = 57;
if (event.keyCode >= zeroKeyCode && event.keyCode <= nineKeyCode) {
let color = event.keyCode - zeroKeyCode;
if (this.shiftDown) {
color += 9;
}
if (color <= COLORS.length) { // colors omits 0
this.sidebar.setColor(color);
}
}
}
private keyUp = (event: KeyboardEvent) => {
// If not drawing a circle, switch back to Rectangle and Pencil
if (event.keyCode === 16) { // Shift
this.shiftDown = false;
this.clearShiftAction();
} else if (event.keyCode === 18) { // Alt
this.altDown = false;
this.paintSurface.setEyedropperMouse(false);
this.updateEdit();
}
}
private undoRedoEvent = (event: KeyboardEvent) => {
const controlOrMeta = event.ctrlKey || event.metaKey; // ctrl on windows, meta on mac
if (event.key === "Undo" || (controlOrMeta && event.key === "z")) {
this.undo();
event.preventDefault();
event.stopPropagation();
} else if (event.key === "Redo" || (controlOrMeta && event.key === "y")) {
this.redo();
event.preventDefault();
event.stopPropagation();
}
}
addKeyListeners() {
document.addEventListener("keydown", this.keyDown);
document.addEventListener("keyup", this.keyUp);
document.addEventListener("keydown", this.undoRedoEvent, true);
}
removeKeyListeners() {
document.removeEventListener("keydown", this.keyDown);
document.removeEventListener("keyup", this.keyUp);
document.removeEventListener("keydown", this.undoRedoEvent, true);
this.paintSurface.removeMouseListeners();
}
private afterResize(showOverlay: boolean) {
this.columns = this.state.width;
this.rows = this.state.height;
this.paintSurface.restore(this.state, true);
// this.bottomBar.updateDimensions(this.columns, this.rows);
this.layout();
if (showOverlay) this.paintSurface.showResizeOverlay();
// Canvas size changed and some edits rely on that (like paint)
this.updateEdit();
}
private drawCursor(col: number, row: number) {
if (this.edit) {
this.paintSurface.drawCursor(this.edit, col, row);
}
}
private paintEdit(edit: Edit, col: number, row: number, gestureEnd = false) {
this.paintSurface.restore(this.state);
this.paintSurface.applyEdit(edit, col, row, gestureEnd);
}
public commit() {
if (this.edit) {
if (this.cachedState) {
this.cachedState = undefined;
}
this.pushState(true);
this.paintEdit(this.edit, this.cursorCol, this.cursorRow, true);
this.state = this.paintSurface.state.copy();
this.updateEdit();
this.redoStack = [];
}
}
private pushState(undo: boolean) {
const stack = undo ? this.undoStack : this.redoStack;
if (stack.length && this.state.equals(stack[stack.length - 1])) {
// Don't push empty commits
return;
}
stack.push(this.state.copy());
this.updateUndoRedo();
}
private discardEdit() {
if (this.edit) {
this.edit = undefined;
this.rePaint();
}
}
private updateEdit() {
if (!this.altDown) {
this.edit = this.newEdit();
}
}
private restore(state: CanvasState) {
if (state.width !== this.state.width || state.height !== this.state.height) {
this.state = state;
this.afterResize(false);
}
else {
this.state = state.copy();
this.paintSurface.restore(state, true);
}
}
private updateUndoRedo() {
// this.bottomBar.updateUndoRedo(this.undoStack.length === 0, this.redoStack.length === 0)
this.sidebar.updateUndoRedo(this.undoStack.length === 0, this.redoStack.length === 0)
}
private paintCell(col: number, row: number, color: number) {
this.paintSurface.writeColor(col, row, color);
}
private newEdit() {
switch (this.activeTool) {
case PaintTool.Normal:
return new PaintEdit(this.columns, this.rows, this.color, this.toolWidth);
case PaintTool.Rectangle:
return new OutlineEdit(this.columns, this.rows, this.color, this.toolWidth);
case PaintTool.Outline:
return new OutlineEdit(this.columns, this.rows, this.color, this.toolWidth);
case PaintTool.Line:
return new LineEdit(this.columns, this.rows, this.color, this.toolWidth);
case PaintTool.Circle:
return new CircleEdit(this.columns, this.rows, this.color, this.toolWidth);
case PaintTool.Erase:
return new PaintEdit(this.columns, this.rows, 0, this.toolWidth);
case PaintTool.Fill:
return new FillEdit(this.columns, this.rows, this.color, this.toolWidth);
case PaintTool.Marquee:
return new MarqueeEdit(this.columns, this.rows, this.color, this.toolWidth);
}
}
private shiftAction() {
if (!this.shiftDown || this.altDown)
return;
switch (this.activeTool) {
case PaintTool.Line:
case PaintTool.Rectangle:
case PaintTool.Circle:
this.setCell(this.paintSurface.mouseCol, this.paintSurface.mouseRow, this.color, false);
break;
}
}
private clearShiftAction() {
if (this.mouseDown)
return;
switch (this.activeTool) {
case PaintTool.Line:
case PaintTool.Rectangle:
case PaintTool.Circle:
this.updateEdit();
this.paintSurface.restore(this.state, true);
break;
}
}
private debug(msg: string) {
// if (this.debugText) {
// this.debugText.text("DEBUG: " + msg);
// }
}
private createDefs() {
this.toolbarRoot.define(defs => {
const p = defs.create("pattern", "alpha-background")
.size(10, 10)
.units(svg.PatternUnits.userSpaceOnUse);
p.draw("rect")
.at(0, 0)
.size(10, 10)
.fill("white");
p.draw("rect")
.at(0, 0)
.size(5, 5)
.fill("#dedede");
p.draw("rect")
.at(5, 5)
.size(5, 5)
.fill("#dedede");
})
}
} | the_stack |
import { OverlayModule } from '@angular/cdk/overlay';
import { Location } from '@angular/common';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import {
ComponentFixture,
fakeAsync,
flush,
TestBed,
tick,
waitForAsync,
} from '@angular/core/testing';
import { MatButtonModule } from '@angular/material/button';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { MatToolbarModule } from '@angular/material/toolbar';
import { By } from '@angular/platform-browser';
import { Params, Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { BehaviorSubject, ReplaySubject, Subject } from 'rxjs';
import {
BuildReportStep,
ScoredItem,
SocialMediaItem,
} from '../../common-types';
import { routes } from '../app-routing.module';
import { AuthGuardService } from '../auth-guard.service';
import { TOXICITY_FILTER_NAME_QUERY_PARAM } from '../create-report/create-report.component';
import { OauthApiService } from '../oauth_api.service';
import { OnboardingService } from '../onboarding.service';
import { ReportProgressBarComponent } from '../report-progress-bar/report-progress-bar.component';
import { ReportAction, ReportService } from '../report.service';
import { SocialMediaItemService } from '../social-media-item.service';
import { ONE_HOUR_MS, ONE_MIN_MS, ToolbarComponent } from './toolbar.component';
/**
* Stub for MatDialogRef. The constructor takes a Subject that should be
* triggered when we want the dialog to close with the value it should send
* back.
*/
class DialogRefStub<T> {
constructor(private dialogCloseTrigger: Subject<T>) {}
afterClosed() {
return this.dialogCloseTrigger.asObservable();
}
}
describe('ToolbarComponent', () => {
let component: ToolbarComponent;
let fixture: ComponentFixture<ToolbarComponent>;
let location: Location;
let mockOauthApiService: jasmine.SpyObj<OauthApiService>;
let mockSocialMediaItemService: jasmine.SpyObj<SocialMediaItemService>;
let commentsSubject: ReplaySubject<Array<ScoredItem<SocialMediaItem>>>;
let reportActionsSubject: BehaviorSubject<ReportAction[]>;
let reportLastEditedSubject: BehaviorSubject<number>;
let reportClearedSubject: Subject<void>;
let reportStepSubject: BehaviorSubject<BuildReportStep>;
let mockReportService: jasmine.SpyObj<ReportService>;
let router: Router;
let mockAuthGuardService: jasmine.SpyObj<AuthGuardService>;
const twitterSignInTestSubject = new ReplaySubject<boolean>(1);
const highlightReviewReportButtonTestSubject = new Subject<void>();
const dialogCloseTrigger = new Subject<boolean>();
const mockOnboardingService = jasmine.createSpyObj<OnboardingService>(
'onboardingService',
['setCreateReportPageOnboardingComplete'],
{ highlightReviewReportButton: highlightReviewReportButtonTestSubject }
);
beforeEach(
waitForAsync(() => {
mockOauthApiService = jasmine.createSpyObj<OauthApiService>(
'oauthApiService',
['revokeAuth', 'twitterSignInChange']
);
mockOauthApiService.twitterSignInChange = twitterSignInTestSubject.asObservable();
mockAuthGuardService = jasmine.createSpyObj<AuthGuardService>(
'authGuardService',
['canActivate']
);
mockAuthGuardService.canActivate.and.returnValue(true);
mockSocialMediaItemService = jasmine.createSpyObj<SocialMediaItemService>(
'socialMediaItemService',
['getTotalCommentFetchCount']
);
commentsSubject = new ReplaySubject(1);
reportActionsSubject = new BehaviorSubject<ReportAction[]>([]);
reportLastEditedSubject = new BehaviorSubject<number>(0);
reportClearedSubject = new Subject<void>();
reportStepSubject = new BehaviorSubject<BuildReportStep>(
BuildReportStep.NONE
);
mockReportService = jasmine.createSpyObj<ReportService>(
'reportService',
[
'addCommentsToReport',
'clearReport',
'getReportActions',
'setReportStep',
'getCommentsForReport',
'getReportReasons',
'getReportSummary',
],
{
reportCommentsChanged: commentsSubject.asObservable(),
reportActionsChanged: reportActionsSubject.asObservable(),
reportLastEditedChanged: reportLastEditedSubject.asObservable(),
reportCleared: reportClearedSubject.asObservable(),
reportStepChanged: reportStepSubject.asObservable(),
}
);
TestBed.configureTestingModule({
declarations: [ReportProgressBarComponent, ToolbarComponent],
imports: [
HttpClientTestingModule,
MatButtonModule,
MatDialogModule,
MatIconModule,
MatToolbarModule,
OverlayModule,
RouterTestingModule.withRoutes(routes),
],
providers: [
{
provide: AuthGuardService,
useValue: mockAuthGuardService,
},
{
provide: OauthApiService,
useValue: mockOauthApiService,
},
{
provide: OnboardingService,
useValue: mockOnboardingService,
},
{
provide: ReportService,
useValue: mockReportService,
},
{
provide: MatDialog,
useValue: {
open(componentName: string) {
return new DialogRefStub<boolean>(dialogCloseTrigger);
},
},
},
{
provide: SocialMediaItemService,
useValue: mockSocialMediaItemService,
},
],
}).compileComponents();
})
);
beforeEach(() => {
fixture = TestBed.createComponent(ToolbarComponent);
component = fixture.componentInstance;
location = TestBed.inject(Location);
fixture.detectChanges();
router = TestBed.inject(Router);
});
it('creates the component', () => {
expect(component).toBeTruthy();
const componentElement = fixture.debugElement.nativeElement;
expect(componentElement.querySelector('.title').textContent).toContain(
'Harassment Manager'
);
});
it('shows the correct elements depending on user sign-in state', () => {
twitterSignInTestSubject.next(true);
fixture.detectChanges();
let getStartedButton = fixture.debugElement.query(
By.css('.get-started-button')
);
let navigationLinks = fixture.debugElement.query(
By.css('.navigation-links')
);
let signOutButton = fixture.debugElement.query(By.css('.sign-out-button'));
expect(getStartedButton).toBeFalsy();
expect(navigationLinks).toBeTruthy();
expect(signOutButton).toBeTruthy();
twitterSignInTestSubject.next(false);
fixture.detectChanges();
getStartedButton = fixture.debugElement.query(
By.css('.get-started-button')
);
navigationLinks = fixture.debugElement.query(By.css('.navigation-links'));
signOutButton = fixture.debugElement.query(By.css('.sign-out-button'));
expect(getStartedButton).toBeTruthy();
expect(navigationLinks).toBeFalsy();
expect(signOutButton).toBeFalsy();
});
it('highlights the review report button for onboarding', fakeAsync(() => {
twitterSignInTestSubject.next(true);
router.navigate(['/create-report']);
tick();
let highlightReviewReportButton = fixture.debugElement.query(
By.css('.highlight-continue-button')
);
expect(highlightReviewReportButton).toBeFalsy();
highlightReviewReportButtonTestSubject.next();
fixture.detectChanges();
highlightReviewReportButton = fixture.debugElement.query(
By.css('.highlight-continue-button')
);
expect(highlightReviewReportButton).toBeTruthy();
const doneButton = document.querySelector(
'.cdk-overlay-container .onboarding-review-report button'
);
expect(doneButton).toBeTruthy();
(doneButton! as HTMLElement).click();
fixture.detectChanges();
highlightReviewReportButton = fixture.debugElement.query(
By.css('.highlight-continue-button')
);
expect(highlightReviewReportButton).toBeFalsy();
// Clear microtask queue.
flush();
}));
it('revokes auth on user sign-out', async () => {
twitterSignInTestSubject.next(true);
fixture.detectChanges();
mockOauthApiService.revokeAuth.and.returnValue(Promise.resolve());
const componentElement = fixture.debugElement.nativeElement;
componentElement.querySelector('.sign-out-button').click();
await fixture.whenStable();
expect(mockOauthApiService.revokeAuth).toHaveBeenCalled();
expect(location.path()).toBe('/');
});
it('shows a notification when comments are added to the report', fakeAsync(() => {
router.navigate(['/create-report']);
tick();
let dropdownElement = document.querySelector('.dropdown');
expect(dropdownElement).toBe(null);
const comments = [
{
item: {
id_str: 'a',
text: 'your mother was a hamster',
date: new Date(),
},
scores: {
TOXICITY: 0.8,
},
},
{
item: {
id_str: 'b',
text: 'and your father smelt of elderberries',
date: new Date(),
},
scores: {
TOXICITY: 0.9,
},
},
];
commentsSubject.next([comments[0]]);
fixture.detectChanges();
dropdownElement = document.querySelector('.dropdown');
expect(component.dropdownElement!.nativeElement.textContent).toContain(
"Nice work! You've started your report."
);
tick(5000);
commentsSubject.next(comments);
fixture.detectChanges();
dropdownElement = document.querySelector('.dropdown');
expect(dropdownElement!.textContent).toContain('Comment added to report');
tick(5000);
}));
it('resets notification state when a user logs out', fakeAsync(() => {
twitterSignInTestSubject.next(true);
fixture.detectChanges();
router.navigate(['/create-report']);
tick();
let dropdownElement = document.querySelector('.dropdown');
expect(dropdownElement).toBe(null);
const comments = [
{
item: {
id_str: 'a',
text: 'your mother was a hamster',
date: new Date(),
},
scores: {
TOXICITY: 0.8,
},
},
{
item: {
id_str: 'b',
text: 'and your father smelt of elderberries',
date: new Date(),
},
scores: {
TOXICITY: 0.9,
},
},
];
commentsSubject.next([comments[0]]);
fixture.detectChanges();
dropdownElement = document.querySelector('.dropdown');
expect(dropdownElement!.textContent).toContain(
"Nice work! You've started your report."
);
tick(5000);
mockOauthApiService.revokeAuth.and.returnValue(Promise.resolve());
const componentElement = fixture.debugElement.nativeElement;
componentElement.querySelector('.sign-out-button').click();
tick();
expect(mockOauthApiService.revokeAuth).toHaveBeenCalled();
router.navigate(['/create-report']);
tick();
commentsSubject.next(comments);
fixture.detectChanges();
dropdownElement = document.querySelector('.dropdown');
expect(dropdownElement!.textContent).toContain(
"Nice work! You've started your report."
);
tick(5000);
}));
it('clicks forward through report flow', fakeAsync(() => {
const queryParams: Params = {};
queryParams[TOXICITY_FILTER_NAME_QUERY_PARAM] = 'test';
// We have to be on the create page, but make sure it works with query
// params.
router.navigate(['/create-report', queryParams]);
reportStepSubject.next(BuildReportStep.ADD_COMMENTS);
tick();
fixture.detectChanges();
let continueButton = fixture.debugElement.query(By.css('.continue-button'));
let backButton = fixture.debugElement.query(By.css('.back-button'));
expect(continueButton).toBeTruthy();
expect(backButton).toBeFalsy();
// Continue button should be disabled.
expect(continueButton.componentInstance.disabled).toBe(true);
const comments = [
{
item: {
id_str: 'a',
text: 'your mother was a hamster',
date: new Date(),
},
scores: {
TOXICITY: 0.8,
},
},
{
item: {
id_str: 'b',
text: 'and your father smelt of elderberries',
date: new Date(),
},
scores: {
TOXICITY: 0.9,
},
},
];
// Once we add comments to the report, the continue button should be
// enabled.
commentsSubject.next([comments[0]]);
mockReportService.getCommentsForReport.and.returnValue([comments[0]]);
fixture.detectChanges();
expect(continueButton.componentInstance.disabled).toBe(false);
continueButton.nativeElement.click();
flush();
fixture.detectChanges();
// Trying to spy on the 'navigate' call for the router doesn't seem to work
// here. Instead we check the URL to verify that navigation completed.
expect(router.url).toBe('/review-report');
reportStepSubject.next(BuildReportStep.EDIT_DETAILS);
fixture.detectChanges();
continueButton = fixture.debugElement.query(By.css('.continue-button'));
backButton = fixture.debugElement.query(By.css('.back-button'));
expect(continueButton).toBeTruthy();
expect(backButton).toBeTruthy();
expect(continueButton.componentInstance.disabled).toBe(false);
continueButton.nativeElement.click();
flush();
fixture.detectChanges();
expect(router.url).toBe('/share-report');
reportStepSubject.next(BuildReportStep.TAKE_ACTION);
fixture.detectChanges();
continueButton = fixture.debugElement.query(By.css('.continue-button'));
backButton = fixture.debugElement.query(By.css('.back-button'));
expect(continueButton).toBeTruthy();
expect(backButton).toBeTruthy();
expect(continueButton.componentInstance.disabled).toBe(false);
reportActionsSubject.next([ReportAction.SAVE_TO_DRIVE]);
fixture.detectChanges();
expect(continueButton.componentInstance.disabled).toBe(false);
mockReportService.getReportReasons.and.returnValue(['Reason 1']);
// The continue button brings up the exit dialog, and doesn't change the
// page.
continueButton.nativeElement.click();
flush();
fixture.detectChanges();
expect(router.url).toBe('/share-report');
expect(component.getExitDialogOpen()).toBe(true);
// If the user continues from the exit dialog then continue to the next
// page.
dialogCloseTrigger.next(/* exitReport = */ true);
flush();
fixture.detectChanges();
expect(router.url).toBe('/report-complete');
expect(component.getExitDialogOpen()).toBe(false);
}));
it('allows user to finish report without taking action', fakeAsync(() => {
router.navigate(['/create-report']);
tick();
reportStepSubject.next(BuildReportStep.ADD_COMMENTS);
fixture.detectChanges();
let continueButton = fixture.debugElement.query(By.css('.continue-button'));
const comment = {
item: {
id_str: 'a',
text: 'your mother was a hamster',
date: new Date(),
},
scores: {
TOXICITY: 0.8,
},
};
commentsSubject.next([comment]);
fixture.detectChanges();
continueButton.nativeElement.click();
reportStepSubject.next(BuildReportStep.EDIT_DETAILS);
flush();
fixture.detectChanges();
continueButton = fixture.debugElement.query(By.css('.continue-button'));
continueButton.nativeElement.click();
reportStepSubject.next(BuildReportStep.TAKE_ACTION);
flush();
fixture.detectChanges();
continueButton = fixture.debugElement.query(By.css('.continue-button'));
mockReportService.getReportReasons.and.returnValue(['Reason 1']);
mockReportService.getCommentsForReport.and.returnValue([comment]);
continueButton.nativeElement.click();
flush();
fixture.detectChanges();
dialogCloseTrigger.next(/* exitReport = */ true);
flush();
fixture.detectChanges();
expect(router.url).toBe('/home');
expect(component.getExitDialogOpen()).toBe(false);
}));
it('clicks backward through report flow', fakeAsync(() => {
router.navigate(['/share-report']);
tick();
fixture.detectChanges();
expect(router.url).toBe('/share-report');
reportStepSubject.next(BuildReportStep.TAKE_ACTION);
fixture.detectChanges();
let continueButton = fixture.debugElement.query(By.css('.continue-button'));
let backButton = fixture.debugElement.query(By.css('.back-button'));
expect(continueButton).toBeTruthy();
expect(backButton).toBeTruthy();
backButton.nativeElement.click();
flush();
fixture.detectChanges();
expect(router.url).toBe('/review-report');
reportStepSubject.next(BuildReportStep.EDIT_DETAILS);
fixture.detectChanges();
continueButton = fixture.debugElement.query(By.css('.continue-button'));
backButton = fixture.debugElement.query(By.css('.back-button'));
expect(continueButton).toBeTruthy();
expect(backButton).toBeTruthy();
backButton.nativeElement.click();
flush();
fixture.detectChanges();
expect(router.url).toBe('/create-report');
reportStepSubject.next(BuildReportStep.ADD_COMMENTS);
fixture.detectChanges();
continueButton = fixture.debugElement.query(By.css('.continue-button'));
backButton = fixture.debugElement.query(By.css('.back-button'));
expect(continueButton).toBeTruthy();
expect(backButton).toBeFalsy();
}));
it('shows the last edited time', fakeAsync(() => {
const now = Date.now();
reportLastEditedSubject.next(now);
router.navigate(['/create-report']);
tick();
fixture.detectChanges();
let lastEditedText = fixture.debugElement.query(By.css('.last-edited'));
expect(lastEditedText.nativeElement.textContent).toContain(
'Last edit less than 1 min ago'
);
reportLastEditedSubject.next(now - (ONE_HOUR_MS * 5 + ONE_MIN_MS * 20));
tick();
fixture.detectChanges();
lastEditedText = fixture.debugElement.query(By.css('.last-edited'));
expect(lastEditedText.nativeElement.textContent).toContain(
'Last edit 5 hr 20 min ago'
);
reportLastEditedSubject.next(1604206800000);
tick();
fixture.detectChanges();
lastEditedText = fixture.debugElement.query(By.css('.last-edited'));
expect(lastEditedText.nativeElement.textContent).toContain(
'Last edit on Nov 1'
);
}));
it('navigates to home when report is cleared', fakeAsync(() => {
router.navigate(['/create-report']);
tick();
expect(router.url).toEqual('/create-report');
reportClearedSubject.next();
tick();
expect(router.url).toEqual('/home');
}));
}); | the_stack |
import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import { axe } from 'jest-axe';
import { typeIs } from '@leafygreen-ui/lib';
import RadioBox from './RadioBox';
import RadioBoxGroup from './RadioBoxGroup';
const className = 'test-radio-box-class';
const { container } = render(
<RadioBox value="radio-1" className={className} checked readOnly>
Input 1
</RadioBox>,
);
describe('packages/RadioBox', () => {
const radioBoxContainer = container.firstChild;
if (!typeIs.element(radioBoxContainer)) {
throw new Error('Could not find radio box container element');
}
const radioBox = radioBoxContainer.firstChild;
if (!typeIs.input(radioBox)) {
throw new Error('Could not find radio box input element');
}
test('does not have basic accessibility issues', async () => {
const results = await axe(radioBoxContainer);
expect(results).toHaveNoViolations();
});
test(`renders "${className}" in RadioBox's classList`, () => {
expect(radioBoxContainer.classList.contains(className)).toBe(true);
});
test('renders as checked, when the checked prop is set', () => {
expect(radioBox.checked).toBe(true);
expect(radioBox.getAttribute('aria-checked')).toBe('true');
});
test('renders as disabled, when the disabled prop is set', () => {
const { container } = render(
<RadioBox value="option-disabled" disabled>
Input 2
</RadioBox>,
);
const radioBoxContainer = container.firstChild;
if (!typeIs.element(radioBoxContainer)) {
throw new Error('Could not find radio box container element');
}
const radioBox = radioBoxContainer.firstChild;
if (!typeIs.input(radioBox)) {
throw new Error('Could not find radio box input element');
}
expect(radioBox.getAttribute('aria-disabled')).toBe('true');
});
});
describe('packages/RadioBoxGroup', () => {
function WrappedRadioBox({ text }: { text: string }) {
return (
<div className="wrapped-radio-box">
{text} <RadioBox value="option-3">Input 3</RadioBox>
</div>
);
}
const { container } = render(
<RadioBoxGroup className="test-radio-box-group">
<h1>Will Remain As Text</h1>
<RadioBox value="option-1">Input 1</RadioBox>
<RadioBox value="option-2">Input 2</RadioBox>
<WrappedRadioBox text="Also still text" />
</RadioBoxGroup>,
);
const radioBoxGroupContainer = container.firstChild;
if (!typeIs.element(radioBoxGroupContainer)) {
throw new Error('Could not find radio box group container element');
}
const text = radioBoxGroupContainer.children[0];
const option1 = radioBoxGroupContainer.children[1];
const option2 = radioBoxGroupContainer.children[2];
const wrapped = radioBoxGroupContainer.children[3];
test.todo(`correct number of children render`);
// expect(radioBoxGroupContainer.children).toHaveLength(4)
// radioBoxGroupContainer.children.length returns 1
test(`input ids are all unique`, () => {
const radioChildren = [option1, option2, wrapped];
const uniqueIDs = new Set();
radioChildren.forEach(c => uniqueIDs.add(c.querySelector('input')!.id));
expect(uniqueIDs.size).toEqual(radioChildren.length);
});
test('renders children of Radio Box Group, that are not themselves Radio Boxes, as is, without converting them to RadioBoxes', () => {
expect(text.tagName.toLowerCase()).toBe('h1');
});
test('renders wrapper components as themselves', () => {
expect(wrapped.tagName.toLowerCase()).toBe('div');
expect(wrapped.className).toBe('wrapped-radio-box');
});
describe('when controlled', () => {
const controlledOnChange = jest.fn();
render(
<RadioBoxGroup value="option-1" onChange={controlledOnChange}>
<RadioBox value="option-1">Option 1</RadioBox>
<RadioBox value="option-2">Option 2</RadioBox>
<WrappedRadioBox text="text" />
</RadioBoxGroup>,
{ container },
);
const radioBoxGroup = container.firstChild;
if (!typeIs.element(radioBoxGroup)) {
throw new Error('Could not find radio box group element');
}
const firstRadioBoxLabel = radioBoxGroup.firstChild;
if (!typeIs.element(firstRadioBoxLabel)) {
throw new Error('Could not find label element');
}
const firstRadioBoxInput = firstRadioBoxLabel.firstChild;
const secondRadioBoxInput = radioBoxGroup.children[1].firstChild;
if (
!typeIs.input(firstRadioBoxInput) ||
!typeIs.input(secondRadioBoxInput)
) {
throw new Error('Could not find input element');
}
fireEvent.click(secondRadioBoxInput);
test('initial value set by radio box group when prop provided', () => {
expect(firstRadioBoxInput.checked).toBe(true);
expect(firstRadioBoxInput.getAttribute('aria-checked')).toBe('true');
});
test('onChange fires once when the label is clicked', () => {
expect(controlledOnChange.mock.calls.length).toBe(1);
});
test('radio input does not become checked when clicked', () => {
expect(secondRadioBoxInput.checked).toBe(false);
});
});
describe('when controlled with a wrapper component', () => {
const controlledOnChange = jest.fn();
const { container } = render(
<RadioBoxGroup value="option-1" onChange={controlledOnChange}>
<RadioBox value="option-1">Option 1</RadioBox>
<RadioBox value="option-2">Option 2</RadioBox>
<WrappedRadioBox text="text" />
</RadioBoxGroup>,
);
const radioBoxGroup = container.firstChild;
if (!typeIs.element(radioBoxGroup)) {
throw new Error('Could not find radio box group element');
}
const firstRadioBoxLabel = radioBoxGroup.firstChild;
if (!typeIs.element(firstRadioBoxLabel)) {
throw new Error('Could not find label element');
}
const firstRadioBoxInput = firstRadioBoxLabel.firstChild;
if (!typeIs.input(firstRadioBoxInput)) {
throw new Error('Could not find input element');
}
const wrappedRadioBoxInput =
radioBoxGroup.children[2].firstElementChild?.firstElementChild;
if (!typeIs.input(wrappedRadioBoxInput)) {
throw new Error('Could not find wrapped input element');
}
fireEvent.click(wrappedRadioBoxInput);
test('initial value set by radio box group', () => {
// .checked prop can be inconsistent in ssr tests,
// so while I'd like to do expect(firstRadioBoxInput.checked).toBe(true);
// aria-checked should be good enough
expect(firstRadioBoxInput.getAttribute('aria-checked')).toBe('true');
});
test('onChange fires when the wrapped label is clicked', () => {
expect(controlledOnChange.mock.calls.length).toBe(1);
});
test('wrapped input does not become checked when clicked', () => {
expect(wrappedRadioBoxInput.checked).toBe(false);
});
});
describe('when controlled with a selected wrapper component', () => {
const controlledOnChange = jest.fn();
const { container } = render(
<RadioBoxGroup value="option-3" onChange={controlledOnChange}>
<RadioBox value="option-1">Option 1</RadioBox>
<RadioBox value="option-2">Option 2</RadioBox>
<WrappedRadioBox text="text" />
</RadioBoxGroup>,
);
const radioBoxGroup = container.firstChild;
if (!typeIs.element(radioBoxGroup)) {
throw new Error('Could not find radio box group element');
}
const wrappedRadioBoxInput =
radioBoxGroup.children[2].firstElementChild?.firstElementChild;
if (!typeIs.input(wrappedRadioBoxInput)) {
throw new Error('Could not find wrapped input element');
}
test('wrapped input is rendered as checked', () => {
expect(wrappedRadioBoxInput.checked).toBe(true);
expect(wrappedRadioBoxInput.getAttribute('aria-checked')).toBe('true');
});
});
describe('when uncontrolled', () => {
const setupUncontrolledTest = () => {
const onChange = jest.fn();
const { container } = render(
<RadioBoxGroup onChange={onChange}>
<RadioBox value="option-1">Option 1</RadioBox>
<RadioBox value="option-2">Option 2</RadioBox>
</RadioBoxGroup>,
);
const radioBoxGroup = container.firstChild;
if (!typeIs.element(radioBoxGroup)) {
throw new Error('Could not find radio box group element');
}
const firstLabel = radioBoxGroup.firstChild;
if (!typeIs.element(firstLabel)) {
throw new Error('Could not find first label element');
}
const firstInput = firstLabel.firstChild;
if (!typeIs.input(firstInput)) {
throw new Error('Could not find first radio box input element');
}
const secondLabel = radioBoxGroup.children[1];
if (!typeIs.element(secondLabel)) {
throw new Error('Could not find second label element');
}
const secondInput = secondLabel.firstChild;
if (!typeIs.input(secondInput)) {
throw new Error('Could not find second radio box input element');
}
return {
onChange,
container,
radioBoxGroup,
firstLabel,
firstInput,
secondLabel,
secondInput,
};
};
test('onChange fires once when the label is clicked', () => {
const { onChange, firstLabel } = setupUncontrolledTest();
fireEvent.click(firstLabel);
expect(onChange.mock.calls.length).toBe(1);
});
test('first radio box becomes checked when clicked first', () => {
const { firstInput, secondInput, firstLabel } = setupUncontrolledTest();
fireEvent.click(firstLabel);
expect(firstInput.getAttribute('aria-checked')).toBe('true');
expect(firstInput.checked).toBe(true);
expect(secondInput.getAttribute('aria-checked')).toBe('false');
expect(secondInput.checked).toBe(false);
});
test('second radio box becomes checked when clicked first', () => {
const { firstInput, secondInput, secondLabel } = setupUncontrolledTest();
fireEvent.click(secondLabel);
expect(firstInput.getAttribute('aria-checked')).toBe('false');
expect(firstInput.checked).toBe(false);
expect(secondInput.getAttribute('aria-checked')).toBe('true');
expect(secondInput.checked).toBe(true);
});
test('first radio box becomes checked when clicked second', () => {
const {
firstInput,
secondInput,
secondLabel,
firstLabel,
} = setupUncontrolledTest();
fireEvent.click(secondLabel);
fireEvent.click(firstLabel);
expect(firstInput.getAttribute('aria-checked')).toBe('true');
expect(firstInput.checked).toBe(true);
expect(secondInput.getAttribute('aria-checked')).toBe('false');
expect(secondInput.checked).toBe(false);
});
describe('and the default prop is set', () => {
const uncontrolledOnChange = jest.fn();
const uncontrolledContainer = render(
<RadioBoxGroup onChange={uncontrolledOnChange}>
<RadioBox value="option-1">RadioBox Button 1</RadioBox>
<RadioBox default value="option-2">
RadioBox Button 1
</RadioBox>
</RadioBoxGroup>,
).container.firstChild;
const defaultRadioBox =
uncontrolledContainer &&
(uncontrolledContainer as HTMLElement).children[1].firstChild;
test('radio box is checked when default prop is set', () => {
expect((defaultRadioBox as HTMLInputElement).checked).toBe(true);
});
});
});
}); | the_stack |
import {FS, Net} from "../../lib";
const AVATARS_FILE = 'config/avatars.json';
/**
* Avatar IDs should be in one of these formats:
* - 'cynthia' - official avatars in https://play.pokemonshowdown.com/sprites/trainers/
* - '#splxraiders' - hosted custom avatars in https://play.pokemonshowdown.com/sprites/trainers-custom/
* - 'example.png' - side server custom avatars in config/avatars/ in your server
*/
type AvatarID = string;
const AVATAR_FORMATS_MESSAGE = Config.serverid === 'showdown' ?
"Custom avatars start with '#', like '#splxraiders'." :
"Custom avatars look like 'example.png'. Custom avatars should be put in `config/avatars/`. Your server must be registered for custom avatars to work.";
interface AvatarEntry {
timeReceived?: number;
timeUpdated?: number;
notNotified?: boolean;
/**
* First entry is the personal avatar.
* Will never only contain `null` - the entry should just be deleted if it does.
*/
allowed: [AvatarID | null, ...AvatarID[]];
/**
* undefined = personal avatar;
* null = no default (shouldn't occur in practice);
* (ignored during Christmas, where the any avatar is default if it ends in `xmas`.)
*/
default?: AvatarID | null;
}
const customAvatars: {[userid: string]: AvatarEntry} = Object.create(null);
try {
const configAvatars = JSON.parse(FS(AVATARS_FILE).readSync());
Object.assign(customAvatars, configAvatars);
} catch {
if (Config.customavatars) {
for (const userid in Config.customavatars) {
customAvatars[userid] = {allowed: [Config.customavatars[userid]]};
}
}
if (Config.allowedavatars) {
for (const avatar in Config.customavatars) {
for (const userid of Config.customavatars[avatar]) {
customAvatars[userid] ??= {allowed: [null]};
customAvatars[userid].allowed.push(avatar);
}
}
}
FS(AVATARS_FILE).writeSync(JSON.stringify(customAvatars));
}
if ((Config.customavatars && Object.keys(Config.customavatars).length) || Config.allowedavatars) {
Monitor.crashlog("Please remove 'customavatars' and 'allowedavatars' from Config (config/config.js). Your avatars have been migrated to the new '/addavatar' system.");
}
function saveCustomAvatars(instant?: boolean) {
FS(AVATARS_FILE).writeUpdate(() => JSON.stringify(customAvatars), {throttle: instant ? null : 60_000});
}
export const Avatars = new class {
avatars = customAvatars;
userCanUse(user: User, avatar: string): AvatarID | null {
let validatedAvatar = null;
for (const id of [user.id, ...user.previousIDs]) {
validatedAvatar = Avatars.canUse(id, avatar);
if (validatedAvatar) break;
}
return validatedAvatar;
}
canUse(userid: ID, avatar: string): AvatarID | null {
avatar = avatar.toLowerCase().replace(/[^a-z0-9-.]+/g, '');
if (OFFICIAL_AVATARS.has(avatar)) return avatar;
const customs = customAvatars[userid]?.allowed;
if (!customs) return null;
if (customs.includes(avatar)) return avatar;
if (customs.includes('#' + avatar)) return '#' + avatar;
if (avatar.startsWith('#') && customs.includes(avatar.slice(1))) return avatar.slice(1);
return null;
}
save(instant?: boolean) {
saveCustomAvatars(instant);
}
src(avatar: AvatarID) {
if (avatar.includes('.')) return '';
const avatarUrl = avatar.startsWith('#') ? `trainers-custom/${avatar.slice(1)}.png` : `trainers/${avatar}.png`;
return `https://${Config.routes.client}/sprites/${avatarUrl}`;
}
exists(avatar: string) {
if (avatar.includes('.')) {
return FS(`config/avatars/${avatar}`).isFile();
}
if (!avatar.startsWith('#')) {
return OFFICIAL_AVATARS.has(avatar);
}
return Net(Avatars.src(avatar)).get().then(() => true).catch(() => false);
}
convert(avatar: string) {
if (avatar.startsWith('#') && avatar.includes('.')) return avatar.slice(1);
return avatar;
}
async validate(avatar: string, options?: {rejectOfficial?: boolean}) {
avatar = this.convert(avatar);
if (!/^#?[a-z0-9-]+$/.test(avatar) && !/^[a-z0-9.-]+$/.test(avatar)) {
throw new Chat.ErrorMessage(`Avatar "${avatar}" is not in a valid format. ${AVATAR_FORMATS_MESSAGE}`);
}
if (!await this.exists(avatar)) {
throw new Chat.ErrorMessage(`Avatar "${avatar}" doesn't exist. ${AVATAR_FORMATS_MESSAGE}`);
}
if (options?.rejectOfficial && /^[a-z0-9-]+$/.test(avatar)) {
throw new Chat.ErrorMessage(`Avatar "${avatar}" is an official avatar that all users already have access to.`);
}
return avatar;
}
img(avatar: AvatarID, noAlt?: boolean) {
const src = Avatars.src(avatar);
if (!src) return <strong><code>{avatar}</code></strong>;
return <img
src={src} alt={noAlt ? '' : avatar} width="80" height="80" class="pixelated" style={{verticalAlign: 'middle'}}
/>;
}
getDefault(userid: ID) {
const entry = customAvatars[userid];
if (!entry) return null;
const DECEMBER = 11; // famous JavaScript issue
if (new Date().getMonth() === DECEMBER && entry.allowed.some(avatar => avatar?.endsWith('xmas'))) {
return entry.allowed.find(avatar => avatar?.endsWith('xmas'));
}
return entry.default === undefined ? entry.allowed[0] : entry.default;
}
/** does not include validation */
setDefault(userid: ID, avatar: AvatarID | null) {
if (avatar === this.getDefault(userid)) return;
const entry = (customAvatars[userid] ??= {allowed: [null]});
if (avatar === entry.allowed[0]) {
delete entry.default;
} else {
entry.default = avatar;
}
saveCustomAvatars();
}
addAllowed(userid: ID, avatar: AvatarID | null) {
const entry = (customAvatars[userid] ??= {allowed: [null]});
if (entry.allowed.includes(avatar)) return false;
entry.allowed.push(avatar);
entry.notNotified = true;
this.tryNotify(Users.get(userid));
return true;
}
removeAllowed(userid: ID, avatar: AvatarID | null) {
const entry = customAvatars[userid];
if (!entry?.allowed.includes(avatar)) return false;
if (entry.allowed[0] === avatar) {
entry.allowed[0] = null;
} else {
entry.allowed = entry.allowed.filter(a => a !== avatar) as any;
}
if (!entry.allowed.some(Boolean)) delete customAvatars[userid];
return true;
}
addPersonal(userid: ID, avatar: AvatarID | null) {
const entry = (customAvatars[userid] ??= {allowed: [null]});
if (entry.allowed.includes(avatar)) return false;
entry.timeReceived ||= Date.now();
entry.timeUpdated = Date.now();
if (!entry.allowed[0]) {
entry.allowed[0] = avatar;
} else {
entry.allowed.unshift(avatar);
}
delete entry.default;
entry.notNotified = true;
this.tryNotify(Users.get(userid));
return true;
}
handleLogin(user: User) {
const avatar = this.getDefault(user.id);
if (avatar) user.avatar = avatar;
this.tryNotify(user);
}
tryNotify(user?: User | null) {
if (!user) return;
const entry = customAvatars[user.id];
if (entry?.notNotified) {
user.send(
`|pm|&|${user.getIdentity()}|/raw ` +
Chat.html`${<>
<p>
You have a new custom avatar!
</p>
<p>
{entry.allowed.map(avatar => avatar && [Avatars.img(avatar), ' '])}
</p>
Use <button class="button" name="send" value="/avatars"><code>/avatars</code></button> for usage instructions.
</>}`
);
delete entry.notNotified;
saveCustomAvatars();
}
}
};
function listUsers(users: string[]) {
return users.flatMap((userid, i) => [i ? ', ' : null, <username class="username">{userid}</username>]);
}
const OFFICIAL_AVATARS = new Set([
'aaron',
'acetrainercouple-gen3', 'acetrainercouple',
'acetrainerf-gen1', 'acetrainerf-gen1rb', 'acetrainerf-gen2', 'acetrainerf-gen3', 'acetrainerf-gen3rs', 'acetrainerf-gen4dp', 'acetrainerf-gen4', 'acetrainerf',
'acetrainer-gen1', 'acetrainer-gen1rb', 'acetrainer-gen2', 'acetrainer-gen3jp', 'acetrainer-gen3', 'acetrainer-gen3rs', 'acetrainer-gen4dp', 'acetrainer-gen4', 'acetrainer',
'acetrainersnowf',
'acetrainersnow',
'agatha-gen1', 'agatha-gen1rb', 'agatha-gen3',
'alder',
'anabel-gen3',
'archer',
'archie-gen3',
'argenta',
'ariana',
'aromalady-gen3', 'aromalady-gen3rs', 'aromalady',
'artist-gen4', 'artist',
'ash-alola', 'ash-hoenn', 'ash-kalos', 'ash-unova', 'ash-capbackward', 'ash-johto', 'ash-sinnoh', 'ash',
'backersf',
'backers',
'backpackerf',
'backpacker',
'baker',
'barry',
'battlegirl-gen3', 'battlegirl-gen4', 'battlegirl',
'beauty-gen1', 'beauty-gen1rb', 'beauty-gen2jp', 'beauty-gen2', 'beauty-gen3', 'beauty-gen3rs', 'beauty-gen4dp', 'beauty-gen5bw2', 'beauty',
'bellelba',
'bellepa',
'benga',
'bertha',
'bianca-pwt', 'bianca',
'biker-gen1', 'biker-gen1rb', 'biker-gen2', 'biker-gen3', 'biker-gen4', 'biker',
'bill-gen3',
'birch-gen3',
'birdkeeper-gen1', 'birdkeeper-gen1rb', 'birdkeeper-gen2', 'birdkeeper-gen3', 'birdkeeper-gen3rs', 'birdkeeper-gen4dp', 'birdkeeper',
'blackbelt-gen1', 'blackbelt-gen1rb', 'blackbelt-gen2', 'blackbelt-gen3', 'blackbelt-gen3rs', 'blackbelt-gen4dp', 'blackbelt-gen4', 'blackbelt',
'blaine-gen1', 'blaine-gen1rb', 'blaine-gen2', 'blaine-gen3', 'blaine',
'blue-gen1champion', 'blue-gen1', 'blue-gen1rbchampion', 'blue-gen1rb', 'blue-gen1rbtwo', 'blue-gen1two', 'blue-gen2', 'blue-gen3champion', 'blue-gen3', 'blue-gen3two', 'blue',
'boarder-gen2', 'boarder',
'brandon-gen3',
'brawly-gen3', 'brawly',
'brendan-gen3', 'brendan-gen3rs',
'brock-gen1', 'brock-gen1rb', 'brock-gen2', 'brock-gen3', 'brock',
'bruno-gen1', 'bruno-gen1rb', 'bruno-gen2', 'bruno-gen3', 'bruno',
'brycenman',
'brycen',
'buck',
'bugcatcher-gen1', 'bugcatcher-gen1rb', 'bugcatcher-gen2', 'bugcatcher-gen3', 'bugcatcher-gen3rs', 'bugcatcher-gen4dp', 'bugcatcher',
'bugmaniac-gen3',
'bugsy-gen2', 'bugsy',
'burgh',
'burglar-gen1', 'burglar-gen1rb', 'burglar-gen2', 'burglar-gen3', 'burglar',
'byron',
'caitlin',
'cameraman',
'camper-gen2', 'camper-gen3', 'camper-gen3rs', 'camper',
'candice',
'channeler-gen1', 'channeler-gen1rb', 'channeler-gen3',
'cheren-gen5bw2', 'cheren',
'cheryl',
'chili',
'chuck-gen2', 'chuck',
'cilan',
'clair-gen2', 'clair',
'clay',
'clemont',
'clerkf',
'clerk-boss', 'clerk',
'clown',
'collector-gen3', 'collector',
'colress',
'courtney-gen3',
'cowgirl',
'crasherwake',
'cress',
'crushgirl-gen3',
'crushkin-gen3',
'cueball-gen1', 'cueball-gen1rb', 'cueball-gen3',
'cyclistf-gen4', 'cyclistf',
'cyclist-gen4', 'cyclist',
'cynthia-gen4', 'cynthia',
'cyrus',
'dahlia',
'daisy-gen3',
'dancer',
'darach',
'dawn-gen4pt', 'dawn',
'depotagent',
'doctor',
'doubleteam',
'dragontamer-gen3', 'dragontamer',
'drake-gen3',
'drayden',
'elesa-gen5bw2', 'elesa',
'emmet',
'engineer-gen1', 'engineer-gen1rb', 'engineer-gen3',
'erika-gen1', 'erika-gen1rb', 'erika-gen2', 'erika-gen3', 'erika',
'ethan-gen2c', 'ethan-gen2', 'ethan-pokeathlon', 'ethan',
'eusine-gen2', 'eusine',
'expertf-gen3',
'expert-gen3',
'falkner-gen2',
'falkner',
'fantina',
'firebreather-gen2',
'firebreather',
'fisherman-gen1', 'fisherman-gen1rb', 'fisherman-gen2jp', 'fisherman-gen3', 'fisherman-gen3rs', 'fisherman-gen4', 'fisherman',
'flannery-gen3', 'flannery',
'flint',
'galacticgruntf',
'galacticgrunt',
'gambler-gen1', 'gambler-gen1rb', 'gambler',
'gamer-gen3',
'gardenia',
'gentleman-gen1', 'gentleman-gen1rb', 'gentleman-gen2', 'gentleman-gen3', 'gentleman-gen3rs', 'gentleman-gen4dp', 'gentleman-gen4', 'gentleman',
'ghetsis-gen5bw', 'ghetsis',
'giovanni-gen1', 'giovanni-gen1rb', 'giovanni-gen3', 'giovanni',
'glacia-gen3',
'greta-gen3',
'grimsley',
'guitarist-gen2', 'guitarist-gen3', 'guitarist-gen4', 'guitarist',
'harlequin',
'hexmaniac-gen3jp', 'hexmaniac-gen3',
'hiker-gen1', 'hiker-gen1rb', 'hiker-gen2', 'hiker-gen3', 'hiker-gen3rs', 'hiker-gen4', 'hiker',
'hilbert-wonderlauncher', 'hilbert',
'hilda-wonderlauncher', 'hilda',
'hooligans',
'hoopster',
'hugh',
'idol',
'infielder',
'ingo',
'interviewers-gen3',
'interviewers',
'iris-gen5bw2', 'iris',
'janine-gen2', 'janine',
'janitor',
'jasmine-gen2', 'jasmine',
'jessiejames-gen1',
'jogger',
'jrtrainerf-gen1', 'jrtrainerf-gen1rb',
'jrtrainer-gen1', 'jrtrainer-gen1rb',
'juan-gen3',
'juan',
'juggler-gen1', 'juggler-gen1rb', 'juggler-gen2', 'juggler-gen3', 'juggler',
'jupiter',
'karen-gen2', 'karen',
'kimonogirl-gen2', 'kimonogirl',
'kindler-gen3',
'koga-gen1', 'koga-gen2', 'koga-gen1rb', 'koga-gen3', 'koga',
'kris-gen2',
'lady-gen3', 'lady-gen3rs', 'lady-gen4', 'lady',
'lance-gen1', 'lance-gen1rb', 'lance-gen2', 'lance-gen3', 'lance',
'lass-gen1', 'lass-gen1rb', 'lass-gen2', 'lass-gen3', 'lass-gen3rs', 'lass-gen4dp', 'lass-gen4', 'lass',
'leaf-gen3',
'lenora',
'linebacker',
'li',
'liza',
'lorelei-gen1', 'lorelei-gen1rb', 'lorelei-gen3',
'ltsurge-gen1', 'ltsurge-gen1rb', 'ltsurge-gen2', 'ltsurge-gen3', 'ltsurge',
'lucas-gen4pt', 'lucas',
'lucian',
'lucy-gen3',
'lyra-pokeathlon', 'lyra',
'madame-gen4dp', 'madame-gen4', 'madame',
'maid-gen4', 'maid',
'marley',
'marlon',
'marshal',
'mars',
'matt-gen3',
'maxie-gen3',
'may-gen3', 'may-gen3rs',
'maylene',
'medium-gen2jp', 'medium',
'mira',
'misty-gen1', 'misty-gen2', 'misty-gen1rb', 'misty-gen3', 'misty',
'morty-gen2', 'morty',
'mrfuji-gen3',
'musician',
'nate-wonderlauncher', 'nate',
'ninjaboy-gen3', 'ninjaboy',
'noland-gen3',
'norman-gen3', 'norman',
'n',
'nurse',
'nurseryaide',
'oak-gen1', 'oak-gen1rb', 'oak-gen2', 'oak-gen3',
'officer-gen2',
'oldcouple-gen3',
'painter-gen3',
'palmer',
'parasollady-gen3', 'parasollady-gen4', 'parasollady',
'petrel',
'phoebe-gen3',
'picnicker-gen2', 'picnicker-gen3', 'picnicker-gen3rs', 'picnicker',
'pilot',
'plasmagruntf-gen5bw', 'plasmagruntf',
'plasmagrunt-gen5bw', 'plasmagrunt',
'pokefanf-gen2', 'pokefanf-gen3', 'pokefanf-gen4', 'pokefanf',
'pokefan-gen2', 'pokefan-gen3', 'pokefan-gen4', 'pokefan',
'pokekid',
'pokemaniac-gen1', 'pokemaniac-gen1rb', 'pokemaniac-gen2', 'pokemaniac-gen3', 'pokemaniac-gen3rs', 'pokemaniac',
'pokemonbreederf-gen3', 'pokemonbreederf-gen3frlg', 'pokemonbreederf-gen4', 'pokemonbreederf',
'pokemonbreeder-gen3', 'pokemonbreeder-gen4', 'pokemonbreeder',
'pokemonrangerf-gen3', 'pokemonrangerf-gen3rs', 'pokemonrangerf-gen4', 'pokemonrangerf',
'pokemonranger-gen3', 'pokemonranger-gen3rs', 'pokemonranger-gen4', 'pokemonranger',
'policeman-gen4', 'policeman',
'preschoolerf',
'preschooler',
'proton',
'pryce-gen2', 'pryce',
'psychicf-gen3', 'psychicf-gen3rs', 'psychicf-gen4', 'psychicfjp-gen3', 'psychicf',
'psychic-gen1', 'psychic-gen1rb', 'psychic-gen2', 'psychic-gen3', 'psychic-gen3rs', 'psychic-gen4', 'psychic',
'rancher',
'red-gen1main', 'red-gen1', 'red-gen1rb', 'red-gen1title', 'red-gen2', 'red-gen3', 'red',
'reporter',
'richboy-gen3', 'richboy-gen4', 'richboy',
'riley',
'roark',
'rocker-gen1', 'rocker-gen1rb', 'rocker-gen3',
'rocket-gen1', 'rocket-gen1rb',
'rocketgruntf-gen2', 'rocketgruntf',
'rocketgrunt-gen2', 'rocketgrunt',
'rocketexecutivef-gen2',
'rocketexecutive-gen2',
'rood',
'rosa-wonderlauncher', 'rosa',
'roughneck-gen4', 'roughneck',
'roxanne-gen3', 'roxanne',
'roxie',
'ruinmaniac-gen3', 'ruinmaniac-gen3rs', 'ruinmaniac',
'sabrina-gen1', 'sabrina-gen1rb', 'sabrina-gen2', 'sabrina-gen3', 'sabrina',
'sage-gen2', 'sage-gen2jp', 'sage',
'sailor-gen1', 'sailor-gen1rb', 'sailor-gen2', 'sailor-gen3jp', 'sailor-gen3', 'sailor-gen3rs', 'sailor',
'saturn',
'schoolboy-gen2',
'schoolkidf-gen3', 'schoolkidf-gen4', 'schoolkidf',
'schoolkid-gen3', 'schoolkid-gen4dp', 'schoolkid-gen4', 'schoolkid',
'scientistf',
'scientist-gen1', 'scientist-gen1rb', 'scientist-gen2', 'scientist-gen3', 'scientist-gen4dp', 'scientist-gen4', 'scientist',
'shadowtriad',
'shauntal',
'shelly-gen3',
'sidney-gen3',
'silver-gen2kanto', 'silver-gen2', 'silver',
'sisandbro-gen3', 'sisandbro-gen3rs', 'sisandbro',
'skierf-gen4dp', 'skierf',
'skier-gen2', 'skier',
'skyla',
'smasher',
'spenser-gen3',
'srandjr-gen3',
'steven-gen3', 'steven',
'striker',
'supernerd-gen1', 'supernerd-gen1rb', 'supernerd-gen2', 'supernerd-gen3', 'supernerd',
'swimmerf-gen2', 'swimmerf-gen3', 'swimmerf-gen3rs', 'swimmerf-gen4dp', 'swimmerf-gen4', 'swimmerfjp-gen2', 'swimmerf',
'swimmer-gen1', 'swimmer-gen1rb', 'swimmer-gen4dp', 'swimmer-gen4jp', 'swimmer-gen4', 'swimmerm-gen2', 'swimmerm-gen3', 'swimmerm-gen3rs', 'swimmer',
'tabitha-gen3',
'tamer-gen1', 'tamer-gen1rb', 'tamer-gen3',
'tateandliza-gen3',
'tate',
'teacher-gen2', 'teacher',
'teamaquabeta-gen3',
'teamaquagruntf-gen3',
'teamaquagruntm-gen3',
'teammagmagruntf-gen3',
'teammagmagruntm-gen3',
'teamrocketgruntf-gen3',
'teamrocketgruntm-gen3',
'teamrocket',
'thorton',
'triathletebikerf-gen3',
'triathletebikerm-gen3',
'triathleterunnerf-gen3',
'triathleterunnerm-gen3',
'triathleteswimmerf-gen3',
'triathleteswimmerm-gen3',
'tuberf-gen3', 'tuberf-gen3rs', 'tuberf',
'tuber-gen3', 'tuber',
'tucker-gen3',
'twins-gen2', 'twins-gen3', 'twins-gen3rs', 'twins-gen4dp', 'twins-gen4', 'twins',
'unknownf',
'unknown',
'veteranf',
'veteran-gen4', 'veteran',
'volkner',
'waiter-gen4dp', 'waiter-gen4', 'waiter',
'waitress-gen4', 'waitress',
'wallace-gen3', 'wallace-gen3rs', 'wallace',
'wally-gen3',
'wattson-gen3', 'wattson',
'whitney-gen2', 'whitney',
'will-gen2', 'will',
'winona-gen3', 'winona',
'worker-gen4',
'workerice',
'worker',
'yellow',
'youngcouple-gen3', 'youngcouple-gen3rs', 'youngcouple-gen4dp', 'youngcouple',
'youngster-gen1', 'youngster-gen1rb', 'youngster-gen2', 'youngster-gen3', 'youngster-gen3rs', 'youngster-gen4', 'youngster-gen4dp', 'youngster',
'zinzolin',
]);
const OFFICIAL_AVATARS_BELIOT419 = new Set([
'acerola', 'aetheremployee', 'aetheremployeef', 'aetherfoundation', 'aetherfoundationf', 'anabel',
'beauty-gen7', 'blue-gen7', 'burnet', 'colress-gen7', 'dexio', 'elio', 'faba', 'gladion-stance',
'gladion', 'grimsley-gen7', 'hapu', 'hau-stance', 'hau', 'hiker-gen7', 'ilima', 'kahili', 'kiawe',
'kukui-stand', 'kukui', 'lana', 'lass-gen7', 'lillie-z', 'lillie', 'lusamine-nihilego', 'lusamine',
'mallow', 'mina', 'molayne', 'nanu', 'officeworker', 'olivia', 'plumeria', 'pokemonbreeder-gen7',
'pokemonbreederf-gen7', 'preschoolers', 'red-gen7', 'risingstar', 'risingstarf', 'ryuki',
'samsonoak', 'selene', 'sightseer', 'sina', 'sophocles', 'teacher-gen7', 'theroyal', 'wally',
'wicke', 'youngathlete', 'youngathletef', 'youngster-gen7',
]);
const OFFICIAL_AVATARS_GNOMOWLADNY = new Set([
'az', 'brawly-gen6', 'bryony', 'drasna', 'evelyn', 'furisodegirl-black', 'furisodegirl-pink', 'guzma',
'hala', 'korrina', 'malva', 'nita', 'olympia', 'ramos', 'shelly', 'sidney', 'siebold', 'tierno',
'valerie', 'viola', 'wallace-gen6', 'wikstrom', 'winona-gen6', 'wulfric', 'xerosic', 'youngn', 'zinnia',
]);
for (const avatar of OFFICIAL_AVATARS_BELIOT419) OFFICIAL_AVATARS.add(avatar);
for (const avatar of OFFICIAL_AVATARS_GNOMOWLADNY) OFFICIAL_AVATARS.add(avatar);
export const commands: Chat.ChatCommands = {
avatar(target, room, user) {
if (!target) return this.parse(`${this.cmdToken}avatars`);
const [maybeAvatar, silent] = target.split(',');
const avatar = Avatars.userCanUse(user, maybeAvatar);
if (!avatar) {
if (silent) return false;
this.errorReply("Unrecognized avatar - make sure you're on the right account?");
return false;
}
user.avatar = avatar;
if (user.id in customAvatars && !avatar.endsWith('xmas')) {
Avatars.setDefault(user.id, avatar);
}
if (!silent) {
this.sendReply(
`${this.tr`Avatar changed to:`}\n` +
Chat.html`|raw|${Avatars.img(avatar)}`
);
if (OFFICIAL_AVATARS_BELIOT419.has(avatar)) {
this.sendReply(`|raw|(${this.tr`Artist: `}<a href="https://www.deviantart.com/beliot419">Beliot419</a>)`);
}
if (OFFICIAL_AVATARS_GNOMOWLADNY.has(avatar)) {
this.sendReply(`|raw|(${this.tr`Artist: `}Gnomowladny)`);
}
}
},
avatarhelp: [`/avatar [avatar name or number] - Change your trainer sprite.`],
avatars(target, room, user) {
this.runBroadcast();
if (target.startsWith('#')) return this.parse(`/avatarusers ${target}`);
const targetUser = this.broadcasting && !target ? null : this.getUserOrSelf(target);
const targetUserids = targetUser ? new Set([targetUser.id, ...targetUser.previousIDs]) :
target ? new Set([toID(target)]) : null;
if (targetUserids && targetUser !== user && !user.can('alts')) {
throw new Chat.ErrorMessage("You don't have permission to look at another user's avatars!");
}
const out = [];
if (targetUserids) {
const hasButton = !this.broadcasting && targetUser === user;
for (const id of targetUserids) {
const allowed = customAvatars[id]?.allowed;
if (allowed) {
out.push(
<p>Custom avatars from account <strong>{id}</strong>:</p>,
allowed.filter(Boolean).map(avatar => (
<p>
{hasButton ?
<button name="send" value={`/avatar ${avatar}`} class="button">{Avatars.img(avatar!)}</button> :
Avatars.img(avatar!)
} {}
<code>/avatar {avatar!.replace('#', '')}</code>
</p>
))
);
}
}
if (!out.length && target) {
out.push(<p>User <strong>{toID(target)}</strong> doesn't have any custom avatars.</p>);
}
}
if (!out.length) {
out.push(<p>Custom avatars require you to be a contributor/staff or win a tournament prize.</p>);
}
this.sendReplyBox(<>
{!target && [<p>
You can <button name="avatars" class="button">change your avatar</button> by clicking on it in the {}
<button name="openOptions" class="button" aria-label="Options"><i class="fa fa-cog"></i></button> menu in the upper {}
right.
</p>, <p>
Avatars from generations other than 3-5 are hidden. You can find them in this {}
<a href="https://play.pokemonshowdown.com/sprites/trainers/"><strong>full list of avatars</strong></a>. {}
You can use them by typing <code>/avatar <i>[avatar's name]</i></code> into any chat. For example, {}
<code>/avatar erika-gen2</code>.
</p>]}
{out}
</>);
},
avatarshelp: [
`/avatars - Explains how to change avatars.`,
`/avatars [username] - Shows custom avatars available to a user.`,
`!avatars - Show everyone that information. Requires: + % @ # &`,
],
addavatar() {
this.sendReply("Is this a personal avatar or a group avatar?");
return this.parse(`/help addavatar`);
},
addavatarhelp: [
`/personalavatar [username], [avatar] - Gives a user a default (personal) avatar.`,
`/groupavatar [username], [avatar] - Gives a user an allowed (group) avatar.`,
`/removeavatar [username], [avatar] - Removes access to an avatar from a user.`,
`/removeavatar [username] - Removes access to all custom avatars from a user.`,
AVATAR_FORMATS_MESSAGE,
],
personalavatar: 'defaultavatar',
async defaultavatar(target, room, user) {
this.checkCan('bypassall');
if (!target) return this.parse(`/help defaultavatar`);
const [inputUsername, inputAvatar] = this.splitOne(target);
if (!Users.isUsername(inputUsername)) {
throw new Chat.ErrorMessage(`"${inputUsername}" is not a valid username.`);
}
const userid = toID(inputUsername);
const avatar = await Avatars.validate(inputAvatar, {rejectOfficial: true});
if (!Avatars.addPersonal(userid, avatar)) {
throw new Chat.ErrorMessage(`User "${inputUsername}" can already use avatar "${avatar}".`);
}
this.globalModlog('PERSONAL AVATAR', userid, avatar);
this.sendReplyBox(<div>
{Avatars.img(avatar)}<br />
Added to <username class="username">{inputUsername}</username>
</div>);
},
defaultavatarhelp: 'addavatarhelp',
allowedavatar: 'allowavatar',
groupavatar: 'allowavatar',
async allowavatar(target, room, user) {
this.checkCan('bypassall');
if (!target) return this.parse(`/help defaultavatar`);
const [inputUsername, inputAvatar] = this.splitOne(target);
if (!Users.isUsername(inputUsername)) {
throw new Chat.ErrorMessage(`"${inputUsername}" is not a valid username.`);
}
const userid = toID(inputUsername);
const avatar = await Avatars.validate(inputAvatar, {rejectOfficial: true});
if (!Avatars.addAllowed(userid, avatar)) {
throw new Chat.ErrorMessage(`User "${inputUsername}" can already use avatar "${avatar}".`);
}
this.globalModlog('GROUP AVATAR', userid, avatar);
this.sendReplyBox(<div>
{Avatars.img(avatar)}<br />
Added to <username class="username">{inputUsername}</username>
</div>);
},
allowavatarhelp: 'addavatarhelp',
denyavatar: 'removeavatar',
disallowavatar: 'removeavatar',
removeavatars: 'removeavatar',
removeavatar(target, room, user) {
this.checkCan('bypassall');
if (!target) return this.parse(`/help defaultavatar`);
const [inputUsername, inputAvatar] = this.splitOne(target);
if (!Users.isUsername(inputUsername)) {
throw new Chat.ErrorMessage(`"${inputUsername}" is not a valid username.`);
}
const userid = toID(inputUsername);
const avatar = Avatars.convert(inputAvatar);
const allowed = customAvatars[userid]?.allowed.filter(Boolean);
if (!allowed) {
throw new Chat.ErrorMessage(`${inputUsername} doesn't have any custom avatars.`);
}
if (avatar) {
if (!Avatars.removeAllowed(userid, avatar)) {
throw new Chat.ErrorMessage(`${inputUsername} doesn't have access to avatar "${avatar}"`);
}
this.globalModlog('REMOVE AVATAR', userid, avatar);
this.sendReplyBox(<div>
{Avatars.img(avatar)}<br />
Removed from <username class="username">{inputUsername}</username>
</div>);
} else {
// delete all
delete customAvatars[userid];
Avatars.save();
this.globalModlog('REMOVE AVATARS', userid, allowed.join(','));
this.sendReplyBox(<div>
{allowed.map(curAvatar => [Avatars.img(curAvatar!), ' '])}<br />
Removed from <username class="username">{inputUsername}</username>
</div>);
}
},
removeavatarhelp: 'addavatarhelp',
async avatarusers(target, room, user) {
target = '#' + toID(target);
if (!Avatars.userCanUse(user, target) && !user.can('alts')) {
throw new Chat.ErrorMessage(`You don't have access to avatar "${target}"`);
}
this.runBroadcast();
const users = [];
for (const userid in customAvatars) {
if (customAvatars[userid].allowed.includes(target)) {
users.push(userid);
}
}
users.sort();
if (!users.length && !await Avatars.exists(target)) {
throw new Chat.ErrorMessage(`Unrecognized avatar "${target}"`);
}
this.sendReplyBox(<>
<p>{Avatars.img(target, true)}</p>
<p>
<code>{target}</code><br />
{users ? listUsers(users) : <p>No users currently allowed to use this avatar</p>}
</p>
</>);
},
async masspavatar(target, room, user) {
this.checkCan('bypassall');
const usernames = target.trim().split(/\s*\n|,\s*/)
.map(username => username.endsWith('.png') ? username.slice(0, -4) : username);
for (const username of usernames) {
if (!Users.isUsername(username)) {
throw new Chat.ErrorMessage(`Invalid username "${username}"`);
}
await Avatars.validate('#' + toID(username));
}
const userids = usernames.map(toID);
for (const userid of userids) {
const avatar = '#' + userid;
Avatars.addPersonal(userid, avatar);
this.globalModlog('PERSONAL AVATAR', userid, avatar);
}
this.sendReplyBox(<div>
{userids.map(userid => Avatars.img('#' + userid))}<br />
Added {userids.length} avatars
</div>);
},
async massxmasavatar(target, room, user) {
this.checkCan('bypassall');
const usernames = target.trim().split(/\s*\n|,\s*/)
.map(username => username.endsWith('.png') ? username.slice(0, -4) : username)
.map(username => username.endsWith('xmas') ? username.slice(0, -4) : username);
for (const username of usernames) {
if (!Users.isUsername(username)) {
throw new Chat.ErrorMessage(`Invalid username "${username}"`);
}
await Avatars.validate(`#${toID(username)}xmas`);
}
const userids = usernames.map(toID);
for (const userid of userids) {
const avatar = `#${userid}xmas`;
Avatars.addAllowed(userid, avatar);
this.globalModlog('GROUP AVATAR', userid, avatar);
}
this.sendReplyBox(<div>
{userids.map(userid => Avatars.img(`#${userid}xmas`))}<br />
Added {userids.length} avatars
</div>);
},
async massgavatar(target, room, user) {
this.checkCan('bypassall');
const args = target.trim().split(/\s*\n|,\s*/);
let curAvatar = '';
const toUpdate: Record<string, Set<ID>> = Object.create(null);
for (const arg of args) {
if (arg.startsWith('#')) {
curAvatar = await Avatars.validate(arg);
} else {
if (!curAvatar) return this.parse(`/help massgavatar`);
if (!/[A-Za-z0-9]/.test(arg.charAt(0)) || !/[A-Za-z]/.test(arg)) {
throw new Chat.ErrorMessage(`Invalid username "${arg}"`);
}
(toUpdate[curAvatar] ??= new Set()).add(toID(arg));
}
}
const out = [];
for (const avatar in toUpdate) {
const newUsers = toUpdate[avatar];
const oldUsers = new Set<ID>();
for (const userid in customAvatars) {
if (customAvatars[userid].allowed.includes(avatar)) {
oldUsers.add(userid as ID);
}
}
const added: ID[] = [];
for (const newUser of newUsers) {
if (!oldUsers.has(newUser)) {
Avatars.addAllowed(newUser, avatar);
added.push(newUser);
this.globalModlog('GROUP AVATAR', newUser, avatar);
}
}
const removed: ID[] = [];
for (const oldUser of oldUsers) {
if (!newUsers.has(oldUser)) {
Avatars.removeAllowed(oldUser, avatar);
removed.push(oldUser);
this.globalModlog('REMOVE AVATAR', oldUser, avatar);
}
}
out.push(<p>{Avatars.img(avatar, true)}</p>);
out.push(<div><code>{avatar}</code></div>);
if (added.length) out.push(<div>{oldUsers.size ? 'Added' : 'New'}: {listUsers(added)}</div>);
if (removed.length) out.push(<div>Removed: {listUsers(removed)}</div>);
if (!added.length && !removed.length) out.push(<div>No change</div>);
}
this.sendReplyBox(<>{out}</>);
Avatars.save(true);
},
};
Users.Avatars = Avatars;
Chat.multiLinePattern.register(
'/massgavatar', '/masspavatar', '/massxmasavatar',
); | the_stack |
import { LiveAnnouncer } from '@angular/cdk/a11y';
import {
ConnectedPosition,
ScrollStrategy,
ScrollStrategyOptions,
} from '@angular/cdk/overlay';
import { Component, ElementRef, NgZone, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MatIconRegistry } from '@angular/material/icon';
import { DomSanitizer } from '@angular/platform-browser';
import { NavigationEnd, Router } from '@angular/router';
import * as moment from 'moment';
import { take } from 'rxjs/operators';
import { BuildReportStep } from '../../common-types';
import { ExitDialogComponent } from '../exit-dialog/exit-dialog.component';
import {
EventAction,
EventCategory,
GoogleAnalyticsService,
} from '../google_analytics.service';
import { OauthApiService } from '../oauth_api.service';
import { OnboardingService } from '../onboarding.service';
import {
getRouterLinkForReportStep,
ReportAction,
ReportService,
} from '../report.service';
import { SocialMediaItemService } from '../social-media-item.service';
export const ONE_MIN_MS = 60 * 1000;
export const ONE_HOUR_MS = 60 * ONE_MIN_MS;
export const ONE_DAY_MS = 24 * ONE_HOUR_MS;
@Component({
selector: 'app-toolbar',
templateUrl: './toolbar.component.html',
styleUrls: ['./toolbar.component.scss'],
})
export class ToolbarComponent {
// Reference to the dropdown for testing purposes.
@ViewChild('dropdown') dropdownElement?: ElementRef;
// Number of comments in the report draft.
reportDraftCommentCount = 0;
// Number of comments that were most recently added to the report. This is
// shown in a notification to the user.
reportNotificationCommentCount = 0;
// Whether to show the user a notification about having just added comments to
// the report.
reportNotificationOpen = false;
showBuildReportStepper = false;
currentStep = BuildReportStep.NONE;
// Copy of enum to use in the template.
readonly BuildReportStep = BuildReportStep;
private reportStarted = false;
notificationTitleText = '';
notificationSubtitleText = '';
private exitDialogOpen = false;
userIsSignedIn = false;
onboarding = false;
reportActions: ReportAction[];
reportLastEditedMs = Date.now();
overlayScrollStrategy: ScrollStrategy;
// This describes how the overlay should be connected to the origin element.
connectedOverlayPositions: ConnectedPosition[] = [
{
originX: 'center',
originY: 'bottom',
overlayX: 'end',
overlayY: 'top',
offsetY: 24,
},
// Secondary positioning strategy
{
originX: 'start',
originY: 'center',
overlayX: 'end',
overlayY: 'center',
offsetX: -24,
},
];
constructor(
private oauthApiService: OauthApiService,
private ngZone: NgZone,
private router: Router,
private reportService: ReportService,
private iconRegistry: MatIconRegistry,
private sanitizer: DomSanitizer,
private onboardingService: OnboardingService,
private readonly scrollStrategyOptions: ScrollStrategyOptions,
public dialog: MatDialog,
private googleAnalyticsService: GoogleAnalyticsService,
private socialMediaItemService: SocialMediaItemService,
private liveAnnouncer: LiveAnnouncer
) {
this.overlayScrollStrategy = this.scrollStrategyOptions.block();
this.iconRegistry.addSvgIcon(
'report_icon',
this.sanitizer.bypassSecurityTrustResourceUrl('/report.svg')
);
this.iconRegistry.addSvgIcon(
'report_icon_white',
this.sanitizer.bypassSecurityTrustResourceUrl('/report_white.svg')
);
this.reportService.reportLastEditedChanged.subscribe(lastEditedMs => {
this.reportLastEditedMs = lastEditedMs;
});
this.reportService.reportCommentsChanged.subscribe(reportComments => {
this.reportNotificationCommentCount = Math.max(
0,
reportComments.length - this.reportDraftCommentCount
);
if (this.reportNotificationCommentCount > 0) {
this.reportNotificationOpen = true;
this.notificationTitleText = this.getNotificationTitleText();
this.notificationSubtitleText = this.getNotificationSubtitleText();
this.reportStarted = true;
setTimeout(() => {
this.reportNotificationOpen = false;
}, 5000);
}
this.reportDraftCommentCount = reportComments.length;
});
this.reportActions = this.reportService.getReportActions();
this.reportService.reportActionsChanged.subscribe(reportActions => {
this.reportActions = reportActions;
});
this.reportService.reportCleared.subscribe(() => {
this.router.navigate(['/home']);
});
this.oauthApiService.twitterSignInChange.subscribe(signedIn => {
this.userIsSignedIn = signedIn;
});
this.onboardingService.highlightReviewReportButton.subscribe(() => {
this.nextOnboardingStep();
});
this.reportService.reportStepChanged.subscribe(
(reportStep: BuildReportStep) => {
this.currentStep = reportStep;
}
);
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
if (event.url.includes('/create-report')) {
this.reportService.setReportStep(BuildReportStep.ADD_COMMENTS);
this.showBuildReportStepper = true;
} else if (event.url === '/review-report') {
this.reportService.setReportStep(BuildReportStep.EDIT_DETAILS);
this.showBuildReportStepper = true;
} else if (event.url === '/share-report') {
this.reportService.setReportStep(BuildReportStep.TAKE_ACTION);
this.showBuildReportStepper = true;
} else if (event.url === '/report-complete') {
this.reportService.setReportStep(BuildReportStep.COMPLETE);
this.showBuildReportStepper = false;
} else {
this.showBuildReportStepper = false;
}
}
});
}
/**
* Returns a string describing the time the report was last edited:
* If the edit was less than a minute ago, it returns 'Last edit less than 1
* min ago'.
* If the edit was less than a day ago, it returns 'Last edit ' + the number
* of hours and minutes since the last edit.
* If the edit was more than a day ago, it returns 'Last edit ' + the month
* and day of the last edit.
*/
getTimeSinceLastReportEditString(): string {
const now = Date.now();
const msSinceLastReportEdit = now - this.reportLastEditedMs;
let timeStr = 'Last edit';
if (msSinceLastReportEdit < ONE_MIN_MS) {
timeStr += ' less than 1 min ago';
} else {
const days =
msSinceLastReportEdit >= ONE_DAY_MS
? Math.floor(msSinceLastReportEdit / ONE_DAY_MS)
: 0;
const hours =
msSinceLastReportEdit >= ONE_HOUR_MS
? Math.floor(
(msSinceLastReportEdit - ONE_DAY_MS * days) / ONE_HOUR_MS
)
: 0;
const minutes = Math.floor(
(msSinceLastReportEdit - (ONE_DAY_MS * days + ONE_HOUR_MS * hours)) /
ONE_MIN_MS
);
if (days >= 1) {
const date = moment(this.reportLastEditedMs);
timeStr += ` on ${date.format('MMM D')}`;
} else {
if (hours >= 1) {
timeStr += ` ${hours} hr`;
}
if (minutes > 0) {
timeStr += ` ${minutes} min`;
}
timeStr += ' ago';
}
}
return timeStr;
}
getStepperButtonActive(): boolean {
if (this.currentStep === BuildReportStep.ADD_COMMENTS) {
return this.reportDraftCommentCount > 0;
} else if (this.currentStep === BuildReportStep.TAKE_ACTION) {
return !this.exitDialogOpen;
} else {
return true;
}
}
getStepperButtonRouterLink(): string {
return getRouterLinkForReportStep(this.currentStep + 1);
}
onStepperButtonClick(): void {
const nextPage = this.getStepperButtonRouterLink();
if (nextPage === '/report-complete') {
if (this.exitDialogOpen) {
return;
}
const dialogRef = this.dialog.open(ExitDialogComponent, {
panelClass: 'exit-dialog-container',
});
this.exitDialogOpen = true;
dialogRef
.afterClosed()
.pipe(take(1))
.subscribe(exitReport => {
this.exitDialogOpen = false;
if (exitReport) {
// Log that we've finished the report.
this.googleAnalyticsService.emitEvent(
EventCategory.REPORT,
EventAction.FINISH_REPORT
);
this.reportService.clearReport();
if (this.reportActions.length > 0) {
// Show 'report complete' page only if user took action on report.
this.router.navigate([nextPage]);
} else {
this.router.navigate(['/home']);
}
}
});
} else {
this.router.navigate([nextPage]);
}
}
getExitDialogOpen(): boolean {
return this.exitDialogOpen;
}
getBackButtonText(): string {
if (this.currentStep === BuildReportStep.EDIT_DETAILS) {
return 'Back to Comments';
} else if (this.currentStep === BuildReportStep.TAKE_ACTION) {
return 'Back to Details';
} else {
return '';
}
}
getBackButtonRouterLink(): string {
if (this.currentStep === BuildReportStep.EDIT_DETAILS) {
return '/create-report';
} else if (this.currentStep === BuildReportStep.TAKE_ACTION) {
return '/review-report';
} else {
// We shouldn't get here, but if we do, navigate to home.
return '/home';
}
}
getCreateReportRouterLink(): string {
if (this.currentStep === BuildReportStep.EDIT_DETAILS) {
return '/review-report';
} else if (this.currentStep === BuildReportStep.TAKE_ACTION) {
return '/share-report';
} else {
return '/create-report';
}
}
getReportButtonText(): string {
if (this.currentStep === BuildReportStep.TAKE_ACTION) {
return 'Close report';
} else {
return 'Continue';
}
}
getReportButtonA11yLabel(): string {
if (this.currentStep === BuildReportStep.ADD_COMMENTS) {
return this.reportDraftCommentCount + (
this.reportDraftCommentCount === 1 ? ' Comment' : ' Comments')
+ ' in Report Draft. Continue.'
} else if (this.currentStep === BuildReportStep.EDIT_DETAILS) {
return 'Continue';
} else if (this.currentStep === BuildReportStep.TAKE_ACTION) {
return 'Close report';
} else {
return '';
}
}
nextOnboardingStep() {
this.onboarding = !this.onboarding;
if (!this.onboarding) {
this.liveAnnouncer.announce('Exited onboarding walkthrough dialog');
this.onboardingService.setCreateReportPageOnboardingComplete();
}
}
revokeAuthorization(): void {
this.oauthApiService.revokeAuth().then(() => {
this.reportStarted = false;
this.ngZone.run(() => {
this.router.navigate(['/']);
});
});
}
getNotificationTitleText(): string {
if (!this.reportStarted) {
return 'Nice work! You\'ve started your report.';
} else if (this.reportNotificationCommentCount === 1) {
return 'Comment added to report';
} else {
return `${this.reportNotificationCommentCount} comments added to report`;
}
}
getNotificationSubtitleText(): string {
if (!this.reportStarted) {
return (
'Review your report draft or continue adding comments at your ' +
'own pace.'
);
} else {
return (
'Processing harmful content can be taxing. Take a break and come ' +
'back anytime. Your work will be saved.'
);
}
}
} | the_stack |
import * as path from 'path';
import * as util from 'util';
// 3pp
import * as _ from 'lodash';
import { fs, SfdxProject } from '@salesforce/core';
import { TypeDefObj } from './typeDefObj';
interface TypeDefObjs {
[key: string]: TypeDefObj;
}
// Constants
const METADATA_FILE_EXT = '-meta.xml';
const LWC_FOLDER_NAME = 'lwc';
const _lightningDefTypes = {
APPLICATION: {
defType: 'APPLICATION',
format: 'XML',
fileSuffix: '.app',
hasMetadata: true,
},
CONTROLLER: {
defType: 'CONTROLLER',
format: 'JS',
fileSuffix: 'Controller.js',
},
COMPONENT: {
defType: 'COMPONENT',
format: 'XML',
fileSuffix: '.cmp',
hasMetadata: true,
},
EVENT: {
defType: 'EVENT',
format: 'XML',
fileSuffix: '.evt',
hasMetadata: 'true',
},
HELPER: {
defType: 'HELPER',
format: 'JS',
fileSuffix: 'Helper.js',
},
INTERFACE: {
defType: 'INTERFACE',
format: 'XML',
fileSuffix: '.intf',
hasMetadata: true,
},
RENDERER: {
defType: 'RENDERER',
format: 'JS',
fileSuffix: 'Renderer.js',
},
STYLE: {
defType: 'STYLE',
format: 'CSS',
fileSuffix: '.css',
},
PROVIDER: {
defType: 'PROVIDER',
format: 'JS',
fileSuffix: 'Provider.js',
},
MODEL: {
defType: 'MODEL',
format: 'JS',
fileSuffix: 'Model.js',
},
TESTSUITE: {
defType: 'TESTSUITE',
format: 'JS',
fileSuffix: 'Test.js',
},
DOCUMENTATION: {
defType: 'DOCUMENTATION',
format: 'XML',
fileSuffix: '.auradoc',
},
TOKENS: {
defType: 'TOKENS',
format: 'XML',
fileSuffix: '.tokens',
hasMetadata: true,
},
DESIGN: {
defType: 'DESIGN',
format: 'XML',
fileSuffix: '.design',
},
SVG: {
defType: 'SVG',
format: 'SVG',
fileSuffix: '.svg',
},
};
const _lwcDefTypes = {
MODULE_RESOURCE_JS: {
defType: 'MODULE',
format: 'JS',
fileSuffix: '.js',
},
MODULE_RESOURCE_HTML: {
defType: 'MODULE',
format: 'HTML',
fileSuffix: '.html',
},
MODULE_RESOURCE_CSS: {
defType: 'MODULE',
format: 'CSS',
fileSuffix: '.css',
},
MODULE_RESOURCE_SVG: {
defType: 'MODULE',
format: 'SVG',
fileSuffix: '.svg',
},
MODULE_RESOURCE_XML: {
defType: 'MODULE',
format: 'XML',
fileSuffix: '.xml',
},
};
const _waveDefTypes = {
JSON: {
defType: 'JSON',
format: 'JSON',
fileSuffix: '.json',
},
HTML: {
defType: 'HTML',
format: 'HTML',
fileSuffix: '.html',
},
CSV: {
defType: 'CSV',
format: 'CSV',
fileSuffix: '.csv',
},
XML: {
defType: 'XML',
format: 'XML',
fileSuffix: '.xml',
},
TXT: {
defType: 'TXT',
format: 'TXT',
fileSuffix: '.txt',
},
IMG: {
defType: 'IMG',
format: 'IMG',
fileSuffix: '.img',
},
JPG: {
defType: 'JPG',
format: 'JPG',
fileSuffix: '.jpg',
},
JPEG: {
defType: 'JPEG',
format: 'JPEG',
fileSuffix: '.jpeg',
},
GIF: {
defType: 'GIF',
format: 'GIF',
fileSuffix: '.gif',
},
PNG: {
defType: 'PNG',
format: 'PNG',
fileSuffix: '.png',
},
};
const _typeDefMatchesDecompositionExtension = function (typeDef: TypeDefObj, typeExtension: string) {
if (
!util.isNullOrUndefined(typeDef.decompositionConfig) &&
!util.isNullOrUndefined(typeDef.decompositionConfig.decompositions)
) {
for (const decomposition of typeDef.decompositionConfig.decompositions) {
if (decomposition.ext.toLowerCase() === typeExtension.toLowerCase()) {
return true;
}
}
}
return false;
};
const _typeDefMatchesExtension = function (typeDef, typeExtension, includeDecomposedSubtypes) {
if (!util.isNullOrUndefined(typeDef.ext) && typeDef.ext.toLowerCase() === typeExtension) {
return true;
} else if (includeDecomposedSubtypes) {
return _typeDefMatchesDecompositionExtension(typeDef, typeExtension);
} else {
return false;
}
};
const _getDecompositionByName = function (typeDefs, value) {
if (util.isNullOrUndefined(value)) {
return null;
}
let foundDecomposition;
Object.keys(typeDefs).forEach((key) => {
if (!util.isNullOrUndefined(typeDefs[key].decompositionConfig)) {
typeDefs[key].decompositionConfig.decompositions.forEach((decomposition) => {
if (decomposition.metadataName === value) {
foundDecomposition = decomposition;
}
});
}
});
return util.isNullOrUndefined(foundDecomposition) ? null : foundDecomposition;
};
class MetadataRegistry {
private readonly typeDefs: TypeDefObjs;
private readonly typeDirectories: string[];
private readonly lightningDefTypes;
private readonly waveDefTypes;
private lwcDefTypes;
private typeDefsByExtension;
private readonly metadataFileExt;
private readonly projectPath: string;
constructor() {
this.typeDefs = this.getMetadataTypeDefs();
this.typeDirectories = this.getTypeDirectories();
this.lightningDefTypes = _lightningDefTypes;
this.waveDefTypes = _waveDefTypes;
this.lwcDefTypes = _lwcDefTypes;
this.typeDefsByExtension = this.getTypeDefsByExtension();
this.metadataFileExt = METADATA_FILE_EXT;
this.projectPath = SfdxProject.resolveProjectPathSync();
}
isSupported(metadataName) {
const isSupportedType = !util.isNullOrUndefined(this.getTypeDefinitionByMetadataName(metadataName));
if (isSupportedType) {
return true;
}
const decomposedSubtype = _getDecompositionByName(this.typeDefs, metadataName);
return !util.isNullOrUndefined(decomposedSubtype) && decomposedSubtype.isAddressable;
}
static getMetadataFileExt() {
return METADATA_FILE_EXT;
}
public getMetadataTypeDefs() {
if (!this.typeDefs) {
const metadataInfos = require(path.join(__dirname, '..', '..', '..', 'metadata', 'metadataTypeInfos.json')) as {
typeDefs: TypeDefObjs;
};
return metadataInfos.typeDefs;
} else {
return this.typeDefs;
}
}
/**
* Returns a formatted key provided a metadata type and name. This is used as a unique
* identifier for metadata. E.g., `ApexClass__MyClass`
*
* @param metadataType The metadata type. E.g., `ApexClass`
* @param metadataName The metadata name. E.g., `MyClass`
*/
public static getMetadataKey(metadataType: string, metadataName: string): string {
return `${metadataType}__${metadataName}`;
}
// Returns list of default directories for all metadata types
private getTypeDirectories(): string[] {
if (util.isNullOrUndefined(this.typeDirectories)) {
const metadataTypeInfos = this.getMetadataTypeDefs();
return Object.values(metadataTypeInfos).map((i) => i.defaultDirectory);
} else {
return this.typeDirectories;
}
}
private getTypeDefsByExtension() {
const typeDefsByExtension = new Map();
Object.keys(this.typeDefs).forEach((metadataName) => {
const metadataTypeExtension = this.typeDefs[metadataName].ext;
typeDefsByExtension.set(metadataTypeExtension, this.typeDefs[metadataName]);
});
return typeDefsByExtension;
}
public getLightningDefByFileName(fileName) {
return this.lightningDefTypes[
Object.keys(this.lightningDefTypes).find((key) => {
const lightningDefType = this.lightningDefTypes[key];
return fileName.endsWith(lightningDefType.fileSuffix);
})
];
}
public getWaveDefByFileName(fileName) {
return this.waveDefTypes[
Object.keys(this.waveDefTypes).find((key) => {
const waveDefType = this.waveDefTypes[key];
return fileName.endsWith(waveDefType.fileSuffix);
})
];
}
public getLightningDefByType(type) {
return this.lightningDefTypes[
Object.keys(this.lightningDefTypes).find((key) => {
const lightningDefType = this.lightningDefTypes[key];
return type === lightningDefType.defType;
})
];
}
/**
* Returns the array of typeDefs where the default directory of each typeDef matches the passed in 'name' param
*
* @param name
* @returns {any[]}
*/
public getTypeDefinitionsByDirectoryName(name) {
const metadataNames = Object.keys(this.typeDefs).filter((key) => this.typeDefs[key].defaultDirectory === name);
return metadataNames.map((metadataName) => this.typeDefs[metadataName]);
}
public getTypeDefinitionByMetadataName(metadataName: string) {
let typeDef = this.typeDefs[metadataName];
if (!typeDef && metadataName.endsWith('Settings')) {
// even though there is one "Settings" in the describeMetadata response when you retrieve a setting it comes
// down as "AccountSettings", "CaseSettings", etc. so here we account for that scenario.
typeDef = this.typeDefs['Settings'];
}
if (!typeDef && metadataName.endsWith('CustomLabel')) {
typeDef = this.typeDefs['CustomLabels'];
}
return typeDef;
}
// given file extension, return type def
public getTypeDefinitionByFileName(filePath: string, useTrueExtType?: boolean) {
if (util.isNullOrUndefined(filePath)) {
return null;
}
let workspaceFilePath = filePath;
if (filePath.startsWith(this.projectPath)) {
workspaceFilePath = filePath.substring(SfdxProject.resolveProjectPathSync().length, filePath.length);
}
if (workspaceFilePath.includes(`${path.sep}aura${path.sep}`)) {
return this.typeDefs.AuraDefinitionBundle;
}
if (workspaceFilePath.includes(`${path.sep}waveTemplates${path.sep}`)) {
return this.typeDefs.WaveTemplateBundle;
}
if (workspaceFilePath.includes(`${path.sep}${this.typeDefs.ExperienceBundle.defaultDirectory}${path.sep}`)) {
return this.typeDefs.ExperienceBundle;
}
if (workspaceFilePath.includes(`${path.sep}${LWC_FOLDER_NAME}${path.sep}`)) {
return this.typeDefs.LightningComponentBundle;
}
if (workspaceFilePath.includes(`${path.sep}${this.typeDefs.CustomSite.defaultDirectory}${path.sep}`)) {
return this.typeDefs.CustomSite;
}
// CustomObject file names are special, they are all named "object-meta.xml"
if (path.basename(workspaceFilePath) === this.typeDefs.CustomObject.ext + this.metadataFileExt) {
return this.typeDefs.CustomObject;
}
const typeDefWithNonStandardExtension = this.getTypeDefinitionByFileNameWithNonStandardExtension(workspaceFilePath);
if (!_.isNil(typeDefWithNonStandardExtension)) {
return typeDefWithNonStandardExtension;
}
if (workspaceFilePath.endsWith(this.metadataFileExt)) {
workspaceFilePath = workspaceFilePath.substring(0, workspaceFilePath.indexOf(this.metadataFileExt));
}
let typeExtension = path.extname(workspaceFilePath);
if (util.isNullOrUndefined(typeExtension)) {
return null;
}
typeExtension = typeExtension.replace('.', '');
const defs = Object.values(this.typeDefs);
const defaultDirectory = path
.dirname(workspaceFilePath)
.split(path.sep)
.find((i) => !!i && this.typeDirectories.includes(i));
let typeDef: TypeDefObj;
if (defaultDirectory) {
typeDef = defs.find((def) => def.ext === typeExtension && def.defaultDirectory === defaultDirectory);
}
if (_.isNil(typeDef)) {
typeDef = this.typeDefsByExtension.get(typeExtension);
}
if (!_.isNil(typeDef)) {
if (!_.isNil(useTrueExtType) && useTrueExtType) {
return typeDef;
}
if (!_.isNil(typeDef.parent)) {
return typeDef.parent;
}
return typeDef;
}
return null;
}
// A document must be co-resident with its metadata file.
// A file from an exploded zip static resource must be within a directory that is co-resident with its metadata file.
private getTypeDefinitionByFileNameWithNonStandardExtension(fileName, isDirectoryPathElement?, typeDefsToCheck?) {
const supportedTypeDefs = [this.typeDefs.Document, this.typeDefs.StaticResource];
const candidateTypeDefs = util.isNullOrUndefined(typeDefsToCheck) ? supportedTypeDefs : typeDefsToCheck;
let typeDef = this.getTypeDefinitionByFileNameWithCoresidentMetadataFile(fileName, candidateTypeDefs, false);
if (util.isNullOrUndefined(typeDef) && candidateTypeDefs.includes(this.typeDefs.StaticResource)) {
typeDef = this.getTypeDefinitionByFileNameWithCoresidentMetadataFile(
path.dirname(fileName),
[this.typeDefs.StaticResource],
true
);
}
if (util.isNullOrUndefined(typeDef)) {
typeDef = this.getTypeDefinitionByFileNameMatchingDefaultDirectory(
fileName,
isDirectoryPathElement,
candidateTypeDefs
);
}
return typeDef;
}
private getTypeDefinitionByFileNameWithCoresidentMetadataFile(fileName, typeDefsToCheck, recurse) {
const dir = path.dirname(fileName);
if (this.isDirPathExpended(dir)) {
return null;
}
const fullName = path.basename(fileName, path.extname(fileName));
// eslint-disable-next-line @typescript-eslint/no-shadow
const typeDef = typeDefsToCheck.find((typeDef) =>
fs.existsSync(path.join(dir, `${fullName}.${typeDef.ext}${this.metadataFileExt}`))
);
if (!util.isNullOrUndefined(typeDef)) {
return typeDef;
}
return recurse ? this.getTypeDefinitionByFileNameWithCoresidentMetadataFile(dir, typeDefsToCheck, true) : null;
}
private getTypeDefinitionByFileNameMatchingDefaultDirectory(fileName, isDirectoryPathElement, typeDefsToCheck) {
const dir = path.dirname(fileName);
if (this.isDirPathExpended(dir)) {
return null;
}
if (typeDefsToCheck.includes(this.typeDefs.Document) && !isDirectoryPathElement) {
const pathElements = fileName.split(path.sep);
if (
pathElements.length >= 3 &&
pathElements[pathElements.length - 3] === this.typeDefs.Document.defaultDirectory
) {
return this.typeDefs.Document;
}
}
if (typeDefsToCheck.includes(this.typeDefs.StaticResource)) {
if (isDirectoryPathElement) {
if (path.basename(fileName) === this.typeDefs.StaticResource.defaultDirectory) {
return this.typeDefs.StaticResource;
}
}
return this.getTypeDefinitionByFileNameMatchingDefaultDirectory(dir, true, [this.typeDefs.StaticResource]);
}
return null;
}
private isDirPathExpended(dir) {
return util.isNullOrUndefined(dir) || dir === path.parse(dir).root || dir === '.';
}
public isValidAuraSuffix(suffix) {
const auraTypeDefKey = Object.keys(this.lightningDefTypes).find((key) => {
const fileSuffix = this.lightningDefTypes[key].fileSuffix;
return fileSuffix && fileSuffix === suffix;
});
return !util.isNullOrUndefined(auraTypeDefKey);
}
private isValidWaveTemplateSuffix(suffix) {
const wtTypeDefKey = Object.keys(this.waveDefTypes).find((key) => {
const fileSuffix = this.waveDefTypes[key].fileSuffix;
return fileSuffix && fileSuffix === suffix;
});
return !util.isNullOrUndefined(wtTypeDefKey);
}
public isValidLwcSuffix(suffix) {
const lwcTypeDefKey = Object.keys(this.lwcDefTypes).find((key) => {
const fileSuffix = this.lwcDefTypes[key].fileSuffix;
return fileSuffix && fileSuffix === suffix;
});
return !util.isNullOrUndefined(lwcTypeDefKey);
}
public isValidMetadataExtension(ext) {
const extWithoutPeriod = ext.replace('.', '');
const isValidMetadataExtension = !util.isNullOrUndefined(this.typeDefsByExtension.get(extWithoutPeriod));
return isValidMetadataExtension || this.isValidAuraSuffix(ext) || this.isValidLwcSuffix(ext);
}
private isValidDecompositionExtension(ext) {
const extWithoutPeriod = ext.replace('.', '');
const includeDecomposedSubtypes = true;
const typeDefKey = Object.keys(this.typeDefs).find((key) =>
_typeDefMatchesExtension(this.typeDefs[key], extWithoutPeriod, includeDecomposedSubtypes)
);
const typeDef = this.typeDefs[typeDefKey];
return !util.isNullOrUndefined(typeDefKey) && typeDef.ext.toLowerCase() !== extWithoutPeriod.toLowerCase();
}
private isValidExperienceBundleFile(sourcePath) {
const relativeFilePath = MetadataRegistry.splitOnDirName(
`${this.typeDefs.ExperienceBundle.defaultDirectory}${path.sep}`,
sourcePath
)[1];
const relativePathArray = relativeFilePath.split(path.sep);
if (relativePathArray.length == 1) {
// it should be a meta file
const META_FILE_SUFFIX = '.site';
return relativePathArray[0].endsWith(`${META_FILE_SUFFIX}${this.metadataFileExt}`);
}
// There should be 2 folders /siteName/type and the file name should have a json suffix
return relativePathArray.length == 3 && path.extname(relativePathArray[2]).replace('.', '') === 'json';
}
/**
* @param dirName - metadataObjDirName
* @param pathToSplit - /baseDir/metadataObjDirName(ie, dirName)/bundleFiles
*
* This function is like pathToSplit.split(dirName). except that it splits on the last occurance of dirName
* If there is a parent dir with the same name as metadata object dir name, then pathToSplit.split(dirName) may
* not give desired result, so getting the last occurance of the dir name to split on and splitting based on that
*
* @param pathToSplit - An array with 2 elements in it. pathToSplit[0] - baseDir and pathToSplit[1] - bundleFiles
*/
static splitOnDirName(dirName: string, pathToSplit: string): string[] {
const dirStartIndex = pathToSplit.lastIndexOf(dirName);
const dirEndIndex = dirStartIndex + dirName.length;
return [pathToSplit.substring(0, dirStartIndex - 1), pathToSplit.substring(dirEndIndex)];
}
public isValidSourceFilePath(sourcePath) {
let fileName = path.basename(sourcePath);
if (fileName.endsWith(this.metadataFileExt)) {
fileName = fileName.substring(0, fileName.indexOf(this.metadataFileExt));
}
const projectPath = SfdxProject.resolveProjectPathSync();
let workspaceSourcePath = sourcePath;
// Aura / LWC are special
if (sourcePath.startsWith(projectPath)) {
workspaceSourcePath = sourcePath.substring(SfdxProject.resolveProjectPathSync().length, sourcePath.length);
}
if (workspaceSourcePath.includes(`${path.sep}aura${path.sep}`)) {
const cmpName = path.basename(path.dirname(sourcePath));
const suffix = fileName.substring(cmpName.length, fileName.length);
return this.isValidAuraSuffix(suffix);
} else if (workspaceSourcePath.includes(`${path.sep}${LWC_FOLDER_NAME}${path.sep}`)) {
const suffix = '.' + fileName.split('.').pop();
return this.isValidLwcSuffix(suffix);
} else if (workspaceSourcePath.includes(`${path.sep}waveTemplates${path.sep}`)) {
const suffix = '.' + fileName.split('.').pop();
return this.isValidWaveTemplateSuffix(suffix);
} else if (
workspaceSourcePath.includes(`${path.sep}${this.typeDefs.ExperienceBundle.defaultDirectory}${path.sep}`)
) {
return this.isValidExperienceBundleFile(workspaceSourcePath);
} else {
const ext = path.extname(fileName);
if (!util.isNullOrUndefined(ext) && ext.length > 0) {
return (
this.isValidMetadataExtension(ext) ||
this.isValidDecompositionExtension(ext) ||
this.getTypeDefinitionByFileNameWithNonStandardExtension(workspaceSourcePath) !== null
);
} else {
return (
this.isValidMetadataExtension(fileName) ||
this.getTypeDefinitionByFileNameMatchingDefaultDirectory(workspaceSourcePath, false, [
this.typeDefs.Document,
this.typeDefs.StaticResource,
]) !== null
);
}
}
}
public isCustomName(name) {
const customNameRegex = new RegExp(/.*__.$/);
return customNameRegex.test(name);
}
}
export = MetadataRegistry; | the_stack |
import './layer_list_panel.css';
import svg_controls_alt from 'ikonate/icons/controls-alt.svg';
import svg_eye_crossed from 'ikonate/icons/eye-crossed.svg';
import svg_eye from 'ikonate/icons/eye.svg';
import {deleteLayer, LayerManager, ManagedUserLayer, TopLevelLayerListSpecification} from 'neuroglancer/layer';
import {TrackableBooleanCheckbox} from 'neuroglancer/trackable_boolean';
import {DropLayers, registerLayerBarDragLeaveHandler, registerLayerBarDropHandlers, registerLayerDragHandlers} from 'neuroglancer/ui/layer_drag_and_drop';
import {LayerNameWidget} from 'neuroglancer/ui/layer_side_panel';
import {SidePanel, SidePanelManager} from 'neuroglancer/ui/side_panel';
import {DEFAULT_SIDE_PANEL_LOCATION, SidePanelLocation, TrackableSidePanelLocation} from 'neuroglancer/ui/side_panel_location';
import {animationFrameDebounce} from 'neuroglancer/util/animation_frame_debounce';
import {RefCounted} from 'neuroglancer/util/disposable';
import {updateChildren} from 'neuroglancer/util/dom';
import {emptyToUndefined} from 'neuroglancer/util/json';
import {Trackable} from 'neuroglancer/util/trackable';
import {makeDeleteButton} from 'neuroglancer/widget/delete_button';
import {makeIcon} from 'neuroglancer/widget/icon';
import {CheckboxIcon} from '../widget/checkbox_icon';
const DEFAULT_LAYER_LIST_PANEL_LOCATION: SidePanelLocation = {
...DEFAULT_SIDE_PANEL_LOCATION,
side: 'left',
row: 0,
};
export class LayerListPanelState implements Trackable {
location = new TrackableSidePanelLocation(DEFAULT_LAYER_LIST_PANEL_LOCATION);
get changed() {
return this.location.changed;
}
restoreState(obj: unknown) {
if (obj === undefined) return;
this.location.restoreState(obj);
}
reset() {
this.location.reset();
}
toJSON() {
return emptyToUndefined(this.location.toJSON());
}
}
class LayerVisibilityWidget extends RefCounted {
element = document.createElement('div');
constructor(public layer: ManagedUserLayer) {
super();
const {element} = this;
const hideIcon = makeIcon({
svg: svg_eye,
title: 'Hide layer',
onClick: () => {
this.layer.setVisible(false);
}
});
const showIcon = makeIcon({
svg: svg_eye_crossed,
title: 'Show layer',
onClick: () => {
this.layer.setVisible(true);
}
});
element.appendChild(showIcon);
element.appendChild(hideIcon);
const updateView = () => {
const visible = this.layer.visible;
hideIcon.style.display = visible ? '' : 'none';
showIcon.style.display = !visible ? '' : 'none';
};
updateView();
this.registerDisposer(layer.layerChanged.add(updateView));
}
}
function makeSelectedLayerSidePanelCheckboxIcon(layer: ManagedUserLayer) {
const {selectedLayer} = layer.manager.root;
const icon = new CheckboxIcon(
{
get value() {
return selectedLayer.layer === layer && selectedLayer.visible;
},
set value(value: boolean) {
if (value) {
selectedLayer.layer = layer;
selectedLayer.visible = true;
} else {
selectedLayer.visible = false;
}
},
changed: selectedLayer.changed,
},
{
backgroundScheme: 'dark',
enableTitle: 'Show layer side panel',
disableTitle: 'Hide layer side panel',
svg: svg_controls_alt,
});
icon.element.classList.add('neuroglancer-layer-list-panel-item-controls');
return icon;
}
class LayerListItem extends RefCounted {
element = document.createElement('div');
numberElement = document.createElement('div');
generation = -1;
constructor(public panel: LayerListPanel, public layer: ManagedUserLayer) {
super();
const {element, numberElement} = this;
element.classList.add('neuroglancer-layer-list-panel-item');
numberElement.classList.add('neuroglancer-layer-list-panel-item-number');
element.appendChild(
this
.registerDisposer(new TrackableBooleanCheckbox(
{
get value() {
return !layer.archived;
},
set value(value: boolean) {
layer.setArchived(!value);
},
changed: layer.layerChanged,
},
{
enableTitle: 'Archive layer (disable and remove from layer groups)',
disableTitle: 'Unarchive layer (enable and add to all layer groups)'
}))
.element);
element.appendChild(numberElement);
element.appendChild(this.registerDisposer(new LayerVisibilityWidget(layer)).element);
element.appendChild(this.registerDisposer(new LayerNameWidget(layer)).element);
element.appendChild(
this.registerDisposer(makeSelectedLayerSidePanelCheckboxIcon(layer)).element);
const deleteButton = makeDeleteButton({
title: 'Delete layer',
onClick: () => {
deleteLayer(this.layer);
}
});
deleteButton.classList.add('neuroglancer-layer-list-panel-item-delete');
element.appendChild(deleteButton);
registerLayerDragHandlers(
panel, element, layer, {isLayerListPanel: true, getLayoutSpec: () => undefined});
registerLayerBarDropHandlers(panel, element, layer, /*allowArchived=*/ true);
element.addEventListener('click', (event: MouseEvent) => {
if (event.ctrlKey) {
panel.selectedLayer.toggle(layer);
event.preventDefault();
} else if (event.altKey) {
layer.pickEnabled = !layer.pickEnabled;
event.preventDefault();
}
});
element.addEventListener('contextmenu', (event: MouseEvent) => {
panel.selectedLayer.toggle(layer);
event.stopPropagation();
event.preventDefault();
});
}
}
export class LayerListPanel extends SidePanel {
private items = new Map<ManagedUserLayer, LayerListItem>();
itemContainer = document.createElement('div');
layerDropZone = document.createElement('div');
titleElement: HTMLElement;
get layerManager() {
return this.manager.layerManager;
}
get selectedLayer() {
return this.manager.selectedLayer;
}
dropLayers: DropLayers|undefined;
dragEnterCount = 0;
private generation = -1;
constructor(
sidePanelManager: SidePanelManager, public manager: TopLevelLayerListSpecification,
public state: LayerListPanelState) {
super(sidePanelManager, state.location);
const {itemContainer, layerDropZone} = this;
const {titleElement} = this.addTitleBar({title: ''});
this.titleElement = titleElement!;
itemContainer.classList.add('neuroglancer-layer-list-panel-items');
this.addBody(itemContainer);
layerDropZone.style.flex = '1';
const debouncedUpdateView =
this.registerCancellable(animationFrameDebounce(() => this.render()));
this.visibility.changed.add(debouncedUpdateView);
this.registerDisposer(this.layerManager.layersChanged.add(debouncedUpdateView));
this.registerDisposer(this.selectedLayer.changed.add(debouncedUpdateView));
registerLayerBarDragLeaveHandler(this);
registerLayerBarDropHandlers(this, layerDropZone, undefined, /*allowArchived=*/ true);
this.render();
}
render() {
const self = this;
const selectedLayer = this.selectedLayer.layer;
const generation = ++this.generation;
let numVisible = 0;
let numHidden = 0;
let numArchived = 0;
this.layerManager.updateNonArchivedLayerIndices();
function* getItems() {
const {items} = self;
let numNonArchivedLayers = 0;
for (const layer of self.layerManager.managedLayers) {
if (!layer.archived) ++numNonArchivedLayers;
}
const numberElementWidth = `${(numNonArchivedLayers + 1).toString().length}ch`;
for (const layer of self.layerManager.managedLayers) {
if (layer.visible) {
++numVisible;
} else if (!layer.archived) {
++numHidden;
} else {
++numArchived;
}
let item = items.get(layer);
if (item === undefined) {
item = self.registerDisposer(new LayerListItem(self, layer));
items.set(layer, item);
item.generation = generation;
} else {
item.generation = generation;
}
const {nonArchivedLayerIndex} = layer;
item.numberElement.style.width = numberElementWidth;
if (nonArchivedLayerIndex === -1) {
item.numberElement.style.visibility = 'hidden';
} else {
item.numberElement.style.visibility = '';
item.numberElement.textContent = `${nonArchivedLayerIndex+1}`;
}
item.element.dataset.selected = (layer === selectedLayer).toString();
item.element.dataset.archived = (layer.archived).toString();
yield item.element;
}
for (const [userLayer, item] of items) {
if (generation !== item.generation) {
items.delete(userLayer);
self.unregisterDisposer(item);
item.dispose();
}
}
yield self.layerDropZone;
}
updateChildren(this.itemContainer, getItems());
let title = 'Layers';
if (numVisible || numHidden || numArchived) {
title += ' (';
let sep = '';
if (numVisible + numHidden) {
title += `${numVisible}/${numHidden + numVisible} visible`;
sep = ', ';
}
if (numArchived) {
title += `${sep}${numArchived} archived`;
}
title += ')';
}
this.titleElement.textContent = title;
}
}
export class LayerArchiveCountWidget extends RefCounted {
element = document.createElement('div');
constructor(public layerManager: LayerManager) {
super();
const debouncedRender = this.registerCancellable(animationFrameDebounce(() => this.render()));
this.registerDisposer(layerManager.layersChanged.add(debouncedRender));
this.render();
}
private render() {
let numArchived = 0;
const {managedLayers} = this.layerManager;
for (const layer of managedLayers) {
if (layer.archived) ++numArchived;
}
const {element} = this;
if (numArchived !== 0) {
const numLayers = managedLayers.length;
element.textContent = `${numLayers - numArchived}/${numLayers}`;
} else {
element.textContent = '';
}
}
} | the_stack |
import { apply, chain, mergeWith, move, Rule, Tree, url, MergeStrategy, noop, SchematicsException, externalSchematic } from '@angular-devkit/schematics';
import {
applyAndLog, addImportStatement, addToNgModule, createOrOverwriteFile, removeFromNgModule,
addDependencyInjection, getNgToolkitInfo, updateNgToolkitInfo, addDependencyToPackageJson, updateCode
} from '@ng-toolkit/_utils';
import { getFileContent } from '@schematics/angular/utility/test';
import { getWorkspace } from '@schematics/angular/utility/config';
import { NodeDependencyType } from '@schematics/angular/utility/dependencies';
import { BrowserBuilderOptions, BrowserBuilderTarget, WorkspaceSchema, WorkspaceTargets, TestBuilderTarget } from '@schematics/angular/utility/workspace-models';
import { IToolkitUniversalSchema, IUniversalSchema } from './schema';
import outdent from 'outdent';
import bugsnag from '@bugsnag/js';
const bugsnagClient = bugsnag('0b326fddc255310e516875c9874fed91');
export default function addUniversal(options: IToolkitUniversalSchema): Rule {
if (!options.clientProject) {
options.clientProject = options.project;
}
// Remove extra properties to avoid schema errors while running @nguniversal/express-engine schematic.
const { disableBugsnag, http, directory, project, ...optionsReduced } = options;
const expressOptions: IUniversalSchema = optionsReduced;
// Register bugsnag in order to catch and notify any rule error.
bugsnagClient.config.beforeSend = (report: any) => {
report.metaData = {
subsystem: {
package: 'universal',
options: options
}
}
}
const templateSource = apply(url('./files'), [
move(options.directory)
]);
const rules: Rule[] = [];
rules.push(removePreviousServerlessFiles(options));
rules.push(mergeWith(templateSource, MergeStrategy.Overwrite));
rules.push(applyExpressEngine(options, expressOptions));
rules.push(applyPackageJsonScripts(options));
rules.push(enhanceServerModule(options));
rules.push(renameAndEnhanceBrowserModule(options));
rules.push(updateWebpackConfig());
rules.push(addWrappers(options));
rules.push(applyOtherNgToolkitSchematics(options));
rules.push(addPrerender(options));
rules.push(editTSConfigFile(options));
rules.push(addRobotFile(options));
if (!options.disableBugsnag) {
return applyAndLog(chain(rules), bugsnagClient);
} else {
return chain(rules);
}
}
function getSourceRoot(tree: Tree, options: IToolkitUniversalSchema): string {
const workspace = getWorkspace(tree);
return `${workspace.projects[options.clientProject].sourceRoot}`;
}
function removePreviousServerlessFiles(options: IToolkitUniversalSchema): Rule {
return (tree: Tree) => {
const packageJsonSource = JSON.parse(getFileContent(tree, `package.json`));
if (packageJsonSource.dependencies['@ng-toolkit/serverless']) {
const ngToolkitSettings = getNgToolkitInfo(tree, options);
tree.delete(`./local.${ngToolkitSettings.serverless.lambdaTS ? 'ts' : 'js'}`);
tree.delete(`./server.ts`);
tree.delete(`./webpack.server.config.js`);
}
return tree;
}
}
function applyExpressEngine(options: IToolkitUniversalSchema, expressOptions: IUniversalSchema): Rule {
return (tree: Tree) => {
let hasUniversalBuild = false;
const workspace: WorkspaceSchema = getWorkspace(tree);
const architect: WorkspaceTargets | undefined = workspace.projects[options.clientProject].architect;
if (architect) {
for (let builder in architect) {
if (architect[builder].builder === '@angular-devkit/build-angular:server') {
hasUniversalBuild = true;
}
}
}
if (!hasUniversalBuild) {
return externalSchematic('@nguniversal/express-engine', 'ng-add', expressOptions);
} else {
return noop();
}
}
}
function applyPackageJsonScripts(options: IToolkitUniversalSchema) {
return (tree: Tree) => {
const serverPort = options.serverPort ? options.serverPort.toString() : '4000';
tree.overwrite(`local.js`, getFileContent(tree, `local.js`).replace(/__distFolder__/g, 'dist/server').replace(/__serverPort__/g, serverPort));
tree.overwrite(`${options.serverFileName}`, getFileContent(tree, `${options.serverFileName}`).replace(/\/\/ Start up the Node server.*/gs, '').replace('const app = express();', 'export const app = express();'));
const pkgPath = `/package.json`;
const buffer = tree.read(pkgPath);
if (buffer === null) {
throw new SchematicsException('Could not find package.json');
}
const pkg = JSON.parse(buffer.toString());
pkg.scripts['server'] = 'node local.js';
pkg.scripts['build:prod'] = 'npm run build:ssr';
pkg.scripts['serve:ssr'] = 'node local.js';
tree.overwrite(pkgPath, JSON.stringify(pkg, null, 2));
addDependencyToPackageJson(tree, options, {
type: NodeDependencyType.Default,
name: '@nguniversal/common',
version: '8.1.0'
});
return tree;
}
}
function enhanceServerModule(options: IToolkitUniversalSchema): Rule {
return (tree: Tree) => {
const serverModulePath = `/${getSourceRoot(tree, options)}/${options.appDir}/${options.rootModuleFileName}`;
addImportStatement(tree, serverModulePath, 'ServerTransferStateModule', '@angular/platform-server');
addToNgModule(tree, serverModulePath, 'imports', 'ServerTransferStateModule');
return tree;
};
}
function renameAndEnhanceBrowserModule(options: IToolkitUniversalSchema): Rule {
return (tree: Tree) => {
const browserModulePath = `/${getSourceRoot(tree, options)}/${options.appDir}/${options.appDir}.browser.module.ts`;
const modulePath = `/${getSourceRoot(tree, options)}/${options.appDir}/${options.appDir}.module.ts`;
const mainPath = `/${getSourceRoot(tree, options)}/main.ts`;
// Create browser entry module
createOrOverwriteFile(tree, browserModulePath, getFileContent(tree, modulePath).replace('AppModule', 'AppBrowserModule'));
//c Change app.module.ts
addImportStatement(tree, modulePath, 'CommonModule', '@angular/common');
addToNgModule(tree, modulePath, 'imports', 'CommonModule');
if (options.http) {
addImportStatement(tree, modulePath, 'TransferHttpCacheModule', '@nguniversal/common');
addImportStatement(tree, modulePath, 'HttpClientModule', '@angular/common/http');
addToNgModule(tree, modulePath, 'imports', 'TransferHttpCacheModule');
addToNgModule(tree, modulePath, 'imports', 'HttpClientModule');
}
// Change app.browser.module.ts
removeFromNgModule(tree, browserModulePath, 'imports', `BrowserModule.withServerTransition({ appId: '${options.appId}' })`);
removeFromNgModule(tree, browserModulePath, 'declarations');
addImportStatement(tree, browserModulePath, 'AppModule', './app.module');
addToNgModule(tree, browserModulePath, 'imports', 'AppModule');
addImportStatement(tree, browserModulePath, 'BrowserTransferStateModule', '@angular/platform-browser');
addToNgModule(tree, browserModulePath, 'imports', 'BrowserTransferStateModule');
// Change entry in main.ts
addImportStatement(tree, mainPath, 'AppBrowserModule', `./${options.appDir}/app.browser.module`)
createOrOverwriteFile(tree, mainPath, getFileContent(tree, mainPath).replace(
'.bootstrapModule(AppModule)',
'.bootstrapModule(AppBrowserModule)'
)
);
return tree;
}
}
function updateWebpackConfig(): Rule {
return (tree: Tree) => {
const webpackConfig = getFileContent(tree, `./webpack.server.config.js`);
let newWebpackConfig = webpackConfig.replace('output: {', `output: {\n\t\tlibraryTarget: 'commonjs2',`);
// For some reason, this line was added on 8.1.0 of `@nguniversal/express-engine` package.
// Commenting this line will let our serverless lambda to properly run.
// const ngToolkitSettings = getNgToolkitInfo(tree, options);
// if (ngToolkitSettings.serverless) {}
const externalsRegex: RegExp = new RegExp('externals: {((.|\n)*?)}');
newWebpackConfig = newWebpackConfig.replace(
externalsRegex,
`externals: {\n\t\t\// './dist/server/main': 'require("./server/main")'\n\t}`
);
createOrOverwriteFile(tree, `./webpack.server.config.js`, newWebpackConfig);
return tree;
}
}
function addWrappers(options: IToolkitUniversalSchema): Rule {
return (tree: Tree) => {
const modulePath = `/${getSourceRoot(tree, options)}/${options.appDir}/${options.appDir}.module.ts`;
addImportStatement(tree, modulePath, 'NgtUniversalModule', '@ng-toolkit/universal');
addToNgModule(tree, modulePath, 'imports', 'NgtUniversalModule');
// search for 'window' occurences and replace them with injected Window instance
tree.getDir(`/${getSourceRoot(tree, options)}`).visit(visitor => {
if (visitor.endsWith('.ts')) {
let fileContent = getFileContent(tree, visitor);
if (fileContent.match(/class.*{[\s\S]*?((?:[()'"`\s])localStorage)/)) {
addDependencyInjection(tree, visitor, 'localStorage', 'any', '@ng-toolkit/universal', 'LOCAL_STORAGE');
updateCode(tree, visitor, 'localStorage');
fileContent = getFileContent(tree, visitor);
}
if (fileContent.match(/class.*{[\s\S]*?((?:[()'"`\s])window)/)) {
addDependencyInjection(tree, visitor, 'window', 'Window', '@ng-toolkit/universal', 'WINDOW');
updateCode(tree, visitor, 'window');
}
// if (fileContent.match(/class.*{[\s\S]*?((?:[()'"`\s])document)/)) {
// addDependencyInjection(tree, visitor, 'document', 'Document', '@ng-toolkit/universal', 'NGT_DOCUMENT');
// updateCode(tree, visitor, 'document');
// }
}
});
return tree;
}
}
/**
* Applies other @ng-toolkit schematics if installed.
* @param options the @ng-toolkit/universal schema
*/
function applyOtherNgToolkitSchematics(options: IToolkitUniversalSchema): Rule {
return (tree: Tree) => {
const ngToolkitSettings = getNgToolkitInfo(tree, options);
ngToolkitSettings.universal = options;
updateNgToolkitInfo(tree, ngToolkitSettings, options);
let externals: Rule[] = [];
// Run ng-add of @ng-toolkit/serverless schematic if serverless exists.
if (ngToolkitSettings.serverless) {
ngToolkitSettings.serverless.directory = options.directory;
ngToolkitSettings.serverless.skipInstall = true;
ngToolkitSettings.serverless.clientProject = options.clientProject;
externals.push(externalSchematic('@ng-toolkit/serverless', 'ng-add', ngToolkitSettings.serverless));
} else if (tree.exists(`${options.directory}/.firebaserc`)) {
ngToolkitSettings.serverless = {};
ngToolkitSettings.serverless.directory = options.directory;
ngToolkitSettings.serverless.skipInstall = true;
ngToolkitSettings.serverless.provider = 'firebase';
ngToolkitSettings.serverless.clientProject = options.clientProject;
externals.push(externalSchematic('@ng-toolkit/serverless', 'ng-add', ngToolkitSettings.serverless));
}
const workspace = getWorkspace(tree);
const projectArchitect = workspace.projects[options.clientProject].architect;
// Run ng-add of @ng-toolkit/pwa schematic if pwa exists.
if (
projectArchitect &&
projectArchitect.build &&
projectArchitect.build.configurations &&
projectArchitect.build.configurations.production &&
(<Partial<BrowserBuilderOptions>>projectArchitect.build.configurations.production).serviceWorker != undefined) {
if (!ngToolkitSettings.pwa) {
ngToolkitSettings.pwa = {};
}
ngToolkitSettings.pwa.directory = options.directory;
ngToolkitSettings.pwa.skipInstall = true;
ngToolkitSettings.pwa.clientProject = options.clientProject;
externals.push(externalSchematic('@ng-toolkit/pwa', 'ng-add', ngToolkitSettings.pwa));
}
if (externals.length > 0) {
return chain(externals);
}
return tree;
}
}
function addPrerender(options: IToolkitUniversalSchema): Rule {
return (tree: Tree) => {
// Add dependencies
addDependencyToPackageJson(tree, options, {
type: NodeDependencyType.Default,
name: 'domino',
version: '^2.1.4'
});
// Add scripts
const pkgPath = `package.json`;
const buffer = tree.read(pkgPath);
if (buffer === null) {
throw new SchematicsException('Could not find package.json at addPrerender function');
}
const pkg = JSON.parse(buffer.toString());
pkg.scripts['start:prerender'] = "npm run build:prerender & npm run serve:prerender";
pkg.scripts['serve:prerender'] = 'node static.js';
pkg.scripts['build:prerender'] = 'npm run build:prod && node dist/prerender.js';
tree.overwrite(pkgPath, JSON.stringify(pkg, null, 2));
// Add entry in webpack configuration
const webpackConfig = getFileContent(tree, `./webpack.server.config.js`);
createOrOverwriteFile(tree, `./webpack.server.config.js`, webpackConfig.replace(
`server: './server.ts'`,
`server: './server.ts',\n\t\tprerender: './prerender.ts'`
)
);
return tree;
}
}
/**
* Change the default `tsconfig.json` file to enable default imports for some JS packages.
* Also set the module code generation to CommonJS to enable webpack typescript compilation and other stuff.
* @param options serverless options schema
*/
function editTSConfigFile(options: IToolkitUniversalSchema): Rule {
return tree => {
const tsConfig: any = JSON.parse(getFileContent(tree, `${options.directory}/tsconfig.json`));
tsConfig.compilerOptions['esModuleInterop'] = true;
tsConfig.compilerOptions['allowSyntheticDefaultImports'] = true;
tsConfig.compilerOptions['module'] = 'commonjs';
tree.overwrite(`${options.directory}/tsconfig.json`, JSON.stringify(tsConfig, null, 2));
return tree;
}
}
function addRobotFile(options: IToolkitUniversalSchema): Rule {
return (tree: Tree) => {
// Create robots.txt file
const robotFileContent = outdent`
# Allow all URLs (see http://www.robotstxt.org/robotstxt.html)
User-agent: *
Allow: /
`
createOrOverwriteFile(tree, `/${getSourceRoot(tree, options)}/robots.txt`, robotFileContent);
// Load and edit angular.json file content to include the robots.txt file
const workspace: WorkspaceSchema = getWorkspace(tree);
const projectArchitect: WorkspaceTargets | undefined = workspace.projects[options.clientProject].architect;
if (projectArchitect) {
const browserBuilder: BrowserBuilderTarget | undefined = projectArchitect.build;
const testBuilder: TestBuilderTarget | undefined = projectArchitect.test;
if (browserBuilder && browserBuilder.options.assets) {
if (browserBuilder.options.assets.every(x => typeof x === 'string')) {
browserBuilder.options.assets.push(`${getSourceRoot(tree, options)}/robots.txt`);
projectArchitect.build = browserBuilder;
}
}
if (testBuilder && testBuilder.options.assets) {
if (testBuilder.options.assets.every(x => typeof x === 'string')) {
testBuilder.options.assets.push(`${getSourceRoot(tree, options)}/robots.txt`);
projectArchitect.test = testBuilder;
}
}
}
workspace.projects[options.clientProject].architect = projectArchitect;
createOrOverwriteFile(tree, `${options.directory}/angular.json`, JSON.stringify(workspace, null, 2));
return tree;
}
} | the_stack |
import { IAddress, IMessage, Message, Prompts, Session, UniversalBot } from 'botbuilder';
import * as chai from 'chai';
import * as chaiAsPromised from 'chai-as-promised';
import { BotTester } from './../../../src/BotTester';
import { TestConnector } from './../../../src/TestConnector';
import { getAdaptiveCard, getAdaptiveCardAttachment, getAdaptiveCardMessage } from './../../adaptiveCardProvider';
chai.use(chaiAsPromised);
const expect = chai.expect;
const connector = new TestConnector();
// lines with //# should be converted to headers for markdown docs
describe('BotTester', () => {
let bot;
beforeEach(() => {
bot = new UniversalBot(connector);
});
// ... tests live here!
//```
//# Test for single response
//```javascript
it('can handle a single response', () => {
bot.dialog('/', (session) => {
session.send('hello!');
});
const botTester = new BotTester(bot)
.sendMessageToBot('Hola!', 'hello!');
return botTester.runTest();
});
//```
//# Test for multiple responses
//```javascript
it('can handle multiple responses', () => {
bot.dialog('/', (session) => {
session.send('hello!');
session.send('how are you doing?');
});
new BotTester(bot)
.sendMessageToBot('Hola!', 'hello!', 'how are you doing?')
.runTest();
});
//```
//# Test for random response arrays
//```javascript
// re-run the test multiple times to guarantee that multiple colors are returned
let randomResponseRunCounter = 5;
const randomColors = ['red', 'green', 'blue', 'grey', 'gray', 'purple', 'magenta', 'cheese', 'orange', 'hazelnut'];
while (randomResponseRunCounter--) {
it('Can handle random responses', () => {
bot.dialog('/', (session) => {
session.send(randomColors);
});
return new BotTester(bot)
.sendMessageToBot('tell me a color!', randomColors)
.runTest();
});
}
//```
//# Test with prompts
//```javascript
it('can test prompts', () => {
bot.dialog('/', [(session) => {
new Prompts.text(session, 'Hi there! Tell me something you like');
}, (session, results) => {
session.send(`${results.response} is pretty cool.`);
new Prompts.text(session, 'Why do you like it?');
}, (session) => session.send('Interesting. Well, that\'s all I have for now')]);
return new BotTester(bot)
.sendMessageToBot('Hola!', 'Hi there! Tell me something you like')
.sendMessageToBot('The sky', 'The sky is pretty cool.', 'Why do you like it?')
.sendMessageToBot('It\'s blue', 'Interesting. Well, that\'s all I have for now')
.runTest();
});
//```
//# Test Adaptive Cards
//``` javascript
it('can correctly check against adaptive cards', () => {
bot.dialog('/', (session) => {
session.send(getAdaptiveCardMessage());
});
return new BotTester(bot)
.sendMessageToBot('anything', getAdaptiveCardMessage())
.runTest();
});
//```
//# Inspect session
//```javascript
it('can inspect session state', () => {
bot.dialog('/', [(session) => {
new Prompts.text(session, 'What would you like to set data to?');
}, (session, results) => {
session.userData = { data: results.response };
session.save();
}]);
return new BotTester(bot)
.sendMessageToBot('Start this thing!', 'What would you like to set data to?')
.sendMessageToBotAndExpectSaveWithNoResponse('This is data!')
.checkSession((session) => {
expect(session.userData).not.to.be.null;
expect(session.userData.data).to.be.equal('This is data!');
})
.runTest();
});
//```
//# Test custom messages
//```javascript
it('can handle custom messages in response', () => {
const customMessage: { someField?: {} } & IMessage = new Message()
.text('this is text')
.toMessage();
customMessage.someField = {
a: 1
};
customMessage.type = 'newType';
const matchingCustomMessage: { someField?: {} } & IMessage = new Message()
.toMessage();
matchingCustomMessage.text = 'this is text';
matchingCustomMessage.type = 'newType';
bot.dialog('/', (session: Session) => {
session.send(customMessage);
});
return new BotTester(bot)
.sendMessageToBot('anything', customMessage)
.sendMessageToBot('anything', matchingCustomMessage)
.runTest();
});
//```
//# Address/multiuser cases
//```javascript
describe('Address/multi user', () => {
const defaultAddress = { channelId: 'console',
user: { id: 'customUser1', name: 'A' },
bot: { id: 'customBot1', name: 'Bot1' },
conversation: { id: 'customUser1Conversation' }
};
const user2Address = { channelId: 'console',
user: { id: 'user2', name: 'B' },
bot: { id: 'bot', name: 'Bot' },
conversation: { id: 'user2Conversation' }
};
beforeEach(() => {
bot.dialog('/', (session) => session.send(session.message.address.user.name));
});
//```
//## Can check addressess, including partial addresses
//```javascript
it('can ensure proper address being used for routing. Includes partial address', () => {
const askForUser1Name = new Message()
.text('What is my name?')
.address(defaultAddress)
.toMessage();
const expectedAddressInMessage = new Message()
.address(defaultAddress)
.toMessage();
const addr = {
user: {
id: defaultAddress.user.id
}
} as IAddress;
// partial addresses work as well (i.e. if you only want to check one field such as userId)
const expectedPartialAddress = new Message()
.address(addr)
.toMessage();
return new BotTester(bot)
.sendMessageToBot(askForUser1Name, expectedAddressInMessage)
.sendMessageToBot(askForUser1Name, expectedPartialAddress)
.runTest();
});
//```
//## Can have a default address assigned to the bot
//```javascript
// the bot can have a default address that messages are sent to. If needed, the default address can be ignored by sending an IMessage
it('Can have a default address assigned to it and communicate to multiple users', () => {
const askForUser1Name = new Message()
.text('What is my name?')
.address(defaultAddress)
.toMessage();
const askForUser2Name = new Message()
.text('What is my name?')
.address(user2Address)
.toMessage();
const user1ExpectedResponse = new Message()
.text('A')
.address(defaultAddress)
.toMessage();
const user2ExpectedResponse = new Message()
.text('B')
.address(user2Address)
.toMessage();
// when testing for an address that is not the default for the bot, the address must be passed in
return new BotTester(bot, { defaultAddress })
// because user 1 is the default address, the expected responses can be a string
.sendMessageToBot(askForUser1Name, 'A')
.sendMessageToBot('What is my name?', user1ExpectedResponse)
.sendMessageToBot(askForUser1Name, user1ExpectedResponse)
.sendMessageToBot(askForUser2Name, user2ExpectedResponse)
.runTest();
});
});
//```
//# Can test batch responses
//```javascript
it('can handle batch responses', () => {
const CUSTOMER_ADDRESS: IAddress = { channelId: 'console',
user: { id: 'userId1', name: 'user1' },
bot: { id: 'bot', name: 'Bot' },
conversation: { id: 'user1Conversation' }
};
const msg1 = new Message()
.address(CUSTOMER_ADDRESS)
.text('hello')
.toMessage();
const msg2 = new Message()
.address(CUSTOMER_ADDRESS)
.text('there')
.toMessage();
bot.dialog('/', (session: Session) => {
bot.send([msg1, msg2]);
});
return new BotTester(bot, { defaultAddress: CUSTOMER_ADDRESS })
.sendMessageToBot('anything', 'hello', 'there')
.runTest();
});
//```
//# Can test using regex
//```javascript
it('accepts RegExp', () => {
const numberRegex = /^\d+/;
bot.dialog('/', (session) => {
// send only numbers for this test case ....
session.send(session.message.text);
});
return new BotTester(bot)
.sendMessageToBot('1', numberRegex)
.sendMessageToBot('3156', numberRegex)
.sendMessageToBot('8675309', numberRegex)
.runTest();
});
//```
//# variable # args can have mixed type
//```javascript
it('rest params can have mixed type', () => {
const numberRegex = /^\d+/;
bot.dialog('/', (session) => {
session.send(session.message.text);
session.send(session.message.text);
});
return new BotTester(bot)
.sendMessageToBot('123', numberRegex, '123')
.runTest();
});
//```
//# Can perform arbitrary work between test steps
//```javascript
it('can do arbitrary work between test steps', () => {
let responseString = 'goodbye';
bot.dialog('/', (session) => {
// send only numbers for this test case ....
session.send(responseString);
});
return new BotTester(bot)
.sendMessageToBot('you say', 'goodbye')
.then(() => responseString = 'hello')
.sendMessageToBot('and i say', 'hello')
.runTest();
});
//```
//# Can wait between test steps
//```javascript
it('can wait between test steps', () => {
const delay = 1000;
let beforeDelayTime;
let afterDelayTime;
bot.dialog('/', (session) => {
// send only numbers for this test case ....
if (afterDelayTime - beforeDelayTime >= delay) {
session.send('i waited some time');
}
});
return new BotTester(bot)
.then(() => beforeDelayTime = Date.now())
.wait(delay)
.then(() => afterDelayTime = Date.now())
.sendMessageToBot('have you waited ?', 'i waited some time')
.runTest();
});
//```
//# can check messages while ignoring order
//``` javascript
it('can accept messages without expectations for order', () => {
bot.dialog('/', (session) => {
session.send('hi');
session.send('there');
session.send('how are you?');
});
return new BotTester(bot)
.sendMessageToBotIgnoringResponseOrder('anything', 'how are you?', 'hi', 'there')
.runTest();
});
//```
//# can apply one or more message filters in the BotTester options for messages to ignore
//``` javascript
it('can apply one or more message filters in the BotTester options for messages to ignore', () => {
bot.dialog('/', (session) => {
session.send('hello');
session.send('how');
session.send('are');
session.send('you?');
});
const ignoreHowMessage = (message) => !message.text.includes('how');
const ignoreAreMessage = (message) => !message.text.includes('are');
return new BotTester(bot, { messageFilters: [ignoreHowMessage, ignoreAreMessage]})
.sendMessageToBot('intro', 'hello', 'you?')
.runTest();
});
//```
//# can modify BotTester options
//``` javascript
describe('can modifiy options in line in builder chain', () => {
it('add a message filter', () => {
bot.dialog('/', (session) => {
session.send('hello');
session.send('there');
session.send('green');
});
return new BotTester(bot)
.addMessageFilter((msg) => !msg.text.includes('hello'))
.addMessageFilter((msg) => !msg.text.includes('there'))
.sendMessageToBot('hey', 'green')
.runTest();
});
it('change timeout time', (done) => {
const timeout = 750;
bot.dialog('/', (session) => {
setTimeout(() => session.send('hi there'), timeout * 2 );
});
expect(new BotTester(bot)
.setTimeout(timeout)
.sendMessageToBot('hey', 'hi there')
.runTest()
).to.be.rejected.notify(done);
});
it('can ignore typing events', () => {
bot.dialog('/', (session) => {
session.send('hello');
session.sendTyping();
session.send('goodbye');
});
return new BotTester(bot)
.ignoreTypingEvent()
.sendMessageToBot('hey', 'hello', 'goodbye')
.runTest();
});
});
//```
describe('Cases not for docs', () => {
it('can handle undefined expectedResponses', () => {
bot.dialog('/', (session: Session) => {
session.send('hello');
});
return new BotTester(bot)
.sendMessageToBot('this IS another thing')
// send second message to make sure the tests can continue as expected
.sendMessageToBot('this could be anything!', 'hello')
.runTest();
});
it('can ensure adaptive cards are present, regardless of order', () => {
bot.dialog('/', (session: Session) => {
session.send(getAdaptiveCardMessage());
});
const matchingCard = getAdaptiveCard();
const nonMatchingCard = getAdaptiveCard();
nonMatchingCard.actions = [{title: 'this is not the correct title', type: 'this is no the correct type'}];
const message1 = getAdaptiveCardMessage(nonMatchingCard);
const message2 = getAdaptiveCardMessage(matchingCard);
message1.attachments.push(getAdaptiveCardAttachment(matchingCard));
message2.attachments.push(getAdaptiveCardAttachment(nonMatchingCard));
return new BotTester(bot)
.sendMessageToBot('anything', message1)
.sendMessageToBot('anything', message2)
.runTest();
});
});
}); | the_stack |
import * as Generator from "./generators";
import * as Constant from "./utilities";
import * as Iterator from "./iterators";
import {Enumerable, OrderedEnumerable, IEnumerable, IEnumerator, IGrouping} from "./enumerable";
//-----------------------------------------------------------------------------
// Implementation of EnumerableConstructor interface
//-----------------------------------------------------------------------------
/**
* Converts any Iterable<T> object into LINQ-able object
* @param TSource An Array, Map, Set, String or other Iterable object.
*/
function getEnumerable<T>(TSource: Iterable<T> | IEnumerable<T>):
Enumerable<T> {
return new EnumerableImpl<T>(TSource);
}
/**
* Generates <count> of <T> elements starting with <start>. T is any
* type which could be cast to number: number, enum, etc.
* @param start First value in sequence.
* @param count Number of elements to iteratel.
* @example
* var sum = Range(0, 7).Sum();
*/
function getRange(start: number, count: number): Enumerable<number> {
return new EnumerableImpl<number>(undefined, Generator.Range, [start, count]);
}
/**
* Repeat element <start> of type T <count> of times.
* @param start First value in sequence.
* @param count Number of elements to iteratel.
* @example
* var sum = Repeat("v", 7);
*/
function getRepeat<T>(value: T, count: number): Enumerable<T> {
return new EnumerableImpl<T>(undefined, Generator.Repeat, [value, count]);
}
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
export {
getEnumerable as default,
getEnumerable as AsEnumerable,
getEnumerable as asEnumerable,
getEnumerable as From,
getEnumerable as from,
getRange as range,
getRange as Range,
getRepeat as repeat,
getRepeat as Repeat,
Enumerable,
IEnumerable,
IEnumerator
};
//-----------------------------------------------------------------------------
// Enumerable Implementation
//-----------------------------------------------------------------------------
class EnumerableImpl<T> implements Enumerable<T>, Iterable<T>, IEnumerable<T> {
//-------------------------------------------------------------------------
// Fields
//-------------------------------------------------------------------------
protected _target: Iterable<any>;
protected _factory: Function;
protected _factoryArg: any;
constructor(target: Iterable<any> | IEnumerable<any>,
factory?: Function,
arg?: any) {
this._target = <Iterable<any>>target;
this._factory = factory;
this._factoryArg = arg;
// JavaScript naming convention
(this as any)['aggregate'] = this.Aggregate;
(this as any)['all'] = this.All;
(this as any)['any'] = this.Any;
(this as any)['average'] = this.Average;
(this as any)['chunkBy'] = this.ChunkBy;
(this as any)['contains'] = this.Contains;
(this as any)['count'] = this.Count;
(this as any)['max'] = this.Max;
(this as any)['min'] = this.Min;
(this as any)['elementAt'] = this.ElementAt;
(this as any)['elementAtOrDefault'] = this.ElementAtOrDefault;
(this as any)['first'] = this.First;
(this as any)['firstOrDefault'] = this.FirstOrDefault;
(this as any)['last'] = this.Last;
(this as any)['lastOrDefault'] = this.LastOrDefault;
(this as any)['sequenceEqual'] = this.SequenceEqual;
(this as any)['single'] = this.Single;
(this as any)['singleOrDefault'] = this.SingleOrDefault;
(this as any)['sum'] = this.Sum;
(this as any)['toArray'] = this.ToArray;
(this as any)['toMap'] = this.ToMap;
(this as any)['toDictionary'] = this.ToDictionary;
(this as any)['defaultIfEmpty'] = this.DefaultIfEmpty;
(this as any)['concat'] = this.Concat;
(this as any)['distinct'] = this.Distinct;
(this as any)['except'] = this.Except;
(this as any)['groupBy'] = this.GroupBy;
(this as any)['groupJoin'] = this.GroupJoin;
(this as any)['intersect'] = this.Intersect;
(this as any)['join'] = this.Join;
(this as any)['ofType'] = this.OfType;
(this as any)['orderBy'] = this.OrderBy;
(this as any)['orderByDescend'] = this.OrderByDescending;
(this as any)['range'] = this.Range;
(this as any)['repeat'] = this.Repeat;
(this as any)['reverse'] = this.Reverse;
(this as any)['select'] = this.Select;
(this as any)['selectMany'] = this.SelectMany;
(this as any)['skip'] = this.Skip;
(this as any)['skipWhile'] = this.SkipWhile;
(this as any)['take'] = this.Take;
(this as any)['takeWhile'] = this.TakeWhile;
(this as any)['union'] = this.Union;
(this as any)['where'] = this.Where;
(this as any)['zip'] = this.Zip;
}
///////////////////////////////////////////////////////////////////////////
/** Returns JavaScript iterator */
public [Symbol.iterator](): Iterator<T> {
return (null != this._factory) ? this._factory.apply(this, this._factoryArg)
: this._target[Symbol.iterator]();
}
/** Returns C# style enumerator */
public GetEnumerator(): IEnumerator<T> {
return new Iterator.CSharpEnumerator<T>(this[Symbol.iterator]());
}
//-------------------------------------------------------------------------
// Immediate execution methods
//-------------------------------------------------------------------------
public Aggregate<B>(func: (x: T, y: T) => T, resultSelector?: (x: T) => B): B;
public Aggregate<A, B>(seed: A, func: (x: A, y: T) => A, resultSelector?: (x: A) => B): B;
public Aggregate<A, B>(alpha: (x: T|A, y: T) => T|A,
beta: (x: T|A, y?: T) => A | B = Constant.selfFn,
gamma: (x: A) => B = Constant.selfFn): B {
let zero: A;
let method: (x: A, y: T) => A;
let selector: (x: A) => B;
if (Constant.CONST_FUNCTION === typeof alpha) {
method = <(x: A, y: T) => A>alpha;
selector = <(x: A) => B>beta;
} else {
zero = alpha as any;
method = <(x: A, y: T) => A>beta;
selector = gamma;
}
let result: A = zero;
for (let value of this) {
if ([null, undefined].indexOf(result) > -1 || (isNaN(result as any) && !result))
result = Constant.getDefaultVal(typeof (value));
result = method(result, value);
}
return selector(result);
}
public All(predicate: (x: T) => boolean = Constant.trueFn) {
for (let value of this) {
if (!predicate(value)) {
return false;
}
}
return true;
}
public Any(predicate?: (x: T) => boolean) {
let iterator: Iterator<T>;
// Check if at least one exist
if (!predicate && (iterator = this[Symbol.iterator]())) {
return !iterator.next().done;
}
// Check if any satisfy the criteria
for (let value of this) {
if (predicate(value)) {
return true;
}
}
return false;
}
public Average(func: (x: T) => number = Constant.selfFn): number {
let sum = 0, count = 0;
for (let value of this) {
sum += func(value);
count++;
}
return sum / count;
}
public Contains(value: T, equal: (a: T, b: T) =>
boolean = (a, b) => a === b):
boolean {
for (let item of this) {
if (equal(item, value)) {
return true;
}
}
return false;
}
public Count(predicate: (x: T) => boolean): number {
let count = 0;
if (predicate) {
for (let value of this) {
if (predicate(value)) {
count++;
}
}
} else if (this._target && (this._target as any)[Constant.CONST_LENGTH]) {
count = (this._target as any)[Constant.CONST_LENGTH];
} else {
for (let value of this) {
count++;
}
}
return count;
}
public Max(transform: (x: T) => number = Constant.selfFn): number {
let value: number, max: number, hasValue = false;
for (let item of this) {
value = transform(item);
if (hasValue) {
if (max < value) max = value;
}
else {
max = value;
hasValue = true;
}
}
if (!hasValue) throw Constant.CONST_NO_ELEMENTS;
return max;
}
public Min(transform: (x: T) => number = Constant.selfFn): number {
let value: number, min: number, hasValue = false;
for (let item of this) {
value = transform(item);
if (hasValue) {
if (min > value) min = value;
}
else {
min = value;
hasValue = true;
}
}
if (!hasValue) throw Constant.CONST_NO_ELEMENTS;
return min;
}
public ElementAt(index: number): T {
if (Array.isArray(this._target)) {
if (0 > index ||
(this._target as any)[Constant.CONST_LENGTH] <= index) {
throw Constant.CONST_OUTOFRANGE;
}
return (this._target as any)[index];
}
let count = 0;
for (let value of this) {
if (index > count++) {
continue;
}
return value;
}
throw Constant.CONST_OUTOFRANGE;
}
public ElementAtOrDefault(index: number): T {
if (Array.isArray(this._target)) {
let length = (this._target as any)[Constant.CONST_LENGTH];
if (0 > index || length <= index) {
let value = (this._target as any)[0];
return 0 < length
? Constant.getDefaultVal(typeof (value), value)
: undefined;
}
return (this._target as any)[index];
}
let value: T, count = 0;
for (let item of this) {
if (index === count++) {
return item;
}
value = item;
}
return Constant.getDefaultVal(typeof value, value); // Last good value
}
public First(predicate: (x: T) => boolean = Constant.trueFn): T {
for (let value of this) {
if (predicate(value)) {
return value;
}
}
throw Constant.CONST_NOTHING_FOUND;
}
public FirstOrDefault(predicate: (x: T) => boolean = Constant.trueFn): T {
let value: T;
for (let item of this) {
value = item;
if (predicate(item)) {
return item;
}
}
return Constant.getDefaultVal(typeof value); // Last good value
}
public Last(predicate: (x: T) => boolean = Constant.trueFn): T {
let value: T, found = false;
for (let item of this) {
if (predicate(item)) {
value = item;
found = true;
}
}
if (!found) {
throw Constant.CONST_NOTHING_FOUND;
}
return value;
}
public LastOrDefault(predicate: (x: T) => boolean = Constant.trueFn): T {
let value: T, lastKnown: T, found = false;
for (let item of this) {
if (predicate(item)) {
value = item;
found = true;
}
lastKnown = item;
}
return (found) ? value : Constant.getDefaultVal(typeof lastKnown);
}
public SequenceEqual(other: Iterable<T>,
equal: (a: T, b: T) => boolean = (a, b) => a === b):
boolean {
let res1: IteratorResult<T>, res2: IteratorResult<T>;
let it1 = this[Symbol.iterator]();
let it2 = other[Symbol.iterator]();
while (true) {
res1 = it1.next(); res2 = it2.next();
if (res1.done && res2.done) return true;
if ((res1.done != res2.done) || !equal(res1.value, res2.value)) {
return false;
}
};
}
public Single(predicate: (x: T) => boolean = Constant.trueFn): T {
let value: T, hasValue = false;
for (let item of this) {
if (predicate(item)) {
if (!hasValue) {
value = item;
hasValue = true;
}
else {
throw Constant.CONST_TOO_MANY;
}
}
}
if (hasValue) return value;
throw Constant.CONST_NOTHING_FOUND;
}
public SingleOrDefault<TSource>(predicate: (x: T) => boolean =
Constant.trueFn): T {
let value: T, lastKnown: T, hasValue = false;
for (let item of this) {
if (predicate(item)) {
if (!hasValue) {
value = item;
hasValue = true;
}
else {
throw Constant.CONST_TOO_MANY;
}
}
lastKnown = item;
}
return (hasValue) ? value : Constant.getDefaultVal(typeof lastKnown);
}
public Sum(transform: (x: T) => number = Constant.selfFn): number {
let sum: number = 0;
for (let value of this) {
sum += transform(value);
}
return sum;
}
public ToArray(): Array<T> {
let array: Array<T> = [];
for (let value of this) {
array.push(value);
}
return array;
}
public ToMap<TKey, TElement>(keySelector: (x: T) => TKey,
elementSelector: (x: T) =>
TElement = Constant.selfFn):
Map<TKey, TElement> {
let dictionary = new Map<TKey, TElement>();
for (let value of this) {
dictionary.set(keySelector(value), elementSelector(value));
}
return dictionary;
}
public ToDictionary<TKey, TElement>(keySelector: (x: T) => TKey,
elementSelector: (x: T) =>
TElement = Constant.selfFn):
Map<TKey, TElement> {
let dictionary = new Map<TKey, TElement>();
for (let value of this) {
dictionary.set(keySelector(value), elementSelector(value));
}
return dictionary;
}
public Cast<V>(): Enumerable<V> {
// TODO: Remove any once TypeScript 2.0 out
return this as any as Enumerable<V>;
}
//-------------------------------------------------------------------------
// Deferred execution methods
//-------------------------------------------------------------------------
public DefaultIfEmpty(defaultValue: T = undefined): Enumerable<T> {
return new EnumerableImpl<T>(undefined, Generator.DefaultIfEmpty, [this, defaultValue]);
}
public Concat<V>(second: Iterable<V>): Enumerable<T|V> {
return new EnumerableImpl<T|V>(undefined, Generator.Concat, [this, second]);
}
public ChunkBy<K, E, V>(keySelect: (x: T, i: number) => K,
elementSelector: (x: T) => E = Constant.selfFn,
resultSelector: (a: K, b: Iterable<E>) => V = (a, b) => b as any):
Enumerable<V> {
return new EnumerableImpl<V>(undefined, Generator.ChunkBy,
[this, keySelect, elementSelector, resultSelector]);
}
public Distinct<V>(keySelector?: (x: T) => V): Enumerable<T> {
if (keySelector)
return new EnumerableImpl<T>(undefined, Generator.Distinct, [this, keySelector]);
return new EnumerableImpl<T>(undefined, Generator.DistinctFast, [this]);
}
public Except<K,V>(other: Iterable<V>, keySelector?: (x: V|T) => K): Enumerable<T> {
return new EnumerableImpl<T>(undefined, Generator.Intersect,
[ this, Constant.getKeys(other, keySelector), true, keySelector ]);
}
public GroupBy<K>(selKey: (x: T) => K): Enumerable<IGrouping<K, T>>;
public GroupBy<K, E>(selKey: (x: T) => K, selElement: (x: T) => E): Enumerable<IGrouping<K, E>>;
public GroupBy<K, E, R>(selKey: (x: T) => K, selElement: (x: T) => E = Constant.selfFn,
selResult: (a: K, b: Iterable<E>) => R = Constant.defGrouping): Enumerable<R> {
let map: Map<K, Array<E>> = Constant.getKeyedMap(this, selKey, selElement);
return new EnumerableImpl<R>(undefined, Generator.GroupBy, [map, selResult]) as any;
}
public GroupJoin<I, K, R>(inner: Iterable<I>,
oKeySelect: (a: T) => K,
iKeySelect: (b: I) => K,
resultSelector: (a: T, b: Iterable<I>) =>
R = Constant.defGrouping): Enumerable<R> {
return new EnumerableImpl<R>(undefined, Generator.GroupJoin,
[this, oKeySelect, resultSelector,
Constant.getKeyedMapFast(inner, iKeySelect)]);
}
public Intersect<K>(other: Iterable<T>,
keySelector?: (x: T) => K): Enumerable<T> {
return new EnumerableImpl<T>(undefined, Generator.Intersect, [this,
Constant.getKeys(other, keySelector),
false, keySelector]);
}
public Join<I, K, R>(inner: Iterable<I>,
oSelector: (o: T) => K,
iSelector: (i: I) => K,
transform: (o: T, i: I) => R): Enumerable<R> {
return new EnumerableImpl<R>(undefined, Generator.Join,
[this, oSelector, transform, Constant.getKeyedMapFast(inner, iSelector)]);
}
public OfType(obj: any): Enumerable<T> {
let typeName: string;
switch (obj) {
case Number:
typeName = Constant.CONST_NUMBER;
break;
case Boolean:
typeName = Constant.CONST_BOOLEAN;
break;
case String:
typeName = Constant.CONST_STRING;
break;
case Symbol:
typeName = Constant.CONST_SYMBOL;
break;
default:
typeName = undefined;
}
return new EnumerableImpl<T>(undefined, Generator.OfType, [this, obj, typeName]);
}
public OrderBy<K>(keySelect: (x: T) => K, equal: (a: K, b: K) => number): OrderedEnumerable<T> {
return new OrderedLinq<T, K>(this, (array: Array<T>) => Generator.Forward(array), keySelect, equal);
}
public OrderByDescending<K>(keySelect: (x: T) => K, equal: (a: K, b: K) => number): OrderedEnumerable<T> {
return new OrderedLinq<T, K>(this, (array: Array<T>) => Generator.Reverse(array), keySelect, equal, true);
}
public Range(start: number, count: number): Enumerable<number> {
return new EnumerableImpl<number>(undefined, Generator.Range, [start, count]);
}
public Repeat<V>(element: V, count: number): Enumerable<V> {
return new EnumerableImpl<V>(undefined, Generator.Repeat, [element, count]);
}
public Reverse(): Enumerable<T> {
let array: Array<T> = Array.isArray(this._target)
? <Array<T>>this._target : this.ToArray();
return new EnumerableImpl<T>(undefined, Generator.Reverse, [array]);
}
public Select<V>(transform: (x: T, index?: number) => V): Enumerable<V> {
return new EnumerableImpl<V>(undefined, Generator.Select, [this, transform]);
}
public SelectMany<S, V>(selector: (x: T, index: number) =>
Iterable<S> = Constant.selfFn,
result: (x: T, s: S) =>
V = (x, s) => s as any as V):
Enumerable<V> {
return new EnumerableImpl<V>(undefined, Generator.SelectMany,
[this, selector, result]);
}
public Skip(skip: number): Enumerable<T> {
return new EnumerableImpl<T>(undefined, Generator.Skip, [this, skip]);
}
public SkipWhile(predicate: (x: T, i?: number) => boolean): Enumerable<T> {
return new EnumerableImpl<T>(undefined, Generator.SkipWhile, [this, predicate]);
}
public Take(take: number): Enumerable<T> {
return new EnumerableImpl<T>(undefined, Generator.TakeWhile,
[this, (a: T, n: number) => take > n]);
}
public TakeWhile(predicate: (x: T, i: number) => boolean): Enumerable<T> {
return new EnumerableImpl<T>(undefined, Generator.TakeWhile, [this, predicate]);
}
public Union<K>(second: Iterable<T>, keySelector?: (x: T) => K): Enumerable<T> {
if (keySelector)
return new EnumerableImpl<T>(undefined, Generator.Union, [this, second, keySelector]);
return new EnumerableImpl<T>(undefined, Generator.UnionFast, [this, second]);
}
public Where(predicate: (x: T, i?: number) => Boolean = Constant.trueFn):
Enumerable<T> {
return new EnumerableImpl<T>(undefined, Generator.Where, [this, predicate]);
}
public Zip<V, Z>(second: Iterable<V>, func: (a: T, b: V) => Z):
Enumerable<Z> {
return new EnumerableImpl<Z>(undefined, Generator.Zip, [this, second, func]);
}
}
class OrderedLinq<T, K> extends EnumerableImpl<T> implements OrderedEnumerable<T> {
private comparer: (a: any, b: any) => number;
constructor(target: Iterable<any> | IEnumerable<any>,
factory: Function,
keySelect: (x: T) => K,
equal: (a: K, b: K) => number,
private reversed: boolean = false) {
super(target, factory);
if (keySelect) {
this.comparer = equal ? (a: any, b: any) => equal(keySelect(a), keySelect(b))
: (a: any, b: any) => Constant.defCompare(keySelect(a), keySelect(b));
} else {
this.comparer = equal;
}
(this as any)['thenBy'] = this.ThenBy;
(this as any)['thenByDescending'] = this.ThenByDescending;
}
public [Symbol.iterator](): Iterator<T> {
if (!this._factoryArg) {
this._factoryArg = (<EnumerableImpl<T>>this._target).ToArray();
if (this.comparer) {
this._factoryArg.sort(this.comparer);
} else {
this._factoryArg.sort();
}
}
return this._factory(this._factoryArg);
}
public ThenBy<K>(keySelect: (x: T) => K, equal?: (a: K, b: K) => number): OrderedEnumerable<T> {
if (!keySelect && !equal) return this;
const compare = keySelect ? equal ? (a: any, b: any) => equal(keySelect(a), keySelect(b))
: (a: any, b: any) => Constant.defCompare(keySelect(a), keySelect(b))
: equal;
const superEqual = this.comparer;
const comparer = (!superEqual) ? compare
: (a: any, b: any) => superEqual(a, b) || (this.reversed ? -compare(a, b) : compare(a, b));
return new OrderedLinq<T, K>(this._target, this._factory, undefined, comparer, this.reversed);
}
public ThenByDescending<K>(keySelect: (x: T) => K, equal?: (a: K, b: K) => number): OrderedEnumerable<T> {
if (!keySelect && !equal) return this;
const compare = keySelect ? equal ? (a: any, b: any) => equal(keySelect(a), keySelect(b))
: (a: any, b: any) => Constant.defCompare(keySelect(a), keySelect(b))
: equal;
const superEqual = this.comparer;
const comparer = (!superEqual) ? compare
: (a: any, b: any) => superEqual(a, b) || (this.reversed ? compare(a, b) : -compare(a, b));
return new OrderedLinq<T, K>(this._target, this._factory, undefined, comparer, this.reversed);
}
}
/** Copyright (c) ENikS. All rights reserved. */ | the_stack |
import {InstanceFactory} from "../instancefactory";
import { HttpRequest } from "../../web/httprequest";
import { HttpResponse } from "../../web/httpresponse";
import { NoomiError } from "../../tools/errorfactory";
import { Util } from "../../tools/util";
import { App } from "../../tools/application";
import { IWebCacheObj } from "../../web/webcache";
/**
* 路由类配置
*/
interface IRouteClassCfg{
/**
* 类名
*/
className?:string;
/**
* 命名空间
*/
namespace?:string;
/**
* 路径数组,数组元素为 {path:路径,method:方法名}
*/
paths?:any[];
}
/**
* 路由配置类型
*/
interface IRouteCfg{
/**
* 路由路径
*/
path?:string;
/**
* 类名
*/
className?:string;
/**
* 命名空间
*/
namespace?:string;
/**
* 路由正则表达式
*/
reg?:RegExp;
/**
* 该路由对应的实例名
*/
instanceName?:string;
/**
* 该路由对应的实例方法
*/
method?:string;
/**
* 路由执行结果数组
*/
results?:Array<IRouteResult>;
}
/**
* 路由结果类型
* @since 0.0.6
*/
enum ERouteResultType{
/**
* 重定向
*/
REDIRECT='redirect',
/**
* 路由链,和redirect不同,浏览器地址不会改变
*/
CHAIN='chain',
/**
* 文件流,主要用于文件下载
*/
STREAM='stream',
/**
* 什么都不做
*/
NONE='none',
/**
* json数据,默认类型
*/
JSON='json'
}
/**
* 路由结果类型
*/
interface IRouteResult{
/**
* 结果类型
*/
type?:ERouteResultType;
/**
* 返回值,当返回值与value一致时,将执行此结果
*/
value?:any;
/**
* 路径,type 为redirect 和 url时,必须设置
*/
url?:string;
/**
* 参数名数组,当type为chain时,从当前路由对应类中获取参数数组对应的属性值并以参数对象传递到下一个路由
*/
params?:Array<string>
}
/**
* 路由对象
*/
interface IRoute{
/**
* 路由对应实例
*/
instance:any;
/**
* 路由对应方法名
*/
method:string;
/**
* 路由处理结果集
*/
results?:Array<IRouteResult>;
/**
* route 实例对应url路径
* @since 0.4.7
*/
path?:string;
/**
* 参数对象
* @since 0.4.7
*/
params?:object;
}
/**
* 路由工厂类
* 用于管理所有路由对象
*/
class RouteFactory{
/**
* 动态路由(带通配符)路由集合
*/
static dynaRouteArr:IRouteCfg[] = new Array();
/**
* 静态路由(不带通配符)路由集合
*/
static staticRouteMap:Map<string,IRouteCfg> = new Map();
/**
* 注册路由map,添加到实例工厂时统一处理
*/
private static registRouteMap:Map<string,IRouteClassCfg> = new Map();
/**
* 注册路由
* @param cfg 路由配置
*/
public static registRoute(cfg:IRouteCfg){
if(!this.registRouteMap.has(cfg.className)){
this.registRouteMap.set(cfg.className,{
paths:[]
})
}
let obj = this.registRouteMap.get(cfg.className);
//命名空间,针对Router注解器
if(cfg.namespace){
obj.namespace = cfg.namespace;
}
if(cfg.path){
obj.paths.push({path:cfg.path,method:cfg.method,results:cfg.results});
}
}
/**
* 处理实例路由
* 把注册路由添加到路由对象中
* @param instanceName 实例名
* @param className 类名
*/
public static handleInstanceRoute(instanceName:string,className:string){
if(!this.registRouteMap.has(className)){
return;
}
let cfg = this.registRouteMap.get(className);
let paths = cfg.paths;
for(let p of paths){
this.addRoute(Util.getUrlPath([cfg.namespace||'',p.path]),instanceName,p.method,p.results);
}
//删除已处理的class
this.registRouteMap.delete(className);
}
/**
* 添加路由
* @param path 路由路径,支持通配符*,需要method支持
* @param className 对应类
* @param method 方法,path中包含*,则不设置
* @param results 路由处理结果集
*/
private static addRoute(path:string,className:string,method?:string,results?:Array<IRouteResult>){
if(results && results.length>0){
for(let r of results){
if((r.type === ERouteResultType.CHAIN || r.type === ERouteResultType.REDIRECT)
&& (!r.url || typeof r.url !=='string' || (r.url = r.url.trim())=== '')){
throw new NoomiError("2101");
}
}
}
if(method){
method = method.trim();
}
//没有通配符
if(path.indexOf('*') === -1){
this.staticRouteMap.set(path,{
instanceName:className,
method:method,
results:results
});
}else{ //有通配符
if(!this.dynaRouteArr.find(item=>item.path === path)){
this.dynaRouteArr.push({
path:path,
reg:Util.toReg(path,3),
instanceName:className,
method:method,
results:results
});
}
}
}
/**
* 根据路径获取路由对象
* @param path url路径
* @returns 路由对象
*/
public static getRoute(path:string):IRoute{
let item:IRouteCfg;
let method:string; //方法名
//下查找非通配符map
if(this.staticRouteMap.has(path)){
item = this.staticRouteMap.get(path);
method = item.method;
}else{
for(let i=0;i<this.dynaRouteArr.length;i++){
item = this.dynaRouteArr[i];
//路径测试通过
if(item.reg.test(path)){
method = item.method;
if(!method){
let index = path.lastIndexOf("/");
//通配符处理
if(index !== -1){
//通配符方法
method = path.substr(index+1);
}
}
break;
}
}
}
//找到匹配的则返回
if(item && method){
let instance = InstanceFactory.getInstance(item.instanceName);
if(instance && typeof instance[method] === 'function'){
return {instance:instance,method:method,results:item.results};
}
}
return null;
}
/**
* 路由方法执行
* @param pathOrRoute 路径或路由
* @param req request 对象
* @param res response 对象
* @param params 调用参数对象
* @returns 0 正常 1异常
*/
public static async handleRoute(route:IRoute,req:HttpRequest,res:HttpResponse,params?:object):Promise<number|IWebCacheObj|string>{
//绑定path
if(!route.path && req){
route.path = req.url;
}
//设置request
if(typeof route.instance.setRequest === 'function'){
route.instance.setRequest(req);
}
//设置response
if(typeof route.instance.setResponse === 'function'){
route.instance.setResponse(res);
}
//初始化参数
if(!params){
params = await req.init();
}
//设置model
if(typeof route.instance.setModel === 'function'){
let nullArr;
if(route.instance.__getNullCheck){ //空属性
nullArr = route.instance.__getNullCheck(route.method);
}
route.instance.setModel(params,nullArr);
}
//实际调用方法
let func = route.instance[route.method];
if(typeof func !== 'function'){
throw new NoomiError("1010");
}
let re = await func.call(route.instance,route.instance||params);
return await this.handleResult(route,re);
}
/**
* 处理路由结果
* @param route route对象
* @param data 路由对应方法返回值
*/
public static async handleResult(route:IRoute,data:any):Promise<number|IWebCacheObj|string>{
const results = route.results;
if(results && results.length > 0){
//单个结果,不判断返回值
if(results.length === 1){
return await this.handleOneResult(route,results[0],data);
}else{
let r:IRouteResult;
for(r of results){
//result不带value,或找到返回值匹配,则处理
if(r.value === undefined || data && data == r.value){
return await this.handleOneResult(route,r,data);
}
}
}
}
//默认回写json
return await this.handleOneResult(route,{},data);
}
/**
* 处理一个路由结果
* @param route route对象
* @param result route result
* @param data 路由执行结果
* @returns cache数据对象或0
*/
public static async handleOneResult(route:IRoute,result:IRouteResult,data:any):Promise<IWebCacheObj|number|string>{
let url:string;
const instance = route.instance;
const res:HttpResponse = route.instance.response;
//返回值
let ret:IWebCacheObj|number = 0;
switch(result.type){
case ERouteResultType.REDIRECT: //重定向
url = handleParamUrl(instance,result.url);
let pa = [];
//参数属性
if(result.params && Array.isArray(result.params) && result.params.length>0){
for(let pn of result.params){
let v = getValue(instance,pn);
if(v !== undefined){
pa.push(pn+'=' + v);
}
}
}
let pas:string = pa.join('&');
if(pas !== ''){
if(url.indexOf('?') === -1){
url += '?' + pas;
}else{
url += '&' + pas;
}
}
res.redirect(url);
return ERouteResultType.REDIRECT;
case ERouteResultType.CHAIN: //路由器链
url = handleParamUrl(instance,result.url);
let url1 = App.url.parse(url).pathname;
let params = App.qs.parse(App.url.parse(url).query);
//参数处理
if(result.params && Array.isArray(result.params) && result.params.length>0){
for(let pn of result.params){
let v = getValue(instance,pn);
if(v !== undefined){
params[pn] = v;
}
}
}
let route1 = this.getRoute(url1);
if(route1 === null){
throw new NoomiError("2103",url1);
}
//设置route path
route1.path = url1;
return await this.handleRoute(route1,route.instance.request,res,params);
case ERouteResultType.NONE: //什么都不做
break;
case ERouteResultType.STREAM: //文件流
//文件名
let pn:string = result.params[0];
if(pn){
let fn:string = getValue(instance,pn);
if(fn){
fn = Util.getAbsPath([fn]);
if(!App.fs.existsSync(fn)){
throw new NoomiError('0050');
}
res.writeFileToClient({
data:fn
});
}
}
break;
default: //json
let mimeType:string;
//处理json对象
if(typeof data === 'object'){
data = JSON.stringify(data);
mimeType = 'application/json';
}else{
mimeType = 'text/plain';
}
ret = {
data:data, //如果无数据,则返回''
mimeType:mimeType
};
}
return ret;
/**
* 处理带参数的url,参数放在{}中
* @param url 源url,以${propName}出现
* @returns 处理后的url
*/
function handleParamUrl(instance:any,url:string):string{
let reg:RegExp = /\$\{.*?\}/g;
let r:RegExpExecArray;
//处理带参数url
while((r=reg.exec(url)) !== null){
let pn = r[0].substring(2,r[0].length-1);
url = url.replace(r[0],getValue(instance,pn));
}
return url;
}
/**
* 获取属性值
* @param instance 实例
* @param pn 属性名
* @returns 属性值
*/
function getValue(instance:any,pn:string):any{
if(instance[pn] !== undefined){
return instance[pn];
}else if(instance.model && instance.model[pn] !== undefined){
return instance.model[pn];
}
}
}
/**
* 处理异常信息
* @param res response 对象
* @param e 异常
* @deprecated 1.0.0
*/
static handleException(res:HttpResponse,e:any){}
/**
* 初始化路由工厂
* @param config 配置文件
* @param ns 命名空间(上级路由路径)
*/
// static init(config:any,ns?:string){
// let ns1:string = config.namespace? config.namespace.trim():undefined;
// if(ns1){
// if(ns){
// ns = Util.getUrlPath([ns,ns1]);
// }else{
// ns = Util.getUrlPath([ns1])
// }
// }
// if(!ns){
// ns = '';
// }
// //处理本级路由
// if(Array.isArray(config.routes)){
// config.routes.forEach((item)=>{
// //增加namespce前缀
// let p = Util.getUrlPath([ns,item.path]);
// this.addRoute(p,item.instance_name,item.method,item.results);
// });
// }
// //处理子路径路由
// if(Array.isArray(config.files)){
// config.files.forEach((item)=>{
// const p = Util.getAbsPath([App.configPath, item]);
// this.parseFile(p,ns);
// });
// }
// }
// /**
// * 解析路由文件
// * @param path 文件路径
// * @param ns 命名空间,默认 /
// */
// static parseFile(path:string,ns?:string){
// interface RouteJSON{
// namespace:string; //命名空间
// route_error_handler:string; //路由异常处理器
// files:Array<string>; //引入文件
// routes:Array<any>; //实例配置数组
// }
// //读取文件
// let json:RouteJSON = null;
// try{
// let jsonStr:string = App.fs.readFileSync(path,'utf-8');
// json = App.JSON.parse(jsonStr);
// }catch(e){
// throw new NoomiError("2100") +'\n' + e;
// }
// this.init(json,ns);
// }
}
export {RouteFactory,IRoute,IRouteCfg,IRouteResult,ERouteResultType}; | the_stack |
import {Component, OnInit, ViewChild} from '@angular/core';
import {Router, NavigationStart} from '@angular/router';
import {SensorParserConfig} from '../../model/sensor-parser-config';
import {SensorParserConfigService} from '../../service/sensor-parser-config.service';
import {MetronAlerts} from '../../shared/metron-alerts';
import {MetronDialogBox} from '../../shared/metron-dialog-box';
import {Sort} from '../../util/enums';
import {SortEvent} from '../../shared/metron-table/metron-table.directive';
import {StormService} from '../../service/storm.service';
import {TopologyStatus} from '../../model/topology-status';
import {SensorParserConfigHistory} from '../../model/sensor-parser-config-history';
import {SensorParserConfigHistoryService} from '../../service/sensor-parser-config-history.service';
@Component({
selector: 'metron-config-sensor-parser-list',
templateUrl: 'sensor-parser-list.component.html',
styleUrls: ['sensor-parser-list.component.scss']
})
export class SensorParserListComponent implements OnInit {
componentName: string = 'Sensors';
@ViewChild('table') table;
count: number = 0;
sensors: SensorParserConfigHistory[] = [];
sensorsStatus: TopologyStatus[] = [];
selectedSensor: SensorParserConfigHistory;
selectedSensors: SensorParserConfigHistory[] = [];
enableAutoRefresh: boolean = true;
constructor(private sensorParserConfigService: SensorParserConfigService,
private sensorParserConfigHistoryService: SensorParserConfigHistoryService,
private stormService: StormService,
private router: Router,
private metronAlerts: MetronAlerts,
private metronDialogBox: MetronDialogBox) {
router.events.subscribe(event => {
if (event instanceof NavigationStart && event.url === '/sensors') {
this.onNavigationStart();
}
});
}
getSensors(justOnce: boolean) {
this.sensorParserConfigService.getAll().subscribe(
(results: {string: SensorParserConfig}) => {
this.sensors = [];
for (let sensorName of Object.keys(results)) {
let sensorParserConfigHistory = new SensorParserConfigHistory();
sensorParserConfigHistory.sensorName = sensorName;
sensorParserConfigHistory.config = results[sensorName];
this.sensors.push(sensorParserConfigHistory);
}
this.selectedSensors = [];
this.count = this.sensors.length;
if (!justOnce) {
this.getStatus();
this.pollStatus();
} else {
this.getStatus();
}
}
);
}
onSort($event: SortEvent) {
switch ($event.sortBy) {
case 'sensorName':
this.sensors.sort((obj1: SensorParserConfigHistory, obj2: SensorParserConfigHistory) => {
if ($event.sortOrder === Sort.ASC) {
return obj1.sensorName.localeCompare(obj2.sensorName);
}
return obj2.sensorName.localeCompare(obj1.sensorName);
});
break;
case 'parserClassName':
this.sensors.sort((obj1: SensorParserConfigHistory, obj2: SensorParserConfigHistory) => {
if ($event.sortOrder === Sort.ASC) {
return this.getParserType(obj1.config).localeCompare(this.getParserType(obj2.config));
}
return this.getParserType(obj2.config).localeCompare(this.getParserType(obj1.config));
});
break;
case 'status':
case 'modifiedBy':
case 'modifiedByDate':
case 'latency':
case 'throughput':
this.sensors.sort((obj1: SensorParserConfigHistory, obj2: SensorParserConfigHistory) => {
if (!obj1[$event.sortBy] || !obj1[$event.sortBy]) {
return 0;
}
if ($event.sortOrder === Sort.ASC) {
return obj1[$event.sortBy].localeCompare(obj2[$event.sortBy]);
}
return obj2[$event.sortBy].localeCompare(obj1[$event.sortBy]);
});
break;
}
}
private pollStatus() {
this.stormService.pollGetAll().subscribe(
(results: TopologyStatus[]) => {
this.sensorsStatus = results;
this.updateSensorStatus();
},
error => {
this.updateSensorStatus();
}
);
}
private getStatus() {
this.stormService.getAll().subscribe(
(results: TopologyStatus[]) => {
this.sensorsStatus = results;
this.updateSensorStatus();
},
error => {
this.updateSensorStatus();
}
);
}
updateSensorStatus() {
for (let sensor of this.sensors) {
let status: TopologyStatus = this.sensorsStatus.find(status => {
return status.name === sensor.sensorName;
});
if (status) {
if (status.status === 'ACTIVE') {
sensor['status'] = 'Running';
}
if (status.status === 'KILLED') {
sensor['status'] = 'Stopped';
}
if (status.status === 'INACTIVE') {
sensor['status'] = 'Disabled';
}
} else {
sensor['status'] = 'Stopped';
}
sensor['latency'] = status && status.status === 'ACTIVE' ? (status.latency + 'ms') : '-';
sensor['throughput'] = status && status.status === 'ACTIVE' ? (Math.round(status.throughput * 100) / 100) + 'kb/s' : '-';
}
}
getParserType(sensor: SensorParserConfig): string {
let items = sensor.parserClassName.split('.');
return items[items.length - 1].replace('Basic', '').replace('Parser', '');
}
ngOnInit() {
this.getSensors(false);
this.sensorParserConfigService.dataChanged$.subscribe(
data => {
this.getSensors(true);
}
);
}
addAddSensor() {
this.router.navigateByUrl('/sensors(dialog:sensors-config/new)');
}
navigateToSensorEdit(selectedSensor: SensorParserConfigHistory, event) {
this.selectedSensor = selectedSensor;
this.router.navigateByUrl('/sensors(dialog:sensors-config/' + selectedSensor.sensorName + ')');
event.stopPropagation();
}
onRowSelected(sensor: SensorParserConfigHistory, $event) {
if ($event.target.checked) {
this.selectedSensors.push(sensor);
} else {
this.selectedSensors.splice(this.selectedSensors.indexOf(sensor), 1);
}
}
onSelectDeselectAll($event) {
let checkBoxes = this.table.nativeElement.querySelectorAll('tr td:last-child input[type="checkbox"]');
for (let ele of checkBoxes) {
ele.checked = $event.target.checked;
}
if ($event.target.checked) {
this.selectedSensors = this.sensors.slice(0).map((sensorParserInfo: SensorParserConfigHistory) => sensorParserInfo);
} else {
this.selectedSensors = [];
}
}
onSensorRowSelect(sensor: SensorParserConfigHistory, $event) {
if ($event.target.type !== 'checkbox' && $event.target.parentElement.firstChild.type !== 'checkbox') {
if (this.selectedSensor === sensor) {
this.selectedSensor = null;
this.router.navigateByUrl('/sensors');
return;
}
this.selectedSensor = sensor;
this.router.navigateByUrl('/sensors(dialog:sensors-readonly/' + sensor.sensorName + ')');
}
}
deleteSensor($event, selectedSensorsToDelete: SensorParserConfigHistory[]) {
if ($event) {
$event.stopPropagation();
}
let sensorNames = selectedSensorsToDelete.map(sensor => { return sensor.sensorName; });
let confirmationsMsg = 'Are you sure you want to delete sensor(s) ' + sensorNames.join(', ') + ' ?';
this.metronDialogBox.showConfirmationMessage(confirmationsMsg).subscribe(result => {
if (result) {
this.sensorParserConfigService.deleteSensorParserConfigs(sensorNames)
.subscribe((deleteResult: {success: Array<string>, failure: Array<string>}) => {
if (deleteResult.success.length > 0) {
this.metronAlerts.showSuccessMessage('Deleted sensors: ' + deleteResult.success.join(', '));
}
if (deleteResult.failure.length > 0) {
this.metronAlerts.showErrorMessage('Unable to deleted sensors: ' + deleteResult.failure.join(', '));
}
});
}
});
}
onDeleteSensor() {
this.deleteSensor(null, this.selectedSensors);
}
onStopSensors() {
for (let sensor of this.selectedSensors) {
if (sensor['status'] === 'Running' || sensor['status'] === 'Disabled') {
this.onStopSensor(sensor, null);
}
}
}
onStopSensor(sensor: SensorParserConfigHistory, event) {
this.toggleStartStopInProgress(sensor);
this.stormService.stopParser(sensor.sensorName).subscribe(result => {
this.metronAlerts.showSuccessMessage('Stopped sensor ' + sensor.sensorName);
this.toggleStartStopInProgress(sensor);
},
error => {
this.metronAlerts.showErrorMessage('Unable to stop sensor ' + sensor.sensorName);
this.toggleStartStopInProgress(sensor);
});
if (event !== null) {
event.stopPropagation();
}
}
onStartSensors() {
for (let sensor of this.selectedSensors) {
if (sensor['status'] === 'Stopped') {
this.onStartSensor(sensor, null);
}
}
}
onStartSensor(sensor: SensorParserConfigHistory, event) {
this.toggleStartStopInProgress(sensor);
this.stormService.startParser(sensor.sensorName).subscribe(result => {
if (result['status'] === 'ERROR') {
this.metronAlerts.showErrorMessage('Unable to start sensor ' + sensor.sensorName + ': ' + result['message']);
} else {
this.metronAlerts.showSuccessMessage('Started sensor ' + sensor.sensorName);
}
this.toggleStartStopInProgress(sensor);
},
error => {
this.metronAlerts.showErrorMessage('Unable to start sensor ' + sensor.sensorName);
this.toggleStartStopInProgress(sensor);
});
if (event !== null) {
event.stopPropagation();
}
}
onDisableSensors() {
for (let sensor of this.selectedSensors) {
if (sensor['status'] === 'Running') {
this.onDisableSensor(sensor, null);
}
}
}
onDisableSensor(sensor: SensorParserConfigHistory, event) {
this.toggleStartStopInProgress(sensor);
this.stormService.deactivateParser(sensor.sensorName).subscribe(result => {
this.metronAlerts.showSuccessMessage('Disabled sensor ' + sensor.sensorName);
this.toggleStartStopInProgress(sensor);
},
error => {
this.metronAlerts.showErrorMessage('Unable to disable sensor ' + sensor.sensorName);
this.toggleStartStopInProgress(sensor);
});
if (event !== null) {
event.stopPropagation();
}
}
onEnableSensors() {
for (let sensor of this.selectedSensors) {
if (sensor['status'] === 'Disabled') {
this.onEnableSensor(sensor, null);
}
}
}
onEnableSensor(sensor: SensorParserConfigHistory, event) {
this.toggleStartStopInProgress(sensor);
this.stormService.activateParser(sensor.sensorName).subscribe(result => {
this.metronAlerts.showSuccessMessage('Enabled sensor ' + sensor.sensorName);
this.toggleStartStopInProgress(sensor);
},
error => {
this.metronAlerts.showErrorMessage('Unable to enabled sensor ' + sensor.sensorName);
this.toggleStartStopInProgress(sensor);
});
if (event != null) {
event.stopPropagation();
}
}
toggleStartStopInProgress(sensor: SensorParserConfigHistory) {
sensor.config['startStopInProgress'] = !sensor.config['startStopInProgress'];
}
onNavigationStart() {
this.selectedSensor = null;
this.selectedSensors = [];
}
} | the_stack |
import {Inject, Injectable, PLATFORM_ID} from '@angular/core';
import {AngularFireLiteApp} from '../core.service';
import {HttpClient} from '@angular/common/http';
import {FirebaseAppConfig} from '../core.config';
import {makeStateKey, TransferState} from '@angular/platform-browser';
import {isPlatformBrowser, isPlatformServer} from '@angular/common';
import {BehaviorSubject, from, Observable, of, Subject} from 'rxjs';
import {map, tap} from 'rxjs/operators';
import {FirebaseFirestore} from '@firebase/firestore-types';
import 'firebase/firestore';
@Injectable()
export class AngularFireLiteFirestore {
private readonly firestore: FirebaseFirestore;
private readonly config: FirebaseAppConfig;
private readonly browser = isPlatformBrowser(this.platformId);
constructor(private app: AngularFireLiteApp,
private http: HttpClient,
private state: TransferState,
@Inject(PLATFORM_ID) private platformId: Object) {
this.firestore = app.instance().firestore();
this.config = app.config();
}
// ------------- Read -----------------//
read(ref: string): Observable<any> | BehaviorSubject<any> {
const dataStateKey = makeStateKey<Object>(ref + 'firestore:read');
const refArray = ref.split('/');
if (refArray[0] === '/') {
refArray.shift();
}
if (refArray[refArray.length - 1] === '/') {
refArray.pop();
}
const slashes = refArray.length - 1;
if (isPlatformServer(this.platformId)) {
return this.http
.get(`https://firestore.googleapis.com/v1beta1/projects/${this.config.projectId}/databases/(default)/documents/${ref}`)
.pipe(map((res: any) => {
const docData = {};
if (slashes % 2 !== 0) {
Object.keys(res.fields)
.forEach((key) => {
for (const keyValue in res.fields[key]) {
if (keyValue) {
docData[key] = res.fields[key][keyValue];
}
}
});
return docData;
} else {
const colData = [];
res.documents.forEach((doc) => {
const singleDocData = {};
Object.keys(doc.fields)
.forEach((key) => {
for (const keyValue in doc.fields[key]) {
if (keyValue) {
singleDocData[key] = doc.fields[key][keyValue];
}
}
});
colData.push(singleDocData);
});
return colData;
}
})
, tap((pl) => {
this.state.set(dataStateKey, pl);
}));
}
if (this.browser) {
const data = [];
const SSRedValue = this.state.get(dataStateKey, []);
const DATA = new BehaviorSubject<any>(SSRedValue);
if (slashes % 2 === 0) {
this.firestore.collection(ref).onSnapshot((snapshot) => {
snapshot.docs.forEach((doc) => {
data.push(doc.data());
});
DATA.next(data);
});
} else {
this.firestore.doc(ref).onSnapshot((snapshot) => {
DATA.next(snapshot.data());
});
}
return DATA;
}
}
// ------------- Write -----------------//
write(ref: string, data: Object, merge?: boolean): Observable<any> {
if (this.browser) {
return from(this.firestore.doc(ref).set(data, {merge: merge}));
}
}
push(ref: string, data: Object): Observable<any> {
if (this.browser) {
return from(this.firestore.collection(ref).add(data));
}
}
update(ref: string, data: Object): Observable<any> {
if (this.browser) {
return from(this.firestore.doc(ref).update(data));
}
}
// ------------- Delete -----------------//
remove(DocumentRef: string): Observable<any> {
if (isPlatformServer(this.platformId)) {
return this.http
.delete(`https://firestore.googleapis.com/v1beta1/projects/${this.config.projectId}/databases/(default)/documents/${DocumentRef}`);
}
if (this.browser) {
return from(this.firestore.doc(DocumentRef).delete());
}
}
removeField(ref: string, ...fields): Observable<any> {
if (this.browser) {
return from(this.firestore.doc(ref).update(fields));
}
}
removeCollection(collectionRef: string): Observable<any> {
if (this.browser) {
return from(this.firestore.collection(collectionRef).get().then((snapshot) => {
snapshot.docs.forEach((doc) => {
this.firestore.batch().delete(doc.ref);
});
}));
}
}
// ------------- Query -----------------//
query(ref: string) {
const PID = this.platformId;
const HTTP = this.http;
const CONFIG = this.config;
const state = this.state;
const fs = this.firestore;
const SSQ: any = {
'from': [{'collectionId': ref}]
};
const SQ = {
'structuredQuery': SSQ
};
function SQHFS(DSK) {
const data = [];
return HTTP
.post(`https://firestore.googleapis.com/v1beta1/projects/${CONFIG.projectId}/databases/(default)/documents:runQuery`,
JSON.stringify(SQ))
.pipe(map((res: any) => {
for (const doc of res) {
const documentData = {};
Object.keys(doc.document.fields).forEach((fieldName) => {
const fieldType = Object.keys(doc.document.fields[fieldName]);
documentData[fieldName] = doc.document.fields[fieldName][fieldType[0]];
});
data.push(documentData);
}
return data;
})
, tap((pl) => {
state.set(DSK, pl);
}));
}
function FSD(value) {
switch (typeof value) {
case 'boolean':
return {'booleanValue': value};
case 'string':
return {'stringValue': value};
case 'number':
return {'doubleValue': value};
case 'object':
return {'arrayValue': value};
}
}
const SQOB = [];
let BQ = fs.collection(ref) as any;
return {
where(document: string, comparison: string, value: any): Query {
let SOP = '';
switch (comparison) {
case '<':
SOP = 'LESS_THAN';
break;
case '<=':
SOP = 'LESS_THAN_OR_EQUAL';
break;
case '>':
SOP = 'GREATER_THAN';
break;
case '>=':
SOP = 'GREATER_THAN_OR_EQUAL';
break;
case '==':
SOP = 'EQUAL';
break;
}
SSQ['where'] = {'fieldFilter': {'field': {'fieldPath': document}, 'op': SOP, 'value': FSD(value)}};
BQ = BQ.where(document, comparison, value);
return this;
},
startAt(...startValue): Query {
const SV = [];
startValue.forEach((value) => {
SV.push(FSD(value));
});
SSQ.startAt = {};
SSQ.startAt.before = true;
SSQ.startAt.values = SV;
BQ = BQ.startAt(...startValue);
return this;
},
startAfter(...startValue): Query {
const SV = [];
startValue.forEach((value) => {
SV.push(FSD(value));
});
SSQ.startAt = {};
SSQ.startAt.before = false;
SSQ.startAt.values = SV;
BQ = BQ.startAfter(...startValue);
return this;
},
endAt(...endValue): Query {
const SV = [];
endValue.forEach((value) => {
SV.push(FSD(value));
});
SSQ.endAt = {};
SSQ.endAt.before = false;
SSQ.endAt.values = SV;
BQ = BQ.endAt(...endValue);
return this;
},
endBefore(...endValue): Query {
const SV = [];
endValue.forEach((value) => {
SV.push(FSD(value));
});
SSQ.endAt = {};
SSQ.endAt.before = true;
SSQ.endAt.values = SV;
BQ = BQ.endBefore(...endValue);
return this;
},
limit(limit: number): Query {
SSQ.limit = limit;
BQ = BQ.limit(limit);
return this;
},
orderBy(path: string, order?: 'asc' | 'desc'): Query {
const orderBy = {
field: {
fieldPath: ''
}
};
orderBy.field.fieldPath = path;
switch (order) {
case 'asc':
orderBy['direction'] = 'ASCENDING';
break;
case 'desc':
orderBy['direction'] = 'DESCENDING';
break;
}
SQOB.push(orderBy);
BQ = BQ.orderBy(path, order);
SSQ.orderBy = SQOB as any;
return this;
},
on(): BehaviorSubject<any> | Observable<any> {
const ONDSK = makeStateKey<Object | Array<any>>(ref + 'firestore:query');
if (isPlatformServer(PID)) {
return SQHFS(ONDSK);
}
if (isPlatformBrowser(PID)) {
const SSRedValue = state.get(ONDSK, []);
const VALUE = new BehaviorSubject<any>(SSRedValue);
BQ.onSnapshot((snapshot) => {
const data = [];
snapshot.forEach((doc) => {
data.push(doc.data());
});
VALUE.next(data);
});
return VALUE;
}
},
get(): BehaviorSubject<any> | Observable<any> {
const GETDSK = makeStateKey<Object | Array<any>>(ref + 'firestore:query');
if (isPlatformServer(PID)) {
return SQHFS(GETDSK);
}
if (isPlatformBrowser(PID)) {
const data = [];
const SSRedValue = state.get(GETDSK, []);
const VALUE = new BehaviorSubject<any>(SSRedValue);
BQ.get().then((snapshot) => {
snapshot.forEach((doc) => {
data.push(doc);
});
VALUE.next(data);
});
return VALUE;
}
}
};
}
// ------------- Transactions and Batched Writes -----------------//
// TODO: Add Transactions SSR support
transaction(): Transaction {
if (this.browser) {
const fs = this.firestore;
let transactionToRun: Promise<any>;
let readCount = 0;
const transactions = {
get(ref) {
return fs.doc(ref).get();
},
set(ref, data) {
return fs.doc(ref).set(data);
}
};
return {
set(ref: string, data: Object): Transaction {
transactionToRun = transactionToRun.then(() => {
transactions.set(ref, data);
});
return this;
},
get(ref: string): Subject<any> {
const getSubject = new Subject();
if (readCount > 0) {
transactionToRun = transactionToRun.then(() => {
transactions.get(ref).then((value) => {
getSubject.next({data: value.data(), next: this});
});
});
} else if (readCount === 0) {
transactionToRun = transactions.get(ref).then((value) => {
getSubject.next({data: value.data(), next: this});
});
}
readCount++;
return getSubject;
},
run(): Observable<any> {
return from(fs.runTransaction(() => {
return transactionToRun;
}));
}
};
} else {
return {
set(ref: string, data: Object): Transaction {
return this;
},
get(ref: string): Subject<any> {
return new Subject();
},
run(): Observable<any> {
return of();
}
};
}
}
// TODO: Add batched writes SSR support
batch(): Batch {
if (this.browser) {
const fs = this.firestore;
const b = this.firestore.batch();
return {
set(ref: string, data: Object): Batch {
b.set(fs.doc(ref), data);
return this;
},
update(ref: string, data: Object): Batch {
b.update(fs.doc(ref), data);
return this;
},
delete(ref: string): Batch {
b.delete(fs.doc(ref));
return this;
},
commit(): Observable<any> {
return from(b.commit());
}
};
} else {
return {
set(ref: string, data: Object) {
return this;
},
update(ref: string, data: Object): Batch {
return this;
},
delete(ref: string): Batch {
return this;
},
commit(): Observable<any> {
return of();
}
};
}
}
}
export interface Batch {
set(ref: string, data: Object): Batch;
update(ref: string, data: Object): Batch;
delete(ref: string): Batch;
commit(): Observable<any>
}
export interface Transaction {
set(ref: string, data: Object): Transaction;
get(ref: string): Subject<any>;
run(): Observable<any>
}
export interface Query {
where(document: string, comparison: string, value: any): Query;
startAt(...startValue: Array<string>): Query;
endAt(...endValue: Array<string>): Query;
startAfter(...startValue: Array<string>): Query;
endBefore(...endValue: Array<string>): Query;
limit(limit: number): Query;
orderBy(path: string, order?: 'asc' | 'desc'): Query;
on(): BehaviorSubject<any> | Observable<any>;
get(): BehaviorSubject<any> | Observable<any>;
} | the_stack |
import {hasOwnProperty} from 'core-helpers';
import {
Observable,
createObservable,
isObservable,
canBeObserved,
isEmbeddable,
ObserverPayload
} from '@layr/observable';
import {throwError} from '@layr/utilities';
import {possiblyAsync} from 'possibly-async';
import type {
Component,
TraverseAttributesIteratee,
TraverseAttributesOptions,
ResolveAttributeSelectorOptions
} from '../component';
import {Property, PropertyOptions, IntrospectedProperty, UnintrospectedProperty} from './property';
import {
ValueType,
IntrospectedValueType,
UnintrospectedValueType,
createValueType,
unintrospectValueType
} from './value-types';
import {fork} from '../forking';
import {AttributeSelector} from './attribute-selector';
import type {Sanitizer, SanitizerFunction} from '../sanitization';
import type {Validator, ValidatorFunction} from '../validation';
import {SerializeOptions} from '../serialization';
import {deserialize, DeserializeOptions} from '../deserialization';
import {isComponentClass, isComponentInstance, ensureComponentClass} from '../utilities';
export type AttributeOptions = PropertyOptions & {
valueType?: string;
value?: unknown;
default?: unknown;
sanitizers?: (Sanitizer | SanitizerFunction)[];
validators?: (Validator | ValidatorFunction)[];
items?: AttributeItemsOptions;
getter?: (this: any) => unknown;
setter?: (this: any, value: any) => void;
};
type AttributeItemsOptions = {
sanitizers?: (Sanitizer | SanitizerFunction)[];
validators?: (Validator | ValidatorFunction)[];
items?: AttributeItemsOptions;
};
export type ValueSource = 'server' | 'store' | 'local' | 'client';
export type IntrospectedAttribute = IntrospectedProperty & {
value?: unknown;
default?: unknown;
} & IntrospectedValueType;
export type UnintrospectedAttribute = UnintrospectedProperty & {
options: {
value?: unknown;
default?: unknown;
} & UnintrospectedValueType;
};
/**
* *Inherits from [`Property`](https://layrjs.com/docs/v2/reference/property) and [`Observable`](https://layrjs.com/docs/v2/reference/observable#observable-class).*
*
* An `Attribute` represents an attribute of a [Component](https://layrjs.com/docs/v2/reference/component) class, prototype, or instance. It plays the role of a regular JavaScript object attribute, but brings some extra features such as runtime type checking, validation, serialization, or observability.
*
* #### Usage
*
* Typically, you create an `Attribute` and associate it to a component by using the [`@attribute()`](https://layrjs.com/docs/v2/reference/component#attribute-decorator) decorator.
*
* For example, here is how you would define a `Movie` class with some attributes:
*
* ```
* // JS
*
* import {Component, attribute, validators} from '﹫layr/component';
*
* const {minLength} = validators;
*
* class Movie extends Component {
* // Optional 'string' class attribute
* ﹫attribute('string?') static customName;
*
* // Required 'string' instance attribute
* ﹫attribute('string') title;
*
* // Optional 'string' instance attribute with a validator and a default value
* ﹫attribute('string?', {validators: [minLength(16)]}) summary = '';
* }
* ```
*
* ```
* // TS
*
* import {Component, attribute, validators} from '﹫layr/component';
*
* const {minLength} = validators;
*
* class Movie extends Component {
* // Optional 'string' class attribute
* ﹫attribute('string?') static customName?: string;
*
* // Required 'string' instance attribute
* ﹫attribute('string') title!: string;
*
* // Optional 'string' instance attribute with a validator and a default value
* ﹫attribute('string?', {validators: [minLength(16)]}) summary? = '';
* }
* ```
*
* Then you can access the attributes like you would normally do with regular JavaScript objects:
*
* ```
* Movie.customName = 'Film';
* Movie.customName; // => 'Film'
*
* const movie = new Movie({title: 'Inception'});
* movie.title; // => 'Inception'
* movie.title = 'Inception 2';
* movie.title; // => 'Inception 2'
* movie.summary; // => '' (default value)
* ```
*
* And you can take profit of some extra features:
*
* ```
* // Runtime type checking
* movie.title = 123; // Error
* movie.title = undefined; // Error
*
* // Validation
* movie.summary = undefined;
* movie.isValid(); // => true (movie.summary is optional)
* movie.summary = 'A nice movie.';
* movie.isValid(); // => false (movie.summary is too short)
* movie.summary = 'An awesome movie.'
* movie.isValid(); // => true
*
* // Serialization
* movie.serialize();
* // => {__component: 'Movie', title: 'Inception 2', summary: 'An awesome movie.'}
* ```
*/
export class Attribute extends Observable(Property) {
/**
* Creates an instance of [`Attribute`](https://layrjs.com/docs/v2/reference/attribute). Typically, instead of using this constructor, you would rather use the [`@attribute()`](https://layrjs.com/docs/v2/reference/component#attribute-decorator) decorator.
*
* @param name The name of the attribute.
* @param parent The component class, prototype, or instance that owns the attribute.
* @param [options.valueType] A string specifying the [type of values](https://layrjs.com/docs/v2/reference/value-type#supported-types) the attribute can store (default: `'any'`).
* @param [options.value] The initial value of the attribute (usable for class attributes only).
* @param [options.default] The default value (or a function returning the default value) of the attribute (usable for instance attributes only).
* @param [options.sanitizers] An array of [sanitizers](https://layrjs.com/docs/v2/reference/sanitizer) for the value of the attribute.
* @param [options.validators] An array of [validators](https://layrjs.com/docs/v2/reference/validator) for the value of the attribute.
* @param [options.items.sanitizers] An array of [sanitizers](https://layrjs.com/docs/v2/reference/sanitizer) for the items of an array attribute.
* @param [options.items.validators] An array of [validators](https://layrjs.com/docs/v2/reference/validator) for the items of an array attribute.
* @param [options.getter] A getter function for getting the value of the attribute. Plays the same role as a regular [JavaScript getter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get).
* @param [options.setter] A setter function for setting the value of the attribute. Plays the same role as a regular [JavaScript setter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set).
* @param [options.exposure] A [`PropertyExposure`](https://layrjs.com/docs/v2/reference/property#property-exposure-type) object specifying how the attribute should be exposed to remote access.
*
* @returns The [`Attribute`](https://layrjs.com/docs/v2/reference/attribute) instance that was created.
*
* @example
* ```
* import {Component, Attribute} from '﹫layr/component';
*
* class Movie extends Component {}
*
* const title = new Attribute('title', Movie.prototype, {valueType: 'string'});
*
* title.getName(); // => 'title'
* title.getParent(); // => Movie.prototype
* title.getValueType().toString(); // => 'string'
* ```
*
* @category Creation
*/
constructor(name: string, parent: typeof Component | Component, options: AttributeOptions = {}) {
super(name, parent, options);
}
_initialize() {
this.addObserver(this._onChange.bind(this));
}
// === Options ===
_getter?: () => unknown;
_setter?: (value: any) => void;
setOptions(options: AttributeOptions = {}) {
const {
valueType,
value: initialValue,
default: defaultValue,
sanitizers,
validators,
items,
getter,
setter,
...otherOptions
} = options;
const hasInitialValue = 'value' in options;
const hasDefaultValue = 'default' in options;
super.setOptions(otherOptions);
this._valueType = createValueType(valueType, this, {sanitizers, validators, items});
if (getter !== undefined || setter !== undefined) {
if (initialValue !== undefined) {
throw new Error(
`An attribute cannot have both a getter or setter and an initial value (${this.describe()})`
);
}
if (defaultValue !== undefined) {
throw new Error(
`An attribute cannot have both a getter or setter and a default value (${this.describe()})`
);
}
if (getter !== undefined) {
this._getter = getter;
}
if (setter !== undefined) {
if (getter === undefined) {
throw new Error(
`An attribute cannot have a setter without a getter (${this.describe()})`
);
}
this._setter = setter;
}
this._isSet = true;
return;
}
if (hasInitialValue) {
this.setValue(initialValue);
}
if (hasDefaultValue) {
this._default = defaultValue;
}
}
// === Property Methods ===
/**
* See the methods that are inherited from the [`Property`](https://layrjs.com/docs/v2/reference/property#basic-methods) class.
*
* @category Property Methods
*/
// === Value type ===
_valueType!: ValueType;
/**
* Returns the type of values the attribute can store.
*
* @returns A [ValueType](https://layrjs.com/docs/v2/reference/value-type) instance.
*
* @example
* ```
* const title = Movie.prototype.getAttribute('title');
* title.getValueType(); // => A ValueType instance
* title.getValueType().toString(); // => 'string'
* title.getValueType().isOptional(); // => false
* ```
*
* @category Value Type
*/
getValueType() {
return this._valueType;
}
// === Value ===
_value?: unknown;
_isSet?: boolean;
/**
* Returns the current value of the attribute.
*
* @param [options.throwIfUnset] A boolean specifying whether the method should throw an error if the value is not set (default: `true`). If `false` is specified and the value is not set, the method returns `undefined`.
*
* @returns A value of the type handled by the attribute.
*
* @example
* ```
* const title = movie.getAttribute('title');
* title.getValue(); // => 'Inception'
* title.unsetValue();
* title.getValue(); // => Error
* title.getValue({throwIfUnset: false}); // => undefined
* ```
*
* @category Value
*/
getValue(options: {throwIfUnset?: boolean; autoFork?: boolean} = {}) {
const {throwIfUnset = true, autoFork = true} = options;
if (!this.isSet()) {
if (throwIfUnset) {
throw new Error(`Cannot get the value of an unset attribute (${this.describe()})`);
}
return undefined;
}
if (this._getter !== undefined) {
return this._getter.call(this.getParent());
}
if (autoFork && !hasOwnProperty(this, '_value')) {
const parent = this.getParent();
const value = this._value;
const componentClass = isComponentInstance(value)
? ensureComponentClass(parent).getComponent(value.constructor.getComponentName())
: undefined;
let forkedValue = fork(value, {componentClass});
if (canBeObserved(forkedValue)) {
if (!isObservable(forkedValue)) {
forkedValue = createObservable(forkedValue);
}
if (isEmbeddable(forkedValue)) {
forkedValue.addObserver(this);
}
}
this._value = forkedValue;
}
return this._value;
}
_ignoreNextSetValueCall?: boolean;
/**
* Sets the value of the attribute. If the type of the value doesn't match the expected type, an error is thrown.
*
* When the attribute's value changes, the observers of the attribute are automatically executed, and the observers of the parent component are executed as well.
*
* @param value The value to be set.
* @param [options.source] A string specifying the [source of the value](https://layrjs.com/docs/v2/reference/attribute#value-source-type) (default: `'local'`).
*
* @example
* ```
* const title = movie.getAttribute('title');
* title.setValue('Inception 2');
* title.setValue(123); // => Error
* ```
*
* @category Value
*/
setValue(value: unknown, {source = 'local'}: {source?: ValueSource} = {}) {
if (hasOwnProperty(this, '_ignoreNextSetValueCall')) {
delete this._ignoreNextSetValueCall;
return {previousValue: undefined, newValue: undefined};
}
if (this.isControlled() && !(source === 'server' || source === 'store')) {
throw new Error(
`Cannot set the value of a controlled attribute when the source is different than 'server' or 'store' (${this.describe()}, source: '${source}')`
);
}
this.checkValue(value);
value = this.sanitizeValue(value);
if (this._setter !== undefined) {
this._setter.call(this.getParent(), value);
return {previousValue: undefined, newValue: undefined};
}
if (this._getter !== undefined) {
throw new Error(
`Cannot set the value of an attribute that has a getter but no setter (${this.describe()})`
);
}
if (canBeObserved(value) && !isObservable(value)) {
value = createObservable(value);
}
const previousValue = this.getValue({throwIfUnset: false});
this._value = value;
this._isSet = true;
const valueHasChanged = (value as any)?.valueOf() !== (previousValue as any)?.valueOf();
if (valueHasChanged) {
if (isObservable(previousValue) && isEmbeddable(previousValue)) {
previousValue.removeObserver(this);
}
if (isObservable(value) && isEmbeddable(value)) {
value.addObserver(this);
}
}
if (valueHasChanged || source !== this._source) {
this.callObservers({source});
}
return {previousValue, newValue: value};
}
/**
* Unsets the value of the attribute. If the value is already unset, nothing happens.
*
* @example
* ```
* const title = movie.getAttribute('title');
* title.isSet(); // => true
* title.unsetValue();
* title.isSet(); // => false
* ```
*
* @category Value
*/
unsetValue() {
if (this._getter !== undefined) {
throw new Error(
`Cannot unset the value of an attribute that has a getter (${this.describe()})`
);
}
if (this._isSet !== true) {
return {previousValue: undefined};
}
const previousValue = this.getValue({throwIfUnset: false});
this._value = undefined;
this._isSet = false;
if (isObservable(previousValue) && isEmbeddable(previousValue)) {
previousValue.removeObserver(this);
}
this.callObservers({source: 'local'});
return {previousValue};
}
/**
* Returns whether the value of the attribute is set or not.
*
* @returns A boolean.
*
* @example
* ```
* const title = movie.getAttribute('title');
* title.isSet(); // => true
* title.unsetValue();
* title.isSet(); // => false
* ```
*
* @category Value
*/
isSet() {
return this._isSet === true;
}
checkValue(value: unknown) {
return this.getValueType().checkValue(value, this);
}
sanitizeValue(value: unknown) {
return this.getValueType().sanitizeValue(value);
}
// === Value source ===
_source: ValueSource = 'local';
/**
* Returns the source of the value of the attribute.
*
* @returns A [`ValueSource`](https://layrjs.com/docs/v2/reference/attribute#value-source-type) string.
*
* @example
* ```
* const title = movie.getAttribute('title');
* title.getValueSource(); // => 'local' (the value was set locally)
* ```
*
* @category Value Source
*/
getValueSource() {
return this._source;
}
/**
* Sets the source of the value of the attribute.
*
* @param source A [`ValueSource`](https://layrjs.com/docs/v2/reference/attribute#value-source-type) string.
*
* @example
* ```
* const title = movie.getAttribute('title');
* title.setValueSource('local'); // The value was set locally
* title.setValueSource('server'); // The value came from an upper layer
* title.setValueSource('client'); // The value came from a lower layer
* ```
*
* @category Value Source
*/
setValueSource(source: ValueSource) {
if (source !== this._source) {
this._source = source;
this.callObservers({source});
}
}
/**
* @typedef ValueSource
*
* A string representing the source of a value.
*
* Currently, four types of sources are supported:
*
* * `'server'`: The value comes from an upper layer.
* * `'store'`: The value comes from a store.
* * `'local'`: The value comes from the current layer.
* * `'client'`: The value comes from a lower layer.
* ```
*
* @category Value Source
*/
// === Default value ===
_default?: unknown;
/**
* Returns the default value of the attribute as specified when the attribute was created.
*
* @returns A value or a function returning a value.
*
* @example
* ```
* const summary = movie.getAttribute('summary');
* summary.getDefault(); // => function () { return ''; }
* ```
*
* @category Default Value
*/
getDefault() {
return this._default;
}
/**
* Evaluate the default value of the attribute. If the default value is a function, the function is called (with the attribute's parent as `this` context), and the result is returned. Otherwise, the default value is returned as is.
*
* @returns A value of any type.
*
* @example
* ```
* const summary = movie.getAttribute('summary');
* summary.evaluateDefault(); // ''
* ```
*
* @category Default Value
*/
evaluateDefault() {
let value = this._default;
if (typeof value === 'function' && !isComponentClass(value)) {
value = value.call(this.getParent());
}
return value;
}
_isDefaultSetInConstructor?: boolean;
_fixDecoration() {
if (this._isDefaultSetInConstructor) {
this._ignoreNextSetValueCall = true;
}
}
// === 'isControlled' mark
_isControlled?: boolean;
isControlled() {
return this._isControlled === true;
}
markAsControlled() {
Object.defineProperty(this, '_isControlled', {value: true});
}
// === Observers ===
_onChange(payload: ObserverPayload & {source?: ValueSource}) {
const {source = 'local'} = payload;
if (source !== this._source) {
this._source = source;
}
this.getParent().callObservers(payload);
}
// === Attribute traversal ===
_traverseAttributes(iteratee: TraverseAttributesIteratee, options: TraverseAttributesOptions) {
const {setAttributesOnly} = options;
const value = setAttributesOnly ? this.getValue() : undefined;
this.getValueType()._traverseAttributes(iteratee, this, value, options);
}
// === Attribute selectors ===
_resolveAttributeSelector(
normalizedAttributeSelector: AttributeSelector,
options: ResolveAttributeSelectorOptions
) {
const {setAttributesOnly} = options;
const value = setAttributesOnly ? this.getValue() : undefined;
return this.getValueType()._resolveAttributeSelector(
normalizedAttributeSelector,
this,
value,
options
);
}
// === Serialization ===
serialize(options: SerializeOptions = {}): unknown {
if (!this.isSet()) {
throw new Error(`Cannot serialize an unset attribute (${this.describe()})`);
}
return this.getValueType().serializeValue(this.getValue(), this, options);
}
// === Deserialization ===
deserialize(
serializedValue: unknown,
options: DeserializeOptions = {}
): void | PromiseLike<void> {
if (this.isSet()) {
const value = this.getValue();
if (value !== undefined && this.getValueType().canDeserializeInPlace(this)) {
return (value as any).deserialize(serializedValue, options);
}
}
const rootComponent = ensureComponentClass(this.getParent());
return possiblyAsync(
deserialize(serializedValue, {...options, rootComponent}),
(deserializedValue) => {
this.setValue(deserializedValue, {source: options.source});
}
);
}
// === Validation ===
/**
* Validates the value of the attribute. If the value doesn't pass the validation, an error is thrown. The error is a JavaScript `Error` instance with a `failedValidators` custom attribute which contains the result of the [`runValidators()`](https://layrjs.com/docs/v2/reference/attribute#run-validators-instance-method) method.
*
* @param [attributeSelector] In case the value of the attribute is a component, your can pass an [`AttributeSelector`](https://layrjs.com/docs/v2/reference/attribute-selector) specifying the component's attributes to be validated (default: `true`, which means that all the component's attributes will be validated).
*
* @example
* ```
* // JS
*
* import {Component, attribute, validators} from '﹫layr/component';
*
* const {notEmpty} = validators;
*
* class Movie extends Component {
* ﹫attribute('string', {validators: [notEmpty()]}) title;
* }
*
* const movie = new Movie({title: 'Inception'});
* const title = movie.getAttribute('title');
*
* title.getValue(); // => 'Inception'
* title.validate(); // All good!
* title.setValue('');
* title.validate(); // => Error {failedValidators: [{validator: ..., path: ''}]}
* ```
*
* @example
* ```
* // TS
*
* import {Component, attribute, validators} from '﹫layr/component';
*
* const {notEmpty} = validators;
*
* class Movie extends Component {
* ﹫attribute('string', {validators: [notEmpty()]}) title!: string;
* }
*
* const movie = new Movie({title: 'Inception'});
* const title = movie.getAttribute('title');
*
* title.getValue(); // => 'Inception'
* title.validate(); // All good!
* title.setValue('');
* title.validate(); // => Error {failedValidators: [{validator: ..., path: ''}]}
* ```
*
* @category Validation
*/
validate(attributeSelector: AttributeSelector = true) {
const failedValidators = this.runValidators(attributeSelector);
if (failedValidators.length === 0) {
return;
}
const details = failedValidators
.map(({validator, path}) => `${validator.getMessage()} (path: '${path}')`)
.join(', ');
let displayMessage: string | undefined;
for (const {validator} of failedValidators) {
const message = validator.getMessage({generateIfMissing: false});
if (message !== undefined) {
displayMessage = message;
break;
}
}
throwError(
`The following error(s) occurred while validating the attribute '${this.getName()}': ${details}`,
{displayMessage, failedValidators}
);
}
/**
* Returns whether the value of the attribute is valid.
*
* @param [attributeSelector] In case the value of the attribute is a component, your can pass an [`AttributeSelector`](https://layrjs.com/docs/v2/reference/attribute-selector) specifying the component's attributes to be validated (default: `true`, which means that all the component's attributes will be validated).
*
* @returns A boolean.
*
* @example
* ```
* // See the `title` definition in the `validate()` example
*
* title.getValue(); // => 'Inception'
* title.isValid(); // => true
* title.setValue('');
* title.isValid(); // => false
* ```
*
* @category Validation
*/
isValid(attributeSelector: AttributeSelector = true) {
const failedValidators = this.runValidators(attributeSelector);
return failedValidators.length === 0;
}
/**
* Runs the validators with the value of the attribute.
*
* @param [attributeSelector] In case the value of the attribute is a component, your can pass an [`AttributeSelector`](https://layrjs.com/docs/v2/reference/attribute-selector) specifying the component's attributes to be validated (default: `true`, which means that all the component's attributes will be validated).
*
* @returns An array containing the validators that have failed. Each item is a plain object composed of a `validator` (a [`Validator`](https://layrjs.com/docs/v2/reference/validator) instance) and a `path` (a string representing the path of the attribute containing the validator that has failed).
*
* @example
* ```
* // See the `title` definition in the `validate()` example
*
* title.getValue(); // => 'Inception'
* title.runValidators(); // => []
* title.setValue('');
* title.runValidators(); // => [{validator: ..., path: ''}]
* ```
*
* @category Validation
*/
runValidators(attributeSelector: AttributeSelector = true) {
if (!this.isSet()) {
throw new Error(`Cannot run the validators of an unset attribute (${this.describe()})`);
}
const failedValidators = this.getValueType().runValidators(this.getValue(), attributeSelector);
return failedValidators;
}
// === Observability ===
/**
* See the methods that are inherited from the [`Observable`](https://layrjs.com/docs/v2/reference/observable#observable-class) class.
*
* @category Observability
*/
// === Introspection ===
introspect() {
const introspectedAttribute = super.introspect() as IntrospectedAttribute;
if (introspectedAttribute === undefined) {
return undefined;
}
const exposure = this.getExposure();
const getIsExposed = exposure !== undefined ? hasOwnProperty(exposure, 'get') : false;
const setIsExposed = exposure !== undefined ? hasOwnProperty(exposure, 'set') : false;
if (getIsExposed && this.isSet()) {
introspectedAttribute.value = this.getValue();
}
if (setIsExposed) {
const defaultValue = this.getDefault();
if (defaultValue !== undefined) {
introspectedAttribute.default = defaultValue;
}
}
Object.assign(introspectedAttribute, this.getValueType().introspect());
return introspectedAttribute;
}
static unintrospect(introspectedAttribute: IntrospectedAttribute) {
const {
value: initialValue,
default: defaultValue,
valueType,
validators,
items,
...introspectedProperty
} = introspectedAttribute;
const hasInitialValue = 'value' in introspectedAttribute;
const hasDefaultValue = 'default' in introspectedAttribute;
const {name, options} = super.unintrospect(introspectedProperty) as UnintrospectedAttribute;
if (hasInitialValue) {
options.value = initialValue;
}
if (hasDefaultValue) {
options.default = defaultValue;
}
Object.assign(options, unintrospectValueType({valueType, validators, items}));
return {name, options};
}
// === Utilities ===
static isAttribute(value: any): value is Attribute {
return isAttributeInstance(value);
}
describeType() {
return 'attribute';
}
}
/**
* Returns whether the specified value is an `Attribute` class.
*
* @param value A value of any type.
*
* @returns A boolean.
*
* @category Utilities
*/
export function isAttributeClass(value: any): value is typeof Attribute {
return typeof value?.isAttribute === 'function';
}
/**
* Returns whether the specified value is an `Attribute` instance.
*
* @param value A value of any type.
*
* @returns A boolean.
*
* @category Utilities
*/
export function isAttributeInstance(value: any): value is Attribute {
return isAttributeClass(value?.constructor) === true;
} | the_stack |
function getMainDiv(rootControl: JQuery): JQuery {
return rootControl.find('div');
}
describe('textFieldDirective: <uif-textfield />', () => {
beforeEach(() => {
angular.mock.module('officeuifabric.components.textfield');
});
it('should be able to set value', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
$scope.valueChanged = () => {
// empty body
};
spyOn($scope, 'valueChanged');
$scope.textBoxValue = 'Test 1';
let textBox: JQuery = $compile('<uif-textfield ng-model="textBoxValue" ng-change="valueChanged()"></uif-textfield>')($scope);
textBox = jQuery(textBox[0]);
$scope.$apply();
let mainDiv: JQuery = getMainDiv(textBox);
let input: JQuery = mainDiv.find('input');
expect(input.val()).toBe('Test 1');
$scope.textBoxValue = 'Test 2';
$scope.$apply();
expect(input.val()).toBe('Test 2');
expect($scope.valueChanged).toHaveBeenCalled();
}));
it('should be able to set label and description', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
let textBox: JQuery = $compile('<uif-textfield uif-label="Label contents"' +
' uif-description="Description contents"></uif-textfield>')($scope);
textBox = jQuery(textBox[0]);
$scope.$apply();
let label: JQuery = getMainDiv(textBox).find('label.ms-Label');
expect(label.html()).toBe('Label contents');
let description: JQuery = textBox.find('span.ms-TextField-description');
expect(description.html()).toBe('Description contents');
}));
it('should be able to set underlined', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
let textBox: JQuery = $compile('<uif-textfield uif-underlined></uif-textfield>')($scope);
textBox = jQuery(textBox[0]);
// element must be appended to the body, otherwise focus/blur events don't fire
textBox.appendTo(document.body);
$scope.$apply();
let div: JQuery = getMainDiv(textBox);
expect(div.hasClass('ms-TextField--underlined')).toBe(true, 'textfield should have ms-textfield--underlined');
let input: JQuery = textBox.find('input');
let container: JQuery = textBox.find('div');
input.focus();
expect(container.hasClass('is-active')).toBe(true, 'Container should have class in-active when focused');
input.blur();
expect(container.hasClass('is-active')).toBe(false, 'Container should not have class in-active when not focused');
}));
it('should be able to set required', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
let textBox: JQuery = $compile('<uif-textfield required></uif-textfield>')($scope);
textBox = jQuery(textBox[0]);
// element must be appended to the body, otherwise focus/blur events don't fire
textBox.appendTo(document.body);
$scope.$apply();
let div: JQuery = getMainDiv(textBox);
expect(div.hasClass('is-required')).toBe(true, 'textfield should have is-required');
// ng-required
textBox = $compile('<uif-textfield ng-required="isRequired"></uif-textfield>')($scope);
textBox = jQuery(textBox[0]);
let ngRequiredDiv: JQuery = getMainDiv(textBox);
$scope.isRequired = true;
$scope.$apply();
expect(ngRequiredDiv.hasClass('is-required')).toBe(true, 'textfield should have is-required');
$scope.isRequired = false;
$scope.$apply();
expect(ngRequiredDiv.hasClass('is-required')).toBe(false, 'textfield should not have is-required');
}));
it('should be able to set disabled', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
let textBox: JQuery = $compile('<uif-textfield disabled></uif-textfield>')($scope);
textBox = jQuery(textBox[0]);
// element must be appended to the body, otherwise focus/blur events don't fire
textBox.appendTo(document.body);
$scope.$apply();
let div: JQuery = getMainDiv(textBox);
expect(div.hasClass('is-disabled')).toBe(true, 'textfield should have is-disabled');
let input: JQuery = textBox.find('input');
let container: JQuery = textBox.find('div');
spyOn(input[0], 'focus');
input.click();
expect(container.hasClass('is-active')).toBe(false, 'Container should not be able to get in-active class as it is disabled');
expect(input[0].focus).not.toHaveBeenCalled();
// ng-disabled
$scope.isDisabled = true;
textBox = $compile('<uif-textfield ng-disabled="isDisabled"></uif-textfield>')($scope);
$scope.$apply();
textBox = jQuery(textBox[0]);
textBox.appendTo(document.body);
div = getMainDiv(textBox);
input = textBox.find('input');
expect(input.attr('disabled')).toBe('disabled', 'Input should be disabled');
spyOn(input[0], 'focus');
expect(div.hasClass('is-disabled')).toBe(true, 'textfield should have is-disabled');
input.click();
expect(div.hasClass('is-active')).toBe(false, 'Container should not be able to get in-active class as it is disabled');
expect(input[0].focus).not.toHaveBeenCalled();
$scope.isDisabled = false;
$scope.$apply();
expect(input.attr('disabled')).toBe(undefined, 'Input should not be disabled');
expect(div.hasClass('is-disabled')).toBe(false, 'textfield should not be disabled');
input.focus();
expect(div.hasClass('is-active')).toBe(true, 'Container should be able to get is-active class as it is not disabled');
input.blur();
expect(div.hasClass('is-active')).toBe(false, 'Container should not have class in-active when not focused');
}));
it('should be able to set min, max and step for input', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
let textBox: JQuery = $compile('<uif-textfield min="0" max="2" step="1" ></uif-textfield>')($scope);
textBox = jQuery(textBox[0]);
$scope.$apply();
let input: JQuery = textBox.find('input');
expect(input.attr('max')).toBe('2', 'max value is set');
expect(input.attr('min')).toBe('0', 'min value is set');
expect(input.attr('step')).toBe('1', 'step value is set');
}));
it('should be able to set placeholder', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
$scope.value = '';
let textBox: JQuery = $compile('<uif-textfield placeholder="Placeholder contents" ng-model="value"></uif-textfield>')($scope);
textBox = jQuery(textBox[0]);
$scope.$apply();
let label: JQuery = textBox.find('div.ms-TextField--placeholder label.ms-Label');
expect(label.html()).toBe('Placeholder contents');
expect(label.hasClass('ng-hide')).toBe(false, 'Label should be visible before click');
let input: JQuery = textBox.find('input');
input.focus();
expect(label.hasClass('ng-hide')).toBe(true, 'Label should be hidden after focus');
input.blur();
expect(label.hasClass('ng-hide')).toBe(false, 'Label should be visible after blur');
$scope.value = 'Test';
$scope.$apply();
expect(label.hasClass('ng-hide')).toBe(true, 'Label should be hidden after setting ng-model');
}));
it('should be able to set as multiline', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
$scope.value = 'multiline text';
let textBox: JQuery = $compile('<uif-textfield ng-model="value" uif-multiline="true"></uif-textfield>')($scope);
textBox = jQuery(textBox[0]);
$scope.$apply();
let textArea: JQuery = textBox.find('textarea.ms-TextField-field');
textArea = jQuery(textArea);
expect(textArea.hasClass('ng-hide')).toBe(false, 'textarea should be visible.');
expect(textArea.val()).toBe('multiline text');
let div: JQuery = textBox.find('div');
expect(div.hasClass('ms-TextField--multiline')).toBe(true, 'Container should have class ms-TextField--multiline.');
let textInput: JQuery = textBox.find('input.ms-TextField-field');
textInput = jQuery(textInput);
expect(textInput.hasClass('ng-hide')).toBe(true, 'input should be hidden');
}));
// input should be able to be of type password
// multiline (textbox) is not able to be set of type password
it('input should be able to be of type password', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
let textBox: JQuery = $compile('<uif-textfield ng-model="value" uif-type="password"></uif-textfield>')($scope);
textBox = jQuery(textBox[0]);
$scope.$apply();
let textInput: JQuery = textBox.find('input.ms-TextField-field');
textInput = jQuery(textInput);
expect(textInput.attr('type')).toBe('password', 'input is of type password');
let textArea: JQuery = textBox.find('textarea.ms-TextField-field');
textArea = jQuery(textArea);
expect(textArea.attr('type')).toBe(undefined, 'textarea can not be set of type password');
}));
// input should verify uif-type
it(
'should be validating uif-type attributes',
inject(($compile: Function, $rootScope: angular.IRootScopeService, $log: angular.ILogService) => {
let $scope: any = $rootScope.$new();
expect($log.error.logs.length).toBe(0);
$compile('<uif-textfield ng-model="value" uif-type="invalid"></uif-textfield>')($scope);
$scope.$digest();
expect($log.error.logs[0]).toContain('Error [ngOfficeUiFabric] officeuifabric.components.textfield - Unsupported type: ' +
'The type (\'invalid\') is not supported by the Office UI Fabric. ' +
'Supported options are listed here: ' +
'https://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/textfield/uifTypeEnum.ts');
}));
// input with placeholder should focus on click on label
// click on the placeholder should hide it an set the focus into the input field
it('input with placeholder should focus on click on label', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
let textBox: JQuery = $compile('<uif-textfield placeholder="Placeholder contents"></uif-textfield>')($scope);
textBox = jQuery(textBox[0]);
$scope.$apply();
let label: JQuery = textBox.find('div.ms-TextField--placeholder label.ms-Label');
expect(label.html()).toBe('Placeholder contents');
expect(label.hasClass('ng-hide')).toBe(false, 'Label should be visible before click');
let input: JQuery = textBox.find('input.ms-TextField-field');
input = jQuery(input);
spyOn(input[0], 'focus');
label.click();
expect(input[0].focus).toHaveBeenCalled();
// multiline tests
textBox = $compile('<uif-textfield placeholder="Placeholder contents" uif-multiline="true"></uif-textfield>')($scope);
textBox = jQuery(textBox[0]);
$scope.$apply();
label = textBox.find('div.ms-TextField--placeholder label.ms-Label');
expect(label.html()).toBe('Placeholder contents');
expect(label.hasClass('ng-hide')).toBe(false, 'Label should be visible before click');
input = textBox.find('textarea.ms-TextField-field');
input = jQuery(input);
spyOn(input[0], 'focus');
label.click();
expect(input[0].focus).toHaveBeenCalled();
}));
it(
'changing text field should set $dirty on model',
inject(($compile: angular.ICompileService, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
$scope.modelValue = 'test';
let liteTextBox: angular.IAugmentedJQuery =
$compile('<uif-textfield ng-model="modelValue" placeholder="Placeholder contents"></uif-textfield>')($scope);
let textBox: JQuery = jQuery(liteTextBox[0]);
$scope.$digest();
let input: JQuery = textBox.find('input.ms-TextField-field');
input = jQuery(input);
let ngModelCtrl: angular.INgModelController = angular.element(textBox).controller('ngModel');
expect(ngModelCtrl.$dirty).toBe(false);
input.val('xyz');
angular.element(input).triggerHandler('input');
$scope.$digest();
expect(ngModelCtrl.$dirty).toBe(true);
}));
it(
'defocusing text field sets $touched on model',
inject(($compile: angular.ICompileService, $rootScope: angular.IRootScopeService) => {
let $scope: any = $rootScope.$new();
$scope.modelValue = 'test';
let liteTextBox: angular.IAugmentedJQuery =
$compile('<uif-textfield ng-model="modelValue" placeholder="Placeholder contents"></uif-textfield>')($scope);
let textBox: JQuery = jQuery(liteTextBox[0]);
$scope.$digest();
let input: JQuery = textBox.find('input.ms-TextField-field');
input = jQuery(input);
let ngModelCtrl: angular.INgModelController = angular.element(textBox).controller('ngModel');
expect(ngModelCtrl.$touched).toBe(false);
angular.element(input).triggerHandler('blur');
$scope.$digest();
expect(ngModelCtrl.$touched).toBe(true);
}));
it(
'should allow to interpolate uif-type value',
inject((
$compile: angular.ICompileService,
$rootScope: angular.IRootScopeService,
$log: angular.ILogService) => {
let inputElement: JQuery = null;
let scope: any = $rootScope.$new();
let html: string = `<uif-textfield uif-label='some label' uif-type='{{type}}'></uif-textfield>`;
let element: JQuery = angular.element(html);
scope.type = 'password';
// compile with scope = password
$compile(element)(scope);
scope.$digest();
element = jQuery(element[0]);
// test that password is listed
inputElement = element.find('input');
expect(inputElement.attr('type')).toBe('password');
// change scope
scope.type = 'number';
// compile with scope = password
scope.$digest();
element = jQuery(element[0]);
// test that password is listed
inputElement = element.find('input');
expect(inputElement.attr('type')).toBe('number');
})
);
}); | the_stack |
/// <reference types="long" />
import * as $protobuf from 'protobufjs';
/** Properties of a BatchHeader. */
export interface IBatchHeader {
/** BatchHeader signerPublicKey */
signerPublicKey?: string | null | undefined;
/** BatchHeader transactionIds */
transactionIds?: string[] | null | undefined;
}
/** Represents a BatchHeader. */
export class BatchHeader implements IBatchHeader {
/**
* Constructs a new BatchHeader.
* @param [properties] Properties to set
*/
constructor(properties?: IBatchHeader);
/** BatchHeader signerPublicKey. */
public signerPublicKey: string;
/** BatchHeader transactionIds. */
public transactionIds: string[];
/**
* Creates a new BatchHeader instance using the specified properties.
* @param [properties] Properties to set
* @returns BatchHeader instance
*/
public static create(properties?: IBatchHeader): BatchHeader;
/**
* Encodes the specified BatchHeader message. Does not implicitly {@link BatchHeader.verify|verify} messages.
* @param message BatchHeader message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IBatchHeader, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified BatchHeader message, length delimited. Does not implicitly {@link BatchHeader.verify|verify} messages.
* @param message BatchHeader message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IBatchHeader, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a BatchHeader message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns BatchHeader
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): BatchHeader;
/**
* Decodes a BatchHeader message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns BatchHeader
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): BatchHeader;
/**
* Verifies a BatchHeader message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a BatchHeader message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns BatchHeader
*/
public static fromObject(object: { [k: string]: any }): BatchHeader;
/**
* Creates a plain object from a BatchHeader message. Also converts values to other types if specified.
* @param message BatchHeader
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: BatchHeader, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this BatchHeader to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Batch. */
export interface IBatch {
/** Batch header */
header?: Uint8Array | null | undefined;
/** Batch headerSignature */
headerSignature?: string | null | undefined;
/** Batch transactions */
transactions?: ITransaction[] | null | undefined;
/** Batch trace */
trace?: boolean | null | undefined;
}
/** Represents a Batch. */
export class Batch implements IBatch {
/**
* Constructs a new Batch.
* @param [properties] Properties to set
*/
constructor(properties?: IBatch);
/** Batch header. */
public header: Uint8Array;
/** Batch headerSignature. */
public headerSignature: string;
/** Batch transactions. */
public transactions: ITransaction[];
/** Batch trace. */
public trace: boolean;
/**
* Creates a new Batch instance using the specified properties.
* @param [properties] Properties to set
* @returns Batch instance
*/
public static create(properties?: IBatch): Batch;
/**
* Encodes the specified Batch message. Does not implicitly {@link Batch.verify|verify} messages.
* @param message Batch message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IBatch, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Batch message, length delimited. Does not implicitly {@link Batch.verify|verify} messages.
* @param message Batch message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IBatch, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Batch message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Batch
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): Batch;
/**
* Decodes a Batch message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Batch
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): Batch;
/**
* Verifies a Batch message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a Batch message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Batch
*/
public static fromObject(object: { [k: string]: any }): Batch;
/**
* Creates a plain object from a Batch message. Also converts values to other types if specified.
* @param message Batch
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: Batch, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Batch to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a BatchList. */
export interface IBatchList {
/** BatchList batches */
batches?: IBatch[] | null | undefined;
}
/** Represents a BatchList. */
export class BatchList implements IBatchList {
/**
* Constructs a new BatchList.
* @param [properties] Properties to set
*/
constructor(properties?: IBatchList);
/** BatchList batches. */
public batches: IBatch[];
/**
* Creates a new BatchList instance using the specified properties.
* @param [properties] Properties to set
* @returns BatchList instance
*/
public static create(properties?: IBatchList): BatchList;
/**
* Encodes the specified BatchList message. Does not implicitly {@link BatchList.verify|verify} messages.
* @param message BatchList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IBatchList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified BatchList message, length delimited. Does not implicitly {@link BatchList.verify|verify} messages.
* @param message BatchList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IBatchList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a BatchList message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns BatchList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): BatchList;
/**
* Decodes a BatchList message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns BatchList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): BatchList;
/**
* Verifies a BatchList message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a BatchList message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns BatchList
*/
public static fromObject(object: { [k: string]: any }): BatchList;
/**
* Creates a plain object from a BatchList message. Also converts values to other types if specified.
* @param message BatchList
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: BatchList, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this BatchList to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a TransactionHeader. */
export interface ITransactionHeader {
/** TransactionHeader batcherPublicKey */
batcherPublicKey?: string | null | undefined;
/** TransactionHeader dependencies */
dependencies?: string[] | null | undefined;
/** TransactionHeader familyName */
familyName?: string | null | undefined;
/** TransactionHeader familyVersion */
familyVersion?: string | null | undefined;
/** TransactionHeader inputs */
inputs?: string[] | null | undefined;
/** TransactionHeader nonce */
nonce?: string | null | undefined;
/** TransactionHeader outputs */
outputs?: string[] | null | undefined;
/** TransactionHeader payloadSha512 */
payloadSha512?: string | null | undefined;
/** TransactionHeader signerPublicKey */
signerPublicKey?: string | null | undefined;
}
/** Represents a TransactionHeader. */
export class TransactionHeader implements ITransactionHeader {
/**
* Constructs a new TransactionHeader.
* @param [properties] Properties to set
*/
constructor(properties?: ITransactionHeader);
/** TransactionHeader batcherPublicKey. */
public batcherPublicKey: string;
/** TransactionHeader dependencies. */
public dependencies: string[];
/** TransactionHeader familyName. */
public familyName: string;
/** TransactionHeader familyVersion. */
public familyVersion: string;
/** TransactionHeader inputs. */
public inputs: string[];
/** TransactionHeader nonce. */
public nonce: string;
/** TransactionHeader outputs. */
public outputs: string[];
/** TransactionHeader payloadSha512. */
public payloadSha512: string;
/** TransactionHeader signerPublicKey. */
public signerPublicKey: string;
/**
* Creates a new TransactionHeader instance using the specified properties.
* @param [properties] Properties to set
* @returns TransactionHeader instance
*/
public static create(properties?: ITransactionHeader): TransactionHeader;
/**
* Encodes the specified TransactionHeader message. Does not implicitly {@link TransactionHeader.verify|verify} messages.
* @param message TransactionHeader message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ITransactionHeader, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TransactionHeader message, length delimited. Does not implicitly {@link TransactionHeader.verify|verify} messages.
* @param message TransactionHeader message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ITransactionHeader, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TransactionHeader message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TransactionHeader
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): TransactionHeader;
/**
* Decodes a TransactionHeader message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TransactionHeader
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): TransactionHeader;
/**
* Verifies a TransactionHeader message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a TransactionHeader message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TransactionHeader
*/
public static fromObject(object: { [k: string]: any }): TransactionHeader;
/**
* Creates a plain object from a TransactionHeader message. Also converts values to other types if specified.
* @param message TransactionHeader
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: TransactionHeader, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TransactionHeader to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Transaction. */
export interface ITransaction {
/** Transaction header */
header?: Uint8Array | null | undefined;
/** Transaction headerSignature */
headerSignature?: string | null | undefined;
/** Transaction payload */
payload?: Uint8Array | null | undefined;
}
/** Represents a Transaction. */
export class Transaction implements ITransaction {
/**
* Constructs a new Transaction.
* @param [properties] Properties to set
*/
constructor(properties?: ITransaction);
/** Transaction header. */
public header: Uint8Array;
/** Transaction headerSignature. */
public headerSignature: string;
/** Transaction payload. */
public payload: Uint8Array;
/**
* Creates a new Transaction instance using the specified properties.
* @param [properties] Properties to set
* @returns Transaction instance
*/
public static create(properties?: ITransaction): Transaction;
/**
* Encodes the specified Transaction message. Does not implicitly {@link Transaction.verify|verify} messages.
* @param message Transaction message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ITransaction, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Transaction message, length delimited. Does not implicitly {@link Transaction.verify|verify} messages.
* @param message Transaction message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ITransaction, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Transaction message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Transaction
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): Transaction;
/**
* Decodes a Transaction message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Transaction
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): Transaction;
/**
* Verifies a Transaction message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a Transaction message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Transaction
*/
public static fromObject(object: { [k: string]: any }): Transaction;
/**
* Creates a plain object from a Transaction message. Also converts values to other types if specified.
* @param message Transaction
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: Transaction, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Transaction to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a TransactionList. */
export interface ITransactionList {
/** TransactionList transactions */
transactions?: ITransaction[] | null | undefined;
}
/** Represents a TransactionList. */
export class TransactionList implements ITransactionList {
/**
* Constructs a new TransactionList.
* @param [properties] Properties to set
*/
constructor(properties?: ITransactionList);
/** TransactionList transactions. */
public transactions: ITransaction[];
/**
* Creates a new TransactionList instance using the specified properties.
* @param [properties] Properties to set
* @returns TransactionList instance
*/
public static create(properties?: ITransactionList): TransactionList;
/**
* Encodes the specified TransactionList message. Does not implicitly {@link TransactionList.verify|verify} messages.
* @param message TransactionList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ITransactionList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TransactionList message, length delimited. Does not implicitly {@link TransactionList.verify|verify} messages.
* @param message TransactionList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ITransactionList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TransactionList message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TransactionList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): TransactionList;
/**
* Decodes a TransactionList message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TransactionList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): TransactionList;
/**
* Verifies a TransactionList message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a TransactionList message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TransactionList
*/
public static fromObject(object: { [k: string]: any }): TransactionList;
/**
* Creates a plain object from a TransactionList message. Also converts values to other types if specified.
* @param message TransactionList
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: TransactionList, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TransactionList to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a BlockHeader. */
export interface IBlockHeader {
/** BlockHeader blockNum */
blockNum?: number | Long | null | undefined;
/** BlockHeader previousBlockId */
previousBlockId?: string | null | undefined;
/** BlockHeader signerPublicKey */
signerPublicKey?: string | null | undefined;
/** BlockHeader batchIds */
batchIds?: string[] | null | undefined;
/** BlockHeader consensus */
consensus?: Uint8Array | null | undefined;
/** BlockHeader stateRootHash */
stateRootHash?: string | null | undefined;
}
/** Represents a BlockHeader. */
export class BlockHeader implements IBlockHeader {
/**
* Constructs a new BlockHeader.
* @param [properties] Properties to set
*/
constructor(properties?: IBlockHeader);
/** BlockHeader blockNum. */
public blockNum: number | Long;
/** BlockHeader previousBlockId. */
public previousBlockId: string;
/** BlockHeader signerPublicKey. */
public signerPublicKey: string;
/** BlockHeader batchIds. */
public batchIds: string[];
/** BlockHeader consensus. */
public consensus: Uint8Array;
/** BlockHeader stateRootHash. */
public stateRootHash: string;
/**
* Creates a new BlockHeader instance using the specified properties.
* @param [properties] Properties to set
* @returns BlockHeader instance
*/
public static create(properties?: IBlockHeader): BlockHeader;
/**
* Encodes the specified BlockHeader message. Does not implicitly {@link BlockHeader.verify|verify} messages.
* @param message BlockHeader message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IBlockHeader, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified BlockHeader message, length delimited. Does not implicitly {@link BlockHeader.verify|verify} messages.
* @param message BlockHeader message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IBlockHeader, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a BlockHeader message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns BlockHeader
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): BlockHeader;
/**
* Decodes a BlockHeader message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns BlockHeader
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): BlockHeader;
/**
* Verifies a BlockHeader message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a BlockHeader message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns BlockHeader
*/
public static fromObject(object: { [k: string]: any }): BlockHeader;
/**
* Creates a plain object from a BlockHeader message. Also converts values to other types if specified.
* @param message BlockHeader
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: BlockHeader, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this BlockHeader to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Block. */
export interface IBlock {
/** Block header */
header?: Uint8Array | null | undefined;
/** Block headerSignature */
headerSignature?: string | null | undefined;
/** Block batches */
batches?: IBatch[] | null | undefined;
}
/** Represents a Block. */
export class Block implements IBlock {
/**
* Constructs a new Block.
* @param [properties] Properties to set
*/
constructor(properties?: IBlock);
/** Block header. */
public header: Uint8Array;
/** Block headerSignature. */
public headerSignature: string;
/** Block batches. */
public batches: IBatch[];
/**
* Creates a new Block instance using the specified properties.
* @param [properties] Properties to set
* @returns Block instance
*/
public static create(properties?: IBlock): Block;
/**
* Encodes the specified Block message. Does not implicitly {@link Block.verify|verify} messages.
* @param message Block message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IBlock, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Block message, length delimited. Does not implicitly {@link Block.verify|verify} messages.
* @param message Block message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IBlock, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Block message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Block
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): Block;
/**
* Decodes a Block message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Block
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): Block;
/**
* Verifies a Block message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a Block message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Block
*/
public static fromObject(object: { [k: string]: any }): Block;
/**
* Creates a plain object from a Block message. Also converts values to other types if specified.
* @param message Block
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: Block, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Block to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientBatchListRequest. */
export interface IClientBatchListRequest {
/** ClientBatchListRequest headId */
headId?: string | null | undefined;
/** ClientBatchListRequest batchIds */
batchIds?: string[] | null | undefined;
/** ClientBatchListRequest paging */
paging?: IClientPagingControls | null | undefined;
/** ClientBatchListRequest sorting */
sorting?: IClientSortControls[] | null | undefined;
}
/** Represents a ClientBatchListRequest. */
export class ClientBatchListRequest implements IClientBatchListRequest {
/**
* Constructs a new ClientBatchListRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IClientBatchListRequest);
/** ClientBatchListRequest headId. */
public headId: string;
/** ClientBatchListRequest batchIds. */
public batchIds: string[];
/** ClientBatchListRequest paging. */
public paging?: IClientPagingControls | null | undefined;
/** ClientBatchListRequest sorting. */
public sorting: IClientSortControls[];
/**
* Creates a new ClientBatchListRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientBatchListRequest instance
*/
public static create(properties?: IClientBatchListRequest): ClientBatchListRequest;
/**
* Encodes the specified ClientBatchListRequest message. Does not implicitly {@link ClientBatchListRequest.verify|verify} messages.
* @param message ClientBatchListRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientBatchListRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientBatchListRequest message, length delimited. Does not implicitly {@link ClientBatchListRequest.verify|verify} messages.
* @param message ClientBatchListRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientBatchListRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientBatchListRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientBatchListRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientBatchListRequest;
/**
* Decodes a ClientBatchListRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientBatchListRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientBatchListRequest;
/**
* Verifies a ClientBatchListRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientBatchListRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientBatchListRequest
*/
public static fromObject(object: { [k: string]: any }): ClientBatchListRequest;
/**
* Creates a plain object from a ClientBatchListRequest message. Also converts values to other types if specified.
* @param message ClientBatchListRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientBatchListRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientBatchListRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientBatchListResponse. */
export interface IClientBatchListResponse {
/** ClientBatchListResponse status */
status?: ClientBatchListResponse.Status | null | undefined;
/** ClientBatchListResponse batches */
batches?: IBatch[] | null | undefined;
/** ClientBatchListResponse headId */
headId?: string | null | undefined;
/** ClientBatchListResponse paging */
paging?: IClientPagingResponse | null | undefined;
}
/** Represents a ClientBatchListResponse. */
export class ClientBatchListResponse implements IClientBatchListResponse {
/**
* Constructs a new ClientBatchListResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IClientBatchListResponse);
/** ClientBatchListResponse status. */
public status: ClientBatchListResponse.Status;
/** ClientBatchListResponse batches. */
public batches: IBatch[];
/** ClientBatchListResponse headId. */
public headId: string;
/** ClientBatchListResponse paging. */
public paging?: IClientPagingResponse | null | undefined;
/**
* Creates a new ClientBatchListResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientBatchListResponse instance
*/
public static create(properties?: IClientBatchListResponse): ClientBatchListResponse;
/**
* Encodes the specified ClientBatchListResponse message. Does not implicitly {@link ClientBatchListResponse.verify|verify} messages.
* @param message ClientBatchListResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientBatchListResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientBatchListResponse message, length delimited. Does not implicitly {@link ClientBatchListResponse.verify|verify} messages.
* @param message ClientBatchListResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientBatchListResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientBatchListResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientBatchListResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientBatchListResponse;
/**
* Decodes a ClientBatchListResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientBatchListResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientBatchListResponse;
/**
* Verifies a ClientBatchListResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientBatchListResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientBatchListResponse
*/
public static fromObject(object: { [k: string]: any }): ClientBatchListResponse;
/**
* Creates a plain object from a ClientBatchListResponse message. Also converts values to other types if specified.
* @param message ClientBatchListResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientBatchListResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientBatchListResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ClientBatchListResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
INTERNAL_ERROR = 2,
NOT_READY = 3,
NO_ROOT = 4,
NO_RESOURCE = 5,
INVALID_PAGING = 6,
INVALID_SORT = 7,
INVALID_ID = 8,
}
}
/** Properties of a ClientBatchGetRequest. */
export interface IClientBatchGetRequest {
/** ClientBatchGetRequest batchId */
batchId?: string | null | undefined;
}
/** Represents a ClientBatchGetRequest. */
export class ClientBatchGetRequest implements IClientBatchGetRequest {
/**
* Constructs a new ClientBatchGetRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IClientBatchGetRequest);
/** ClientBatchGetRequest batchId. */
public batchId: string;
/**
* Creates a new ClientBatchGetRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientBatchGetRequest instance
*/
public static create(properties?: IClientBatchGetRequest): ClientBatchGetRequest;
/**
* Encodes the specified ClientBatchGetRequest message. Does not implicitly {@link ClientBatchGetRequest.verify|verify} messages.
* @param message ClientBatchGetRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientBatchGetRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientBatchGetRequest message, length delimited. Does not implicitly {@link ClientBatchGetRequest.verify|verify} messages.
* @param message ClientBatchGetRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientBatchGetRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientBatchGetRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientBatchGetRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientBatchGetRequest;
/**
* Decodes a ClientBatchGetRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientBatchGetRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientBatchGetRequest;
/**
* Verifies a ClientBatchGetRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientBatchGetRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientBatchGetRequest
*/
public static fromObject(object: { [k: string]: any }): ClientBatchGetRequest;
/**
* Creates a plain object from a ClientBatchGetRequest message. Also converts values to other types if specified.
* @param message ClientBatchGetRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientBatchGetRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientBatchGetRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientBatchGetResponse. */
export interface IClientBatchGetResponse {
/** ClientBatchGetResponse status */
status?: ClientBatchGetResponse.Status | null | undefined;
/** ClientBatchGetResponse batch */
batch?: IBatch | null | undefined;
}
/** Represents a ClientBatchGetResponse. */
export class ClientBatchGetResponse implements IClientBatchGetResponse {
/**
* Constructs a new ClientBatchGetResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IClientBatchGetResponse);
/** ClientBatchGetResponse status. */
public status: ClientBatchGetResponse.Status;
/** ClientBatchGetResponse batch. */
public batch?: IBatch | null | undefined;
/**
* Creates a new ClientBatchGetResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientBatchGetResponse instance
*/
public static create(properties?: IClientBatchGetResponse): ClientBatchGetResponse;
/**
* Encodes the specified ClientBatchGetResponse message. Does not implicitly {@link ClientBatchGetResponse.verify|verify} messages.
* @param message ClientBatchGetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientBatchGetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientBatchGetResponse message, length delimited. Does not implicitly {@link ClientBatchGetResponse.verify|verify} messages.
* @param message ClientBatchGetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientBatchGetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientBatchGetResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientBatchGetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientBatchGetResponse;
/**
* Decodes a ClientBatchGetResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientBatchGetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientBatchGetResponse;
/**
* Verifies a ClientBatchGetResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientBatchGetResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientBatchGetResponse
*/
public static fromObject(object: { [k: string]: any }): ClientBatchGetResponse;
/**
* Creates a plain object from a ClientBatchGetResponse message. Also converts values to other types if specified.
* @param message ClientBatchGetResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientBatchGetResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientBatchGetResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ClientBatchGetResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
INTERNAL_ERROR = 2,
NO_RESOURCE = 5,
INVALID_ID = 8,
}
}
/** Properties of a ClientPagingControls. */
export interface IClientPagingControls {
/** ClientPagingControls start */
start?: string | null | undefined;
/** ClientPagingControls limit */
limit?: number | null | undefined;
}
/** Represents a ClientPagingControls. */
export class ClientPagingControls implements IClientPagingControls {
/**
* Constructs a new ClientPagingControls.
* @param [properties] Properties to set
*/
constructor(properties?: IClientPagingControls);
/** ClientPagingControls start. */
public start: string;
/** ClientPagingControls limit. */
public limit: number;
/**
* Creates a new ClientPagingControls instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientPagingControls instance
*/
public static create(properties?: IClientPagingControls): ClientPagingControls;
/**
* Encodes the specified ClientPagingControls message. Does not implicitly {@link ClientPagingControls.verify|verify} messages.
* @param message ClientPagingControls message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientPagingControls, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientPagingControls message, length delimited. Does not implicitly {@link ClientPagingControls.verify|verify} messages.
* @param message ClientPagingControls message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientPagingControls, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientPagingControls message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientPagingControls
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientPagingControls;
/**
* Decodes a ClientPagingControls message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientPagingControls
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientPagingControls;
/**
* Verifies a ClientPagingControls message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientPagingControls message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientPagingControls
*/
public static fromObject(object: { [k: string]: any }): ClientPagingControls;
/**
* Creates a plain object from a ClientPagingControls message. Also converts values to other types if specified.
* @param message ClientPagingControls
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ClientPagingControls, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ClientPagingControls to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientPagingResponse. */
export interface IClientPagingResponse {
/** ClientPagingResponse next */
next?: string | null | undefined;
/** ClientPagingResponse start */
start?: string | null | undefined;
/** ClientPagingResponse limit */
limit?: number | null | undefined;
}
/** Represents a ClientPagingResponse. */
export class ClientPagingResponse implements IClientPagingResponse {
/**
* Constructs a new ClientPagingResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IClientPagingResponse);
/** ClientPagingResponse next. */
public next: string;
/** ClientPagingResponse start. */
public start: string;
/** ClientPagingResponse limit. */
public limit: number;
/**
* Creates a new ClientPagingResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientPagingResponse instance
*/
public static create(properties?: IClientPagingResponse): ClientPagingResponse;
/**
* Encodes the specified ClientPagingResponse message. Does not implicitly {@link ClientPagingResponse.verify|verify} messages.
* @param message ClientPagingResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientPagingResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientPagingResponse message, length delimited. Does not implicitly {@link ClientPagingResponse.verify|verify} messages.
* @param message ClientPagingResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientPagingResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientPagingResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientPagingResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientPagingResponse;
/**
* Decodes a ClientPagingResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientPagingResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientPagingResponse;
/**
* Verifies a ClientPagingResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientPagingResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientPagingResponse
*/
public static fromObject(object: { [k: string]: any }): ClientPagingResponse;
/**
* Creates a plain object from a ClientPagingResponse message. Also converts values to other types if specified.
* @param message ClientPagingResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ClientPagingResponse, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ClientPagingResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientSortControls. */
export interface IClientSortControls {
/** ClientSortControls keys */
keys?: string[] | null | undefined;
/** ClientSortControls reverse */
reverse?: boolean | null | undefined;
}
/** Represents a ClientSortControls. */
export class ClientSortControls implements IClientSortControls {
/**
* Constructs a new ClientSortControls.
* @param [properties] Properties to set
*/
constructor(properties?: IClientSortControls);
/** ClientSortControls keys. */
public keys: string[];
/** ClientSortControls reverse. */
public reverse: boolean;
/**
* Creates a new ClientSortControls instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientSortControls instance
*/
public static create(properties?: IClientSortControls): ClientSortControls;
/**
* Encodes the specified ClientSortControls message. Does not implicitly {@link ClientSortControls.verify|verify} messages.
* @param message ClientSortControls message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientSortControls, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientSortControls message, length delimited. Does not implicitly {@link ClientSortControls.verify|verify} messages.
* @param message ClientSortControls message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientSortControls, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientSortControls message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientSortControls
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientSortControls;
/**
* Decodes a ClientSortControls message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientSortControls
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientSortControls;
/**
* Verifies a ClientSortControls message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientSortControls message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientSortControls
*/
public static fromObject(object: { [k: string]: any }): ClientSortControls;
/**
* Creates a plain object from a ClientSortControls message. Also converts values to other types if specified.
* @param message ClientSortControls
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ClientSortControls, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ClientSortControls to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientBatchStatus. */
export interface IClientBatchStatus {
/** ClientBatchStatus batchId */
batchId?: string | null | undefined;
/** ClientBatchStatus status */
status?: ClientBatchStatus.Status | null | undefined;
/** ClientBatchStatus invalidTransactions */
invalidTransactions?: ClientBatchStatus.IInvalidTransaction[] | null | undefined;
}
/** Represents a ClientBatchStatus. */
export class ClientBatchStatus implements IClientBatchStatus {
/**
* Constructs a new ClientBatchStatus.
* @param [properties] Properties to set
*/
constructor(properties?: IClientBatchStatus);
/** ClientBatchStatus batchId. */
public batchId: string;
/** ClientBatchStatus status. */
public status: ClientBatchStatus.Status;
/** ClientBatchStatus invalidTransactions. */
public invalidTransactions: ClientBatchStatus.IInvalidTransaction[];
/**
* Creates a new ClientBatchStatus instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientBatchStatus instance
*/
public static create(properties?: IClientBatchStatus): ClientBatchStatus;
/**
* Encodes the specified ClientBatchStatus message. Does not implicitly {@link ClientBatchStatus.verify|verify} messages.
* @param message ClientBatchStatus message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientBatchStatus, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientBatchStatus message, length delimited. Does not implicitly {@link ClientBatchStatus.verify|verify} messages.
* @param message ClientBatchStatus message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientBatchStatus, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientBatchStatus message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientBatchStatus
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientBatchStatus;
/**
* Decodes a ClientBatchStatus message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientBatchStatus
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientBatchStatus;
/**
* Verifies a ClientBatchStatus message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientBatchStatus message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientBatchStatus
*/
public static fromObject(object: { [k: string]: any }): ClientBatchStatus;
/**
* Creates a plain object from a ClientBatchStatus message. Also converts values to other types if specified.
* @param message ClientBatchStatus
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ClientBatchStatus, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ClientBatchStatus to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ClientBatchStatus {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
COMMITTED = 1,
INVALID = 2,
PENDING = 3,
UNKNOWN = 4,
}
/** Properties of an InvalidTransaction. */
interface IInvalidTransaction {
/** InvalidTransaction transactionId */
transactionId?: string | null | undefined;
/** InvalidTransaction message */
message?: string | null | undefined;
/** InvalidTransaction extendedData */
extendedData?: Uint8Array | null | undefined;
}
/** Represents an InvalidTransaction. */
class InvalidTransaction implements IInvalidTransaction {
/**
* Constructs a new InvalidTransaction.
* @param [properties] Properties to set
*/
constructor(properties?: ClientBatchStatus.IInvalidTransaction);
/** InvalidTransaction transactionId. */
public transactionId: string;
/** InvalidTransaction message. */
public message: string;
/** InvalidTransaction extendedData. */
public extendedData: Uint8Array;
/**
* Creates a new InvalidTransaction instance using the specified properties.
* @param [properties] Properties to set
* @returns InvalidTransaction instance
*/
public static create(properties?: ClientBatchStatus.IInvalidTransaction): ClientBatchStatus.InvalidTransaction;
/**
* Encodes the specified InvalidTransaction message. Does not implicitly {@link ClientBatchStatus.InvalidTransaction.verify|verify} messages.
* @param message InvalidTransaction message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(
message: ClientBatchStatus.IInvalidTransaction,
writer?: $protobuf.Writer,
): $protobuf.Writer;
/**
* Encodes the specified InvalidTransaction message, length delimited. Does not implicitly {@link ClientBatchStatus.InvalidTransaction.verify|verify} messages.
* @param message InvalidTransaction message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(
message: ClientBatchStatus.IInvalidTransaction,
writer?: $protobuf.Writer,
): $protobuf.Writer;
/**
* Decodes an InvalidTransaction message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns InvalidTransaction
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(
reader: $protobuf.Reader | Uint8Array,
length?: number,
): ClientBatchStatus.InvalidTransaction;
/**
* Decodes an InvalidTransaction message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns InvalidTransaction
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientBatchStatus.InvalidTransaction;
/**
* Verifies an InvalidTransaction message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates an InvalidTransaction message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns InvalidTransaction
*/
public static fromObject(object: { [k: string]: any }): ClientBatchStatus.InvalidTransaction;
/**
* Creates a plain object from an InvalidTransaction message. Also converts values to other types if specified.
* @param message InvalidTransaction
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientBatchStatus.InvalidTransaction,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this InvalidTransaction to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a ClientBatchSubmitRequest. */
export interface IClientBatchSubmitRequest {
/** ClientBatchSubmitRequest batches */
batches?: IBatch[] | null | undefined;
}
/** Represents a ClientBatchSubmitRequest. */
export class ClientBatchSubmitRequest implements IClientBatchSubmitRequest {
/**
* Constructs a new ClientBatchSubmitRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IClientBatchSubmitRequest);
/** ClientBatchSubmitRequest batches. */
public batches: IBatch[];
/**
* Creates a new ClientBatchSubmitRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientBatchSubmitRequest instance
*/
public static create(properties?: IClientBatchSubmitRequest): ClientBatchSubmitRequest;
/**
* Encodes the specified ClientBatchSubmitRequest message. Does not implicitly {@link ClientBatchSubmitRequest.verify|verify} messages.
* @param message ClientBatchSubmitRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientBatchSubmitRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientBatchSubmitRequest message, length delimited. Does not implicitly {@link ClientBatchSubmitRequest.verify|verify} messages.
* @param message ClientBatchSubmitRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientBatchSubmitRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientBatchSubmitRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientBatchSubmitRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientBatchSubmitRequest;
/**
* Decodes a ClientBatchSubmitRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientBatchSubmitRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientBatchSubmitRequest;
/**
* Verifies a ClientBatchSubmitRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientBatchSubmitRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientBatchSubmitRequest
*/
public static fromObject(object: { [k: string]: any }): ClientBatchSubmitRequest;
/**
* Creates a plain object from a ClientBatchSubmitRequest message. Also converts values to other types if specified.
* @param message ClientBatchSubmitRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientBatchSubmitRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientBatchSubmitRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientBatchSubmitResponse. */
export interface IClientBatchSubmitResponse {
/** ClientBatchSubmitResponse status */
status?: ClientBatchSubmitResponse.Status | null | undefined;
}
/** Represents a ClientBatchSubmitResponse. */
export class ClientBatchSubmitResponse implements IClientBatchSubmitResponse {
/**
* Constructs a new ClientBatchSubmitResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IClientBatchSubmitResponse);
/** ClientBatchSubmitResponse status. */
public status: ClientBatchSubmitResponse.Status;
/**
* Creates a new ClientBatchSubmitResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientBatchSubmitResponse instance
*/
public static create(properties?: IClientBatchSubmitResponse): ClientBatchSubmitResponse;
/**
* Encodes the specified ClientBatchSubmitResponse message. Does not implicitly {@link ClientBatchSubmitResponse.verify|verify} messages.
* @param message ClientBatchSubmitResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientBatchSubmitResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientBatchSubmitResponse message, length delimited. Does not implicitly {@link ClientBatchSubmitResponse.verify|verify} messages.
* @param message ClientBatchSubmitResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientBatchSubmitResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientBatchSubmitResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientBatchSubmitResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientBatchSubmitResponse;
/**
* Decodes a ClientBatchSubmitResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientBatchSubmitResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientBatchSubmitResponse;
/**
* Verifies a ClientBatchSubmitResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientBatchSubmitResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientBatchSubmitResponse
*/
public static fromObject(object: { [k: string]: any }): ClientBatchSubmitResponse;
/**
* Creates a plain object from a ClientBatchSubmitResponse message. Also converts values to other types if specified.
* @param message ClientBatchSubmitResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientBatchSubmitResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientBatchSubmitResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ClientBatchSubmitResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
INTERNAL_ERROR = 2,
INVALID_BATCH = 3,
QUEUE_FULL = 4,
}
}
/** Properties of a ClientBatchStatusRequest. */
export interface IClientBatchStatusRequest {
/** ClientBatchStatusRequest batchIds */
batchIds?: string[] | null | undefined;
/** ClientBatchStatusRequest wait */
wait?: boolean | null | undefined;
/** ClientBatchStatusRequest timeout */
timeout?: number | null | undefined;
}
/** Represents a ClientBatchStatusRequest. */
export class ClientBatchStatusRequest implements IClientBatchStatusRequest {
/**
* Constructs a new ClientBatchStatusRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IClientBatchStatusRequest);
/** ClientBatchStatusRequest batchIds. */
public batchIds: string[];
/** ClientBatchStatusRequest wait. */
public wait: boolean;
/** ClientBatchStatusRequest timeout. */
public timeout: number;
/**
* Creates a new ClientBatchStatusRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientBatchStatusRequest instance
*/
public static create(properties?: IClientBatchStatusRequest): ClientBatchStatusRequest;
/**
* Encodes the specified ClientBatchStatusRequest message. Does not implicitly {@link ClientBatchStatusRequest.verify|verify} messages.
* @param message ClientBatchStatusRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientBatchStatusRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientBatchStatusRequest message, length delimited. Does not implicitly {@link ClientBatchStatusRequest.verify|verify} messages.
* @param message ClientBatchStatusRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientBatchStatusRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientBatchStatusRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientBatchStatusRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientBatchStatusRequest;
/**
* Decodes a ClientBatchStatusRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientBatchStatusRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientBatchStatusRequest;
/**
* Verifies a ClientBatchStatusRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientBatchStatusRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientBatchStatusRequest
*/
public static fromObject(object: { [k: string]: any }): ClientBatchStatusRequest;
/**
* Creates a plain object from a ClientBatchStatusRequest message. Also converts values to other types if specified.
* @param message ClientBatchStatusRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientBatchStatusRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientBatchStatusRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientBatchStatusResponse. */
export interface IClientBatchStatusResponse {
/** ClientBatchStatusResponse status */
status?: ClientBatchStatusResponse.Status | null | undefined;
/** ClientBatchStatusResponse batchStatuses */
batchStatuses?: IClientBatchStatus[] | null | undefined;
}
/** Represents a ClientBatchStatusResponse. */
export class ClientBatchStatusResponse implements IClientBatchStatusResponse {
/**
* Constructs a new ClientBatchStatusResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IClientBatchStatusResponse);
/** ClientBatchStatusResponse status. */
public status: ClientBatchStatusResponse.Status;
/** ClientBatchStatusResponse batchStatuses. */
public batchStatuses: IClientBatchStatus[];
/**
* Creates a new ClientBatchStatusResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientBatchStatusResponse instance
*/
public static create(properties?: IClientBatchStatusResponse): ClientBatchStatusResponse;
/**
* Encodes the specified ClientBatchStatusResponse message. Does not implicitly {@link ClientBatchStatusResponse.verify|verify} messages.
* @param message ClientBatchStatusResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientBatchStatusResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientBatchStatusResponse message, length delimited. Does not implicitly {@link ClientBatchStatusResponse.verify|verify} messages.
* @param message ClientBatchStatusResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientBatchStatusResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientBatchStatusResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientBatchStatusResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientBatchStatusResponse;
/**
* Decodes a ClientBatchStatusResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientBatchStatusResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientBatchStatusResponse;
/**
* Verifies a ClientBatchStatusResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientBatchStatusResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientBatchStatusResponse
*/
public static fromObject(object: { [k: string]: any }): ClientBatchStatusResponse;
/**
* Creates a plain object from a ClientBatchStatusResponse message. Also converts values to other types if specified.
* @param message ClientBatchStatusResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientBatchStatusResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientBatchStatusResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ClientBatchStatusResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
INTERNAL_ERROR = 2,
NO_RESOURCE = 5,
INVALID_ID = 8,
}
}
/** Properties of a ClientBlockListRequest. */
export interface IClientBlockListRequest {
/** ClientBlockListRequest headId */
headId?: string | null | undefined;
/** ClientBlockListRequest blockIds */
blockIds?: string[] | null | undefined;
/** ClientBlockListRequest paging */
paging?: IClientPagingControls | null | undefined;
/** ClientBlockListRequest sorting */
sorting?: IClientSortControls[] | null | undefined;
}
/** Represents a ClientBlockListRequest. */
export class ClientBlockListRequest implements IClientBlockListRequest {
/**
* Constructs a new ClientBlockListRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IClientBlockListRequest);
/** ClientBlockListRequest headId. */
public headId: string;
/** ClientBlockListRequest blockIds. */
public blockIds: string[];
/** ClientBlockListRequest paging. */
public paging?: IClientPagingControls | null | undefined;
/** ClientBlockListRequest sorting. */
public sorting: IClientSortControls[];
/**
* Creates a new ClientBlockListRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientBlockListRequest instance
*/
public static create(properties?: IClientBlockListRequest): ClientBlockListRequest;
/**
* Encodes the specified ClientBlockListRequest message. Does not implicitly {@link ClientBlockListRequest.verify|verify} messages.
* @param message ClientBlockListRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientBlockListRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientBlockListRequest message, length delimited. Does not implicitly {@link ClientBlockListRequest.verify|verify} messages.
* @param message ClientBlockListRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientBlockListRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientBlockListRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientBlockListRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientBlockListRequest;
/**
* Decodes a ClientBlockListRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientBlockListRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientBlockListRequest;
/**
* Verifies a ClientBlockListRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientBlockListRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientBlockListRequest
*/
public static fromObject(object: { [k: string]: any }): ClientBlockListRequest;
/**
* Creates a plain object from a ClientBlockListRequest message. Also converts values to other types if specified.
* @param message ClientBlockListRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientBlockListRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientBlockListRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientBlockListResponse. */
export interface IClientBlockListResponse {
/** ClientBlockListResponse status */
status?: ClientBlockListResponse.Status | null | undefined;
/** ClientBlockListResponse blocks */
blocks?: IBlock[] | null | undefined;
/** ClientBlockListResponse headId */
headId?: string | null | undefined;
/** ClientBlockListResponse paging */
paging?: IClientPagingResponse | null | undefined;
}
/** Represents a ClientBlockListResponse. */
export class ClientBlockListResponse implements IClientBlockListResponse {
/**
* Constructs a new ClientBlockListResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IClientBlockListResponse);
/** ClientBlockListResponse status. */
public status: ClientBlockListResponse.Status;
/** ClientBlockListResponse blocks. */
public blocks: IBlock[];
/** ClientBlockListResponse headId. */
public headId: string;
/** ClientBlockListResponse paging. */
public paging?: IClientPagingResponse | null | undefined;
/**
* Creates a new ClientBlockListResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientBlockListResponse instance
*/
public static create(properties?: IClientBlockListResponse): ClientBlockListResponse;
/**
* Encodes the specified ClientBlockListResponse message. Does not implicitly {@link ClientBlockListResponse.verify|verify} messages.
* @param message ClientBlockListResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientBlockListResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientBlockListResponse message, length delimited. Does not implicitly {@link ClientBlockListResponse.verify|verify} messages.
* @param message ClientBlockListResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientBlockListResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientBlockListResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientBlockListResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientBlockListResponse;
/**
* Decodes a ClientBlockListResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientBlockListResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientBlockListResponse;
/**
* Verifies a ClientBlockListResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientBlockListResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientBlockListResponse
*/
public static fromObject(object: { [k: string]: any }): ClientBlockListResponse;
/**
* Creates a plain object from a ClientBlockListResponse message. Also converts values to other types if specified.
* @param message ClientBlockListResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientBlockListResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientBlockListResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ClientBlockListResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
INTERNAL_ERROR = 2,
NOT_READY = 3,
NO_ROOT = 4,
NO_RESOURCE = 5,
INVALID_PAGING = 6,
INVALID_SORT = 7,
INVALID_ID = 8,
}
}
/** Properties of a ClientBlockGetByIdRequest. */
export interface IClientBlockGetByIdRequest {
/** ClientBlockGetByIdRequest blockId */
blockId?: string | null | undefined;
}
/** Represents a ClientBlockGetByIdRequest. */
export class ClientBlockGetByIdRequest implements IClientBlockGetByIdRequest {
/**
* Constructs a new ClientBlockGetByIdRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IClientBlockGetByIdRequest);
/** ClientBlockGetByIdRequest blockId. */
public blockId: string;
/**
* Creates a new ClientBlockGetByIdRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientBlockGetByIdRequest instance
*/
public static create(properties?: IClientBlockGetByIdRequest): ClientBlockGetByIdRequest;
/**
* Encodes the specified ClientBlockGetByIdRequest message. Does not implicitly {@link ClientBlockGetByIdRequest.verify|verify} messages.
* @param message ClientBlockGetByIdRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientBlockGetByIdRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientBlockGetByIdRequest message, length delimited. Does not implicitly {@link ClientBlockGetByIdRequest.verify|verify} messages.
* @param message ClientBlockGetByIdRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientBlockGetByIdRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientBlockGetByIdRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientBlockGetByIdRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientBlockGetByIdRequest;
/**
* Decodes a ClientBlockGetByIdRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientBlockGetByIdRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientBlockGetByIdRequest;
/**
* Verifies a ClientBlockGetByIdRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientBlockGetByIdRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientBlockGetByIdRequest
*/
public static fromObject(object: { [k: string]: any }): ClientBlockGetByIdRequest;
/**
* Creates a plain object from a ClientBlockGetByIdRequest message. Also converts values to other types if specified.
* @param message ClientBlockGetByIdRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientBlockGetByIdRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientBlockGetByIdRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientBlockGetByNumRequest. */
export interface IClientBlockGetByNumRequest {
/** ClientBlockGetByNumRequest blockNum */
blockNum?: number | Long | null | undefined;
}
/** Represents a ClientBlockGetByNumRequest. */
export class ClientBlockGetByNumRequest implements IClientBlockGetByNumRequest {
/**
* Constructs a new ClientBlockGetByNumRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IClientBlockGetByNumRequest);
/** ClientBlockGetByNumRequest blockNum. */
public blockNum: number | Long;
/**
* Creates a new ClientBlockGetByNumRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientBlockGetByNumRequest instance
*/
public static create(properties?: IClientBlockGetByNumRequest): ClientBlockGetByNumRequest;
/**
* Encodes the specified ClientBlockGetByNumRequest message. Does not implicitly {@link ClientBlockGetByNumRequest.verify|verify} messages.
* @param message ClientBlockGetByNumRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientBlockGetByNumRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientBlockGetByNumRequest message, length delimited. Does not implicitly {@link ClientBlockGetByNumRequest.verify|verify} messages.
* @param message ClientBlockGetByNumRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientBlockGetByNumRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientBlockGetByNumRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientBlockGetByNumRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientBlockGetByNumRequest;
/**
* Decodes a ClientBlockGetByNumRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientBlockGetByNumRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientBlockGetByNumRequest;
/**
* Verifies a ClientBlockGetByNumRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientBlockGetByNumRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientBlockGetByNumRequest
*/
public static fromObject(object: { [k: string]: any }): ClientBlockGetByNumRequest;
/**
* Creates a plain object from a ClientBlockGetByNumRequest message. Also converts values to other types if specified.
* @param message ClientBlockGetByNumRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientBlockGetByNumRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientBlockGetByNumRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientBlockGetByTransactionIdRequest. */
export interface IClientBlockGetByTransactionIdRequest {
/** ClientBlockGetByTransactionIdRequest transactionId */
transactionId?: string | null | undefined;
}
/** Represents a ClientBlockGetByTransactionIdRequest. */
export class ClientBlockGetByTransactionIdRequest implements IClientBlockGetByTransactionIdRequest {
/**
* Constructs a new ClientBlockGetByTransactionIdRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IClientBlockGetByTransactionIdRequest);
/** ClientBlockGetByTransactionIdRequest transactionId. */
public transactionId: string;
/**
* Creates a new ClientBlockGetByTransactionIdRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientBlockGetByTransactionIdRequest instance
*/
public static create(properties?: IClientBlockGetByTransactionIdRequest): ClientBlockGetByTransactionIdRequest;
/**
* Encodes the specified ClientBlockGetByTransactionIdRequest message. Does not implicitly {@link ClientBlockGetByTransactionIdRequest.verify|verify} messages.
* @param message ClientBlockGetByTransactionIdRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientBlockGetByTransactionIdRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientBlockGetByTransactionIdRequest message, length delimited. Does not implicitly {@link ClientBlockGetByTransactionIdRequest.verify|verify} messages.
* @param message ClientBlockGetByTransactionIdRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(
message: IClientBlockGetByTransactionIdRequest,
writer?: $protobuf.Writer,
): $protobuf.Writer;
/**
* Decodes a ClientBlockGetByTransactionIdRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientBlockGetByTransactionIdRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientBlockGetByTransactionIdRequest;
/**
* Decodes a ClientBlockGetByTransactionIdRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientBlockGetByTransactionIdRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientBlockGetByTransactionIdRequest;
/**
* Verifies a ClientBlockGetByTransactionIdRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientBlockGetByTransactionIdRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientBlockGetByTransactionIdRequest
*/
public static fromObject(object: { [k: string]: any }): ClientBlockGetByTransactionIdRequest;
/**
* Creates a plain object from a ClientBlockGetByTransactionIdRequest message. Also converts values to other types if specified.
* @param message ClientBlockGetByTransactionIdRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientBlockGetByTransactionIdRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientBlockGetByTransactionIdRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientBlockGetByBatchIdRequest. */
export interface IClientBlockGetByBatchIdRequest {
/** ClientBlockGetByBatchIdRequest batchId */
batchId?: string | null | undefined;
}
/** Represents a ClientBlockGetByBatchIdRequest. */
export class ClientBlockGetByBatchIdRequest implements IClientBlockGetByBatchIdRequest {
/**
* Constructs a new ClientBlockGetByBatchIdRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IClientBlockGetByBatchIdRequest);
/** ClientBlockGetByBatchIdRequest batchId. */
public batchId: string;
/**
* Creates a new ClientBlockGetByBatchIdRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientBlockGetByBatchIdRequest instance
*/
public static create(properties?: IClientBlockGetByBatchIdRequest): ClientBlockGetByBatchIdRequest;
/**
* Encodes the specified ClientBlockGetByBatchIdRequest message. Does not implicitly {@link ClientBlockGetByBatchIdRequest.verify|verify} messages.
* @param message ClientBlockGetByBatchIdRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientBlockGetByBatchIdRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientBlockGetByBatchIdRequest message, length delimited. Does not implicitly {@link ClientBlockGetByBatchIdRequest.verify|verify} messages.
* @param message ClientBlockGetByBatchIdRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(
message: IClientBlockGetByBatchIdRequest,
writer?: $protobuf.Writer,
): $protobuf.Writer;
/**
* Decodes a ClientBlockGetByBatchIdRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientBlockGetByBatchIdRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientBlockGetByBatchIdRequest;
/**
* Decodes a ClientBlockGetByBatchIdRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientBlockGetByBatchIdRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientBlockGetByBatchIdRequest;
/**
* Verifies a ClientBlockGetByBatchIdRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientBlockGetByBatchIdRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientBlockGetByBatchIdRequest
*/
public static fromObject(object: { [k: string]: any }): ClientBlockGetByBatchIdRequest;
/**
* Creates a plain object from a ClientBlockGetByBatchIdRequest message. Also converts values to other types if specified.
* @param message ClientBlockGetByBatchIdRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientBlockGetByBatchIdRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientBlockGetByBatchIdRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientBlockGetResponse. */
export interface IClientBlockGetResponse {
/** ClientBlockGetResponse status */
status?: ClientBlockGetResponse.Status | null | undefined;
/** ClientBlockGetResponse block */
block?: IBlock | null | undefined;
}
/** Represents a ClientBlockGetResponse. */
export class ClientBlockGetResponse implements IClientBlockGetResponse {
/**
* Constructs a new ClientBlockGetResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IClientBlockGetResponse);
/** ClientBlockGetResponse status. */
public status: ClientBlockGetResponse.Status;
/** ClientBlockGetResponse block. */
public block?: IBlock | null | undefined;
/**
* Creates a new ClientBlockGetResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientBlockGetResponse instance
*/
public static create(properties?: IClientBlockGetResponse): ClientBlockGetResponse;
/**
* Encodes the specified ClientBlockGetResponse message. Does not implicitly {@link ClientBlockGetResponse.verify|verify} messages.
* @param message ClientBlockGetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientBlockGetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientBlockGetResponse message, length delimited. Does not implicitly {@link ClientBlockGetResponse.verify|verify} messages.
* @param message ClientBlockGetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientBlockGetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientBlockGetResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientBlockGetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientBlockGetResponse;
/**
* Decodes a ClientBlockGetResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientBlockGetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientBlockGetResponse;
/**
* Verifies a ClientBlockGetResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientBlockGetResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientBlockGetResponse
*/
public static fromObject(object: { [k: string]: any }): ClientBlockGetResponse;
/**
* Creates a plain object from a ClientBlockGetResponse message. Also converts values to other types if specified.
* @param message ClientBlockGetResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientBlockGetResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientBlockGetResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ClientBlockGetResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
INTERNAL_ERROR = 2,
NO_RESOURCE = 5,
INVALID_ID = 8,
}
}
/** Properties of a ClientEventsSubscribeRequest. */
export interface IClientEventsSubscribeRequest {
/** ClientEventsSubscribeRequest subscriptions */
subscriptions?: IEventSubscription[] | null | undefined;
/** ClientEventsSubscribeRequest lastKnownBlockIds */
lastKnownBlockIds?: string[] | null | undefined;
}
/** Represents a ClientEventsSubscribeRequest. */
export class ClientEventsSubscribeRequest implements IClientEventsSubscribeRequest {
/**
* Constructs a new ClientEventsSubscribeRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IClientEventsSubscribeRequest);
/** ClientEventsSubscribeRequest subscriptions. */
public subscriptions: IEventSubscription[];
/** ClientEventsSubscribeRequest lastKnownBlockIds. */
public lastKnownBlockIds: string[];
/**
* Creates a new ClientEventsSubscribeRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientEventsSubscribeRequest instance
*/
public static create(properties?: IClientEventsSubscribeRequest): ClientEventsSubscribeRequest;
/**
* Encodes the specified ClientEventsSubscribeRequest message. Does not implicitly {@link ClientEventsSubscribeRequest.verify|verify} messages.
* @param message ClientEventsSubscribeRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientEventsSubscribeRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientEventsSubscribeRequest message, length delimited. Does not implicitly {@link ClientEventsSubscribeRequest.verify|verify} messages.
* @param message ClientEventsSubscribeRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientEventsSubscribeRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientEventsSubscribeRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientEventsSubscribeRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientEventsSubscribeRequest;
/**
* Decodes a ClientEventsSubscribeRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientEventsSubscribeRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientEventsSubscribeRequest;
/**
* Verifies a ClientEventsSubscribeRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientEventsSubscribeRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientEventsSubscribeRequest
*/
public static fromObject(object: { [k: string]: any }): ClientEventsSubscribeRequest;
/**
* Creates a plain object from a ClientEventsSubscribeRequest message. Also converts values to other types if specified.
* @param message ClientEventsSubscribeRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientEventsSubscribeRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientEventsSubscribeRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientEventsSubscribeResponse. */
export interface IClientEventsSubscribeResponse {
/** ClientEventsSubscribeResponse status */
status?: ClientEventsSubscribeResponse.Status | null | undefined;
/** ClientEventsSubscribeResponse responseMessage */
responseMessage?: string | null | undefined;
}
/** Represents a ClientEventsSubscribeResponse. */
export class ClientEventsSubscribeResponse implements IClientEventsSubscribeResponse {
/**
* Constructs a new ClientEventsSubscribeResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IClientEventsSubscribeResponse);
/** ClientEventsSubscribeResponse status. */
public status: ClientEventsSubscribeResponse.Status;
/** ClientEventsSubscribeResponse responseMessage. */
public responseMessage: string;
/**
* Creates a new ClientEventsSubscribeResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientEventsSubscribeResponse instance
*/
public static create(properties?: IClientEventsSubscribeResponse): ClientEventsSubscribeResponse;
/**
* Encodes the specified ClientEventsSubscribeResponse message. Does not implicitly {@link ClientEventsSubscribeResponse.verify|verify} messages.
* @param message ClientEventsSubscribeResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientEventsSubscribeResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientEventsSubscribeResponse message, length delimited. Does not implicitly {@link ClientEventsSubscribeResponse.verify|verify} messages.
* @param message ClientEventsSubscribeResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientEventsSubscribeResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientEventsSubscribeResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientEventsSubscribeResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientEventsSubscribeResponse;
/**
* Decodes a ClientEventsSubscribeResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientEventsSubscribeResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientEventsSubscribeResponse;
/**
* Verifies a ClientEventsSubscribeResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientEventsSubscribeResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientEventsSubscribeResponse
*/
public static fromObject(object: { [k: string]: any }): ClientEventsSubscribeResponse;
/**
* Creates a plain object from a ClientEventsSubscribeResponse message. Also converts values to other types if specified.
* @param message ClientEventsSubscribeResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientEventsSubscribeResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientEventsSubscribeResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ClientEventsSubscribeResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
INVALID_FILTER = 2,
UNKNOWN_BLOCK = 3,
}
}
/** Properties of a ClientEventsUnsubscribeRequest. */
export interface IClientEventsUnsubscribeRequest {}
/** Represents a ClientEventsUnsubscribeRequest. */
export class ClientEventsUnsubscribeRequest implements IClientEventsUnsubscribeRequest {
/**
* Constructs a new ClientEventsUnsubscribeRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IClientEventsUnsubscribeRequest);
/**
* Creates a new ClientEventsUnsubscribeRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientEventsUnsubscribeRequest instance
*/
public static create(properties?: IClientEventsUnsubscribeRequest): ClientEventsUnsubscribeRequest;
/**
* Encodes the specified ClientEventsUnsubscribeRequest message. Does not implicitly {@link ClientEventsUnsubscribeRequest.verify|verify} messages.
* @param message ClientEventsUnsubscribeRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientEventsUnsubscribeRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientEventsUnsubscribeRequest message, length delimited. Does not implicitly {@link ClientEventsUnsubscribeRequest.verify|verify} messages.
* @param message ClientEventsUnsubscribeRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(
message: IClientEventsUnsubscribeRequest,
writer?: $protobuf.Writer,
): $protobuf.Writer;
/**
* Decodes a ClientEventsUnsubscribeRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientEventsUnsubscribeRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientEventsUnsubscribeRequest;
/**
* Decodes a ClientEventsUnsubscribeRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientEventsUnsubscribeRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientEventsUnsubscribeRequest;
/**
* Verifies a ClientEventsUnsubscribeRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientEventsUnsubscribeRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientEventsUnsubscribeRequest
*/
public static fromObject(object: { [k: string]: any }): ClientEventsUnsubscribeRequest;
/**
* Creates a plain object from a ClientEventsUnsubscribeRequest message. Also converts values to other types if specified.
* @param message ClientEventsUnsubscribeRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientEventsUnsubscribeRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientEventsUnsubscribeRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientEventsUnsubscribeResponse. */
export interface IClientEventsUnsubscribeResponse {
/** ClientEventsUnsubscribeResponse status */
status?: ClientEventsUnsubscribeResponse.Status | null | undefined;
}
/** Represents a ClientEventsUnsubscribeResponse. */
export class ClientEventsUnsubscribeResponse implements IClientEventsUnsubscribeResponse {
/**
* Constructs a new ClientEventsUnsubscribeResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IClientEventsUnsubscribeResponse);
/** ClientEventsUnsubscribeResponse status. */
public status: ClientEventsUnsubscribeResponse.Status;
/**
* Creates a new ClientEventsUnsubscribeResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientEventsUnsubscribeResponse instance
*/
public static create(properties?: IClientEventsUnsubscribeResponse): ClientEventsUnsubscribeResponse;
/**
* Encodes the specified ClientEventsUnsubscribeResponse message. Does not implicitly {@link ClientEventsUnsubscribeResponse.verify|verify} messages.
* @param message ClientEventsUnsubscribeResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientEventsUnsubscribeResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientEventsUnsubscribeResponse message, length delimited. Does not implicitly {@link ClientEventsUnsubscribeResponse.verify|verify} messages.
* @param message ClientEventsUnsubscribeResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(
message: IClientEventsUnsubscribeResponse,
writer?: $protobuf.Writer,
): $protobuf.Writer;
/**
* Decodes a ClientEventsUnsubscribeResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientEventsUnsubscribeResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientEventsUnsubscribeResponse;
/**
* Decodes a ClientEventsUnsubscribeResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientEventsUnsubscribeResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientEventsUnsubscribeResponse;
/**
* Verifies a ClientEventsUnsubscribeResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientEventsUnsubscribeResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientEventsUnsubscribeResponse
*/
public static fromObject(object: { [k: string]: any }): ClientEventsUnsubscribeResponse;
/**
* Creates a plain object from a ClientEventsUnsubscribeResponse message. Also converts values to other types if specified.
* @param message ClientEventsUnsubscribeResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientEventsUnsubscribeResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientEventsUnsubscribeResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ClientEventsUnsubscribeResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
INTERNAL_ERROR = 2,
}
}
/** Properties of a ClientEventsGetRequest. */
export interface IClientEventsGetRequest {
/** ClientEventsGetRequest subscriptions */
subscriptions?: IEventSubscription[] | null | undefined;
/** ClientEventsGetRequest blockIds */
blockIds?: string[] | null | undefined;
}
/** Represents a ClientEventsGetRequest. */
export class ClientEventsGetRequest implements IClientEventsGetRequest {
/**
* Constructs a new ClientEventsGetRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IClientEventsGetRequest);
/** ClientEventsGetRequest subscriptions. */
public subscriptions: IEventSubscription[];
/** ClientEventsGetRequest blockIds. */
public blockIds: string[];
/**
* Creates a new ClientEventsGetRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientEventsGetRequest instance
*/
public static create(properties?: IClientEventsGetRequest): ClientEventsGetRequest;
/**
* Encodes the specified ClientEventsGetRequest message. Does not implicitly {@link ClientEventsGetRequest.verify|verify} messages.
* @param message ClientEventsGetRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientEventsGetRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientEventsGetRequest message, length delimited. Does not implicitly {@link ClientEventsGetRequest.verify|verify} messages.
* @param message ClientEventsGetRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientEventsGetRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientEventsGetRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientEventsGetRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientEventsGetRequest;
/**
* Decodes a ClientEventsGetRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientEventsGetRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientEventsGetRequest;
/**
* Verifies a ClientEventsGetRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientEventsGetRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientEventsGetRequest
*/
public static fromObject(object: { [k: string]: any }): ClientEventsGetRequest;
/**
* Creates a plain object from a ClientEventsGetRequest message. Also converts values to other types if specified.
* @param message ClientEventsGetRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientEventsGetRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientEventsGetRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientEventsGetResponse. */
export interface IClientEventsGetResponse {
/** ClientEventsGetResponse status */
status?: ClientEventsGetResponse.Status | null | undefined;
/** ClientEventsGetResponse events */
events?: IEvent[] | null | undefined;
}
/** Represents a ClientEventsGetResponse. */
export class ClientEventsGetResponse implements IClientEventsGetResponse {
/**
* Constructs a new ClientEventsGetResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IClientEventsGetResponse);
/** ClientEventsGetResponse status. */
public status: ClientEventsGetResponse.Status;
/** ClientEventsGetResponse events. */
public events: IEvent[];
/**
* Creates a new ClientEventsGetResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientEventsGetResponse instance
*/
public static create(properties?: IClientEventsGetResponse): ClientEventsGetResponse;
/**
* Encodes the specified ClientEventsGetResponse message. Does not implicitly {@link ClientEventsGetResponse.verify|verify} messages.
* @param message ClientEventsGetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientEventsGetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientEventsGetResponse message, length delimited. Does not implicitly {@link ClientEventsGetResponse.verify|verify} messages.
* @param message ClientEventsGetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientEventsGetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientEventsGetResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientEventsGetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientEventsGetResponse;
/**
* Decodes a ClientEventsGetResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientEventsGetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientEventsGetResponse;
/**
* Verifies a ClientEventsGetResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientEventsGetResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientEventsGetResponse
*/
public static fromObject(object: { [k: string]: any }): ClientEventsGetResponse;
/**
* Creates a plain object from a ClientEventsGetResponse message. Also converts values to other types if specified.
* @param message ClientEventsGetResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientEventsGetResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientEventsGetResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ClientEventsGetResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
INTERNAL_ERROR = 2,
INVALID_FILTER = 3,
UNKNOWN_BLOCK = 4,
}
}
/** Properties of an Event. */
export interface IEvent {
/** Event eventType */
eventType?: string | null | undefined;
/** Event attributes */
attributes?: Event.IAttribute[] | null | undefined;
/** Event data */
data?: Uint8Array | null | undefined;
}
/** Represents an Event. */
export class Event implements IEvent {
/**
* Constructs a new Event.
* @param [properties] Properties to set
*/
constructor(properties?: IEvent);
/** Event eventType. */
public eventType: string;
/** Event attributes. */
public attributes: Event.IAttribute[];
/** Event data. */
public data: Uint8Array;
/**
* Creates a new Event instance using the specified properties.
* @param [properties] Properties to set
* @returns Event instance
*/
public static create(properties?: IEvent): Event;
/**
* Encodes the specified Event message. Does not implicitly {@link Event.verify|verify} messages.
* @param message Event message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IEvent, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Event message, length delimited. Does not implicitly {@link Event.verify|verify} messages.
* @param message Event message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IEvent, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Event message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Event
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): Event;
/**
* Decodes an Event message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Event
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): Event;
/**
* Verifies an Event message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates an Event message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Event
*/
public static fromObject(object: { [k: string]: any }): Event;
/**
* Creates a plain object from an Event message. Also converts values to other types if specified.
* @param message Event
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: Event, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Event to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace Event {
/** Properties of an Attribute. */
interface IAttribute {
/** Attribute key */
key?: string | null | undefined;
/** Attribute value */
value?: string | null | undefined;
}
/** Represents an Attribute. */
class Attribute implements IAttribute {
/**
* Constructs a new Attribute.
* @param [properties] Properties to set
*/
constructor(properties?: Event.IAttribute);
/** Attribute key. */
public key: string;
/** Attribute value. */
public value: string;
/**
* Creates a new Attribute instance using the specified properties.
* @param [properties] Properties to set
* @returns Attribute instance
*/
public static create(properties?: Event.IAttribute): Event.Attribute;
/**
* Encodes the specified Attribute message. Does not implicitly {@link Event.Attribute.verify|verify} messages.
* @param message Attribute message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: Event.IAttribute, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Attribute message, length delimited. Does not implicitly {@link Event.Attribute.verify|verify} messages.
* @param message Attribute message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: Event.IAttribute, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Attribute message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Attribute
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): Event.Attribute;
/**
* Decodes an Attribute message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Attribute
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): Event.Attribute;
/**
* Verifies an Attribute message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates an Attribute message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Attribute
*/
public static fromObject(object: { [k: string]: any }): Event.Attribute;
/**
* Creates a plain object from an Attribute message. Also converts values to other types if specified.
* @param message Attribute
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: Event.Attribute, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Attribute to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of an EventList. */
export interface IEventList {
/** EventList events */
events?: IEvent[] | null | undefined;
}
/** Represents an EventList. */
export class EventList implements IEventList {
/**
* Constructs a new EventList.
* @param [properties] Properties to set
*/
constructor(properties?: IEventList);
/** EventList events. */
public events: IEvent[];
/**
* Creates a new EventList instance using the specified properties.
* @param [properties] Properties to set
* @returns EventList instance
*/
public static create(properties?: IEventList): EventList;
/**
* Encodes the specified EventList message. Does not implicitly {@link EventList.verify|verify} messages.
* @param message EventList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IEventList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified EventList message, length delimited. Does not implicitly {@link EventList.verify|verify} messages.
* @param message EventList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IEventList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an EventList message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns EventList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): EventList;
/**
* Decodes an EventList message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns EventList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): EventList;
/**
* Verifies an EventList message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates an EventList message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns EventList
*/
public static fromObject(object: { [k: string]: any }): EventList;
/**
* Creates a plain object from an EventList message. Also converts values to other types if specified.
* @param message EventList
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: EventList, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this EventList to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an EventFilter. */
export interface IEventFilter {
/** EventFilter key */
key?: string | null | undefined;
/** EventFilter matchString */
matchString?: string | null | undefined;
/** EventFilter filterType */
filterType?: EventFilter.FilterType | null | undefined;
}
/** Represents an EventFilter. */
export class EventFilter implements IEventFilter {
/**
* Constructs a new EventFilter.
* @param [properties] Properties to set
*/
constructor(properties?: IEventFilter);
/** EventFilter key. */
public key: string;
/** EventFilter matchString. */
public matchString: string;
/** EventFilter filterType. */
public filterType: EventFilter.FilterType;
/**
* Creates a new EventFilter instance using the specified properties.
* @param [properties] Properties to set
* @returns EventFilter instance
*/
public static create(properties?: IEventFilter): EventFilter;
/**
* Encodes the specified EventFilter message. Does not implicitly {@link EventFilter.verify|verify} messages.
* @param message EventFilter message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IEventFilter, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified EventFilter message, length delimited. Does not implicitly {@link EventFilter.verify|verify} messages.
* @param message EventFilter message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IEventFilter, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an EventFilter message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns EventFilter
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): EventFilter;
/**
* Decodes an EventFilter message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns EventFilter
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): EventFilter;
/**
* Verifies an EventFilter message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates an EventFilter message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns EventFilter
*/
public static fromObject(object: { [k: string]: any }): EventFilter;
/**
* Creates a plain object from an EventFilter message. Also converts values to other types if specified.
* @param message EventFilter
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: EventFilter, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this EventFilter to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace EventFilter {
/** FilterType enum. */
enum FilterType {
FILTER_TYPE_UNSET = 0,
SIMPLE_ANY = 1,
SIMPLE_ALL = 2,
REGEX_ANY = 3,
REGEX_ALL = 4,
}
}
/** Properties of an EventSubscription. */
export interface IEventSubscription {
/** EventSubscription eventType */
eventType?: string | null | undefined;
/** EventSubscription filters */
filters?: IEventFilter[] | null | undefined;
}
/** Represents an EventSubscription. */
export class EventSubscription implements IEventSubscription {
/**
* Constructs a new EventSubscription.
* @param [properties] Properties to set
*/
constructor(properties?: IEventSubscription);
/** EventSubscription eventType. */
public eventType: string;
/** EventSubscription filters. */
public filters: IEventFilter[];
/**
* Creates a new EventSubscription instance using the specified properties.
* @param [properties] Properties to set
* @returns EventSubscription instance
*/
public static create(properties?: IEventSubscription): EventSubscription;
/**
* Encodes the specified EventSubscription message. Does not implicitly {@link EventSubscription.verify|verify} messages.
* @param message EventSubscription message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IEventSubscription, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified EventSubscription message, length delimited. Does not implicitly {@link EventSubscription.verify|verify} messages.
* @param message EventSubscription message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IEventSubscription, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an EventSubscription message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns EventSubscription
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): EventSubscription;
/**
* Decodes an EventSubscription message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns EventSubscription
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): EventSubscription;
/**
* Verifies an EventSubscription message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates an EventSubscription message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns EventSubscription
*/
public static fromObject(object: { [k: string]: any }): EventSubscription;
/**
* Creates a plain object from an EventSubscription message. Also converts values to other types if specified.
* @param message EventSubscription
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: EventSubscription, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this EventSubscription to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientPeersGetRequest. */
export interface IClientPeersGetRequest {}
/** Represents a ClientPeersGetRequest. */
export class ClientPeersGetRequest implements IClientPeersGetRequest {
/**
* Constructs a new ClientPeersGetRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IClientPeersGetRequest);
/**
* Creates a new ClientPeersGetRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientPeersGetRequest instance
*/
public static create(properties?: IClientPeersGetRequest): ClientPeersGetRequest;
/**
* Encodes the specified ClientPeersGetRequest message. Does not implicitly {@link ClientPeersGetRequest.verify|verify} messages.
* @param message ClientPeersGetRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientPeersGetRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientPeersGetRequest message, length delimited. Does not implicitly {@link ClientPeersGetRequest.verify|verify} messages.
* @param message ClientPeersGetRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientPeersGetRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientPeersGetRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientPeersGetRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientPeersGetRequest;
/**
* Decodes a ClientPeersGetRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientPeersGetRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientPeersGetRequest;
/**
* Verifies a ClientPeersGetRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientPeersGetRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientPeersGetRequest
*/
public static fromObject(object: { [k: string]: any }): ClientPeersGetRequest;
/**
* Creates a plain object from a ClientPeersGetRequest message. Also converts values to other types if specified.
* @param message ClientPeersGetRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientPeersGetRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientPeersGetRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientPeersGetResponse. */
export interface IClientPeersGetResponse {
/** ClientPeersGetResponse status */
status?: ClientPeersGetResponse.Status | null | undefined;
/** ClientPeersGetResponse peers */
peers?: string[] | null | undefined;
}
/** Represents a ClientPeersGetResponse. */
export class ClientPeersGetResponse implements IClientPeersGetResponse {
/**
* Constructs a new ClientPeersGetResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IClientPeersGetResponse);
/** ClientPeersGetResponse status. */
public status: ClientPeersGetResponse.Status;
/** ClientPeersGetResponse peers. */
public peers: string[];
/**
* Creates a new ClientPeersGetResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientPeersGetResponse instance
*/
public static create(properties?: IClientPeersGetResponse): ClientPeersGetResponse;
/**
* Encodes the specified ClientPeersGetResponse message. Does not implicitly {@link ClientPeersGetResponse.verify|verify} messages.
* @param message ClientPeersGetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientPeersGetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientPeersGetResponse message, length delimited. Does not implicitly {@link ClientPeersGetResponse.verify|verify} messages.
* @param message ClientPeersGetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientPeersGetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientPeersGetResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientPeersGetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientPeersGetResponse;
/**
* Decodes a ClientPeersGetResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientPeersGetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientPeersGetResponse;
/**
* Verifies a ClientPeersGetResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientPeersGetResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientPeersGetResponse
*/
public static fromObject(object: { [k: string]: any }): ClientPeersGetResponse;
/**
* Creates a plain object from a ClientPeersGetResponse message. Also converts values to other types if specified.
* @param message ClientPeersGetResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientPeersGetResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientPeersGetResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ClientPeersGetResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
ERROR = 2,
}
}
/** Properties of a ClientReceiptGetRequest. */
export interface IClientReceiptGetRequest {
/** ClientReceiptGetRequest transactionIds */
transactionIds?: string[] | null | undefined;
}
/** Represents a ClientReceiptGetRequest. */
export class ClientReceiptGetRequest implements IClientReceiptGetRequest {
/**
* Constructs a new ClientReceiptGetRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IClientReceiptGetRequest);
/** ClientReceiptGetRequest transactionIds. */
public transactionIds: string[];
/**
* Creates a new ClientReceiptGetRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientReceiptGetRequest instance
*/
public static create(properties?: IClientReceiptGetRequest): ClientReceiptGetRequest;
/**
* Encodes the specified ClientReceiptGetRequest message. Does not implicitly {@link ClientReceiptGetRequest.verify|verify} messages.
* @param message ClientReceiptGetRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientReceiptGetRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientReceiptGetRequest message, length delimited. Does not implicitly {@link ClientReceiptGetRequest.verify|verify} messages.
* @param message ClientReceiptGetRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientReceiptGetRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientReceiptGetRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientReceiptGetRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientReceiptGetRequest;
/**
* Decodes a ClientReceiptGetRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientReceiptGetRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientReceiptGetRequest;
/**
* Verifies a ClientReceiptGetRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientReceiptGetRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientReceiptGetRequest
*/
public static fromObject(object: { [k: string]: any }): ClientReceiptGetRequest;
/**
* Creates a plain object from a ClientReceiptGetRequest message. Also converts values to other types if specified.
* @param message ClientReceiptGetRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientReceiptGetRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientReceiptGetRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientReceiptGetResponse. */
export interface IClientReceiptGetResponse {
/** ClientReceiptGetResponse status */
status?: ClientReceiptGetResponse.Status | null | undefined;
/** ClientReceiptGetResponse receipts */
receipts?: ITransactionReceipt[] | null | undefined;
}
/** Represents a ClientReceiptGetResponse. */
export class ClientReceiptGetResponse implements IClientReceiptGetResponse {
/**
* Constructs a new ClientReceiptGetResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IClientReceiptGetResponse);
/** ClientReceiptGetResponse status. */
public status: ClientReceiptGetResponse.Status;
/** ClientReceiptGetResponse receipts. */
public receipts: ITransactionReceipt[];
/**
* Creates a new ClientReceiptGetResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientReceiptGetResponse instance
*/
public static create(properties?: IClientReceiptGetResponse): ClientReceiptGetResponse;
/**
* Encodes the specified ClientReceiptGetResponse message. Does not implicitly {@link ClientReceiptGetResponse.verify|verify} messages.
* @param message ClientReceiptGetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientReceiptGetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientReceiptGetResponse message, length delimited. Does not implicitly {@link ClientReceiptGetResponse.verify|verify} messages.
* @param message ClientReceiptGetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientReceiptGetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientReceiptGetResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientReceiptGetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientReceiptGetResponse;
/**
* Decodes a ClientReceiptGetResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientReceiptGetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientReceiptGetResponse;
/**
* Verifies a ClientReceiptGetResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientReceiptGetResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientReceiptGetResponse
*/
public static fromObject(object: { [k: string]: any }): ClientReceiptGetResponse;
/**
* Creates a plain object from a ClientReceiptGetResponse message. Also converts values to other types if specified.
* @param message ClientReceiptGetResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientReceiptGetResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientReceiptGetResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ClientReceiptGetResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
INTERNAL_ERROR = 2,
NO_RESOURCE = 5,
INVALID_ID = 8,
}
}
/** Properties of a TransactionReceipt. */
export interface ITransactionReceipt {
/** TransactionReceipt stateChanges */
stateChanges?: IStateChange[] | null | undefined;
/** TransactionReceipt events */
events?: IEvent[] | null | undefined;
/** TransactionReceipt data */
data?: Uint8Array[] | null | undefined;
/** TransactionReceipt transactionId */
transactionId?: string | null | undefined;
}
/** Represents a TransactionReceipt. */
export class TransactionReceipt implements ITransactionReceipt {
/**
* Constructs a new TransactionReceipt.
* @param [properties] Properties to set
*/
constructor(properties?: ITransactionReceipt);
/** TransactionReceipt stateChanges. */
public stateChanges: IStateChange[];
/** TransactionReceipt events. */
public events: IEvent[];
/** TransactionReceipt data. */
public data: Uint8Array[];
/** TransactionReceipt transactionId. */
public transactionId: string;
/**
* Creates a new TransactionReceipt instance using the specified properties.
* @param [properties] Properties to set
* @returns TransactionReceipt instance
*/
public static create(properties?: ITransactionReceipt): TransactionReceipt;
/**
* Encodes the specified TransactionReceipt message. Does not implicitly {@link TransactionReceipt.verify|verify} messages.
* @param message TransactionReceipt message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ITransactionReceipt, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TransactionReceipt message, length delimited. Does not implicitly {@link TransactionReceipt.verify|verify} messages.
* @param message TransactionReceipt message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ITransactionReceipt, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TransactionReceipt message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TransactionReceipt
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): TransactionReceipt;
/**
* Decodes a TransactionReceipt message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TransactionReceipt
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): TransactionReceipt;
/**
* Verifies a TransactionReceipt message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a TransactionReceipt message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TransactionReceipt
*/
public static fromObject(object: { [k: string]: any }): TransactionReceipt;
/**
* Creates a plain object from a TransactionReceipt message. Also converts values to other types if specified.
* @param message TransactionReceipt
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: TransactionReceipt, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TransactionReceipt to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a StateChange. */
export interface IStateChange {
/** StateChange address */
address?: string | null | undefined;
/** StateChange value */
value?: Uint8Array | null | undefined;
/** StateChange type */
type?: StateChange.Type | null | undefined;
}
/** Represents a StateChange. */
export class StateChange implements IStateChange {
/**
* Constructs a new StateChange.
* @param [properties] Properties to set
*/
constructor(properties?: IStateChange);
/** StateChange address. */
public address: string;
/** StateChange value. */
public value: Uint8Array;
/** StateChange type. */
public type: StateChange.Type;
/**
* Creates a new StateChange instance using the specified properties.
* @param [properties] Properties to set
* @returns StateChange instance
*/
public static create(properties?: IStateChange): StateChange;
/**
* Encodes the specified StateChange message. Does not implicitly {@link StateChange.verify|verify} messages.
* @param message StateChange message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IStateChange, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified StateChange message, length delimited. Does not implicitly {@link StateChange.verify|verify} messages.
* @param message StateChange message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IStateChange, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a StateChange message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns StateChange
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): StateChange;
/**
* Decodes a StateChange message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns StateChange
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): StateChange;
/**
* Verifies a StateChange message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a StateChange message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns StateChange
*/
public static fromObject(object: { [k: string]: any }): StateChange;
/**
* Creates a plain object from a StateChange message. Also converts values to other types if specified.
* @param message StateChange
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: StateChange, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this StateChange to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace StateChange {
/** Type enum. */
enum Type {
TYPE_UNSET = 0,
SET = 1,
DELETE = 2,
}
}
/** Properties of a StateChangeList. */
export interface IStateChangeList {
/** StateChangeList stateChanges */
stateChanges?: IStateChange[] | null | undefined;
}
/** Represents a StateChangeList. */
export class StateChangeList implements IStateChangeList {
/**
* Constructs a new StateChangeList.
* @param [properties] Properties to set
*/
constructor(properties?: IStateChangeList);
/** StateChangeList stateChanges. */
public stateChanges: IStateChange[];
/**
* Creates a new StateChangeList instance using the specified properties.
* @param [properties] Properties to set
* @returns StateChangeList instance
*/
public static create(properties?: IStateChangeList): StateChangeList;
/**
* Encodes the specified StateChangeList message. Does not implicitly {@link StateChangeList.verify|verify} messages.
* @param message StateChangeList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IStateChangeList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified StateChangeList message, length delimited. Does not implicitly {@link StateChangeList.verify|verify} messages.
* @param message StateChangeList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IStateChangeList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a StateChangeList message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns StateChangeList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): StateChangeList;
/**
* Decodes a StateChangeList message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns StateChangeList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): StateChangeList;
/**
* Verifies a StateChangeList message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a StateChangeList message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns StateChangeList
*/
public static fromObject(object: { [k: string]: any }): StateChangeList;
/**
* Creates a plain object from a StateChangeList message. Also converts values to other types if specified.
* @param message StateChangeList
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: StateChangeList, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this StateChangeList to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientStateListRequest. */
export interface IClientStateListRequest {
/** ClientStateListRequest stateRoot */
stateRoot?: string | null | undefined;
/** ClientStateListRequest address */
address?: string | null | undefined;
/** ClientStateListRequest paging */
paging?: IClientPagingControls | null | undefined;
/** ClientStateListRequest sorting */
sorting?: IClientSortControls[] | null | undefined;
}
/** Represents a ClientStateListRequest. */
export class ClientStateListRequest implements IClientStateListRequest {
/**
* Constructs a new ClientStateListRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IClientStateListRequest);
/** ClientStateListRequest stateRoot. */
public stateRoot: string;
/** ClientStateListRequest address. */
public address: string;
/** ClientStateListRequest paging. */
public paging?: IClientPagingControls | null | undefined;
/** ClientStateListRequest sorting. */
public sorting: IClientSortControls[];
/**
* Creates a new ClientStateListRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientStateListRequest instance
*/
public static create(properties?: IClientStateListRequest): ClientStateListRequest;
/**
* Encodes the specified ClientStateListRequest message. Does not implicitly {@link ClientStateListRequest.verify|verify} messages.
* @param message ClientStateListRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientStateListRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientStateListRequest message, length delimited. Does not implicitly {@link ClientStateListRequest.verify|verify} messages.
* @param message ClientStateListRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientStateListRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientStateListRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientStateListRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientStateListRequest;
/**
* Decodes a ClientStateListRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientStateListRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientStateListRequest;
/**
* Verifies a ClientStateListRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientStateListRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientStateListRequest
*/
public static fromObject(object: { [k: string]: any }): ClientStateListRequest;
/**
* Creates a plain object from a ClientStateListRequest message. Also converts values to other types if specified.
* @param message ClientStateListRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientStateListRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientStateListRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientStateListResponse. */
export interface IClientStateListResponse {
/** ClientStateListResponse status */
status?: ClientStateListResponse.Status | null | undefined;
/** ClientStateListResponse entries */
entries?: ClientStateListResponse.IEntry[] | null | undefined;
/** ClientStateListResponse stateRoot */
stateRoot?: string | null | undefined;
/** ClientStateListResponse paging */
paging?: IClientPagingResponse | null | undefined;
}
/** Represents a ClientStateListResponse. */
export class ClientStateListResponse implements IClientStateListResponse {
/**
* Constructs a new ClientStateListResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IClientStateListResponse);
/** ClientStateListResponse status. */
public status: ClientStateListResponse.Status;
/** ClientStateListResponse entries. */
public entries: ClientStateListResponse.IEntry[];
/** ClientStateListResponse stateRoot. */
public stateRoot: string;
/** ClientStateListResponse paging. */
public paging?: IClientPagingResponse | null | undefined;
/**
* Creates a new ClientStateListResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientStateListResponse instance
*/
public static create(properties?: IClientStateListResponse): ClientStateListResponse;
/**
* Encodes the specified ClientStateListResponse message. Does not implicitly {@link ClientStateListResponse.verify|verify} messages.
* @param message ClientStateListResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientStateListResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientStateListResponse message, length delimited. Does not implicitly {@link ClientStateListResponse.verify|verify} messages.
* @param message ClientStateListResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientStateListResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientStateListResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientStateListResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientStateListResponse;
/**
* Decodes a ClientStateListResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientStateListResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientStateListResponse;
/**
* Verifies a ClientStateListResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientStateListResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientStateListResponse
*/
public static fromObject(object: { [k: string]: any }): ClientStateListResponse;
/**
* Creates a plain object from a ClientStateListResponse message. Also converts values to other types if specified.
* @param message ClientStateListResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientStateListResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientStateListResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ClientStateListResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
INTERNAL_ERROR = 2,
NOT_READY = 3,
NO_ROOT = 4,
NO_RESOURCE = 5,
INVALID_PAGING = 6,
INVALID_SORT = 7,
INVALID_ADDRESS = 8,
INVALID_ROOT = 9,
}
/** Properties of an Entry. */
interface IEntry {
/** Entry address */
address?: string | null | undefined;
/** Entry data */
data?: Uint8Array | null | undefined;
}
/** Represents an Entry. */
class Entry implements IEntry {
/**
* Constructs a new Entry.
* @param [properties] Properties to set
*/
constructor(properties?: ClientStateListResponse.IEntry);
/** Entry address. */
public address: string;
/** Entry data. */
public data: Uint8Array;
/**
* Creates a new Entry instance using the specified properties.
* @param [properties] Properties to set
* @returns Entry instance
*/
public static create(properties?: ClientStateListResponse.IEntry): ClientStateListResponse.Entry;
/**
* Encodes the specified Entry message. Does not implicitly {@link ClientStateListResponse.Entry.verify|verify} messages.
* @param message Entry message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ClientStateListResponse.IEntry, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Entry message, length delimited. Does not implicitly {@link ClientStateListResponse.Entry.verify|verify} messages.
* @param message Entry message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(
message: ClientStateListResponse.IEntry,
writer?: $protobuf.Writer,
): $protobuf.Writer;
/**
* Decodes an Entry message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Entry
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientStateListResponse.Entry;
/**
* Decodes an Entry message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Entry
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientStateListResponse.Entry;
/**
* Verifies an Entry message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates an Entry message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Entry
*/
public static fromObject(object: { [k: string]: any }): ClientStateListResponse.Entry;
/**
* Creates a plain object from an Entry message. Also converts values to other types if specified.
* @param message Entry
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientStateListResponse.Entry,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this Entry to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a ClientStateGetRequest. */
export interface IClientStateGetRequest {
/** ClientStateGetRequest stateRoot */
stateRoot?: string | null | undefined;
/** ClientStateGetRequest address */
address?: string | null | undefined;
}
/** Represents a ClientStateGetRequest. */
export class ClientStateGetRequest implements IClientStateGetRequest {
/**
* Constructs a new ClientStateGetRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IClientStateGetRequest);
/** ClientStateGetRequest stateRoot. */
public stateRoot: string;
/** ClientStateGetRequest address. */
public address: string;
/**
* Creates a new ClientStateGetRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientStateGetRequest instance
*/
public static create(properties?: IClientStateGetRequest): ClientStateGetRequest;
/**
* Encodes the specified ClientStateGetRequest message. Does not implicitly {@link ClientStateGetRequest.verify|verify} messages.
* @param message ClientStateGetRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientStateGetRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientStateGetRequest message, length delimited. Does not implicitly {@link ClientStateGetRequest.verify|verify} messages.
* @param message ClientStateGetRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientStateGetRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientStateGetRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientStateGetRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientStateGetRequest;
/**
* Decodes a ClientStateGetRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientStateGetRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientStateGetRequest;
/**
* Verifies a ClientStateGetRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientStateGetRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientStateGetRequest
*/
public static fromObject(object: { [k: string]: any }): ClientStateGetRequest;
/**
* Creates a plain object from a ClientStateGetRequest message. Also converts values to other types if specified.
* @param message ClientStateGetRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientStateGetRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientStateGetRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientStateGetResponse. */
export interface IClientStateGetResponse {
/** ClientStateGetResponse status */
status?: ClientStateGetResponse.Status | null | undefined;
/** ClientStateGetResponse value */
value?: Uint8Array | null | undefined;
/** ClientStateGetResponse stateRoot */
stateRoot?: string | null | undefined;
}
/** Represents a ClientStateGetResponse. */
export class ClientStateGetResponse implements IClientStateGetResponse {
/**
* Constructs a new ClientStateGetResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IClientStateGetResponse);
/** ClientStateGetResponse status. */
public status: ClientStateGetResponse.Status;
/** ClientStateGetResponse value. */
public value: Uint8Array;
/** ClientStateGetResponse stateRoot. */
public stateRoot: string;
/**
* Creates a new ClientStateGetResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientStateGetResponse instance
*/
public static create(properties?: IClientStateGetResponse): ClientStateGetResponse;
/**
* Encodes the specified ClientStateGetResponse message. Does not implicitly {@link ClientStateGetResponse.verify|verify} messages.
* @param message ClientStateGetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientStateGetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientStateGetResponse message, length delimited. Does not implicitly {@link ClientStateGetResponse.verify|verify} messages.
* @param message ClientStateGetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientStateGetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientStateGetResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientStateGetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientStateGetResponse;
/**
* Decodes a ClientStateGetResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientStateGetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientStateGetResponse;
/**
* Verifies a ClientStateGetResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientStateGetResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientStateGetResponse
*/
public static fromObject(object: { [k: string]: any }): ClientStateGetResponse;
/**
* Creates a plain object from a ClientStateGetResponse message. Also converts values to other types if specified.
* @param message ClientStateGetResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientStateGetResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientStateGetResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ClientStateGetResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
INTERNAL_ERROR = 2,
NOT_READY = 3,
NO_ROOT = 4,
NO_RESOURCE = 5,
INVALID_ADDRESS = 6,
INVALID_ROOT = 7,
}
}
/** Properties of a ClientStatusGetRequest. */
export interface IClientStatusGetRequest {}
/** Represents a ClientStatusGetRequest. */
export class ClientStatusGetRequest implements IClientStatusGetRequest {
/**
* Constructs a new ClientStatusGetRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IClientStatusGetRequest);
/**
* Creates a new ClientStatusGetRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientStatusGetRequest instance
*/
public static create(properties?: IClientStatusGetRequest): ClientStatusGetRequest;
/**
* Encodes the specified ClientStatusGetRequest message. Does not implicitly {@link ClientStatusGetRequest.verify|verify} messages.
* @param message ClientStatusGetRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientStatusGetRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientStatusGetRequest message, length delimited. Does not implicitly {@link ClientStatusGetRequest.verify|verify} messages.
* @param message ClientStatusGetRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientStatusGetRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientStatusGetRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientStatusGetRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientStatusGetRequest;
/**
* Decodes a ClientStatusGetRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientStatusGetRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientStatusGetRequest;
/**
* Verifies a ClientStatusGetRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientStatusGetRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientStatusGetRequest
*/
public static fromObject(object: { [k: string]: any }): ClientStatusGetRequest;
/**
* Creates a plain object from a ClientStatusGetRequest message. Also converts values to other types if specified.
* @param message ClientStatusGetRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientStatusGetRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientStatusGetRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientStatusGetResponse. */
export interface IClientStatusGetResponse {
/** ClientStatusGetResponse status */
status?: ClientStatusGetResponse.Status | null | undefined;
/** ClientStatusGetResponse peers */
peers?: ClientStatusGetResponse.IPeer[] | null | undefined;
/** ClientStatusGetResponse endpoint */
endpoint?: string | null | undefined;
}
/** Represents a ClientStatusGetResponse. */
export class ClientStatusGetResponse implements IClientStatusGetResponse {
/**
* Constructs a new ClientStatusGetResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IClientStatusGetResponse);
/** ClientStatusGetResponse status. */
public status: ClientStatusGetResponse.Status;
/** ClientStatusGetResponse peers. */
public peers: ClientStatusGetResponse.IPeer[];
/** ClientStatusGetResponse endpoint. */
public endpoint: string;
/**
* Creates a new ClientStatusGetResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientStatusGetResponse instance
*/
public static create(properties?: IClientStatusGetResponse): ClientStatusGetResponse;
/**
* Encodes the specified ClientStatusGetResponse message. Does not implicitly {@link ClientStatusGetResponse.verify|verify} messages.
* @param message ClientStatusGetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientStatusGetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientStatusGetResponse message, length delimited. Does not implicitly {@link ClientStatusGetResponse.verify|verify} messages.
* @param message ClientStatusGetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientStatusGetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientStatusGetResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientStatusGetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientStatusGetResponse;
/**
* Decodes a ClientStatusGetResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientStatusGetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientStatusGetResponse;
/**
* Verifies a ClientStatusGetResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientStatusGetResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientStatusGetResponse
*/
public static fromObject(object: { [k: string]: any }): ClientStatusGetResponse;
/**
* Creates a plain object from a ClientStatusGetResponse message. Also converts values to other types if specified.
* @param message ClientStatusGetResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientStatusGetResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientStatusGetResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ClientStatusGetResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
ERROR = 2,
}
/** Properties of a Peer. */
interface IPeer {
/** Peer endpoint */
endpoint?: string | null | undefined;
}
/** Represents a Peer. */
class Peer implements IPeer {
/**
* Constructs a new Peer.
* @param [properties] Properties to set
*/
constructor(properties?: ClientStatusGetResponse.IPeer);
/** Peer endpoint. */
public endpoint: string;
/**
* Creates a new Peer instance using the specified properties.
* @param [properties] Properties to set
* @returns Peer instance
*/
public static create(properties?: ClientStatusGetResponse.IPeer): ClientStatusGetResponse.Peer;
/**
* Encodes the specified Peer message. Does not implicitly {@link ClientStatusGetResponse.Peer.verify|verify} messages.
* @param message Peer message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ClientStatusGetResponse.IPeer, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Peer message, length delimited. Does not implicitly {@link ClientStatusGetResponse.Peer.verify|verify} messages.
* @param message Peer message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(
message: ClientStatusGetResponse.IPeer,
writer?: $protobuf.Writer,
): $protobuf.Writer;
/**
* Decodes a Peer message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Peer
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientStatusGetResponse.Peer;
/**
* Decodes a Peer message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Peer
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientStatusGetResponse.Peer;
/**
* Verifies a Peer message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a Peer message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Peer
*/
public static fromObject(object: { [k: string]: any }): ClientStatusGetResponse.Peer;
/**
* Creates a plain object from a Peer message. Also converts values to other types if specified.
* @param message Peer
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientStatusGetResponse.Peer,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this Peer to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a ClientTransactionListRequest. */
export interface IClientTransactionListRequest {
/** ClientTransactionListRequest headId */
headId?: string | null | undefined;
/** ClientTransactionListRequest transactionIds */
transactionIds?: string[] | null | undefined;
/** ClientTransactionListRequest paging */
paging?: IClientPagingControls | null | undefined;
/** ClientTransactionListRequest sorting */
sorting?: IClientSortControls[] | null | undefined;
}
/** Represents a ClientTransactionListRequest. */
export class ClientTransactionListRequest implements IClientTransactionListRequest {
/**
* Constructs a new ClientTransactionListRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IClientTransactionListRequest);
/** ClientTransactionListRequest headId. */
public headId: string;
/** ClientTransactionListRequest transactionIds. */
public transactionIds: string[];
/** ClientTransactionListRequest paging. */
public paging?: IClientPagingControls | null | undefined;
/** ClientTransactionListRequest sorting. */
public sorting: IClientSortControls[];
/**
* Creates a new ClientTransactionListRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientTransactionListRequest instance
*/
public static create(properties?: IClientTransactionListRequest): ClientTransactionListRequest;
/**
* Encodes the specified ClientTransactionListRequest message. Does not implicitly {@link ClientTransactionListRequest.verify|verify} messages.
* @param message ClientTransactionListRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientTransactionListRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientTransactionListRequest message, length delimited. Does not implicitly {@link ClientTransactionListRequest.verify|verify} messages.
* @param message ClientTransactionListRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientTransactionListRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientTransactionListRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientTransactionListRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientTransactionListRequest;
/**
* Decodes a ClientTransactionListRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientTransactionListRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientTransactionListRequest;
/**
* Verifies a ClientTransactionListRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientTransactionListRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientTransactionListRequest
*/
public static fromObject(object: { [k: string]: any }): ClientTransactionListRequest;
/**
* Creates a plain object from a ClientTransactionListRequest message. Also converts values to other types if specified.
* @param message ClientTransactionListRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientTransactionListRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientTransactionListRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientTransactionListResponse. */
export interface IClientTransactionListResponse {
/** ClientTransactionListResponse status */
status?: ClientTransactionListResponse.Status | null | undefined;
/** ClientTransactionListResponse transactions */
transactions?: ITransaction[] | null | undefined;
/** ClientTransactionListResponse headId */
headId?: string | null | undefined;
/** ClientTransactionListResponse paging */
paging?: IClientPagingResponse | null | undefined;
}
/** Represents a ClientTransactionListResponse. */
export class ClientTransactionListResponse implements IClientTransactionListResponse {
/**
* Constructs a new ClientTransactionListResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IClientTransactionListResponse);
/** ClientTransactionListResponse status. */
public status: ClientTransactionListResponse.Status;
/** ClientTransactionListResponse transactions. */
public transactions: ITransaction[];
/** ClientTransactionListResponse headId. */
public headId: string;
/** ClientTransactionListResponse paging. */
public paging?: IClientPagingResponse | null | undefined;
/**
* Creates a new ClientTransactionListResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientTransactionListResponse instance
*/
public static create(properties?: IClientTransactionListResponse): ClientTransactionListResponse;
/**
* Encodes the specified ClientTransactionListResponse message. Does not implicitly {@link ClientTransactionListResponse.verify|verify} messages.
* @param message ClientTransactionListResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientTransactionListResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientTransactionListResponse message, length delimited. Does not implicitly {@link ClientTransactionListResponse.verify|verify} messages.
* @param message ClientTransactionListResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientTransactionListResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientTransactionListResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientTransactionListResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientTransactionListResponse;
/**
* Decodes a ClientTransactionListResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientTransactionListResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientTransactionListResponse;
/**
* Verifies a ClientTransactionListResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientTransactionListResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientTransactionListResponse
*/
public static fromObject(object: { [k: string]: any }): ClientTransactionListResponse;
/**
* Creates a plain object from a ClientTransactionListResponse message. Also converts values to other types if specified.
* @param message ClientTransactionListResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientTransactionListResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientTransactionListResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ClientTransactionListResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
INTERNAL_ERROR = 2,
NOT_READY = 3,
NO_ROOT = 4,
NO_RESOURCE = 5,
INVALID_PAGING = 6,
INVALID_SORT = 7,
INVALID_ID = 8,
}
}
/** Properties of a ClientTransactionGetRequest. */
export interface IClientTransactionGetRequest {
/** ClientTransactionGetRequest transactionId */
transactionId?: string | null | undefined;
}
/** Represents a ClientTransactionGetRequest. */
export class ClientTransactionGetRequest implements IClientTransactionGetRequest {
/**
* Constructs a new ClientTransactionGetRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IClientTransactionGetRequest);
/** ClientTransactionGetRequest transactionId. */
public transactionId: string;
/**
* Creates a new ClientTransactionGetRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientTransactionGetRequest instance
*/
public static create(properties?: IClientTransactionGetRequest): ClientTransactionGetRequest;
/**
* Encodes the specified ClientTransactionGetRequest message. Does not implicitly {@link ClientTransactionGetRequest.verify|verify} messages.
* @param message ClientTransactionGetRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientTransactionGetRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientTransactionGetRequest message, length delimited. Does not implicitly {@link ClientTransactionGetRequest.verify|verify} messages.
* @param message ClientTransactionGetRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientTransactionGetRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientTransactionGetRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientTransactionGetRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientTransactionGetRequest;
/**
* Decodes a ClientTransactionGetRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientTransactionGetRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientTransactionGetRequest;
/**
* Verifies a ClientTransactionGetRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientTransactionGetRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientTransactionGetRequest
*/
public static fromObject(object: { [k: string]: any }): ClientTransactionGetRequest;
/**
* Creates a plain object from a ClientTransactionGetRequest message. Also converts values to other types if specified.
* @param message ClientTransactionGetRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientTransactionGetRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientTransactionGetRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ClientTransactionGetResponse. */
export interface IClientTransactionGetResponse {
/** ClientTransactionGetResponse status */
status?: ClientTransactionGetResponse.Status | null | undefined;
/** ClientTransactionGetResponse transaction */
transaction?: ITransaction | null | undefined;
}
/** Represents a ClientTransactionGetResponse. */
export class ClientTransactionGetResponse implements IClientTransactionGetResponse {
/**
* Constructs a new ClientTransactionGetResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IClientTransactionGetResponse);
/** ClientTransactionGetResponse status. */
public status: ClientTransactionGetResponse.Status;
/** ClientTransactionGetResponse transaction. */
public transaction?: ITransaction | null | undefined;
/**
* Creates a new ClientTransactionGetResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ClientTransactionGetResponse instance
*/
public static create(properties?: IClientTransactionGetResponse): ClientTransactionGetResponse;
/**
* Encodes the specified ClientTransactionGetResponse message. Does not implicitly {@link ClientTransactionGetResponse.verify|verify} messages.
* @param message ClientTransactionGetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IClientTransactionGetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ClientTransactionGetResponse message, length delimited. Does not implicitly {@link ClientTransactionGetResponse.verify|verify} messages.
* @param message ClientTransactionGetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IClientTransactionGetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ClientTransactionGetResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ClientTransactionGetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ClientTransactionGetResponse;
/**
* Decodes a ClientTransactionGetResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ClientTransactionGetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ClientTransactionGetResponse;
/**
* Verifies a ClientTransactionGetResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ClientTransactionGetResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ClientTransactionGetResponse
*/
public static fromObject(object: { [k: string]: any }): ClientTransactionGetResponse;
/**
* Creates a plain object from a ClientTransactionGetResponse message. Also converts values to other types if specified.
* @param message ClientTransactionGetResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ClientTransactionGetResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ClientTransactionGetResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ClientTransactionGetResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
INTERNAL_ERROR = 2,
NO_RESOURCE = 5,
INVALID_ID = 8,
}
}
/** Properties of a ConsensusPeerMessage. */
export interface IConsensusPeerMessage {
/** ConsensusPeerMessage messageType */
messageType?: string | null | undefined;
/** ConsensusPeerMessage content */
content?: Uint8Array | null | undefined;
/** ConsensusPeerMessage name */
name?: string | null | undefined;
/** ConsensusPeerMessage version */
version?: string | null | undefined;
}
/** Represents a ConsensusPeerMessage. */
export class ConsensusPeerMessage implements IConsensusPeerMessage {
/**
* Constructs a new ConsensusPeerMessage.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusPeerMessage);
/** ConsensusPeerMessage messageType. */
public messageType: string;
/** ConsensusPeerMessage content. */
public content: Uint8Array;
/** ConsensusPeerMessage name. */
public name: string;
/** ConsensusPeerMessage version. */
public version: string;
/**
* Creates a new ConsensusPeerMessage instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusPeerMessage instance
*/
public static create(properties?: IConsensusPeerMessage): ConsensusPeerMessage;
/**
* Encodes the specified ConsensusPeerMessage message. Does not implicitly {@link ConsensusPeerMessage.verify|verify} messages.
* @param message ConsensusPeerMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusPeerMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusPeerMessage message, length delimited. Does not implicitly {@link ConsensusPeerMessage.verify|verify} messages.
* @param message ConsensusPeerMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusPeerMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusPeerMessage message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusPeerMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusPeerMessage;
/**
* Decodes a ConsensusPeerMessage message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusPeerMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusPeerMessage;
/**
* Verifies a ConsensusPeerMessage message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusPeerMessage message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusPeerMessage
*/
public static fromObject(object: { [k: string]: any }): ConsensusPeerMessage;
/**
* Creates a plain object from a ConsensusPeerMessage message. Also converts values to other types if specified.
* @param message ConsensusPeerMessage
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ConsensusPeerMessage, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ConsensusPeerMessage to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusBlock. */
export interface IConsensusBlock {
/** ConsensusBlock blockId */
blockId?: Uint8Array | null | undefined;
/** ConsensusBlock previousId */
previousId?: Uint8Array | null | undefined;
/** ConsensusBlock signerId */
signerId?: Uint8Array | null | undefined;
/** ConsensusBlock blockNum */
blockNum?: number | Long | null | undefined;
/** ConsensusBlock payload */
payload?: Uint8Array | null | undefined;
/** ConsensusBlock summary */
summary?: Uint8Array | null | undefined;
}
/** Represents a ConsensusBlock. */
export class ConsensusBlock implements IConsensusBlock {
/**
* Constructs a new ConsensusBlock.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusBlock);
/** ConsensusBlock blockId. */
public blockId: Uint8Array;
/** ConsensusBlock previousId. */
public previousId: Uint8Array;
/** ConsensusBlock signerId. */
public signerId: Uint8Array;
/** ConsensusBlock blockNum. */
public blockNum: number | Long;
/** ConsensusBlock payload. */
public payload: Uint8Array;
/** ConsensusBlock summary. */
public summary: Uint8Array;
/**
* Creates a new ConsensusBlock instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusBlock instance
*/
public static create(properties?: IConsensusBlock): ConsensusBlock;
/**
* Encodes the specified ConsensusBlock message. Does not implicitly {@link ConsensusBlock.verify|verify} messages.
* @param message ConsensusBlock message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusBlock, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusBlock message, length delimited. Does not implicitly {@link ConsensusBlock.verify|verify} messages.
* @param message ConsensusBlock message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusBlock, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusBlock message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusBlock
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusBlock;
/**
* Decodes a ConsensusBlock message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusBlock
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusBlock;
/**
* Verifies a ConsensusBlock message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusBlock message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusBlock
*/
public static fromObject(object: { [k: string]: any }): ConsensusBlock;
/**
* Creates a plain object from a ConsensusBlock message. Also converts values to other types if specified.
* @param message ConsensusBlock
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ConsensusBlock, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ConsensusBlock to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusPeerInfo. */
export interface IConsensusPeerInfo {
/** ConsensusPeerInfo peerId */
peerId?: Uint8Array | null | undefined;
}
/** Represents a ConsensusPeerInfo. */
export class ConsensusPeerInfo implements IConsensusPeerInfo {
/**
* Constructs a new ConsensusPeerInfo.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusPeerInfo);
/** ConsensusPeerInfo peerId. */
public peerId: Uint8Array;
/**
* Creates a new ConsensusPeerInfo instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusPeerInfo instance
*/
public static create(properties?: IConsensusPeerInfo): ConsensusPeerInfo;
/**
* Encodes the specified ConsensusPeerInfo message. Does not implicitly {@link ConsensusPeerInfo.verify|verify} messages.
* @param message ConsensusPeerInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusPeerInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusPeerInfo message, length delimited. Does not implicitly {@link ConsensusPeerInfo.verify|verify} messages.
* @param message ConsensusPeerInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusPeerInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusPeerInfo message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusPeerInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusPeerInfo;
/**
* Decodes a ConsensusPeerInfo message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusPeerInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusPeerInfo;
/**
* Verifies a ConsensusPeerInfo message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusPeerInfo message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusPeerInfo
*/
public static fromObject(object: { [k: string]: any }): ConsensusPeerInfo;
/**
* Creates a plain object from a ConsensusPeerInfo message. Also converts values to other types if specified.
* @param message ConsensusPeerInfo
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ConsensusPeerInfo, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ConsensusPeerInfo to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusSettingsEntry. */
export interface IConsensusSettingsEntry {
/** ConsensusSettingsEntry key */
key?: string | null | undefined;
/** ConsensusSettingsEntry value */
value?: string | null | undefined;
}
/** Represents a ConsensusSettingsEntry. */
export class ConsensusSettingsEntry implements IConsensusSettingsEntry {
/**
* Constructs a new ConsensusSettingsEntry.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusSettingsEntry);
/** ConsensusSettingsEntry key. */
public key: string;
/** ConsensusSettingsEntry value. */
public value: string;
/**
* Creates a new ConsensusSettingsEntry instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusSettingsEntry instance
*/
public static create(properties?: IConsensusSettingsEntry): ConsensusSettingsEntry;
/**
* Encodes the specified ConsensusSettingsEntry message. Does not implicitly {@link ConsensusSettingsEntry.verify|verify} messages.
* @param message ConsensusSettingsEntry message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusSettingsEntry, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusSettingsEntry message, length delimited. Does not implicitly {@link ConsensusSettingsEntry.verify|verify} messages.
* @param message ConsensusSettingsEntry message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusSettingsEntry, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusSettingsEntry message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusSettingsEntry
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusSettingsEntry;
/**
* Decodes a ConsensusSettingsEntry message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusSettingsEntry
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusSettingsEntry;
/**
* Verifies a ConsensusSettingsEntry message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusSettingsEntry message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusSettingsEntry
*/
public static fromObject(object: { [k: string]: any }): ConsensusSettingsEntry;
/**
* Creates a plain object from a ConsensusSettingsEntry message. Also converts values to other types if specified.
* @param message ConsensusSettingsEntry
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusSettingsEntry,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusSettingsEntry to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusStateEntry. */
export interface IConsensusStateEntry {
/** ConsensusStateEntry address */
address?: string | null | undefined;
/** ConsensusStateEntry data */
data?: Uint8Array | null | undefined;
}
/** Represents a ConsensusStateEntry. */
export class ConsensusStateEntry implements IConsensusStateEntry {
/**
* Constructs a new ConsensusStateEntry.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusStateEntry);
/** ConsensusStateEntry address. */
public address: string;
/** ConsensusStateEntry data. */
public data: Uint8Array;
/**
* Creates a new ConsensusStateEntry instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusStateEntry instance
*/
public static create(properties?: IConsensusStateEntry): ConsensusStateEntry;
/**
* Encodes the specified ConsensusStateEntry message. Does not implicitly {@link ConsensusStateEntry.verify|verify} messages.
* @param message ConsensusStateEntry message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusStateEntry, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusStateEntry message, length delimited. Does not implicitly {@link ConsensusStateEntry.verify|verify} messages.
* @param message ConsensusStateEntry message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusStateEntry, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusStateEntry message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusStateEntry
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusStateEntry;
/**
* Decodes a ConsensusStateEntry message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusStateEntry
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusStateEntry;
/**
* Verifies a ConsensusStateEntry message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusStateEntry message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusStateEntry
*/
public static fromObject(object: { [k: string]: any }): ConsensusStateEntry;
/**
* Creates a plain object from a ConsensusStateEntry message. Also converts values to other types if specified.
* @param message ConsensusStateEntry
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ConsensusStateEntry, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ConsensusStateEntry to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusRegisterRequest. */
export interface IConsensusRegisterRequest {
/** ConsensusRegisterRequest name */
name?: string | null | undefined;
/** ConsensusRegisterRequest version */
version?: string | null | undefined;
}
/** Represents a ConsensusRegisterRequest. */
export class ConsensusRegisterRequest implements IConsensusRegisterRequest {
/**
* Constructs a new ConsensusRegisterRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusRegisterRequest);
/** ConsensusRegisterRequest name. */
public name: string;
/** ConsensusRegisterRequest version. */
public version: string;
/**
* Creates a new ConsensusRegisterRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusRegisterRequest instance
*/
public static create(properties?: IConsensusRegisterRequest): ConsensusRegisterRequest;
/**
* Encodes the specified ConsensusRegisterRequest message. Does not implicitly {@link ConsensusRegisterRequest.verify|verify} messages.
* @param message ConsensusRegisterRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusRegisterRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusRegisterRequest message, length delimited. Does not implicitly {@link ConsensusRegisterRequest.verify|verify} messages.
* @param message ConsensusRegisterRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusRegisterRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusRegisterRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusRegisterRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusRegisterRequest;
/**
* Decodes a ConsensusRegisterRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusRegisterRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusRegisterRequest;
/**
* Verifies a ConsensusRegisterRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusRegisterRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusRegisterRequest
*/
public static fromObject(object: { [k: string]: any }): ConsensusRegisterRequest;
/**
* Creates a plain object from a ConsensusRegisterRequest message. Also converts values to other types if specified.
* @param message ConsensusRegisterRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusRegisterRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusRegisterRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusRegisterResponse. */
export interface IConsensusRegisterResponse {
/** ConsensusRegisterResponse status */
status?: ConsensusRegisterResponse.Status | null | undefined;
/** ConsensusRegisterResponse chainHead */
chainHead?: IConsensusBlock | null | undefined;
/** ConsensusRegisterResponse peers */
peers?: IConsensusPeerInfo[] | null | undefined;
}
/** Represents a ConsensusRegisterResponse. */
export class ConsensusRegisterResponse implements IConsensusRegisterResponse {
/**
* Constructs a new ConsensusRegisterResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusRegisterResponse);
/** ConsensusRegisterResponse status. */
public status: ConsensusRegisterResponse.Status;
/** ConsensusRegisterResponse chainHead. */
public chainHead?: IConsensusBlock | null | undefined;
/** ConsensusRegisterResponse peers. */
public peers: IConsensusPeerInfo[];
/**
* Creates a new ConsensusRegisterResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusRegisterResponse instance
*/
public static create(properties?: IConsensusRegisterResponse): ConsensusRegisterResponse;
/**
* Encodes the specified ConsensusRegisterResponse message. Does not implicitly {@link ConsensusRegisterResponse.verify|verify} messages.
* @param message ConsensusRegisterResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusRegisterResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusRegisterResponse message, length delimited. Does not implicitly {@link ConsensusRegisterResponse.verify|verify} messages.
* @param message ConsensusRegisterResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusRegisterResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusRegisterResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusRegisterResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusRegisterResponse;
/**
* Decodes a ConsensusRegisterResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusRegisterResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusRegisterResponse;
/**
* Verifies a ConsensusRegisterResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusRegisterResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusRegisterResponse
*/
public static fromObject(object: { [k: string]: any }): ConsensusRegisterResponse;
/**
* Creates a plain object from a ConsensusRegisterResponse message. Also converts values to other types if specified.
* @param message ConsensusRegisterResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusRegisterResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusRegisterResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ConsensusRegisterResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
BAD_REQUEST = 2,
SERVICE_ERROR = 3,
NOT_READY = 4,
}
}
/** Properties of a ConsensusNotifyPeerConnected. */
export interface IConsensusNotifyPeerConnected {
/** ConsensusNotifyPeerConnected peerInfo */
peerInfo?: IConsensusPeerInfo | null | undefined;
}
/** Represents a ConsensusNotifyPeerConnected. */
export class ConsensusNotifyPeerConnected implements IConsensusNotifyPeerConnected {
/**
* Constructs a new ConsensusNotifyPeerConnected.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusNotifyPeerConnected);
/** ConsensusNotifyPeerConnected peerInfo. */
public peerInfo?: IConsensusPeerInfo | null | undefined;
/**
* Creates a new ConsensusNotifyPeerConnected instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusNotifyPeerConnected instance
*/
public static create(properties?: IConsensusNotifyPeerConnected): ConsensusNotifyPeerConnected;
/**
* Encodes the specified ConsensusNotifyPeerConnected message. Does not implicitly {@link ConsensusNotifyPeerConnected.verify|verify} messages.
* @param message ConsensusNotifyPeerConnected message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusNotifyPeerConnected, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusNotifyPeerConnected message, length delimited. Does not implicitly {@link ConsensusNotifyPeerConnected.verify|verify} messages.
* @param message ConsensusNotifyPeerConnected message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusNotifyPeerConnected, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusNotifyPeerConnected message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusNotifyPeerConnected
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusNotifyPeerConnected;
/**
* Decodes a ConsensusNotifyPeerConnected message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusNotifyPeerConnected
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusNotifyPeerConnected;
/**
* Verifies a ConsensusNotifyPeerConnected message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusNotifyPeerConnected message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusNotifyPeerConnected
*/
public static fromObject(object: { [k: string]: any }): ConsensusNotifyPeerConnected;
/**
* Creates a plain object from a ConsensusNotifyPeerConnected message. Also converts values to other types if specified.
* @param message ConsensusNotifyPeerConnected
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusNotifyPeerConnected,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusNotifyPeerConnected to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusNotifyPeerDisconnected. */
export interface IConsensusNotifyPeerDisconnected {
/** ConsensusNotifyPeerDisconnected peerId */
peerId?: Uint8Array | null | undefined;
}
/** Represents a ConsensusNotifyPeerDisconnected. */
export class ConsensusNotifyPeerDisconnected implements IConsensusNotifyPeerDisconnected {
/**
* Constructs a new ConsensusNotifyPeerDisconnected.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusNotifyPeerDisconnected);
/** ConsensusNotifyPeerDisconnected peerId. */
public peerId: Uint8Array;
/**
* Creates a new ConsensusNotifyPeerDisconnected instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusNotifyPeerDisconnected instance
*/
public static create(properties?: IConsensusNotifyPeerDisconnected): ConsensusNotifyPeerDisconnected;
/**
* Encodes the specified ConsensusNotifyPeerDisconnected message. Does not implicitly {@link ConsensusNotifyPeerDisconnected.verify|verify} messages.
* @param message ConsensusNotifyPeerDisconnected message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusNotifyPeerDisconnected, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusNotifyPeerDisconnected message, length delimited. Does not implicitly {@link ConsensusNotifyPeerDisconnected.verify|verify} messages.
* @param message ConsensusNotifyPeerDisconnected message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(
message: IConsensusNotifyPeerDisconnected,
writer?: $protobuf.Writer,
): $protobuf.Writer;
/**
* Decodes a ConsensusNotifyPeerDisconnected message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusNotifyPeerDisconnected
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusNotifyPeerDisconnected;
/**
* Decodes a ConsensusNotifyPeerDisconnected message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusNotifyPeerDisconnected
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusNotifyPeerDisconnected;
/**
* Verifies a ConsensusNotifyPeerDisconnected message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusNotifyPeerDisconnected message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusNotifyPeerDisconnected
*/
public static fromObject(object: { [k: string]: any }): ConsensusNotifyPeerDisconnected;
/**
* Creates a plain object from a ConsensusNotifyPeerDisconnected message. Also converts values to other types if specified.
* @param message ConsensusNotifyPeerDisconnected
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusNotifyPeerDisconnected,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusNotifyPeerDisconnected to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusNotifyPeerMessage. */
export interface IConsensusNotifyPeerMessage {
/** ConsensusNotifyPeerMessage message */
message?: IConsensusPeerMessage | null | undefined;
/** ConsensusNotifyPeerMessage senderId */
senderId?: Uint8Array | null | undefined;
}
/** Represents a ConsensusNotifyPeerMessage. */
export class ConsensusNotifyPeerMessage implements IConsensusNotifyPeerMessage {
/**
* Constructs a new ConsensusNotifyPeerMessage.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusNotifyPeerMessage);
/** ConsensusNotifyPeerMessage message. */
public message?: IConsensusPeerMessage | null | undefined;
/** ConsensusNotifyPeerMessage senderId. */
public senderId: Uint8Array;
/**
* Creates a new ConsensusNotifyPeerMessage instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusNotifyPeerMessage instance
*/
public static create(properties?: IConsensusNotifyPeerMessage): ConsensusNotifyPeerMessage;
/**
* Encodes the specified ConsensusNotifyPeerMessage message. Does not implicitly {@link ConsensusNotifyPeerMessage.verify|verify} messages.
* @param message ConsensusNotifyPeerMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusNotifyPeerMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusNotifyPeerMessage message, length delimited. Does not implicitly {@link ConsensusNotifyPeerMessage.verify|verify} messages.
* @param message ConsensusNotifyPeerMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusNotifyPeerMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusNotifyPeerMessage message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusNotifyPeerMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusNotifyPeerMessage;
/**
* Decodes a ConsensusNotifyPeerMessage message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusNotifyPeerMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusNotifyPeerMessage;
/**
* Verifies a ConsensusNotifyPeerMessage message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusNotifyPeerMessage message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusNotifyPeerMessage
*/
public static fromObject(object: { [k: string]: any }): ConsensusNotifyPeerMessage;
/**
* Creates a plain object from a ConsensusNotifyPeerMessage message. Also converts values to other types if specified.
* @param message ConsensusNotifyPeerMessage
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusNotifyPeerMessage,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusNotifyPeerMessage to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusNotifyBlockNew. */
export interface IConsensusNotifyBlockNew {
/** ConsensusNotifyBlockNew block */
block?: IConsensusBlock | null | undefined;
}
/** Represents a ConsensusNotifyBlockNew. */
export class ConsensusNotifyBlockNew implements IConsensusNotifyBlockNew {
/**
* Constructs a new ConsensusNotifyBlockNew.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusNotifyBlockNew);
/** ConsensusNotifyBlockNew block. */
public block?: IConsensusBlock | null | undefined;
/**
* Creates a new ConsensusNotifyBlockNew instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusNotifyBlockNew instance
*/
public static create(properties?: IConsensusNotifyBlockNew): ConsensusNotifyBlockNew;
/**
* Encodes the specified ConsensusNotifyBlockNew message. Does not implicitly {@link ConsensusNotifyBlockNew.verify|verify} messages.
* @param message ConsensusNotifyBlockNew message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusNotifyBlockNew, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusNotifyBlockNew message, length delimited. Does not implicitly {@link ConsensusNotifyBlockNew.verify|verify} messages.
* @param message ConsensusNotifyBlockNew message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusNotifyBlockNew, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusNotifyBlockNew message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusNotifyBlockNew
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusNotifyBlockNew;
/**
* Decodes a ConsensusNotifyBlockNew message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusNotifyBlockNew
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusNotifyBlockNew;
/**
* Verifies a ConsensusNotifyBlockNew message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusNotifyBlockNew message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusNotifyBlockNew
*/
public static fromObject(object: { [k: string]: any }): ConsensusNotifyBlockNew;
/**
* Creates a plain object from a ConsensusNotifyBlockNew message. Also converts values to other types if specified.
* @param message ConsensusNotifyBlockNew
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusNotifyBlockNew,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusNotifyBlockNew to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusNotifyBlockValid. */
export interface IConsensusNotifyBlockValid {
/** ConsensusNotifyBlockValid blockId */
blockId?: Uint8Array | null | undefined;
}
/** Represents a ConsensusNotifyBlockValid. */
export class ConsensusNotifyBlockValid implements IConsensusNotifyBlockValid {
/**
* Constructs a new ConsensusNotifyBlockValid.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusNotifyBlockValid);
/** ConsensusNotifyBlockValid blockId. */
public blockId: Uint8Array;
/**
* Creates a new ConsensusNotifyBlockValid instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusNotifyBlockValid instance
*/
public static create(properties?: IConsensusNotifyBlockValid): ConsensusNotifyBlockValid;
/**
* Encodes the specified ConsensusNotifyBlockValid message. Does not implicitly {@link ConsensusNotifyBlockValid.verify|verify} messages.
* @param message ConsensusNotifyBlockValid message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusNotifyBlockValid, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusNotifyBlockValid message, length delimited. Does not implicitly {@link ConsensusNotifyBlockValid.verify|verify} messages.
* @param message ConsensusNotifyBlockValid message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusNotifyBlockValid, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusNotifyBlockValid message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusNotifyBlockValid
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusNotifyBlockValid;
/**
* Decodes a ConsensusNotifyBlockValid message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusNotifyBlockValid
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusNotifyBlockValid;
/**
* Verifies a ConsensusNotifyBlockValid message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusNotifyBlockValid message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusNotifyBlockValid
*/
public static fromObject(object: { [k: string]: any }): ConsensusNotifyBlockValid;
/**
* Creates a plain object from a ConsensusNotifyBlockValid message. Also converts values to other types if specified.
* @param message ConsensusNotifyBlockValid
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusNotifyBlockValid,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusNotifyBlockValid to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusNotifyBlockInvalid. */
export interface IConsensusNotifyBlockInvalid {
/** ConsensusNotifyBlockInvalid blockId */
blockId?: Uint8Array | null | undefined;
}
/** Represents a ConsensusNotifyBlockInvalid. */
export class ConsensusNotifyBlockInvalid implements IConsensusNotifyBlockInvalid {
/**
* Constructs a new ConsensusNotifyBlockInvalid.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusNotifyBlockInvalid);
/** ConsensusNotifyBlockInvalid blockId. */
public blockId: Uint8Array;
/**
* Creates a new ConsensusNotifyBlockInvalid instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusNotifyBlockInvalid instance
*/
public static create(properties?: IConsensusNotifyBlockInvalid): ConsensusNotifyBlockInvalid;
/**
* Encodes the specified ConsensusNotifyBlockInvalid message. Does not implicitly {@link ConsensusNotifyBlockInvalid.verify|verify} messages.
* @param message ConsensusNotifyBlockInvalid message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusNotifyBlockInvalid, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusNotifyBlockInvalid message, length delimited. Does not implicitly {@link ConsensusNotifyBlockInvalid.verify|verify} messages.
* @param message ConsensusNotifyBlockInvalid message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusNotifyBlockInvalid, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusNotifyBlockInvalid message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusNotifyBlockInvalid
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusNotifyBlockInvalid;
/**
* Decodes a ConsensusNotifyBlockInvalid message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusNotifyBlockInvalid
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusNotifyBlockInvalid;
/**
* Verifies a ConsensusNotifyBlockInvalid message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusNotifyBlockInvalid message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusNotifyBlockInvalid
*/
public static fromObject(object: { [k: string]: any }): ConsensusNotifyBlockInvalid;
/**
* Creates a plain object from a ConsensusNotifyBlockInvalid message. Also converts values to other types if specified.
* @param message ConsensusNotifyBlockInvalid
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusNotifyBlockInvalid,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusNotifyBlockInvalid to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusNotifyBlockCommit. */
export interface IConsensusNotifyBlockCommit {
/** ConsensusNotifyBlockCommit blockId */
blockId?: Uint8Array | null | undefined;
}
/** Represents a ConsensusNotifyBlockCommit. */
export class ConsensusNotifyBlockCommit implements IConsensusNotifyBlockCommit {
/**
* Constructs a new ConsensusNotifyBlockCommit.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusNotifyBlockCommit);
/** ConsensusNotifyBlockCommit blockId. */
public blockId: Uint8Array;
/**
* Creates a new ConsensusNotifyBlockCommit instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusNotifyBlockCommit instance
*/
public static create(properties?: IConsensusNotifyBlockCommit): ConsensusNotifyBlockCommit;
/**
* Encodes the specified ConsensusNotifyBlockCommit message. Does not implicitly {@link ConsensusNotifyBlockCommit.verify|verify} messages.
* @param message ConsensusNotifyBlockCommit message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusNotifyBlockCommit, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusNotifyBlockCommit message, length delimited. Does not implicitly {@link ConsensusNotifyBlockCommit.verify|verify} messages.
* @param message ConsensusNotifyBlockCommit message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusNotifyBlockCommit, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusNotifyBlockCommit message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusNotifyBlockCommit
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusNotifyBlockCommit;
/**
* Decodes a ConsensusNotifyBlockCommit message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusNotifyBlockCommit
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusNotifyBlockCommit;
/**
* Verifies a ConsensusNotifyBlockCommit message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusNotifyBlockCommit message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusNotifyBlockCommit
*/
public static fromObject(object: { [k: string]: any }): ConsensusNotifyBlockCommit;
/**
* Creates a plain object from a ConsensusNotifyBlockCommit message. Also converts values to other types if specified.
* @param message ConsensusNotifyBlockCommit
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusNotifyBlockCommit,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusNotifyBlockCommit to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusNotifyAck. */
export interface IConsensusNotifyAck {}
/** Represents a ConsensusNotifyAck. */
export class ConsensusNotifyAck implements IConsensusNotifyAck {
/**
* Constructs a new ConsensusNotifyAck.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusNotifyAck);
/**
* Creates a new ConsensusNotifyAck instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusNotifyAck instance
*/
public static create(properties?: IConsensusNotifyAck): ConsensusNotifyAck;
/**
* Encodes the specified ConsensusNotifyAck message. Does not implicitly {@link ConsensusNotifyAck.verify|verify} messages.
* @param message ConsensusNotifyAck message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusNotifyAck, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusNotifyAck message, length delimited. Does not implicitly {@link ConsensusNotifyAck.verify|verify} messages.
* @param message ConsensusNotifyAck message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusNotifyAck, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusNotifyAck message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusNotifyAck
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusNotifyAck;
/**
* Decodes a ConsensusNotifyAck message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusNotifyAck
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusNotifyAck;
/**
* Verifies a ConsensusNotifyAck message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusNotifyAck message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusNotifyAck
*/
public static fromObject(object: { [k: string]: any }): ConsensusNotifyAck;
/**
* Creates a plain object from a ConsensusNotifyAck message. Also converts values to other types if specified.
* @param message ConsensusNotifyAck
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ConsensusNotifyAck, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ConsensusNotifyAck to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusSendToRequest. */
export interface IConsensusSendToRequest {
/** ConsensusSendToRequest message */
message?: IConsensusPeerMessage | null | undefined;
/** ConsensusSendToRequest peerId */
peerId?: Uint8Array | null | undefined;
}
/** Represents a ConsensusSendToRequest. */
export class ConsensusSendToRequest implements IConsensusSendToRequest {
/**
* Constructs a new ConsensusSendToRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusSendToRequest);
/** ConsensusSendToRequest message. */
public message?: IConsensusPeerMessage | null | undefined;
/** ConsensusSendToRequest peerId. */
public peerId: Uint8Array;
/**
* Creates a new ConsensusSendToRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusSendToRequest instance
*/
public static create(properties?: IConsensusSendToRequest): ConsensusSendToRequest;
/**
* Encodes the specified ConsensusSendToRequest message. Does not implicitly {@link ConsensusSendToRequest.verify|verify} messages.
* @param message ConsensusSendToRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusSendToRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusSendToRequest message, length delimited. Does not implicitly {@link ConsensusSendToRequest.verify|verify} messages.
* @param message ConsensusSendToRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusSendToRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusSendToRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusSendToRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusSendToRequest;
/**
* Decodes a ConsensusSendToRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusSendToRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusSendToRequest;
/**
* Verifies a ConsensusSendToRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusSendToRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusSendToRequest
*/
public static fromObject(object: { [k: string]: any }): ConsensusSendToRequest;
/**
* Creates a plain object from a ConsensusSendToRequest message. Also converts values to other types if specified.
* @param message ConsensusSendToRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusSendToRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusSendToRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusSendToResponse. */
export interface IConsensusSendToResponse {
/** ConsensusSendToResponse status */
status?: ConsensusSendToResponse.Status | null | undefined;
}
/** Represents a ConsensusSendToResponse. */
export class ConsensusSendToResponse implements IConsensusSendToResponse {
/**
* Constructs a new ConsensusSendToResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusSendToResponse);
/** ConsensusSendToResponse status. */
public status: ConsensusSendToResponse.Status;
/**
* Creates a new ConsensusSendToResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusSendToResponse instance
*/
public static create(properties?: IConsensusSendToResponse): ConsensusSendToResponse;
/**
* Encodes the specified ConsensusSendToResponse message. Does not implicitly {@link ConsensusSendToResponse.verify|verify} messages.
* @param message ConsensusSendToResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusSendToResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusSendToResponse message, length delimited. Does not implicitly {@link ConsensusSendToResponse.verify|verify} messages.
* @param message ConsensusSendToResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusSendToResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusSendToResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusSendToResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusSendToResponse;
/**
* Decodes a ConsensusSendToResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusSendToResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusSendToResponse;
/**
* Verifies a ConsensusSendToResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusSendToResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusSendToResponse
*/
public static fromObject(object: { [k: string]: any }): ConsensusSendToResponse;
/**
* Creates a plain object from a ConsensusSendToResponse message. Also converts values to other types if specified.
* @param message ConsensusSendToResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusSendToResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusSendToResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ConsensusSendToResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
BAD_REQUEST = 2,
SERVICE_ERROR = 3,
NOT_READY = 4,
UNKNOWN_PEER = 5,
}
}
/** Properties of a ConsensusBroadcastRequest. */
export interface IConsensusBroadcastRequest {
/** ConsensusBroadcastRequest message */
message?: IConsensusPeerMessage | null | undefined;
}
/** Represents a ConsensusBroadcastRequest. */
export class ConsensusBroadcastRequest implements IConsensusBroadcastRequest {
/**
* Constructs a new ConsensusBroadcastRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusBroadcastRequest);
/** ConsensusBroadcastRequest message. */
public message?: IConsensusPeerMessage | null | undefined;
/**
* Creates a new ConsensusBroadcastRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusBroadcastRequest instance
*/
public static create(properties?: IConsensusBroadcastRequest): ConsensusBroadcastRequest;
/**
* Encodes the specified ConsensusBroadcastRequest message. Does not implicitly {@link ConsensusBroadcastRequest.verify|verify} messages.
* @param message ConsensusBroadcastRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusBroadcastRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusBroadcastRequest message, length delimited. Does not implicitly {@link ConsensusBroadcastRequest.verify|verify} messages.
* @param message ConsensusBroadcastRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusBroadcastRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusBroadcastRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusBroadcastRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusBroadcastRequest;
/**
* Decodes a ConsensusBroadcastRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusBroadcastRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusBroadcastRequest;
/**
* Verifies a ConsensusBroadcastRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusBroadcastRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusBroadcastRequest
*/
public static fromObject(object: { [k: string]: any }): ConsensusBroadcastRequest;
/**
* Creates a plain object from a ConsensusBroadcastRequest message. Also converts values to other types if specified.
* @param message ConsensusBroadcastRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusBroadcastRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusBroadcastRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusBroadcastResponse. */
export interface IConsensusBroadcastResponse {
/** ConsensusBroadcastResponse status */
status?: ConsensusBroadcastResponse.Status | null | undefined;
}
/** Represents a ConsensusBroadcastResponse. */
export class ConsensusBroadcastResponse implements IConsensusBroadcastResponse {
/**
* Constructs a new ConsensusBroadcastResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusBroadcastResponse);
/** ConsensusBroadcastResponse status. */
public status: ConsensusBroadcastResponse.Status;
/**
* Creates a new ConsensusBroadcastResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusBroadcastResponse instance
*/
public static create(properties?: IConsensusBroadcastResponse): ConsensusBroadcastResponse;
/**
* Encodes the specified ConsensusBroadcastResponse message. Does not implicitly {@link ConsensusBroadcastResponse.verify|verify} messages.
* @param message ConsensusBroadcastResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusBroadcastResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusBroadcastResponse message, length delimited. Does not implicitly {@link ConsensusBroadcastResponse.verify|verify} messages.
* @param message ConsensusBroadcastResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusBroadcastResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusBroadcastResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusBroadcastResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusBroadcastResponse;
/**
* Decodes a ConsensusBroadcastResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusBroadcastResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusBroadcastResponse;
/**
* Verifies a ConsensusBroadcastResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusBroadcastResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusBroadcastResponse
*/
public static fromObject(object: { [k: string]: any }): ConsensusBroadcastResponse;
/**
* Creates a plain object from a ConsensusBroadcastResponse message. Also converts values to other types if specified.
* @param message ConsensusBroadcastResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusBroadcastResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusBroadcastResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ConsensusBroadcastResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
BAD_REQUEST = 2,
SERVICE_ERROR = 3,
NOT_READY = 4,
}
}
/** Properties of a ConsensusInitializeBlockRequest. */
export interface IConsensusInitializeBlockRequest {
/** ConsensusInitializeBlockRequest previousId */
previousId?: Uint8Array | null | undefined;
}
/** Represents a ConsensusInitializeBlockRequest. */
export class ConsensusInitializeBlockRequest implements IConsensusInitializeBlockRequest {
/**
* Constructs a new ConsensusInitializeBlockRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusInitializeBlockRequest);
/** ConsensusInitializeBlockRequest previousId. */
public previousId: Uint8Array;
/**
* Creates a new ConsensusInitializeBlockRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusInitializeBlockRequest instance
*/
public static create(properties?: IConsensusInitializeBlockRequest): ConsensusInitializeBlockRequest;
/**
* Encodes the specified ConsensusInitializeBlockRequest message. Does not implicitly {@link ConsensusInitializeBlockRequest.verify|verify} messages.
* @param message ConsensusInitializeBlockRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusInitializeBlockRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusInitializeBlockRequest message, length delimited. Does not implicitly {@link ConsensusInitializeBlockRequest.verify|verify} messages.
* @param message ConsensusInitializeBlockRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(
message: IConsensusInitializeBlockRequest,
writer?: $protobuf.Writer,
): $protobuf.Writer;
/**
* Decodes a ConsensusInitializeBlockRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusInitializeBlockRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusInitializeBlockRequest;
/**
* Decodes a ConsensusInitializeBlockRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusInitializeBlockRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusInitializeBlockRequest;
/**
* Verifies a ConsensusInitializeBlockRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusInitializeBlockRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusInitializeBlockRequest
*/
public static fromObject(object: { [k: string]: any }): ConsensusInitializeBlockRequest;
/**
* Creates a plain object from a ConsensusInitializeBlockRequest message. Also converts values to other types if specified.
* @param message ConsensusInitializeBlockRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusInitializeBlockRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusInitializeBlockRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusInitializeBlockResponse. */
export interface IConsensusInitializeBlockResponse {
/** ConsensusInitializeBlockResponse status */
status?: ConsensusInitializeBlockResponse.Status | null | undefined;
}
/** Represents a ConsensusInitializeBlockResponse. */
export class ConsensusInitializeBlockResponse implements IConsensusInitializeBlockResponse {
/**
* Constructs a new ConsensusInitializeBlockResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusInitializeBlockResponse);
/** ConsensusInitializeBlockResponse status. */
public status: ConsensusInitializeBlockResponse.Status;
/**
* Creates a new ConsensusInitializeBlockResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusInitializeBlockResponse instance
*/
public static create(properties?: IConsensusInitializeBlockResponse): ConsensusInitializeBlockResponse;
/**
* Encodes the specified ConsensusInitializeBlockResponse message. Does not implicitly {@link ConsensusInitializeBlockResponse.verify|verify} messages.
* @param message ConsensusInitializeBlockResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusInitializeBlockResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusInitializeBlockResponse message, length delimited. Does not implicitly {@link ConsensusInitializeBlockResponse.verify|verify} messages.
* @param message ConsensusInitializeBlockResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(
message: IConsensusInitializeBlockResponse,
writer?: $protobuf.Writer,
): $protobuf.Writer;
/**
* Decodes a ConsensusInitializeBlockResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusInitializeBlockResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusInitializeBlockResponse;
/**
* Decodes a ConsensusInitializeBlockResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusInitializeBlockResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusInitializeBlockResponse;
/**
* Verifies a ConsensusInitializeBlockResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusInitializeBlockResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusInitializeBlockResponse
*/
public static fromObject(object: { [k: string]: any }): ConsensusInitializeBlockResponse;
/**
* Creates a plain object from a ConsensusInitializeBlockResponse message. Also converts values to other types if specified.
* @param message ConsensusInitializeBlockResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusInitializeBlockResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusInitializeBlockResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ConsensusInitializeBlockResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
BAD_REQUEST = 2,
SERVICE_ERROR = 3,
NOT_READY = 4,
INVALID_STATE = 5,
UNKNOWN_BLOCK = 6,
}
}
/** Properties of a ConsensusSummarizeBlockRequest. */
export interface IConsensusSummarizeBlockRequest {}
/** Represents a ConsensusSummarizeBlockRequest. */
export class ConsensusSummarizeBlockRequest implements IConsensusSummarizeBlockRequest {
/**
* Constructs a new ConsensusSummarizeBlockRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusSummarizeBlockRequest);
/**
* Creates a new ConsensusSummarizeBlockRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusSummarizeBlockRequest instance
*/
public static create(properties?: IConsensusSummarizeBlockRequest): ConsensusSummarizeBlockRequest;
/**
* Encodes the specified ConsensusSummarizeBlockRequest message. Does not implicitly {@link ConsensusSummarizeBlockRequest.verify|verify} messages.
* @param message ConsensusSummarizeBlockRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusSummarizeBlockRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusSummarizeBlockRequest message, length delimited. Does not implicitly {@link ConsensusSummarizeBlockRequest.verify|verify} messages.
* @param message ConsensusSummarizeBlockRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(
message: IConsensusSummarizeBlockRequest,
writer?: $protobuf.Writer,
): $protobuf.Writer;
/**
* Decodes a ConsensusSummarizeBlockRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusSummarizeBlockRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusSummarizeBlockRequest;
/**
* Decodes a ConsensusSummarizeBlockRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusSummarizeBlockRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusSummarizeBlockRequest;
/**
* Verifies a ConsensusSummarizeBlockRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusSummarizeBlockRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusSummarizeBlockRequest
*/
public static fromObject(object: { [k: string]: any }): ConsensusSummarizeBlockRequest;
/**
* Creates a plain object from a ConsensusSummarizeBlockRequest message. Also converts values to other types if specified.
* @param message ConsensusSummarizeBlockRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusSummarizeBlockRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusSummarizeBlockRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusSummarizeBlockResponse. */
export interface IConsensusSummarizeBlockResponse {
/** ConsensusSummarizeBlockResponse status */
status?: ConsensusSummarizeBlockResponse.Status | null | undefined;
/** ConsensusSummarizeBlockResponse summary */
summary?: Uint8Array | null | undefined;
}
/** Represents a ConsensusSummarizeBlockResponse. */
export class ConsensusSummarizeBlockResponse implements IConsensusSummarizeBlockResponse {
/**
* Constructs a new ConsensusSummarizeBlockResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusSummarizeBlockResponse);
/** ConsensusSummarizeBlockResponse status. */
public status: ConsensusSummarizeBlockResponse.Status;
/** ConsensusSummarizeBlockResponse summary. */
public summary: Uint8Array;
/**
* Creates a new ConsensusSummarizeBlockResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusSummarizeBlockResponse instance
*/
public static create(properties?: IConsensusSummarizeBlockResponse): ConsensusSummarizeBlockResponse;
/**
* Encodes the specified ConsensusSummarizeBlockResponse message. Does not implicitly {@link ConsensusSummarizeBlockResponse.verify|verify} messages.
* @param message ConsensusSummarizeBlockResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusSummarizeBlockResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusSummarizeBlockResponse message, length delimited. Does not implicitly {@link ConsensusSummarizeBlockResponse.verify|verify} messages.
* @param message ConsensusSummarizeBlockResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(
message: IConsensusSummarizeBlockResponse,
writer?: $protobuf.Writer,
): $protobuf.Writer;
/**
* Decodes a ConsensusSummarizeBlockResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusSummarizeBlockResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusSummarizeBlockResponse;
/**
* Decodes a ConsensusSummarizeBlockResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusSummarizeBlockResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusSummarizeBlockResponse;
/**
* Verifies a ConsensusSummarizeBlockResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusSummarizeBlockResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusSummarizeBlockResponse
*/
public static fromObject(object: { [k: string]: any }): ConsensusSummarizeBlockResponse;
/**
* Creates a plain object from a ConsensusSummarizeBlockResponse message. Also converts values to other types if specified.
* @param message ConsensusSummarizeBlockResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusSummarizeBlockResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusSummarizeBlockResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ConsensusSummarizeBlockResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
BAD_REQUEST = 2,
SERVICE_ERROR = 3,
NOT_READY = 4,
INVALID_STATE = 5,
BLOCK_NOT_READY = 6,
}
}
/** Properties of a ConsensusFinalizeBlockRequest. */
export interface IConsensusFinalizeBlockRequest {
/** ConsensusFinalizeBlockRequest data */
data?: Uint8Array | null | undefined;
}
/** Represents a ConsensusFinalizeBlockRequest. */
export class ConsensusFinalizeBlockRequest implements IConsensusFinalizeBlockRequest {
/**
* Constructs a new ConsensusFinalizeBlockRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusFinalizeBlockRequest);
/** ConsensusFinalizeBlockRequest data. */
public data: Uint8Array;
/**
* Creates a new ConsensusFinalizeBlockRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusFinalizeBlockRequest instance
*/
public static create(properties?: IConsensusFinalizeBlockRequest): ConsensusFinalizeBlockRequest;
/**
* Encodes the specified ConsensusFinalizeBlockRequest message. Does not implicitly {@link ConsensusFinalizeBlockRequest.verify|verify} messages.
* @param message ConsensusFinalizeBlockRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusFinalizeBlockRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusFinalizeBlockRequest message, length delimited. Does not implicitly {@link ConsensusFinalizeBlockRequest.verify|verify} messages.
* @param message ConsensusFinalizeBlockRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusFinalizeBlockRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusFinalizeBlockRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusFinalizeBlockRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusFinalizeBlockRequest;
/**
* Decodes a ConsensusFinalizeBlockRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusFinalizeBlockRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusFinalizeBlockRequest;
/**
* Verifies a ConsensusFinalizeBlockRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusFinalizeBlockRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusFinalizeBlockRequest
*/
public static fromObject(object: { [k: string]: any }): ConsensusFinalizeBlockRequest;
/**
* Creates a plain object from a ConsensusFinalizeBlockRequest message. Also converts values to other types if specified.
* @param message ConsensusFinalizeBlockRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusFinalizeBlockRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusFinalizeBlockRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusFinalizeBlockResponse. */
export interface IConsensusFinalizeBlockResponse {
/** ConsensusFinalizeBlockResponse status */
status?: ConsensusFinalizeBlockResponse.Status | null | undefined;
/** ConsensusFinalizeBlockResponse blockId */
blockId?: Uint8Array | null | undefined;
}
/** Represents a ConsensusFinalizeBlockResponse. */
export class ConsensusFinalizeBlockResponse implements IConsensusFinalizeBlockResponse {
/**
* Constructs a new ConsensusFinalizeBlockResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusFinalizeBlockResponse);
/** ConsensusFinalizeBlockResponse status. */
public status: ConsensusFinalizeBlockResponse.Status;
/** ConsensusFinalizeBlockResponse blockId. */
public blockId: Uint8Array;
/**
* Creates a new ConsensusFinalizeBlockResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusFinalizeBlockResponse instance
*/
public static create(properties?: IConsensusFinalizeBlockResponse): ConsensusFinalizeBlockResponse;
/**
* Encodes the specified ConsensusFinalizeBlockResponse message. Does not implicitly {@link ConsensusFinalizeBlockResponse.verify|verify} messages.
* @param message ConsensusFinalizeBlockResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusFinalizeBlockResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusFinalizeBlockResponse message, length delimited. Does not implicitly {@link ConsensusFinalizeBlockResponse.verify|verify} messages.
* @param message ConsensusFinalizeBlockResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(
message: IConsensusFinalizeBlockResponse,
writer?: $protobuf.Writer,
): $protobuf.Writer;
/**
* Decodes a ConsensusFinalizeBlockResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusFinalizeBlockResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusFinalizeBlockResponse;
/**
* Decodes a ConsensusFinalizeBlockResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusFinalizeBlockResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusFinalizeBlockResponse;
/**
* Verifies a ConsensusFinalizeBlockResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusFinalizeBlockResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusFinalizeBlockResponse
*/
public static fromObject(object: { [k: string]: any }): ConsensusFinalizeBlockResponse;
/**
* Creates a plain object from a ConsensusFinalizeBlockResponse message. Also converts values to other types if specified.
* @param message ConsensusFinalizeBlockResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusFinalizeBlockResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusFinalizeBlockResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ConsensusFinalizeBlockResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
BAD_REQUEST = 2,
SERVICE_ERROR = 3,
NOT_READY = 4,
INVALID_STATE = 5,
BLOCK_NOT_READY = 6,
}
}
/** Properties of a ConsensusCancelBlockRequest. */
export interface IConsensusCancelBlockRequest {}
/** Represents a ConsensusCancelBlockRequest. */
export class ConsensusCancelBlockRequest implements IConsensusCancelBlockRequest {
/**
* Constructs a new ConsensusCancelBlockRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusCancelBlockRequest);
/**
* Creates a new ConsensusCancelBlockRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusCancelBlockRequest instance
*/
public static create(properties?: IConsensusCancelBlockRequest): ConsensusCancelBlockRequest;
/**
* Encodes the specified ConsensusCancelBlockRequest message. Does not implicitly {@link ConsensusCancelBlockRequest.verify|verify} messages.
* @param message ConsensusCancelBlockRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusCancelBlockRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusCancelBlockRequest message, length delimited. Does not implicitly {@link ConsensusCancelBlockRequest.verify|verify} messages.
* @param message ConsensusCancelBlockRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusCancelBlockRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusCancelBlockRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusCancelBlockRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusCancelBlockRequest;
/**
* Decodes a ConsensusCancelBlockRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusCancelBlockRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusCancelBlockRequest;
/**
* Verifies a ConsensusCancelBlockRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusCancelBlockRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusCancelBlockRequest
*/
public static fromObject(object: { [k: string]: any }): ConsensusCancelBlockRequest;
/**
* Creates a plain object from a ConsensusCancelBlockRequest message. Also converts values to other types if specified.
* @param message ConsensusCancelBlockRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusCancelBlockRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusCancelBlockRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusCancelBlockResponse. */
export interface IConsensusCancelBlockResponse {
/** ConsensusCancelBlockResponse status */
status?: ConsensusCancelBlockResponse.Status | null | undefined;
}
/** Represents a ConsensusCancelBlockResponse. */
export class ConsensusCancelBlockResponse implements IConsensusCancelBlockResponse {
/**
* Constructs a new ConsensusCancelBlockResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusCancelBlockResponse);
/** ConsensusCancelBlockResponse status. */
public status: ConsensusCancelBlockResponse.Status;
/**
* Creates a new ConsensusCancelBlockResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusCancelBlockResponse instance
*/
public static create(properties?: IConsensusCancelBlockResponse): ConsensusCancelBlockResponse;
/**
* Encodes the specified ConsensusCancelBlockResponse message. Does not implicitly {@link ConsensusCancelBlockResponse.verify|verify} messages.
* @param message ConsensusCancelBlockResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusCancelBlockResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusCancelBlockResponse message, length delimited. Does not implicitly {@link ConsensusCancelBlockResponse.verify|verify} messages.
* @param message ConsensusCancelBlockResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusCancelBlockResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusCancelBlockResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusCancelBlockResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusCancelBlockResponse;
/**
* Decodes a ConsensusCancelBlockResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusCancelBlockResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusCancelBlockResponse;
/**
* Verifies a ConsensusCancelBlockResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusCancelBlockResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusCancelBlockResponse
*/
public static fromObject(object: { [k: string]: any }): ConsensusCancelBlockResponse;
/**
* Creates a plain object from a ConsensusCancelBlockResponse message. Also converts values to other types if specified.
* @param message ConsensusCancelBlockResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusCancelBlockResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusCancelBlockResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ConsensusCancelBlockResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
BAD_REQUEST = 2,
SERVICE_ERROR = 3,
NOT_READY = 4,
INVALID_STATE = 5,
}
}
/** Properties of a ConsensusCheckBlocksRequest. */
export interface IConsensusCheckBlocksRequest {
/** ConsensusCheckBlocksRequest blockIds */
blockIds?: Uint8Array[] | null | undefined;
}
/** Represents a ConsensusCheckBlocksRequest. */
export class ConsensusCheckBlocksRequest implements IConsensusCheckBlocksRequest {
/**
* Constructs a new ConsensusCheckBlocksRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusCheckBlocksRequest);
/** ConsensusCheckBlocksRequest blockIds. */
public blockIds: Uint8Array[];
/**
* Creates a new ConsensusCheckBlocksRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusCheckBlocksRequest instance
*/
public static create(properties?: IConsensusCheckBlocksRequest): ConsensusCheckBlocksRequest;
/**
* Encodes the specified ConsensusCheckBlocksRequest message. Does not implicitly {@link ConsensusCheckBlocksRequest.verify|verify} messages.
* @param message ConsensusCheckBlocksRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusCheckBlocksRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusCheckBlocksRequest message, length delimited. Does not implicitly {@link ConsensusCheckBlocksRequest.verify|verify} messages.
* @param message ConsensusCheckBlocksRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusCheckBlocksRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusCheckBlocksRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusCheckBlocksRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusCheckBlocksRequest;
/**
* Decodes a ConsensusCheckBlocksRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusCheckBlocksRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusCheckBlocksRequest;
/**
* Verifies a ConsensusCheckBlocksRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusCheckBlocksRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusCheckBlocksRequest
*/
public static fromObject(object: { [k: string]: any }): ConsensusCheckBlocksRequest;
/**
* Creates a plain object from a ConsensusCheckBlocksRequest message. Also converts values to other types if specified.
* @param message ConsensusCheckBlocksRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusCheckBlocksRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusCheckBlocksRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusCheckBlocksResponse. */
export interface IConsensusCheckBlocksResponse {
/** ConsensusCheckBlocksResponse status */
status?: ConsensusCheckBlocksResponse.Status | null | undefined;
}
/** Represents a ConsensusCheckBlocksResponse. */
export class ConsensusCheckBlocksResponse implements IConsensusCheckBlocksResponse {
/**
* Constructs a new ConsensusCheckBlocksResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusCheckBlocksResponse);
/** ConsensusCheckBlocksResponse status. */
public status: ConsensusCheckBlocksResponse.Status;
/**
* Creates a new ConsensusCheckBlocksResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusCheckBlocksResponse instance
*/
public static create(properties?: IConsensusCheckBlocksResponse): ConsensusCheckBlocksResponse;
/**
* Encodes the specified ConsensusCheckBlocksResponse message. Does not implicitly {@link ConsensusCheckBlocksResponse.verify|verify} messages.
* @param message ConsensusCheckBlocksResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusCheckBlocksResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusCheckBlocksResponse message, length delimited. Does not implicitly {@link ConsensusCheckBlocksResponse.verify|verify} messages.
* @param message ConsensusCheckBlocksResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusCheckBlocksResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusCheckBlocksResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusCheckBlocksResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusCheckBlocksResponse;
/**
* Decodes a ConsensusCheckBlocksResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusCheckBlocksResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusCheckBlocksResponse;
/**
* Verifies a ConsensusCheckBlocksResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusCheckBlocksResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusCheckBlocksResponse
*/
public static fromObject(object: { [k: string]: any }): ConsensusCheckBlocksResponse;
/**
* Creates a plain object from a ConsensusCheckBlocksResponse message. Also converts values to other types if specified.
* @param message ConsensusCheckBlocksResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusCheckBlocksResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusCheckBlocksResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ConsensusCheckBlocksResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
BAD_REQUEST = 2,
SERVICE_ERROR = 3,
NOT_READY = 4,
UNKNOWN_BLOCK = 5,
}
}
/** Properties of a ConsensusCommitBlockRequest. */
export interface IConsensusCommitBlockRequest {
/** ConsensusCommitBlockRequest blockId */
blockId?: Uint8Array | null | undefined;
}
/** Represents a ConsensusCommitBlockRequest. */
export class ConsensusCommitBlockRequest implements IConsensusCommitBlockRequest {
/**
* Constructs a new ConsensusCommitBlockRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusCommitBlockRequest);
/** ConsensusCommitBlockRequest blockId. */
public blockId: Uint8Array;
/**
* Creates a new ConsensusCommitBlockRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusCommitBlockRequest instance
*/
public static create(properties?: IConsensusCommitBlockRequest): ConsensusCommitBlockRequest;
/**
* Encodes the specified ConsensusCommitBlockRequest message. Does not implicitly {@link ConsensusCommitBlockRequest.verify|verify} messages.
* @param message ConsensusCommitBlockRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusCommitBlockRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusCommitBlockRequest message, length delimited. Does not implicitly {@link ConsensusCommitBlockRequest.verify|verify} messages.
* @param message ConsensusCommitBlockRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusCommitBlockRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusCommitBlockRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusCommitBlockRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusCommitBlockRequest;
/**
* Decodes a ConsensusCommitBlockRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusCommitBlockRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusCommitBlockRequest;
/**
* Verifies a ConsensusCommitBlockRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusCommitBlockRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusCommitBlockRequest
*/
public static fromObject(object: { [k: string]: any }): ConsensusCommitBlockRequest;
/**
* Creates a plain object from a ConsensusCommitBlockRequest message. Also converts values to other types if specified.
* @param message ConsensusCommitBlockRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusCommitBlockRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusCommitBlockRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusCommitBlockResponse. */
export interface IConsensusCommitBlockResponse {
/** ConsensusCommitBlockResponse status */
status?: ConsensusCommitBlockResponse.Status | null | undefined;
}
/** Represents a ConsensusCommitBlockResponse. */
export class ConsensusCommitBlockResponse implements IConsensusCommitBlockResponse {
/**
* Constructs a new ConsensusCommitBlockResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusCommitBlockResponse);
/** ConsensusCommitBlockResponse status. */
public status: ConsensusCommitBlockResponse.Status;
/**
* Creates a new ConsensusCommitBlockResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusCommitBlockResponse instance
*/
public static create(properties?: IConsensusCommitBlockResponse): ConsensusCommitBlockResponse;
/**
* Encodes the specified ConsensusCommitBlockResponse message. Does not implicitly {@link ConsensusCommitBlockResponse.verify|verify} messages.
* @param message ConsensusCommitBlockResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusCommitBlockResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusCommitBlockResponse message, length delimited. Does not implicitly {@link ConsensusCommitBlockResponse.verify|verify} messages.
* @param message ConsensusCommitBlockResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusCommitBlockResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusCommitBlockResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusCommitBlockResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusCommitBlockResponse;
/**
* Decodes a ConsensusCommitBlockResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusCommitBlockResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusCommitBlockResponse;
/**
* Verifies a ConsensusCommitBlockResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusCommitBlockResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusCommitBlockResponse
*/
public static fromObject(object: { [k: string]: any }): ConsensusCommitBlockResponse;
/**
* Creates a plain object from a ConsensusCommitBlockResponse message. Also converts values to other types if specified.
* @param message ConsensusCommitBlockResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusCommitBlockResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusCommitBlockResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ConsensusCommitBlockResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
BAD_REQUEST = 2,
SERVICE_ERROR = 3,
NOT_READY = 4,
UNKNOWN_BLOCK = 5,
}
}
/** Properties of a ConsensusIgnoreBlockRequest. */
export interface IConsensusIgnoreBlockRequest {
/** ConsensusIgnoreBlockRequest blockId */
blockId?: Uint8Array | null | undefined;
}
/** Represents a ConsensusIgnoreBlockRequest. */
export class ConsensusIgnoreBlockRequest implements IConsensusIgnoreBlockRequest {
/**
* Constructs a new ConsensusIgnoreBlockRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusIgnoreBlockRequest);
/** ConsensusIgnoreBlockRequest blockId. */
public blockId: Uint8Array;
/**
* Creates a new ConsensusIgnoreBlockRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusIgnoreBlockRequest instance
*/
public static create(properties?: IConsensusIgnoreBlockRequest): ConsensusIgnoreBlockRequest;
/**
* Encodes the specified ConsensusIgnoreBlockRequest message. Does not implicitly {@link ConsensusIgnoreBlockRequest.verify|verify} messages.
* @param message ConsensusIgnoreBlockRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusIgnoreBlockRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusIgnoreBlockRequest message, length delimited. Does not implicitly {@link ConsensusIgnoreBlockRequest.verify|verify} messages.
* @param message ConsensusIgnoreBlockRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusIgnoreBlockRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusIgnoreBlockRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusIgnoreBlockRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusIgnoreBlockRequest;
/**
* Decodes a ConsensusIgnoreBlockRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusIgnoreBlockRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusIgnoreBlockRequest;
/**
* Verifies a ConsensusIgnoreBlockRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusIgnoreBlockRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusIgnoreBlockRequest
*/
public static fromObject(object: { [k: string]: any }): ConsensusIgnoreBlockRequest;
/**
* Creates a plain object from a ConsensusIgnoreBlockRequest message. Also converts values to other types if specified.
* @param message ConsensusIgnoreBlockRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusIgnoreBlockRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusIgnoreBlockRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusIgnoreBlockResponse. */
export interface IConsensusIgnoreBlockResponse {
/** ConsensusIgnoreBlockResponse status */
status?: ConsensusIgnoreBlockResponse.Status | null | undefined;
}
/** Represents a ConsensusIgnoreBlockResponse. */
export class ConsensusIgnoreBlockResponse implements IConsensusIgnoreBlockResponse {
/**
* Constructs a new ConsensusIgnoreBlockResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusIgnoreBlockResponse);
/** ConsensusIgnoreBlockResponse status. */
public status: ConsensusIgnoreBlockResponse.Status;
/**
* Creates a new ConsensusIgnoreBlockResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusIgnoreBlockResponse instance
*/
public static create(properties?: IConsensusIgnoreBlockResponse): ConsensusIgnoreBlockResponse;
/**
* Encodes the specified ConsensusIgnoreBlockResponse message. Does not implicitly {@link ConsensusIgnoreBlockResponse.verify|verify} messages.
* @param message ConsensusIgnoreBlockResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusIgnoreBlockResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusIgnoreBlockResponse message, length delimited. Does not implicitly {@link ConsensusIgnoreBlockResponse.verify|verify} messages.
* @param message ConsensusIgnoreBlockResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusIgnoreBlockResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusIgnoreBlockResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusIgnoreBlockResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusIgnoreBlockResponse;
/**
* Decodes a ConsensusIgnoreBlockResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusIgnoreBlockResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusIgnoreBlockResponse;
/**
* Verifies a ConsensusIgnoreBlockResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusIgnoreBlockResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusIgnoreBlockResponse
*/
public static fromObject(object: { [k: string]: any }): ConsensusIgnoreBlockResponse;
/**
* Creates a plain object from a ConsensusIgnoreBlockResponse message. Also converts values to other types if specified.
* @param message ConsensusIgnoreBlockResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusIgnoreBlockResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusIgnoreBlockResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ConsensusIgnoreBlockResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
BAD_REQUEST = 2,
SERVICE_ERROR = 3,
NOT_READY = 4,
UNKNOWN_BLOCK = 5,
}
}
/** Properties of a ConsensusFailBlockRequest. */
export interface IConsensusFailBlockRequest {
/** ConsensusFailBlockRequest blockId */
blockId?: Uint8Array | null | undefined;
}
/** Represents a ConsensusFailBlockRequest. */
export class ConsensusFailBlockRequest implements IConsensusFailBlockRequest {
/**
* Constructs a new ConsensusFailBlockRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusFailBlockRequest);
/** ConsensusFailBlockRequest blockId. */
public blockId: Uint8Array;
/**
* Creates a new ConsensusFailBlockRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusFailBlockRequest instance
*/
public static create(properties?: IConsensusFailBlockRequest): ConsensusFailBlockRequest;
/**
* Encodes the specified ConsensusFailBlockRequest message. Does not implicitly {@link ConsensusFailBlockRequest.verify|verify} messages.
* @param message ConsensusFailBlockRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusFailBlockRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusFailBlockRequest message, length delimited. Does not implicitly {@link ConsensusFailBlockRequest.verify|verify} messages.
* @param message ConsensusFailBlockRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusFailBlockRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusFailBlockRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusFailBlockRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusFailBlockRequest;
/**
* Decodes a ConsensusFailBlockRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusFailBlockRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusFailBlockRequest;
/**
* Verifies a ConsensusFailBlockRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusFailBlockRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusFailBlockRequest
*/
public static fromObject(object: { [k: string]: any }): ConsensusFailBlockRequest;
/**
* Creates a plain object from a ConsensusFailBlockRequest message. Also converts values to other types if specified.
* @param message ConsensusFailBlockRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusFailBlockRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusFailBlockRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusFailBlockResponse. */
export interface IConsensusFailBlockResponse {
/** ConsensusFailBlockResponse status */
status?: ConsensusFailBlockResponse.Status | null | undefined;
}
/** Represents a ConsensusFailBlockResponse. */
export class ConsensusFailBlockResponse implements IConsensusFailBlockResponse {
/**
* Constructs a new ConsensusFailBlockResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusFailBlockResponse);
/** ConsensusFailBlockResponse status. */
public status: ConsensusFailBlockResponse.Status;
/**
* Creates a new ConsensusFailBlockResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusFailBlockResponse instance
*/
public static create(properties?: IConsensusFailBlockResponse): ConsensusFailBlockResponse;
/**
* Encodes the specified ConsensusFailBlockResponse message. Does not implicitly {@link ConsensusFailBlockResponse.verify|verify} messages.
* @param message ConsensusFailBlockResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusFailBlockResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusFailBlockResponse message, length delimited. Does not implicitly {@link ConsensusFailBlockResponse.verify|verify} messages.
* @param message ConsensusFailBlockResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusFailBlockResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusFailBlockResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusFailBlockResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusFailBlockResponse;
/**
* Decodes a ConsensusFailBlockResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusFailBlockResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusFailBlockResponse;
/**
* Verifies a ConsensusFailBlockResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusFailBlockResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusFailBlockResponse
*/
public static fromObject(object: { [k: string]: any }): ConsensusFailBlockResponse;
/**
* Creates a plain object from a ConsensusFailBlockResponse message. Also converts values to other types if specified.
* @param message ConsensusFailBlockResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusFailBlockResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusFailBlockResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ConsensusFailBlockResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
BAD_REQUEST = 2,
SERVICE_ERROR = 3,
NOT_READY = 4,
UNKNOWN_BLOCK = 5,
}
}
/** Properties of a ConsensusBlocksGetRequest. */
export interface IConsensusBlocksGetRequest {
/** ConsensusBlocksGetRequest blockIds */
blockIds?: Uint8Array[] | null | undefined;
}
/** Represents a ConsensusBlocksGetRequest. */
export class ConsensusBlocksGetRequest implements IConsensusBlocksGetRequest {
/**
* Constructs a new ConsensusBlocksGetRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusBlocksGetRequest);
/** ConsensusBlocksGetRequest blockIds. */
public blockIds: Uint8Array[];
/**
* Creates a new ConsensusBlocksGetRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusBlocksGetRequest instance
*/
public static create(properties?: IConsensusBlocksGetRequest): ConsensusBlocksGetRequest;
/**
* Encodes the specified ConsensusBlocksGetRequest message. Does not implicitly {@link ConsensusBlocksGetRequest.verify|verify} messages.
* @param message ConsensusBlocksGetRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusBlocksGetRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusBlocksGetRequest message, length delimited. Does not implicitly {@link ConsensusBlocksGetRequest.verify|verify} messages.
* @param message ConsensusBlocksGetRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusBlocksGetRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusBlocksGetRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusBlocksGetRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusBlocksGetRequest;
/**
* Decodes a ConsensusBlocksGetRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusBlocksGetRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusBlocksGetRequest;
/**
* Verifies a ConsensusBlocksGetRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusBlocksGetRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusBlocksGetRequest
*/
public static fromObject(object: { [k: string]: any }): ConsensusBlocksGetRequest;
/**
* Creates a plain object from a ConsensusBlocksGetRequest message. Also converts values to other types if specified.
* @param message ConsensusBlocksGetRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusBlocksGetRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusBlocksGetRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusBlocksGetResponse. */
export interface IConsensusBlocksGetResponse {
/** ConsensusBlocksGetResponse status */
status?: ConsensusBlocksGetResponse.Status | null | undefined;
/** ConsensusBlocksGetResponse blocks */
blocks?: IConsensusBlock[] | null | undefined;
}
/** Represents a ConsensusBlocksGetResponse. */
export class ConsensusBlocksGetResponse implements IConsensusBlocksGetResponse {
/**
* Constructs a new ConsensusBlocksGetResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusBlocksGetResponse);
/** ConsensusBlocksGetResponse status. */
public status: ConsensusBlocksGetResponse.Status;
/** ConsensusBlocksGetResponse blocks. */
public blocks: IConsensusBlock[];
/**
* Creates a new ConsensusBlocksGetResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusBlocksGetResponse instance
*/
public static create(properties?: IConsensusBlocksGetResponse): ConsensusBlocksGetResponse;
/**
* Encodes the specified ConsensusBlocksGetResponse message. Does not implicitly {@link ConsensusBlocksGetResponse.verify|verify} messages.
* @param message ConsensusBlocksGetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusBlocksGetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusBlocksGetResponse message, length delimited. Does not implicitly {@link ConsensusBlocksGetResponse.verify|verify} messages.
* @param message ConsensusBlocksGetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusBlocksGetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusBlocksGetResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusBlocksGetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusBlocksGetResponse;
/**
* Decodes a ConsensusBlocksGetResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusBlocksGetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusBlocksGetResponse;
/**
* Verifies a ConsensusBlocksGetResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusBlocksGetResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusBlocksGetResponse
*/
public static fromObject(object: { [k: string]: any }): ConsensusBlocksGetResponse;
/**
* Creates a plain object from a ConsensusBlocksGetResponse message. Also converts values to other types if specified.
* @param message ConsensusBlocksGetResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusBlocksGetResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusBlocksGetResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ConsensusBlocksGetResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
BAD_REQUEST = 2,
SERVICE_ERROR = 3,
NOT_READY = 4,
UNKNOWN_BLOCK = 5,
}
}
/** Properties of a ConsensusChainHeadGetRequest. */
export interface IConsensusChainHeadGetRequest {}
/** Represents a ConsensusChainHeadGetRequest. */
export class ConsensusChainHeadGetRequest implements IConsensusChainHeadGetRequest {
/**
* Constructs a new ConsensusChainHeadGetRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusChainHeadGetRequest);
/**
* Creates a new ConsensusChainHeadGetRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusChainHeadGetRequest instance
*/
public static create(properties?: IConsensusChainHeadGetRequest): ConsensusChainHeadGetRequest;
/**
* Encodes the specified ConsensusChainHeadGetRequest message. Does not implicitly {@link ConsensusChainHeadGetRequest.verify|verify} messages.
* @param message ConsensusChainHeadGetRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusChainHeadGetRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusChainHeadGetRequest message, length delimited. Does not implicitly {@link ConsensusChainHeadGetRequest.verify|verify} messages.
* @param message ConsensusChainHeadGetRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusChainHeadGetRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusChainHeadGetRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusChainHeadGetRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusChainHeadGetRequest;
/**
* Decodes a ConsensusChainHeadGetRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusChainHeadGetRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusChainHeadGetRequest;
/**
* Verifies a ConsensusChainHeadGetRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusChainHeadGetRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusChainHeadGetRequest
*/
public static fromObject(object: { [k: string]: any }): ConsensusChainHeadGetRequest;
/**
* Creates a plain object from a ConsensusChainHeadGetRequest message. Also converts values to other types if specified.
* @param message ConsensusChainHeadGetRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusChainHeadGetRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusChainHeadGetRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusChainHeadGetResponse. */
export interface IConsensusChainHeadGetResponse {
/** ConsensusChainHeadGetResponse status */
status?: ConsensusChainHeadGetResponse.Status | null | undefined;
/** ConsensusChainHeadGetResponse block */
block?: IConsensusBlock | null | undefined;
}
/** Represents a ConsensusChainHeadGetResponse. */
export class ConsensusChainHeadGetResponse implements IConsensusChainHeadGetResponse {
/**
* Constructs a new ConsensusChainHeadGetResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusChainHeadGetResponse);
/** ConsensusChainHeadGetResponse status. */
public status: ConsensusChainHeadGetResponse.Status;
/** ConsensusChainHeadGetResponse block. */
public block?: IConsensusBlock | null | undefined;
/**
* Creates a new ConsensusChainHeadGetResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusChainHeadGetResponse instance
*/
public static create(properties?: IConsensusChainHeadGetResponse): ConsensusChainHeadGetResponse;
/**
* Encodes the specified ConsensusChainHeadGetResponse message. Does not implicitly {@link ConsensusChainHeadGetResponse.verify|verify} messages.
* @param message ConsensusChainHeadGetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusChainHeadGetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusChainHeadGetResponse message, length delimited. Does not implicitly {@link ConsensusChainHeadGetResponse.verify|verify} messages.
* @param message ConsensusChainHeadGetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusChainHeadGetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusChainHeadGetResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusChainHeadGetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusChainHeadGetResponse;
/**
* Decodes a ConsensusChainHeadGetResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusChainHeadGetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusChainHeadGetResponse;
/**
* Verifies a ConsensusChainHeadGetResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusChainHeadGetResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusChainHeadGetResponse
*/
public static fromObject(object: { [k: string]: any }): ConsensusChainHeadGetResponse;
/**
* Creates a plain object from a ConsensusChainHeadGetResponse message. Also converts values to other types if specified.
* @param message ConsensusChainHeadGetResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusChainHeadGetResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusChainHeadGetResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ConsensusChainHeadGetResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
BAD_REQUEST = 2,
SERVICE_ERROR = 3,
NOT_READY = 4,
NO_CHAIN_HEAD = 5,
}
}
/** Properties of a ConsensusSettingsGetRequest. */
export interface IConsensusSettingsGetRequest {
/** ConsensusSettingsGetRequest blockId */
blockId?: Uint8Array | null | undefined;
/** ConsensusSettingsGetRequest keys */
keys?: string[] | null | undefined;
}
/** Represents a ConsensusSettingsGetRequest. */
export class ConsensusSettingsGetRequest implements IConsensusSettingsGetRequest {
/**
* Constructs a new ConsensusSettingsGetRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusSettingsGetRequest);
/** ConsensusSettingsGetRequest blockId. */
public blockId: Uint8Array;
/** ConsensusSettingsGetRequest keys. */
public keys: string[];
/**
* Creates a new ConsensusSettingsGetRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusSettingsGetRequest instance
*/
public static create(properties?: IConsensusSettingsGetRequest): ConsensusSettingsGetRequest;
/**
* Encodes the specified ConsensusSettingsGetRequest message. Does not implicitly {@link ConsensusSettingsGetRequest.verify|verify} messages.
* @param message ConsensusSettingsGetRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusSettingsGetRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusSettingsGetRequest message, length delimited. Does not implicitly {@link ConsensusSettingsGetRequest.verify|verify} messages.
* @param message ConsensusSettingsGetRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusSettingsGetRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusSettingsGetRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusSettingsGetRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusSettingsGetRequest;
/**
* Decodes a ConsensusSettingsGetRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusSettingsGetRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusSettingsGetRequest;
/**
* Verifies a ConsensusSettingsGetRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusSettingsGetRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusSettingsGetRequest
*/
public static fromObject(object: { [k: string]: any }): ConsensusSettingsGetRequest;
/**
* Creates a plain object from a ConsensusSettingsGetRequest message. Also converts values to other types if specified.
* @param message ConsensusSettingsGetRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusSettingsGetRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusSettingsGetRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusSettingsGetResponse. */
export interface IConsensusSettingsGetResponse {
/** ConsensusSettingsGetResponse status */
status?: ConsensusSettingsGetResponse.Status | null | undefined;
/** ConsensusSettingsGetResponse entries */
entries?: IConsensusSettingsEntry[] | null | undefined;
}
/** Represents a ConsensusSettingsGetResponse. */
export class ConsensusSettingsGetResponse implements IConsensusSettingsGetResponse {
/**
* Constructs a new ConsensusSettingsGetResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusSettingsGetResponse);
/** ConsensusSettingsGetResponse status. */
public status: ConsensusSettingsGetResponse.Status;
/** ConsensusSettingsGetResponse entries. */
public entries: IConsensusSettingsEntry[];
/**
* Creates a new ConsensusSettingsGetResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusSettingsGetResponse instance
*/
public static create(properties?: IConsensusSettingsGetResponse): ConsensusSettingsGetResponse;
/**
* Encodes the specified ConsensusSettingsGetResponse message. Does not implicitly {@link ConsensusSettingsGetResponse.verify|verify} messages.
* @param message ConsensusSettingsGetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusSettingsGetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusSettingsGetResponse message, length delimited. Does not implicitly {@link ConsensusSettingsGetResponse.verify|verify} messages.
* @param message ConsensusSettingsGetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusSettingsGetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusSettingsGetResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusSettingsGetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusSettingsGetResponse;
/**
* Decodes a ConsensusSettingsGetResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusSettingsGetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusSettingsGetResponse;
/**
* Verifies a ConsensusSettingsGetResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusSettingsGetResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusSettingsGetResponse
*/
public static fromObject(object: { [k: string]: any }): ConsensusSettingsGetResponse;
/**
* Creates a plain object from a ConsensusSettingsGetResponse message. Also converts values to other types if specified.
* @param message ConsensusSettingsGetResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusSettingsGetResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusSettingsGetResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ConsensusSettingsGetResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
BAD_REQUEST = 2,
SERVICE_ERROR = 3,
NOT_READY = 4,
UNKNOWN_BLOCK = 5,
}
}
/** Properties of a ConsensusStateGetRequest. */
export interface IConsensusStateGetRequest {
/** ConsensusStateGetRequest blockId */
blockId?: Uint8Array | null | undefined;
/** ConsensusStateGetRequest addresses */
addresses?: string[] | null | undefined;
}
/** Represents a ConsensusStateGetRequest. */
export class ConsensusStateGetRequest implements IConsensusStateGetRequest {
/**
* Constructs a new ConsensusStateGetRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusStateGetRequest);
/** ConsensusStateGetRequest blockId. */
public blockId: Uint8Array;
/** ConsensusStateGetRequest addresses. */
public addresses: string[];
/**
* Creates a new ConsensusStateGetRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusStateGetRequest instance
*/
public static create(properties?: IConsensusStateGetRequest): ConsensusStateGetRequest;
/**
* Encodes the specified ConsensusStateGetRequest message. Does not implicitly {@link ConsensusStateGetRequest.verify|verify} messages.
* @param message ConsensusStateGetRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusStateGetRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusStateGetRequest message, length delimited. Does not implicitly {@link ConsensusStateGetRequest.verify|verify} messages.
* @param message ConsensusStateGetRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusStateGetRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusStateGetRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusStateGetRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusStateGetRequest;
/**
* Decodes a ConsensusStateGetRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusStateGetRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusStateGetRequest;
/**
* Verifies a ConsensusStateGetRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusStateGetRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusStateGetRequest
*/
public static fromObject(object: { [k: string]: any }): ConsensusStateGetRequest;
/**
* Creates a plain object from a ConsensusStateGetRequest message. Also converts values to other types if specified.
* @param message ConsensusStateGetRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusStateGetRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusStateGetRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ConsensusStateGetResponse. */
export interface IConsensusStateGetResponse {
/** ConsensusStateGetResponse status */
status?: ConsensusStateGetResponse.Status | null | undefined;
/** ConsensusStateGetResponse entries */
entries?: IConsensusStateEntry[] | null | undefined;
}
/** Represents a ConsensusStateGetResponse. */
export class ConsensusStateGetResponse implements IConsensusStateGetResponse {
/**
* Constructs a new ConsensusStateGetResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IConsensusStateGetResponse);
/** ConsensusStateGetResponse status. */
public status: ConsensusStateGetResponse.Status;
/** ConsensusStateGetResponse entries. */
public entries: IConsensusStateEntry[];
/**
* Creates a new ConsensusStateGetResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns ConsensusStateGetResponse instance
*/
public static create(properties?: IConsensusStateGetResponse): ConsensusStateGetResponse;
/**
* Encodes the specified ConsensusStateGetResponse message. Does not implicitly {@link ConsensusStateGetResponse.verify|verify} messages.
* @param message ConsensusStateGetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IConsensusStateGetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ConsensusStateGetResponse message, length delimited. Does not implicitly {@link ConsensusStateGetResponse.verify|verify} messages.
* @param message ConsensusStateGetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IConsensusStateGetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ConsensusStateGetResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ConsensusStateGetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ConsensusStateGetResponse;
/**
* Decodes a ConsensusStateGetResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ConsensusStateGetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ConsensusStateGetResponse;
/**
* Verifies a ConsensusStateGetResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ConsensusStateGetResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ConsensusStateGetResponse
*/
public static fromObject(object: { [k: string]: any }): ConsensusStateGetResponse;
/**
* Creates a plain object from a ConsensusStateGetResponse message. Also converts values to other types if specified.
* @param message ConsensusStateGetResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ConsensusStateGetResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this ConsensusStateGetResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ConsensusStateGetResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
BAD_REQUEST = 2,
SERVICE_ERROR = 3,
NOT_READY = 4,
UNKNOWN_BLOCK = 5,
}
}
/** Properties of a GenesisData. */
export interface IGenesisData {
/** GenesisData batches */
batches?: IBatch[] | null | undefined;
}
/** Represents a GenesisData. */
export class GenesisData implements IGenesisData {
/**
* Constructs a new GenesisData.
* @param [properties] Properties to set
*/
constructor(properties?: IGenesisData);
/** GenesisData batches. */
public batches: IBatch[];
/**
* Creates a new GenesisData instance using the specified properties.
* @param [properties] Properties to set
* @returns GenesisData instance
*/
public static create(properties?: IGenesisData): GenesisData;
/**
* Encodes the specified GenesisData message. Does not implicitly {@link GenesisData.verify|verify} messages.
* @param message GenesisData message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IGenesisData, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified GenesisData message, length delimited. Does not implicitly {@link GenesisData.verify|verify} messages.
* @param message GenesisData message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IGenesisData, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a GenesisData message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns GenesisData
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): GenesisData;
/**
* Decodes a GenesisData message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns GenesisData
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): GenesisData;
/**
* Verifies a GenesisData message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a GenesisData message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns GenesisData
*/
public static fromObject(object: { [k: string]: any }): GenesisData;
/**
* Creates a plain object from a GenesisData message. Also converts values to other types if specified.
* @param message GenesisData
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: GenesisData, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this GenesisData to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Policy. */
export interface IPolicy {
/** Policy name */
name?: string | null | undefined;
/** Policy entries */
entries?: Policy.IEntry[] | null | undefined;
}
/** Represents a Policy. */
export class Policy implements IPolicy {
/**
* Constructs a new Policy.
* @param [properties] Properties to set
*/
constructor(properties?: IPolicy);
/** Policy name. */
public name: string;
/** Policy entries. */
public entries: Policy.IEntry[];
/**
* Creates a new Policy instance using the specified properties.
* @param [properties] Properties to set
* @returns Policy instance
*/
public static create(properties?: IPolicy): Policy;
/**
* Encodes the specified Policy message. Does not implicitly {@link Policy.verify|verify} messages.
* @param message Policy message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IPolicy, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Policy message, length delimited. Does not implicitly {@link Policy.verify|verify} messages.
* @param message Policy message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IPolicy, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Policy message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Policy
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): Policy;
/**
* Decodes a Policy message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Policy
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): Policy;
/**
* Verifies a Policy message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a Policy message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Policy
*/
public static fromObject(object: { [k: string]: any }): Policy;
/**
* Creates a plain object from a Policy message. Also converts values to other types if specified.
* @param message Policy
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: Policy, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Policy to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace Policy {
/** EntryType enum. */
enum EntryType {
ENTRY_TYPE_UNSET = 0,
PERMIT_KEY = 1,
DENY_KEY = 2,
}
/** Properties of an Entry. */
interface IEntry {
/** Entry type */
type?: Policy.EntryType | null | undefined;
/** Entry key */
key?: string | null | undefined;
}
/** Represents an Entry. */
class Entry implements IEntry {
/**
* Constructs a new Entry.
* @param [properties] Properties to set
*/
constructor(properties?: Policy.IEntry);
/** Entry type. */
public type: Policy.EntryType;
/** Entry key. */
public key: string;
/**
* Creates a new Entry instance using the specified properties.
* @param [properties] Properties to set
* @returns Entry instance
*/
public static create(properties?: Policy.IEntry): Policy.Entry;
/**
* Encodes the specified Entry message. Does not implicitly {@link Policy.Entry.verify|verify} messages.
* @param message Entry message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: Policy.IEntry, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Entry message, length delimited. Does not implicitly {@link Policy.Entry.verify|verify} messages.
* @param message Entry message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: Policy.IEntry, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Entry message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Entry
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): Policy.Entry;
/**
* Decodes an Entry message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Entry
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): Policy.Entry;
/**
* Verifies an Entry message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates an Entry message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Entry
*/
public static fromObject(object: { [k: string]: any }): Policy.Entry;
/**
* Creates a plain object from an Entry message. Also converts values to other types if specified.
* @param message Entry
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: Policy.Entry, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Entry to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a PolicyList. */
export interface IPolicyList {
/** PolicyList policies */
policies?: IPolicy[] | null | undefined;
}
/** Represents a PolicyList. */
export class PolicyList implements IPolicyList {
/**
* Constructs a new PolicyList.
* @param [properties] Properties to set
*/
constructor(properties?: IPolicyList);
/** PolicyList policies. */
public policies: IPolicy[];
/**
* Creates a new PolicyList instance using the specified properties.
* @param [properties] Properties to set
* @returns PolicyList instance
*/
public static create(properties?: IPolicyList): PolicyList;
/**
* Encodes the specified PolicyList message. Does not implicitly {@link PolicyList.verify|verify} messages.
* @param message PolicyList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IPolicyList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PolicyList message, length delimited. Does not implicitly {@link PolicyList.verify|verify} messages.
* @param message PolicyList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IPolicyList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PolicyList message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PolicyList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): PolicyList;
/**
* Decodes a PolicyList message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PolicyList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): PolicyList;
/**
* Verifies a PolicyList message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a PolicyList message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PolicyList
*/
public static fromObject(object: { [k: string]: any }): PolicyList;
/**
* Creates a plain object from a PolicyList message. Also converts values to other types if specified.
* @param message PolicyList
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: PolicyList, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PolicyList to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Role. */
export interface IRole {
/** Role name */
name?: string | null | undefined;
/** Role policyName */
policyName?: string | null | undefined;
}
/** Represents a Role. */
export class Role implements IRole {
/**
* Constructs a new Role.
* @param [properties] Properties to set
*/
constructor(properties?: IRole);
/** Role name. */
public name: string;
/** Role policyName. */
public policyName: string;
/**
* Creates a new Role instance using the specified properties.
* @param [properties] Properties to set
* @returns Role instance
*/
public static create(properties?: IRole): Role;
/**
* Encodes the specified Role message. Does not implicitly {@link Role.verify|verify} messages.
* @param message Role message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IRole, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Role message, length delimited. Does not implicitly {@link Role.verify|verify} messages.
* @param message Role message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IRole, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Role message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Role
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): Role;
/**
* Decodes a Role message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Role
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): Role;
/**
* Verifies a Role message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a Role message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Role
*/
public static fromObject(object: { [k: string]: any }): Role;
/**
* Creates a plain object from a Role message. Also converts values to other types if specified.
* @param message Role
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: Role, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Role to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a RoleList. */
export interface IRoleList {
/** RoleList roles */
roles?: IRole[] | null | undefined;
}
/** Represents a RoleList. */
export class RoleList implements IRoleList {
/**
* Constructs a new RoleList.
* @param [properties] Properties to set
*/
constructor(properties?: IRoleList);
/** RoleList roles. */
public roles: IRole[];
/**
* Creates a new RoleList instance using the specified properties.
* @param [properties] Properties to set
* @returns RoleList instance
*/
public static create(properties?: IRoleList): RoleList;
/**
* Encodes the specified RoleList message. Does not implicitly {@link RoleList.verify|verify} messages.
* @param message RoleList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IRoleList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified RoleList message, length delimited. Does not implicitly {@link RoleList.verify|verify} messages.
* @param message RoleList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IRoleList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a RoleList message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns RoleList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): RoleList;
/**
* Decodes a RoleList message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns RoleList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): RoleList;
/**
* Verifies a RoleList message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a RoleList message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns RoleList
*/
public static fromObject(object: { [k: string]: any }): RoleList;
/**
* Creates a plain object from a RoleList message. Also converts values to other types if specified.
* @param message RoleList
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: RoleList, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this RoleList to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ChangeLogEntry. */
export interface IChangeLogEntry {
/** ChangeLogEntry parent */
parent?: Uint8Array | null | undefined;
/** ChangeLogEntry additions */
additions?: Uint8Array[] | null | undefined;
/** ChangeLogEntry successors */
successors?: ChangeLogEntry.ISuccessor[] | null | undefined;
}
/** Represents a ChangeLogEntry. */
export class ChangeLogEntry implements IChangeLogEntry {
/**
* Constructs a new ChangeLogEntry.
* @param [properties] Properties to set
*/
constructor(properties?: IChangeLogEntry);
/** ChangeLogEntry parent. */
public parent: Uint8Array;
/** ChangeLogEntry additions. */
public additions: Uint8Array[];
/** ChangeLogEntry successors. */
public successors: ChangeLogEntry.ISuccessor[];
/**
* Creates a new ChangeLogEntry instance using the specified properties.
* @param [properties] Properties to set
* @returns ChangeLogEntry instance
*/
public static create(properties?: IChangeLogEntry): ChangeLogEntry;
/**
* Encodes the specified ChangeLogEntry message. Does not implicitly {@link ChangeLogEntry.verify|verify} messages.
* @param message ChangeLogEntry message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IChangeLogEntry, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ChangeLogEntry message, length delimited. Does not implicitly {@link ChangeLogEntry.verify|verify} messages.
* @param message ChangeLogEntry message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IChangeLogEntry, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ChangeLogEntry message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ChangeLogEntry
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ChangeLogEntry;
/**
* Decodes a ChangeLogEntry message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ChangeLogEntry
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ChangeLogEntry;
/**
* Verifies a ChangeLogEntry message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a ChangeLogEntry message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ChangeLogEntry
*/
public static fromObject(object: { [k: string]: any }): ChangeLogEntry;
/**
* Creates a plain object from a ChangeLogEntry message. Also converts values to other types if specified.
* @param message ChangeLogEntry
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ChangeLogEntry, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ChangeLogEntry to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace ChangeLogEntry {
/** Properties of a Successor. */
interface ISuccessor {
/** Successor successor */
successor?: Uint8Array | null | undefined;
/** Successor deletions */
deletions?: Uint8Array[] | null | undefined;
}
/** Represents a Successor. */
class Successor implements ISuccessor {
/**
* Constructs a new Successor.
* @param [properties] Properties to set
*/
constructor(properties?: ChangeLogEntry.ISuccessor);
/** Successor successor. */
public successor: Uint8Array;
/** Successor deletions. */
public deletions: Uint8Array[];
/**
* Creates a new Successor instance using the specified properties.
* @param [properties] Properties to set
* @returns Successor instance
*/
public static create(properties?: ChangeLogEntry.ISuccessor): ChangeLogEntry.Successor;
/**
* Encodes the specified Successor message. Does not implicitly {@link ChangeLogEntry.Successor.verify|verify} messages.
* @param message Successor message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ChangeLogEntry.ISuccessor, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Successor message, length delimited. Does not implicitly {@link ChangeLogEntry.Successor.verify|verify} messages.
* @param message Successor message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ChangeLogEntry.ISuccessor, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Successor message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Successor
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): ChangeLogEntry.Successor;
/**
* Decodes a Successor message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Successor
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): ChangeLogEntry.Successor;
/**
* Verifies a Successor message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a Successor message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Successor
*/
public static fromObject(object: { [k: string]: any }): ChangeLogEntry.Successor;
/**
* Creates a plain object from a Successor message. Also converts values to other types if specified.
* @param message Successor
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: ChangeLogEntry.Successor,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this Successor to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a DisconnectMessage. */
export interface IDisconnectMessage {}
/** Represents a DisconnectMessage. */
export class DisconnectMessage implements IDisconnectMessage {
/**
* Constructs a new DisconnectMessage.
* @param [properties] Properties to set
*/
constructor(properties?: IDisconnectMessage);
/**
* Creates a new DisconnectMessage instance using the specified properties.
* @param [properties] Properties to set
* @returns DisconnectMessage instance
*/
public static create(properties?: IDisconnectMessage): DisconnectMessage;
/**
* Encodes the specified DisconnectMessage message. Does not implicitly {@link DisconnectMessage.verify|verify} messages.
* @param message DisconnectMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IDisconnectMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified DisconnectMessage message, length delimited. Does not implicitly {@link DisconnectMessage.verify|verify} messages.
* @param message DisconnectMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IDisconnectMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a DisconnectMessage message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns DisconnectMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): DisconnectMessage;
/**
* Decodes a DisconnectMessage message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns DisconnectMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): DisconnectMessage;
/**
* Verifies a DisconnectMessage message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a DisconnectMessage message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns DisconnectMessage
*/
public static fromObject(object: { [k: string]: any }): DisconnectMessage;
/**
* Creates a plain object from a DisconnectMessage message. Also converts values to other types if specified.
* @param message DisconnectMessage
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: DisconnectMessage, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this DisconnectMessage to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a PeerRegisterRequest. */
export interface IPeerRegisterRequest {
/** PeerRegisterRequest endpoint */
endpoint?: string | null | undefined;
/** PeerRegisterRequest protocolVersion */
protocolVersion?: number | null | undefined;
}
/** Represents a PeerRegisterRequest. */
export class PeerRegisterRequest implements IPeerRegisterRequest {
/**
* Constructs a new PeerRegisterRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IPeerRegisterRequest);
/** PeerRegisterRequest endpoint. */
public endpoint: string;
/** PeerRegisterRequest protocolVersion. */
public protocolVersion: number;
/**
* Creates a new PeerRegisterRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns PeerRegisterRequest instance
*/
public static create(properties?: IPeerRegisterRequest): PeerRegisterRequest;
/**
* Encodes the specified PeerRegisterRequest message. Does not implicitly {@link PeerRegisterRequest.verify|verify} messages.
* @param message PeerRegisterRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IPeerRegisterRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PeerRegisterRequest message, length delimited. Does not implicitly {@link PeerRegisterRequest.verify|verify} messages.
* @param message PeerRegisterRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IPeerRegisterRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PeerRegisterRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PeerRegisterRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): PeerRegisterRequest;
/**
* Decodes a PeerRegisterRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PeerRegisterRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): PeerRegisterRequest;
/**
* Verifies a PeerRegisterRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a PeerRegisterRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PeerRegisterRequest
*/
public static fromObject(object: { [k: string]: any }): PeerRegisterRequest;
/**
* Creates a plain object from a PeerRegisterRequest message. Also converts values to other types if specified.
* @param message PeerRegisterRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: PeerRegisterRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PeerRegisterRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a PeerUnregisterRequest. */
export interface IPeerUnregisterRequest {}
/** Represents a PeerUnregisterRequest. */
export class PeerUnregisterRequest implements IPeerUnregisterRequest {
/**
* Constructs a new PeerUnregisterRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IPeerUnregisterRequest);
/**
* Creates a new PeerUnregisterRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns PeerUnregisterRequest instance
*/
public static create(properties?: IPeerUnregisterRequest): PeerUnregisterRequest;
/**
* Encodes the specified PeerUnregisterRequest message. Does not implicitly {@link PeerUnregisterRequest.verify|verify} messages.
* @param message PeerUnregisterRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IPeerUnregisterRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PeerUnregisterRequest message, length delimited. Does not implicitly {@link PeerUnregisterRequest.verify|verify} messages.
* @param message PeerUnregisterRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IPeerUnregisterRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PeerUnregisterRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PeerUnregisterRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): PeerUnregisterRequest;
/**
* Decodes a PeerUnregisterRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PeerUnregisterRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): PeerUnregisterRequest;
/**
* Verifies a PeerUnregisterRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a PeerUnregisterRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PeerUnregisterRequest
*/
public static fromObject(object: { [k: string]: any }): PeerUnregisterRequest;
/**
* Creates a plain object from a PeerUnregisterRequest message. Also converts values to other types if specified.
* @param message PeerUnregisterRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: PeerUnregisterRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this PeerUnregisterRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a GetPeersRequest. */
export interface IGetPeersRequest {}
/** Represents a GetPeersRequest. */
export class GetPeersRequest implements IGetPeersRequest {
/**
* Constructs a new GetPeersRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IGetPeersRequest);
/**
* Creates a new GetPeersRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns GetPeersRequest instance
*/
public static create(properties?: IGetPeersRequest): GetPeersRequest;
/**
* Encodes the specified GetPeersRequest message. Does not implicitly {@link GetPeersRequest.verify|verify} messages.
* @param message GetPeersRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IGetPeersRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified GetPeersRequest message, length delimited. Does not implicitly {@link GetPeersRequest.verify|verify} messages.
* @param message GetPeersRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IGetPeersRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a GetPeersRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns GetPeersRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): GetPeersRequest;
/**
* Decodes a GetPeersRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns GetPeersRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): GetPeersRequest;
/**
* Verifies a GetPeersRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a GetPeersRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns GetPeersRequest
*/
public static fromObject(object: { [k: string]: any }): GetPeersRequest;
/**
* Creates a plain object from a GetPeersRequest message. Also converts values to other types if specified.
* @param message GetPeersRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: GetPeersRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this GetPeersRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a GetPeersResponse. */
export interface IGetPeersResponse {
/** GetPeersResponse peerEndpoints */
peerEndpoints?: string[] | null | undefined;
}
/** Represents a GetPeersResponse. */
export class GetPeersResponse implements IGetPeersResponse {
/**
* Constructs a new GetPeersResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IGetPeersResponse);
/** GetPeersResponse peerEndpoints. */
public peerEndpoints: string[];
/**
* Creates a new GetPeersResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns GetPeersResponse instance
*/
public static create(properties?: IGetPeersResponse): GetPeersResponse;
/**
* Encodes the specified GetPeersResponse message. Does not implicitly {@link GetPeersResponse.verify|verify} messages.
* @param message GetPeersResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IGetPeersResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified GetPeersResponse message, length delimited. Does not implicitly {@link GetPeersResponse.verify|verify} messages.
* @param message GetPeersResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IGetPeersResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a GetPeersResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns GetPeersResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): GetPeersResponse;
/**
* Decodes a GetPeersResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns GetPeersResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): GetPeersResponse;
/**
* Verifies a GetPeersResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a GetPeersResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns GetPeersResponse
*/
public static fromObject(object: { [k: string]: any }): GetPeersResponse;
/**
* Creates a plain object from a GetPeersResponse message. Also converts values to other types if specified.
* @param message GetPeersResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: GetPeersResponse, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this GetPeersResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a PingRequest. */
export interface IPingRequest {}
/** Represents a PingRequest. */
export class PingRequest implements IPingRequest {
/**
* Constructs a new PingRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IPingRequest);
/**
* Creates a new PingRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns PingRequest instance
*/
public static create(properties?: IPingRequest): PingRequest;
/**
* Encodes the specified PingRequest message. Does not implicitly {@link PingRequest.verify|verify} messages.
* @param message PingRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IPingRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PingRequest message, length delimited. Does not implicitly {@link PingRequest.verify|verify} messages.
* @param message PingRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IPingRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PingRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PingRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): PingRequest;
/**
* Decodes a PingRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PingRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): PingRequest;
/**
* Verifies a PingRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a PingRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PingRequest
*/
public static fromObject(object: { [k: string]: any }): PingRequest;
/**
* Creates a plain object from a PingRequest message. Also converts values to other types if specified.
* @param message PingRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: PingRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PingRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a PingResponse. */
export interface IPingResponse {}
/** Represents a PingResponse. */
export class PingResponse implements IPingResponse {
/**
* Constructs a new PingResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IPingResponse);
/**
* Creates a new PingResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns PingResponse instance
*/
public static create(properties?: IPingResponse): PingResponse;
/**
* Encodes the specified PingResponse message. Does not implicitly {@link PingResponse.verify|verify} messages.
* @param message PingResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IPingResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PingResponse message, length delimited. Does not implicitly {@link PingResponse.verify|verify} messages.
* @param message PingResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IPingResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PingResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PingResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): PingResponse;
/**
* Decodes a PingResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PingResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): PingResponse;
/**
* Verifies a PingResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a PingResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PingResponse
*/
public static fromObject(object: { [k: string]: any }): PingResponse;
/**
* Creates a plain object from a PingResponse message. Also converts values to other types if specified.
* @param message PingResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: PingResponse, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PingResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a GossipMessage. */
export interface IGossipMessage {
/** GossipMessage content */
content?: Uint8Array | null | undefined;
/** GossipMessage contentType */
contentType?: GossipMessage.ContentType | null | undefined;
/** GossipMessage timeToLive */
timeToLive?: number | null | undefined;
}
/** Represents a GossipMessage. */
export class GossipMessage implements IGossipMessage {
/**
* Constructs a new GossipMessage.
* @param [properties] Properties to set
*/
constructor(properties?: IGossipMessage);
/** GossipMessage content. */
public content: Uint8Array;
/** GossipMessage contentType. */
public contentType: GossipMessage.ContentType;
/** GossipMessage timeToLive. */
public timeToLive: number;
/**
* Creates a new GossipMessage instance using the specified properties.
* @param [properties] Properties to set
* @returns GossipMessage instance
*/
public static create(properties?: IGossipMessage): GossipMessage;
/**
* Encodes the specified GossipMessage message. Does not implicitly {@link GossipMessage.verify|verify} messages.
* @param message GossipMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IGossipMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified GossipMessage message, length delimited. Does not implicitly {@link GossipMessage.verify|verify} messages.
* @param message GossipMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IGossipMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a GossipMessage message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns GossipMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): GossipMessage;
/**
* Decodes a GossipMessage message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns GossipMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): GossipMessage;
/**
* Verifies a GossipMessage message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a GossipMessage message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns GossipMessage
*/
public static fromObject(object: { [k: string]: any }): GossipMessage;
/**
* Creates a plain object from a GossipMessage message. Also converts values to other types if specified.
* @param message GossipMessage
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: GossipMessage, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this GossipMessage to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace GossipMessage {
/** ContentType enum. */
enum ContentType {
CONTENT_TYPE_UNSET = 0,
BLOCK = 1,
BATCH = 2,
}
}
/** Properties of a NetworkAcknowledgement. */
export interface INetworkAcknowledgement {
/** NetworkAcknowledgement status */
status?: NetworkAcknowledgement.Status | null | undefined;
}
/** Represents a NetworkAcknowledgement. */
export class NetworkAcknowledgement implements INetworkAcknowledgement {
/**
* Constructs a new NetworkAcknowledgement.
* @param [properties] Properties to set
*/
constructor(properties?: INetworkAcknowledgement);
/** NetworkAcknowledgement status. */
public status: NetworkAcknowledgement.Status;
/**
* Creates a new NetworkAcknowledgement instance using the specified properties.
* @param [properties] Properties to set
* @returns NetworkAcknowledgement instance
*/
public static create(properties?: INetworkAcknowledgement): NetworkAcknowledgement;
/**
* Encodes the specified NetworkAcknowledgement message. Does not implicitly {@link NetworkAcknowledgement.verify|verify} messages.
* @param message NetworkAcknowledgement message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: INetworkAcknowledgement, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified NetworkAcknowledgement message, length delimited. Does not implicitly {@link NetworkAcknowledgement.verify|verify} messages.
* @param message NetworkAcknowledgement message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: INetworkAcknowledgement, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a NetworkAcknowledgement message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns NetworkAcknowledgement
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): NetworkAcknowledgement;
/**
* Decodes a NetworkAcknowledgement message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns NetworkAcknowledgement
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): NetworkAcknowledgement;
/**
* Verifies a NetworkAcknowledgement message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a NetworkAcknowledgement message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns NetworkAcknowledgement
*/
public static fromObject(object: { [k: string]: any }): NetworkAcknowledgement;
/**
* Creates a plain object from a NetworkAcknowledgement message. Also converts values to other types if specified.
* @param message NetworkAcknowledgement
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: NetworkAcknowledgement,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this NetworkAcknowledgement to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace NetworkAcknowledgement {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
ERROR = 2,
}
}
/** Properties of a GossipBlockRequest. */
export interface IGossipBlockRequest {
/** GossipBlockRequest blockId */
blockId?: string | null | undefined;
/** GossipBlockRequest nonce */
nonce?: string | null | undefined;
/** GossipBlockRequest timeToLive */
timeToLive?: number | null | undefined;
}
/** Represents a GossipBlockRequest. */
export class GossipBlockRequest implements IGossipBlockRequest {
/**
* Constructs a new GossipBlockRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IGossipBlockRequest);
/** GossipBlockRequest blockId. */
public blockId: string;
/** GossipBlockRequest nonce. */
public nonce: string;
/** GossipBlockRequest timeToLive. */
public timeToLive: number;
/**
* Creates a new GossipBlockRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns GossipBlockRequest instance
*/
public static create(properties?: IGossipBlockRequest): GossipBlockRequest;
/**
* Encodes the specified GossipBlockRequest message. Does not implicitly {@link GossipBlockRequest.verify|verify} messages.
* @param message GossipBlockRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IGossipBlockRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified GossipBlockRequest message, length delimited. Does not implicitly {@link GossipBlockRequest.verify|verify} messages.
* @param message GossipBlockRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IGossipBlockRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a GossipBlockRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns GossipBlockRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): GossipBlockRequest;
/**
* Decodes a GossipBlockRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns GossipBlockRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): GossipBlockRequest;
/**
* Verifies a GossipBlockRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a GossipBlockRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns GossipBlockRequest
*/
public static fromObject(object: { [k: string]: any }): GossipBlockRequest;
/**
* Creates a plain object from a GossipBlockRequest message. Also converts values to other types if specified.
* @param message GossipBlockRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: GossipBlockRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this GossipBlockRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a GossipBlockResponse. */
export interface IGossipBlockResponse {
/** GossipBlockResponse content */
content?: Uint8Array | null | undefined;
}
/** Represents a GossipBlockResponse. */
export class GossipBlockResponse implements IGossipBlockResponse {
/**
* Constructs a new GossipBlockResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IGossipBlockResponse);
/** GossipBlockResponse content. */
public content: Uint8Array;
/**
* Creates a new GossipBlockResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns GossipBlockResponse instance
*/
public static create(properties?: IGossipBlockResponse): GossipBlockResponse;
/**
* Encodes the specified GossipBlockResponse message. Does not implicitly {@link GossipBlockResponse.verify|verify} messages.
* @param message GossipBlockResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IGossipBlockResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified GossipBlockResponse message, length delimited. Does not implicitly {@link GossipBlockResponse.verify|verify} messages.
* @param message GossipBlockResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IGossipBlockResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a GossipBlockResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns GossipBlockResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): GossipBlockResponse;
/**
* Decodes a GossipBlockResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns GossipBlockResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): GossipBlockResponse;
/**
* Verifies a GossipBlockResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a GossipBlockResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns GossipBlockResponse
*/
public static fromObject(object: { [k: string]: any }): GossipBlockResponse;
/**
* Creates a plain object from a GossipBlockResponse message. Also converts values to other types if specified.
* @param message GossipBlockResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: GossipBlockResponse, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this GossipBlockResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a GossipBatchResponse. */
export interface IGossipBatchResponse {
/** GossipBatchResponse content */
content?: Uint8Array | null | undefined;
}
/** Represents a GossipBatchResponse. */
export class GossipBatchResponse implements IGossipBatchResponse {
/**
* Constructs a new GossipBatchResponse.
* @param [properties] Properties to set
*/
constructor(properties?: IGossipBatchResponse);
/** GossipBatchResponse content. */
public content: Uint8Array;
/**
* Creates a new GossipBatchResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns GossipBatchResponse instance
*/
public static create(properties?: IGossipBatchResponse): GossipBatchResponse;
/**
* Encodes the specified GossipBatchResponse message. Does not implicitly {@link GossipBatchResponse.verify|verify} messages.
* @param message GossipBatchResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IGossipBatchResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified GossipBatchResponse message, length delimited. Does not implicitly {@link GossipBatchResponse.verify|verify} messages.
* @param message GossipBatchResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IGossipBatchResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a GossipBatchResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns GossipBatchResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): GossipBatchResponse;
/**
* Decodes a GossipBatchResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns GossipBatchResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): GossipBatchResponse;
/**
* Verifies a GossipBatchResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a GossipBatchResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns GossipBatchResponse
*/
public static fromObject(object: { [k: string]: any }): GossipBatchResponse;
/**
* Creates a plain object from a GossipBatchResponse message. Also converts values to other types if specified.
* @param message GossipBatchResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: GossipBatchResponse, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this GossipBatchResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a GossipBatchByBatchIdRequest. */
export interface IGossipBatchByBatchIdRequest {
/** GossipBatchByBatchIdRequest id */
id?: string | null | undefined;
/** GossipBatchByBatchIdRequest nonce */
nonce?: string | null | undefined;
/** GossipBatchByBatchIdRequest timeToLive */
timeToLive?: number | null | undefined;
}
/** Represents a GossipBatchByBatchIdRequest. */
export class GossipBatchByBatchIdRequest implements IGossipBatchByBatchIdRequest {
/**
* Constructs a new GossipBatchByBatchIdRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IGossipBatchByBatchIdRequest);
/** GossipBatchByBatchIdRequest id. */
public id: string;
/** GossipBatchByBatchIdRequest nonce. */
public nonce: string;
/** GossipBatchByBatchIdRequest timeToLive. */
public timeToLive: number;
/**
* Creates a new GossipBatchByBatchIdRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns GossipBatchByBatchIdRequest instance
*/
public static create(properties?: IGossipBatchByBatchIdRequest): GossipBatchByBatchIdRequest;
/**
* Encodes the specified GossipBatchByBatchIdRequest message. Does not implicitly {@link GossipBatchByBatchIdRequest.verify|verify} messages.
* @param message GossipBatchByBatchIdRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IGossipBatchByBatchIdRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified GossipBatchByBatchIdRequest message, length delimited. Does not implicitly {@link GossipBatchByBatchIdRequest.verify|verify} messages.
* @param message GossipBatchByBatchIdRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IGossipBatchByBatchIdRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a GossipBatchByBatchIdRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns GossipBatchByBatchIdRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): GossipBatchByBatchIdRequest;
/**
* Decodes a GossipBatchByBatchIdRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns GossipBatchByBatchIdRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): GossipBatchByBatchIdRequest;
/**
* Verifies a GossipBatchByBatchIdRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a GossipBatchByBatchIdRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns GossipBatchByBatchIdRequest
*/
public static fromObject(object: { [k: string]: any }): GossipBatchByBatchIdRequest;
/**
* Creates a plain object from a GossipBatchByBatchIdRequest message. Also converts values to other types if specified.
* @param message GossipBatchByBatchIdRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: GossipBatchByBatchIdRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this GossipBatchByBatchIdRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a GossipBatchByTransactionIdRequest. */
export interface IGossipBatchByTransactionIdRequest {
/** GossipBatchByTransactionIdRequest ids */
ids?: string[] | null | undefined;
/** GossipBatchByTransactionIdRequest nonce */
nonce?: string | null | undefined;
/** GossipBatchByTransactionIdRequest timeToLive */
timeToLive?: number | null | undefined;
}
/** Represents a GossipBatchByTransactionIdRequest. */
export class GossipBatchByTransactionIdRequest implements IGossipBatchByTransactionIdRequest {
/**
* Constructs a new GossipBatchByTransactionIdRequest.
* @param [properties] Properties to set
*/
constructor(properties?: IGossipBatchByTransactionIdRequest);
/** GossipBatchByTransactionIdRequest ids. */
public ids: string[];
/** GossipBatchByTransactionIdRequest nonce. */
public nonce: string;
/** GossipBatchByTransactionIdRequest timeToLive. */
public timeToLive: number;
/**
* Creates a new GossipBatchByTransactionIdRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns GossipBatchByTransactionIdRequest instance
*/
public static create(properties?: IGossipBatchByTransactionIdRequest): GossipBatchByTransactionIdRequest;
/**
* Encodes the specified GossipBatchByTransactionIdRequest message. Does not implicitly {@link GossipBatchByTransactionIdRequest.verify|verify} messages.
* @param message GossipBatchByTransactionIdRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IGossipBatchByTransactionIdRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified GossipBatchByTransactionIdRequest message, length delimited. Does not implicitly {@link GossipBatchByTransactionIdRequest.verify|verify} messages.
* @param message GossipBatchByTransactionIdRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(
message: IGossipBatchByTransactionIdRequest,
writer?: $protobuf.Writer,
): $protobuf.Writer;
/**
* Decodes a GossipBatchByTransactionIdRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns GossipBatchByTransactionIdRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): GossipBatchByTransactionIdRequest;
/**
* Decodes a GossipBatchByTransactionIdRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns GossipBatchByTransactionIdRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): GossipBatchByTransactionIdRequest;
/**
* Verifies a GossipBatchByTransactionIdRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a GossipBatchByTransactionIdRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns GossipBatchByTransactionIdRequest
*/
public static fromObject(object: { [k: string]: any }): GossipBatchByTransactionIdRequest;
/**
* Creates a plain object from a GossipBatchByTransactionIdRequest message. Also converts values to other types if specified.
* @param message GossipBatchByTransactionIdRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: GossipBatchByTransactionIdRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this GossipBatchByTransactionIdRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a GossipConsensusMessage. */
export interface IGossipConsensusMessage {
/** GossipConsensusMessage message */
message?: Uint8Array | null | undefined;
/** GossipConsensusMessage senderId */
senderId?: Uint8Array | null | undefined;
/** GossipConsensusMessage timeToLive */
timeToLive?: number | null | undefined;
}
/** Represents a GossipConsensusMessage. */
export class GossipConsensusMessage implements IGossipConsensusMessage {
/**
* Constructs a new GossipConsensusMessage.
* @param [properties] Properties to set
*/
constructor(properties?: IGossipConsensusMessage);
/** GossipConsensusMessage message. */
public message: Uint8Array;
/** GossipConsensusMessage senderId. */
public senderId: Uint8Array;
/** GossipConsensusMessage timeToLive. */
public timeToLive: number;
/**
* Creates a new GossipConsensusMessage instance using the specified properties.
* @param [properties] Properties to set
* @returns GossipConsensusMessage instance
*/
public static create(properties?: IGossipConsensusMessage): GossipConsensusMessage;
/**
* Encodes the specified GossipConsensusMessage message. Does not implicitly {@link GossipConsensusMessage.verify|verify} messages.
* @param message GossipConsensusMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IGossipConsensusMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified GossipConsensusMessage message, length delimited. Does not implicitly {@link GossipConsensusMessage.verify|verify} messages.
* @param message GossipConsensusMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IGossipConsensusMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a GossipConsensusMessage message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns GossipConsensusMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): GossipConsensusMessage;
/**
* Decodes a GossipConsensusMessage message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns GossipConsensusMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): GossipConsensusMessage;
/**
* Verifies a GossipConsensusMessage message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a GossipConsensusMessage message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns GossipConsensusMessage
*/
public static fromObject(object: { [k: string]: any }): GossipConsensusMessage;
/**
* Creates a plain object from a GossipConsensusMessage message. Also converts values to other types if specified.
* @param message GossipConsensusMessage
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: GossipConsensusMessage,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this GossipConsensusMessage to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a TpRegisterRequest. */
export interface ITpRegisterRequest {
/** TpRegisterRequest family */
family?: string | null | undefined;
/** TpRegisterRequest version */
version?: string | null | undefined;
/** TpRegisterRequest namespaces */
namespaces?: string[] | null | undefined;
/** TpRegisterRequest maxOccupancy */
maxOccupancy?: number | null | undefined;
}
/** Represents a TpRegisterRequest. */
export class TpRegisterRequest implements ITpRegisterRequest {
/**
* Constructs a new TpRegisterRequest.
* @param [properties] Properties to set
*/
constructor(properties?: ITpRegisterRequest);
/** TpRegisterRequest family. */
public family: string;
/** TpRegisterRequest version. */
public version: string;
/** TpRegisterRequest namespaces. */
public namespaces: string[];
/** TpRegisterRequest maxOccupancy. */
public maxOccupancy: number;
/**
* Creates a new TpRegisterRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns TpRegisterRequest instance
*/
public static create(properties?: ITpRegisterRequest): TpRegisterRequest;
/**
* Encodes the specified TpRegisterRequest message. Does not implicitly {@link TpRegisterRequest.verify|verify} messages.
* @param message TpRegisterRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ITpRegisterRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TpRegisterRequest message, length delimited. Does not implicitly {@link TpRegisterRequest.verify|verify} messages.
* @param message TpRegisterRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ITpRegisterRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TpRegisterRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TpRegisterRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): TpRegisterRequest;
/**
* Decodes a TpRegisterRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TpRegisterRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): TpRegisterRequest;
/**
* Verifies a TpRegisterRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a TpRegisterRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TpRegisterRequest
*/
public static fromObject(object: { [k: string]: any }): TpRegisterRequest;
/**
* Creates a plain object from a TpRegisterRequest message. Also converts values to other types if specified.
* @param message TpRegisterRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: TpRegisterRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TpRegisterRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a TpRegisterResponse. */
export interface ITpRegisterResponse {
/** TpRegisterResponse status */
status?: TpRegisterResponse.Status | null | undefined;
}
/** Represents a TpRegisterResponse. */
export class TpRegisterResponse implements ITpRegisterResponse {
/**
* Constructs a new TpRegisterResponse.
* @param [properties] Properties to set
*/
constructor(properties?: ITpRegisterResponse);
/** TpRegisterResponse status. */
public status: TpRegisterResponse.Status;
/**
* Creates a new TpRegisterResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns TpRegisterResponse instance
*/
public static create(properties?: ITpRegisterResponse): TpRegisterResponse;
/**
* Encodes the specified TpRegisterResponse message. Does not implicitly {@link TpRegisterResponse.verify|verify} messages.
* @param message TpRegisterResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ITpRegisterResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TpRegisterResponse message, length delimited. Does not implicitly {@link TpRegisterResponse.verify|verify} messages.
* @param message TpRegisterResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ITpRegisterResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TpRegisterResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TpRegisterResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): TpRegisterResponse;
/**
* Decodes a TpRegisterResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TpRegisterResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): TpRegisterResponse;
/**
* Verifies a TpRegisterResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a TpRegisterResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TpRegisterResponse
*/
public static fromObject(object: { [k: string]: any }): TpRegisterResponse;
/**
* Creates a plain object from a TpRegisterResponse message. Also converts values to other types if specified.
* @param message TpRegisterResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: TpRegisterResponse, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TpRegisterResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace TpRegisterResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
ERROR = 2,
}
}
/** Properties of a TpUnregisterRequest. */
export interface ITpUnregisterRequest {}
/** Represents a TpUnregisterRequest. */
export class TpUnregisterRequest implements ITpUnregisterRequest {
/**
* Constructs a new TpUnregisterRequest.
* @param [properties] Properties to set
*/
constructor(properties?: ITpUnregisterRequest);
/**
* Creates a new TpUnregisterRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns TpUnregisterRequest instance
*/
public static create(properties?: ITpUnregisterRequest): TpUnregisterRequest;
/**
* Encodes the specified TpUnregisterRequest message. Does not implicitly {@link TpUnregisterRequest.verify|verify} messages.
* @param message TpUnregisterRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ITpUnregisterRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TpUnregisterRequest message, length delimited. Does not implicitly {@link TpUnregisterRequest.verify|verify} messages.
* @param message TpUnregisterRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ITpUnregisterRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TpUnregisterRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TpUnregisterRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): TpUnregisterRequest;
/**
* Decodes a TpUnregisterRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TpUnregisterRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): TpUnregisterRequest;
/**
* Verifies a TpUnregisterRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a TpUnregisterRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TpUnregisterRequest
*/
public static fromObject(object: { [k: string]: any }): TpUnregisterRequest;
/**
* Creates a plain object from a TpUnregisterRequest message. Also converts values to other types if specified.
* @param message TpUnregisterRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: TpUnregisterRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TpUnregisterRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a TpUnregisterResponse. */
export interface ITpUnregisterResponse {
/** TpUnregisterResponse status */
status?: TpUnregisterResponse.Status | null | undefined;
}
/** Represents a TpUnregisterResponse. */
export class TpUnregisterResponse implements ITpUnregisterResponse {
/**
* Constructs a new TpUnregisterResponse.
* @param [properties] Properties to set
*/
constructor(properties?: ITpUnregisterResponse);
/** TpUnregisterResponse status. */
public status: TpUnregisterResponse.Status;
/**
* Creates a new TpUnregisterResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns TpUnregisterResponse instance
*/
public static create(properties?: ITpUnregisterResponse): TpUnregisterResponse;
/**
* Encodes the specified TpUnregisterResponse message. Does not implicitly {@link TpUnregisterResponse.verify|verify} messages.
* @param message TpUnregisterResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ITpUnregisterResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TpUnregisterResponse message, length delimited. Does not implicitly {@link TpUnregisterResponse.verify|verify} messages.
* @param message TpUnregisterResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ITpUnregisterResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TpUnregisterResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TpUnregisterResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): TpUnregisterResponse;
/**
* Decodes a TpUnregisterResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TpUnregisterResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): TpUnregisterResponse;
/**
* Verifies a TpUnregisterResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a TpUnregisterResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TpUnregisterResponse
*/
public static fromObject(object: { [k: string]: any }): TpUnregisterResponse;
/**
* Creates a plain object from a TpUnregisterResponse message. Also converts values to other types if specified.
* @param message TpUnregisterResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: TpUnregisterResponse, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TpUnregisterResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace TpUnregisterResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
ERROR = 2,
}
}
/** Properties of a TpProcessRequest. */
export interface ITpProcessRequest {
/** TpProcessRequest header */
header?: ITransactionHeader | null | undefined;
/** TpProcessRequest payload */
payload?: Uint8Array | null | undefined;
/** TpProcessRequest signature */
signature?: string | null | undefined;
/** TpProcessRequest contextId */
contextId?: string | null | undefined;
}
/** Represents a TpProcessRequest. */
export class TpProcessRequest implements ITpProcessRequest {
/**
* Constructs a new TpProcessRequest.
* @param [properties] Properties to set
*/
constructor(properties?: ITpProcessRequest);
/** TpProcessRequest header. */
public header?: ITransactionHeader | null | undefined;
/** TpProcessRequest payload. */
public payload: Uint8Array;
/** TpProcessRequest signature. */
public signature: string;
/** TpProcessRequest contextId. */
public contextId: string;
/**
* Creates a new TpProcessRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns TpProcessRequest instance
*/
public static create(properties?: ITpProcessRequest): TpProcessRequest;
/**
* Encodes the specified TpProcessRequest message. Does not implicitly {@link TpProcessRequest.verify|verify} messages.
* @param message TpProcessRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ITpProcessRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TpProcessRequest message, length delimited. Does not implicitly {@link TpProcessRequest.verify|verify} messages.
* @param message TpProcessRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ITpProcessRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TpProcessRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TpProcessRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): TpProcessRequest;
/**
* Decodes a TpProcessRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TpProcessRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): TpProcessRequest;
/**
* Verifies a TpProcessRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a TpProcessRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TpProcessRequest
*/
public static fromObject(object: { [k: string]: any }): TpProcessRequest;
/**
* Creates a plain object from a TpProcessRequest message. Also converts values to other types if specified.
* @param message TpProcessRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: TpProcessRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TpProcessRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a TpProcessResponse. */
export interface ITpProcessResponse {
/** TpProcessResponse status */
status?: TpProcessResponse.Status | null | undefined;
/** TpProcessResponse message */
message?: string | null | undefined;
/** TpProcessResponse extendedData */
extendedData?: Uint8Array | null | undefined;
}
/** Represents a TpProcessResponse. */
export class TpProcessResponse implements ITpProcessResponse {
/**
* Constructs a new TpProcessResponse.
* @param [properties] Properties to set
*/
constructor(properties?: ITpProcessResponse);
/** TpProcessResponse status. */
public status: TpProcessResponse.Status;
/** TpProcessResponse message. */
public message: string;
/** TpProcessResponse extendedData. */
public extendedData: Uint8Array;
/**
* Creates a new TpProcessResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns TpProcessResponse instance
*/
public static create(properties?: ITpProcessResponse): TpProcessResponse;
/**
* Encodes the specified TpProcessResponse message. Does not implicitly {@link TpProcessResponse.verify|verify} messages.
* @param message TpProcessResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ITpProcessResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TpProcessResponse message, length delimited. Does not implicitly {@link TpProcessResponse.verify|verify} messages.
* @param message TpProcessResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ITpProcessResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TpProcessResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TpProcessResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): TpProcessResponse;
/**
* Decodes a TpProcessResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TpProcessResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): TpProcessResponse;
/**
* Verifies a TpProcessResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a TpProcessResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TpProcessResponse
*/
public static fromObject(object: { [k: string]: any }): TpProcessResponse;
/**
* Creates a plain object from a TpProcessResponse message. Also converts values to other types if specified.
* @param message TpProcessResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: TpProcessResponse, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TpProcessResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace TpProcessResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
INVALID_TRANSACTION = 2,
INTERNAL_ERROR = 3,
}
}
/** Properties of a Setting. */
export interface ISetting {
/** Setting entries */
entries?: Setting.IEntry[] | null | undefined;
}
/** Represents a Setting. */
export class Setting implements ISetting {
/**
* Constructs a new Setting.
* @param [properties] Properties to set
*/
constructor(properties?: ISetting);
/** Setting entries. */
public entries: Setting.IEntry[];
/**
* Creates a new Setting instance using the specified properties.
* @param [properties] Properties to set
* @returns Setting instance
*/
public static create(properties?: ISetting): Setting;
/**
* Encodes the specified Setting message. Does not implicitly {@link Setting.verify|verify} messages.
* @param message Setting message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ISetting, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Setting message, length delimited. Does not implicitly {@link Setting.verify|verify} messages.
* @param message Setting message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ISetting, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Setting message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Setting
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): Setting;
/**
* Decodes a Setting message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Setting
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): Setting;
/**
* Verifies a Setting message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a Setting message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Setting
*/
public static fromObject(object: { [k: string]: any }): Setting;
/**
* Creates a plain object from a Setting message. Also converts values to other types if specified.
* @param message Setting
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: Setting, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Setting to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace Setting {
/** Properties of an Entry. */
interface IEntry {
/** Entry key */
key?: string | null | undefined;
/** Entry value */
value?: string | null | undefined;
}
/** Represents an Entry. */
class Entry implements IEntry {
/**
* Constructs a new Entry.
* @param [properties] Properties to set
*/
constructor(properties?: Setting.IEntry);
/** Entry key. */
public key: string;
/** Entry value. */
public value: string;
/**
* Creates a new Entry instance using the specified properties.
* @param [properties] Properties to set
* @returns Entry instance
*/
public static create(properties?: Setting.IEntry): Setting.Entry;
/**
* Encodes the specified Entry message. Does not implicitly {@link Setting.Entry.verify|verify} messages.
* @param message Entry message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: Setting.IEntry, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Entry message, length delimited. Does not implicitly {@link Setting.Entry.verify|verify} messages.
* @param message Entry message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: Setting.IEntry, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Entry message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Entry
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): Setting.Entry;
/**
* Decodes an Entry message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Entry
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): Setting.Entry;
/**
* Verifies an Entry message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates an Entry message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Entry
*/
public static fromObject(object: { [k: string]: any }): Setting.Entry;
/**
* Creates a plain object from an Entry message. Also converts values to other types if specified.
* @param message Entry
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: Setting.Entry, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Entry to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a TpStateEntry. */
export interface ITpStateEntry {
/** TpStateEntry address */
address?: string | null | undefined;
/** TpStateEntry data */
data?: Uint8Array | null | undefined;
}
/** Represents a TpStateEntry. */
export class TpStateEntry implements ITpStateEntry {
/**
* Constructs a new TpStateEntry.
* @param [properties] Properties to set
*/
constructor(properties?: ITpStateEntry);
/** TpStateEntry address. */
public address: string;
/** TpStateEntry data. */
public data: Uint8Array;
/**
* Creates a new TpStateEntry instance using the specified properties.
* @param [properties] Properties to set
* @returns TpStateEntry instance
*/
public static create(properties?: ITpStateEntry): TpStateEntry;
/**
* Encodes the specified TpStateEntry message. Does not implicitly {@link TpStateEntry.verify|verify} messages.
* @param message TpStateEntry message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ITpStateEntry, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TpStateEntry message, length delimited. Does not implicitly {@link TpStateEntry.verify|verify} messages.
* @param message TpStateEntry message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ITpStateEntry, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TpStateEntry message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TpStateEntry
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): TpStateEntry;
/**
* Decodes a TpStateEntry message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TpStateEntry
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): TpStateEntry;
/**
* Verifies a TpStateEntry message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a TpStateEntry message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TpStateEntry
*/
public static fromObject(object: { [k: string]: any }): TpStateEntry;
/**
* Creates a plain object from a TpStateEntry message. Also converts values to other types if specified.
* @param message TpStateEntry
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: TpStateEntry, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TpStateEntry to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a TpStateGetRequest. */
export interface ITpStateGetRequest {
/** TpStateGetRequest contextId */
contextId?: string | null | undefined;
/** TpStateGetRequest addresses */
addresses?: string[] | null | undefined;
}
/** Represents a TpStateGetRequest. */
export class TpStateGetRequest implements ITpStateGetRequest {
/**
* Constructs a new TpStateGetRequest.
* @param [properties] Properties to set
*/
constructor(properties?: ITpStateGetRequest);
/** TpStateGetRequest contextId. */
public contextId: string;
/** TpStateGetRequest addresses. */
public addresses: string[];
/**
* Creates a new TpStateGetRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns TpStateGetRequest instance
*/
public static create(properties?: ITpStateGetRequest): TpStateGetRequest;
/**
* Encodes the specified TpStateGetRequest message. Does not implicitly {@link TpStateGetRequest.verify|verify} messages.
* @param message TpStateGetRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ITpStateGetRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TpStateGetRequest message, length delimited. Does not implicitly {@link TpStateGetRequest.verify|verify} messages.
* @param message TpStateGetRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ITpStateGetRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TpStateGetRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TpStateGetRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): TpStateGetRequest;
/**
* Decodes a TpStateGetRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TpStateGetRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): TpStateGetRequest;
/**
* Verifies a TpStateGetRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a TpStateGetRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TpStateGetRequest
*/
public static fromObject(object: { [k: string]: any }): TpStateGetRequest;
/**
* Creates a plain object from a TpStateGetRequest message. Also converts values to other types if specified.
* @param message TpStateGetRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: TpStateGetRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TpStateGetRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a TpStateGetResponse. */
export interface ITpStateGetResponse {
/** TpStateGetResponse entries */
entries?: ITpStateEntry[] | null | undefined;
/** TpStateGetResponse status */
status?: TpStateGetResponse.Status | null | undefined;
}
/** Represents a TpStateGetResponse. */
export class TpStateGetResponse implements ITpStateGetResponse {
/**
* Constructs a new TpStateGetResponse.
* @param [properties] Properties to set
*/
constructor(properties?: ITpStateGetResponse);
/** TpStateGetResponse entries. */
public entries: ITpStateEntry[];
/** TpStateGetResponse status. */
public status: TpStateGetResponse.Status;
/**
* Creates a new TpStateGetResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns TpStateGetResponse instance
*/
public static create(properties?: ITpStateGetResponse): TpStateGetResponse;
/**
* Encodes the specified TpStateGetResponse message. Does not implicitly {@link TpStateGetResponse.verify|verify} messages.
* @param message TpStateGetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ITpStateGetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TpStateGetResponse message, length delimited. Does not implicitly {@link TpStateGetResponse.verify|verify} messages.
* @param message TpStateGetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ITpStateGetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TpStateGetResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TpStateGetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): TpStateGetResponse;
/**
* Decodes a TpStateGetResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TpStateGetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): TpStateGetResponse;
/**
* Verifies a TpStateGetResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a TpStateGetResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TpStateGetResponse
*/
public static fromObject(object: { [k: string]: any }): TpStateGetResponse;
/**
* Creates a plain object from a TpStateGetResponse message. Also converts values to other types if specified.
* @param message TpStateGetResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: TpStateGetResponse, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TpStateGetResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace TpStateGetResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
AUTHORIZATION_ERROR = 2,
}
}
/** Properties of a TpStateSetRequest. */
export interface ITpStateSetRequest {
/** TpStateSetRequest contextId */
contextId?: string | null | undefined;
/** TpStateSetRequest entries */
entries?: ITpStateEntry[] | null | undefined;
}
/** Represents a TpStateSetRequest. */
export class TpStateSetRequest implements ITpStateSetRequest {
/**
* Constructs a new TpStateSetRequest.
* @param [properties] Properties to set
*/
constructor(properties?: ITpStateSetRequest);
/** TpStateSetRequest contextId. */
public contextId: string;
/** TpStateSetRequest entries. */
public entries: ITpStateEntry[];
/**
* Creates a new TpStateSetRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns TpStateSetRequest instance
*/
public static create(properties?: ITpStateSetRequest): TpStateSetRequest;
/**
* Encodes the specified TpStateSetRequest message. Does not implicitly {@link TpStateSetRequest.verify|verify} messages.
* @param message TpStateSetRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ITpStateSetRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TpStateSetRequest message, length delimited. Does not implicitly {@link TpStateSetRequest.verify|verify} messages.
* @param message TpStateSetRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ITpStateSetRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TpStateSetRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TpStateSetRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): TpStateSetRequest;
/**
* Decodes a TpStateSetRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TpStateSetRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): TpStateSetRequest;
/**
* Verifies a TpStateSetRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a TpStateSetRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TpStateSetRequest
*/
public static fromObject(object: { [k: string]: any }): TpStateSetRequest;
/**
* Creates a plain object from a TpStateSetRequest message. Also converts values to other types if specified.
* @param message TpStateSetRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: TpStateSetRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TpStateSetRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a TpStateSetResponse. */
export interface ITpStateSetResponse {
/** TpStateSetResponse addresses */
addresses?: string[] | null | undefined;
/** TpStateSetResponse status */
status?: TpStateSetResponse.Status | null | undefined;
}
/** Represents a TpStateSetResponse. */
export class TpStateSetResponse implements ITpStateSetResponse {
/**
* Constructs a new TpStateSetResponse.
* @param [properties] Properties to set
*/
constructor(properties?: ITpStateSetResponse);
/** TpStateSetResponse addresses. */
public addresses: string[];
/** TpStateSetResponse status. */
public status: TpStateSetResponse.Status;
/**
* Creates a new TpStateSetResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns TpStateSetResponse instance
*/
public static create(properties?: ITpStateSetResponse): TpStateSetResponse;
/**
* Encodes the specified TpStateSetResponse message. Does not implicitly {@link TpStateSetResponse.verify|verify} messages.
* @param message TpStateSetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ITpStateSetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TpStateSetResponse message, length delimited. Does not implicitly {@link TpStateSetResponse.verify|verify} messages.
* @param message TpStateSetResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ITpStateSetResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TpStateSetResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TpStateSetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): TpStateSetResponse;
/**
* Decodes a TpStateSetResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TpStateSetResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): TpStateSetResponse;
/**
* Verifies a TpStateSetResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a TpStateSetResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TpStateSetResponse
*/
public static fromObject(object: { [k: string]: any }): TpStateSetResponse;
/**
* Creates a plain object from a TpStateSetResponse message. Also converts values to other types if specified.
* @param message TpStateSetResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: TpStateSetResponse, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TpStateSetResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace TpStateSetResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
AUTHORIZATION_ERROR = 2,
}
}
/** Properties of a TpStateDeleteRequest. */
export interface ITpStateDeleteRequest {
/** TpStateDeleteRequest contextId */
contextId?: string | null | undefined;
/** TpStateDeleteRequest addresses */
addresses?: string[] | null | undefined;
}
/** Represents a TpStateDeleteRequest. */
export class TpStateDeleteRequest implements ITpStateDeleteRequest {
/**
* Constructs a new TpStateDeleteRequest.
* @param [properties] Properties to set
*/
constructor(properties?: ITpStateDeleteRequest);
/** TpStateDeleteRequest contextId. */
public contextId: string;
/** TpStateDeleteRequest addresses. */
public addresses: string[];
/**
* Creates a new TpStateDeleteRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns TpStateDeleteRequest instance
*/
public static create(properties?: ITpStateDeleteRequest): TpStateDeleteRequest;
/**
* Encodes the specified TpStateDeleteRequest message. Does not implicitly {@link TpStateDeleteRequest.verify|verify} messages.
* @param message TpStateDeleteRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ITpStateDeleteRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TpStateDeleteRequest message, length delimited. Does not implicitly {@link TpStateDeleteRequest.verify|verify} messages.
* @param message TpStateDeleteRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ITpStateDeleteRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TpStateDeleteRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TpStateDeleteRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): TpStateDeleteRequest;
/**
* Decodes a TpStateDeleteRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TpStateDeleteRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): TpStateDeleteRequest;
/**
* Verifies a TpStateDeleteRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a TpStateDeleteRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TpStateDeleteRequest
*/
public static fromObject(object: { [k: string]: any }): TpStateDeleteRequest;
/**
* Creates a plain object from a TpStateDeleteRequest message. Also converts values to other types if specified.
* @param message TpStateDeleteRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: TpStateDeleteRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TpStateDeleteRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a TpStateDeleteResponse. */
export interface ITpStateDeleteResponse {
/** TpStateDeleteResponse addresses */
addresses?: string[] | null | undefined;
/** TpStateDeleteResponse status */
status?: TpStateDeleteResponse.Status | null | undefined;
}
/** Represents a TpStateDeleteResponse. */
export class TpStateDeleteResponse implements ITpStateDeleteResponse {
/**
* Constructs a new TpStateDeleteResponse.
* @param [properties] Properties to set
*/
constructor(properties?: ITpStateDeleteResponse);
/** TpStateDeleteResponse addresses. */
public addresses: string[];
/** TpStateDeleteResponse status. */
public status: TpStateDeleteResponse.Status;
/**
* Creates a new TpStateDeleteResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns TpStateDeleteResponse instance
*/
public static create(properties?: ITpStateDeleteResponse): TpStateDeleteResponse;
/**
* Encodes the specified TpStateDeleteResponse message. Does not implicitly {@link TpStateDeleteResponse.verify|verify} messages.
* @param message TpStateDeleteResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ITpStateDeleteResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TpStateDeleteResponse message, length delimited. Does not implicitly {@link TpStateDeleteResponse.verify|verify} messages.
* @param message TpStateDeleteResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ITpStateDeleteResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TpStateDeleteResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TpStateDeleteResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): TpStateDeleteResponse;
/**
* Decodes a TpStateDeleteResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TpStateDeleteResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): TpStateDeleteResponse;
/**
* Verifies a TpStateDeleteResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a TpStateDeleteResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TpStateDeleteResponse
*/
public static fromObject(object: { [k: string]: any }): TpStateDeleteResponse;
/**
* Creates a plain object from a TpStateDeleteResponse message. Also converts values to other types if specified.
* @param message TpStateDeleteResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: TpStateDeleteResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this TpStateDeleteResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace TpStateDeleteResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
AUTHORIZATION_ERROR = 2,
}
}
/** Properties of a TpReceiptAddDataRequest. */
export interface ITpReceiptAddDataRequest {
/** TpReceiptAddDataRequest contextId */
contextId?: string | null | undefined;
/** TpReceiptAddDataRequest data */
data?: Uint8Array | null | undefined;
}
/** Represents a TpReceiptAddDataRequest. */
export class TpReceiptAddDataRequest implements ITpReceiptAddDataRequest {
/**
* Constructs a new TpReceiptAddDataRequest.
* @param [properties] Properties to set
*/
constructor(properties?: ITpReceiptAddDataRequest);
/** TpReceiptAddDataRequest contextId. */
public contextId: string;
/** TpReceiptAddDataRequest data. */
public data: Uint8Array;
/**
* Creates a new TpReceiptAddDataRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns TpReceiptAddDataRequest instance
*/
public static create(properties?: ITpReceiptAddDataRequest): TpReceiptAddDataRequest;
/**
* Encodes the specified TpReceiptAddDataRequest message. Does not implicitly {@link TpReceiptAddDataRequest.verify|verify} messages.
* @param message TpReceiptAddDataRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ITpReceiptAddDataRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TpReceiptAddDataRequest message, length delimited. Does not implicitly {@link TpReceiptAddDataRequest.verify|verify} messages.
* @param message TpReceiptAddDataRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ITpReceiptAddDataRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TpReceiptAddDataRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TpReceiptAddDataRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): TpReceiptAddDataRequest;
/**
* Decodes a TpReceiptAddDataRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TpReceiptAddDataRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): TpReceiptAddDataRequest;
/**
* Verifies a TpReceiptAddDataRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a TpReceiptAddDataRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TpReceiptAddDataRequest
*/
public static fromObject(object: { [k: string]: any }): TpReceiptAddDataRequest;
/**
* Creates a plain object from a TpReceiptAddDataRequest message. Also converts values to other types if specified.
* @param message TpReceiptAddDataRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: TpReceiptAddDataRequest,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this TpReceiptAddDataRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a TpReceiptAddDataResponse. */
export interface ITpReceiptAddDataResponse {
/** TpReceiptAddDataResponse status */
status?: TpReceiptAddDataResponse.Status | null | undefined;
}
/** Represents a TpReceiptAddDataResponse. */
export class TpReceiptAddDataResponse implements ITpReceiptAddDataResponse {
/**
* Constructs a new TpReceiptAddDataResponse.
* @param [properties] Properties to set
*/
constructor(properties?: ITpReceiptAddDataResponse);
/** TpReceiptAddDataResponse status. */
public status: TpReceiptAddDataResponse.Status;
/**
* Creates a new TpReceiptAddDataResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns TpReceiptAddDataResponse instance
*/
public static create(properties?: ITpReceiptAddDataResponse): TpReceiptAddDataResponse;
/**
* Encodes the specified TpReceiptAddDataResponse message. Does not implicitly {@link TpReceiptAddDataResponse.verify|verify} messages.
* @param message TpReceiptAddDataResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ITpReceiptAddDataResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TpReceiptAddDataResponse message, length delimited. Does not implicitly {@link TpReceiptAddDataResponse.verify|verify} messages.
* @param message TpReceiptAddDataResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ITpReceiptAddDataResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TpReceiptAddDataResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TpReceiptAddDataResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): TpReceiptAddDataResponse;
/**
* Decodes a TpReceiptAddDataResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TpReceiptAddDataResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): TpReceiptAddDataResponse;
/**
* Verifies a TpReceiptAddDataResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a TpReceiptAddDataResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TpReceiptAddDataResponse
*/
public static fromObject(object: { [k: string]: any }): TpReceiptAddDataResponse;
/**
* Creates a plain object from a TpReceiptAddDataResponse message. Also converts values to other types if specified.
* @param message TpReceiptAddDataResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(
message: TpReceiptAddDataResponse,
options?: $protobuf.IConversionOptions,
): { [k: string]: any };
/**
* Converts this TpReceiptAddDataResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace TpReceiptAddDataResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
ERROR = 2,
}
}
/** Properties of a TpEventAddRequest. */
export interface ITpEventAddRequest {
/** TpEventAddRequest contextId */
contextId?: string | null | undefined;
/** TpEventAddRequest event */
event?: IEvent | null | undefined;
}
/** Represents a TpEventAddRequest. */
export class TpEventAddRequest implements ITpEventAddRequest {
/**
* Constructs a new TpEventAddRequest.
* @param [properties] Properties to set
*/
constructor(properties?: ITpEventAddRequest);
/** TpEventAddRequest contextId. */
public contextId: string;
/** TpEventAddRequest event. */
public event?: IEvent | null | undefined;
/**
* Creates a new TpEventAddRequest instance using the specified properties.
* @param [properties] Properties to set
* @returns TpEventAddRequest instance
*/
public static create(properties?: ITpEventAddRequest): TpEventAddRequest;
/**
* Encodes the specified TpEventAddRequest message. Does not implicitly {@link TpEventAddRequest.verify|verify} messages.
* @param message TpEventAddRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ITpEventAddRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TpEventAddRequest message, length delimited. Does not implicitly {@link TpEventAddRequest.verify|verify} messages.
* @param message TpEventAddRequest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ITpEventAddRequest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TpEventAddRequest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TpEventAddRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): TpEventAddRequest;
/**
* Decodes a TpEventAddRequest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TpEventAddRequest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): TpEventAddRequest;
/**
* Verifies a TpEventAddRequest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a TpEventAddRequest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TpEventAddRequest
*/
public static fromObject(object: { [k: string]: any }): TpEventAddRequest;
/**
* Creates a plain object from a TpEventAddRequest message. Also converts values to other types if specified.
* @param message TpEventAddRequest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: TpEventAddRequest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TpEventAddRequest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a TpEventAddResponse. */
export interface ITpEventAddResponse {
/** TpEventAddResponse status */
status?: TpEventAddResponse.Status | null | undefined;
}
/** Represents a TpEventAddResponse. */
export class TpEventAddResponse implements ITpEventAddResponse {
/**
* Constructs a new TpEventAddResponse.
* @param [properties] Properties to set
*/
constructor(properties?: ITpEventAddResponse);
/** TpEventAddResponse status. */
public status: TpEventAddResponse.Status;
/**
* Creates a new TpEventAddResponse instance using the specified properties.
* @param [properties] Properties to set
* @returns TpEventAddResponse instance
*/
public static create(properties?: ITpEventAddResponse): TpEventAddResponse;
/**
* Encodes the specified TpEventAddResponse message. Does not implicitly {@link TpEventAddResponse.verify|verify} messages.
* @param message TpEventAddResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ITpEventAddResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TpEventAddResponse message, length delimited. Does not implicitly {@link TpEventAddResponse.verify|verify} messages.
* @param message TpEventAddResponse message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ITpEventAddResponse, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TpEventAddResponse message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TpEventAddResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): TpEventAddResponse;
/**
* Decodes a TpEventAddResponse message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TpEventAddResponse
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): TpEventAddResponse;
/**
* Verifies a TpEventAddResponse message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a TpEventAddResponse message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TpEventAddResponse
*/
public static fromObject(object: { [k: string]: any }): TpEventAddResponse;
/**
* Creates a plain object from a TpEventAddResponse message. Also converts values to other types if specified.
* @param message TpEventAddResponse
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: TpEventAddResponse, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TpEventAddResponse to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace TpEventAddResponse {
/** Status enum. */
enum Status {
STATUS_UNSET = 0,
OK = 1,
ERROR = 2,
}
}
/** Properties of a MessageList. */
export interface IMessageList {
/** MessageList messages */
messages?: IMessage[] | null | undefined;
}
/** Represents a MessageList. */
export class MessageList implements IMessageList {
/**
* Constructs a new MessageList.
* @param [properties] Properties to set
*/
constructor(properties?: IMessageList);
/** MessageList messages. */
public messages: IMessage[];
/**
* Creates a new MessageList instance using the specified properties.
* @param [properties] Properties to set
* @returns MessageList instance
*/
public static create(properties?: IMessageList): MessageList;
/**
* Encodes the specified MessageList message. Does not implicitly {@link MessageList.verify|verify} messages.
* @param message MessageList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IMessageList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified MessageList message, length delimited. Does not implicitly {@link MessageList.verify|verify} messages.
* @param message MessageList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IMessageList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a MessageList message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns MessageList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): MessageList;
/**
* Decodes a MessageList message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns MessageList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): MessageList;
/**
* Verifies a MessageList message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a MessageList message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns MessageList
*/
public static fromObject(object: { [k: string]: any }): MessageList;
/**
* Creates a plain object from a MessageList message. Also converts values to other types if specified.
* @param message MessageList
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: MessageList, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this MessageList to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Message. */
export interface IMessage {
/** Message messageType */
messageType?: Message.MessageType | null | undefined;
/** Message correlationId */
correlationId?: string | null | undefined;
/** Message content */
content?: Uint8Array | null | undefined;
}
/** Represents a Message. */
export class Message implements IMessage {
/**
* Constructs a new Message.
* @param [properties] Properties to set
*/
constructor(properties?: IMessage);
/** Message messageType. */
public messageType: Message.MessageType;
/** Message correlationId. */
public correlationId: string;
/** Message content. */
public content: Uint8Array;
/**
* Creates a new Message instance using the specified properties.
* @param [properties] Properties to set
* @returns Message instance
*/
public static create(properties?: IMessage): Message;
/**
* Encodes the specified Message message. Does not implicitly {@link Message.verify|verify} messages.
* @param message Message message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: IMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Message message, length delimited. Does not implicitly {@link Message.verify|verify} messages.
* @param message Message message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: IMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Message message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Message
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: $protobuf.Reader | Uint8Array, length?: number): Message;
/**
* Decodes a Message message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Message
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: $protobuf.Reader | Uint8Array): Message;
/**
* Verifies a Message message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): string | null;
/**
* Creates a Message message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Message
*/
public static fromObject(object: { [k: string]: any }): Message;
/**
* Creates a plain object from a Message message. Also converts values to other types if specified.
* @param message Message
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: Message, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Message to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
export namespace Message {
/** MessageType enum. */
enum MessageType {
DEFAULT = 0,
TP_REGISTER_REQUEST = 1,
TP_REGISTER_RESPONSE = 2,
TP_UNREGISTER_REQUEST = 3,
TP_UNREGISTER_RESPONSE = 4,
TP_PROCESS_REQUEST = 5,
TP_PROCESS_RESPONSE = 6,
TP_STATE_GET_REQUEST = 7,
TP_STATE_GET_RESPONSE = 8,
TP_STATE_SET_REQUEST = 9,
TP_STATE_SET_RESPONSE = 10,
TP_STATE_DELETE_REQUEST = 11,
TP_STATE_DELETE_RESPONSE = 12,
TP_RECEIPT_ADD_DATA_REQUEST = 13,
TP_RECEIPT_ADD_DATA_RESPONSE = 14,
TP_EVENT_ADD_REQUEST = 15,
TP_EVENT_ADD_RESPONSE = 16,
CLIENT_BATCH_SUBMIT_REQUEST = 100,
CLIENT_BATCH_SUBMIT_RESPONSE = 101,
CLIENT_BLOCK_LIST_REQUEST = 102,
CLIENT_BLOCK_LIST_RESPONSE = 103,
CLIENT_BLOCK_GET_BY_ID_REQUEST = 104,
CLIENT_BLOCK_GET_RESPONSE = 105,
CLIENT_BATCH_LIST_REQUEST = 106,
CLIENT_BATCH_LIST_RESPONSE = 107,
CLIENT_BATCH_GET_REQUEST = 108,
CLIENT_BATCH_GET_RESPONSE = 109,
CLIENT_TRANSACTION_LIST_REQUEST = 110,
CLIENT_TRANSACTION_LIST_RESPONSE = 111,
CLIENT_TRANSACTION_GET_REQUEST = 112,
CLIENT_TRANSACTION_GET_RESPONSE = 113,
CLIENT_STATE_CURRENT_REQUEST = 114,
CLIENT_STATE_CURRENT_RESPONSE = 115,
CLIENT_STATE_LIST_REQUEST = 116,
CLIENT_STATE_LIST_RESPONSE = 117,
CLIENT_STATE_GET_REQUEST = 118,
CLIENT_STATE_GET_RESPONSE = 119,
CLIENT_BATCH_STATUS_REQUEST = 120,
CLIENT_BATCH_STATUS_RESPONSE = 121,
CLIENT_RECEIPT_GET_REQUEST = 122,
CLIENT_RECEIPT_GET_RESPONSE = 123,
CLIENT_BLOCK_GET_BY_NUM_REQUEST = 124,
CLIENT_PEERS_GET_REQUEST = 125,
CLIENT_PEERS_GET_RESPONSE = 126,
CLIENT_BLOCK_GET_BY_TRANSACTION_ID_REQUEST = 127,
CLIENT_BLOCK_GET_BY_BATCH_ID_REQUEST = 128,
CLIENT_STATUS_GET_REQUEST = 129,
CLIENT_STATUS_GET_RESPONSE = 130,
CLIENT_EVENTS_SUBSCRIBE_REQUEST = 500,
CLIENT_EVENTS_SUBSCRIBE_RESPONSE = 501,
CLIENT_EVENTS_UNSUBSCRIBE_REQUEST = 502,
CLIENT_EVENTS_UNSUBSCRIBE_RESPONSE = 503,
CLIENT_EVENTS = 504,
CLIENT_EVENTS_GET_REQUEST = 505,
CLIENT_EVENTS_GET_RESPONSE = 506,
GOSSIP_MESSAGE = 200,
GOSSIP_REGISTER = 201,
GOSSIP_UNREGISTER = 202,
GOSSIP_BLOCK_REQUEST = 205,
GOSSIP_BLOCK_RESPONSE = 206,
GOSSIP_BATCH_BY_BATCH_ID_REQUEST = 207,
GOSSIP_BATCH_BY_TRANSACTION_ID_REQUEST = 208,
GOSSIP_BATCH_RESPONSE = 209,
GOSSIP_GET_PEERS_REQUEST = 210,
GOSSIP_GET_PEERS_RESPONSE = 211,
GOSSIP_CONSENSUS_MESSAGE = 212,
NETWORK_ACK = 300,
NETWORK_CONNECT = 301,
NETWORK_DISCONNECT = 302,
AUTHORIZATION_CONNECTION_RESPONSE = 600,
AUTHORIZATION_VIOLATION = 601,
AUTHORIZATION_TRUST_REQUEST = 602,
AUTHORIZATION_TRUST_RESPONSE = 603,
AUTHORIZATION_CHALLENGE_REQUEST = 604,
AUTHORIZATION_CHALLENGE_RESPONSE = 605,
AUTHORIZATION_CHALLENGE_SUBMIT = 606,
AUTHORIZATION_CHALLENGE_RESULT = 607,
PING_REQUEST = 700,
PING_RESPONSE = 701,
CONSENSUS_REGISTER_REQUEST = 800,
CONSENSUS_REGISTER_RESPONSE = 801,
CONSENSUS_SEND_TO_REQUEST = 802,
CONSENSUS_SEND_TO_RESPONSE = 803,
CONSENSUS_BROADCAST_REQUEST = 804,
CONSENSUS_BROADCAST_RESPONSE = 805,
CONSENSUS_INITIALIZE_BLOCK_REQUEST = 806,
CONSENSUS_INITIALIZE_BLOCK_RESPONSE = 807,
CONSENSUS_FINALIZE_BLOCK_REQUEST = 808,
CONSENSUS_FINALIZE_BLOCK_RESPONSE = 809,
CONSENSUS_SUMMARIZE_BLOCK_REQUEST = 828,
CONSENSUS_SUMMARIZE_BLOCK_RESPONSE = 829,
CONSENSUS_CANCEL_BLOCK_REQUEST = 810,
CONSENSUS_CANCEL_BLOCK_RESPONSE = 811,
CONSENSUS_CHECK_BLOCKS_REQUEST = 812,
CONSENSUS_CHECK_BLOCKS_RESPONSE = 813,
CONSENSUS_COMMIT_BLOCK_REQUEST = 814,
CONSENSUS_COMMIT_BLOCK_RESPONSE = 815,
CONSENSUS_IGNORE_BLOCK_REQUEST = 816,
CONSENSUS_IGNORE_BLOCK_RESPONSE = 817,
CONSENSUS_FAIL_BLOCK_REQUEST = 818,
CONSENSUS_FAIL_BLOCK_RESPONSE = 819,
CONSENSUS_SETTINGS_GET_REQUEST = 820,
CONSENSUS_SETTINGS_GET_RESPONSE = 821,
CONSENSUS_STATE_GET_REQUEST = 822,
CONSENSUS_STATE_GET_RESPONSE = 823,
CONSENSUS_BLOCKS_GET_REQUEST = 824,
CONSENSUS_BLOCKS_GET_RESPONSE = 825,
CONSENSUS_CHAIN_HEAD_GET_REQUEST = 826,
CONSENSUS_CHAIN_HEAD_GET_RESPONSE = 827,
CONSENSUS_NOTIFY_PEER_CONNECTED = 900,
CONSENSUS_NOTIFY_PEER_DISCONNECTED = 901,
CONSENSUS_NOTIFY_PEER_MESSAGE = 902,
CONSENSUS_NOTIFY_BLOCK_NEW = 903,
CONSENSUS_NOTIFY_BLOCK_VALID = 904,
CONSENSUS_NOTIFY_BLOCK_INVALID = 905,
CONSENSUS_NOTIFY_BLOCK_COMMIT = 906,
CONSENSUS_NOTIFY_ACK = 999,
}
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { Location } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { BatchManagementClient } from "../batchManagementClient";
import {
SupportedSku,
LocationListSupportedVirtualMachineSkusNextOptionalParams,
LocationListSupportedVirtualMachineSkusOptionalParams,
LocationListSupportedCloudServiceSkusNextOptionalParams,
LocationListSupportedCloudServiceSkusOptionalParams,
LocationGetQuotasOptionalParams,
LocationGetQuotasResponse,
LocationListSupportedVirtualMachineSkusResponse,
LocationListSupportedCloudServiceSkusResponse,
CheckNameAvailabilityParameters,
LocationCheckNameAvailabilityOptionalParams,
LocationCheckNameAvailabilityResponse,
LocationListSupportedVirtualMachineSkusNextResponse,
LocationListSupportedCloudServiceSkusNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing Location operations. */
export class LocationImpl implements Location {
private readonly client: BatchManagementClient;
/**
* Initialize a new instance of the class Location class.
* @param client Reference to the service client
*/
constructor(client: BatchManagementClient) {
this.client = client;
}
/**
* Gets the list of Batch supported Virtual Machine VM sizes available at the given location.
* @param locationName The region for which to retrieve Batch service supported SKUs.
* @param options The options parameters.
*/
public listSupportedVirtualMachineSkus(
locationName: string,
options?: LocationListSupportedVirtualMachineSkusOptionalParams
): PagedAsyncIterableIterator<SupportedSku> {
const iter = this.listSupportedVirtualMachineSkusPagingAll(
locationName,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listSupportedVirtualMachineSkusPagingPage(
locationName,
options
);
}
};
}
private async *listSupportedVirtualMachineSkusPagingPage(
locationName: string,
options?: LocationListSupportedVirtualMachineSkusOptionalParams
): AsyncIterableIterator<SupportedSku[]> {
let result = await this._listSupportedVirtualMachineSkus(
locationName,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listSupportedVirtualMachineSkusNext(
locationName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listSupportedVirtualMachineSkusPagingAll(
locationName: string,
options?: LocationListSupportedVirtualMachineSkusOptionalParams
): AsyncIterableIterator<SupportedSku> {
for await (const page of this.listSupportedVirtualMachineSkusPagingPage(
locationName,
options
)) {
yield* page;
}
}
/**
* Gets the list of Batch supported Cloud Service VM sizes available at the given location.
* @param locationName The region for which to retrieve Batch service supported SKUs.
* @param options The options parameters.
*/
public listSupportedCloudServiceSkus(
locationName: string,
options?: LocationListSupportedCloudServiceSkusOptionalParams
): PagedAsyncIterableIterator<SupportedSku> {
const iter = this.listSupportedCloudServiceSkusPagingAll(
locationName,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listSupportedCloudServiceSkusPagingPage(
locationName,
options
);
}
};
}
private async *listSupportedCloudServiceSkusPagingPage(
locationName: string,
options?: LocationListSupportedCloudServiceSkusOptionalParams
): AsyncIterableIterator<SupportedSku[]> {
let result = await this._listSupportedCloudServiceSkus(
locationName,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listSupportedCloudServiceSkusNext(
locationName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listSupportedCloudServiceSkusPagingAll(
locationName: string,
options?: LocationListSupportedCloudServiceSkusOptionalParams
): AsyncIterableIterator<SupportedSku> {
for await (const page of this.listSupportedCloudServiceSkusPagingPage(
locationName,
options
)) {
yield* page;
}
}
/**
* Gets the Batch service quotas for the specified subscription at the given location.
* @param locationName The region for which to retrieve Batch service quotas.
* @param options The options parameters.
*/
getQuotas(
locationName: string,
options?: LocationGetQuotasOptionalParams
): Promise<LocationGetQuotasResponse> {
return this.client.sendOperationRequest(
{ locationName, options },
getQuotasOperationSpec
);
}
/**
* Gets the list of Batch supported Virtual Machine VM sizes available at the given location.
* @param locationName The region for which to retrieve Batch service supported SKUs.
* @param options The options parameters.
*/
private _listSupportedVirtualMachineSkus(
locationName: string,
options?: LocationListSupportedVirtualMachineSkusOptionalParams
): Promise<LocationListSupportedVirtualMachineSkusResponse> {
return this.client.sendOperationRequest(
{ locationName, options },
listSupportedVirtualMachineSkusOperationSpec
);
}
/**
* Gets the list of Batch supported Cloud Service VM sizes available at the given location.
* @param locationName The region for which to retrieve Batch service supported SKUs.
* @param options The options parameters.
*/
private _listSupportedCloudServiceSkus(
locationName: string,
options?: LocationListSupportedCloudServiceSkusOptionalParams
): Promise<LocationListSupportedCloudServiceSkusResponse> {
return this.client.sendOperationRequest(
{ locationName, options },
listSupportedCloudServiceSkusOperationSpec
);
}
/**
* Checks whether the Batch account name is available in the specified region.
* @param locationName The desired region for the name check.
* @param parameters Properties needed to check the availability of a name.
* @param options The options parameters.
*/
checkNameAvailability(
locationName: string,
parameters: CheckNameAvailabilityParameters,
options?: LocationCheckNameAvailabilityOptionalParams
): Promise<LocationCheckNameAvailabilityResponse> {
return this.client.sendOperationRequest(
{ locationName, parameters, options },
checkNameAvailabilityOperationSpec
);
}
/**
* ListSupportedVirtualMachineSkusNext
* @param locationName The region for which to retrieve Batch service supported SKUs.
* @param nextLink The nextLink from the previous successful call to the
* ListSupportedVirtualMachineSkus method.
* @param options The options parameters.
*/
private _listSupportedVirtualMachineSkusNext(
locationName: string,
nextLink: string,
options?: LocationListSupportedVirtualMachineSkusNextOptionalParams
): Promise<LocationListSupportedVirtualMachineSkusNextResponse> {
return this.client.sendOperationRequest(
{ locationName, nextLink, options },
listSupportedVirtualMachineSkusNextOperationSpec
);
}
/**
* ListSupportedCloudServiceSkusNext
* @param locationName The region for which to retrieve Batch service supported SKUs.
* @param nextLink The nextLink from the previous successful call to the ListSupportedCloudServiceSkus
* method.
* @param options The options parameters.
*/
private _listSupportedCloudServiceSkusNext(
locationName: string,
nextLink: string,
options?: LocationListSupportedCloudServiceSkusNextOptionalParams
): Promise<LocationListSupportedCloudServiceSkusNextResponse> {
return this.client.sendOperationRequest(
{ locationName, nextLink, options },
listSupportedCloudServiceSkusNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const getQuotasOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/quotas",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.BatchLocationQuota
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.locationName
],
headerParameters: [Parameters.accept],
serializer
};
const listSupportedVirtualMachineSkusOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/virtualMachineSkus",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SupportedSkusResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [
Parameters.apiVersion,
Parameters.maxresults,
Parameters.filter
],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.locationName
],
headerParameters: [Parameters.accept],
serializer
};
const listSupportedCloudServiceSkusOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/cloudServiceSkus",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SupportedSkusResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [
Parameters.apiVersion,
Parameters.maxresults,
Parameters.filter
],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.locationName
],
headerParameters: [Parameters.accept],
serializer
};
const checkNameAvailabilityOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.Batch/locations/{locationName}/checkNameAvailability",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.CheckNameAvailabilityResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.parameters7,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.locationName
],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const listSupportedVirtualMachineSkusNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SupportedSkusResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [
Parameters.apiVersion,
Parameters.maxresults,
Parameters.filter
],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.nextLink,
Parameters.locationName
],
headerParameters: [Parameters.accept],
serializer
};
const listSupportedCloudServiceSkusNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.SupportedSkusResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [
Parameters.apiVersion,
Parameters.maxresults,
Parameters.filter
],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.nextLink,
Parameters.locationName
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
export default class BlowfishEngine {
// prettier-ignore
static readonly KP: number[] = [
0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0,
0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b
];
// prettier-ignore
static readonly KS0: number[] = [
0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96,
0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658,
0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e,
0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6,
0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c,
0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1,
0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a,
0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176,
0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706,
0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b,
0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c,
0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a,
0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760,
0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8,
0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33,
0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0,
0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777,
0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705,
0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e,
0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9,
0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f,
0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a
];
// prettier-ignore
static readonly KS1: number[] = [
0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d,
0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65,
0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9,
0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d,
0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc,
0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908,
0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124,
0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908,
0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b,
0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa,
0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d,
0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5,
0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96,
0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca,
0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77,
0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054,
0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea,
0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646,
0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea,
0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e,
0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd,
0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7
];
// prettier-ignore
static readonly KS2: number[] = [
0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7,
0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af,
0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4,
0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec,
0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332,
0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58,
0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22,
0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60,
0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99,
0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74,
0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3,
0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979,
0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa,
0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086,
0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24,
0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84,
0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09,
0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe,
0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0,
0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188,
0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8,
0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0
];
// prettier-ignore
static readonly KS3: number[] = [
0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742,
0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79,
0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a,
0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1,
0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797,
0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6,
0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba,
0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5,
0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce,
0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd,
0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb,
0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc,
0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc,
0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a,
0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a,
0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b,
0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e,
0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623,
0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a,
0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3,
0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c,
0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
];
static readonly ROUNDS: number = 16;
static readonly BLOCK_SIZE: number = 8;
static readonly SBOX_SK: number = 256;
static readonly P_SZ: number = BlowfishEngine.ROUNDS + 2;
S0: number[];
S1: number[];
S2: number[];
S3: number[];
P: number[];
workingKey: Uint8Array;
constructor() {
this.S0 = new Array<number>(BlowfishEngine.SBOX_SK);
this.S1 = new Array<number>(BlowfishEngine.SBOX_SK);
this.S2 = new Array<number>(BlowfishEngine.SBOX_SK);
this.S3 = new Array<number>(BlowfishEngine.SBOX_SK);
this.P = new Array<number>(BlowfishEngine.P_SZ);
this.workingKey = new Uint8Array(16);
}
init(key: Uint8Array): void {
this.workingKey = key;
this.setKey(this.workingKey);
}
setKey(key: Uint8Array): void {
/*
* (1) Initialize the S-boxes and the P-array, with a fixed string This
* string contains the hexadecimal digits of pi (3.141...)
*/
for (let i = 0; i < BlowfishEngine.SBOX_SK; i++) {
this.S0[i] = BlowfishEngine.KS0[i];
this.S1[i] = BlowfishEngine.KS1[i];
this.S2[i] = BlowfishEngine.KS2[i];
this.S3[i] = BlowfishEngine.KS3[i];
}
for (let i = 0; i < BlowfishEngine.P_SZ; i++) {
this.P[i] = BlowfishEngine.KP[i];
}
/*
* (2) Now, XOR P[0] with the first 32 bits of the key, XOR P[1] with
* the second 32-bits of the key, and so on for all bits of the key (up
* to P[17]). Repeatedly cycle through the key bits until the entire
* P-array has been XOR-ed with the key bits
*/
const keyLength = key.byteLength;
let keyIndex = 0;
for (let i = 0; i < BlowfishEngine.P_SZ; i++) {
// get the 32 bits of the key, in 4 * 8 bit chunks
let data = 0x0000000;
for (let j = 0; j < 4; j++) {
// create a 32 bit block
data = (data << 8) | (key[keyIndex++] & 0xff);
// wrap when we get to the end of the key
if (keyIndex >= keyLength) {
keyIndex = 0;
}
}
// XOR the newly created 32 bit chunk onto the P-array
this.P[i] ^= data;
}
/*
* (3) Encrypt the all-zero string with the Blowfish algorithm, using
* the sub-keys described in (1) and (2)
*
* (4) Replace P1 and P2 with the output of step (3)
*
* (5) Encrypt the output of step(3) using the Blowfish algorithm, with
* the modified sub-keys.
*
* (6) Replace P3 and P4 with the output of step (5)
*
* (7) Continue the process, replacing all elements of the P-array and
* then all four S-boxes in order, with the output of the continuously
* changing Blowfish algorithm
*/
this.processTable(0, 0, this.P);
this.processTable(this.P[BlowfishEngine.P_SZ - 2], this.P[BlowfishEngine.P_SZ - 1], this.S0);
this.processTable(this.S0[BlowfishEngine.SBOX_SK - 2], this.S0[BlowfishEngine.SBOX_SK - 1], this.S1);
this.processTable(this.S1[BlowfishEngine.SBOX_SK - 2], this.S1[BlowfishEngine.SBOX_SK - 1], this.S2);
this.processTable(this.S2[BlowfishEngine.SBOX_SK - 2], this.S2[BlowfishEngine.SBOX_SK - 1], this.S3);
}
processTable(xl: number, xr: number, table: number[]): void {
const size: number = table.length;
for (let s = 0; s < size; s += 2) {
xl = this.xor(xl, this.P[0]);
for (let i = 1; i < BlowfishEngine.ROUNDS; i += 2) {
xr = this.xor(xr, this.xor(this.F(xl), this.P[i]));
xl = this.xor(xl, this.xor(this.F(xr), this.P[i + 1]));
}
xr = this.xor(xr, this.P[BlowfishEngine.ROUNDS + 1]);
table[s] = xr;
table[s + 1] = xl;
xr = xl; // end of cycle swap
xl = table[s];
}
}
/**
* Function F looks like this:
* Divide xL into four eight-bit quarters: a, b, c, and d.
* Then, F(xL) = ((S1,a + S2,b mod 232) XOR S3,c) + S4,d mod 232.
* F(0xFFFFFF)
* ((S1[255] + S2[255]) XOR S3[255]) + S4[255]
* ((0x6e85076a + 0xdb83adf7) ^ 0x406000e0) + 0x3ac372e6
* @param x
*/
F(x: number): number {
return ((this.S0[x >>> 24] + this.S1[(x >>> 16) & 0xff]) ^ this.S2[(x >>> 8) & 0xff]) + this.S3[x & 0xff];
}
getBlockSize(): number {
return BlowfishEngine.BLOCK_SIZE;
}
encryptBlock(src: Uint8Array, srcIndex: number, dst: Uint8Array, dstIndex: number): void {
let xl: number = this.bytesTo32Bits(src, srcIndex);
let xr: number = this.bytesTo32Bits(src, srcIndex + 4);
xl ^= this.P[0];
for (let i = 1; i < BlowfishEngine.ROUNDS; i += 2) {
xr ^= this.F(xl) ^ this.P[i];
xl ^= this.F(xr) ^ this.P[i + 1];
}
xr ^= this.P[BlowfishEngine.ROUNDS + 1];
this.bits32ToBytes(xr, dst, dstIndex);
this.bits32ToBytes(xl, dst, dstIndex + 4);
}
decryptBlock(src: Uint8Array, srcIndex: number, dst: Uint8Array, dstIndex: number): void {
let xl = this.bytesTo32Bits(src, srcIndex);
let xr = this.bytesTo32Bits(src, srcIndex + 4);
xl ^= this.P[BlowfishEngine.ROUNDS + 1];
for (let i = BlowfishEngine.ROUNDS; i > 0; i -= 2) {
xr ^= this.F(xl) ^ this.P[i];
xl ^= this.F(xr) ^ this.P[i - 1];
}
xr ^= this.P[0];
this.bits32ToBytes(xr, dst, dstIndex);
this.bits32ToBytes(xl, dst, dstIndex + 4);
}
signedToUnsigned(signed: number): number {
return signed >>> 0;
}
xor(a: number, b: number): number {
return this.signedToUnsigned(a ^ b);
}
addMod32(a: number, b: number): number {
return this.signedToUnsigned((a + b) | 0);
}
bytesTo32Bits(b: Uint8Array, i: number): number {
return this.signedToUnsigned(
((b[i + 3] & 0xff) << 24) | ((b[i + 2] & 0xff) << 16) | ((b[i + 1] & 0xff) << 8) | (b[i] & 0xff)
);
}
bits32ToBytes(inb: number, b: Uint8Array, offset: number): void {
b[offset] = inb;
b[offset + 1] = inb >> 8;
b[offset + 2] = inb >> 16;
b[offset + 3] = inb >> 24;
}
} | the_stack |
import {
Action,
Dictionary,
Text,
MagicVariable,
Variable,
List,
ContentItemFilter,
AdjustOffset,
RawParameter
} from "./OutputData";
import { ConvertingContext } from "./Converter";
import { Position } from "./Production";
import { CoercionTypeClass } from "./WFTypes/Types";
import { PositionedError } from "./PositionedError";
export { PositionedError } from "./PositionedError";
export class Parse {
special: "InputArg" | "ControlFlowMode" | "Arglist" | undefined;
start: Position;
end: Position;
constructor(start: Position, end: Position) {
this.start = start;
this.end = end;
}
error(_cc: ConvertingContext, message: string) {
return new PositionedError(message, this.start, this.end);
}
warn(cc: ConvertingContext, message: string) {
return cc.warn(new PositionedError(message, this.start, this.end));
}
canBeString(_cc: ConvertingContext): this is AsString {
return false;
}
canBeBoolean(_cc: ConvertingContext): this is AsBoolean {
return false;
}
canBeText(_cc: ConvertingContext): this is AsText {
return false;
}
canBeList(_cc: ConvertingContext): this is AsList {
return false;
}
canBeArray(_cc: ConvertingContext): this is AsArray {
return false;
}
canBeAbleArray(_cc: ConvertingContext): this is AsAbleArray {
return false;
}
canBeVariable(_cc: ConvertingContext): this is AsVariable {
return false;
}
canBeAction(_cc: ConvertingContext): this is AsAction {
return false;
}
canBeDictionary(_cc: ConvertingContext): this is AsDictionary {
return false;
}
canBeRawKeyedDictionary(
_cc: ConvertingContext
): this is AsRawKeyedDictionary {
return false;
}
canBeRawDeepDictionary(
_cc: ConvertingContext
): this is AsRawDeepDictionary {
return false;
}
canBeRawDeepArray(_cc: ConvertingContext): this is AsRawDeepArray {
return false;
}
canBeNameType(_cc: ConvertingContext): this is AsNameType {
return false;
}
canBeStringVariable(_cc: ConvertingContext): this is AsStringVariable {
return false;
}
canBeNumber(_cc: ConvertingContext): this is AsNumber {
return false;
}
canBeFilter(_cc: ConvertingContext): this is AsFilter {
return false;
}
canBeFilterItem(_cc: ConvertingContext): this is AsFilterItem {
return false;
}
canBePreprocessorVariableName(
_cc: ConvertingContext
): this is AsPreprocessorVariableName {
return false;
}
canBeTimeOffsetParameter(
_cc: ConvertingContext
): this is AsTimeOffsetParameter {
return false;
}
canBeRaw(_cc: ConvertingContext): this is AsRaw {
return false;
}
canBeImportQuestion(_cc: ConvertingContext): this is AsImportQuestion {
return false;
}
getDeepestRealValue(_cc: ConvertingContext): Parse {
return this;
}
// [Symbol.hasInstance]() {
// throw new Error("Instanceof is not supported on Parse. This should never happen.");
// }
}
export interface AsString extends Parse {
canBeString(cc: ConvertingContext): true;
asString(cc: ConvertingContext): string;
}
export interface AsBoolean extends Parse {
canBeBoolean(cc: ConvertingContext): true;
asBoolean(cc: ConvertingContext): boolean;
}
export interface AsText extends Parse {
canBeText(cc: ConvertingContext): true;
asText(cc: ConvertingContext): Text;
}
export interface AsList extends Parse {
canBeList(cc: ConvertingContext): true;
asList(cc: ConvertingContext): List;
}
export interface AsArray extends Parse {
canBeArray(cc: ConvertingContext): true;
asArray(cc: ConvertingContext): Array<string>;
}
export interface AsAbleArray extends Parse {
canBeAbleArray(cc: ConvertingContext): true;
asAbleArray(cc: ConvertingContext): Array<AsAble>;
}
export interface AsVariable extends Parse {
canBeVariable(cc: ConvertingContext): true;
asVariable(cc: ConvertingContext): Variable;
}
export interface AsAction extends Parse {
canBeAction(cc: ConvertingContext): true;
asAction(cc: ConvertingContext): Action | undefined;
}
export interface AsDictionary extends Parse {
canBeDictionary(cc: ConvertingContext): true;
asDictionary(cc: ConvertingContext): Dictionary;
}
export interface AsRawKeyedDictionary extends Parse {
canBeRawKeyedDictionary(cc: ConvertingContext): true;
asRawKeyedDictionary(cc: ConvertingContext): { [key: string]: AsAble };
}
export interface AsRawDeepDictionary extends Parse {
canBeRawDeepDictionary(cc: ConvertingContext): true;
asRawDeepDictionary(cc: ConvertingContext): NestedStringDictionary;
}
export interface AsRawDeepArray extends Parse {
canBeRawDeepArray(cc: ConvertingContext): true;
asRawDeepArray(cc: ConvertingContext): NestedStringDictionaryItemArray;
}
export interface AsNameType extends Parse {
canBeNameType(cc: ConvertingContext): true;
asNameType(cc: ConvertingContext): { name: string; type: string };
}
export interface AsStringVariable extends Parse {
canBeStringVariable(cc: ConvertingContext): true;
asStringVariable(cc: ConvertingContext): string;
}
export interface AsNumber extends Parse {
canBeNumber(cc: ConvertingContext): true;
asNumber(cc: ConvertingContext): number;
}
export interface AsFilter extends Parse {
canBeFilter(cc: ConvertingContext): true;
asFilter(cc: ConvertingContext, type: CoercionTypeClass): ContentItemFilter;
}
export interface AsFilterItem extends Parse {
canBeFilterItem(cc: ConvertingContext): true;
asFilterItem(cc: ConvertingContext, filter: ContentItemFilter): void;
}
export interface AsPreprocessorVariableName extends Parse {
canBePreprocessorVariableName(cc: ConvertingContext): true;
asPreprocessorVariableName(cc: ConvertingContext): string;
}
export interface AsTimeOffsetParameter extends Parse {
canBeTimeOffsetParameter(cc: ConvertingContext): true;
asTimeOffsetParameter(cc: ConvertingContext): AdjustOffset;
}
export interface AsRaw extends Parse {
canBeRaw(cc: ConvertingContext): true;
asRaw(cc: ConvertingContext): RawParameter;
}
export interface AsImportQuestion extends Parse {
canBeImportQuestion(cc: ConvertingContext): true;
asImportQuestion(
cc: ConvertingContext,
parameterKey: string,
actionUUID: string
): string;
}
export const parseTypeList = [
"String",
"Boolean",
"Text",
"List",
"Array",
"AbleArray",
"Variable",
"Action",
"Dictionary",
"RawKeyedDictionary",
"RawDeepDictionary",
"NameType",
"StringVariable",
"Number",
"Filter",
"FilterItem",
"TimeOffsetParameter",
"Raw",
"ImportQuestion"
// not PreprocessorVariableName
];
export type AsAble = Parse;
export type NestedStringDictionaryItem =
| string
| number
| boolean
| undefined
| NestedStringDictionaryItemArray
| NestedStringDictionary;
export type NestedStringDictionary = {
[key: string]: NestedStringDictionaryItem;
};
export interface NestedStringDictionaryItemArray
extends Array<NestedStringDictionaryItem> {}
export function createRawDeepItem(
cc: ConvertingContext,
value: Parse
): NestedStringDictionaryItem {
if (value.canBeString(cc)) {
return value.asString(cc);
} else if (value.canBeRawDeepDictionary(cc)) {
return value.asRawDeepDictionary(cc);
} else if (value.canBeRawDeepArray(cc)) {
return value.asRawDeepArray(cc);
}
throw value.error(cc, "Must be string or raw deep dictionary");
}
export { ConvertVariableParse } from "./ParserData/ConvertVariableParse";
export { ErrorParse } from "./ParserData/ErrorParse";
export { FilterParse } from "./ParserData/FilterParse";
export { FilterItemParse } from "./ParserData/FilterItemParse";
export { ArglistParse } from "./ParserData/ArglistParse";
export { RawParse } from "./ParserData/RawParse";
export { DictionaryParse } from "./ParserData/DictionaryParse";
export { ListParse } from "./ParserData/ListParse";
export { BarlistParse } from "./ParserData/BarlistParse";
export { CharsParse } from "./ParserData/CharsParse";
export { IdentifierParse } from "./ParserData/IdentifierParse";
export { NumberParse } from "./ParserData/NumberParse";
export { VariableFlagParse } from "./ParserData/VariableFlagParse";
export { VariableParse } from "./ParserData/VariableParse";
export { ActionParse } from "./ParserData/ActionParse";
export class ActionsParse extends Parse
implements AsAction, AsVariable, AsText {
actions: Array<AsAble>;
constructor(start: Position, end: Position, actions: Array<AsAble>) {
super(start, end);
this.actions = actions;
}
canBeText(_cc: ConvertingContext): true {
return true;
}
asText(cc: ConvertingContext) {
const variable = this.asVariable(cc);
const text = new Text();
text.add(variable);
return text;
}
canBeVariable(_cc: ConvertingContext): true {
return true;
}
asVariable(cc: ConvertingContext) {
const action = this.asAction(cc);
if (!action) {
throw this.error(
cc,
"There are no actions to make a variable from."
);
}
return new MagicVariable(action);
}
canBeAction(_cc: ConvertingContext): true {
return true;
}
asAction(cc: ConvertingContext) {
let lastAction: Action | undefined;
this.actions.forEach(action => {
if (!action.canBeAction(cc)) {
action.warn(cc, "This value must be an action.");
return;
}
try {
lastAction = action.asAction(cc);
} catch (e) {
cc.warn(e);
return undefined;
}
});
return lastAction;
}
asShortcut(
arg0:
| {
[key: string]: (
cc: ConvertingContext,
...args: AsAble[]
) => void;
}
| ConvertingContext
| undefined,
options: { useWarnings: boolean }
) {
let cc: ConvertingContext;
if (arg0 instanceof ConvertingContext) {
cc = arg0;
} else {
cc = new ConvertingContext();
const converterActions = arg0;
if (converterActions) {
Object.keys(converterActions).forEach(key => {
cc.setParserAction(key, converterActions[key]);
});
}
}
cc.useWarnings = options.useWarnings;
this.asAction(cc);
if (cc.controlFlowStack.length !== 0) {
this.warn(
cc,
`There are ${cc.controlFlowStack.length} unended block actions. Check to make sure that every block (if/repeat/choose from menu) has an end.`
);
}
return cc.shortcut;
}
}
// Text::asString
// Text::build | the_stack |
module Cats {
var glob = require("glob");
/**
* This class represents the total IDE. Wehn CATS is started a single instance of this class
* will be created that takes care of rendering all the components and open a project
* if applicable.
*/
export class Ide extends qx.event.Emitter{
// List of different themes that are available
private themes:Array<Theme>;
theme:Theme;
private recentProjects:Array<string>;
rootDir: string;
projects: Project[] = [];
resultPane: Gui.TabView;
toolBar: Gui.ToolBar;
contextPane: Gui.TabView;
statusBar: Gui.StatusBar;
editorTabView: Gui.EditorTabView;
console: Gui.ConsoleLog;
processTable: Gui.ProcessTable;
todoList: Gui.ResultTable;
bookmarks:Gui.ResultTable;
problemResult:Gui.ResultTable;
menuBar:Gui.MenuBar;
propertyTable:Gui.PropertyTable;
outlineNavigator:Gui.OutlineNavigator;
fileNavigator:Gui.FileNavigator;
debug:boolean= false;
catsHomeDir: string;
config:IDEConfiguration;
private static STORE_KEY = "cats.config";
private lastEntry = <any>{};
icons:IconMap;
constructor() {
super();
this.catsHomeDir = process.cwd();
this.loadMessages();
this.config = this.loadPreferences();
this.recentProjects = Array.isArray(this.config.projects) ? this.config.projects : [];
this.icons = this.loadIconsMap();
this.themes = this.loadThemes();
window.onpopstate = (data) => {
if (data && data.state) this.goto(data.state);
}
this.loadShortCuts();
qx.theme.manager.Meta.getInstance().setTheme(cats.theme.Default);
this.setTheme(this.config.theme);
}
private loadShortCuts() {
try {
var fileName = OS.File.join(this.catsHomeDir, "resource/shortcuts.json");
var c = OS.File.readTextFile(fileName);
var shortCutSets:{} = JSON.parse(c);
var os = "linux";
if (Cats.OS.File.isWindows()) {
os = "win";
} else if (Cats.OS.File.isOSX()) {
os = "osx";
}
var shortCuts = shortCutSets[os];
for (var shortCut in shortCuts) {
var commandName = shortCuts[shortCut];
var cmd = new qx.ui.command.Command(shortCut);
cmd.addListener("execute", (function(commandName: string) {
Cats.Commands.commandRegistry.runCommand(commandName);
}).bind(null, commandName));
}
} catch (err) {
console.error("Error loading shortcuts" + err);
}
}
/**
* Load the icons map from the file.
*/
private loadIconsMap() {
return JSON.parse(OS.File.readTextFile("resource/icons.json"));
}
/**
* Load the themes from the file.
*/
private loadThemes() {
return JSON.parse(OS.File.readTextFile("resource/themes.json"));
}
setFont(size=14) {
var theme = cats.theme.Font;
theme.fonts.default.size = size;
var manager = qx.theme.manager.Font.getInstance();
// @TODO hack to make Qooxdoo aware there is a change
manager.setTheme(cats.theme.Font16);
// manager.setTheme(null);
manager.setTheme(theme);
this.emit("config");
}
setColors(colorTheme = cats.theme.ColorDark) {
var manager = qx.theme.manager.Color.getInstance();
qx.theme.manager.Color.getInstance().setTheme(colorTheme);
// document.body.style.color = "black";
document.body.style.color = colorTheme.colors.text;
/*
var colors = manager.getTheme()["colors"];
var jcolors = JSON.stringify(colors.__proto__,null,4);
IDE.console.log(jcolors);
var editor = new Gui.Editor.SourceEditor();
IDE.editorTabView.addEditor(editor,{row:0, column:0});
editor.setContent(jcolors);
editor.setMode("ace/mode/json");
IDE.console.log(jcolors);
for (var c in colors) {
var dyn = manager.isDynamic(c);
IDE.console.log(c + ":" + colors[c] + ":" + dyn);
}
*/
}
/**
* Load all the locale dependend messages from the message file.
*
* @param locale The locale you want to retrieve the messages for
*/
private loadMessages(locale="en") {
const fileName = "resource/locales/" + locale + "/messages.json";
const messages = JSON.parse(OS.File.readTextFile(fileName));
let map:IMap = {};
for (var key in messages) {
map[key] = messages[key].message;
}
qx.locale.Manager.getInstance().setLocale(locale);
qx.locale.Manager.getInstance().addTranslation(locale, map);
}
private goto(entry) {
const hash = entry.hash;
this.lastEntry = entry;
const page = <Gui.EditorPage>qx.core.ObjectRegistry.fromHashCode(hash);
if (page) IDE.editorTabView.navigateToPage(page, entry.pos);
}
/**
* Initialize the different modules within the IDE.
*
*/
init(rootDoc:qx.ui.container.Composite) {
Cats.Commands.init();
const layouter = new Gui.Layout(rootDoc);
rootDoc.setBackgroundColor("transparent");
layouter.layout(this);
this.menuBar = new Gui.MenuBar();
// @TODO fix for 1.4
this.initFileDropArea();
this.handleCloseWindow();
}
/**
* Add an entry to the history list
*/
addHistory(editor:Editor, pos?:any) {
const page = this.editorTabView.getPageForEditor(editor);
if ((this.lastEntry.hash === page.toHashCode()) && (this.lastEntry.pos === pos)) return;
var entry ={
hash: page.toHashCode(),
pos: pos
};
history.pushState(entry,page.getLabel());
}
getCurrentTheme() :Theme {
const themeName = this.config.theme || "default";
var theme = this.themes.find((theme) => {return theme.name == themeName});
if (theme) return theme;
return this.getDefaultTheme();
}
getThemes() {
return this.themes;
}
/**
* Attach the drag n' drop event listeners to the document
*
* @author LordZardeck <sean@blackfireweb.com>
*/
private initFileDropArea(): void {
// Listen onto file drop events
document.documentElement.addEventListener("drop", (ev) => this.acceptFileDrop(ev), false);
// Prevent the browser from redirecting to the file
document.documentElement.addEventListener("dragover", (event: DragEvent) => {
event.stopPropagation();
event.preventDefault();
event.dataTransfer.dropEffect = "copy"; // Explicitly show this is a copy.
}, false);
}
/**
* Process the file and open it inside a new ACE session
*
* @param event {DragEvent}
* @author LordZardeck <sean@blackfireweb.com>
*/
private acceptFileDrop(event: DragEvent): void {
event.stopPropagation();
event.preventDefault();
// Loop over each file dropped. More than one file
// can be added at a time
const files: FileList = event.dataTransfer.files;
for(var i = 0; i < files.length; i++) {
var path:string = (<any>files[i]).path;
FileEditor.OpenEditor(path);
}
}
/**
* Load the projects and files that were open last time before the
* IDE was closed.
*/
restorePreviousProjects() {
console.info("restoring previous project and sessions.");
if (this.config.projects && this.config.projects.length) {
const projectDir = this.config.projects[0];
this.setDirectory(projectDir);
if (this.config.sessions) {
console.info("Found previous sessions: ", this.config.sessions.length);
this.config.sessions.forEach((session) => {
try {
var editor = Editor.Restore(session.type, JSON.parse(session.state));
if (editor) IDE.editorTabView.addEditor(editor);
} catch (err) {
console.error("error " + err);
}
});
}
// this.project.refresh();
}
}
private getDefaultTheme() : Theme {
return {
"name" : "default",
"background" : "linear-gradient(to right, #666 , #888)",
"color" : "Color",
"ace" : "ace/theme/eclipse"
}
}
private findTheme(name:string) : Theme {
return this.themes.find((theme) => {return theme.name == name});
}
/**
* CLose the current project
*/
close() {
this.projects.forEach((project) => project.close());
this.fileNavigator.clear();
this.todoList.clear();
this.problemResult.clear();
this.console.clear();
this.projects=[];
}
/**
* Get a set of default preferences.
*/
private getDefaultPreferences() {
var defaultConfig:IDEConfiguration = {
version: "2.0",
theme: "default",
fontSize: 13,
editor : {
rightMargin: 100
},
locale: "en",
rememberOpenFiles: false,
sessions: [],
projects:[]
};
return defaultConfig;
}
/**
* Load the configuration for the IDE. If there is no configuration
* found or it is an old version, use the default one to use.
*/
private loadPreferences() {
var configStr = localStorage[Ide.STORE_KEY];
if (configStr) {
try {
var config:IDEConfiguration = JSON.parse(configStr);
if (config.version === "2.0") return config;
} catch (err) {
console.error("Error during parsing config " + err);
}
}
return this.getDefaultPreferences();
}
/**
* Set the theme for this IDE
*/
setTheme(name="default") {
var theme = this.findTheme(name);
if (! theme) {
IDE.console.error(`Theme with name ${name} not found.`);
theme = this.getDefaultTheme();
}
this.theme = theme;
const colorTheme = cats.theme[theme.color] || cats.theme.Color;
document.body.style.background = theme.background;
var manager = qx.theme.manager.Color.getInstance();
qx.theme.manager.Color.getInstance().setTheme(colorTheme);
document.body.style.color = colorTheme.colors.text
this.setFont(this.config.fontSize);
this.emit("config");
}
/**
* Update the configuration for IDE
*
*/
updatePreferences(config:IDEConfiguration) {
this.config = config;
this.setTheme(config.theme);
this.emit("config", config);
this.savePreferences();
}
/**
* Persist the current IDE configuration to a file
*/
savePreferences() {
try {
let config = this.config;
config.version = "2.0";
config.sessions = [];
config.projects = this.recentProjects;
this.editorTabView.getEditors().forEach((editor)=>{
var state = editor.getState();
if ((state !== null) && (editor.getType())) {
config.sessions.push({
state: JSON.stringify(state),
type: editor.getType()
});
}
});
var configStr = JSON.stringify(config);
localStorage[Ide.STORE_KEY] = configStr;
} catch (err) {
console.error(err);
}
}
/**
* For a given file get the first project it belongs to.
*/
getProject(fileName:string) {
for (var x=0;x<this.projects.length;x++) {
let project = this.projects[x];
if (project.hasScriptFile(fileName)) return project;
}
}
/**
* Find all possible TSConfig files from a certain base directory.
*/
private getTSConfigs(dir:string) {
var configs:string[] = glob.sync(dir + "/" + "**/tsconfig*.json");
if (configs.length === 0) {
this.console.log("No tsconfig file found, creating a default one");
let fileName = OS.File.PATH.join(dir,"tsconfig.json");
OS.File.writeTextFile(fileName,"{}");
configs = [fileName];
}
return configs;
}
refresh() {
this.setDirectory(this.rootDir, false);
}
/**
* Set the working directory. CATS will start scanning the directory and subdirectories for
* tsconfig files and for each one found create a TS Project. If none found it will create
* the default config file and use that one instead.
*
* @param directory the directory of the new project
* @param refreshFileNavigator should the fileNavigator also be refreshed.
*/
setDirectory(directory: string, refreshFileNavigator = true) {
this.projects = [];
this.rootDir = OS.File.PATH.resolve(this.catsHomeDir,directory);
var index = this.recentProjects.indexOf(directory);
if (index !== -1) {
this.recentProjects.splice(index,1);
}
this.recentProjects.push(directory);
var name = OS.File.PATH.basename(directory);
document.title = "CATS | " + name;
if (refreshFileNavigator) this.fileNavigator.setRootDir(directory);
var configs:string[] = this.getTSConfigs(directory);
configs.forEach((config) => {
let path = OS.File.PATH.resolve(config);
path = OS.File.switchToForwardSlashes(path);
let p = new Project(path);
this.projects.push(p);
});
}
private handleCloseWindow() {
// Catch the close of the windows in order to save any unsaved changes
var win = getNWWindow();
win.on("close", function() {
var doClose = () => {
IDE.savePreferences();
this.close(true);
};
try {
if (IDE.editorTabView.hasUnsavedChanges()) {
var dialog = new Gui.ConfirmDialog("There are unsaved changes!\nDo you really want to continue?");
dialog.onConfirm = doClose;
dialog.show();
} else {
doClose();
}
} catch (err) { } // lets ignore this
});
}
/**
* Quit the application. If there are unsaved changes ask the user if they really
* want to quit.
*/
quit() {
var GUI = getNWGui();
var doClose = () => {
this.savePreferences();
GUI.App.quit();
};
if (this.editorTabView.hasUnsavedChanges()) {
var dialog = new Gui.ConfirmDialog("There are unsaved files!\nDo you really want to quit?");
dialog.onConfirm = doClose;
dialog.show();
} else {
doClose();
}
}
}
} | the_stack |
import { MSGraphClient, MSGraphClientFactory } from '@microsoft/sp-http';
import Utilities from './Utilities';
import { IFolder } from '../model/IFolder';
import { IMail } from '../model/IMail';
import { IMailMetadata } from '../model/IMailMetadata';
export default class GraphController {
private client: MSGraphClient;
private metadataExtensionName = 'mmsharepoint.onmicrosoft.MailStorage';
private saveMetadata: boolean;
constructor (saveMetadata: boolean) {
this.saveMetadata = saveMetadata;
}
public init(graphFactory: MSGraphClientFactory): Promise<boolean> {
return graphFactory
.getClient()
.then((client: MSGraphClient) => {
this.client = client;
return true;
})
.catch((error) => {
return false;
});
}
public getClient() {
return this.client;
}
/**
* This function retrieves all 1st-level folders from user's OneDrive
*/
public getOneDriveFolder(): Promise<IFolder[]> {
return this.client
.api('me/drive/root/children')
.version('v1.0')
.filter('folder ne null')
.select('id, name, parentReference, webUrl')
.get()
.then((response): any => {
let folders: Array<IFolder> = new Array<IFolder>();
response.value.forEach((item) => {
folders.push({ id: item.id, name: item.name, driveID: item.parentReference.driveId, parentFolder: null, webUrl: item.webUrl });
});
return folders;
});
}
public getGroupRootFolders(group: IFolder): Promise<IFolder[]> {
return this.client
.api(`drives/${group.driveID}/root/children`)
.version('v1.0')
.filter('folder ne null')
.select('id, name, webUrl')
.get()
.then((response): any => {
let folders: Array<IFolder> = new Array<IFolder>();
response.value.forEach((item) => {
folders.push({ id: item.id, name: item.name, driveID: group.driveID, parentFolder: group, webUrl: item.webUrl});
});
return folders;
});
}
public getSubFolder(folder: IFolder): Promise<IFolder[]> {
return this.client
.api(`drives/${folder.driveID}/items/${folder.id}/children`)
.version('v1.0')
.filter('folder ne null')
.select('id, name, webUrl')
.get()
.then((response): any => {
let folders: Array<IFolder> = new Array<IFolder>();
response.value.forEach((item) => {
folders.push({ id: item.id, name: item.name, driveID: folder.driveID, parentFolder: folder, webUrl: item.webUrl});
});
return folders;
});
}
/**
* This function retrievs the user's membership groups from Graph
*/
public getJoinedGroups(): Promise<IFolder[]> {
return this.client
.api('me/memberOf')
.version('v1.0')
.select('id, displayName, webUrl')
.get()
.then((response): any => {
let folders: Array<IFolder> = new Array<IFolder>();
response.value.forEach((item) => {
// Show unified Groups but NO Teams
if (item['@odata.type'] === '#microsoft.graph.group') {
if(!item.resourceProvisioningOptions || item.resourceProvisioningOptions.indexOf('Team') === -1) {
folders.push({ id: item.id, name: item.displayName, driveID: item.id, parentFolder: null, webUrl: item.webUrl});
}
}
});
return folders;
});
}
/**
* This function retrievs the user's membership groups from Graph
*/
public getJoinedTeams(): Promise<IFolder[]> {
return this.client
.api('me/joinedTeams')
.version('v1.0')
.select('id, displayName, webUrl')
.get()
.then((response): any => {
let folders: Array<IFolder> = new Array<IFolder>();
response.value.forEach((item) => {
folders.push({ id: item.id, name: item.displayName, driveID: item.id, parentFolder: null, webUrl: item.webUrl});
});
return folders;
});
}
/**
* This function retrieves all Drives for a given Group
*/
public getGroupDrives(group: IFolder): Promise<IFolder[]> {
return this.client
.api(`groups/${group.id}/drives`)
.version('v1.0')
.select('id, name, webUrl')
.get()
.then((response): any => {
let folders: Array<IFolder> = new Array<IFolder>();
response.value.forEach((item) => {
folders.push({ id: item.id, name: item.name, driveID: item.id, parentFolder: group, webUrl: item.webUrl});
});
return folders;
});
}
public retrieveMimeMail = (driveID: string, folderID: string, mail: IMail, clientCallback: (msg: string)=>void): Promise<string> => {
return this.client
.api(`me/messages/${mail.id}/$value`)
.version('v1.0')
.responseType('TEXT')
.get()
.then((response): any => {
if (response.length < (4 * 1024 * 1024)) // If Mail size bigger 4MB use resumable upload
{
return this.saveNormalMail(driveID, folderID, response, Utilities.createMailFileName(mail.subject), clientCallback);
}
else {
return this.saveBigMail(driveID, folderID, response, Utilities.createMailFileName(mail.subject), clientCallback);
}
});
}
private saveNormalMail(driveID: string, folderID: string, mimeStream: string, fileName: string, clientCallback: (msg: string)=>void): Promise<string> {
const apiUrl = driveID !== folderID ? `drives/${driveID}/items/${folderID}:/${fileName}.eml:/content` : `drives/${driveID}/root:/${fileName}.eml:/content`;
return this.client
.api(apiUrl)
.put(mimeStream)
.then((response) => {
clientCallback('Success');
return 'Success';
})
.catch((error) => {
clientCallback('Error');
return null;
});
}
public async saveBigMail(driveID: string, folderID: string, mimeStream: string, fileName: string, clientCallback: (msg: string)=>void) {
const sessionOptions = {
"item": {
"@microsoft.graph.conflictBehavior": "rename"
}
};
const apiUrl = driveID !== folderID ? `drives/${driveID}/items/${folderID}:/${fileName}.eml:/createUploadSession` : `drives/${driveID}/root:/${fileName}.eml:/createUploadSession`;
return this.client
.api(apiUrl)
.post(JSON.stringify(sessionOptions))
.then(async (response):Promise<any> => {
try {
const resp = await this.uploadMailSlices(mimeStream, response.uploadUrl);
clientCallback('Success');
return 'Success';
}
catch(err) {
clientCallback('Error');
return null;
}
});
}
private async uploadMailSlices(mimeStream: string, uploadUrl: string) {
let minSize=0;
let maxSize=5*327680; // 5*320kb slices --> MUST be a multiple of 320 KiB (327,680 bytes)
while(mimeStream.length > minSize) {
const fileSlice = mimeStream.slice(minSize, maxSize);
const resp = await this.uploadMailSlice(uploadUrl, minSize, maxSize, mimeStream.length, fileSlice);
minSize = maxSize;
maxSize += 5*327680;
if (maxSize > mimeStream.length) {
maxSize = mimeStream.length;
}
if (resp.id !== undefined) {
return resp;
}
else {
}
}
}
private async uploadMailSlice(uploadUrl: string, minSize: number, maxSize: number, totalSize: number, fileSlice: string) {
const header = {
"Content-Length": `${maxSize - minSize}`,
"Content-Range": `bytes ${minSize}-${maxSize-1}/${totalSize}`,
};
return await this.client
.api(uploadUrl)
.headers(header)
.put(fileSlice);
}
public saveMailMetadata(mailId: string, displayName: string, url: string, savedDate: Date) {
if (this.saveMetadata) {
const apiUrl = `/me/messages/${mailId}/extensions`;
const metadataBody = {
"@odata.type" : "microsoft.graph.openTypeExtension",
"extensionName" : this.metadataExtensionName,
"saveDisplayName" : displayName,
"saveUrl" : url,
"savedDate" : savedDate.toISOString()
};
this.client
.api(apiUrl)
.version('v1.0')
.post(JSON.stringify(metadataBody))
.then((response) => {
console.log(response);
});
}
}
public retrieveMailMetadata(mailId: string): Promise<any> {
const apiUrl = `/me/messages/${mailId}`;
const expand = `Extensions($filter=id eq 'Microsoft.OutlookServices.OpenTypeExtension.${this.metadataExtensionName}')`;
return this.client
.api(apiUrl)
.version('v1.0')
.expand(expand)
.select('id,subject,extensions')
.get()
.then((response) => {
if (typeof response.extensions !== 'undefined' && response.extensions !== null) {
const metadata: IMailMetadata = {
extensionName: response.extensions[0].extensionName,
saveDisplayName: response.extensions[0].saveDisplayName,
saveUrl: response.extensions[0].saveUrl,
savedDate: new Date(response.extensions[0].savedDate)
};
return metadata;
}
else {
return null;
}
},
(error) => {
console.log(error);
return null;
});
}
} | the_stack |
import { AutorestNormalizedConfiguration } from "../autorest-normalized-configuration";
import { ConfigurationSchemaProcessor } from "./processor";
import { RawConfiguration } from "./types";
export const AUTOREST_CONFIGURATION_CATEGORIES = {
logging: {
name: "Logging",
},
installation: {
name: "Manage installation",
},
core: {
name: "Core Settings",
},
feature: {
name: "Feature flags",
},
extensions: {
name: "Generators and extensions",
description:
"> While AutoRest can be extended arbitrarily by 3rd parties (say, with a custom generator),\n> we officially support and maintain the following functionality.\n> More specific help is shown when combining the following switches with `--help` .",
},
};
export const SUPPORTED_EXTENSIONS_SCHEMA = {
csharp: {
type: "boolean",
category: "extensions",
description: "Generate C# client code",
},
go: {
type: "boolean",
category: "extensions",
description: "Generate Go client code",
},
java: {
type: "boolean",
category: "extensions",
description: "Generate Java client code",
},
python: {
type: "boolean",
category: "extensions",
description: "Generate Python client code",
},
az: {
type: "boolean",
category: "extensions",
description: "Generate Az cli code",
},
typescript: {
type: "boolean",
category: "extensions",
description: "Generate TypeScript client code",
},
azureresourceschema: {
type: "boolean",
category: "extensions",
description: "Generate Azurer resource schemas",
},
"model-validator": {
type: "boolean",
category: "extensions",
description:
"Validates an OpenAPI document against linked examples (see https://github.com/Azure/azure-rest-api-specs/search?q=x-ms-examples ",
},
"azure-validator": {
type: "boolean",
category: "extensions",
description:
"Validates an OpenAPI document against guidelines to improve quality (and optionally Azure guidelines)",
},
} as const;
// Switch next 2 lines to have autocomplete when writting configuration. Make sure to revert otherwise it lose the detailed typing for each option.
// export const AUTOREST_CONFIGURATION_SCHEMA : RootConfigurationSchema<keyof typeof AUTOREST_CONFIGURATION_CATEGORIES> = {
export const AUTOREST_CONFIGURATION_SCHEMA = {
/**
* Verbosity category
*/
verbose: { type: "boolean", category: "logging", description: "Display verbose logging information" },
debug: { type: "boolean", category: "logging", description: "Display debug logging information" },
level: {
type: "string",
category: "logging",
enum: ["debug", "verbose", "information", "warning", "error", "fatal"],
description: "Set logging level",
},
"message-format": {
type: "string",
category: "logging",
description: "Format of logging messages",
enum: ["json", "regular"],
},
/**
* Manage installation category
*/
info: {
type: "boolean",
category: "installation",
description: "Display information about the installed version of autorest and its extensions",
},
"list-available": {
type: "boolean",
category: "installation",
description: "Display available AutoRest versions",
},
reset: {
type: "boolean",
category: "installation",
description: "Removes all autorest extensions and downloads the latest version of the autorest-core extension",
},
preview: {
type: "boolean",
category: "installation",
description: "Enables using autorest extensions that are not yet released",
},
latest: {
type: "boolean",
category: "installation",
description: "Install the latest autorest-core extension",
},
force: {
type: "boolean",
category: "installation",
description: "Force the re-installation of the autorest-core extension and frameworks",
},
version: {
type: "string",
category: "installation",
description: "Use the specified version of the autorest-core extension",
},
use: {
type: "array",
category: "installation",
items: { type: "string" },
description:
"Specify an extension to load and use. Format: --use=<packagename>[@<version>] (e.g. --use=@autorest/modelerfour@~4.19.0)",
},
"use-extension": {
type: "dictionary",
category: "installation",
description: `Specify extension to load and use. Format: {"<packageName>": "<version>"}`,
items: { type: "string" },
},
/**
* Core settings
*/
help: {
type: "boolean",
category: "core",
description: "Display help (combine with flags like --csharp to get further details about specific functionality)",
},
memory: { type: "string", category: "core", description: "Configure max memory allowed for autorest process(s)" },
"input-file": {
type: "array",
category: "core",
description: "OpenAPI file to use as input (use this setting repeatedly to pass multiple files at once)",
items: { type: "string" },
},
"output-folder": {
type: "string",
category: "core",
description: `Target folder for generated artifacts; default: "<base folder>/generated"`,
},
"github-auth-token": {
type: "string",
category: "core",
description: "OAuth token to use when pointing AutoRest at files living in a private GitHub repository",
},
"azure-arm": {
type: "boolean",
category: "core",
description: "Generate code in Azure flavor",
},
"header-text": {
type: "string",
category: "core",
description:
"Text to include as a header comment in generated files (magic strings:MICROSOFTMIT, MICROSOFT_APACHE, MICROSOFT_MIT_NO_VERSION, MICROSOFT_APACHE_NO_VERSION, MICROSOFT_MIT_NOCODEGEN)",
},
"openapi-type": {
type: "string",
category: "core",
description: `Open API Type: "arm" or "data-plane"`,
},
"output-converted-oai3": {
type: "boolean",
category: "core",
description: `If enabled and the input-files are swager 2.0 this will output the resulting OpenAPI3.0 converted files to the output-folder`,
},
eol: {
type: "string",
category: "core",
enum: ["default", "lf", "crlf"],
description: "Change the end of line character for generated output.",
},
title: {
type: "string",
category: "core",
description: "Override the service client's name listed in the swagger under title.",
},
"override-client-name": {
type: "string",
category: "core",
description:
"Name to use for the generated client type. By default, uses the value of the 'Title' field from the input files",
},
directive: {
type: "array",
category: "core",
items: {
type: "object",
properties: {
from: { type: "array", items: { type: "string" } },
// directive is also used in the powershell extension (where and set in particular are object there) https://github.com/Azure/autorest.powershell/blob/main/docs/directives.md
// where: { type: "array", items: { type: "string" } },
reason: { type: "array", items: { type: "string" } },
suppress: { type: "array", deprecated: true, items: { type: "string" } },
// set: { type: "array", items: { type: "string" } },
transform: { type: "array", items: { type: "string" } },
"text-transform": { type: "array", items: { type: "string" } },
test: { type: "array", items: { type: "string" } },
debug: {
type: "boolean",
description:
"Debug this directive. When set to true autorest will log additional information regarding that directive.",
},
},
},
},
require: {
type: "array",
category: "core",
description: "Additional configuration file(s) to include.",
items: { type: "string" },
},
"try-require": {
type: "array",
category: "core",
description:
"Additional configuration file(s) to try to include. Will not fail if the configuration file doesn't exist.",
items: { type: "string", description: "Additional configuration files to include." },
},
"declare-directive": {
type: "dictionary",
category: "core",
description:
"Declare some reusable directives (https://github.com/Azure/autorest/blob/main/packages/libs/configuration/resources/directives.md#how-it-works)",
items: { type: "string" },
},
"output-artifact": {
type: "array",
category: "core",
description: "Additional artifact type to emit to the output-folder",
items: { type: "string" },
},
"allow-no-input": { type: "boolean" },
"exclude-file": { type: "array", items: { type: "string" } },
"base-folder": { type: "string" },
stats: { type: "boolean", category: "core", description: "Output some statistics about current autorest run." },
profile: {
type: "array",
category: "core",
description: "Reservered for future use.",
items: { type: "string" },
},
suppressions: {
type: "array",
category: "core",
description: "List of warning/error code to ignore.",
items: {
type: "object",
properties: {
code: { type: "string" },
from: { type: "array", items: { type: "string" } },
where: { type: "array", items: { type: "string" } },
reason: { type: "string" },
},
},
},
"output-file": { type: "string" },
/**
* Feature flags
*/
"deduplicate-inline-models": { type: "boolean", category: "feature", description: "Deduplicate inline models" },
"include-x-ms-examples-original-file": {
type: "boolean",
category: "feature",
description: "Include x-ms-original-file property in x-ms-examples",
},
/**
* Ignore.
*/
"pass-thru": {
type: "array",
items: { type: "string" },
},
} as const;
export type AutorestRawConfiguration = RawConfiguration<typeof AUTOREST_CONFIGURATION_SCHEMA> & {
[key: string]: any;
};
export const AUTOREST_CONFIGURATION_DEFINITION = {
categories: AUTOREST_CONFIGURATION_CATEGORIES,
schema: AUTOREST_CONFIGURATION_SCHEMA,
};
export const AUTOREST_CONFIGURATION_DEFINITION_FOR_HELP = {
categories: AUTOREST_CONFIGURATION_CATEGORIES,
// SUPPORTED_EXTENSIONS_SCHEMA can either be a flag to enable or a scope which cause issue with the validation.
schema: { ...AUTOREST_CONFIGURATION_SCHEMA, ...SUPPORTED_EXTENSIONS_SCHEMA },
};
export const autorestConfigurationProcessor = new ConfigurationSchemaProcessor(AUTOREST_CONFIGURATION_DEFINITION);
export const AUTOREST_INITIAL_CONFIG: AutorestNormalizedConfiguration =
autorestConfigurationProcessor.getInitialConfig(); | the_stack |
import { Pos, NoPos, SrcFile, Position } from "../../pos"
import { token } from "../../token"
import { ByteStr } from "../../bytestr"
import { Int64 } from "../../int64"
import { Num } from "../../num"
import { numconv } from "../../numconv"
import { StrWriter } from "../../util"
import { Scope, Ent, nilScope } from "../scope"
import { NodeVisitor } from "../visit"
import { ReprVisitor, ReprOptions } from "../repr"
// --------------------------------------------------------------------------------
export interface TypedNode {
type :Type
}
class Node {
_scope? :Scope = undefined
pos :Pos
toString() :string { return this.constructor.name }
// repr returns a human-readable and machine-parsable string representation
// of the tree represented by this node.
// If a custom writer is provided via options.w, the empty string is returned.
repr(options? :ReprOptions) :string {
let v = new ReprVisitor(options)
v.visitNode(this)
return v.toString()
}
isUnresolved() :this is UnresolvedType|TypedNode {
// isUnresolved returns true for any node that references something which is
// not yet resolved. TODO: consider adding node UnresolvedIdent
return (
this.isUnresolvedType() ||
(!this.isType() && (this as any).type instanceof UnresolvedType)
)
}
// Auto-generated methods:
// isTYPE() :this is TYPE
isType() :this is Type {
return (
this instanceof Type &&
(
this instanceof Template ? this.base.isType() :
this instanceof TemplateInvocation ? this.template.isType() :
true
)
)
}
// convertToNodeInPlace is a destructive action which transforms the receiver
// to become a copy of otherNode.
convertToNodeInPlace<T extends Node>(otherNode :T) :T {
let dst = this as any
let src = otherNode as any
dst.__proto__ = src.__proto__
for (let k in dst) {
delete dst[k]
}
for (let k in src) {
dst[k] = src[k]
}
return dst as T
}
}
class Package extends Node {
pos = NoPos
name :string
_scope :Scope
files :File[] = []
toString() :string { return `(Package ${JSON.stringify(this.name)})` }
}
class File extends Node {
pos = NoPos
sfile :SrcFile
_scope :Scope
imports :ImportDecl[] // imports in this file
decls :(Decl|FunExpr)[] // top-level declarations
unresolved? :Set<Ident> // unresolved references
endPos :Position|null // when non-null, the position of #end "data tail"
endMeta :Expr[] // Any metadata as part of #end
toString() :string { return `(File ${JSON.stringify(this.sfile.name)})` }
}
class Comment extends Node {
value :Uint8Array
}
class Bad extends Node {
message :string
// Bad is a placeholder for something that failed to parse correctly
// and where we can't provide a better node.
}
class FunSig extends Node {
// TODO: consider merging with FunType
params :FieldDecl[]
result? :Type // null = auto
}
class Stmt extends Node {
_scope :Scope
}
class Expr extends Stmt {
type? :Type = null // effective type of expression. null until resolved.
}
// -----------------------------------------------------------------------------
// Types
class Type extends Expr {
_scope = nilScope
// Note: "type" property on a type has a different meaning than for other
// node classes. "type" is used to describe a subtype in some classes,
// like for instance OptionalType.
// accepts returns true if the other type is compatible with this type.
// essentially: "this >= other"
// For instance, if the receiver is the same as `other`
// or a superset of `other`, true is returned.
accepts(other :Type) :bool { return this.equals(other) }
// equals returns true if the receiver is equivalent to `other`
equals(other :Type) :bool { return this === other }
// canonicalType returns the underlying canonical type for
// classes that wraps a type, like AliasType.
canonicalType() :Type { return this }
}
class VoidType extends Type {
// Equivalent to a strict type of "nil"; function with no return value.
}
export const t_void = new VoidType(NoPos)
class UnresolvedType extends Type {
// UnresolvedType represents a type that is not yet known, but may be
// known later (i.e. during bind/resolve.)
//
// Whenever something refers to this type, you must call addRef(x) where
// x is the thing that uses/refers to this type. This makes it possible
// for the TypeResolver to--when resolving this type--go in and edit all
// the uses of this type, updating them with a concrete, resolved type.
refs? :Set<Node> = null // things that references this type
def :Expr
addRef(x :Node) {
assert(x !== this.def, 'addRef called with own definition')
if (!this.refs) {
this.refs = new Set<Node>([x])
} else {
this.refs.add(x)
}
}
repr(options? :ReprOptions) {
return '~' + this.def.repr(options)
}
}
class OptionalType extends Type { // aka "nullable" type
// OptionalType = Type "?"
type :Type
equals(t :Type) :bool {
return this === t || (t.isOptionalType() && this.type.equals(t.type))
}
accepts(t :Type) :bool {
return (
this.equals(t) || // e.g. "x T?; y T?; x = y"
this.type.accepts(t) || // e.g. "x T?; y T; x = y"
t === t_nil // e.g. "x T?; x = nil"
)
}
toString() :string { return `${this.type}?` }
}
// Storage denotes the storage type needed for a primitive type
export enum Storage {
None = 0, // zero-width; not a concrete type
Ptr, // Target-defined pointer (at least 32 bit)
Int, // Target-defined integer (at least 32 bit)
Bool, // Target-defined boolean
i8, // 8-bit integer
i16, // 16-bit integer
i32, // 32-bit integer
i64, // 64-bit integer
f32, // 32-bit floating-point
f64, // 64-bit floating-point
}
const StorageSize = {
[Storage.None] : 0,
[Storage.Ptr] : 4, // Note: target arch may use different size
[Storage.Int] : 4, // Note: target arch may use different size
[Storage.Bool] : 4, // Note: target arch may use different size
[Storage.i8] : 1,
[Storage.i16] : 2,
[Storage.i32] : 4,
[Storage.i64] : 8,
[Storage.f32] : 4,
[Storage.f64] : 8,
}
class PrimType extends Type { // was "BasicType"
// primitive type, e.g. i32, f64, bool, etc.
pos = NoPos
name :string
storage :Storage // type of underlying storage
_storageSize = StorageSize[this.storage] // size in bytes
// storageSize returns the underlying storage size in bytes
storageSize() :int { return this._storageSize }
// simplified type te
isType() :this is Type { return true }
// convenience function used by arch rewrite rules
isI8() :bool { return this.storage == Storage.i8 }
isI16() :bool { return this.storage == Storage.i16 }
isI32() :bool { return this.storage == Storage.i32 }
isI64() :bool { return this.storage == Storage.i64 }
isF32() :bool { return this.storage == Storage.f32 }
isF64() :bool { return this.storage == Storage.f64 }
isBool() :bool { return this.storage == Storage.Bool }
isPtr() :bool { return this.storage == Storage.Ptr }
isNil() :bool { return this.storage == Storage.None }
toString() :string { return this.name }
repr(options? :ReprOptions) :string { return this.name }
}
class NilType extends PrimType {}
class BoolType extends PrimType {}
class NumType extends PrimType {} // all number types
class FloatType extends NumType {}
class IntType extends NumType {}
class SIntType extends IntType {}
class UIntType extends IntType {}
class MemType extends UIntType {} // used by SSA IR to represent memory state
// predefined constant of all primitive types.
// string names should match exported constant name sans "t_".
export const t_nil = new NilType("nil", Storage.None)
export const t_bool = new BoolType("bool", Storage.Bool)
export const t_rune = new UIntType("rune", Storage.i32)
export const t_byte = new UIntType("byte", Storage.i8)
export const t_u8 = new UIntType("u8", Storage.i8)
export const t_i8 = new SIntType("i8", Storage.i8)
export const t_u16 = new UIntType("u16", Storage.i16)
export const t_i16 = new SIntType("i16", Storage.i16)
export const t_u32 = new UIntType("u32", Storage.i32)
export const t_i32 = new SIntType("i32", Storage.i32)
export const t_u64 = new UIntType("u64", Storage.i64)
export const t_i64 = new SIntType("i64", Storage.i64)
export const t_uint = new UIntType("uint", Storage.Int)
export const t_int = new SIntType("int", Storage.Int)
export const t_uintptr = new UIntType("uintptr", Storage.Ptr)
export const t_mem = new MemType("mem", Storage.Ptr)
export const t_f32 = new FloatType("f32", Storage.f32)
export const t_f64 = new FloatType("f64", Storage.f64)
class StrType extends Type {
// StrType = "str" ("<" length ">")?
len :int // -1 means length only known at runtime
toString() :string { return this.len == -1 ? "str" : `str<${this.len}>` }
equals(t :Type) :bool { return this === t || t.isStrType() }
repr(options? :ReprOptions) :string { return this.toString() }
}
class UnionType extends Type {
// UnionType = Type ("|" Type)+
types :Set<Type>
add(t :Type) {
assert(!(t instanceof UnionType), 'adding union type to union type')
this.types.add(t)
}
toString() :string {
let s = '(', first = true
for (let t of this.types) {
if (first) {
first = false
} else {
s += '|'
}
s += t.toString()
}
return s + ')'
}
equals(other :Type) :bool {
if (this === other) {
return true
}
if (!(other instanceof UnionType) || other.types.size != this.types.size) {
return false
}
// Note: This relies on type instances being singletons (being interned)
for (let t of this.types) {
if (!other.types.has(t)) {
return false
}
}
return true
}
accepts(other :Type) :bool {
if (this === other) {
return true
}
if (!(other instanceof UnionType)) {
// e.g. (int|i32|i64) accepts i32
return this.types.has(other)
}
// Note: This relies on type instances being singletons (being interned)
// make sure that we have at least the types of `other`.
// e.g.
// (int|f32|bool) accepts (int|f32) => true
// (int|f32) accepts (int|f32|bool) => false
for (let t of other.types) {
if (!this.types.has(t)) {
return false
}
}
return true
}
}
class AliasType extends Type {
// AliasType = "type" Ident Type
// AliasType is an alternate name for a type.
name :ByteStr // alias name
type :Type // type this is an alias of
equals(other :Type) :bool {
return this === other || (other.isAliasType() && this.type.equals(other.type))
}
canonicalType() :Type {
let t :Type = this.type
while (t instanceof AliasType) {
t = t.type
}
return t
}
toString() :string { return `(AliasType ${this.type})` }
}
class TupleType extends Type {
// TupleType = "(" Type ("," Type)+ ")"
pos = NoPos
types :Type[]
}
class ListType extends Type {
// ListType = Type "[]"
pos = NoPos
type :Type // element type
equals(t :Type) :bool {
return this === t || (t instanceof ListType && this.type.equals(t.type))
}
accepts(t :Type) :bool {
// Note: This way, ListType <= RestType, e.g.
// fun foo(x ...int) { y int[] = x }
return t instanceof ListType && this.type.equals(t.type)
}
}
class RestType extends ListType {
// RestType = "..." Type
// Specialized generic type instance.
// Rest is really a list, but represented as a subclass
toString() :string { return `...${super.toString()}` }
equals(t :Type) :bool {
return this === t || (t instanceof RestType && this.type.equals(t.type))
}
}
class StructType extends Type {
// StructType = "{" (Decl ";")* "}"
_scope :Scope
name :Ident|null
decls :Decl[]
toString() :string {
return this.name ? this.name.toString() : "{anon}"
}
// equals(t :Type) :bool {
// if (this === t) {
// return true
// }
// if (t instanceof StructType) {
// if (
// this.decls.length != t.decls.length ||
// ( this.name !== t.name &&
// (!this.name || !t.name || this.name.value !== t.name.value)
// )
// ) {
// return false
// }
// for (let i = 0; i < this.decls.length; i++) {
// let a = this.decls[i]
// let b = t.decls[i]
// if (a !== b) {
// if (a.isType() && b.isType()) {
// if (!a.equals(b)) {
// return false
// }
// } else {
// return false
// }
// }
// }
// return true
// }
// return false
// }
}
class FunType extends Type {
// FunType = ( Type | TupleType ) "->" Type
args :Type[]
result :Type
equals(t :Type) :bool {
return (
this === t ||
( t.isFunType() &&
this.args.length == t.args.length &&
this.result.equals(t.result) &&
this.args.every((at, i) => at.equals(t.args[i]))
)
)
}
}
// -----------------------------------------------------------------------------
// Template
class Template<T extends Node=Node> extends Type {
// Note on extends Type:
// Template can be both a value and a type.
// Node.isType has been specialized to check template's base.
// This means that:
// let n1 = new Template<Expr>(someExpr)
// let n2 = new Template<Type>(someType)
// n1.isType() // == false
// n2.isType() // == true
//
_scope :Scope
vars :TemplateVar[] // never empty. position and name are both important
base :T | TemplateInvocation<T> // node this template can instantiate
// bottomBase returns the bottom-most base
bottomBase() :Node {
return this.base instanceof Template ? this.base.bottomBase() : this.base
}
// aliases returns a possibly-empty list of Templates which this template
// uses as its base.
//
// Example:
// type A<T> {x T}
// type B<X> A<X>
// type C<Y> B<Y>
//
// Template(A).aliases() => [] // none
// Template(B).aliases() => [ Template(A) ]
// Template(C).aliases() => [ Template(B), Template(A) ]
//
aliases() :Template[] {
let a :Template[] = []
let bn :Node = this.base
while (true) {
if (bn instanceof TemplateInvocation) {
bn = bn.template
} else if (bn instanceof Template) {
a.push(bn)
bn = bn.base
} else {
break
}
}
return a
}
toString() :string {
return (
this.bottomBase() +
"<" + this.vars.map(v => v.name).join(",") + ">"
)
}
}
class TemplateInvocation<T extends Node=Node> extends Type {
// Note on extends Type: See note in Template class definition.
_scope :Scope
name :Ident|null // e.g "Foo2" from "Foo2<X> Foo<X>"
args :Node[]
template :Template<T>
toString() :string {
return (
(this.name ? this.name.toString() : this.template.bottomBase().toString()) +
"<" + this.args.join(",") + ">"
)
}
}
class TemplateVar<T extends Node=Node> extends Type {
// TemplateVar = Ident Constraint? ("=" Default)?
// Constraint = Node
// Default = Expr
_scope :Scope
name :Ident
constraint? :Node // e.g. "T is ConstraintType"
def? :T // e.g. "T = int"
equals(t :TemplateVar) :bool { return this === t }
toString() :string { return `(TemplateVar ${this.name})` }
}
// -----------------------------------------------------------------------------
// Flow control
class ReturnStmt extends Stmt {
result :Expr // t_nil means no explicit return values
type :Type|null // effective type. null until resolved.
}
class ForStmt extends Stmt {
// "for" init ; cond ; incr { body }
init :Stmt|null // initializer
cond :Expr|null // condition for executing the body. null=unconditional
incr :Stmt|null // incrementor
body :Expr
}
class WhileStmt extends ForStmt {
// "while" cond { body }
init = null
incr = null
}
class BranchStmt extends Stmt {
// BranchStmt = ("break" | "continue") label?
tok :token // BREAK | CONTINUE
label :Ident|null = null
}
// end of flow control
// -----------------------------------------------------------------------------
// Declarations
class Decl extends Stmt {}
class ImportDecl extends Decl {
path :StringLit
localIdent :Ident|null
}
class MultiDecl extends Decl {
// MultiDecl represents a collection of declarations that were parsed from
// a multi-declaration site. E.g. "type (a int; b f32)"
decls :Decl[]
}
class VarDecl extends Decl {
// VarDecl = Idents (Type | Type? "=" Values)
group :Object|null // null means not part of a group
idents :Ident[]
type :Type|null // null means no type
values :Expr[]|null // null means no values
}
class TypeDecl extends Decl {
// TypeDecl = "type" Ident Type
ident :Ident
type :Type
group :Object|null // nil = not part of a group
}
class FieldDecl extends Decl {
// FieldDecl = (VarDecl | EmbeddedField | MethodDecl)
type :Type
name? :Ident // null means anonymous field/parameter
}
// -----------------------------------------------------------------------------
// Expressions
class Ident extends Expr {
ent? :Ent = null // what this name references
value :ByteStr // interned value
incrWrite() {
assert(this.ent != null)
this.ent!.writes++
}
// ref registers a reference to this ent from an identifier
refEnt(ent :Ent) {
assert(this !== ent.value, "ref declaration")
ent.nreads++
this.ent = ent
}
// ref unregisters a reference to this ent from an identifier
unrefEnt() {
assert(this.ent, "null ent")
this.ent!.nreads--
this.ent = null
}
toString() :string { return this.value.toString() }
}
class Block extends Expr {
list :Stmt[]
}
class IfExpr extends Expr {
cond :Expr
then :Expr
els_ :Expr|null
}
class CollectionExpr extends Expr {
entries :Expr[]
}
class TupleExpr extends CollectionExpr {
// TupleExpr = "(" Expr ("," Expr)+ ")"
// e.g. (1, true, "three")
type? :TupleType = null
}
class ListExpr extends CollectionExpr {
// ListExpr = "[" ExprList [("," | ";")] "]"
// e.g. [1, 2, x]
type? :ListType
}
class SelectorExpr extends Expr {
// Selector = Expr "." ( Ident | Selector )
lhs :Expr
rhs :Expr // Ident or SelectorExpr
}
class IndexExpr extends Expr {
// IndexExpr = Expr "[" Expr "]"
// e.g. foo[1]
operand :Expr
index :Expr
indexnum :Num = -1 // used by resolver. >=0 : resolved, -1 : invalid or unresolved
}
class SliceExpr extends Expr {
// SliceExpr = Expr "[" Expr? ":" Expr? "]"
// e.g. foo[1:4]
type? :ListType|TupleType = null
operand :Expr
start :Expr|null
end :Expr|null
startnum :Num = -1 // used by resolver. >=0 : resolved, -1 : invalid or unresolved
endnum :Num = -1 // used by resolver. >=0 : resolved, -1 : invalid or unresolved
}
class LiteralExpr extends Expr {
_scope = nilScope
value :Int64|number|Uint8Array
}
class NumLit extends LiteralExpr {
value :Int64 | number
type :NumType
// convertToType coverts the value of the literal to the provided basic type.
// Returns null if the conversion would be lossy.
//
convertToType(t :NumType) :NumLit|null {
if (t === this.type) {
return this
}
let [v, lossless] = numconv(this.value, t)
if (lossless) {
if (t instanceof FloatType) {
return new FloatLit(this.pos, v as number, t)
}
if (t instanceof IntType) {
return new IntLit(this.pos, v, t, token.INT)
}
throw new Error(`unexpected NumType ${t.constructor}`)
}
return null
}
toString() :string { return this.value.toString() }
}
class IntLit extends NumLit {
format :token.INT | token.INT_BIN | token.INT_OCT | token.INT_HEX
type :IntType // type is always known
base() :int {
switch (this.format) {
case token.INT_HEX: return 16
case token.INT_OCT: return 8
case token.INT_BIN: return 2
default: return 10
}
}
convertToType(t :NumType) :NumLit|null {
// specialization of NumLit.convertToType that carries over format
let n = super.convertToType(t)
if (n && n !== this && n instanceof IntLit) {
n.format = this.format
}
return n
}
toString() :string {
switch (this.format) {
case token.INT_HEX: return '0x' + this.value.toString(16)
case token.INT_OCT: return '0o' + this.value.toString(8)
case token.INT_BIN: return '0b' + this.value.toString(2)
default: return this.value.toString(10)
}
}
visit(v: NodeVisitor) {
v.visitFieldN("type", this.type)
v.visitField("value", this.value)
v.visitFieldE("format", this.format, token)
}
}
const zeros = "00000000"
class RuneLit extends NumLit {
type = t_rune
value :int // codepoint
// 'a', '\n', '\x00', '\u0000', '\U00000000'
toString() :string {
let c = this.value
switch (c) {
// see scanner/scanEscape
case 0x00: return "'\\0'"
case 0x07: return "'\\a'"
case 0x08: return "'\\b'"
case 0x09: return "'\\t'"
case 0x0A: return "'\\n'"
case 0x0B: return "'\\v'"
case 0x0C: return "'\\f'"
case 0x0D: return "'\\r'"
case 0x27: return "'\\''"
case 0x5C: return "'\\\\'"
}
if (c >= 0x20 && c <= 0x7E) { // visible printable ASCII
return `'${String.fromCharCode(c)}'`
}
let s = c.toString(16).toUpperCase(), z = s.length
return (
z > 4 ? ("'\\U" + (z < 8 ? zeros.substr(0, 8-z) : ""))
: z > 2 ? ("'\\u" + (z < 4 ? zeros.substr(0, 4-z) : ""))
: ("'\\x" + (z < 4 ? zeros.substr(0, 2-z) : ""))
) + s + "'"
}
}
class FloatLit extends NumLit {
value :number
type :FloatType
}
class StringLit extends LiteralExpr {
value :Uint8Array
type :StrType
}
class Assignment extends Expr {
// e.g. "x = y", "x++"
op :token // ILLEGAL means no operation
lhs :Expr[]
rhs :Expr[] // empty == lhs++ or lhs--
decls :bool[] // index => bool: new declaration?
}
class Operation extends Expr {
// e.g. "x + y"
op :token // [token.operator_beg .. token.operator_end]
x :Expr // left-hand side
y :Expr|null // right-hand size. nil means unary expression
}
class CallExpr extends Expr {
// Fun(ArgList[0], ArgList[1], ...)
receiver :Expr
args :Expr[]
hasRest :bool // last argument is followed by ...
}
class FunExpr extends Expr {
sig :FunSig
name? :Ident // null = anonymous func expression
isInit :bool // true for special "init" funs at file level
type? :FunType = null
body? :Expr = null // null = forward declaration
}
class TypeConvExpr extends Expr {
// converts expr to type
expr :Expr
type :Type
}
class Atom extends Expr {
// Atom = "nil" | "true" | "false"
// A value that identifies itself.
pos = NoPos
_scope = nilScope
name :string
type :BoolType|NilType
} | the_stack |
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { ActivatedRoute, NavigationEnd, NavigationStart, Router } from '@angular/router';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { BehaviorSubject } from 'rxjs/Rx';
import { IdentityCardService } from '../services/identity-card.service';
import { ClientService } from '../services/client.service';
import { AdminService } from '../services/admin.service';
import { InitializationService } from '../services/initialization.service';
import { AlertService } from '../basic-modals/alert.service';
import { ConfigService } from '../services/config.service';
import { Config } from '../services/config/configStructure.service';
import { SampleBusinessNetworkService } from '../services/samplebusinessnetwork.service';
import { BusinessNetworkDefinition, IdCard } from 'composer-common';
import { DrawerDismissReasons, DrawerService } from '../common/drawer';
import { LoginComponent } from './login.component';
import * as fileSaver from 'file-saver';
import * as chai from 'chai';
import * as sinon from 'sinon';
let should = chai.should();
class RouterStub {
// Route.events is Observable
private subject = new BehaviorSubject(this.eventParams);
public events = this.subject.asObservable();
// Event parameters
private _eventParams;
get eventParams() {
return this._eventParams;
}
set eventParams(event) {
let nav;
if (event.nav === 'end') {
console.log('MY ONLY FRIEND THE END');
nav = new NavigationEnd(0, event.url, event.urlAfterRedirects);
} else {
nav = new NavigationStart(0, event.url);
}
this._eventParams = nav;
this.subject.next(nav);
}
// Route.snapshot.events
get snapshot() {
return {params: this.events};
}
navigateByUrl(url: string) {
return url;
}
navigate = sinon.stub();
}
export class ActivatedRouteStub {
// ActivatedRoute.queryParams is Observable
private subject = new BehaviorSubject(this.testParams);
public queryParams = this.subject.asObservable();
// Test parameters
private _testParams: {};
get testParams() {
return this._testParams;
}
set testParams(queryParams: {}) {
this._testParams = queryParams;
this.subject.next(queryParams);
}
private _testFragment: string;
get testFragment() {
return this._testFragment;
}
set testFragment(fragment: string) {
this._testFragment = fragment;
}
// ActivatedRoute.snapshot.params
get snapshot() {
return {queryParams: this.testParams, fragment: this.testFragment};
}
}
@Component({
selector: 'connection-profile',
template: ''
})
class MockConnectionProfileComponent {
@Input()
public connectionProfile;
@Output()
public profileUpdated: EventEmitter<any> = new EventEmitter<any>();
}
@Component({
selector: 'deploy-business-network',
template: ''
})
class MockDeployComponent {
@Output()
public finishedSampleImport: EventEmitter<any> = new EventEmitter<any>();
@Input()
public showCredentials;
}
@Component({
selector: 'app-footer',
template: ''
})
class MockFooterComponent {
}
@Component({
selector: 'identity-card',
template: ''
})
class MockIdentityCardComponent {
@Input() link: String;
@Input() identity: any;
@Input() indestructible: any;
@Input() cardRef: string;
@Input() showSpecial: boolean;
}
@Component({
selector: 'create-identity-card',
template: ''
})
class MockCreateIdentityCardComponent {
@Input()
public connectionProfileRefs;
@Input()
public connectionProfileNames;
@Input()
public connectionProfiles;
@Output()
public finishedCardCreation: EventEmitter<any> = new EventEmitter<any>();
}
@Component({
selector: 'tutorial-link',
template: ''
})
class MockTutorialLinkComponent {
@Input()
link: string;
}
describe(`LoginComponent`, () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
let mockAdminService;
let mockIdentityCardService;
let mockClientService;
let mockInitializationService;
let mockSampleBusinessNetworkService;
let routerStub;
let mockAlertService;
let mockConfigService;
let mockConfig;
let mockModal;
let mockDrawer;
let businessNetworkMock;
let activatedRoute;
beforeEach(() => {
mockIdentityCardService = sinon.createStubInstance(IdentityCardService);
mockClientService = sinon.createStubInstance(ClientService);
mockAdminService = sinon.createStubInstance(AdminService);
mockInitializationService = sinon.createStubInstance(InitializationService);
mockSampleBusinessNetworkService = sinon.createStubInstance(SampleBusinessNetworkService);
mockAlertService = sinon.createStubInstance(AlertService);
mockConfigService = sinon.createStubInstance(ConfigService);
mockConfig = sinon.createStubInstance(Config);
mockDrawer = sinon.createStubInstance(DrawerService);
mockModal = sinon.createStubInstance(NgbModal);
businessNetworkMock = sinon.createStubInstance(BusinessNetworkDefinition);
routerStub = new RouterStub();
activatedRoute = new ActivatedRouteStub();
mockAlertService.successStatus$ = {next: sinon.stub()};
mockAlertService.busyStatus$ = {next: sinon.stub()};
mockAlertService.errorStatus$ = {next: sinon.stub()};
TestBed.configureTestingModule({
declarations: [
LoginComponent,
MockConnectionProfileComponent,
MockCreateIdentityCardComponent,
MockIdentityCardComponent,
MockFooterComponent,
MockDeployComponent,
MockTutorialLinkComponent
],
providers: [
{provide: IdentityCardService, useValue: mockIdentityCardService},
{provide: ClientService, useValue: mockClientService},
{provide: Router, useValue: routerStub},
{provide: ActivatedRoute, useValue: activatedRoute},
{provide: AdminService, useValue: mockAdminService},
{provide: InitializationService, useValue: mockInitializationService},
{provide: SampleBusinessNetworkService, useValue: mockSampleBusinessNetworkService},
{provide: AlertService, useValue: mockAlertService},
{provide: DrawerService, useValue: mockDrawer},
{provide: NgbModal, useValue: mockModal},
{provide: ConfigService, useValue: mockConfigService},
]
});
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
});
it('should create the component', () => {
component.should.be.ok;
});
describe('ngOnInit', () => {
let handleRouteChangeStub;
beforeEach(() => {
handleRouteChangeStub = sinon.stub(component, 'handleRouteChange');
});
it('should load identity cards', fakeAsync(() => {
mockInitializationService.initialize.returns(Promise.resolve());
let loadIdentityCardsStub = sinon.stub(component, 'loadIdentityCards');
component.ngOnInit();
tick();
mockInitializationService.initialize.should.have.been.called;
loadIdentityCardsStub.should.have.been.called;
}));
it('should check if playground is hosted or being used locally', fakeAsync(() => {
mockInitializationService.initialize.returns(Promise.resolve());
mockConfigService.isWebOnly.returns(true);
let loadIdentityCardsStub = sinon.stub(component, 'loadIdentityCards');
component.ngOnInit();
tick();
mockConfigService.isWebOnly.should.have.been.called;
component['usingLocally'].should.be.false;
}));
it('should set config', fakeAsync(() => {
mockInitializationService.initialize.returns(Promise.resolve());
mockConfigService.isWebOnly.returns(true);
mockConfigService.getConfig.returns(mockConfig);
let loadIdentityCardsStub = sinon.stub(component, 'loadIdentityCards');
component.ngOnInit();
tick();
mockConfigService.getConfig.should.have.been.called;
component['config'].should.deep.equal(mockConfig);
}));
it('should handle the route change', fakeAsync(() => {
mockInitializationService.initialize.returns(Promise.resolve());
let loadIdentityCardsStub = sinon.stub(component, 'loadIdentityCards');
mockConfigService.getConfig.returns(mockConfig);
component.ngOnInit();
tick();
routerStub.eventParams = {url: '/login', nav: 'end'};
handleRouteChangeStub.should.have.been.called;
}));
});
describe('handleRouteChange', () => {
it('should clear the URL to /login if hits default with invalid fragment and having queryParams', () => {
activatedRoute.testFragment = 'penguin';
activatedRoute.testParams = {ref: 'ABC'};
let goLoginMainStub = sinon.stub(component, 'goLoginMain');
component['handleRouteChange']();
goLoginMainStub.should.have.been.called;
});
it('should clear the URL to /login if hits default with no fragment but having queryParams', () => {
activatedRoute.testParams = {ref: 'ABC'};
let goLoginMainStub = sinon.stub(component, 'goLoginMain');
component['handleRouteChange']();
goLoginMainStub.should.have.been.called;
});
it('should clear the URL to /login if hits default with invalid fragment but having no queryParams', () => {
activatedRoute.testFragment = 'penguin';
let goLoginMainStub = sinon.stub(component, 'goLoginMain');
component['handleRouteChange']();
goLoginMainStub.should.have.been.called;
});
it('should call closeSubView when no queryParams or fragment passed', () => {
activatedRoute.testParams = {};
let closeSubViewStub = sinon.stub(component, 'closeSubView');
component['handleRouteChange']();
closeSubViewStub.should.have.been.called;
});
it('should display deploy screen when #deploy in url using ref in params', () => {
let deployNetworkStub = sinon.stub(component, 'deployNetwork');
activatedRoute.testFragment = 'deploy';
activatedRoute.testParams = 'ABC';
component['handleRouteChange']();
deployNetworkStub.should.have.been.called;
});
it('should display card create screen when #create-card is in the URL', () => {
let createIdCardStub = sinon.stub(component, 'createIdCard');
activatedRoute.testFragment = 'create-card';
component['handleRouteChange']();
createIdCardStub.should.have.been.called;
});
});
describe('goLoginMain', () => {
it('should navigate the user to /login', () => {
component['goLoginMain']();
routerStub.navigate.should.have.been.calledWith(['/login']);
});
});
describe('goDeploy', () => {
it('should navigate the user to /login', () => {
component['goDeploy']('ABC');
routerStub.navigate.should.have.been.calledWith(['/login'], {fragment: 'deploy', queryParams: {ref: 'ABC'}});
});
});
describe('goCreateCard', () => {
it('should navigate the user to /login', () => {
component['goCreateCard']();
routerStub.navigate.should.have.been.calledWith(['/login'], {fragment: 'create-card'});
});
});
describe('loadIdentityCards', () => {
it('should load identity cards and sort the profiles force reload', fakeAsync(() => {
let mockIdCard1 = sinon.createStubInstance(IdCard);
mockIdCard1.getUserName.returns('card1');
mockIdCard1.getConnectionProfile.returns({name: 'myProfile1'});
let mockIdCard2 = sinon.createStubInstance(IdCard);
mockIdCard2.getUserName.returns('card2');
mockIdCard2.getConnectionProfile.returns({name: 'myProfile2'});
let mockIdCard3 = sinon.createStubInstance(IdCard);
mockIdCard3.getUserName.returns('card3');
mockIdCard3.getConnectionProfile.returns({name: 'myProfile1'});
let mockIdCard4 = sinon.createStubInstance(IdCard);
mockIdCard4.getUserName.returns('card4');
mockIdCard4.getConnectionProfile.returns({name: '$default'});
let mockIdCard5 = sinon.createStubInstance(IdCard);
mockIdCard5.getUserName.returns('card5');
mockIdCard5.getConnectionProfile.returns({name: 'bobProfile'});
let mockIdCards = new Map<string, IdCard>();
mockIdCards.set('myCardRef1', mockIdCard1);
mockIdCards.set('myCardRef2', mockIdCard2);
mockIdCards.set('myCardRef3', mockIdCard3);
mockIdCards.set('myCardRef4', mockIdCard4);
mockIdCards.set('myCardRef5', mockIdCard5);
mockIdentityCardService.getQualifiedProfileName.withArgs({name: 'myProfile1'}).returns('xxx-myProfile1');
mockIdentityCardService.getQualifiedProfileName.withArgs({name: 'myProfile2'}).returns('xxx-myProfile2');
mockIdentityCardService.getQualifiedProfileName.withArgs({name: 'bobProfile'}).returns('xxx-bobProfile');
mockIdentityCardService.getQualifiedProfileName.withArgs({name: '$default'}).returns('web-$default');
mockIdentityCardService.getIdentityCards.returns(Promise.resolve(mockIdCards));
mockIdentityCardService.getIndestructibleIdentityCards.returns(['myCardRef4']);
let sortCards = sinon.stub(component, 'sortIdCards');
component.loadIdentityCards(true);
tick();
sortCards.should.have.been.called;
mockIdentityCardService.getIdentityCards.should.have.been.calledWith(true);
component['connectionProfileRefs'].should.deep.equal(['xxx-bobProfile', 'xxx-myProfile1', 'xxx-myProfile2', 'web-$default']);
component['connectionProfileNames'].size.should.equal(4);
component['connectionProfileNames'].get('xxx-myProfile1').should.equal('myProfile1');
component['connectionProfileNames'].get('xxx-myProfile2').should.equal('myProfile2');
component['connectionProfileNames'].get('xxx-bobProfile').should.equal('bobProfile');
component['connectionProfileNames'].get('web-$default').should.equal('$default');
component['idCardRefs'].size.should.equal(4);
component['idCardRefs'].get('xxx-myProfile1').length.should.equal(2);
component['idCardRefs'].get('xxx-myProfile1').should.deep.equal(['myCardRef1', 'myCardRef3']);
component['idCardRefs'].get('xxx-myProfile2').length.should.equal(1);
component['idCardRefs'].get('xxx-myProfile2').should.deep.equal(['myCardRef2']);
component['idCardRefs'].get('xxx-bobProfile').should.deep.equal(['myCardRef5']);
component['idCardRefs'].get('web-$default').should.deep.equal(['myCardRef4']);
component['indestructibleCards'].should.deep.equal(['myCardRef4']);
}));
it('should load identity cards and ensure there is always a web connection profile', fakeAsync(() => {
let mockIdCard1 = sinon.createStubInstance(IdCard);
mockIdCard1.getUserName.returns('PeerAdmin');
mockIdCard1.getConnectionProfile.returns({'name': '$default', 'x-type': 'web'});
let mockIdCard2 = sinon.createStubInstance(IdCard);
mockIdCard2.getUserName.returns('bob');
mockIdCard2.getConnectionProfile.returns({name: 'bobProfile'});
let mockIdCards = new Map<string, IdCard>();
mockIdCards.set('myCardRef1', mockIdCard1);
mockIdCards.set('myCardRef2', mockIdCard2);
mockIdentityCardService.getQualifiedProfileName.withArgs({name: 'bobProfile'}).returns('xxx-bobProfile');
mockIdentityCardService.getQualifiedProfileName.withArgs({name: '$default'}).returns('web-$default');
mockIdentityCardService.getIdentityCards.returns(Promise.resolve(mockIdCards));
mockIdentityCardService.getIndestructibleIdentityCards.returns(['myCardRef1']);
let sortCards = sinon.stub(component, 'sortIdCards');
component.loadIdentityCards();
tick();
component['connectionProfileRefs'].should.deep.equal(['xxx-bobProfile', 'web-$default']);
component['connectionProfileNames'].size.should.equal(1);
component['connectionProfileNames'].get('xxx-bobProfile').should.equal('bobProfile');
component['idCardRefs'].size.should.equal(1);
component['idCardRefs'].get('xxx-bobProfile').should.deep.equal(['myCardRef2']);
component['indestructibleCards'].should.deep.equal(['myCardRef1']);
}));
it('should handle error', fakeAsync(() => {
mockIdentityCardService.getIdentityCards.returns(Promise.reject('some error'));
component.loadIdentityCards();
tick();
mockAlertService.errorStatus$.next.should.have.been.calledWith('some error');
should.not.exist(component['connectionProfileRefs']);
should.not.exist(component['connectionProfileNames']);
should.not.exist(component['idCardRefs']);
should.not.exist(component['idCards']);
}));
});
describe('changeIdentity', () => {
let mockIdCard;
let mockIdCards: Map<string, IdCard>;
beforeEach(() => {
mockIdCard = sinon.createStubInstance(IdCard);
mockIdCard.getBusinessNetworkName.returns('myNetwork');
mockIdCards = new Map<string, IdCard>();
mockIdCards.set('myCardRef', mockIdCard);
});
it('should change identity', fakeAsync(() => {
component['idCards'] = mockIdCards;
sinon.stub(component, 'canDeploy').returns(true);
mockIdentityCardService.setCurrentIdentityCard.returns(Promise.resolve());
mockClientService.ensureConnected.returns(Promise.resolve());
component.changeIdentity('myCardRef', 'myConnectionProfileRef');
tick();
mockIdentityCardService.setCurrentIdentityCard.should.have.been.calledWith('myCardRef');
mockClientService.ensureConnected.should.have.been.calledWith(true);
routerStub.navigate.should.have.been.calledWith(['editor']);
}));
it('should handle error', fakeAsync(() => {
component['idCards'] = mockIdCards;
sinon.stub(component, 'canDeploy').returns(true);
mockIdentityCardService.setCurrentIdentityCard.returns(Promise.reject('some error'));
component.changeIdentity('myCardRef', 'myConnectionProfileRef');
tick();
mockIdentityCardService.setCurrentIdentityCard.should.have.been.calledWith('myCardRef');
mockClientService.ensureConnected.should.not.have.been.called;
routerStub.navigate.should.not.have.been.called;
mockAlertService.errorStatus$.next.should.have.been.calledWith('some error');
}));
it('should open the connect-confirm modal', fakeAsync(() => {
component['idCards'] = mockIdCards;
sinon.stub(component, 'canDeploy').returns(false);
mockModal.open = sinon.stub().returns({
componentInstance: {},
result: Promise.resolve(0)
});
component.changeIdentity('myCardRef', 'myConnectionProfileRef');
tick();
mockModal.open.should.have.been.called;
}));
it('should open connect-confirm modal modal and handle error', fakeAsync(() => {
component['idCards'] = mockIdCards;
sinon.stub(component, 'canDeploy').returns(false);
mockModal.open = sinon.stub().returns({
componentInstance: {},
result: Promise.reject('some error')
});
component.changeIdentity('myCardRef', 'myConnectionProfileRef');
tick();
mockAlertService.errorStatus$.next.should.have.been.called;
mockIdentityCardService.setCurrentIdentityCard.should.not.have.been.called;
}));
it('should open connect-confirm modal and handle cancel', fakeAsync(() => {
component['idCards'] = mockIdCards;
mockModal.open = sinon.stub().returns({
componentInstance: {},
result: Promise.reject(null)
});
component.changeIdentity('myCardRef', 'myConnectionProfileRef');
tick();
mockAlertService.errorStatus$.next.should.not.have.been.called;
mockIdentityCardService.setCurrentIdentityCard.should.not.have.been.called;
}));
});
describe('editConnectionProfile', () => {
it('should edit the connection profile', () => {
component.should.be.ok;
component.editConnectionProfile('myProfile');
component['editingConnectionProfile'].should.equal('myProfile');
});
});
describe('closeSubView', () => {
it('should close the subview', () => {
component['showSubScreen'] = true;
component['showDeployNetwork'] = true;
component['editingConnectionProfile'] = {profile: 'myProfile'};
component.closeSubView();
component['showSubScreen'].should.equal(false);
should.not.exist(component['editingConectionProfile']);
component['showDeployNetwork'].should.equal(false);
});
});
describe('createIdCard', () => {
it('should return the user to the main login screen if no using locally', () => {
component['usingLocally'] = false;
let goLoginMainStub = sinon.stub(component, 'goLoginMain');
component['showSubScreen'] = false;
component['creatingIdCard'] = false;
component['createIdCard']();
goLoginMainStub.should.have.been.called;
component['showSubScreen'].should.be.false;
component['creatingIdCard'].should.be.false;
});
it('should open the ID card screen', () => {
component['showSubScreen'] = false;
component['creatingIdCard'] = false;
component['usingLocally'] = true;
component['createIdCard']();
component['showSubScreen'].should.be.true;
component['creatingIdCard'].should.be.true;
});
});
describe('finishedCardCreation', () => {
it('should close the subscreen and refresh identity cards on success', () => {
let loadIdentityCardsStub = sinon.stub(component, 'loadIdentityCards');
let goLoginMainStub = sinon.stub(component, 'goLoginMain');
component['finishedCardCreation'](true);
goLoginMainStub.should.have.been.called;
loadIdentityCardsStub.should.have.been.called;
});
it('should call closeSubView() on failure', () => {
let loadIdentityCardsStub = sinon.stub(component, 'loadIdentityCards');
let goLoginMainStub = sinon.stub(component, 'goLoginMain');
component['finishedCardCreation'](false);
goLoginMainStub.should.have.been.called;
loadIdentityCardsStub.should.not.have.been.called;
});
});
describe('removeIdentity', () => {
let mockIdCard;
let mockIdCards: Map<string, IdCard>;
let loadIdentityCardsStub;
beforeEach(() => {
mockIdCard = sinon.createStubInstance(IdCard);
mockIdCard.getUserName.returns('myCard');
mockIdCard.getConnectionProfile.returns({'x-type': 'hlfv1'});
mockIdCards = new Map<string, IdCard>();
mockIdCards.set('myCardRef', mockIdCard);
loadIdentityCardsStub = sinon.stub(component, 'loadIdentityCards');
loadIdentityCardsStub.returns(Promise.resolve());
mockIdentityCardService.getAllCardsForBusinessNetwork.returns(new Map<string, IdCard>());
});
it('should open the delete-confirm modal', fakeAsync(() => {
component['idCards'] = mockIdCards;
mockIdentityCardService.deleteIdentityCard.returns(Promise.resolve());
mockModal.open = sinon.stub().returns({
componentInstance: {},
result: Promise.resolve(0)
});
component.removeIdentity('myCardRef');
tick();
mockModal.open.should.have.been.called;
}));
it('should open delete-confirm modal and handle error', fakeAsync(() => {
component['idCards'] = mockIdCards;
mockModal.open = sinon.stub().returns({
componentInstance: {},
result: Promise.reject('some error')
});
component.removeIdentity('myCardRef');
tick();
mockAlertService.errorStatus$.next.should.have.been.called;
mockIdentityCardService.deleteIdentityCard.should.not.have.been.called;
}));
it('should open delete-confirm modal and handle cancel', fakeAsync(() => {
component['idCards'] = mockIdCards;
mockModal.open = sinon.stub().returns({
componentInstance: {},
result: Promise.reject(null)
});
component.removeIdentity('myCardRef');
tick();
mockAlertService.errorStatus$.next.should.not.have.been.called;
mockIdentityCardService.deleteIdentityCard.should.not.have.been.called;
}));
it('should refresh the identity cards after successfully calling identityCardService.deleteIdentityCard()', fakeAsync(() => {
component['idCards'] = mockIdCards;
mockIdentityCardService.deleteIdentityCard.returns(Promise.resolve());
mockModal.open = sinon.stub().returns({
componentInstance: {},
result: Promise.resolve(true)
});
component.removeIdentity('myCardRef');
tick();
// check services called
mockAdminService.connect.should.not.have.been.called;
mockIdentityCardService.deleteIdentityCard.should.have.been.calledWith('myCardRef');
loadIdentityCardsStub.should.have.been.called;
mockAlertService.successStatus$.next.should.have.been.called;
mockAlertService.errorStatus$.next.should.not.have.been.called;
}));
it('should undeploy and refresh the identity cards after successfully calling identityCardService.deleteIdentityCard()', fakeAsync(() => {
let myMap = new Map<string, IdCard>();
let idCardOne = new IdCard({userName: 'bob', businessNetwork: 'bn'}, {'name': 'cp1', 'x-type': 'web'});
myMap.set('idCardOne', idCardOne);
mockIdentityCardService.getAllCardsForBusinessNetwork.returns(myMap);
mockIdCard.getConnectionProfile.returns({'x-type': 'web'});
mockIdCards.set('myCardRef', mockIdCard);
component['idCards'] = mockIdCards;
mockIdentityCardService.deleteIdentityCard.returns(Promise.resolve());
mockAdminService.connect.resolves();
mockAdminService.undeploy.resolves();
mockModal.open = sinon.stub().returns({
componentInstance: {},
result: Promise.resolve(true)
});
component.removeIdentity('myCardRef');
tick();
// check services called
mockAdminService.connect.should.have.been.called;
mockAdminService.undeploy.should.have.been.called;
mockIdentityCardService.deleteIdentityCard.should.have.been.calledWith('myCardRef');
loadIdentityCardsStub.should.have.been.called;
mockAlertService.busyStatus$.next.should.have.been.calledWith({
title: 'Undeploying business network',
force: true
});
mockAlertService.successStatus$.next.should.have.been.called;
mockAlertService.errorStatus$.next.should.not.have.been.called;
}));
it('should not undeploy if more than one identity', fakeAsync(() => {
let myMap = new Map<string, IdCard>();
let idCardOne = new IdCard({userName: 'bob', businessNetwork: 'bn'}, {'name': 'cp1', 'x-type': 'web'});
let idCardTwo = new IdCard({userName: 'fred', businessNetwork: 'bn'}, {'name': 'cp1', 'x-type': 'web'});
myMap.set('myCardRef', idCardOne);
myMap.set('idCardTwo', idCardTwo);
mockIdentityCardService.getAllCardsForBusinessNetwork.returns(myMap);
mockIdCard.getConnectionProfile.returns({'x-type': 'web'});
mockIdCards.set('myCardRef', mockIdCard);
component['idCards'] = mockIdCards;
mockIdentityCardService.deleteIdentityCard.returns(Promise.resolve());
mockModal.open = sinon.stub().returns({
componentInstance: {},
result: Promise.resolve(true)
});
component.removeIdentity('myCardRef');
tick();
// check services called
mockAdminService.connect.should.not.have.been.called;
mockAdminService.undeploy.should.not.have.been.called;
mockIdentityCardService.deleteIdentityCard.should.have.been.calledWith('myCardRef');
loadIdentityCardsStub.should.have.been.called;
mockAlertService.successStatus$.next.should.have.been.called;
mockAlertService.errorStatus$.next.should.not.have.been.called;
}));
it('should handle errors when calling identityCardService.deleteIdentityCard()', fakeAsync(() => {
component['idCards'] = mockIdCards;
mockIdentityCardService.deleteIdentityCard.returns(Promise.reject('some error'));
mockModal.open = sinon.stub().returns({
componentInstance: {},
result: Promise.resolve(true)
});
component.removeIdentity('myCardRef');
tick();
// check services called
mockAlertService.errorStatus$.next.should.have.been.called;
mockAlertService.successStatus$.next.should.not.have.been.called;
loadIdentityCardsStub.should.not.have.been.called;
}));
});
describe('deployNetwork', () => {
it('should return the user to the login main view if they cannot deploy', fakeAsync(() => {
let canDeployStub = sinon.stub(component, 'canDeploy');
canDeployStub.returns(false);
let goLoginMainStub = sinon.stub(component, 'goLoginMain');
component.deployNetwork('1234');
tick();
mockIdentityCardService.getAdminCardRef.should.not.have.been.called;
goLoginMainStub.should.have.been.called;
}));
it('should deploy a new business network showing credentials', fakeAsync(() => {
let canDeployStub = sinon.stub(component, 'canDeploy');
canDeployStub.returns(true);
component['indestructibleCards'] = [];
mockIdentityCardService.getAdminCardRef.returns('4321');
component.deployNetwork('1234');
tick();
mockIdentityCardService.getAdminCardRef.should.have.been.calledWith('1234');
mockIdentityCardService.setCurrentIdentityCard.should.have.been.calledWith('4321');
component['showSubScreen'].should.equal(true);
component['showDeployNetwork'].should.equal(true);
component['showCredentials'].should.equal(true);
}));
it('should deploy a new business network not showing credentials', fakeAsync(() => {
let canDeployStub = sinon.stub(component, 'canDeploy');
canDeployStub.returns(true);
component['indestructibleCards'] = ['4321'];
mockIdentityCardService.getAdminCardRef.returns('4321');
component.deployNetwork('1234');
tick();
mockIdentityCardService.getAdminCardRef.should.have.been.calledWith('1234');
mockIdentityCardService.setCurrentIdentityCard.should.have.been.calledWith('4321');
component['showSubScreen'].should.equal(true);
component['showDeployNetwork'].should.equal(true);
component['showCredentials'].should.equal(false);
}));
});
describe('finishedDeploying', () => {
it('should finish deploying', () => {
let loadStub = sinon.stub(component, 'loadIdentityCards');
let goLoginMainStub = sinon.stub(component, 'goLoginMain');
component.finishedDeploying();
loadStub.should.have.been.called;
goLoginMainStub.should.have.been.called;
});
});
describe('importIdentity', () => {
beforeEach(() => {
mockDrawer.open.returns({
result: Promise.resolve()
});
});
it('should import an identity card', fakeAsync(() => {
let mockIdCard = sinon.createStubInstance(IdCard);
mockIdentityCardService.getIdentityCard.returns(mockIdCard);
let loadIdentityCardsStub = sinon.stub(component, 'loadIdentityCards');
component.importIdentity();
tick();
mockAlertService.successStatus$.next.should.have.been.called;
mockAlertService.errorStatus$.next.should.not.have.been.called;
loadIdentityCardsStub.should.have.been.called;
}));
it('should handle errors', fakeAsync(() => {
mockDrawer.open.returns({
result: Promise.reject('some error')
});
let loadIdentityCardsStub = sinon.stub(component, 'loadIdentityCards');
component.importIdentity();
tick();
loadIdentityCardsStub.should.not.have.been.called;
mockAlertService.errorStatus$.next.should.have.been.calledWith('some error');
}));
it('should handle dismiss by esc key without showing an error modal', fakeAsync(() => {
mockDrawer.open.returns({
result: Promise.reject(DrawerDismissReasons.ESC)
});
let loadIdentityCardsStub = sinon.stub(component, 'loadIdentityCards');
component.importIdentity();
tick();
loadIdentityCardsStub.should.not.have.been.called;
mockAlertService.errorStatus$.next.should.not.have.been.called;
}));
});
describe('exportIdentity', () => {
let sandbox = sinon.sandbox.create();
let mockIdCard;
let saveAsStub;
beforeEach(() => {
saveAsStub = sandbox.stub(fileSaver, 'saveAs');
mockIdCard = sinon.createStubInstance(IdCard);
mockIdCard.getUserName.returns('myCard');
});
afterEach(() => {
sandbox.restore();
});
it('should export an identity card', fakeAsync(() => {
mockIdentityCardService.getIdentityCardForExport.returns(Promise.resolve(mockIdCard));
mockIdCard.toArchive.returns(Promise.resolve('card data'));
component.exportIdentity('myCardRef');
tick();
let expectedFile = new Blob(['card data'], {type: 'application/octet-stream'});
saveAsStub.should.have.been.calledWith(expectedFile, 'myCard.card');
}));
it('should handle errors', fakeAsync(() => {
mockIdentityCardService.getIdentityCardForExport.returns(Promise.resolve(mockIdCard));
mockIdCard.toArchive.returns(Promise.reject('some error'));
component.exportIdentity('myCardRef');
tick();
mockAlertService.errorStatus$.next.should.have.been.calledWith('some error');
}));
});
describe('canDeploy', () => {
it('should check if PeerAdmin and ChannelAdmin cards are available', () => {
component.canDeploy('1234');
mockIdentityCardService.canDeploy.should.have.been.calledWith('1234');
});
});
describe('sortIdCards', () => {
let mockIdCard1;
let mockIdCard2;
let mockIdCard3;
let mockIdCard4;
let mockIdCard5;
let mockIdCard6;
let mockIdCard7;
let mockIdCards;
beforeEach(() => {
mockIdCard1 = sinon.createStubInstance(IdCard);
mockIdCard1.getUserName.returns('card2');
mockIdCard1.getBusinessNetworkName.returns('my-network');
mockIdCard1.getRoles.returns(['PeerAdmin']);
mockIdCard2 = sinon.createStubInstance(IdCard);
mockIdCard2.getUserName.returns('card2');
mockIdCard2.getBusinessNetworkName.returns(null);
mockIdCard2.getRoles.returns(['PeerAdmin']);
mockIdCard3 = sinon.createStubInstance(IdCard);
mockIdCard3.getUserName.returns('card2');
mockIdCard3.getBusinessNetworkName.returns('my-z-alphabet-network');
mockIdCard3.getRoles.returns(['PeerAdmin']);
mockIdCard4 = sinon.createStubInstance(IdCard);
mockIdCard4.getUserName.returns('card1');
mockIdCard4.getBusinessNetworkName.returns(null);
mockIdCard4.getRoles.returns(['PeerAdmin']);
mockIdCard5 = sinon.createStubInstance(IdCard);
mockIdCard5.getUserName.returns('card3');
mockIdCard5.getBusinessNetworkName.returns(null);
mockIdCard5.getRoles.returns(null);
mockIdCard6 = sinon.createStubInstance(IdCard);
mockIdCard6.getUserName.returns('card1');
mockIdCard6.getBusinessNetworkName.returns('my-alphabet-network');
mockIdCard6.getRoles.returns(['PeerAdmin']);
mockIdCard7 = sinon.createStubInstance(IdCard);
mockIdCard7.getUserName.returns('card1');
mockIdCard7.getBusinessNetworkName.returns('my-alphabet-network');
mockIdCard7.getRoles.returns(null);
mockIdCards = new Map<string, IdCard>();
mockIdCards.set('myCardRef1', mockIdCard1);
mockIdCards.set('myCardRef2', mockIdCard2);
mockIdCards.set('myCardRef3', mockIdCard3);
mockIdCards.set('myCardRef4', mockIdCard4);
mockIdCards.set('myCardRef5', mockIdCard5);
mockIdCards.set('myCardRef6', mockIdCard6);
mockIdCards.set('myCardRef7', mockIdCard7);
mockIdentityCardService.getIdentityCard.withArgs('myCardRef1').returns(mockIdCard1);
mockIdentityCardService.getIdentityCard.withArgs('myCardRef2').returns(mockIdCard2);
mockIdentityCardService.getIdentityCard.withArgs('myCardRef3').returns(mockIdCard3);
mockIdentityCardService.getIdentityCard.withArgs('myCardRef4').returns(mockIdCard4);
mockIdentityCardService.getIdentityCard.withArgs('myCardRef5').returns(mockIdCard5);
mockIdentityCardService.getIdentityCard.withArgs('myCardRef6').returns(mockIdCard6);
mockIdentityCardService.getIdentityCard.withArgs('myCardRef7').returns(mockIdCard7);
});
it('should sort the idCards', () => {
let cardRefs = Array.from(mockIdCards.keys());
cardRefs.sort(component['sortIdCards'].bind(component));
cardRefs.should.deep.equal(['myCardRef5', 'myCardRef2', 'myCardRef4', 'myCardRef7', 'myCardRef6', 'myCardRef1', 'myCardRef3']);
});
});
describe('deploySample', () => {
it('should deploy the sample network', fakeAsync(() => {
mockIdentityCardService.getIdentityCardRefsWithProfileAndRole.returns(['4321']);
mockSampleBusinessNetworkService.getSampleList.returns(Promise.resolve([{name: 'mySample'}]));
mockSampleBusinessNetworkService.getChosenSample.returns(Promise.resolve(businessNetworkMock));
mockSampleBusinessNetworkService.deployBusinessNetwork.returns(Promise.resolve('myNewCardRef'));
let loadCardsStub = sinon.stub(component, 'loadIdentityCards').resolves();
let changeIdentityStub = sinon.stub(component, 'changeIdentity');
component.deploySample('profileRef');
tick();
mockIdentityCardService.getIdentityCardRefsWithProfileAndRole.should.have.been.calledWith('profileRef');
mockIdentityCardService.setCurrentIdentityCard.should.have.been.calledWith('4321');
mockSampleBusinessNetworkService.getSampleList.should.have.been.called;
mockSampleBusinessNetworkService.getChosenSample.should.have.been.calledWith({name: 'mySample'});
mockSampleBusinessNetworkService.deployBusinessNetwork.should.have.been.calledWith(businessNetworkMock, 'playgroundSample@basic-sample-network', 'my-basic-sample', 'The Composer basic sample network');
loadCardsStub.should.have.been.calledWith(true);
changeIdentityStub.should.have.been.calledWith('playgroundSample@basic-sample-network');
}));
});
}); | the_stack |
import { EventEmitter } from "events";
import { expect } from "chai";
import sinon from "sinon";
import { BasicClient } from "../src/BasicClient";
class TestClient extends BasicClient {
protected _onMessage = sinon.stub();
protected _sendSubTicker = sinon.stub();
protected _sendSubCandles = sinon.stub();
protected _sendUnsubCandles = sinon.stub();
protected _sendUnsubTicker = sinon.stub();
protected _sendSubTrades = sinon.stub();
protected _sendUnsubTrades = sinon.stub();
protected _sendSubLevel2Snapshots = sinon.stub();
protected _sendUnsubLevel2Snapshots = sinon.stub();
protected _sendSubLevel2Updates = sinon.stub();
protected _sendUnsubLevel2Updates = sinon.stub();
protected _sendSubLevel3Snapshots = sinon.stub();
protected _sendUnsubLevel3Snapshots = sinon.stub();
protected _sendSubLevel3Updates = sinon.stub();
protected _sendUnsubLevel3Updates = sinon.stub();
}
function buildInstance() {
const instance = new TestClient("wss://localhost/test", "test", mockSmartWss);
instance.hasTickers = true;
instance.hasTrades = true;
instance.hasCandles = true;
instance.hasLevel2Snapshots = true;
instance.hasLevel2Updates = true;
instance.hasLevel3Updates = true;
sinon.stub((instance as any)._watcher, "start");
sinon.stub((instance as any)._watcher, "stop");
return instance;
}
function mockSmartWss() {
const wss = new EventEmitter() as any;
wss.connect = sinon.stub();
wss.close = sinon.stub();
wss.mockEmit = function (event, payload) {
if (event === "connected") this.isConnected = true;
this.emit(event, payload);
};
wss.isConnected = false;
wss.close.callsFake(() => {
wss.mockEmit("closing");
setTimeout(() => wss.mockEmit("closed"), 0);
});
return wss;
}
describe("BasicClient", () => {
let instance;
before(() => {
instance = buildInstance();
instance._connect();
});
describe("on first subscribe", () => {
it("should open a connection", () => {
instance.subscribeTrades({ id: "BTCUSD" });
expect(instance._wss).to.not.be.undefined;
expect(instance._wss.connect.callCount).to.equal(1);
});
it("should send subscribe to the socket", () => {
instance._wss.mockEmit("connected");
expect(instance._sendSubTrades.callCount).to.equal(1);
expect(instance._sendSubTrades.args[0][0]).to.equal("BTCUSD");
expect(instance._sendSubTrades.args[0][1]).to.be.an("object");
});
it("should start the watcher", () => {
expect(instance._watcher.start.callCount).to.equal(1);
});
});
describe("on subsequent subscribes", () => {
it("should not connect again", () => {
instance.subscribeTrades({ id: "LTCBTC" });
expect(instance._wss.connect.callCount).to.equal(1);
});
it("should send subscribe to the socket", () => {
expect(instance._sendSubTrades.callCount).to.equal(2);
expect(instance._sendSubTrades.args[1][0]).to.equal("LTCBTC");
expect(instance._sendSubTrades.args[1][1]).to.be.an("object");
});
});
describe("on duplicate subscribe", () => {
it("should not send subscribe to the socket", () => {
instance.subscribeTrades({ id: "LTCBTC" });
expect(instance._sendSubTrades.callCount).to.equal(2);
});
});
describe("on message", () => {
before(() => {
instance._wss.mockEmit("message", "test");
});
it("should call on message", () => {
expect(instance._onMessage.args[0][0]).to.equal("test");
});
});
describe("on reconnect", () => {
it("should resubscribe to markets", () => {
instance._wss.mockEmit("connected");
expect(instance._sendSubTrades.callCount).to.equal(4);
expect(instance._sendSubTrades.args[2][0]).to.equal("BTCUSD");
expect(instance._sendSubTrades.args[2][1]).to.be.an("object");
expect(instance._sendSubTrades.args[3][0]).to.equal("LTCBTC");
expect(instance._sendSubTrades.args[3][1]).to.be.an("object");
});
});
describe("on unsubscribe", () => {
it("should send unsubscribe to socket", () => {
instance.unsubscribeTrades({ id: "LTCBTC" });
expect(instance._sendUnsubTrades.callCount).to.equal(1);
expect(instance._sendUnsubTrades.args[0][0]).to.equal("LTCBTC");
expect(instance._sendUnsubTrades.args[0][1]).to.be.an("object");
});
});
describe("on duplicate unsubscribe", () => {
it("should not send unsubscribe to the socket", () => {
instance.unsubscribeTrades({ id: "LTCBTC" });
expect(instance._sendUnsubTrades.callCount).to.equal(1);
});
});
describe("when no messages received", () => {
let originalWss;
const closingEvent = sinon.stub();
const closedEvent = sinon.stub();
const reconnectingEvent = sinon.stub();
before(async () => {
originalWss = instance._wss;
instance.on("closing", closingEvent);
instance.on("closed", closedEvent);
instance.on("reconnecting", reconnectingEvent);
instance.emit("trade"); // triggers the connection watcher
instance._watcher._reconnect();
});
it("should close the connection", () => {
expect(originalWss.close.callCount).to.equal(1);
});
it("should emit a closing event", () => {
expect(closingEvent.callCount).to.equal(1);
});
it("should emit a closed event", () => {
expect(closedEvent.callCount).to.equal(1);
});
it("should reopen the connection", () => {
expect(instance._wss).to.not.deep.equal(originalWss);
expect(instance._wss.connect.callCount).to.equal(1);
});
it("should emit a reconnected event", () => {
expect(reconnectingEvent.callCount).to.equal(1);
});
});
describe("when connected, on disconnect", () => {
it("disconnect event should fire if the underlying socket closes", done => {
instance._watcher.stop.resetHistory();
instance.on("disconnected", done);
instance._wss.mockEmit("disconnected");
});
it("close should stop the reconnection checker", () => {
expect(instance._watcher.stop.callCount).to.equal(1);
});
});
describe("when connected, .close", () => {
it("close should emit 'closing' and 'closed' events", done => {
instance._watcher.stop.resetHistory();
let closing = false;
instance.on("closing", () => {
closing = true;
});
instance.on("closed", () => {
instance.removeAllListeners();
if (closing) done();
});
instance.close();
});
it("close should stop the reconnection checker", () => {
expect(instance._watcher.stop.callCount).to.equal(2);
});
});
describe("when already closed", () => {
it("should not 'closing' and 'closed' events", () => {
instance.on("closing", () => {
throw new Error("should not reach here");
});
instance.on("closed", () => {
throw new Error("should not reach here");
});
instance.close();
});
});
describe("level2 snapshots", () => {
let instance;
before(() => {
instance = buildInstance();
instance._connect();
});
describe("on first subscribe", () => {
it("should open a connection", () => {
instance.subscribeLevel2Snapshots({ id: "BTCUSD" });
expect(instance._wss).to.not.be.undefined;
expect(instance._wss.connect.callCount).to.equal(1);
});
it("should send subscribe to the socket", () => {
instance._wss.mockEmit("connected");
expect(instance._sendSubLevel2Snapshots.callCount).to.equal(1);
expect(instance._sendSubLevel2Snapshots.args[0][0]).to.equal("BTCUSD");
expect(instance._sendSubLevel2Snapshots.args[0][1]).to.be.an("object");
});
it("should start the reconnectChecker", () => {
expect(instance._watcher.start.callCount).to.equal(1);
});
});
describe("on subsequent subscribes", () => {
it("should not connect again", () => {
instance.subscribeLevel2Snapshots({ id: "LTCBTC" });
expect(instance._wss.connect.callCount).to.equal(1);
});
it("should send subscribe to the socket", () => {
expect(instance._sendSubLevel2Snapshots.callCount).to.equal(2);
expect(instance._sendSubLevel2Snapshots.args[1][0]).to.equal("LTCBTC");
expect(instance._sendSubLevel2Snapshots.args[1][1]).to.be.an("object");
});
});
describe("on unsubscribe", () => {
it("should send unsubscribe to socket", () => {
instance.unsubscribeLevel2Snapshots({ id: "LTCBTC" });
expect(instance._sendUnsubLevel2Snapshots.callCount).to.equal(1);
expect(instance._sendUnsubLevel2Snapshots.args[0][0]).to.equal("LTCBTC");
expect(instance._sendUnsubLevel2Snapshots.args[0][1]).to.be.an("object");
});
});
});
describe("level2 updates", () => {
let instance;
before(() => {
instance = buildInstance();
instance._connect();
});
describe("on first subscribe", () => {
it("should open a connection", () => {
instance.subscribeLevel2Updates({ id: "BTCUSD" });
expect(instance._wss).to.not.be.undefined;
expect(instance._wss.connect.callCount).to.equal(1);
});
it("should send subscribe to the socket", () => {
instance._wss.mockEmit("connected");
expect(instance._sendSubLevel2Updates.callCount).to.equal(1);
expect(instance._sendSubLevel2Updates.args[0][0]).to.equal("BTCUSD");
expect(instance._sendSubLevel2Updates.args[0][1]).to.be.an("object");
});
it("should start the reconnectChecker", () => {
expect(instance._watcher.start.callCount).to.equal(1);
});
});
describe("on subsequent subscribes", () => {
it("should not connect again", () => {
instance.subscribeLevel2Updates({ id: "LTCBTC" });
expect(instance._wss.connect.callCount).to.equal(1);
});
it("should send subscribe to the socket", () => {
expect(instance._sendSubLevel2Updates.callCount).to.equal(2);
expect(instance._sendSubLevel2Updates.args[1][0]).to.equal("LTCBTC");
expect(instance._sendSubLevel2Updates.args[1][1]).to.be.an("object");
});
});
describe("on unsubscribe", () => {
it("should send unsubscribe to socket", () => {
instance.unsubscribeLevel2Updates({ id: "LTCBTC" });
expect(instance._sendUnsubLevel2Updates.callCount).to.equal(1);
expect(instance._sendUnsubLevel2Updates.args[0][0]).to.equal("LTCBTC");
});
});
});
describe("level3 updates", () => {
let instance;
before(() => {
instance = buildInstance();
instance._connect();
});
describe("on first subscribe", () => {
it("should open a connection", () => {
instance.subscribeLevel3Updates({ id: "BTCUSD" });
expect(instance._wss).to.not.be.undefined;
expect(instance._wss.connect.callCount).to.equal(1);
});
it("should send subscribe to the socket", () => {
instance._wss.mockEmit("connected");
expect(instance._sendSubLevel3Updates.callCount).to.equal(1);
expect(instance._sendSubLevel3Updates.args[0][0]).to.equal("BTCUSD");
expect(instance._sendSubLevel3Updates.args[0][1]).to.be.an("object");
});
it("should start the reconnectChecker", () => {
expect(instance._watcher.start.callCount).to.equal(1);
});
});
describe("on subsequent subscribes", () => {
it("should not connect again", () => {
instance.subscribeLevel3Updates({ id: "LTCBTC" });
expect(instance._wss.connect.callCount).to.equal(1);
});
it("should send subscribe to the socket", () => {
expect(instance._sendSubLevel3Updates.callCount).to.equal(2);
expect(instance._sendSubLevel3Updates.args[1][0]).to.equal("LTCBTC");
expect(instance._sendSubLevel3Updates.args[1][1]).to.be.an("object");
});
});
describe("on unsubscribe", () => {
it("should send unsubscribe to socket", () => {
instance.unsubscribeLevel3Updates({ id: "LTCBTC" });
expect(instance._sendUnsubLevel3Updates.callCount).to.equal(1);
expect(instance._sendUnsubLevel3Updates.args[0][0]).to.equal("LTCBTC");
});
});
});
describe("ticker", () => {
let instance;
before(() => {
instance = buildInstance();
instance._connect();
});
describe("on first subscribe", () => {
it("should open a connection", () => {
instance.subscribeTicker({ id: "BTCUSD" });
expect(instance._wss).to.not.be.undefined;
expect(instance._wss.connect.callCount).to.equal(1);
});
it("should send subscribe to the socket", () => {
instance._wss.mockEmit("connected");
expect(instance._sendSubTicker.callCount).to.equal(1);
expect(instance._sendSubTicker.args[0][0]).to.equal("BTCUSD");
expect(instance._sendSubTicker.args[0][1]).to.be.an("object");
});
it("should start the reconnectChecker", () => {
expect(instance._watcher.start.callCount).to.equal(1);
});
});
describe("on subsequent subscribes", () => {
it("should not connect again", () => {
instance.subscribeTicker({ id: "LTCBTC" });
expect(instance._wss.connect.callCount).to.equal(1);
});
it("should send subscribe to the socket", () => {
expect(instance._sendSubTicker.callCount).to.equal(2);
expect(instance._sendSubTicker.args[1][0]).to.equal("LTCBTC");
expect(instance._sendSubTicker.args[1][1]).to.be.an("object");
});
});
// describe("on unsubscribe", () => {
// it("should send unsubscribe to socket", () => {
// instance.unsubscribeTicker({ id: "LTCBTC" });
// expect(instance._sendUnsubTicker.callCount).to.equal(1);
// expect(instance._sendUnsubTicker.args[0][0]).to.equal("LTCBTC");
// });
// });
});
describe("candle", () => {
let instance;
before(() => {
instance = buildInstance();
instance._connect();
});
describe("on first subscribe", () => {
it("should open a connection", () => {
instance.subscribeCandles({ id: "BTCUSD" });
expect(instance._wss).to.not.be.undefined;
expect(instance._wss.connect.callCount).to.equal(1);
});
it("should send subscribe to the socket", () => {
instance._wss.mockEmit("connected");
expect(instance._sendSubCandles.callCount).to.equal(1);
expect(instance._sendSubCandles.args[0][0]).to.equal("BTCUSD");
expect(instance._sendSubCandles.args[0][1]).to.be.an("object");
});
it("should start the reconnectChecker", () => {
expect(instance._watcher.start.callCount).to.equal(1);
});
});
describe("on subsequent subscribes", () => {
it("should not connect again", () => {
instance.subscribeCandles({ id: "LTCBTC" });
expect(instance._wss.connect.callCount).to.equal(1);
});
it("should send subscribe to the socket", () => {
expect(instance._sendSubCandles.callCount).to.equal(2);
expect(instance._sendSubCandles.args[1][0]).to.equal("LTCBTC");
expect(instance._sendSubCandles.args[1][1]).to.be.an("object");
});
});
describe("on unsubscribe", () => {
it("should send unsubscribe to socket", () => {
instance.unsubscribeCandles({ id: "LTCBTC" });
expect(instance._sendUnsubCandles.callCount).to.equal(1);
expect(instance._sendUnsubCandles.args[0][0]).to.equal("LTCBTC");
});
});
});
describe("neutered should no-op", () => {
let instance;
const market = { id: "BTCUSD" };
before(() => {
instance = buildInstance();
instance.hasTickers = false;
instance.hasTrades = false;
instance.hasLevel2Snapshots = false;
instance.hasLevel2Updates = false;
instance.hasLevel3Updates = false;
instance._connect();
instance._wss.mockEmit("connected");
});
it("should not send ticker sub", () => {
instance.subscribeTicker(market);
expect(instance._sendSubTicker.callCount).to.equal(0);
});
it("should not send trade sub", () => {
instance.subscribeTrades(market);
expect(instance._sendSubTrades.callCount).to.equal(0);
});
it("should not send trade unsub", () => {
instance.unsubscribeTrades(market);
expect(instance._sendUnsubTrades.callCount).to.equal(0);
});
it("should not send level2 snapshot sub", () => {
instance.subscribeLevel2Snapshots(market);
expect(instance._sendSubLevel2Snapshots.callCount).to.equal(0);
});
it("should not send level2 snapshot unsub", () => {
instance.unsubscribeLevel2Snapshots(market);
expect(instance._sendUnsubLevel2Snapshots.callCount).to.equal(0);
});
it("should not send level2 update sub", () => {
instance.subscribeLevel2Updates(market);
expect(instance._sendSubLevel2Updates.callCount).to.equal(0);
});
it("should not send level2 update unsub", () => {
instance.unsubscribeLevel2Updates(market);
expect(instance._sendUnsubLevel2Updates.callCount).to.equal(0);
});
it("should not send level3 update sub", () => {
instance.subscribeLevel3Updates(market);
expect(instance._sendSubLevel3Updates.callCount).to.equal(0);
});
it("should not send level3 update unsub", () => {
instance.unsubscribeLevel3Updates(market);
expect(instance._sendUnsubLevel3Updates.callCount).to.equal(0);
});
});
}); | the_stack |
// And then a few modifications, mostly to remove the "duplicate" definitions
// of Score/Graph as interfaces and classes. Interfaces become IScore/IGraph.
export interface IScore {
graph: Graph;
version: string;
}
export interface IGraph {
id: string;
loadingPolicy?: LoadingPolicy;
nodes?: Node[];
edges?: Edge[];
scripts?: Script[];
}
export interface Edge {
id: string;
source: string;
target: string;
sourcePort?: string;
targetPort?: string;
}
export declare enum LoadingPolicy {
AllContentPlaythrough = 'allContentPlaythrough',
SomeContentPlaythrough = 'someContentPlaythrough'
}
export interface Node {
id: string;
kind: string;
loadingPolicy?: LoadingPolicy;
params?: {
[key: string]: Command[];
};
config?: {
[key: string]: any;
};
}
export interface Command {
name: string;
args?: {
[key: string]: any;
};
}
export interface Script {
name: string;
code: string;
}
/**
* Signal types.
*/
export declare enum ContentType {
AUDIO = 'com.nativeformat.content.audio'
}
export declare class Graph implements IGraph {
id: string;
loadingPolicy: LoadingPolicy;
nodes: Node[];
edges: Edge[];
scripts: Script[];
constructor(
id?: string,
loadingPolicy?: LoadingPolicy,
nodes?: Node[],
edges?: Edge[],
scripts?: Script[]
);
static from(graph: IGraph): Graph;
}
export declare class Score implements IScore {
graph: Graph;
version: string;
constructor(graph?: Graph, version?: string);
static from(score: IScore): Score;
}
export abstract class TypedNode {
readonly id: string;
readonly kind: string;
constructor(id: string, kind: string);
toNode(): Node;
toJSON(): Node;
/**
* @deprecated use `connectToTarget` or `connectToSource` instead.
*/
connect(target: TypedNode): Edge;
/**
* Creates an edge from this node to the target node.
* @param target Target node.
*/
connectToTarget(target: TypedNode): Edge;
/**
* Creates an edge from the target node to this node.
* @param source Source node.
*/
connectToSource(source: TypedNode): Edge;
getInputs(): Map<string, ContentType>;
getOutputs(): Map<string, ContentType>;
protected getConfig(): {
[key: string]: any;
};
protected getParams(): {
[key: string]: Command[];
};
}
declare abstract class TypedParam<T> {
readonly initialValue: T;
constructor(initialValue: T);
abstract getCommands(): Command[];
}
declare class ParamMapper<T extends TypedParam<any>> {
readonly name: string;
readonly factory: (cmds: Command[]) => T;
constructor(name: string, factory: (cmds: Command[]) => T);
create(): T;
readParam(node: Node): T;
}
/**
* AudioParam.
*/
export declare class AudioParam extends TypedParam<number> {
private commands;
/**
* Creates a new `AudioParam` instance.
*/
constructor(initialValue: number, commands?: Command[]);
/**
* Creates a new AudioParam mapper.
*/
static newParamMapper(
name: string,
initialValue: number
): ParamMapper<AudioParam>;
/**
* Sets the value of this param at the given start time.
*/
setValueAtTime(value: number, startTime: number): AudioParam;
/**
* Linearly interpolates the param from its current value to the give value at the given time.
*/
linearRampToValueAtTime(value: number, endTime: number): AudioParam;
/**
* Exponentially interpolates the param from its current value to the give value at the given time.
*/
exponentialRampToValueAtTime(value: number, endTime: number): AudioParam;
/**
* Specifies a target to reach starting at a given time and gives a constant with which to guide the curve along.
*/
setTargetAtTime(
target: number,
startTime: number,
timeConstant: number
): AudioParam;
/**
* Specifies a curve to render based on the given float values.
*/
setValueCurveAtTime(
values: number[],
startTime: number,
duration: number
): AudioParam;
/**
* Returns an array of all commands added to this param.
*/
getCommands(): Command[];
}
/**
* Eq3bandNode.
*/
export declare class Eq3bandNode extends TypedNode {
readonly lowCutoff: AudioParam;
readonly midFrequency: AudioParam;
readonly highCutoff: AudioParam;
readonly lowGain: AudioParam;
readonly midGain: AudioParam;
readonly highGain: AudioParam;
/**
* Unique identifier for the plugin kind this node represents.
*/
static PLUGIN_KIND: string;
/**
* `lowCutoff` param factory.
*/
private static LOW_CUTOFF_PARAM;
/**
* `midFrequency` param factory.
*/
private static MID_FREQUENCY_PARAM;
/**
* `highCutoff` param factory.
*/
private static HIGH_CUTOFF_PARAM;
/**
* `lowGain` param factory.
*/
private static LOW_GAIN_PARAM;
/**
* `midGain` param factory.
*/
private static MID_GAIN_PARAM;
/**
* `highGain` param factory.
*/
private static HIGH_GAIN_PARAM;
/**
* Creates a new `Eq3bandNode` instance.
*/
constructor(
id: string,
lowCutoff: AudioParam,
midFrequency: AudioParam,
highCutoff: AudioParam,
lowGain: AudioParam,
midGain: AudioParam,
highGain: AudioParam
);
/**
* `Eq3bandNode` factory.
*/
static create(id?: string): Eq3bandNode;
/**
* Creates a new `Eq3bandNode` from a score `Node`.
*/
static from(node: Node): Eq3bandNode;
/**
* Params for this node.
*/
getParams(): {
[key: string]: Command[];
};
/**
* Inputs for this node.
*/
getInputs(): Map<string, ContentType>;
/**
* Outputs for this node.
*/
getOutputs(): Map<string, ContentType>;
}
/**
* FileNodeConfig.
*/
export interface FileNodeConfig {
file: string;
when?: number;
duration?: number;
offset?: number;
}
/**
* FileNode.
*/
export declare class FileNode extends TypedNode {
readonly file: string;
readonly when: number;
readonly duration: number;
readonly offset: number;
/**
* Unique identifier for the plugin kind this node represents.
*/
static PLUGIN_KIND: string;
/**
* Creates a new `string` mapper for the `file` param.
*/
private static FILE_CONFIG;
/**
* Creates a new `number` mapper for the `when` param.
*/
private static WHEN_CONFIG;
/**
* Creates a new `number` mapper for the `duration` param.
*/
private static DURATION_CONFIG;
/**
* Creates a new `number` mapper for the `offset` param.
*/
private static OFFSET_CONFIG;
/**
* Creates a new `FileNode` instance.
*/
constructor(
id: string,
file: string,
when: number,
duration: number,
offset: number
);
/**
* `FileNode` factory.
*/
static create(config: FileNodeConfig, id?: string): FileNode;
/**
* Creates a new `FileNode` from a score `Node`.
*/
static from(node: Node): FileNode;
/**
* Configs for this node.
*/
getConfig(): FileNodeConfig;
/**
* Inputs for this node.
*/
getInputs(): Map<string, ContentType>;
/**
* Outputs for this node.
*/
getOutputs(): Map<string, ContentType>;
}
/**
* NoiseNodeConfig.
*/
export interface NoiseNodeConfig {
when?: number;
duration?: number;
}
/**
* NoiseNode.
*/
export declare class NoiseNode extends TypedNode {
readonly when: number;
readonly duration: number;
/**
* Unique identifier for the plugin kind this node represents.
*/
static PLUGIN_KIND: string;
/**
* Creates a new `number` mapper for the `when` param.
*/
private static WHEN_CONFIG;
/**
* Creates a new `number` mapper for the `duration` param.
*/
private static DURATION_CONFIG;
/**
* Creates a new `NoiseNode` instance.
*/
constructor(id: string, when: number, duration: number);
/**
* `NoiseNode` factory.
*/
static create(config: NoiseNodeConfig, id?: string): NoiseNode;
/**
* Creates a new `NoiseNode` from a score `Node`.
*/
static from(node: Node): NoiseNode;
/**
* Configs for this node.
*/
getConfig(): NoiseNodeConfig;
/**
* Inputs for this node.
*/
getInputs(): Map<string, ContentType>;
/**
* Outputs for this node.
*/
getOutputs(): Map<string, ContentType>;
}
/**
* SilenceNodeConfig.
*/
export interface SilenceNodeConfig {
when?: number;
duration?: number;
}
/**
* SilenceNode.
*/
export declare class SilenceNode extends TypedNode {
readonly when: number;
readonly duration: number;
/**
* Unique identifier for the plugin kind this node represents.
*/
static PLUGIN_KIND: string;
/**
* Creates a new `number` mapper for the `when` param.
*/
private static WHEN_CONFIG;
/**
* Creates a new `number` mapper for the `duration` param.
*/
private static DURATION_CONFIG;
/**
* Creates a new `SilenceNode` instance.
*/
constructor(id: string, when: number, duration: number);
/**
* `SilenceNode` factory.
*/
static create(config: SilenceNodeConfig, id?: string): SilenceNode;
/**
* Creates a new `SilenceNode` from a score `Node`.
*/
static from(node: Node): SilenceNode;
/**
* Configs for this node.
*/
getConfig(): SilenceNodeConfig;
/**
* Inputs for this node.
*/
getInputs(): Map<string, ContentType>;
/**
* Outputs for this node.
*/
getOutputs(): Map<string, ContentType>;
}
/**
* LoopNodeConfig.
*/
export interface LoopNodeConfig {
when: number;
duration: number;
loopCount?: number;
}
/**
* LoopNode.
*/
export declare class LoopNode extends TypedNode {
readonly when: number;
readonly duration: number;
readonly loopCount: number;
/**
* Unique identifier for the plugin kind this node represents.
*/
static PLUGIN_KIND: string;
/**
* Creates a new `number` mapper for the `when` param.
*/
private static WHEN_CONFIG;
/**
* Creates a new `number` mapper for the `duration` param.
*/
private static DURATION_CONFIG;
/**
* Creates a new `number` mapper for the `loopCount` param.
*/
private static LOOP_COUNT_CONFIG;
/**
* Creates a new `LoopNode` instance.
*/
constructor(id: string, when: number, duration: number, loopCount: number);
/**
* `LoopNode` factory.
*/
static create(config: LoopNodeConfig, id?: string): LoopNode;
/**
* Creates a new `LoopNode` from a score `Node`.
*/
static from(node: Node): LoopNode;
/**
* Configs for this node.
*/
getConfig(): LoopNodeConfig;
/**
* Inputs for this node.
*/
getInputs(): Map<string, ContentType>;
/**
* Outputs for this node.
*/
getOutputs(): Map<string, ContentType>;
}
/**
* StretchNode.
*/
export declare class StretchNode extends TypedNode {
readonly pitchRatio: AudioParam;
readonly stretch: AudioParam;
readonly formantRatio: AudioParam;
/**
* Unique identifier for the plugin kind this node represents.
*/
static PLUGIN_KIND: string;
/**
* `pitchRatio` param factory.
*/
private static PITCH_RATIO_PARAM;
/**
* `stretch` param factory.
*/
private static STRETCH_PARAM;
/**
* `formantRatio` param factory.
*/
private static FORMANT_RATIO_PARAM;
/**
* Creates a new `StretchNode` instance.
*/
constructor(
id: string,
pitchRatio: AudioParam,
stretch: AudioParam,
formantRatio: AudioParam
);
/**
* `StretchNode` factory.
*/
static create(id?: string): StretchNode;
/**
* Creates a new `StretchNode` from a score `Node`.
*/
static from(node: Node): StretchNode;
/**
* Params for this node.
*/
getParams(): {
[key: string]: Command[];
};
/**
* Inputs for this node.
*/
getInputs(): Map<string, ContentType>;
/**
* Outputs for this node.
*/
getOutputs(): Map<string, ContentType>;
}
/**
* DelayNode.
*/
export declare class DelayNode extends TypedNode {
readonly delayTime: AudioParam;
/**
* Unique identifier for the plugin kind this node represents.
*/
static PLUGIN_KIND: string;
/**
* `delayTime` param factory.
*/
private static DELAY_TIME_PARAM;
/**
* Creates a new `DelayNode` instance.
*/
constructor(id: string, delayTime: AudioParam);
/**
* `DelayNode` factory.
*/
static create(id?: string): DelayNode;
/**
* Creates a new `DelayNode` from a score `Node`.
*/
static from(node: Node): DelayNode;
/**
* Params for this node.
*/
getParams(): {
[key: string]: Command[];
};
/**
* Inputs for this node.
*/
getInputs(): Map<string, ContentType>;
/**
* Outputs for this node.
*/
getOutputs(): Map<string, ContentType>;
}
/**
* GainNode.
*/
export declare class GainNode extends TypedNode {
readonly gain: AudioParam;
/**
* Unique identifier for the plugin kind this node represents.
*/
static PLUGIN_KIND: string;
/**
* `gain` param factory.
*/
private static GAIN_PARAM;
/**
* Creates a new `GainNode` instance.
*/
constructor(id: string, gain: AudioParam);
/**
* `GainNode` factory.
*/
static create(id?: string): GainNode;
/**
* Creates a new `GainNode` from a score `Node`.
*/
static from(node: Node): GainNode;
/**
* Params for this node.
*/
getParams(): {
[key: string]: Command[];
};
/**
* Inputs for this node.
*/
getInputs(): Map<string, ContentType>;
/**
* Outputs for this node.
*/
getOutputs(): Map<string, ContentType>;
}
/**
* SineNodeConfig.
*/
export interface SineNodeConfig {
frequency?: number;
when?: number;
duration?: number;
}
/**
* SineNode.
*/
export declare class SineNode extends TypedNode {
readonly frequency: number;
readonly when: number;
readonly duration: number;
/**
* Unique identifier for the plugin kind this node represents.
*/
static PLUGIN_KIND: string;
/**
* Creates a new `number` mapper for the `frequency` param.
*/
private static FREQUENCY_CONFIG;
/**
* Creates a new `number` mapper for the `when` param.
*/
private static WHEN_CONFIG;
/**
* Creates a new `number` mapper for the `duration` param.
*/
private static DURATION_CONFIG;
/**
* Creates a new `SineNode` instance.
*/
constructor(id: string, frequency: number, when: number, duration: number);
/**
* `SineNode` factory.
*/
static create(config: SineNodeConfig, id?: string): SineNode;
/**
* Creates a new `SineNode` from a score `Node`.
*/
static from(node: Node): SineNode;
/**
* Configs for this node.
*/
getConfig(): SineNodeConfig;
/**
* Inputs for this node.
*/
getInputs(): Map<string, ContentType>;
/**
* Outputs for this node.
*/
getOutputs(): Map<string, ContentType>;
}
/**
* FilterNodeFilterType.
*/
export declare enum FilterNodeFilterType {
LOW_PASS = 'lowPass',
HIGH_PASS = 'highPass',
BAND_PASS = 'bandPass'
}
/**
* FilterNodeConfig.
*/
export interface FilterNodeConfig {
filterType?: FilterNodeFilterType;
}
/**
* FilterNode.
*/
export declare class FilterNode extends TypedNode {
readonly filterType: FilterNodeFilterType;
readonly lowCutoff: AudioParam;
readonly highCutoff: AudioParam;
/**
* Unique identifier for the plugin kind this node represents.
*/
static PLUGIN_KIND: string;
/**
* Creates a new `string` mapper for the `filterType` param.
*/
private static FILTER_TYPE_CONFIG;
/**
* `lowCutoff` param factory.
*/
private static LOW_CUTOFF_PARAM;
/**
* `highCutoff` param factory.
*/
private static HIGH_CUTOFF_PARAM;
/**
* Creates a new `FilterNode` instance.
*/
constructor(
id: string,
filterType: FilterNodeFilterType,
lowCutoff: AudioParam,
highCutoff: AudioParam
);
/**
* `FilterNode` factory.
*/
static create(config: FilterNodeConfig, id?: string): FilterNode;
/**
* Creates a new `FilterNode` from a score `Node`.
*/
static from(node: Node): FilterNode;
/**
* Configs for this node.
*/
getConfig(): FilterNodeConfig;
/**
* Params for this node.
*/
getParams(): {
[key: string]: Command[];
};
/**
* Inputs for this node.
*/
getInputs(): Map<string, ContentType>;
/**
* Outputs for this node.
*/
getOutputs(): Map<string, ContentType>;
}
/**
* CompressorNodeDetectionMode.
*/
export declare enum CompressorNodeDetectionMode {
MAX = 'max',
RMS = 'rms'
}
/**
* CompressorNodeKneeMode.
*/
export declare enum CompressorNodeKneeMode {
HARD = 'hard',
SOFT = 'soft'
}
/**
* CompressorNodeConfig.
*/
export interface CompressorNodeConfig {
detectionMode?: CompressorNodeDetectionMode;
kneeMode?: CompressorNodeKneeMode;
cutoffs?: number[];
}
/**
* CompressorNode.
*/
export declare class CompressorNode extends TypedNode {
readonly detectionMode: CompressorNodeDetectionMode;
readonly kneeMode: CompressorNodeKneeMode;
readonly cutoffs: number[];
readonly thresholdDb: AudioParam;
readonly kneeDb: AudioParam;
readonly ratioDb: AudioParam;
readonly attack: AudioParam;
readonly release: AudioParam;
/**
* Unique identifier for the plugin kind this node represents.
*/
static PLUGIN_KIND: string;
/**
* Creates a new `string` mapper for the `detectionMode` param.
*/
private static DETECTION_MODE_CONFIG;
/**
* Creates a new `string` mapper for the `kneeMode` param.
*/
private static KNEE_MODE_CONFIG;
/**
* Creates a new `number[]` mapper for the `cutoffs` param.
*/
private static CUTOFFS_CONFIG;
/**
* `thresholdDb` param factory.
*/
private static THRESHOLD_DB_PARAM;
/**
* `kneeDb` param factory.
*/
private static KNEE_DB_PARAM;
/**
* `ratioDb` param factory.
*/
private static RATIO_DB_PARAM;
/**
* `attack` param factory.
*/
private static ATTACK_PARAM;
/**
* `release` param factory.
*/
private static RELEASE_PARAM;
/**
* Creates a new `CompressorNode` instance.
*/
constructor(
id: string,
detectionMode: CompressorNodeDetectionMode,
kneeMode: CompressorNodeKneeMode,
cutoffs: number[],
thresholdDb: AudioParam,
kneeDb: AudioParam,
ratioDb: AudioParam,
attack: AudioParam,
release: AudioParam
);
/**
* `CompressorNode` factory.
*/
static create(config: CompressorNodeConfig, id?: string): CompressorNode;
/**
* Creates a new `CompressorNode` from a score `Node`.
*/
static from(node: Node): CompressorNode;
/**
* Configs for this node.
*/
getConfig(): CompressorNodeConfig;
/**
* Params for this node.
*/
getParams(): {
[key: string]: Command[];
};
/**
* Inputs for this node.
*/
getInputs(): Map<string, ContentType>;
/**
* Outputs for this node.
*/
getOutputs(): Map<string, ContentType>;
}
/**
* ExpanderNodeDetectionMode.
*/
export declare enum ExpanderNodeDetectionMode {
MAX = 'max',
RMS = 'rms'
}
/**
* ExpanderNodeKneeMode.
*/
export declare enum ExpanderNodeKneeMode {
HARD = 'hard',
SOFT = 'soft'
}
/**
* ExpanderNodeConfig.
*/
export interface ExpanderNodeConfig {
detectionMode?: ExpanderNodeDetectionMode;
kneeMode?: ExpanderNodeKneeMode;
cutoffs?: number[];
}
/**
* ExpanderNode.
*/
export declare class ExpanderNode extends TypedNode {
readonly detectionMode: ExpanderNodeDetectionMode;
readonly kneeMode: ExpanderNodeKneeMode;
readonly cutoffs: number[];
readonly thresholdDb: AudioParam;
readonly kneeDb: AudioParam;
readonly ratioDb: AudioParam;
readonly attack: AudioParam;
readonly release: AudioParam;
/**
* Unique identifier for the plugin kind this node represents.
*/
static PLUGIN_KIND: string;
/**
* Creates a new `string` mapper for the `detectionMode` param.
*/
private static DETECTION_MODE_CONFIG;
/**
* Creates a new `string` mapper for the `kneeMode` param.
*/
private static KNEE_MODE_CONFIG;
/**
* Creates a new `number[]` mapper for the `cutoffs` param.
*/
private static CUTOFFS_CONFIG;
/**
* `thresholdDb` param factory.
*/
private static THRESHOLD_DB_PARAM;
/**
* `kneeDb` param factory.
*/
private static KNEE_DB_PARAM;
/**
* `ratioDb` param factory.
*/
private static RATIO_DB_PARAM;
/**
* `attack` param factory.
*/
private static ATTACK_PARAM;
/**
* `release` param factory.
*/
private static RELEASE_PARAM;
/**
* Creates a new `ExpanderNode` instance.
*/
constructor(
id: string,
detectionMode: ExpanderNodeDetectionMode,
kneeMode: ExpanderNodeKneeMode,
cutoffs: number[],
thresholdDb: AudioParam,
kneeDb: AudioParam,
ratioDb: AudioParam,
attack: AudioParam,
release: AudioParam
);
/**
* `ExpanderNode` factory.
*/
static create(config: ExpanderNodeConfig, id?: string): ExpanderNode;
/**
* Creates a new `ExpanderNode` from a score `Node`.
*/
static from(node: Node): ExpanderNode;
/**
* Configs for this node.
*/
getConfig(): ExpanderNodeConfig;
/**
* Params for this node.
*/
getParams(): {
[key: string]: Command[];
};
/**
* Inputs for this node.
*/
getInputs(): Map<string, ContentType>;
/**
* Outputs for this node.
*/
getOutputs(): Map<string, ContentType>;
}
/**
* CompanderNodeDetectionMode.
*/
export declare enum CompanderNodeDetectionMode {
MAX = 'max',
RMS = 'rms'
}
/**
* CompanderNodeKneeMode.
*/
export declare enum CompanderNodeKneeMode {
HARD = 'hard',
SOFT = 'soft'
}
/**
* CompanderNodeConfig.
*/
export interface CompanderNodeConfig {
detectionMode?: CompanderNodeDetectionMode;
kneeMode?: CompanderNodeKneeMode;
cutoffs?: number[];
}
/**
* CompanderNode.
*/
export declare class CompanderNode extends TypedNode {
readonly detectionMode: CompanderNodeDetectionMode;
readonly kneeMode: CompanderNodeKneeMode;
readonly cutoffs: number[];
readonly compressorThresholdDb: AudioParam;
readonly compressorKneeDb: AudioParam;
readonly compressorRatioDb: AudioParam;
readonly expanderThresholdDb: AudioParam;
readonly expanderKneeDb: AudioParam;
readonly expanderRatioDb: AudioParam;
readonly attack: AudioParam;
readonly release: AudioParam;
/**
* Unique identifier for the plugin kind this node represents.
*/
static PLUGIN_KIND: string;
/**
* Creates a new `string` mapper for the `detectionMode` param.
*/
private static DETECTION_MODE_CONFIG;
/**
* Creates a new `string` mapper for the `kneeMode` param.
*/
private static KNEE_MODE_CONFIG;
/**
* Creates a new `number[]` mapper for the `cutoffs` param.
*/
private static CUTOFFS_CONFIG;
/**
* `compressorThresholdDb` param factory.
*/
private static COMPRESSOR_THRESHOLD_DB_PARAM;
/**
* `compressorKneeDb` param factory.
*/
private static COMPRESSOR_KNEE_DB_PARAM;
/**
* `compressorRatioDb` param factory.
*/
private static COMPRESSOR_RATIO_DB_PARAM;
/**
* `expanderThresholdDb` param factory.
*/
private static EXPANDER_THRESHOLD_DB_PARAM;
/**
* `expanderKneeDb` param factory.
*/
private static EXPANDER_KNEE_DB_PARAM;
/**
* `expanderRatioDb` param factory.
*/
private static EXPANDER_RATIO_DB_PARAM;
/**
* `attack` param factory.
*/
private static ATTACK_PARAM;
/**
* `release` param factory.
*/
private static RELEASE_PARAM;
/**
* Creates a new `CompanderNode` instance.
*/
constructor(
id: string,
detectionMode: CompanderNodeDetectionMode,
kneeMode: CompanderNodeKneeMode,
cutoffs: number[],
compressorThresholdDb: AudioParam,
compressorKneeDb: AudioParam,
compressorRatioDb: AudioParam,
expanderThresholdDb: AudioParam,
expanderKneeDb: AudioParam,
expanderRatioDb: AudioParam,
attack: AudioParam,
release: AudioParam
);
/**
* `CompanderNode` factory.
*/
static create(config: CompanderNodeConfig, id?: string): CompanderNode;
/**
* Creates a new `CompanderNode` from a score `Node`.
*/
static from(node: Node): CompanderNode;
/**
* Configs for this node.
*/
getConfig(): CompanderNodeConfig;
/**
* Params for this node.
*/
getParams(): {
[key: string]: Command[];
};
/**
* Inputs for this node.
*/
getInputs(): Map<string, ContentType>;
/**
* Outputs for this node.
*/
getOutputs(): Map<string, ContentType>;
}
/**
* Map of Node kinds to typed classes.
*/
export declare const NodeKinds: {
'com.nativeformat.plugin.eq.eq3band': typeof Eq3bandNode;
'com.nativeformat.plugin.file.file': typeof FileNode;
'com.nativeformat.plugin.noise.noise': typeof NoiseNode;
'com.nativeformat.plugin.noise.silence': typeof SilenceNode;
'com.nativeformat.plugin.time.loop': typeof LoopNode;
'com.nativeformat.plugin.time.stretch': typeof StretchNode;
'com.nativeformat.plugin.waa.delay': typeof DelayNode;
'com.nativeformat.plugin.waa.gain': typeof GainNode;
'com.nativeformat.plugin.wave.sine': typeof SineNode;
'com.nativeformat.plugin.eq.filter': typeof FilterNode;
'com.nativeformat.plugin.compressor.compressor': typeof CompressorNode;
'com.nativeformat.plugin.compressor.expander': typeof ExpanderNode;
'com.nativeformat.plugin.compressor.compander': typeof CompanderNode;
};
/**
* Computes the number of nanoseconds in the milliseconds given.
*/
export declare function millisToNanos(millis?: number): number;
/**
* Computes the number of nanoseconds in the seconds given.
*/
export declare function secondsToNanos(seconds?: number): number;
/**
* Computes the number of nanoseconds in the minutes given.
*/
export declare function minutesToNanos(minutes?: number): number; | the_stack |
import { Flowchart } from 'flowchart_class';
import { Rule, GFMap } from 'rule_class';
import _ from 'lodash';
import { Metric } from './metric_class';
import { $GF } from 'globals_class';
import { FlowchartCtrl } from './flowchart_ctrl';
/**
* Class FlowchartHandler
*/
export class FlowchartHandler {
$scope: ng.IScope;
$elem: any; //TODO: elem ?
parentDiv: HTMLDivElement;
ctrl: FlowchartCtrl; //TODO: ctrl ?
flowcharts: Flowchart[] = [];
currentFlowchart = 'Main'; // name of current Flowchart
data: gf.TFlowchartHandlerData;
firstLoad = true; // First load
changeSourceFlag = false; // Source changed
changeOptionFlag = true; // Options changed
changeDataFlag = false; // Data changed
changeGraphHoverFlag = false; // Graph Hover
changeRuleFlag = false; // rules changed
static defaultXml: string;
static defaultCsv: string;
onMapping: gf.TIOnMappingObj = {
active: false,
object: null,
value: null,
prop: 'id',
$scope: null,
};
mousedownTimeout = 0;
mousedown = 0;
onEdit = false; // editor open or not
editorWindow: Window | null = null; // Window draw.io editor
/**
* Creates an instance of FlowchartHandler to handle flowchart
* @param {ng.IScope} $scope - angular scope
* @param {any} elem - angular elem
* @param {TODO:FlowchartCtrl} ctrl - ctrlPanel
* @param {*} data - Empty data to store
* @memberof FlowchartHandler
*/
constructor($scope: ng.IScope, elem: any, ctrl: any, data: gf.TFlowchartHandlerData) {
FlowchartHandler.getDefaultDioGraph();
this.$scope = $scope;
this.$elem = elem.find('.flowchart-panel__chart');
this.parentDiv = this.$elem[0];
this.ctrl = ctrl;
this.data = data;
// Events Render
ctrl.events.on('render', () => {
this.render();
});
document.body.onmousedown = () => {
this.mousedown = 0;
window.clearInterval(this.mousedownTimeout);
this.mousedownTimeout = window.setInterval(() => {
this.mousedown += 1;
}, 200);
};
document.body.onmouseup = () => {
this.mousedown = 0;
window.clearInterval(this.mousedownTimeout);
};
}
static getDefaultData(): gf.TFlowchartHandlerData {
return {
flowcharts: [],
};
}
/**
* import data into
*
* @returns {this}
* @param {Object} obj
* @memberof FlowchartHandler
*/
import(obj: any): this {
$GF.log.info('FlowchartHandler.import()');
this.flowcharts = [];
if (obj !== undefined && obj !== null) {
// For version 0.5.0 and under
let tmpFc: gf.TFlowchartData[];
if (Array.isArray(obj)) {
tmpFc = obj;
} else {
tmpFc = obj.flowcharts;
}
// import data
tmpFc.forEach((fcData: gf.TFlowchartData) => {
this.addFlowchart(fcData.name).import(fcData);
});
}
return this;
}
/**
* Reset/empty flowcharts, rules and children
*
* @returns {this}
* @param {Object} obj
* @memberof FlowchartHandler
*/
clear(): this {
this.flowcharts.forEach((fc: Flowchart) => {
fc.clear();
});
this.flowcharts = [];
this.data.flowcharts = [];
return this;
}
/**
* Return default xml source graph
*
* @static
* @returns {string}
* @memberof FlowchartHandler
*/
static getDefaultDioGraph(): string {
let result = FlowchartHandler.defaultXml;
if (!result) {
const url = `${$GF.plugin.getRootPath()}${$GF.CONSTANTS.CONF_FILE_DEFAULTDIO}`;
result = $GF.utils.$loadFile(url);
// $.ajax({
// type: 'GET',
// url: url,
// async: false,
// success: data => {
// FlowchartHandler.defaultXml = data;
// result = data;
// },
// error: () => {
// alert('Error when download ' + url);
// },
// });
}
return result;
}
/**
* Return default xml source graph
*
* @static
* @returns {string}
* @memberof FlowchartHandler
*/
static getDefaultCsvGraph(): string {
let result = FlowchartHandler.defaultCsv;
if (!result) {
const url = `${$GF.plugin.getRootPath()}${$GF.CONSTANTS.CONF_FILE_DEFAULTCSV}`;
result = $GF.utils.$loadFile(url);
// $.ajax({
// type: 'GET',
// url: url,
// async: false,
// success: data => {
// FlowchartHandler.defaultCsv = data;
// result = data;
// },
// error: () => {
// alert('Error when download ' + url);
// },
// });
}
return result;
}
/**
* Get flowchart with name
*
* @param {string} name
* @returns {Flowchart}
* @memberof FlowchartHandler
*/
getFlowchart(name?: string): Flowchart {
//TODO: When multi flowchart
return this.flowcharts[0];
}
/**
* Return array of flowchart
*
* @returns {Flowchart[]} Array of flowchart
* @memberof FlowchartHandler
*/
getFlowcharts(): Flowchart[] {
return this.flowcharts;
}
/**
* Return number of flowchart
*
* @returns {number} Nulber of flowchart
* @memberof FlowchartHandler
*/
countFlowcharts(): number {
if (this.flowcharts !== undefined && Array.isArray(this.flowcharts)) {
return this.flowcharts.length;
}
return 0;
}
/**
* Create a div container for graph
*
* @returns {HTMLDivElement}
* @memberof FlowchartHandler
*/
createContainer(): HTMLDivElement {
const div = document.createElement('div');
div.style.margin = 'auto';
div.style.position = 'relative';
div.style.width = '100%';
div.style.height = '100%';
div.style.touchAction = 'none';
div.style.border = 'none';
div.style.cursor = 'default';
div.style.right = '0px';
div.style.left = '0px';
div.style.bottom = '0px';
div.style.top = '0px';
// div.style.overflow = 'none';
this.parentDiv.appendChild(div);
return div;
// const $container: any = $(`<div class="geDiagramContainer" id="flowchart_${$GF.utils.uniqueID()}" style="right: 0px; border: none; left: 0px; top: 0px; bottom: 0px; touch-action: none; cursor: default; overflow: auto;"></div>`);
// const $container: any = $(`<div class="geDiagramContainer" id="flowchart_${$GF.utils.uniqueID()}" style="margin: auto; position: relative; width: 100%; height: 100%; touch-action: none;border: none;cursor: default"></div>`);
// GOOD : const $container: any = $(`<div class="geDiagramContainer" id="flowchart_${$GF.utils.uniqueID()}" style="margin:auto;position:relative;width:100%;height:100%" style="right: 0px; border: none; left: 0px; top: 0px; bottom: 0px; touch-action: none; cursor: default; overflow: auto;"></div>`);
// const $container: any = $(`<div class="geDiagramContainer" id="flowchart_${$GF.utils.uniqueID()}" tabindex="0" style="right: 0px; border: none; left: 0px; top: 0px; bottom: 0px; touch-action: none; overflow: auto; cursor: default;">`);
// this.$elem.html($container);
// return $container[0];
}
/**
* Add a flowchart
*
* @param {string} name
* @returns {Flowchart}
* @memberof FlowchartHandler
*/
addFlowchart(name: string): Flowchart {
const trc = $GF.trace.before(this.constructor.name + '.' + 'addFlowchart()');
const container = this.createContainer();
const data = Flowchart.getDefaultData();
const flowchart = new Flowchart(name, container, this.ctrl, data);
// flowchart.init();
this.data.flowcharts.push(data);
this.flowcharts.push(flowchart);
trc.after();
return flowchart;
}
/**
* Render for draw
*
* @memberof FlowchartHandler
*/
async render() {
const trc = $GF.trace.before(this.constructor.name + '.' + 'render()');
// not repeat render if mouse down
if (!this.mousedown) {
let optionsFlag = true;
const self = this;
// SOURCE
if (self.changeSourceFlag) {
self.load();
self.changeSourceFlag = false;
self.changeRuleFlag = true;
optionsFlag = true;
// this.ctrl.editModeFalse();
}
// OPTIONS
if (self.changeOptionFlag) {
self.setOptions();
self.changeOptionFlag = false;
optionsFlag = true;
}
// RULES or DATAS
if (self.changeRuleFlag || self.changeDataFlag || self.changeGraphHoverFlag) {
if (self.ctrl.rulesHandler && self.ctrl.metricHandler) {
const rules = self.ctrl.rulesHandler.getRules();
const metrics = self.ctrl.metricHandler.getMetrics();
// Change to async to optimize
self.async_refreshStates(rules, metrics);
}
self.changeDataFlag = false;
optionsFlag = false;
self.changeGraphHoverFlag = false;
}
// OTHER : Resize, OnLoad
if (optionsFlag || self.firstLoad) {
self.applyOptions();
optionsFlag = false;
self.firstLoad = false;
}
// this.refresh();
}
this.ctrl.renderingCompleted();
trc.after();
}
/**
* Flag source change
*
* @returns {this}
* @memberof FlowchartHandler
*/
sourceChanged(): this {
this.changeSourceFlag = true;
return this;
}
/**
* Flag options change
*
* @returns {this}
* @memberof FlowchartHandler
*/
optionChanged(): this {
this.changeOptionFlag = true;
return this;
}
/**
* Flag rule change
*
* @returns {this}
* @memberof FlowchartHandler
*/
ruleChanged(): this {
this.changeRuleFlag = true;
return this;
}
/**
* Flag data change
*
* @returns {this}
* @memberof FlowchartHandler
*/
dataChanged(): this {
this.changeDataFlag = true;
return this;
}
/**
* Flag data Graph-Hover change
*
* @returns {this}
* @memberof FlowchartHandler
*/
graphHoverChanged(): this {
this.changeGraphHoverFlag = true;
return this;
}
/**
* Apply options on graphs
*
* @returns {this}
* @memberof FlowchartHandler
*/
applyOptions(): this {
const trc = $GF.trace.before(this.constructor.name + '.' + 'applyOptions()');
this.flowcharts.forEach(flowchart => {
flowchart.applyOptions();
});
trc.after();
return this;
}
/**
* Call refreshStates asynchronously
*
* @param {Rule[]} rules
* @param {Metric[]} metrics
* @memberof FlowchartHandler
*/
async_refreshStates(rules: Rule[], metrics: Metric[]) {
const trc = $GF.trace.before(this.constructor.name + '.' + 'async_refreshStates()');
this.refreshStates(rules, metrics);
trc.after();
}
/**
* Refresh rules according new rules or data
*
* @param {Rule[]} rules
* @param {Metric[]} metrics
* @returns {this}
* @memberof FlowchartHandler
*/
refreshStates(rules: Rule[], metrics: Metric[]): this {
const trc = $GF.trace.before(this.constructor.name + '.' + 'refreshStates()');
if (this.changeRuleFlag) {
this.updateStates(rules);
this.changeRuleFlag = false;
}
this.setStates(rules, metrics);
this.applyStates();
trc.after();
return this;
}
/**
* Refresh all flowchart
*
* @returns {this}
* @memberof FlowchartHandler
*/
refresh(): this {
this.flowcharts.forEach(flowchart => {
flowchart.refresh();
});
return this;
}
/**
* Change states of cell according to rules and metrics
*
* @param {Rule[]} rules
* @param {any[]} metrics
* @returns {this}
* @memberof FlowchartHandler
*/
setStates(rules: Rule[], metrics: any[]): this {
const trc = $GF.trace.before(this.constructor.name + '.' + 'setStates()');
this.flowcharts.forEach(flowchart => {
flowchart.setStates(rules, metrics);
});
trc.after();
return this;
}
/**
* Update states with rule
*
* @param {Rule[]} rules
* @returns {this}
* @memberof FlowchartHandler
*/
updateStates(rules: Rule[]): this {
const trc = $GF.trace.before(this.constructor.name + '.' + 'updateStates()');
this.flowcharts.forEach(flowchart => {
flowchart.updateStates(rules);
});
trc.after();
return this;
}
/**
* Apply state of cell after setStates
*
* @returns {this}
* @memberof FlowchartHandler
*/
applyStates(): this {
const trc = $GF.trace.before(this.constructor.name + '.' + 'applyStates()');
new Promise(() => {
this.flowcharts.forEach(flowchart => {
flowchart.applyStates();
});
}).then(() => {
this.refresh();
});
trc.after();
return this;
}
/**
* Set and apply options
*
* @returns {this}
* @memberof FlowchartHandler
*/
setOptions(): this {
const trc = $GF.trace.before(this.constructor.name + '.' + 'setOptions()');
this.flowcharts.forEach(flowchart => {
flowchart.setOptions();
});
trc.after();
return this;
}
/**
* (re)draw graph
*
* @returns {this}
* @memberof FlowchartHandler
*/
draw(): this {
const trc = $GF.trace.before(this.constructor.name + '.' + 'draw()');
this.flowcharts.forEach(flowchart => {
flowchart.redraw();
});
trc.after();
return this;
}
/**
* (re)load graph
*
* @returns {this}
* @memberof FlowchartHandler
*/
load(): this {
const trc = $GF.trace.before(this.constructor.name + '.' + 'draw()');
this.flowcharts.forEach(flowchart => {
flowchart.reload();
});
trc.after();
return this;
}
/**
* Active option link/map
*
* @param {Object} objToMap
* @memberof FlowchartHandler
*/
setMap(objToMap: GFMap, prop: gf.TPropertieKey = 'id'): this {
const flowchart = this.getFlowchart(this.currentFlowchart);
this.onMapping.active = true;
this.onMapping.object = objToMap;
this.onMapping.value = objToMap.getId();
this.onMapping.$scope = this.$scope;
this.onMapping.prop = prop;
flowchart.setMap(this.onMapping);
return this;
}
/**
* Desactivate option
*
* @memberof FlowchartHandler
*/
unsetMap(): this {
const flowchart = this.getFlowchart(this.currentFlowchart);
this.onMapping.active = false;
this.onMapping.object = undefined;
this.onMapping.value = '';
flowchart.unsetMap();
return this;
}
/**
* Return true if mapping object is active
*
* @param {properties} objToMap
* @returns true - true if mapping mode
* @memberof FlowchartHandler
*/
isMapping(objToMap: GFMap): boolean {
if (objToMap === undefined || objToMap == null) {
return this.onMapping.active;
}
if (this.onMapping.active === true && objToMap === this.onMapping.object) {
return true;
}
return false;
}
/**
* Wait for draw.io answer
*
* @private
* @param {MessageEvent} event
* @memberof FlowchartHandler
*/
listenMessage(event: any) {
if (event.data === 'ready') {
// send xml
// if (event.source) {
// if (!(event.source instanceof MessagePort) && !(event.source instanceof ServiceWorker)) {
event.source.postMessage(this.getFlowchart(this.currentFlowchart).data.xml, event.origin);
// }
// }
} else {
if (this.onEdit && event.data !== undefined && event.data.length > 0) {
this.getFlowchart(this.currentFlowchart).redraw(event.data);
this.sourceChanged();
this.$scope.$apply();
this.render();
}
if ((this.onEdit && event.data !== undefined) || event.data.length === 0) {
if (this.editorWindow) {
this.editorWindow.close();
}
this.onEdit = false;
window.removeEventListener('message', this.listenMessage.bind(this), false);
}
}
}
/**
* Open graph in draw.io
*
* @memberof FlowchartHandler
*/
openDrawEditor(name?: string) {
const urlEditor = this.getFlowchart(name).getUrlEditor();
const theme = this.getFlowchart(name).getThemeEditor();
const urlParams = `${urlEditor}?embed=1&spin=1&libraries=1&ui=${theme}&src=grafana`;
this.editorWindow = window.open(urlParams, 'MxGraph Editor', 'width=1280, height=720');
this.onEdit = true;
window.addEventListener('message', this.listenMessage.bind(this), false);
}
/**
* Get flowchart names
*
* @returns {string[]}
* @memberof FlowchartHandler
*/
getFlowchartNames(): string[] {
return this.flowcharts.map(f => f.data.name);
}
} | the_stack |
import { GlobalProps } from 'ojs/ojvcomponent';
import { ComponentChildren } from 'preact';
import { DataProvider } from '../ojdataprovider';
import { dvtBaseComponent, dvtBaseComponentEventMap, dvtBaseComponentSettableProperties } from '../ojdvt-base';
import { JetElement, JetSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..';
export interface ojTreemap<K, D extends ojTreemap.Node<K> | any> extends dvtBaseComponent<ojTreemapSettableProperties<K, D>> {
animationDuration?: number;
animationOnDataChange?: 'auto' | 'none';
animationOnDisplay?: 'auto' | 'none';
animationUpdateColor?: string;
as?: string;
colorLabel?: string;
data: DataProvider<K, D> | null;
displayLevels?: number;
drilling?: 'on' | 'off';
groupGaps?: 'all' | 'none' | 'outer';
hiddenCategories?: string[];
highlightMatch?: 'any' | 'all';
highlightMode?: 'categories' | 'descendants';
highlightedCategories?: string[];
hoverBehavior?: 'dim' | 'none';
hoverBehaviorDelay?: number;
isolatedNode?: any;
layout?: 'sliceAndDiceHorizontal' | 'sliceAndDiceVertical' | 'squarified';
nodeContent?: {
renderer: ((context: ojTreemap.NodeContentContext<K, D>) => ({
insert: Element | string;
}));
};
nodeDefaults?: {
groupLabelDisplay?: 'node' | 'off' | 'header';
header?: {
backgroundColor?: string;
borderColor?: string;
hoverBackgroundColor?: string;
hoverInnerColor?: string;
hoverOuterColor?: string;
isolate?: 'off' | 'on';
labelHalign?: 'center' | 'end' | 'start';
labelStyle?: Partial<CSSStyleDeclaration>;
selectedBackgroundColor?: string;
selectedInnerColor?: string;
selectedOuterColor?: string;
useNodeColor?: 'on' | 'off';
};
hoverColor?: string;
labelDisplay?: 'off' | 'node';
labelHalign?: 'start' | 'end' | 'center';
labelMinLength?: number;
labelStyle?: Partial<CSSStyleDeclaration>;
labelValign?: 'top' | 'bottom' | 'center';
selectedInnerColor?: string;
selectedOuterColor?: string;
};
nodeSeparators?: 'bevels' | 'gaps';
rootNode?: any;
selection?: any[];
selectionMode?: 'none' | 'single' | 'multiple';
sizeLabel?: string;
sorting?: 'on' | 'off';
tooltip?: {
renderer: ((context: ojTreemap.TooltipContext<K, D>) => ({
insert: Element | string;
} | {
preventDefault: boolean;
}));
};
touchResponse?: 'touchStart' | 'auto';
translations: {
componentName?: string;
labelAndValue?: string;
labelClearSelection?: string;
labelColor?: string;
labelCountWithTotal?: string;
labelDataVisualization?: string;
labelInvalidData?: string;
labelNoData?: string;
labelSize?: string;
stateCollapsed?: string;
stateDrillable?: string;
stateExpanded?: string;
stateHidden?: string;
stateIsolated?: string;
stateMaximized?: string;
stateMinimized?: string;
stateSelected?: string;
stateUnselected?: string;
stateVisible?: string;
tooltipIsolate?: string;
tooltipRestore?: string;
};
addEventListener<T extends keyof ojTreemapEventMap<K, D>>(type: T, listener: (this: HTMLElement, ev: ojTreemapEventMap<K, D>[T]) => any, options?: (boolean | AddEventListenerOptions)): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void;
getProperty<T extends keyof ojTreemapSettableProperties<K, D>>(property: T): ojTreemap<K, D>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojTreemapSettableProperties<K, D>>(property: T, value: ojTreemapSettableProperties<K, D>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojTreemapSettableProperties<K, D>>): void;
setProperties(properties: ojTreemapSettablePropertiesLenient<K, D>): void;
getContextByNode(node: Element): ojTreemap.NodeContext | null;
}
export namespace ojTreemap {
interface ojBeforeDrill<K, D> extends CustomEvent<{
data: Node<K>;
id: K;
itemData: D;
[propName: string]: any;
}> {
}
interface ojDrill<K, D> extends CustomEvent<{
data: Node<K>;
id: K;
itemData: D;
[propName: string]: any;
}> {
}
// tslint:disable-next-line interface-over-type-literal
type animationDurationChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["animationDuration"]>;
// tslint:disable-next-line interface-over-type-literal
type animationOnDataChangeChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["animationOnDataChange"]>;
// tslint:disable-next-line interface-over-type-literal
type animationOnDisplayChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["animationOnDisplay"]>;
// tslint:disable-next-line interface-over-type-literal
type animationUpdateColorChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["animationUpdateColor"]>;
// tslint:disable-next-line interface-over-type-literal
type asChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["as"]>;
// tslint:disable-next-line interface-over-type-literal
type colorLabelChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["colorLabel"]>;
// tslint:disable-next-line interface-over-type-literal
type dataChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["data"]>;
// tslint:disable-next-line interface-over-type-literal
type displayLevelsChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["displayLevels"]>;
// tslint:disable-next-line interface-over-type-literal
type drillingChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["drilling"]>;
// tslint:disable-next-line interface-over-type-literal
type groupGapsChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["groupGaps"]>;
// tslint:disable-next-line interface-over-type-literal
type hiddenCategoriesChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["hiddenCategories"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightMatchChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["highlightMatch"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightModeChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["highlightMode"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightedCategoriesChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["highlightedCategories"]>;
// tslint:disable-next-line interface-over-type-literal
type hoverBehaviorChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["hoverBehavior"]>;
// tslint:disable-next-line interface-over-type-literal
type hoverBehaviorDelayChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["hoverBehaviorDelay"]>;
// tslint:disable-next-line interface-over-type-literal
type isolatedNodeChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["isolatedNode"]>;
// tslint:disable-next-line interface-over-type-literal
type layoutChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["layout"]>;
// tslint:disable-next-line interface-over-type-literal
type nodeContentChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["nodeContent"]>;
// tslint:disable-next-line interface-over-type-literal
type nodeDefaultsChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["nodeDefaults"]>;
// tslint:disable-next-line interface-over-type-literal
type nodeSeparatorsChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["nodeSeparators"]>;
// tslint:disable-next-line interface-over-type-literal
type rootNodeChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["rootNode"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["selection"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionModeChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["selectionMode"]>;
// tslint:disable-next-line interface-over-type-literal
type sizeLabelChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["sizeLabel"]>;
// tslint:disable-next-line interface-over-type-literal
type sortingChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["sorting"]>;
// tslint:disable-next-line interface-over-type-literal
type tooltipChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["tooltip"]>;
// tslint:disable-next-line interface-over-type-literal
type touchResponseChanged<K, D extends Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["touchResponse"]>;
//------------------------------------------------------------
// Start: generated events for inherited properties
//------------------------------------------------------------
// tslint:disable-next-line interface-over-type-literal
type trackResizeChanged<K, D extends Node<K> | any> = dvtBaseComponent.trackResizeChanged<ojTreemapSettableProperties<K, D>>;
// tslint:disable-next-line interface-over-type-literal
type DataContext = {
color: string;
label: string;
selected: boolean;
size: number;
tooltip: string;
};
// tslint:disable-next-line interface-over-type-literal
type Node<K, D = any> = {
categories?: string[];
color?: string;
drilling?: 'inherit' | 'off' | 'on';
groupLabelDisplay?: string;
header?: {
isolate?: 'off' | 'on';
labelHalign?: 'center' | 'end' | 'start';
labelStyle?: Partial<CSSStyleDeclaration>;
useNodeColor?: 'off' | 'on';
};
id?: K;
label?: string;
labelDisplay?: 'node' | 'off';
labelHalign?: 'center' | 'end' | 'start';
labelStyle?: Partial<CSSStyleDeclaration>;
labelValign?: 'bottom' | 'center' | 'top';
nodes?: Array<Node<K>>;
pattern?: 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' | 'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none' | 'smallChecker' | 'smallCrosshatch' |
'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle';
selectable?: 'auto' | 'off';
shortDesc?: (string | ((context: NodeShortDescContext<K, D>) => string));
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
value: number;
};
// tslint:disable-next-line interface-over-type-literal
type NodeContentContext<K, D> = {
bounds: {
height: number;
width: number;
x: number;
y: number;
};
componentElement: Element;
data: Node<K>;
id: K;
itemData: D;
};
// tslint:disable-next-line interface-over-type-literal
type NodeContext = {
indexPath: number[];
subId: string;
};
// tslint:disable-next-line interface-over-type-literal
type NodeShortDescContext<K, D> = {
data: Node<K>;
id: K;
itemData: D;
label: string;
value: number;
};
// tslint:disable-next-line interface-over-type-literal
type NodeTemplateContext = {
componentElement: Element;
data: object;
index: number;
key: any;
parentData: any[];
parentKey: any;
};
// tslint:disable-next-line interface-over-type-literal
type TooltipContext<K, D> = {
color: string;
componentElement: Element;
data: Node<K>;
id: K;
itemData: D;
label: string;
parentElement: Element;
value: number;
};
}
export interface ojTreemapEventMap<K, D extends ojTreemap.Node<K> | any> extends dvtBaseComponentEventMap<ojTreemapSettableProperties<K, D>> {
'ojBeforeDrill': ojTreemap.ojBeforeDrill<K, D>;
'ojDrill': ojTreemap.ojDrill<K, D>;
'animationDurationChanged': JetElementCustomEvent<ojTreemap<K, D>["animationDuration"]>;
'animationOnDataChangeChanged': JetElementCustomEvent<ojTreemap<K, D>["animationOnDataChange"]>;
'animationOnDisplayChanged': JetElementCustomEvent<ojTreemap<K, D>["animationOnDisplay"]>;
'animationUpdateColorChanged': JetElementCustomEvent<ojTreemap<K, D>["animationUpdateColor"]>;
'asChanged': JetElementCustomEvent<ojTreemap<K, D>["as"]>;
'colorLabelChanged': JetElementCustomEvent<ojTreemap<K, D>["colorLabel"]>;
'dataChanged': JetElementCustomEvent<ojTreemap<K, D>["data"]>;
'displayLevelsChanged': JetElementCustomEvent<ojTreemap<K, D>["displayLevels"]>;
'drillingChanged': JetElementCustomEvent<ojTreemap<K, D>["drilling"]>;
'groupGapsChanged': JetElementCustomEvent<ojTreemap<K, D>["groupGaps"]>;
'hiddenCategoriesChanged': JetElementCustomEvent<ojTreemap<K, D>["hiddenCategories"]>;
'highlightMatchChanged': JetElementCustomEvent<ojTreemap<K, D>["highlightMatch"]>;
'highlightModeChanged': JetElementCustomEvent<ojTreemap<K, D>["highlightMode"]>;
'highlightedCategoriesChanged': JetElementCustomEvent<ojTreemap<K, D>["highlightedCategories"]>;
'hoverBehaviorChanged': JetElementCustomEvent<ojTreemap<K, D>["hoverBehavior"]>;
'hoverBehaviorDelayChanged': JetElementCustomEvent<ojTreemap<K, D>["hoverBehaviorDelay"]>;
'isolatedNodeChanged': JetElementCustomEvent<ojTreemap<K, D>["isolatedNode"]>;
'layoutChanged': JetElementCustomEvent<ojTreemap<K, D>["layout"]>;
'nodeContentChanged': JetElementCustomEvent<ojTreemap<K, D>["nodeContent"]>;
'nodeDefaultsChanged': JetElementCustomEvent<ojTreemap<K, D>["nodeDefaults"]>;
'nodeSeparatorsChanged': JetElementCustomEvent<ojTreemap<K, D>["nodeSeparators"]>;
'rootNodeChanged': JetElementCustomEvent<ojTreemap<K, D>["rootNode"]>;
'selectionChanged': JetElementCustomEvent<ojTreemap<K, D>["selection"]>;
'selectionModeChanged': JetElementCustomEvent<ojTreemap<K, D>["selectionMode"]>;
'sizeLabelChanged': JetElementCustomEvent<ojTreemap<K, D>["sizeLabel"]>;
'sortingChanged': JetElementCustomEvent<ojTreemap<K, D>["sorting"]>;
'tooltipChanged': JetElementCustomEvent<ojTreemap<K, D>["tooltip"]>;
'touchResponseChanged': JetElementCustomEvent<ojTreemap<K, D>["touchResponse"]>;
'trackResizeChanged': JetElementCustomEvent<ojTreemap<K, D>["trackResize"]>;
}
export interface ojTreemapSettableProperties<K, D extends ojTreemap.Node<K> | any> extends dvtBaseComponentSettableProperties {
animationDuration?: number;
animationOnDataChange?: 'auto' | 'none';
animationOnDisplay?: 'auto' | 'none';
animationUpdateColor?: string;
as?: string;
colorLabel?: string;
data: DataProvider<K, D> | null;
displayLevels?: number;
drilling?: 'on' | 'off';
groupGaps?: 'all' | 'none' | 'outer';
hiddenCategories?: string[];
highlightMatch?: 'any' | 'all';
highlightMode?: 'categories' | 'descendants';
highlightedCategories?: string[];
hoverBehavior?: 'dim' | 'none';
hoverBehaviorDelay?: number;
isolatedNode?: any;
layout?: 'sliceAndDiceHorizontal' | 'sliceAndDiceVertical' | 'squarified';
nodeContent?: {
renderer: ((context: ojTreemap.NodeContentContext<K, D>) => ({
insert: Element | string;
}));
};
nodeDefaults?: {
groupLabelDisplay?: 'node' | 'off' | 'header';
header?: {
backgroundColor?: string;
borderColor?: string;
hoverBackgroundColor?: string;
hoverInnerColor?: string;
hoverOuterColor?: string;
isolate?: 'off' | 'on';
labelHalign?: 'center' | 'end' | 'start';
labelStyle?: Partial<CSSStyleDeclaration>;
selectedBackgroundColor?: string;
selectedInnerColor?: string;
selectedOuterColor?: string;
useNodeColor?: 'on' | 'off';
};
hoverColor?: string;
labelDisplay?: 'off' | 'node';
labelHalign?: 'start' | 'end' | 'center';
labelMinLength?: number;
labelStyle?: Partial<CSSStyleDeclaration>;
labelValign?: 'top' | 'bottom' | 'center';
selectedInnerColor?: string;
selectedOuterColor?: string;
};
nodeSeparators?: 'bevels' | 'gaps';
rootNode?: any;
selection?: any[];
selectionMode?: 'none' | 'single' | 'multiple';
sizeLabel?: string;
sorting?: 'on' | 'off';
tooltip?: {
renderer: ((context: ojTreemap.TooltipContext<K, D>) => ({
insert: Element | string;
} | {
preventDefault: boolean;
}));
};
touchResponse?: 'touchStart' | 'auto';
translations: {
componentName?: string;
labelAndValue?: string;
labelClearSelection?: string;
labelColor?: string;
labelCountWithTotal?: string;
labelDataVisualization?: string;
labelInvalidData?: string;
labelNoData?: string;
labelSize?: string;
stateCollapsed?: string;
stateDrillable?: string;
stateExpanded?: string;
stateHidden?: string;
stateIsolated?: string;
stateMaximized?: string;
stateMinimized?: string;
stateSelected?: string;
stateUnselected?: string;
stateVisible?: string;
tooltipIsolate?: string;
tooltipRestore?: string;
};
}
export interface ojTreemapSettablePropertiesLenient<K, D extends ojTreemap.Node<K> | any> extends Partial<ojTreemapSettableProperties<K, D>> {
[key: string]: any;
}
export interface ojTreemapNode<K = any, D = any> extends dvtBaseComponent<ojTreemapNodeSettableProperties<K, D>> {
categories?: string[];
color?: string;
drilling?: 'on' | 'off' | 'inherit';
groupLabelDisplay?: 'node' | 'off' | 'header';
header?: {
isolate?: 'off' | 'on';
labelHalign?: 'center' | 'end' | 'start';
labelStyle?: Partial<CSSStyleDeclaration>;
useNodeColor?: 'on' | 'off';
};
label?: string;
labelDisplay?: 'off' | 'node';
labelHalign?: 'start' | 'end' | 'center';
labelStyle?: Partial<CSSStyleDeclaration>;
labelValign?: 'top' | 'bottom' | 'center';
pattern?: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' |
'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none';
selectable?: 'off' | 'auto';
shortDesc?: (string | ((context: ojTreemap.NodeShortDescContext<K, D>) => string));
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
value: number;
addEventListener<T extends keyof ojTreemapNodeEventMap<K, D>>(type: T, listener: (this: HTMLElement, ev: ojTreemapNodeEventMap<K, D>[T]) => any, options?: (boolean |
AddEventListenerOptions)): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void;
getProperty<T extends keyof ojTreemapNodeSettableProperties<K, D>>(property: T): ojTreemapNode<K, D>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojTreemapNodeSettableProperties<K, D>>(property: T, value: ojTreemapNodeSettableProperties<K, D>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojTreemapNodeSettableProperties<K, D>>): void;
setProperties(properties: ojTreemapNodeSettablePropertiesLenient<K, D>): void;
}
export namespace ojTreemapNode {
// tslint:disable-next-line interface-over-type-literal
type categoriesChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["categories"]>;
// tslint:disable-next-line interface-over-type-literal
type colorChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["color"]>;
// tslint:disable-next-line interface-over-type-literal
type drillingChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["drilling"]>;
// tslint:disable-next-line interface-over-type-literal
type groupLabelDisplayChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["groupLabelDisplay"]>;
// tslint:disable-next-line interface-over-type-literal
type headerChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["header"]>;
// tslint:disable-next-line interface-over-type-literal
type labelChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["label"]>;
// tslint:disable-next-line interface-over-type-literal
type labelDisplayChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["labelDisplay"]>;
// tslint:disable-next-line interface-over-type-literal
type labelHalignChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["labelHalign"]>;
// tslint:disable-next-line interface-over-type-literal
type labelStyleChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["labelStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type labelValignChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["labelValign"]>;
// tslint:disable-next-line interface-over-type-literal
type patternChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["pattern"]>;
// tslint:disable-next-line interface-over-type-literal
type selectableChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["selectable"]>;
// tslint:disable-next-line interface-over-type-literal
type shortDescChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["shortDesc"]>;
// tslint:disable-next-line interface-over-type-literal
type svgClassNameChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["svgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type svgStyleChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["svgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type valueChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["value"]>;
}
export interface ojTreemapNodeEventMap<K = any, D = any> extends dvtBaseComponentEventMap<ojTreemapNodeSettableProperties<K, D>> {
'categoriesChanged': JetElementCustomEvent<ojTreemapNode<K, D>["categories"]>;
'colorChanged': JetElementCustomEvent<ojTreemapNode<K, D>["color"]>;
'drillingChanged': JetElementCustomEvent<ojTreemapNode<K, D>["drilling"]>;
'groupLabelDisplayChanged': JetElementCustomEvent<ojTreemapNode<K, D>["groupLabelDisplay"]>;
'headerChanged': JetElementCustomEvent<ojTreemapNode<K, D>["header"]>;
'labelChanged': JetElementCustomEvent<ojTreemapNode<K, D>["label"]>;
'labelDisplayChanged': JetElementCustomEvent<ojTreemapNode<K, D>["labelDisplay"]>;
'labelHalignChanged': JetElementCustomEvent<ojTreemapNode<K, D>["labelHalign"]>;
'labelStyleChanged': JetElementCustomEvent<ojTreemapNode<K, D>["labelStyle"]>;
'labelValignChanged': JetElementCustomEvent<ojTreemapNode<K, D>["labelValign"]>;
'patternChanged': JetElementCustomEvent<ojTreemapNode<K, D>["pattern"]>;
'selectableChanged': JetElementCustomEvent<ojTreemapNode<K, D>["selectable"]>;
'shortDescChanged': JetElementCustomEvent<ojTreemapNode<K, D>["shortDesc"]>;
'svgClassNameChanged': JetElementCustomEvent<ojTreemapNode<K, D>["svgClassName"]>;
'svgStyleChanged': JetElementCustomEvent<ojTreemapNode<K, D>["svgStyle"]>;
'valueChanged': JetElementCustomEvent<ojTreemapNode<K, D>["value"]>;
}
export interface ojTreemapNodeSettableProperties<K = any, D = any> extends dvtBaseComponentSettableProperties {
categories?: string[];
color?: string;
drilling?: 'on' | 'off' | 'inherit';
groupLabelDisplay?: 'node' | 'off' | 'header';
header?: {
isolate?: 'off' | 'on';
labelHalign?: 'center' | 'end' | 'start';
labelStyle?: Partial<CSSStyleDeclaration>;
useNodeColor?: 'on' | 'off';
};
label?: string;
labelDisplay?: 'off' | 'node';
labelHalign?: 'start' | 'end' | 'center';
labelStyle?: Partial<CSSStyleDeclaration>;
labelValign?: 'top' | 'bottom' | 'center';
pattern?: 'smallChecker' | 'smallCrosshatch' | 'smallDiagonalLeft' | 'smallDiagonalRight' | 'smallDiamond' | 'smallTriangle' | 'largeChecker' | 'largeCrosshatch' | 'largeDiagonalLeft' |
'largeDiagonalRight' | 'largeDiamond' | 'largeTriangle' | 'none';
selectable?: 'off' | 'auto';
shortDesc?: (string | ((context: ojTreemap.NodeShortDescContext<K, D>) => string));
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
value: number;
}
export interface ojTreemapNodeSettablePropertiesLenient<K = any, D = any> extends Partial<ojTreemapNodeSettableProperties<K, D>> {
[key: string]: any;
}
export type TreemapElement<K, D extends ojTreemap.Node<K> | any> = ojTreemap<K, D>;
export type TreemapNodeElement<K = any, D = any> = ojTreemapNode<K, D>;
export namespace TreemapElement {
interface ojBeforeDrill<K, D> extends CustomEvent<{
data: ojTreemap.Node<K>;
id: K;
itemData: D;
[propName: string]: any;
}> {
}
interface ojDrill<K, D> extends CustomEvent<{
data: ojTreemap.Node<K>;
id: K;
itemData: D;
[propName: string]: any;
}> {
}
// tslint:disable-next-line interface-over-type-literal
type animationDurationChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["animationDuration"]>;
// tslint:disable-next-line interface-over-type-literal
type animationOnDataChangeChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["animationOnDataChange"]>;
// tslint:disable-next-line interface-over-type-literal
type animationOnDisplayChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["animationOnDisplay"]>;
// tslint:disable-next-line interface-over-type-literal
type animationUpdateColorChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["animationUpdateColor"]>;
// tslint:disable-next-line interface-over-type-literal
type asChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["as"]>;
// tslint:disable-next-line interface-over-type-literal
type colorLabelChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["colorLabel"]>;
// tslint:disable-next-line interface-over-type-literal
type dataChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["data"]>;
// tslint:disable-next-line interface-over-type-literal
type displayLevelsChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["displayLevels"]>;
// tslint:disable-next-line interface-over-type-literal
type drillingChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["drilling"]>;
// tslint:disable-next-line interface-over-type-literal
type groupGapsChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["groupGaps"]>;
// tslint:disable-next-line interface-over-type-literal
type hiddenCategoriesChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["hiddenCategories"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightMatchChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["highlightMatch"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightModeChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["highlightMode"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightedCategoriesChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["highlightedCategories"]>;
// tslint:disable-next-line interface-over-type-literal
type hoverBehaviorChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["hoverBehavior"]>;
// tslint:disable-next-line interface-over-type-literal
type hoverBehaviorDelayChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["hoverBehaviorDelay"]>;
// tslint:disable-next-line interface-over-type-literal
type isolatedNodeChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["isolatedNode"]>;
// tslint:disable-next-line interface-over-type-literal
type layoutChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["layout"]>;
// tslint:disable-next-line interface-over-type-literal
type nodeContentChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["nodeContent"]>;
// tslint:disable-next-line interface-over-type-literal
type nodeDefaultsChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["nodeDefaults"]>;
// tslint:disable-next-line interface-over-type-literal
type nodeSeparatorsChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["nodeSeparators"]>;
// tslint:disable-next-line interface-over-type-literal
type rootNodeChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["rootNode"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["selection"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionModeChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["selectionMode"]>;
// tslint:disable-next-line interface-over-type-literal
type sizeLabelChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["sizeLabel"]>;
// tslint:disable-next-line interface-over-type-literal
type sortingChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["sorting"]>;
// tslint:disable-next-line interface-over-type-literal
type tooltipChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["tooltip"]>;
// tslint:disable-next-line interface-over-type-literal
type touchResponseChanged<K, D extends ojTreemap.Node<K> | any> = JetElementCustomEvent<ojTreemap<K, D>["touchResponse"]>;
//------------------------------------------------------------
// Start: generated events for inherited properties
//------------------------------------------------------------
// tslint:disable-next-line interface-over-type-literal
type trackResizeChanged<K, D extends ojTreemap.Node<K> | any> = dvtBaseComponent.trackResizeChanged<ojTreemapSettableProperties<K, D>>;
// tslint:disable-next-line interface-over-type-literal
type DataContext = {
color: string;
label: string;
selected: boolean;
size: number;
tooltip: string;
};
// tslint:disable-next-line interface-over-type-literal
type NodeContentContext<K, D> = {
bounds: {
height: number;
width: number;
x: number;
y: number;
};
componentElement: Element;
data: ojTreemap.Node<K>;
id: K;
itemData: D;
};
// tslint:disable-next-line interface-over-type-literal
type NodeShortDescContext<K, D> = {
data: ojTreemap.Node<K>;
id: K;
itemData: D;
label: string;
value: number;
};
// tslint:disable-next-line interface-over-type-literal
type TooltipContext<K, D> = {
color: string;
componentElement: Element;
data: ojTreemap.Node<K>;
id: K;
itemData: D;
label: string;
parentElement: Element;
value: number;
};
}
export namespace TreemapNodeElement {
// tslint:disable-next-line interface-over-type-literal
type categoriesChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["categories"]>;
// tslint:disable-next-line interface-over-type-literal
type colorChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["color"]>;
// tslint:disable-next-line interface-over-type-literal
type drillingChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["drilling"]>;
// tslint:disable-next-line interface-over-type-literal
type groupLabelDisplayChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["groupLabelDisplay"]>;
// tslint:disable-next-line interface-over-type-literal
type headerChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["header"]>;
// tslint:disable-next-line interface-over-type-literal
type labelChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["label"]>;
// tslint:disable-next-line interface-over-type-literal
type labelDisplayChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["labelDisplay"]>;
// tslint:disable-next-line interface-over-type-literal
type labelHalignChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["labelHalign"]>;
// tslint:disable-next-line interface-over-type-literal
type labelStyleChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["labelStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type labelValignChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["labelValign"]>;
// tslint:disable-next-line interface-over-type-literal
type patternChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["pattern"]>;
// tslint:disable-next-line interface-over-type-literal
type selectableChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["selectable"]>;
// tslint:disable-next-line interface-over-type-literal
type shortDescChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["shortDesc"]>;
// tslint:disable-next-line interface-over-type-literal
type svgClassNameChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["svgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type svgStyleChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["svgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type valueChanged<K = any, D = any> = JetElementCustomEvent<ojTreemapNode<K, D>["value"]>;
}
export interface TreemapIntrinsicProps extends Partial<Readonly<ojTreemapSettableProperties<any, any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> {
onojBeforeDrill?: (value: ojTreemapEventMap<any, any>['ojBeforeDrill']) => void;
onojDrill?: (value: ojTreemapEventMap<any, any>['ojDrill']) => void;
onanimationDurationChanged?: (value: ojTreemapEventMap<any, any>['animationDurationChanged']) => void;
onanimationOnDataChangeChanged?: (value: ojTreemapEventMap<any, any>['animationOnDataChangeChanged']) => void;
onanimationOnDisplayChanged?: (value: ojTreemapEventMap<any, any>['animationOnDisplayChanged']) => void;
onanimationUpdateColorChanged?: (value: ojTreemapEventMap<any, any>['animationUpdateColorChanged']) => void;
onasChanged?: (value: ojTreemapEventMap<any, any>['asChanged']) => void;
oncolorLabelChanged?: (value: ojTreemapEventMap<any, any>['colorLabelChanged']) => void;
ondataChanged?: (value: ojTreemapEventMap<any, any>['dataChanged']) => void;
ondisplayLevelsChanged?: (value: ojTreemapEventMap<any, any>['displayLevelsChanged']) => void;
ondrillingChanged?: (value: ojTreemapEventMap<any, any>['drillingChanged']) => void;
ongroupGapsChanged?: (value: ojTreemapEventMap<any, any>['groupGapsChanged']) => void;
onhiddenCategoriesChanged?: (value: ojTreemapEventMap<any, any>['hiddenCategoriesChanged']) => void;
onhighlightMatchChanged?: (value: ojTreemapEventMap<any, any>['highlightMatchChanged']) => void;
onhighlightModeChanged?: (value: ojTreemapEventMap<any, any>['highlightModeChanged']) => void;
onhighlightedCategoriesChanged?: (value: ojTreemapEventMap<any, any>['highlightedCategoriesChanged']) => void;
onhoverBehaviorChanged?: (value: ojTreemapEventMap<any, any>['hoverBehaviorChanged']) => void;
onhoverBehaviorDelayChanged?: (value: ojTreemapEventMap<any, any>['hoverBehaviorDelayChanged']) => void;
onisolatedNodeChanged?: (value: ojTreemapEventMap<any, any>['isolatedNodeChanged']) => void;
onlayoutChanged?: (value: ojTreemapEventMap<any, any>['layoutChanged']) => void;
onnodeContentChanged?: (value: ojTreemapEventMap<any, any>['nodeContentChanged']) => void;
onnodeDefaultsChanged?: (value: ojTreemapEventMap<any, any>['nodeDefaultsChanged']) => void;
onnodeSeparatorsChanged?: (value: ojTreemapEventMap<any, any>['nodeSeparatorsChanged']) => void;
onrootNodeChanged?: (value: ojTreemapEventMap<any, any>['rootNodeChanged']) => void;
onselectionChanged?: (value: ojTreemapEventMap<any, any>['selectionChanged']) => void;
onselectionModeChanged?: (value: ojTreemapEventMap<any, any>['selectionModeChanged']) => void;
onsizeLabelChanged?: (value: ojTreemapEventMap<any, any>['sizeLabelChanged']) => void;
onsortingChanged?: (value: ojTreemapEventMap<any, any>['sortingChanged']) => void;
ontooltipChanged?: (value: ojTreemapEventMap<any, any>['tooltipChanged']) => void;
ontouchResponseChanged?: (value: ojTreemapEventMap<any, any>['touchResponseChanged']) => void;
ontrackResizeChanged?: (value: ojTreemapEventMap<any, any>['trackResizeChanged']) => void;
children?: ComponentChildren;
}
export interface TreemapNodeIntrinsicProps extends Partial<Readonly<ojTreemapNodeSettableProperties<any, any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> {
oncategoriesChanged?: (value: ojTreemapNodeEventMap<any, any>['categoriesChanged']) => void;
oncolorChanged?: (value: ojTreemapNodeEventMap<any, any>['colorChanged']) => void;
ondrillingChanged?: (value: ojTreemapNodeEventMap<any, any>['drillingChanged']) => void;
ongroupLabelDisplayChanged?: (value: ojTreemapNodeEventMap<any, any>['groupLabelDisplayChanged']) => void;
onheaderChanged?: (value: ojTreemapNodeEventMap<any, any>['headerChanged']) => void;
onlabelChanged?: (value: ojTreemapNodeEventMap<any, any>['labelChanged']) => void;
onlabelDisplayChanged?: (value: ojTreemapNodeEventMap<any, any>['labelDisplayChanged']) => void;
onlabelHalignChanged?: (value: ojTreemapNodeEventMap<any, any>['labelHalignChanged']) => void;
onlabelStyleChanged?: (value: ojTreemapNodeEventMap<any, any>['labelStyleChanged']) => void;
onlabelValignChanged?: (value: ojTreemapNodeEventMap<any, any>['labelValignChanged']) => void;
onpatternChanged?: (value: ojTreemapNodeEventMap<any, any>['patternChanged']) => void;
onselectableChanged?: (value: ojTreemapNodeEventMap<any, any>['selectableChanged']) => void;
onshortDescChanged?: (value: ojTreemapNodeEventMap<any, any>['shortDescChanged']) => void;
onsvgClassNameChanged?: (value: ojTreemapNodeEventMap<any, any>['svgClassNameChanged']) => void;
onsvgStyleChanged?: (value: ojTreemapNodeEventMap<any, any>['svgStyleChanged']) => void;
onvalueChanged?: (value: ojTreemapNodeEventMap<any, any>['valueChanged']) => void;
children?: ComponentChildren;
}
declare global {
namespace preact.JSX {
interface IntrinsicElements {
"oj-treemap": TreemapIntrinsicProps;
"oj-treemap-node": TreemapNodeIntrinsicProps;
}
}
} | the_stack |
import _ from "lodash";
import { IO, Nsp, SocketService, SocketSession, Socket } from "@tsed/socketio";
import { getPostgresPool } from "../../util/persistence/db";
import { KotsAppStore, UndeployStatus } from "../../kots_app/kots_app_store";
import { KotsAppStatusStore } from "../../kots_app/kots_app_status_store";
import { State, KotsApp } from "../../kots_app";
import { Params } from "../../server/params";
import { ClusterStore, Cluster } from "../../cluster";
import { PreflightStore } from "../../preflight/preflight_store";
import { TroubleshootStore } from "../../troubleshoot";
import { logger } from "../../server/logger";
import { VeleroClient } from "../../snapshots/resolvers/veleroClient";
import { kotsAppSequenceKey, kotsClusterIdKey } from "../../snapshots/snapshot";
import { Phase, Restore } from "../../snapshots/velero";
import { ReplicatedError } from "../../server/errors";
const DefaultReadyState = [{ kind: "EMPTY", name: "EMPTY", namespace: "EMPTY", state: State.Ready }];
const oneMinuteInMilliseconds = 1 * 60 * 1000;
interface ClusterSocketHistory {
clusterId: string;
socketId: string;
sentPreflightUrls: { [key: string]: boolean };
lastDeployedSequences: Map<string, number>;
}
@SocketService("")
export class KotsDeploySocketService {
@Nsp nsp: SocketIO.Namespace;
kotsAppStore: KotsAppStore;
kotsAppStatusStore: KotsAppStatusStore;
clusterStore: ClusterStore;
preflightStore: PreflightStore;
troubleshootStore: TroubleshootStore;
clusterSocketHistory: ClusterSocketHistory[];
params: Params;
lastUndeployTime: number = 0;
constructor(@IO private io: SocketIO.Server) {
getPostgresPool()
.then((pool) => {
Params.getParams()
.then((params) => {
this.params = params;
this.kotsAppStore = new KotsAppStore(pool, params);
this.kotsAppStatusStore = new KotsAppStatusStore(pool, params);
this.clusterStore = new ClusterStore(pool, params);
this.preflightStore = new PreflightStore(pool);
this.troubleshootStore = new TroubleshootStore(pool, params);
this.clusterSocketHistory = [];
setInterval(this.deployLoop.bind(this), 1000);
setInterval(this.supportBundleLoop.bind(this), 1000);
setInterval(this.restoreLoop.bind(this), 1000);
})
});
}
/**
* Triggered when a new client connects to the Namespace.
*/
async $onConnection(@Socket socket: SocketIO.Socket, @SocketSession session: SocketSession) {
if (!this.clusterStore) {
// we aren't ready
socket.disconnect();
return;
}
const cluster = await this.clusterStore.getFromDeployToken(socket.handshake.query.token);
logger.info(`Cluster ${cluster.id} joined`);
socket.join(cluster.id);
this.clusterSocketHistory.push({
clusterId: cluster.id,
socketId: socket.id,
sentPreflightUrls: {},
lastDeployedSequences: new Map<string, number>()
});
}
/**
* Triggered when a client disconnects from the Namespace.
*/
$onDisconnect(@Socket socket: SocketIO.Socket) {
const updated = _.reject(this.clusterSocketHistory, (csh) => {
return csh.socketId === socket.id;
});
this.clusterSocketHistory = updated;
}
async supportBundleLoop() {
if (!this.clusterSocketHistory) {
return;
}
for (const clusterSocketHistory of this.clusterSocketHistory) {
const pendingSupportBundles = await this.troubleshootStore.listPendingSupportBundlesForCluster(clusterSocketHistory.clusterId);
for (const pendingSupportBundle of pendingSupportBundles) {
const app = await this.kotsAppStore.getApp(pendingSupportBundle.appId);
this.io.in(clusterSocketHistory.clusterId).emit("supportbundle", { uri: `${this.params.shipApiEndpoint}/api/v1/troubleshoot/${app.slug}?incluster=true` });
await this.troubleshootStore.clearPendingSupportBundle(pendingSupportBundle.id);
}
}
}
async restoreLoop() {
if (!this.clusterSocketHistory) {
return;
}
for (const clusterSocketHistory of this.clusterSocketHistory) {
const apps = await this.kotsAppStore.listAppsForCluster(clusterSocketHistory.clusterId);
for (const app of apps) {
if (!app.restoreInProgressName) {
continue;
}
const cluster = await this.clusterStore.getCluster(clusterSocketHistory.clusterId);
try {
await this.handleRestoreInProgress(app, cluster);
} catch (err) {
logger.warn("Failed to handle restore in progress");
logger.warn(err);
}
}
}
}
async handleRestoreInProgress(app: KotsApp, cluster: Cluster): Promise<void> {
if (!app.restoreInProgressName) {
return;
}
switch (app.restoreUndeployStatus) {
case UndeployStatus.InProcess:
break;
case UndeployStatus.Completed:
await this.handleUndeployCompleted(app, cluster);
break;
case UndeployStatus.Failed:
// logger.warn(`Restore ${app.restoreInProgressName} failed`);
// TODO
break;
default:
// start undeploy
const velero = new VeleroClient("velero"); // TODO velero namespace
await this.undeployApp(app, cluster);
this.lastUndeployTime = new Date().getTime();
}
}
async undeployApp(app: KotsApp, cluster: Cluster): Promise<void> {
logger.info(`Starting restore, undeploying app ${app.name}`);
const desiredNamespace = ".";
const kotsAppSpec = await app.getKotsAppSpec(cluster.id, this.kotsAppStore);
const rendered = await app.render(app.currentSequence!.toString(), `overlays/downstreams/${cluster.title}`, kotsAppSpec ? kotsAppSpec.kustomizeVersion : "");
const b = new Buffer(rendered);
const veleroClient = new VeleroClient("velero"); // TODO velero namespace
const backup = await veleroClient.readBackup(app.restoreInProgressName!);
// make operator prune everything
const args = {
app_id: app.id,
app_slug: app.slug,
kubectl_version: kotsAppSpec ? kotsAppSpec.kubectlVersion : "",
namespace: desiredNamespace,
manifests: "",
previous_manifests: b.toString("base64"),
result_callback: "/api/v1/undeploy/result",
wait: true,
clear_namespaces: backup.spec.includedNamespaces,
clear_pvcs: true,
};
this.io.in(cluster.id).emit("deploy", args);
await this.kotsAppStore.updateAppRestoreUndeployStatus(app.id, UndeployStatus.InProcess);
}
async handleUndeployCompleted(app: KotsApp, cluster: Cluster): Promise<void> {
if (!app.restoreInProgressName) {
return;
}
const velero = new VeleroClient("velero"); // TODO velero namespace
const restore = await velero.readRestore(app.restoreInProgressName);
if (!restore) {
await this.startVeleroRestore(velero, app);
} else {
await this.checkRestoreComplete(velero, restore, app);
}
}
async startVeleroRestore(velero: VeleroClient, app: KotsApp): Promise<void> {
if (!app.restoreInProgressName) {
return;
}
logger.info(`Creating velero Restore object ${app.restoreInProgressName}`);
// create the Restore resource
await velero.restore(app.restoreInProgressName, app.restoreInProgressName);
}
async checkRestoreComplete(velero: VeleroClient, restore: Restore, app: KotsApp) {
switch (_.get(restore, "status.phase")) {
case Phase.Completed:
// Switch operator back to deploy mode on the restored sequence
const backup = await velero.readBackup(restore.spec.backupName);
if (!backup.metadata.annotations) {
throw new ReplicatedError(`Backup is missing required annotations`);
}
const sequenceString = backup.metadata.annotations[kotsAppSequenceKey];
if (!sequenceString) {
throw new ReplicatedError(`Backup is missing sequence annotation`);
}
const sequence = parseInt(sequenceString, 10);
if (_.isNaN(sequence)) {
throw new ReplicatedError(`Failed to parse sequence from Backup: ${sequenceString}`);
}
logger.info(`Restore complete, setting deploy version to ${sequence}`);
await this.kotsAppStore.deployVersion(app.id, sequence);
await this.kotsAppStore.updateAppRestoreReset(app.id);
break;
case Phase.PartiallyFailed:
case Phase.Failed:
logger.info(`Restore failed, resetting app restore name`);
await this.kotsAppStore.updateAppRestoreReset(app.id);
break;
default:
// in progress
}
}
// tslint:disable-next-line cyclomatic-complexity
async deployLoop() {
if (!this.clusterSocketHistory) {
return;
}
for (const clusterSocketHistory of this.clusterSocketHistory) {
const apps = await this.kotsAppStore.listAppsForCluster(clusterSocketHistory.clusterId);
for (const app of apps) {
if (app.restoreInProgressName) {
continue;
}
const deployedAppVersion = await this.kotsAppStore.getCurrentVersion(app.id, clusterSocketHistory.clusterId);
const maybeDeployedAppSequence = deployedAppVersion && deployedAppVersion.sequence;
if (maybeDeployedAppSequence! > -1) {
const deployedAppSequence = Number(maybeDeployedAppSequence);
if (!clusterSocketHistory.lastDeployedSequences.has(app.id) || clusterSocketHistory.lastDeployedSequences.get(app.id) !== deployedAppSequence) {
const cluster = await this.clusterStore.getCluster(clusterSocketHistory.clusterId);
try {
const desiredNamespace = ".";
const kotsAppSpec = await app.getKotsAppSpec(cluster.id, this.kotsAppStore);
const rendered = await app.render(deployedAppSequence.toString(), `overlays/downstreams/${cluster.title}`, kotsAppSpec ? kotsAppSpec.kustomizeVersion : "");
const b = new Buffer(rendered);
const imagePullSecret = await app.getImagePullSecretFromArchive(deployedAppSequence.toString());
const args = {
app_id: app.id,
app_slug: app.slug,
kubectl_version: kotsAppSpec ? kotsAppSpec.kubectlVersion : "",
additional_namespaces: kotsAppSpec ? kotsAppSpec.additionalNamespaces : [],
image_pull_secret: imagePullSecret,
namespace: desiredNamespace,
manifests: b.toString("base64"),
previous_manifests: "",
result_callback: "/api/v1/deploy/result",
wait: false,
annotate_slug: !!process.env.ANNOTATE_SLUG,
};
const previousSequence = await this.kotsAppStore.getPreviouslyDeployedSequence(app.id, clusterSocketHistory.clusterId, deployedAppSequence);
if (previousSequence !== undefined) {
const previousRendered = await app.render(previousSequence.toString(), `overlays/downstreams/${cluster.title}`, kotsAppSpec ? kotsAppSpec.kustomizeVersion : "");
const bb = new Buffer(previousRendered);
args.previous_manifests = bb.toString("base64");
}
this.io.in(clusterSocketHistory.clusterId).emit("deploy", args);
clusterSocketHistory.lastDeployedSequences.set(app.id, deployedAppSequence);
} catch (err) {
await this.kotsAppStore.updateDownstreamsStatus(app.id, deployedAppSequence, "failed", String(err));
continue;
}
try {
const kotsAppSpec = await app.getKotsAppSpec(cluster.id, this.kotsAppStore)
if (kotsAppSpec && kotsAppSpec.statusInformers) {
this.io.in(clusterSocketHistory.clusterId).emit("appInformers", {
app_id: app.id,
informers: kotsAppSpec.statusInformers,
});
} else {
// no informers, set state to ready
await this.kotsAppStatusStore.setKotsAppStatus(app.id, DefaultReadyState, new Date());
}
} catch (err) {
logger.error(err);
}
}
}
}
}
}
} | the_stack |
import {
ChangeDetectionStrategy,
Component,
ContentChild,
Directive,
ElementRef,
EmbeddedViewRef,
forwardRef,
Input,
OnChanges,
Renderer2,
TemplateRef,
ViewChild,
ViewContainerRef,
AfterViewInit,
OnDestroy,
ChangeDetectorRef,
NgZone,
Inject
} from '@angular/core';
import {
eachMedia,
LyTheme2,
ThemeVariables,
toBoolean,
LY_COMMON_STYLES,
Placement,
XPosition,
DirPosition,
YPosition,
lyl,
StyleRenderer,
ThemeRef,
StyleCollection,
StyleTemplate,
LyClasses,
WithStyles
} from '@alyle/ui';
import { Subscription } from 'rxjs';
import { ViewportRuler } from '@angular/cdk/scrolling';
import { Platform } from '@angular/cdk/platform';
export interface LyDrawerTheme {
/** Styles for Button Component */
root?: StyleCollection<((classes: LyClasses<typeof STYLES>) => StyleTemplate)>
| ((classes: LyClasses<typeof STYLES>) => StyleTemplate);
}
export interface LyDrawerVariables {
drawer?: LyDrawerTheme;
}
export type LyDrawerPosition = Placement;
export type LyDrawerMode = 'side' | 'over';
const DEFAULT_MODE = 'side';
const DEFAULT_WIDTH = '230px';
const DEFAULT_VALUE = '';
const STYLE_PRIORITY = -2;
const DEFAULT_POSITION = XPosition.before;
export const STYLES = (theme: ThemeVariables & LyDrawerVariables, ref: ThemeRef) => {
const __ = ref.selectorsOf(STYLES);
return {
$name: LyDrawerContent.и,
$priority: STYLE_PRIORITY + 1.9,
root: () => (theme.drawer
&& theme.drawer.root
&& (theme.drawer.root instanceof StyleCollection
? theme.drawer.root.setTransformer(fn => fn(__)).css
: theme.drawer.root(__))
),
drawerContainer: lyl `{
display: block
position: relative
overflow: hidden
-webkit-overflow-scrolling: touch
}`,
drawer: lyl `{
display: block
position: fixed
z-index: ${theme.zIndex.drawer}
overflow: auto
visibility: hidden
}`,
drawerContent: lyl `{
display: block
}`,
drawerOpened: lyl `{
transform: translate(0px, 0px)
visibility: visible
}`,
drawerClosed: null,
backdrop: lyl `{
...${LY_COMMON_STYLES.fill}
background-color: ${theme.drawer.backdrop}
}`,
transition: lyl `{
transition: ${theme.animations.durations.complex}ms ${theme.animations.curves.deceleration}
transition-property: transform, margin, visibility
}`
};
};
@Directive({
selector: 'ly-drawer-content'
})
export class LyDrawerContent {
static readonly и = 'LyDrawerContent';
constructor(
private _renderer: Renderer2,
private _el: ElementRef,
@Inject(forwardRef(() => LyDrawerContainer)) drawerContainer
) {
this._renderer.addClass(this._el.nativeElement, (drawerContainer as LyDrawerContainer).classes.drawerContent);
}
_getHostElement() {
return this._el.nativeElement;
}
}
@Directive({
selector: 'ly-drawer-container',
providers: [
StyleRenderer
]
})
export class LyDrawerContainer implements WithStyles {
/** @docs-private */
readonly classes = this.sRenderer.renderSheet(STYLES, true);
_openDrawers = 0;
@ContentChild(forwardRef(() => LyDrawerContent), { static: true }) _drawerContent: LyDrawerContent;
constructor(
private _renderer: Renderer2,
private _el: ElementRef,
readonly sRenderer: StyleRenderer
) {
this._renderer.addClass(this._el.nativeElement, this.classes.drawerContainer);
}
_getHostElement() {
return this._el.nativeElement;
}
}
@Component({
selector: 'ly-drawer',
templateUrl: './drawer.html',
changeDetection: ChangeDetectionStrategy.OnPush,
exportAs: 'lyDrawer',
providers: [
StyleRenderer
]
})
export class LyDrawer implements OnChanges, AfterViewInit, OnDestroy {
static readonly и = 'LyDrawer';
/**
* Styles
* @docs-private
*/
readonly classes = this._drawerContainer.classes;
private _forceModeOverOpened: boolean;
private _fromToggle: boolean;
private _opened: boolean;
private _viewRef?: EmbeddedViewRef<any>;
private _isAnimation: boolean;
private _hasBackdrop: boolean | null;
private _position: LyDrawerPosition = DEFAULT_POSITION;
private _drawerRootClass: string;
private _drawerClass?: string;
private _drawerContentClass?: string;
private _tabResizeSub: Subscription;
private _isOpen: boolean;
@ViewChild(TemplateRef) _backdrop: TemplateRef<any>;
@Input()
set width(_val: string) {
console.log(LyDrawer.и, this._el.nativeElement);
throw new Error(`${LyDrawer.и}: [width] is deprecated instead use [drawerWidth].`);
}
@Input()
set height(_val: string) {
console.log(LyDrawer.и, this._el.nativeElement);
throw new Error(`${LyDrawer.и}: [height] is deprecated instead use [drawerHeight].`);
}
@Input()
set opened(val: boolean) {
if (val !== this.opened) {
this._opened = toBoolean(val);
this._isOpen = this._opened;
}
}
get opened() {
return this._opened;
}
@Input() mode: LyDrawerMode = DEFAULT_MODE;
@Input() spacingAbove: string | number;
@Input() spacingBelow: string | number;
@Input() spacingBefore: string | number;
@Input() spacingAfter: string | number;
@Input() drawerWidth: number | string;
@Input() drawerHeight: number | string;
@Input()
get hasBackdrop() {
return this._hasBackdrop;
}
set hasBackdrop(val: any) {
this._hasBackdrop = val == null ? null : toBoolean(val);
}
@Input()
set position(val: LyDrawerPosition) {
if (val !== this.position) {
this._position = val;
this[0x1] = this._styleRenderer.add(`${LyDrawer.и}--position-${val}`,
(theme: ThemeVariables) => lyl `{
${theme.getDirection(val as any)}: 0
}`, STYLE_PRIORITY, this[0x1]);
}
}
get position(): LyDrawerPosition {
return this._position;
}
[0x1]: string;
constructor(
private _theme: LyTheme2,
private _styleRenderer: StyleRenderer,
private _renderer: Renderer2,
private _el: ElementRef,
private _drawerContainer: LyDrawerContainer,
private _vcr: ViewContainerRef,
private _viewportRuler: ViewportRuler,
private _cd: ChangeDetectorRef,
private _zone: NgZone,
private _platform: Platform
) {
this._renderer.addClass(this._el.nativeElement, _drawerContainer.classes.drawer);
}
ngOnChanges() {
this._updateBackdrop();
this._updateAnimations();
const __mode = this.mode;
const __forceModeOverOpened = this._forceModeOverOpened;
const __opened = this.opened;
let __width = this.drawerWidth;
const __height = this.drawerHeight;
const __position = this.position;
const __spacingAbove = this.spacingAbove;
const __spacingBelow = this.spacingBelow;
const __spacingBefore = this.spacingBefore;
const __spacingAfter = this.spacingAfter;
if (__width && __height) {
throw new Error(`\`width\` and \`height\` are defined, you can only define one`);
} else if (!__width) {
if (!__height) {
/** set default __width if `width` & `height` is `undefined` */
__width = DEFAULT_WIDTH;
}
}
if ((this._isOpen && __opened) || (this._isOpen) || __forceModeOverOpened) {
/** create styles for mode side */
this._drawerClass = this._theme.updateClass(this._el.nativeElement, this._renderer, this._drawerContainer.classes.drawerOpened, this._drawerClass);
// styles for <ly-drawer-content>
if (__mode === 'side') {
const newKeyDrawerContent = `ly-drawer-content----:${
__width || DEFAULT_VALUE}·${
__position || DEFAULT_VALUE}`;
this._drawerContentClass = this._theme.addStyle(newKeyDrawerContent, (theme: ThemeVariables) => {
const drawerContentStyles: {
marginLeft?: string
marginRight?: string
marginTop?: string
marginBottom?: string
} = {};
const positionVal = `margin-${__position}`;
if (__width) {
eachMedia(__width, (val, media) => {
const newStyleWidth = val === 'over' ? '0px' : toPx(val);
if (media) {
const breakPoint = theme.getBreakpoint(media);
const styleOfBreakPoint = createEmptyPropOrUseExisting(drawerContentStyles, breakPoint);
styleOfBreakPoint[positionVal] = newStyleWidth;
} else {
drawerContentStyles[positionVal] = newStyleWidth;
}
});
}
return drawerContentStyles;
},
this._drawerContainer._drawerContent._getHostElement(),
this._drawerContentClass);
} else if (this._drawerContentClass) {
/** remove styles for <ly-drawer-content> */
this._renderer.removeClass(this._drawerContainer._drawerContent._getHostElement(), this._drawerContentClass);
this._drawerContentClass = undefined;
}
} else {
if (this._drawerContentClass) {
this._renderer.removeClass(this._drawerContainer._drawerContent._getHostElement(), this._drawerContentClass);
this._drawerContentClass = undefined;
}
if (this._drawerClass) {
this._renderer.removeClass(this._el.nativeElement, this._drawerClass);
this._drawerClass = undefined;
}
}
/** default styles */
this._drawerRootClass = this._theme.addStyle(
`ly-drawer-root:${__width}·${__height}·${__spacingAbove}·${__spacingBelow}·${__spacingBefore}·${__spacingAfter}·${__position}·${__mode}·${__forceModeOverOpened}`,
(theme: ThemeVariables) => {
const stylesDrawerRoot: {
width?: string
height?: string
top?: string
bottom?: string
left?: number
right?: number
before?: string
after?: string
transform?: string
} = { };
const pos = theme.getDirection(__position as any);
const positionSign = __position === 'above' ? '-' : '+';
if (__width) {
const dirXSign = pos === DirPosition.left ? '-' : '+';
eachMedia(__width, (val, media) => {
if ((__mode === 'over' || __forceModeOverOpened) && (val === 0 || val === 'over')) {
return;
}
const newVal = val === 'over' ? '0px' : toPx(val);
const newStyleWidth = newVal;
const newTranslateX = `translateX(${dirXSign + newVal})`;
if (media) {
const breakPoint = theme.getBreakpoint(media);
const styleOfBreakPoint = createEmptyPropOrUseExisting(stylesDrawerRoot, breakPoint);
styleOfBreakPoint.width = newStyleWidth;
styleOfBreakPoint.transform = newTranslateX;
} else {
stylesDrawerRoot.width = newStyleWidth;
stylesDrawerRoot.transform = newTranslateX;
}
});
} else if (__height) {
eachMedia(__height, (val, media) => {
const newStyleHeight = toPx(val);
const newTranslateY = `translateY(${positionSign + toPx(val)})`;
if (media) {
const breakPoint = theme.getBreakpoint(media);
const styleOfBreakPoint = createEmptyPropOrUseExisting(stylesDrawerRoot, breakPoint);
styleOfBreakPoint.height = newStyleHeight;
styleOfBreakPoint.transform = newTranslateY;
} else {
stylesDrawerRoot.height = newStyleHeight;
stylesDrawerRoot.transform = newTranslateY;
}
});
}
if (__position === 'before' || __position === 'after') {
eachMedia(__spacingAbove, (val, media) => {
const newStyleSpacingTop = toPx(val || 0);
if (media) {
const breakPoint = theme.getBreakpoint(media);
const styleOfBreakPoint = createEmptyPropOrUseExisting(stylesDrawerRoot, breakPoint);
styleOfBreakPoint.top = newStyleSpacingTop;
} else {
stylesDrawerRoot.top = newStyleSpacingTop;
}
});
eachMedia(__spacingBelow, (val, media) => {
const newStyleSpacingBottom = toPx(val || 0);
if (media) {
const breakPoint = theme.getBreakpoint(media);
const styleOfBreakPoint = createEmptyPropOrUseExisting(stylesDrawerRoot, breakPoint);
styleOfBreakPoint.bottom = newStyleSpacingBottom;
} else {
stylesDrawerRoot.bottom = newStyleSpacingBottom;
}
});
} else if (__position === YPosition.above || __position === YPosition.below) {
eachMedia(__spacingBefore, (val, media) => {
const newStyleSpacingBefore = toPx(val || 0);
if (media) {
const breakPoint = theme.getBreakpoint(media);
const styleOfBreakPoint = createEmptyPropOrUseExisting(stylesDrawerRoot, breakPoint);
styleOfBreakPoint.before = newStyleSpacingBefore;
} else {
stylesDrawerRoot.before = newStyleSpacingBefore;
}
});
eachMedia(__spacingAfter, (val, media) => {
const newStyleSpacingAfter = toPx(val || 0);
if (media) {
const breakPoint = theme.getBreakpoint(media);
const styleOfBreakPoint = createEmptyPropOrUseExisting(stylesDrawerRoot, breakPoint);
styleOfBreakPoint.after = newStyleSpacingAfter;
} else {
stylesDrawerRoot.after = newStyleSpacingAfter;
}
});
}
return stylesDrawerRoot;
}, this._el.nativeElement, this._drawerRootClass, __mode === 'side' ? STYLE_PRIORITY : STYLE_PRIORITY + 1);
this._fromToggle = false;
}
ngAfterViewInit() {
if (this._platform.isBrowser) {
this._tabResizeSub = this._viewportRuler.change().subscribe(() => {
this.ngOnChanges();
});
}
}
ngOnDestroy() {
if (this._tabResizeSub) {
this._tabResizeSub.unsubscribe();
}
}
toggle() {
const width = getComputedStyle(this._el.nativeElement).width;
this._fromToggle = true;
if (width === '0px') {
this._forceModeOverOpened = true;
this._isOpen = true;
} else {
if (this._forceModeOverOpened) {
this._forceModeOverOpened = false;
this._isOpen = this.opened;
} else {
this._isOpen = !this._isOpen;
}
}
this.ngOnChanges();
}
private _contentHasMargin() {
const content = this._drawerContainer._drawerContent._getHostElement() as HTMLElement;
const container = this._drawerContainer._getHostElement() as HTMLElement;
return (content.offsetWidth === container.offsetWidth);
}
private _updateBackdrop() {
if (((this._isOpen && this.opened) || this._isOpen) &&
(this.hasBackdrop != null
? this.hasBackdrop
: (this.mode === 'over' || (this._forceModeOverOpened && this._contentHasMargin())))) {
// create only if is necessary
if (!this._viewRef) {
this._zone.run(() => {
this._drawerContainer._openDrawers++;
this._viewRef = this._vcr.createEmbeddedView(this._backdrop);
this._cd.markForCheck();
(this._viewRef.rootNodes[0] as HTMLDivElement).style.zIndex = `${this._drawerContainer._openDrawers}`;
});
}
} else if (this._viewRef) {
this._zone.run(() => {
this._drawerContainer._openDrawers--;
this._vcr.clear();
this._viewRef = undefined;
this._cd.markForCheck();
if (this._forceModeOverOpened) {
this._forceModeOverOpened = false;
this._isOpen = this.opened;
}
});
}
}
private _updateAnimations() {
if (this._fromToggle && !this._isAnimation) {
this._renderer.addClass(this._el.nativeElement, this.classes.transition);
this._renderer.addClass(this._drawerContainer._drawerContent._getHostElement(), this.classes.transition);
this._isAnimation = true;
} else if (!this._fromToggle && this._isAnimation) {
this._renderer.removeClass(this._el.nativeElement, this.classes.transition);
this._renderer.removeClass(this._drawerContainer._drawerContent._getHostElement(), this.classes.transition);
this._isAnimation = false;
}
}
}
/**
* convert number to px
*/
function toPx(val: string | number) {
if (typeof val === 'number') {
return `${val}px`;
} else {
return val;
}
}
function createEmptyPropOrUseExisting(object: object, key: string, _new?: any) {
return key in object
? object[key]
: object[key] = _new || {};
} | the_stack |
import { when } from 'jest-when';
import * as Config from '@oclif/config';
import * as fs from 'fs-extra';
import * as os from 'os';
import * as path from 'path';
import { Application } from 'lisk-sdk';
import * as application from '../../src/application';
import * as devnetGenesisBlock from '../../config/devnet/genesis_block.json';
import StartCommand from '../../src/commands/start';
import DownloadCommand from '../../src/commands/genesis-block/download';
import { getConfig } from '../utils/config';
import pJSON = require('../../package.json');
describe('start', () => {
let stdout: string[];
let stderr: string[];
let config: Config.IConfig;
beforeEach(async () => {
stdout = [];
stderr = [];
config = await getConfig();
jest.spyOn(process.stdout, 'write').mockImplementation(val => stdout.push(val as string) > -1);
jest.spyOn(process.stderr, 'write').mockImplementation(val => stderr.push(val as string) > -1);
jest.spyOn(application, 'getApplication').mockReturnValue({
run: async () => Promise.resolve(),
} as Application);
jest.spyOn(fs, 'readJSON');
when(fs.readJSON as jest.Mock)
.calledWith('~/.lisk/lisk-core/config/mainnet/config.json')
.mockResolvedValue({
logger: {
consoleLogLevel: 'error',
},
plugins: {},
})
.calledWith('~/.lisk/lisk-core/config/testnet/config.json')
.mockResolvedValue({
logger: {
consoleLogLevel: 'error',
},
plugins: {},
})
.calledWith('~/.lisk/lisk-core/config/devnet/config.json')
.mockResolvedValue({
logger: {
consoleLogLevel: 'error',
},
plugins: {},
})
.calledWith('~/.lisk/lisk-core/config/mainnet/genesis_block.json')
.mockResolvedValue(devnetGenesisBlock)
.calledWith('~/.lisk/lisk-core/config/testnet/genesis_block.json')
.mockResolvedValue(devnetGenesisBlock)
.calledWith('~/.lisk/lisk-core/config/devnet/genesis_block.json')
.mockResolvedValue(devnetGenesisBlock);
jest.spyOn(fs, 'readdirSync');
when(fs.readdirSync as jest.Mock)
.mockReturnValue(['mainnet'])
.calledWith(path.join(__dirname, '../../config'))
.mockReturnValue(['mainnet', 'testnet', 'devnet']);
jest.spyOn(fs, 'existsSync').mockReturnValue(true);
jest.spyOn(fs, 'ensureDirSync').mockReturnValue();
jest.spyOn(fs, 'removeSync').mockReturnValue();
jest.spyOn(fs, 'copyFileSync').mockReturnValue();
jest.spyOn(fs, 'statSync').mockReturnValue({ isDirectory: () => true } as never);
jest.spyOn(os, 'homedir').mockReturnValue('~');
});
describe('when starting without flag', () => {
it('should start with default mainnet config', async () => {
await StartCommand.run([], config);
const [
usedGenesisBlock,
usedConfig,
] = (application.getApplication as jest.Mock).mock.calls[0];
expect(usedGenesisBlock.header.id).toEqual(devnetGenesisBlock.header.id);
expect(usedConfig.version).toBe(pJSON.version);
expect(usedConfig.label).toBe('lisk-core');
});
});
describe('when config already exist in the folder', () => {
it('should fail with already existing config', async () => {
await expect(StartCommand.run(['-n', 'devnet'], config)).rejects.toThrow(
'Datapath ~/.lisk/lisk-core already contains configs for mainnet.',
);
});
});
describe('when config already exist in the folder and called with --overwrite-config', () => {
it('should delete the mainnet config and save the devnet config', async () => {
await StartCommand.run(['-n', 'devnet', '--overwrite-config'], config);
expect(fs.ensureDirSync).toHaveBeenCalledWith('~/.lisk/lisk-core/config');
expect(fs.removeSync).toHaveBeenCalledTimes(1);
expect(fs.copyFileSync).toHaveBeenCalledTimes(2);
});
});
describe('when genesis block does not exists and mainnet is started', () => {
it('should download the genesis block', async () => {
when(fs.existsSync as jest.Mock)
.calledWith('~/.lisk/lisk-core/config/mainnet/genesis_block.json')
.mockReturnValue(false);
jest.spyOn(DownloadCommand, 'run').mockResolvedValue(undefined);
await StartCommand.run(['-n', 'mainnet'], config);
expect(DownloadCommand.run).toHaveBeenCalledTimes(1);
expect(DownloadCommand.run).toHaveBeenCalledWith([
'--network',
'mainnet',
'--data-path',
'~/.lisk/lisk-core',
]);
});
});
describe('when genesis block does not exists and testnet is started with download path', () => {
it('should download the genesis block', async () => {
when(fs.existsSync as jest.Mock)
.calledWith('~/.lisk/lisk-core/config/testnet/genesis_block.json')
.mockReturnValue(false);
jest.spyOn(DownloadCommand, 'run').mockResolvedValue(undefined);
await StartCommand.run(
['-n', 'testnet', '-d', '~/.lisk/lisk-core', '--overwrite-config'],
config,
);
expect(DownloadCommand.run).toHaveBeenCalledTimes(1);
expect(DownloadCommand.run).toHaveBeenCalledWith([
'--network',
'testnet',
'--data-path',
'~/.lisk/lisk-core',
]);
});
});
describe('when genesis block does not exists and testnet is started', () => {
it('should download the genesis block', async () => {
when(fs.existsSync as jest.Mock)
.calledWith('~/.lisk/lisk-core/config/testnet/genesis_block.json')
.mockReturnValue(false);
jest.spyOn(DownloadCommand, 'run').mockResolvedValue(undefined);
await StartCommand.run(['-n', 'testnet', '--overwrite-config'], config);
expect(DownloadCommand.run).toHaveBeenCalledTimes(1);
expect(DownloadCommand.run).toHaveBeenCalledWith([
'--network',
'testnet',
'--data-path',
'~/.lisk/lisk-core',
]);
});
});
describe('when genesis block does not exists and devnet is started', () => {
it('should not download the genesis block', async () => {
when(fs.existsSync as jest.Mock)
.calledWith('~/.lisk/lisk-core/config/devnet/genesis_block.json')
.mockReturnValue(false);
jest.spyOn(DownloadCommand, 'run').mockResolvedValue(undefined);
await StartCommand.run(['-n', 'devnet', '--overwrite-config'], config);
expect(DownloadCommand.run).toHaveBeenCalledTimes(0);
});
});
describe('when unknown network is specified', () => {
it('should throw an error', async () => {
await expect(StartCommand.run(['-n', 'unknown'], config)).rejects.toThrow(
'Network must be one of mainnet,testnet,devnet but received unknown',
);
});
});
describe('when --api-ipc is specified', () => {
it('should update the config value', async () => {
await StartCommand.run(['--api-ipc'], config);
const [, usedConfig] = (application.getApplication as jest.Mock).mock.calls[0];
expect(usedConfig.rpc.enable).toBe(true);
expect(usedConfig.rpc.mode).toBe('ipc');
});
});
describe('when --api-ws is specified', () => {
it('should update the config value', async () => {
await StartCommand.run(['--api-ws'], config);
const [, usedConfig] = (application.getApplication as jest.Mock).mock.calls[0];
expect(usedConfig.rpc.enable).toBe(true);
expect(usedConfig.rpc.mode).toBe('ws');
});
});
describe('when custom host with --api-ws-host is specified along with --api-ws', () => {
it('should update the config value', async () => {
await StartCommand.run(['--api-ws', '--api-ws-host', '0.0.0.0'], config);
const [, usedConfig] = (application.getApplication as jest.Mock).mock.calls[0];
expect(usedConfig.rpc.host).toBe('0.0.0.0');
});
});
describe('when custom port with --api-ws-port is specified along with --api-ws', () => {
it('should update the config value', async () => {
await StartCommand.run(['--api-ws', '--api-ws-port', '8888'], config);
const [, usedConfig] = (application.getApplication as jest.Mock).mock.calls[0];
expect(usedConfig.rpc.port).toBe(8888);
});
});
describe('when --enable-http-api-plugin is specified', () => {
it('should pass this value to configuration', async () => {
await StartCommand.run(['--enable-http-api-plugin'], config);
const [, , options] = (application.getApplication as jest.Mock).mock.calls[0];
expect(options.enableHTTPAPIPlugin).toBe(true);
});
});
describe('when custom host with --http-api-plugin-host is specified along with --enable-http-api-plugin', () => {
it('should update the config value', async () => {
await StartCommand.run(
['--enable-http-api-plugin', '--http-api-plugin-host', '0.0.0.0'],
config,
);
const [, usedConfig] = (application.getApplication as jest.Mock).mock.calls[0];
expect(usedConfig.plugins.httpApi.host).toBe('0.0.0.0');
});
});
describe('when custom port with --http-api-plugin-port is specified along with --enable-http-api-plugin', () => {
it('should update the config value', async () => {
await StartCommand.run(
['--enable-http-api-plugin', '--http-api-plugin-port', '8888'],
config,
);
const [, usedConfig] = (application.getApplication as jest.Mock).mock.calls[0];
expect(usedConfig.plugins.httpApi.port).toBe(8888);
});
});
describe('when custom white list with --http-api-plugin-whitelist is specified along with --enable-http-api-plugin', () => {
it('should update the config value', async () => {
await StartCommand.run(
[
'--enable-http-api-plugin',
'--http-api-plugin-whitelist',
'192.08.0.1:8888,192.08.0.2:8888',
],
config,
);
const [, usedConfig] = (application.getApplication as jest.Mock).mock.calls[0];
expect(usedConfig.plugins.httpApi.whiteList).toEqual(['192.08.0.1:8888', '192.08.0.2:8888']);
});
});
describe('when empty white list with --http-api-plugin-whitelist is specified along with --enable-http-api-plugin', () => {
it('should update the config value', async () => {
await StartCommand.run(
['--enable-http-api-plugin', '--http-api-plugin-whitelist', ''],
config,
);
const [, usedConfig] = (application.getApplication as jest.Mock).mock.calls[0];
expect(usedConfig.plugins.httpApi.whiteList).toEqual([]);
});
});
describe('when --enable-forger-plugin is specified', () => {
it('should pass this value to configuration', async () => {
await StartCommand.run(['--enable-forger-plugin'], config);
const [, , options] = (application.getApplication as jest.Mock).mock.calls[0];
expect(options.enableForgerPlugin).toBe(true);
});
});
describe('when --enable-monitor-plugin is specified', () => {
it('should pass this value to configuration', async () => {
await StartCommand.run(['--enable-monitor-plugin'], config);
const [, , options] = (application.getApplication as jest.Mock).mock.calls[0];
expect(options.enableMonitorPlugin).toBe(true);
});
});
describe('when custom host with --monitor-plugin-host is specified along with --enable-monitor-plugin', () => {
it('should update the config value', async () => {
await StartCommand.run(
['--enable-monitor-plugin', '--monitor-plugin-host', '0.0.0.0'],
config,
);
const [, usedConfig] = (application.getApplication as jest.Mock).mock.calls[0];
expect(usedConfig.plugins.monitor.host).toBe('0.0.0.0');
});
});
describe('when custom port with --monitor-plugin-port is specified along with --enable-monitor-plugin', () => {
it('should update the config value', async () => {
await StartCommand.run(['--enable-monitor-plugin', '--monitor-plugin-port', '8888'], config);
const [, usedConfig] = (application.getApplication as jest.Mock).mock.calls[0];
expect(usedConfig.plugins.monitor.port).toBe(8888);
});
});
describe('when custom white list with --monitor-plugin-whitelist is specified along with --enable-monitor-plugin', () => {
it('should update the config value', async () => {
await StartCommand.run(
[
'--enable-monitor-plugin',
'--monitor-plugin-whitelist',
'192.08.0.1:8888,192.08.0.2:8888',
],
config,
);
const [, usedConfig] = (application.getApplication as jest.Mock).mock.calls[0];
expect(usedConfig.plugins.monitor.whiteList).toEqual(['192.08.0.1:8888', '192.08.0.2:8888']);
});
});
describe('when empty white list with --monitor-plugin-whitelist is specified along with --enable-monitor-plugin', () => {
it('should update the config value', async () => {
await StartCommand.run(['--enable-monitor-plugin', '--monitor-plugin-whitelist', ''], config);
const [, usedConfig] = (application.getApplication as jest.Mock).mock.calls[0];
expect(usedConfig.plugins.monitor.whiteList).toEqual([]);
});
});
describe('when --enable-report-misbehavior-plugin is specified', () => {
it('should pass this value to configuration', async () => {
await StartCommand.run(['--enable-report-misbehavior-plugin'], config);
const [, , options] = (application.getApplication as jest.Mock).mock.calls[0];
expect(options.enableReportMisbehaviorPlugin).toBe(true);
});
});
describe('when config is specified', () => {
it('should update the config value', async () => {
when(fs.readJSON as jest.Mock)
.calledWith('./config.json')
.mockResolvedValue({
logger: {
consoleLogLevel: 'error',
},
plugins: {},
});
await StartCommand.run(['--config=./config.json'], config);
const [, usedConfig] = (application.getApplication as jest.Mock).mock.calls[0];
expect(fs.readJSON).toHaveBeenCalledWith('./config.json');
expect(usedConfig.logger.consoleLogLevel).toBe('error');
});
});
describe('when log is specified', () => {
it('should update the config value', async () => {
await StartCommand.run(['--console-log=trace'], config);
const [, usedConfig] = (application.getApplication as jest.Mock).mock.calls[0];
expect(usedConfig.logger.consoleLogLevel).toBe('trace');
});
it('should update the config value from env', async () => {
process.env.LISK_CONSOLE_LOG_LEVEL = 'error';
await StartCommand.run([], config);
const [, usedConfig] = (application.getApplication as jest.Mock).mock.calls[0];
expect(usedConfig.logger.consoleLogLevel).toBe('error');
process.env.LISK_CONSOLE_LOG_LEVEL = '';
});
});
describe('when file log is specified', () => {
it('should update the config value', async () => {
await StartCommand.run(['--log=trace'], config);
const [, usedConfig] = (application.getApplication as jest.Mock).mock.calls[0];
expect(usedConfig.logger.fileLogLevel).toBe('trace');
});
it('should update the config value fro menv', async () => {
process.env.LISK_FILE_LOG_LEVEL = 'trace';
await StartCommand.run([], config);
const [, usedConfig] = (application.getApplication as jest.Mock).mock.calls[0];
expect(usedConfig.logger.fileLogLevel).toBe('trace');
process.env.LISK_FILE_LOG_LEVEL = '';
});
});
describe('when port is specified', () => {
it('should update the config value', async () => {
await StartCommand.run(['--port=1111'], config);
const [, usedConfig] = (application.getApplication as jest.Mock).mock.calls[0];
expect(usedConfig.network.port).toBe(1111);
});
it('should update the config value fro menv', async () => {
process.env.LISK_PORT = '1234';
await StartCommand.run([], config);
const [, usedConfig] = (application.getApplication as jest.Mock).mock.calls[0];
expect(usedConfig.network.port).toBe(1234);
process.env.LISK_PORT = '';
});
});
describe('when seed peer is specified', () => {
it('should update the config value', async () => {
await StartCommand.run(['--seed-peers=localhost:12234'], config);
const [, usedConfig] = (application.getApplication as jest.Mock).mock.calls[0];
expect(usedConfig.network.seedPeers).toEqual([{ ip: 'localhost', port: 12234 }]);
});
it('should update the config value using env variable', async () => {
process.env.LISK_SEED_PEERS = 'localhost:12234,74.49.3.35:2238';
await StartCommand.run([], config);
const [, usedConfig] = (application.getApplication as jest.Mock).mock.calls[0];
expect(usedConfig.network.seedPeers).toEqual([
{ ip: 'localhost', port: 12234 },
{ ip: '74.49.3.35', port: 2238 },
]);
process.env.LISK_SEED_PEERS = '';
});
});
}); | the_stack |
import { ISamlProvider } from '@aws-cdk/aws-iam';
import * as logs from '@aws-cdk/aws-logs';
import { CfnOutput, ConcreteDependable, IDependable, Resource, Token } from '@aws-cdk/core';
import { Construct } from 'constructs';
import { ClientVpnAuthorizationRule, ClientVpnAuthorizationRuleOptions } from './client-vpn-authorization-rule';
import { IClientVpnConnectionHandler, IClientVpnEndpoint, TransportProtocol, VpnPort } from './client-vpn-endpoint-types';
import { ClientVpnRoute, ClientVpnRouteOptions } from './client-vpn-route';
import { Connections } from './connections';
import { CfnClientVpnEndpoint, CfnClientVpnTargetNetworkAssociation } from './ec2.generated';
import { CidrBlock } from './network-util';
import { ISecurityGroup, SecurityGroup } from './security-group';
import { IVpc, SubnetSelection } from './vpc';
/**
* Options for a client VPN endpoint
*/
export interface ClientVpnEndpointOptions {
/**
* The IPv4 address range, in CIDR notation, from which to assign client IP
* addresses. The address range cannot overlap with the local CIDR of the VPC
* in which the associated subnet is located, or the routes that you add manually.
*
* Changing the address range will replace the Client VPN endpoint.
*
* The CIDR block should be /22 or greater.
*/
readonly cidr: string;
/**
* The ARN of the client certificate for mutual authentication.
*
* The certificate must be signed by a certificate authority (CA) and it must
* be provisioned in AWS Certificate Manager (ACM).
*
* @default - use user-based authentication
*/
readonly clientCertificateArn?: string;
/**
* The type of user-based authentication to use.
*
* @see https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/client-authentication.html
*
* @default - use mutual authentication
*/
readonly userBasedAuthentication?: ClientVpnUserBasedAuthentication;
/**
* Whether to enable connections logging
*
* @default true
*/
readonly logging?: boolean;
/**
* A CloudWatch Logs log group for connection logging
*
* @default - a new group is created
*/
readonly logGroup?: logs.ILogGroup;
/**
* A CloudWatch Logs log stream for connection logging
*
* @default - a new stream is created
*/
readonly logStream?: logs.ILogStream;
/**
* The AWS Lambda function used for connection authorization
*
* The name of the Lambda function must begin with the `AWSClientVPN-` prefix
*
* @default - no connection handler
*/
readonly clientConnectionHandler?: IClientVpnConnectionHandler;
/**
* A brief description of the Client VPN endpoint.
*
* @default - no description
*/
readonly description?: string;
/**
* The security groups to apply to the target network.
*
* @default - a new security group is created
*/
readonly securityGroups?: ISecurityGroup[];
/**
* Specify whether to enable the self-service portal for the Client VPN endpoint.
*
* @default true
*/
readonly selfServicePortal?: boolean;
/**
* The ARN of the server certificate
*/
readonly serverCertificateArn: string;
/**
* Indicates whether split-tunnel is enabled on the AWS Client VPN endpoint.
*
* @see https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/split-tunnel-vpn.html
*
* @default false
*/
readonly splitTunnel?: boolean;
/**
* The transport protocol to be used by the VPN session.
*
* @default TransportProtocol.UDP
*/
readonly transportProtocol?: TransportProtocol;
/**
* The port number to assign to the Client VPN endpoint for TCP and UDP
* traffic.
*
* @default VpnPort.HTTPS
*/
readonly port?: VpnPort;
/**
* Information about the DNS servers to be used for DNS resolution.
*
* A Client VPN endpoint can have up to two DNS servers.
*
* @default - use the DNS address configured on the device
*/
readonly dnsServers?: string[];
/**
* Subnets to associate to the client VPN endpoint.
*
* @default - the VPC default strategy
*/
readonly vpcSubnets?: SubnetSelection;
/**
* Whether to authorize all users to the VPC CIDR
*
* This automatically creates an authorization rule. Set this to `false` and
* use `addAuthorizationRule()` to create your own rules instead.
*
* @default true
*/
readonly authorizeAllUsersToVpcCidr?: boolean;
}
/**
* User-based authentication for a client VPN endpoint
*/
export abstract class ClientVpnUserBasedAuthentication {
/**
* Active Directory authentication
*/
public static activeDirectory(directoryId: string): ClientVpnUserBasedAuthentication {
return new ActiveDirectoryAuthentication(directoryId);
}
/** Federated authentication */
public static federated(samlProvider: ISamlProvider, selfServiceSamlProvider?: ISamlProvider): ClientVpnUserBasedAuthentication {
return new FederatedAuthentication(samlProvider, selfServiceSamlProvider);
}
/** Renders the user based authentication */
public abstract render(): any;
}
/**
* Active Directory authentication
*/
class ActiveDirectoryAuthentication extends ClientVpnUserBasedAuthentication {
constructor(private readonly directoryId: string) {
super();
}
render(): any {
return {
type: 'directory-service-authentication',
activeDirectory: { directoryId: this.directoryId },
};
}
}
/**
* Federated authentication
*/
class FederatedAuthentication extends ClientVpnUserBasedAuthentication {
constructor(private readonly samlProvider: ISamlProvider, private readonly selfServiceSamlProvider?: ISamlProvider) {
super();
}
render(): any {
return {
type: 'federated-authentication',
federatedAuthentication: {
samlProviderArn: this.samlProvider.samlProviderArn,
selfServiceSamlProviderArn: this.selfServiceSamlProvider?.samlProviderArn,
},
};
}
}
/**
* Properties for a client VPN endpoint
*/
export interface ClientVpnEndpointProps extends ClientVpnEndpointOptions {
/**
* The VPC to connect to.
*/
readonly vpc: IVpc;
}
/**
* Attributes when importing an existing client VPN endpoint
*/
export interface ClientVpnEndpointAttributes {
/**
* The endpoint ID
*/
readonly endpointId: string;
/**
* The security groups associated with the endpoint
*/
readonly securityGroups: ISecurityGroup[];
}
/**
* A client VPN connnection
*/
export class ClientVpnEndpoint extends Resource implements IClientVpnEndpoint {
/**
* Import an existing client VPN endpoint
*/
public static fromEndpointAttributes(scope: Construct, id: string, attrs: ClientVpnEndpointAttributes): IClientVpnEndpoint {
class Import extends Resource implements IClientVpnEndpoint {
public readonly endpointId = attrs.endpointId;
public readonly connections = new Connections({ securityGroups: attrs.securityGroups });
public readonly targetNetworksAssociated: IDependable = new ConcreteDependable();
}
return new Import(scope, id);
}
public readonly endpointId: string;
/**
* Allows specify security group connections for the endpoint.
*/
public readonly connections: Connections;
public readonly targetNetworksAssociated: IDependable;
private readonly _targetNetworksAssociated = new ConcreteDependable();
constructor(scope: Construct, id: string, props: ClientVpnEndpointProps) {
super(scope, id);
if (!Token.isUnresolved(props.vpc.vpcCidrBlock)) {
const clientCidr = new CidrBlock(props.cidr);
const vpcCidr = new CidrBlock(props.vpc.vpcCidrBlock);
if (vpcCidr.containsCidr(clientCidr)) {
throw new Error('The client CIDR cannot overlap with the local CIDR of the VPC');
}
}
if (props.dnsServers && props.dnsServers.length > 2) {
throw new Error('A client VPN endpoint can have up to two DNS servers');
}
if (props.logging == false && (props.logGroup || props.logStream)) {
throw new Error('Cannot specify `logGroup` or `logStream` when logging is disabled');
}
if (props.clientConnectionHandler
&& !Token.isUnresolved(props.clientConnectionHandler.functionName)
&& !props.clientConnectionHandler.functionName.startsWith('AWSClientVPN-')) {
throw new Error('The name of the Lambda function must begin with the `AWSClientVPN-` prefix');
}
const logging = props.logging ?? true;
const logGroup = logging
? props.logGroup ?? new logs.LogGroup(this, 'LogGroup')
: undefined;
const securityGroups = props.securityGroups ?? [new SecurityGroup(this, 'SecurityGroup', {
vpc: props.vpc,
})];
this.connections = new Connections({ securityGroups });
const endpoint = new CfnClientVpnEndpoint(this, 'Resource', {
authenticationOptions: renderAuthenticationOptions(props.clientCertificateArn, props.userBasedAuthentication),
clientCidrBlock: props.cidr,
clientConnectOptions: props.clientConnectionHandler
? {
enabled: true,
lambdaFunctionArn: props.clientConnectionHandler.functionArn,
}
: undefined,
connectionLogOptions: {
enabled: logging,
cloudwatchLogGroup: logGroup?.logGroupName,
cloudwatchLogStream: props.logStream?.logStreamName,
},
description: props.description,
dnsServers: props.dnsServers,
securityGroupIds: securityGroups.map(s => s.securityGroupId),
selfServicePortal: booleanToEnabledDisabled(props.selfServicePortal),
serverCertificateArn: props.serverCertificateArn,
splitTunnel: props.splitTunnel,
transportProtocol: props.transportProtocol,
vpcId: props.vpc.vpcId,
vpnPort: props.port,
});
this.endpointId = endpoint.ref;
if (props.userBasedAuthentication && (props.selfServicePortal ?? true)) {
// Output self-service portal URL
new CfnOutput(this, 'SelfServicePortalUrl', {
value: `https://self-service.clientvpn.amazonaws.com/endpoints/${this.endpointId}`,
});
}
// Associate subnets
const subnetIds = props.vpc.selectSubnets(props.vpcSubnets).subnetIds;
if (Token.isUnresolved(subnetIds)) {
throw new Error('Cannot associate subnets when VPC are imported from parameters or exports containing lists of subnet IDs.');
}
for (const [idx, subnetId] of Object.entries(subnetIds)) {
this._targetNetworksAssociated.add(new CfnClientVpnTargetNetworkAssociation(this, `Association${idx}`, {
clientVpnEndpointId: this.endpointId,
subnetId,
}));
}
this.targetNetworksAssociated = this._targetNetworksAssociated;
if (props.authorizeAllUsersToVpcCidr ?? true) {
this.addAuthorizationRule('AuthorizeAll', {
cidr: props.vpc.vpcCidrBlock,
});
}
}
/**
* Adds an authorization rule to this endpoint
*/
public addAuthorizationRule(id: string, props: ClientVpnAuthorizationRuleOptions): ClientVpnAuthorizationRule {
return new ClientVpnAuthorizationRule(this, id, {
...props,
clientVpnEndpoint: this,
});
}
/**
* Adds a route to this endpoint
*/
public addRoute(id: string, props: ClientVpnRouteOptions): ClientVpnRoute {
return new ClientVpnRoute(this, id, {
...props,
clientVpnEndpoint: this,
});
}
}
function renderAuthenticationOptions(
clientCertificateArn?: string,
userBasedAuthentication?: ClientVpnUserBasedAuthentication): CfnClientVpnEndpoint.ClientAuthenticationRequestProperty[] {
const authenticationOptions: CfnClientVpnEndpoint.ClientAuthenticationRequestProperty[] = [];
if (clientCertificateArn) {
authenticationOptions.push({
type: 'certificate-authentication',
mutualAuthentication: {
clientRootCertificateChainArn: clientCertificateArn,
},
});
}
if (userBasedAuthentication) {
authenticationOptions.push(userBasedAuthentication.render());
}
if (authenticationOptions.length === 0) {
throw new Error('A client VPN endpoint must use at least one authentication option');
}
return authenticationOptions;
}
function booleanToEnabledDisabled(val?: boolean): 'enabled' | 'disabled' | undefined {
switch (val) {
case undefined:
return undefined;
case true:
return 'enabled';
case false:
return 'disabled';
}
} | the_stack |
import fs from 'fs'
import sharp, { AvailableFormatInfo } from 'sharp'
import { EventEmitter } from 'events'
import { Readable } from 'stream'
import { bufferToStream, streamToBuffer } from './Utilities'
const DEFAULT_WIDTH: number = 400
export default function Photosaic(
sourceImage: PhotosaicImage,
subImages: PhotosaicImage[],
{
gridNum = 10,
intensity = 0.5,
outputType = 'png',
outputWidth = DEFAULT_WIDTH,
algo = 'closestColor',
}: IPhotosaicOptions = {}
): IPhotosaicFactory {
return {
emitter: new EventEmitter(),
sourceImage,
sourceImageSharp: sharp(),
destinationImageSharp: sharp(),
sourceWidth: 0,
sourceHeight: 0,
subImages,
subImagesList: [],
subImagesListCache: [],
subImageWidth: 0,
subImageHeight: 0,
setSourceImage(source: PhotosaicImage) {
return (this.sourceImage = source)
},
setSubImages(subs: PhotosaicImage[]) {
return (this.subImages = subs)
},
addSubImage(sub: PhotosaicImage) {
this.subImages.push(sub)
return this.subImages
},
imgToStream(img: PhotosaicImage) {
if (typeof img === 'string') return fs.createReadStream(img)
if (img instanceof Buffer) return bufferToStream(img)
return img
},
async imgToBuffer(img: PhotosaicImage) {
if (typeof img === 'string') return await fs.promises.readFile(img)
if (img instanceof Readable) return await streamToBuffer(img)
return img
},
async setupSourceImage() {
this.sourceImageSharp = sharp(await this.imgToBuffer(this.sourceImage))
// https://sharp.pixelplumbing.com/api-input#metadata
const { width } = await this.sourceImageSharp.metadata()
this.sourceImageSharp = sharp(
await this.sourceImageSharp
.rotate()
.resize({
width: outputWidth || width || DEFAULT_WIDTH,
})
.toBuffer()
)
const newDims = await this.sourceImageSharp.metadata()
this.sourceWidth = newDims.width || DEFAULT_WIDTH
this.sourceHeight = newDims.height || DEFAULT_WIDTH
this.destinationImageSharp = sharp({
create: {
width: this.sourceWidth,
height: this.sourceHeight,
channels: 4,
background: { r: 255, g: 255, b: 255, alpha: 0 },
},
}).png()
return this.sourceImageSharp
},
async setupSubImages() {
const sourceWidth = outputWidth || this.sourceWidth || 50
const newWidth = sourceWidth / (gridNum || 10)
const whRatio =
sourceWidth / (this.sourceHeight || outputWidth || DEFAULT_WIDTH)
this.subImageWidth = Math.floor(newWidth)
this.subImageHeight = Math.floor(newWidth / whRatio)
// resetting sourceWidth and sourceHeight to be gridNum * subImgWidth etc.
// because when we Math.floor() above it might be several pixels too small
this.sourceWidth = this.subImageWidth * gridNum
this.sourceHeight = this.subImageHeight * gridNum
const allSubImages = await Promise.all(
this.subImages.map(async (img: PhotosaicImage) => {
const s1 = sharp(await this.imgToBuffer(img))
const sharpImg = sharp(
await s1
.rotate()
.resize({
width: this.subImageWidth,
height: this.subImageHeight,
})
.toBuffer()
)
return {
img: sharpImg,
stats: await sharpImg.stats(),
}
})
)
return (this.subImagesList = sortSubImages(allSubImages))
},
async getPieceAvgColor(
x: number,
y: number,
source?: sharp.Sharp,
subImgWidth?: number,
subImgHeight?: number
) {
const w = subImgWidth || this.subImageWidth
const h = subImgHeight || this.subImageHeight
const piece = await (source || this.sourceImageSharp)
.clone()
.extract({
left: x * w,
top: y * h,
width: w,
height: h,
})
.toBuffer()
const {
channels: [r, g, b, a],
} = await sharp(piece).stats()
return {
r: r.mean,
g: g.mean,
b: b.mean,
a: (a || { mean: 100 }).mean,
}
},
getSubImage(pieceColor: IColor): sharp.Sharp {
switch (algo) {
case 'closestColor': {
const getDiff = (c1: number, c2: number): number => Math.abs(c1 - c2)
const selectedGrayscale = getGrayscale(
pieceColor.r,
pieceColor.g,
pieceColor.b
)
const closestSubImage = binarySubImageSearch(
this.subImagesListCache,
selectedGrayscale,
0,
this.subImagesListCache.length - 1
)
return closestSubImage
? closestSubImage.img.clone()
: this.sourceImageSharp.clone()
}
default: {
// 'random'
const randImgInd = Math.floor(
this.subImagesListCache.length * Math.random()
)
return this.subImagesListCache.splice(randImgInd, 1)[0].img.clone()
}
}
},
async getSourceImgAvgColors(): Promise<IColor[][]> {
let gridColors: IColor[][] = []
let iteration = 0
let smallSource = sharp(
await this.sourceImageSharp
.clone()
.resize({ width: DEFAULT_WIDTH })
.toBuffer()
)
const smallSourceMeta = await smallSource.metadata()
const subWidth = Math.floor(DEFAULT_WIDTH / gridNum)
const subHeight = Math.floor(
(smallSourceMeta.height || DEFAULT_WIDTH) / gridNum
)
// resetting after setting subImages so the width is exactly
// subWidth * gridNum
smallSource = sharp(
await smallSource
.clone()
.resize({ width: subWidth * gridNum })
.toBuffer()
)
for (let x = 0; x < gridNum; x++) {
await Promise.all(
new Array(gridNum).fill(0).map(async (_, y) => {
iteration++
this.emitter.emit(`processing`, iteration)
gridColors[x] = gridColors[x] || []
gridColors[x][y] = await this.getPieceAvgColor(
x,
y,
smallSource,
subWidth,
subHeight
)
})
)
}
return gridColors
},
async build() {
await this.setupSourceImage()
const [avgMainImgColors] = await Promise.all([
this.getSourceImgAvgColors(),
this.setupSubImages(),
])
let compositeSubImgObjects: object[] = []
let iteration = 0
this.subImagesListCache = this.subImagesList.slice(0)
// we're going to execute each row in series, but all cols
// in each row in parallel to try and improve speed
for (let x = 0; x < gridNum; x++) {
await Promise.all(
new Array(gridNum).fill(0).map(async (_, y) => {
iteration++
this.emitter.emit(`processing`, iteration)
const pieceColor = avgMainImgColors[x][y]
const { r, g, b, a } = pieceColor
// If the square is completely transparent, don't insert image here.
// TODO: should we have same logic here for all white or black squares?
if ((a || 0) < 5) return
if (this.subImagesListCache.length === 0)
this.subImagesListCache = this.subImagesList.slice(0)
const subImg = this.getSubImage(pieceColor)
const overlayedSubImg = subImg.composite([
{
input: {
create: {
width: this.subImageWidth,
height: this.subImageHeight,
channels: 4,
background: { r, g, b, alpha: intensity },
},
},
},
])
compositeSubImgObjects.push({
input: await overlayedSubImg.toBuffer(),
left: x * this.subImageWidth,
top: y * this.subImageHeight,
})
})
)
}
// TODO: when the following are resolved remove this and only use
// `.composite` once with all small images
//
// https://github.com/lovell/sharp/issues/1708
// https://github.com/lovell/sharp/issues/1626
while (compositeSubImgObjects.length > 0) {
iteration++
this.emitter.emit(`processing`, iteration)
const compositeImages = compositeSubImgObjects.splice(0, gridNum)
this.destinationImageSharp = sharp(
await this.destinationImageSharp.composite(compositeImages).toBuffer()
)
}
const buffer = await this.destinationImageSharp
.toFormat(outputType)
.toBuffer()
this.emitter.emit(`complete`, buffer)
return buffer
},
}
}
export function getGrayscale(r: number, g: number, b: number): number {
return 0.3 * r + 0.59 * g + 0.11 * b
}
export function binarySubImageSearch(
images: ISubImage[],
targetGrayscale: number,
s: number,
e: number
): ISubImage {
const m = Math.floor((s + e) / 2)
const [rm, gm, bm] = images[m].stats.channels
const [rs, gs, bs] = images[s].stats.channels
const [re, ge, be] = images[e].stats.channels
const midGr = getGrayscale(rm.mean, gm.mean, bm.mean)
const startGr = getGrayscale(rs.mean, gs.mean, bs.mean)
const endGr = getGrayscale(re.mean, ge.mean, be.mean)
if (images.length === 1) return images[0]
if (targetGrayscale == midGr) return images[m]
if (e - 1 === s)
return Math.abs(startGr - targetGrayscale) >
Math.abs(endGr - targetGrayscale)
? images[e]
: images[s]
if (targetGrayscale > midGr)
return binarySubImageSearch(images, targetGrayscale, m, e)
if (targetGrayscale < midGr)
return binarySubImageSearch(images, targetGrayscale, s, m)
return images[m] || images[s]
}
function sortSubImages(imgs: ISubImage[]): ISubImage[] {
return imgs.sort((i1, i2) => {
const [r1, g1, b1] = i1.stats.channels
const [r2, g2, b2] = i2.stats.channels
const gr1 = getGrayscale(r1.mean, g1.mean, b1.mean)
const gr2 = getGrayscale(r2.mean, g2.mean, b2.mean)
return gr1 < gr2 ? -1 : 1
})
}
/**
* @PhotosaicImage
* "string": local filepath to the image
* "Buffer": raw buffer of the image
* "Readable": readable stream of image that can be piped to writable stream
**/
export type PhotosaicImage = string | Buffer | Readable
export interface IColor {
r: number
g: number
b: number
a: number
}
export interface ISubImage {
img: sharp.Sharp
stats: sharp.Stats
}
export interface IPhotosaicFactory {
emitter: EventEmitter
sourceImage: PhotosaicImage
sourceImageSharp: sharp.Sharp
destinationImageSharp: sharp.Sharp
sourceWidth: number
sourceHeight: number
subImages: PhotosaicImage[]
subImagesList: ISubImage[]
subImagesListCache: ISubImage[]
subImageWidth: number
subImageHeight: number
setSourceImage(source: PhotosaicImage): PhotosaicImage
setSubImages(subs: PhotosaicImage[]): PhotosaicImage[]
addSubImage(sub: PhotosaicImage): PhotosaicImage[]
imgToStream(img: PhotosaicImage): Readable
imgToBuffer(img: PhotosaicImage): Promise<Buffer>
setupSourceImage(): Promise<sharp.Sharp>
setupSubImages(): Promise<ISubImage[]>
getPieceAvgColor(
x: number,
y: number,
source?: sharp.Sharp,
subWidth?: number,
subHeight?: number
): Promise<IColor>
getSubImage(pieceColor: IColor): sharp.Sharp
getSourceImgAvgColors(): Promise<IColor[][]>
build(): Promise<Buffer>
}
export interface IPhotosaicOptions {
gridNum?: number // number of columns and rows of subimages we'll use to build the mosaic
intensity?: number // number between 0-1, the intesity that we'll overlay a color on subimages to insert into main image
outputWidth?: null | number // width in pixels of the output image (DEFAULT: original width)
outputType?: AvailableFormatInfo | string
algo?: 'random' | 'closestColor' // how the sub images will be dispersed to build the mosaic
} | the_stack |
import { AfterViewInit, ChangeDetectorRef, Component, ElementRef, Input, OnChanges, SimpleChanges, ViewChild } from '@angular/core';
import { DatabaseInfo } from '@deepkit/orm-browser-api';
import { graphlib, layout } from 'dagre';
import { default as createPanZoom, PanZoom } from 'panzoom';
import { BrowserText } from './browser-text';
import {
isAutoIncrementType,
isBackReferenceType,
isPrimaryKeyType,
isReferenceType,
isSetType,
ReflectionClass,
ReflectionKind,
resolveClassType,
stringifyType,
Type,
TypeProperty,
TypePropertySignature
} from '@deepkit/type';
type EdgeNode = { d: string, class?: string };
type DKNode = { entity: ReflectionClass<any>, properties: (TypeProperty | TypePropertySignature)[], height: number, width: number, x: number, y: number };
@Component({
selector: 'database-graph',
template: `
<div class="nodes" (dblclick)="zoomToFit()"
#graph
[style.width.px]="graphWidth"
[style.height.px]="graphHeight">
<svg
[style.width.px]="graphWidth"
[style.height.px]="graphHeight">
<path
*ngFor="let edge of edges"
[attr.d]="edge.d" [class]="edge.class"></path>
</svg>
<div
*ngFor="let node of nodes"
[style.left.px]="(node.x - (node.width/2))"
[style.top.px]="(node.y - (node.height/2))"
[style.width.px]="node.width"
[style.height.px]="node.height"
class="node">
<ng-container *ngIf="node.property">
{{node.property.name}}
</ng-container>
<ng-container *ngIf="node.entity && node.properties">
<div class="header">
{{node.entity.getClassName()}}
</div>
<div *ngFor="let property of node.properties">
{{propertyLabel(property)}}
</div>
</ng-container>
</div>
</div>
`,
styleUrls: ['./database-graph.component.scss']
})
export class DatabaseGraphComponent implements OnChanges, AfterViewInit {
@Input() database?: DatabaseInfo;
nodes: any[] = [];
edges: EdgeNode[] = [];
svg?: any;
inner?: any;
zoom?: any;
width: number = 1000;
height: number = 500;
graphWidth: number = 500;
graphHeight: number = 500;
browserText = new BrowserText();
@ViewChild('graph') graphElement?: ElementRef<HTMLDivElement>;
graphPanZoom?: PanZoom;
constructor(
protected cd: ChangeDetectorRef,
protected host: ElementRef<HTMLElement>,
) {
}
ngOnChanges(changes: SimpleChanges): void {
if (changes.database) this.loadGraph();
}
ngAfterViewInit(): void {
// if (!this.cards) return;
// this.cards.changes.subscribe((cards) => {
// this.loadCards(cards);
// });
// this.loadCards(this.cards.toArray());
setTimeout(() => this.loadGraph(), 100);
}
// protected loadCards(cards: WorkflowCardComponent[]) {
// for (const card of cards) {
// this.cardMap[card.name] = card;
// }
// this.cd.detectChanges();
// }
public propertyLabel(property: TypeProperty | TypePropertySignature): string {
let type = stringifyType(property.type, { showFullDefinition: false });
if (isPrimaryKeyType(property.type)) {
type += ' & PrimaryKey';
}
if (isAutoIncrementType(property.type)) {
type += ' & AutoIncrement';
}
if (isReferenceType(property.type)) {
type += ' & Reference';
}
if (isBackReferenceType(property.type)) {
type += ' & BackReference';
}
// if (property.isReference) type = 'Reference<' + type + '>';
// if (property.backReference) type = 'BackReference<' + type + '>';
// if (isPrim property.isId) type = 'Primary<' + type + '>';
return String(property.name) + (property.optional ? '?' : '') + ': ' + type;
}
protected loadGraph() {
if (!this.database) return;
const g = new graphlib.Graph({ directed: true, compound: true, multigraph: false });
g.setGraph({
nodesep: 50,
ranksep: 50,
rankdir: 'LR',
align: 'DL',
// rankdir: 'LR',
// ranker: 'longest-path'
});
g.setDefaultEdgeLabel(() => {
return { labelpos: 'c', labeloffset: 0 };
});
this.nodes = [];
this.edges = [];
const propertyHeight = 16;
const propertyListOffset = 28;
// for (const node of this.workflow.places) {
// g.setNode(node, { label: node, width, height });
// }
for (const entity of this.database.getClassSchemas()) {
const properties = [...entity.getProperties()].map(v => v.property);
let maxWidth = this.browserText.getDimensions(entity.getClassName()).width + 25;
for (const property of properties) {
const w = this.browserText.getDimensions(this.propertyLabel(property)).width + 25;
if (w > maxWidth) maxWidth = w;
}
g.setNode(entity.getName(), { entity: entity, properties, width: maxWidth, height: propertyListOffset + (entity.getProperties().length * propertyHeight), });
}
function addEdge(entity: ReflectionClass<any>, rootType: Type, property: Type) {
if (property.kind === ReflectionKind.array) {
addEdge(entity, rootType, property.type);
} else if (isSetType(property) && property.typeArguments) {
addEdge(entity, rootType, property.typeArguments[0]);
} else if (property.kind === ReflectionKind.class || property.kind === ReflectionKind.objectLiteral) {
g.setEdge(entity.getName(), ReflectionClass.from(property).getName());
}
}
for (const entity of this.database.getClassSchemas()) {
for (const property of entity.getProperties()) {
addEdge(entity, property.type, property.type);
}
}
try {
layout(g);
} catch (error) {
console.error('Could not calc layout for graph', error);
}
// dagre calcs sometimes edges with minus coordinates. We forbid that and
// offset everything back
let offsetX = 0;
let offsetY = 0;
this.graphWidth = g.graph().width || 0;
this.graphHeight = g.graph().height || 0;
offsetX = offsetX * -1;
offsetY = offsetY * -1;
// now adjust everything
if (offsetX !== 0 || offsetY !== 0) {
this.graphWidth += offsetX;
this.graphHeight += offsetY;
for (const edge of g.edges()) {
const points = g.edge(edge).points;
if (!points) continue;
for (const item of points) {
item.x += offsetX;
item.y += offsetY;
}
}
for (const nodeId of g.nodes()) {
const node = g.node(nodeId);
node.x += offsetX;
node.y += offsetY;
}
}
const nodeMap: { [name: string]: DKNode } = {};
for (const nodeName of g.nodes()) {
const node = g.node(nodeName);
if (!node) continue;
nodeMap[nodeName] = node as any;
// if (node.width + (node.x - (width / 2)) > this.graphWidth) {
// this.graphWidth = node.width + (node.x - (width / 2));
// }
// if (node.height + (node.y - (height / 2)) > this.graphHeight) {
// this.graphHeight = node.height + (node.y - (height / 2));
// }
this.nodes.push(node as any);
}
const extractEdges = (i: number, node: DKNode, rootProperty: TypePropertySignature | TypeProperty, type: Type) => {
if (type.kind === ReflectionKind.array) {
extractEdges(i, node, rootProperty, type.type);
} else if (isSetType(type) && type.typeArguments) {
extractEdges(i, node, rootProperty, type.typeArguments[0]);
} else if (type.kind === ReflectionKind.class || type.kind === ReflectionKind.objectLiteral) {
const schema = resolveClassType(type);
const toNode = nodeMap[schema.getName()];
if (!toNode) return;
let from = { x: node.x - Math.floor(node.width / 2), y: node.y - Math.floor(node.height / 2) };
let to = { x: toNode.x - Math.floor(toNode.width / 2), y: toNode.y - Math.floor(toNode.height / 2) + Math.floor(propertyListOffset / 2) };
if (to.x > from.x) {
from.x += node.width;
} else if (from.x > to.x) {
to.x += toNode.width;
}
from.y += propertyListOffset + (i * propertyHeight) + Math.floor(propertyHeight / 2);
if (from.x > to.x) {
const t = from;
from = to;
to = t;
}
const middleX = to.x - Math.floor(Math.abs(to.x - from.x) / 2);
const edge: EdgeNode = { d: `M ${from.x} ${from.y} C ${middleX} ${from.y} ${middleX} ${to.y} ${to.x} ${to.y}` };
if (isBackReferenceType(rootProperty.type)) {
edge.class = 'back-reference';
} else if (!isReferenceType(rootProperty.type)) {
edge.class = 'embedded';
}
this.edges.push(edge);
}
};
for (const nodeName of g.nodes()) {
const node = nodeMap[nodeName];
if (!node) continue;
for (let i = 0; i < node.properties.length; i++) {
const property = node.properties[i];
extractEdges(i, node, property, property.type);
}
}
// for (const edge of g.edges()) {
// const points = g.edge(edge).points;
// const d: string[] = [];
// d.push('M ' + (points[0].x + 0.5) + ',' + (points[0].y + 0.5));
// if (points[0].y > this.graphHeight) this.graphHeight = points[0].y + 1;
// for (let i = 1; i < points.length; i++) {
// if (points[i].y > this.graphHeight) this.graphHeight = points[i].y + 1;
// d.push('L ' + (points[i].x + 0.5) + ',' + (points[i].y + 0.5));
// }
// this.edges.push(d.join(' '));
// }
this.cd.detectChanges();
if (this.graphElement) {
if (!this.graphPanZoom) {
this.graphPanZoom = createPanZoom(this.graphElement.nativeElement, {
bounds: true,
zoomSpeed: 0.065,
zoomDoubleClickSpeed: 1
});
this.zoomToFit(true);
} else if (true) {
this.zoomToFit(true);
}
}
this.cd.detectChanges();
}
async zoomToFit(force: boolean = false) {
this._zoomToFit();
requestAnimationFrame(this._zoomToFit.bind(this, force));
}
async _zoomToFit(force: boolean = false) {
try {
if (this.graphElement && this.graphPanZoom) {
const svg = this.graphElement.nativeElement;
const rectParent = this.host.nativeElement.getBoundingClientRect();
const rectScene = svg.getBoundingClientRect();
const xys = this.graphPanZoom.getTransform();
const originWidth = rectScene.width / xys.scale;
const originHeight = rectScene.height / xys.scale;
const zoomX = (rectParent.width - 20) / originWidth;
const zoomY = (rectParent.height - 20) / originHeight;
let targetScale = zoomX < zoomY ? zoomX : zoomY;
if (!force) {
if (xys.scale > 1.001) {
//zoom back to 100% first before to bigpicture
this.graphPanZoom.smoothZoomAbs(
rectParent.width / 2,
rectParent.height / 2,
1,
);
return;
} else if (Math.abs(targetScale - xys.scale) < 0.005) {
//when target scale is the same as currently, we reset back to 100%, so it acts as toggle.
//reset to 100%
targetScale = 1;
}
}
targetScale = Math.min(1, targetScale);
const targetWidth = originWidth * xys.scale;
const targetHeight = originHeight * xys.scale;
const newX = targetWidth > rectParent.width ? -(targetWidth / 2) + rectParent.width / 2 : (rectParent.width / 2) - (targetWidth / 2);
const newY = targetHeight > rectParent.height ? -(targetHeight / 2) + rectParent.height / 2 : (rectParent.height / 2) - (targetHeight / 2);
//we need to cancel current running animations
this.graphPanZoom.pause();
this.graphPanZoom.resume();
this.graphPanZoom.moveBy(
Math.floor(newX - xys.x),
Math.floor(newY - xys.y),
false
);
//correct way to zoom with center of graph as origin when scaled
this.graphPanZoom.smoothZoomAbs(
Math.floor(xys.x + originWidth * xys.scale / 2),
Math.floor(xys.y + originHeight * xys.scale / 2),
1,
);
}
} catch (error) {
console.log('error zooming', error);
}
}
} | the_stack |
import { Test, ExpectType } from "../test";
import {
IsNever,
IsAny,
IsUnion,
IteratedType,
GeneratorNextType,
GeneratorReturnType,
AsyncGeneratorNextType,
AsyncGeneratorReturnType,
PromisedType,
// UnionToIntersection,
Intersection,
IsCallable,
IsConstructable,
IsUnknown,
IsSubtypeOf,
Not,
And,
Or,
XOr,
Every,
Some,
One,
SameType,
SameTypes,
Relatable,
Overlaps,
IsSubsetOf,
IsSupersetOf,
IsProperSubsetOf,
IsProperSupersetOf,
MatchingKeys,
FunctionKeys,
Constructor,
Await,
AwaitAll,
Shift,
Unshift,
Reverse,
Pop,
Push,
Disjoin,
Conjoin,
DisjoinOverlaps,
IsEmpty,
Diff,
Intersect,
Assign,
AsyncIteratedType,
Union
} from "..";
it("type-model", () => {
// Only Type-only tests are provided, below.
});
// #region IteratedType tests
{
type _ = [
Test<ExpectType<IteratedType<Iterable<number>>, number>>,
Test<ExpectType<IteratedType<Generator<number>>, number>>,
// post TS 3.6 behavior
Test<ExpectType<IteratedType<{ [Symbol.iterator](): { next(): { done: false, value: number } } }>, number>>,
Test<ExpectType<IteratedType<{ [Symbol.iterator](): { next(): { done?: false, value: number } } }>, number>>,
Test<ExpectType<IteratedType<{ [Symbol.iterator](): { next(): { value: number } } }>, number>>,
Test<ExpectType<IteratedType<{ [Symbol.iterator](): { next(): { done: true, value: number } } }>, never>>,
// pre TS 3.6 behavior
Test<ExpectType<IteratedType<{ [Symbol.iterator](): { next(): { done: boolean, value: number } } }>, number>>,
];
}
// #endregion IteratedType tests
// #region GeneratorReturnType tests
{
type _ = [
Test<ExpectType<GeneratorReturnType<Iterable<number>>, any>>,
Test<ExpectType<GeneratorReturnType<Generator<number, string, boolean>>, string>>,
Test<ExpectType<GeneratorReturnType<{ [Symbol.iterator](): { next(): { done: true, value: number } } }>, number>>,
Test<ExpectType<GeneratorReturnType<{ [Symbol.iterator](): { next(): { done: false, value: number } } }>, never>>,
Test<ExpectType<GeneratorReturnType<{ [Symbol.iterator](): { next(): { done: boolean, value: number } } }>, number>>,
Test<ExpectType<GeneratorReturnType<{ [Symbol.iterator](): { next(): { done?: false, value: number } } }>, never>>,
];
}
// #endregion GeneratorReturnType tests
// #region GeneratorNextType tests
{
type _ = [
Test<ExpectType<GeneratorNextType<Iterable<number>>, undefined>>,
Test<ExpectType<GeneratorNextType<Generator<"a", "b", number>>, number>>,
Test<ExpectType<GeneratorNextType<{ [Symbol.iterator](): { next(value?: number): any } }>, number>>,
];
}
// #endregion GeneratorNextType tests
// #region AsyncIteratedType tests
{
type _ = [
Test<ExpectType<AsyncIteratedType<AsyncIterable<number>>, number>>,
Test<ExpectType<AsyncIteratedType<{ [Symbol.asyncIterator](): { next(): Promise<{ done: false, value: number }> } }>, number>>,
Test<ExpectType<AsyncIteratedType<{ [Symbol.asyncIterator](): { next(): Promise<{ done: false, value: Promise<number> }> } }>, number>>,
Test<ExpectType<AsyncIteratedType<{ [Symbol.asyncIterator](): { next(): Promise<{ done: false, value: Promise<Promise<number>> }> } }>, number>>,
];
}
// #endregion AsyncIteratedType tests
// #region AsyncGeneratorNextType tests
{
type _ = [
Test<ExpectType<AsyncGeneratorNextType<{ [Symbol.asyncIterator](): { next(value?: number): any } }>, number>>,
];
}
// #endregion AsyncGeneratorNextType tests
// #region AsyncGeneratorReturnType tests
{
type _ = [
Test<ExpectType<AsyncGeneratorReturnType<{ [Symbol.asyncIterator](): { next(): Promise<{ done: true, value: number }> } }>, number>>,
];
}
// #endregion AsyncGeneratorReturnType tests
// #region PromisedType tests
{
type _ = [
Test<ExpectType<PromisedType<number>, never>>,
Test<ExpectType<PromisedType<{ then(): any }>, never>>,
Test<ExpectType<PromisedType<{ then(cb: (x: number) => void): any }>, number>>,
Test<ExpectType<PromisedType<Promise<Promise<number>>>, Promise<number>>>,
];
}
// #endregion
// // #region UnionToIntersection tests
// {
// type _ = [
// __Test<__ExpectType<UnionToIntersection<1 | 2>, 1 & 2>>,
// __Test<__ExpectType<UnionToIntersection<1 | never>, 1>>,
// __Test<__ExpectType<UnionToIntersection<1 | unknown>, unknown>>,
// ];
// }
// // #endregion
// #region Intersection tests
{
type _ = [
Test<ExpectType<Intersection<[1, 2]>, 1 & 2>>,
Test<ExpectType<Intersection<[1, never]>, never>>,
Test<ExpectType<Intersection<[1, unknown]>, 1>>,
];
}
// #endregion
// #region Union tests
{
type _ = [
Test<ExpectType<Union<[1, 2]>, 1 | 2>>,
Test<ExpectType<Union<[1, never]>, 1>>,
Test<ExpectType<Union<[1, unknown]>, unknown>>,
];
}
// #endregion
// #region IsAny tests
{
type _ = [
Test<ExpectType<IsAny<any>, true>>,
Test<ExpectType<IsAny<never>, false>>,
Test<ExpectType<IsAny<unknown>, false>>,
Test<ExpectType<IsAny<number>, false>>,
];
}
// #endregion IsAny tests
// #region IsNever tests
{
type _ = [
Test<ExpectType<IsNever<never>, true>>,
Test<ExpectType<IsNever<any>, false>>,
Test<ExpectType<IsNever<unknown>, false>>,
Test<ExpectType<IsNever<number>, false>>,
];
}
// #endregion IsNever tests
// #region IsUnion tests
{
const enum E { One, Two }
type _ = [
Test<ExpectType<IsUnion<never>, false>>,
Test<ExpectType<IsUnion<any>, false>>,
Test<ExpectType<IsUnion<1>, false>>,
Test<ExpectType<IsUnion<1 | 2>, true>>,
Test<ExpectType<IsUnion<number>, false>>,
Test<ExpectType<IsUnion<boolean>, true>>,
Test<ExpectType<IsUnion<E>, true>>,
];
}
// #endregion IsUnion tests
// #region IsCallable tests
{
type A = { (): void, new (): void };
type _ = [
Test<ExpectType<IsCallable<any>, boolean>>,
Test<ExpectType<IsCallable<never>, never>>,
Test<ExpectType<IsCallable<string>, false>>,
Test<ExpectType<IsCallable<{}>, false>>,
Test<ExpectType<IsCallable<Function>, true>>,
Test<ExpectType<IsCallable<() => void>, true>>,
Test<ExpectType<IsCallable<new () => void>, false>>,
Test<ExpectType<IsCallable<A>, true>>,
];
}
// #endregion IsCallable tests
// #region IsConstructable tests
{
type A = { (): void, new (): void };
type _ = [
Test<ExpectType<IsConstructable<any>, boolean>>,
Test<ExpectType<IsConstructable<never>, never>>,
Test<ExpectType<IsConstructable<string>, false>>,
Test<ExpectType<IsConstructable<{}>, false>>,
Test<ExpectType<IsConstructable<Function>, true>>,
Test<ExpectType<IsConstructable<new () => void>, true>>,
Test<ExpectType<IsConstructable<() => void>, false>>,
Test<ExpectType<IsConstructable<A>, true>>,
];
}
// #endregion IsConstructable tests
// #region IsUnknown tests
{
type _ = [
Test<ExpectType<IsUnknown<unknown>, true>>,
Test<ExpectType<IsUnknown<never>, false>>,
Test<ExpectType<IsUnknown<any>, false>>,
Test<ExpectType<IsUnknown<1>, false>>,
];
}
// #endregion IsUnknown tests
// #region IsSubtypeOf tests
{
type _ = [
Test<ExpectType<IsSubtypeOf<never, never>, true>>,
Test<ExpectType<IsSubtypeOf<never, 1>, true>>,
Test<ExpectType<IsSubtypeOf<1, never>, false>>,
Test<ExpectType<IsSubtypeOf<any, any>, true>>,
Test<ExpectType<IsSubtypeOf<any, 1>, true>>,
Test<ExpectType<IsSubtypeOf<1, any>, true>>,
Test<ExpectType<IsSubtypeOf<unknown, unknown>, true>>,
Test<ExpectType<IsSubtypeOf<unknown, 1>, false>>,
Test<ExpectType<IsSubtypeOf<1, unknown>, true>>,
];
}
// #endregion IsSubtypeOf tests
// #region Not tests
{
type _ = [
Test<ExpectType<Not<true>, false>>,
Test<ExpectType<Not<false>, true>>,
Test<ExpectType<Not<boolean>, boolean>>,
Test<ExpectType<Not<any>, boolean>>,
Test<ExpectType<Not<never>, never>>,
];
}
// #endregion Not tests
// #region And tests
{
type _ = [
Test<ExpectType<And<true, true>, true>>,
Test<ExpectType<And<false, false>, false>>,
Test<ExpectType<And<true, false>, false>>,
Test<ExpectType<And<false, true>, false>>,
Test<ExpectType<And<boolean, true>, boolean>>,
Test<ExpectType<And<boolean, false>, false>>,
Test<ExpectType<And<true, boolean>, boolean>>,
Test<ExpectType<And<false, boolean>, false>>,
Test<ExpectType<And<boolean, boolean>, boolean>>,
Test<ExpectType<And<any, true>, boolean>>,
Test<ExpectType<And<any, false>, false>>,
Test<ExpectType<And<true, any>, boolean>>,
Test<ExpectType<And<false, any>, false>>,
Test<ExpectType<And<any, any>, boolean>>,
Test<ExpectType<And<never, true>, never>>,
Test<ExpectType<And<never, false>, never>>,
Test<ExpectType<And<true, never>, never>>,
Test<ExpectType<And<false, never>, never>>,
Test<ExpectType<And<never, never>, never>>,
];
}
// #endregion And tests
// #region Or tests
{
type _ = [
Test<ExpectType<Or<true, true>, true>>,
Test<ExpectType<Or<false, false>, false>>,
Test<ExpectType<Or<true, false>, true>>,
Test<ExpectType<Or<false, true>, true>>,
Test<ExpectType<Or<boolean, true>, true>>,
Test<ExpectType<Or<boolean, false>, boolean>>,
Test<ExpectType<Or<true, boolean>, true>>,
Test<ExpectType<Or<false, boolean>, boolean>>,
Test<ExpectType<Or<boolean, boolean>, boolean>>,
Test<ExpectType<Or<any, true>, true>>,
Test<ExpectType<Or<any, false>, boolean>>,
Test<ExpectType<Or<true, any>, true>>,
Test<ExpectType<Or<false, any>, boolean>>,
Test<ExpectType<Or<any, any>, boolean>>,
Test<ExpectType<Or<never, true>, never>>,
Test<ExpectType<Or<never, false>, never>>,
Test<ExpectType<Or<true, never>, never>>,
Test<ExpectType<Or<false, never>, never>>,
Test<ExpectType<Or<never, never>, never>>,
];
}
// #endregion Or tests
// #region XOr tests
{
type _ = [
Test<ExpectType<XOr<true, true>, false>>,
Test<ExpectType<XOr<false, false>, false>>,
Test<ExpectType<XOr<true, false>, true>>,
Test<ExpectType<XOr<false, true>, true>>,
Test<ExpectType<XOr<boolean, true>, boolean>>,
Test<ExpectType<XOr<boolean, false>, boolean>>,
Test<ExpectType<XOr<true, boolean>, boolean>>,
Test<ExpectType<XOr<false, boolean>, boolean>>,
Test<ExpectType<XOr<boolean, boolean>, boolean>>,
Test<ExpectType<XOr<any, true>, boolean>>,
Test<ExpectType<XOr<any, false>, boolean>>,
Test<ExpectType<XOr<true, any>, boolean>>,
Test<ExpectType<XOr<false, any>, boolean>>,
Test<ExpectType<XOr<any, any>, boolean>>,
Test<ExpectType<XOr<never, true>, never>>,
Test<ExpectType<XOr<never, false>, never>>,
Test<ExpectType<XOr<true, never>, never>>,
Test<ExpectType<XOr<false, never>, never>>,
Test<ExpectType<XOr<never, never>, never>>,
];
}
// #endregion XOr tests
// #region Every tests
{
type _ = [
Test<ExpectType<Every<[true, true]>, true>>,
Test<ExpectType<Every<[true, true, true]>, true>>,
Test<ExpectType<Every<[true, true, false]>, false>>,
Test<ExpectType<Every<[false, false]>, false>>,
Test<ExpectType<Every<[true, false]>, false>>,
Test<ExpectType<Every<[false, true]>, false>>,
Test<ExpectType<Every<[boolean, true]>, boolean>>,
Test<ExpectType<Every<[boolean, false]>, false>>,
Test<ExpectType<Every<[true, boolean]>, boolean>>,
Test<ExpectType<Every<[false, boolean]>, false>>,
Test<ExpectType<Every<[boolean, boolean]>, boolean>>,
Test<ExpectType<Every<[any, true]>, boolean>>,
Test<ExpectType<Every<[any, false]>, false>>,
Test<ExpectType<Every<[true, any]>, boolean>>,
Test<ExpectType<Every<[false, any]>, false>>,
Test<ExpectType<Every<[any, any]>, boolean>>,
Test<ExpectType<Every<[never, true]>, never>>,
Test<ExpectType<Every<[never, false]>, never>>,
Test<ExpectType<Every<[true, never]>, never>>,
Test<ExpectType<Every<[false, never]>, never>>,
Test<ExpectType<Every<[never, never]>, never>>,
Test<ExpectType<Every<[]>, never>>,
]
}
// #endregion Every tests
// #region Some tests
{
type _ = [
Test<ExpectType<Some<[true, true]>, true>>,
Test<ExpectType<Some<[false, false]>, false>>,
Test<ExpectType<Some<[true, false]>, true>>,
Test<ExpectType<Some<[false, true]>, true>>,
Test<ExpectType<Some<[boolean, true]>, true>>,
Test<ExpectType<Some<[boolean, false]>, boolean>>,
Test<ExpectType<Some<[true, boolean]>, true>>,
Test<ExpectType<Some<[false, boolean]>, boolean>>,
Test<ExpectType<Some<[boolean, boolean]>, boolean>>,
Test<ExpectType<Some<[any, true]>, true>>,
Test<ExpectType<Some<[any, false]>, boolean>>,
Test<ExpectType<Some<[true, any]>, true>>,
Test<ExpectType<Some<[false, any]>, boolean>>,
Test<ExpectType<Some<[any, any]>, boolean>>,
Test<ExpectType<Some<[never, true]>, never>>,
Test<ExpectType<Some<[never, false]>, never>>,
Test<ExpectType<Some<[true, never]>, never>>,
Test<ExpectType<Some<[false, never]>, never>>,
Test<ExpectType<Some<[never, never]>, never>>,
Test<ExpectType<Some<[]>, never>>,
]
}
// #endregion Some tests
// #region One tests
{
type _ = [
Test<ExpectType<One<[true, true]>, false>>,
Test<ExpectType<One<[false, false]>, false>>,
Test<ExpectType<One<[true, false]>, true>>,
Test<ExpectType<One<[false, true]>, true>>,
Test<ExpectType<One<[boolean, true]>, boolean>>,
Test<ExpectType<One<[boolean, false]>, boolean>>,
Test<ExpectType<One<[true, boolean]>, boolean>>,
Test<ExpectType<One<[false, boolean]>, boolean>>,
Test<ExpectType<One<[boolean, boolean]>, boolean>>,
Test<ExpectType<One<[any, true]>, boolean>>,
Test<ExpectType<One<[any, false]>, boolean>>,
Test<ExpectType<One<[true, any]>, boolean>>,
Test<ExpectType<One<[false, any]>, boolean>>,
Test<ExpectType<One<[any, any]>, boolean>>,
Test<ExpectType<One<[never, true]>, never>>,
Test<ExpectType<One<[never, false]>, never>>,
Test<ExpectType<One<[true, never]>, never>>,
Test<ExpectType<One<[false, never]>, never>>,
Test<ExpectType<One<[never, never]>, never>>,
Test<ExpectType<One<[]>, never>>,
]
}
// #endregion One tests
// #region SameType tests
{
type A = { a: number };
type B = { b: number };
type Ab = { a: number, b?: number };
type Ac = { a: number, c?: number };
type Ba = { b: number, a?: number };
type _ = [
Test<ExpectType<SameType<any, any>, true>>,
Test<ExpectType<SameType<never, never>, true>>,
Test<ExpectType<SameType<unknown, unknown>, true>>,
Test<ExpectType<SameType<any, true>, true>>,
Test<ExpectType<SameType<never, true>, false>>,
Test<ExpectType<SameType<unknown, true>, false>>,
Test<ExpectType<SameType<true, true>, true>>,
Test<ExpectType<SameType<false, true>, false>>,
Test<ExpectType<SameType<A, A>, true>>,
Test<ExpectType<SameType<A, B>, false>>,
Test<ExpectType<SameType<Ab, Ba>, false>>,
Test<ExpectType<SameType<Ab, Ac>, true>>,
Test<ExpectType<SameType<true, any>, true>>,
Test<ExpectType<SameType<true, never>, false>>,
Test<ExpectType<SameType<true, unknown>, false>>,
];
}
// #endregion SameType tests
// TODO(rbuckton): Depends on recursion in object types, which is currently unsafe.
// #region SameTypes tests
{
type A = { a: number };
type B = { b: number };
type Ab = { a: number, b?: number };
type Ac = { a: number, c?: number };
type Ba = { b: number, a?: number };
type _ = [
Test<ExpectType<SameTypes<never>, never>>,
Test<ExpectType<SameTypes<[]>, never>>,
Test<ExpectType<SameTypes<[any, any]>, true>>,
Test<ExpectType<SameTypes<[never, never]>, true>>,
Test<ExpectType<SameTypes<[unknown, unknown]>, true>>,
Test<ExpectType<SameTypes<[any, true]>, true>>,
Test<ExpectType<SameTypes<[never, true]>, false>>,
Test<ExpectType<SameTypes<[unknown, true]>, false>>,
Test<ExpectType<SameTypes<[true, true]>, true>>,
Test<ExpectType<SameTypes<[false, true]>, false>>,
Test<ExpectType<SameTypes<[A, A]>, true>>,
Test<ExpectType<SameTypes<[A, B]>, false>>,
Test<ExpectType<SameTypes<[Ab, Ba]>, false>>,
Test<ExpectType<SameTypes<[Ab, Ac]>, true>>,
Test<ExpectType<SameTypes<[true, any]>, true>>,
Test<ExpectType<SameTypes<[true, never]>, false>>,
Test<ExpectType<SameTypes<[true, unknown]>, false>>,
];
}
// #endregion SameTypes tests
// #region Relatable tests
{
type _ = [
Test<ExpectType<Relatable<any, any>, true>>,
Test<ExpectType<Relatable<any, any>, true>>,
Test<ExpectType<Relatable<any, number>, true>>,
Test<ExpectType<Relatable<number, any>, true>>,
Test<ExpectType<Relatable<number, number>, true>>,
Test<ExpectType<Relatable<number, 1>, true>>,
Test<ExpectType<Relatable<1, number>, true>>,
Test<ExpectType<Relatable<1, 2>, false>>,
Test<ExpectType<Relatable<1 | 2, 3 | 4>, false>>,
Test<ExpectType<Relatable<1 | 2, 2 | 3>, false>>,
Test<ExpectType<Relatable<never, any>, false>>,
Test<ExpectType<Relatable<any, never>, false>>,
Test<ExpectType<Relatable<never, never>, false>>,
];
}
// #endregion Relatable tests
// #region Overlaps tests
{
type _ = [
Test<ExpectType<Overlaps<any, any>, true>>,
Test<ExpectType<Overlaps<any, any>, true>>,
Test<ExpectType<Overlaps<any, number>, true>>,
Test<ExpectType<Overlaps<number, any>, true>>,
Test<ExpectType<Overlaps<number, number>, true>>,
Test<ExpectType<Overlaps<number, 1>, true>>,
Test<ExpectType<Overlaps<1, number>, true>>,
Test<ExpectType<Overlaps<1, 2>, false>>,
Test<ExpectType<Overlaps<1 | 2, 3 | 4>, false>>,
Test<ExpectType<Overlaps<1 | 2, 2 | 3>, true>>,
Test<ExpectType<Overlaps<never, any>, false>>,
Test<ExpectType<Overlaps<any, never>, false>>,
Test<ExpectType<Overlaps<never, never>, false>>,
];
}
// #endregion Overlaps tests
// #region IsSubsetOf tests
{
type _ = [
Test<ExpectType<IsSubsetOf<any, any>, boolean>>,
Test<ExpectType<IsSubsetOf<any, 1>, boolean>>,
Test<ExpectType<IsSubsetOf<1, any>, boolean>>,
Test<ExpectType<IsSubsetOf<never, never>, true>>,
Test<ExpectType<IsSubsetOf<never, 1>, true>>,
Test<ExpectType<IsSubsetOf<1, never>, false>>,
Test<ExpectType<IsSubsetOf<unknown, unknown>, false>>,
Test<ExpectType<IsSubsetOf<unknown, 1>, false>>,
Test<ExpectType<IsSubsetOf<1, unknown>, true>>,
Test<ExpectType<IsSubsetOf<number, number>, true>>,
Test<ExpectType<IsSubsetOf<1, 1>, true>>,
Test<ExpectType<IsSubsetOf<1, number>, true>>,
Test<ExpectType<IsSubsetOf<1, 1 | 2>, true>>,
Test<ExpectType<IsSubsetOf<number, 1>, false>>,
Test<ExpectType<IsSubsetOf<1 | 2, 1>, false>>,
];
}
// #endregion IsSubsetOf tests
// #region IsSupersetOf tests
{
type _ = [
Test<ExpectType<IsSupersetOf<any, any>, boolean>>,
Test<ExpectType<IsSupersetOf<any, 1>, boolean>>,
Test<ExpectType<IsSupersetOf<1, any>, boolean>>,
Test<ExpectType<IsSupersetOf<never, never>, true>>,
Test<ExpectType<IsSupersetOf<never, 1>, false>>,
Test<ExpectType<IsSupersetOf<1, never>, true>>,
Test<ExpectType<IsSupersetOf<unknown, unknown>, false>>,
Test<ExpectType<IsSupersetOf<unknown, 1>, true>>,
Test<ExpectType<IsSupersetOf<1, unknown>, false>>,
Test<ExpectType<IsSupersetOf<number, number>, true>>,
Test<ExpectType<IsSupersetOf<1, 1>, true>>,
Test<ExpectType<IsSupersetOf<1, number>, false>>,
Test<ExpectType<IsSupersetOf<1, 1 | 2>, false>>,
Test<ExpectType<IsSupersetOf<number, 1>, true>>,
Test<ExpectType<IsSupersetOf<1 | 2, 1>, true>>,
];
}
// #endregion IsSubsetOf tests
// #region IsProperSubsetOf tests
{
type _ = [
Test<ExpectType<IsProperSubsetOf<any, any>, boolean>>,
Test<ExpectType<IsProperSubsetOf<any, 1>, boolean>>,
Test<ExpectType<IsProperSubsetOf<1, any>, boolean>>,
Test<ExpectType<IsProperSubsetOf<never, never>, false>>,
Test<ExpectType<IsProperSubsetOf<never, 1>, true>>,
Test<ExpectType<IsProperSubsetOf<1, never>, false>>,
Test<ExpectType<IsProperSubsetOf<unknown, unknown>, false>>,
Test<ExpectType<IsProperSubsetOf<unknown, 1>, false>>,
Test<ExpectType<IsProperSubsetOf<1, unknown>, true>>,
Test<ExpectType<IsProperSubsetOf<number, number>, false>>,
Test<ExpectType<IsProperSubsetOf<1, 1>, false>>,
Test<ExpectType<IsProperSubsetOf<1, number>, true>>,
Test<ExpectType<IsProperSubsetOf<1, 1 | 2>, true>>,
Test<ExpectType<IsProperSubsetOf<number, 1>, false>>,
Test<ExpectType<IsProperSubsetOf<1 | 2, 1>, false>>,
];
}
// #endregion IsProperSubsetOf tests
// #region IsProperSupersetOf tests
{
type _ = [
Test<ExpectType<IsProperSupersetOf<any, any>, boolean>>,
Test<ExpectType<IsProperSupersetOf<any, 1>, boolean>>,
Test<ExpectType<IsProperSupersetOf<1, any>, boolean>>,
Test<ExpectType<IsProperSupersetOf<never, never>, false>>,
Test<ExpectType<IsProperSupersetOf<never, 1>, false>>,
Test<ExpectType<IsProperSupersetOf<1, never>, true>>,
Test<ExpectType<IsProperSupersetOf<unknown, unknown>, false>>,
Test<ExpectType<IsProperSupersetOf<unknown, 1>, true>>,
Test<ExpectType<IsProperSupersetOf<1, unknown>, false>>,
Test<ExpectType<IsProperSupersetOf<number, number>, false>>,
Test<ExpectType<IsProperSupersetOf<1, 1>, false>>,
Test<ExpectType<IsProperSupersetOf<1, number>, false>>,
Test<ExpectType<IsProperSupersetOf<1, 1 | 2>, false>>,
Test<ExpectType<IsProperSupersetOf<number, 1>, true>>,
Test<ExpectType<IsProperSupersetOf<1 | 2, 1>, true>>,
];
}
// #endregion IsProperSupersetOf tests
// #region MatchingKeys tests
{
type A = { a: number, b: string, c: number };
type _ = [
Test<ExpectType<MatchingKeys<A, number>, "a" | "c">>,
Test<ExpectType<MatchingKeys<A, string>, "b">>,
Test<ExpectType<MatchingKeys<A, boolean>, never>>,
];
}
// #endregion MatchingKeys tests
// #region FunctionKeys tests
{
type A = { a(x: string): void, b(x: number): void, c(): void, d: new () => any };
type _ = [
Test<ExpectType<FunctionKeys<A>, "a" | "b" | "c" | "d">>,
Test<ExpectType<FunctionKeys<A, () => void>, "c">>,
Test<ExpectType<FunctionKeys<A, (x: string) => void>, "a" | "c">>,
Test<ExpectType<FunctionKeys<A, (x: number) => void>, "b" | "c">>,
Test<ExpectType<FunctionKeys<A, Constructor>, "d">>,
];
}
// #endregion FunctionKeys tests
// #region Await tests
{
type _ = [
Test<ExpectType<Await<number>, number>>,
Test<ExpectType<Await<{ then(): any }>, never>>,
Test<ExpectType<Await<{ then: number }>, { then: number }>>,
Test<ExpectType<Await<Promise<number>>, number>>,
Test<ExpectType<Await<Promise<Promise<number>>>, number>>,
];
}
// #endregion Await tests
// #region AwaitAll tests
{
type _ = [
Test<ExpectType<AwaitAll<[]>, []>>,
Test<ExpectType<AwaitAll<[number]>, [number]>>,
Test<ExpectType<AwaitAll<[Promise<number>]>, [number]>>,
Test<ExpectType<AwaitAll<[Promise<number>, number]>, [number, number]>>,
];
}
// #endregion AwaitAll tests
// #region Shift tests
{
type _ = [
Test<ExpectType<Shift<[1, 2, 3]>, [1, [2, 3]]>>,
Test<ExpectType<Shift<[1, 2]>, [1, [2]]>>,
Test<ExpectType<Shift<[1]>, [1, []]>>,
Test<ExpectType<Shift<[]>, [never, never]>>,
];
}
// #endregion Shift tests
// #region Unshift tests
{
type _ = [
Test<ExpectType<Unshift<[1, 2], 3>, [3, 1, 2]>>,
Test<ExpectType<Unshift<[1], 2>, [2, 1]>>,
Test<ExpectType<Unshift<[], 1>, [1]>>,
Test<ExpectType<Unshift<never, 1>, never>>,
];
}
// #endregion Unshift tests
// #region Reverse tests
{
type _ = [
Test<ExpectType<Reverse<[1, 2, 3]>, [3, 2, 1]>>,
Test<ExpectType<Reverse<[1, 2]>, [2, 1]>>,
Test<ExpectType<Reverse<[1]>, [1]>>,
Test<ExpectType<Reverse<[]>, []>>,
Test<ExpectType<Reverse<[1, ...number[]]>, [1]>>,
Test<ExpectType<Reverse<never>, never>>,
];
}
// #endregion Reverse tests
// #region Pop tests
{
type _ = [
Test<ExpectType<Pop<[1, 2, 3]>, [3, [1, 2]]>>,
Test<ExpectType<Pop<[1, 2]>, [2, [1]]>>,
Test<ExpectType<Pop<[1]>, [1, []]>>,
Test<ExpectType<Pop<[]>, [never, never]>>,
];
}
// #endregion Pop tests
// TODO(rbuckton): Depends on recursion in object types, which is currently unsafe.
// #region Push tests
{
type _ = [
Test<ExpectType<Push<[1, 2], 3>, [1, 2, 3]>>,
Test<ExpectType<Push<[1], 2>, [1, 2]>>,
Test<ExpectType<Push<[], 1>, [1]>>,
Test<ExpectType<Push<never, 1>, never>>,
]
}
// #endregion Push tests
// #region Disjoin tests
{
type A = { a: number };
type B = { b: number };
type AB = { a: number, b: number };
type AandB = A & B;
type AorB = A | B;
type _ = [
Test<ExpectType<Disjoin<AB>, AorB>>,
Test<ExpectType<Disjoin<AandB>, AorB>>,
Test<ExpectType<Disjoin<A>, A>>,
Test<ExpectType<Disjoin<{}>, {}>>,
Test<ExpectType<Disjoin<never>, never>>,
Test<ExpectType<Disjoin<any>, any>>,
];
}
// #endregion Disjoin tests
// #region Conjoin tests
{
type A = { a: number };
type B = { b: number };
type AB = { a: number, b: number };
type T1 = Conjoin<A | B>;
type _ = [
// NOTE: There is no way in typespace to differentiate between `{ a: number, b: number }` and
// `{ a: number } & { b: number }`, so this needs to be manually verified above.
Test<ExpectType<T1, AB>>,
];
}
// #endregion Conjoin tests
// #region DisjoinOverlaps tests
{
type A = { a: number };
type B = { b: number };
type AB = { a: number, b: number };
type _ = [
Test<ExpectType<DisjoinOverlaps<any, any>, true>>,
Test<ExpectType<DisjoinOverlaps<any, any>, true>>,
Test<ExpectType<DisjoinOverlaps<any, number>, true>>,
Test<ExpectType<DisjoinOverlaps<number, any>, true>>,
Test<ExpectType<DisjoinOverlaps<number, number>, true>>,
Test<ExpectType<DisjoinOverlaps<number, 1>, true>>,
Test<ExpectType<DisjoinOverlaps<1, number>, true>>,
Test<ExpectType<DisjoinOverlaps<1, 2>, false>>,
Test<ExpectType<DisjoinOverlaps<1 | 2, 3 | 4>, false>>,
Test<ExpectType<DisjoinOverlaps<1 | 2, 2 | 3>, true>>,
Test<ExpectType<DisjoinOverlaps<A, B>, false>>,
Test<ExpectType<DisjoinOverlaps<A, AB>, true>>,
Test<ExpectType<DisjoinOverlaps<AB, B>, true>>,
Test<ExpectType<DisjoinOverlaps<never, any>, false>>,
Test<ExpectType<DisjoinOverlaps<any, never>, false>>,
Test<ExpectType<DisjoinOverlaps<never, never>, false>>,
];
}
// #endregion DisjoinOverlaps tests
// #region IsEmpty tests
declare const testSymbol: unique symbol;
{
type _ = [
Test<ExpectType<IsEmpty<{}>, true>>,
Test<ExpectType<IsEmpty<{ a: number }>, false>>,
Test<ExpectType<IsEmpty<{ [a: number]: any }>, false>>,
Test<ExpectType<IsEmpty<{ [testSymbol]: any }>, false>>,
];
}
// #endregion IsEmpty tests
// #region Diff tests
{
type A = { a: number };
type B = { b: number };
type B2 = { b: string };
type AB = { a: number, b: number };
type ABC = { a: number, b: number, c: number };
type AC = { a: number, c: number };
type _ = [
Test<ExpectType<Diff<AB, B>, A>>,
Test<ExpectType<Diff<AB, B2>, A>>,
Test<ExpectType<Diff<ABC, B>, AC>>,
];
}
// #endregion Diff tests
// #region Intersect tests
{
type A = { a: number };
type B = { b: number };
type AB1 = { a: number, b: number };
type AB2 = { a: number, b: string };
type AB1and2 = { a: number, b: number & string };
type AC = { a: number, c: number };
type _ = [
Test<ExpectType<Intersect<AB1, AC>, A>>,
Test<ExpectType<Intersect<AB1, AB2>, AB1and2>>,
Test<ExpectType<Intersect<A, B>, {}>>,
];
}
// #endregion Intersect tests
// #region Assign tests
{
type A = { a: number };
type B = { b: number };
type B2 = { b: string };
type C = { c: number };
type AB = { a: number, b: number };
type AB2 = { a: number, b: string };
type AC = { a: number, c: number };
type BC = { b: number, c: number };
type ABC = { a: number, b: number, c: number };
type _ = [
Test<ExpectType<Assign<A, B>, AB>>,
Test<ExpectType<Assign<AB, AC>, ABC>>,
Test<ExpectType<Assign<AB, C>, ABC>>,
Test<ExpectType<Assign<A, BC>, ABC>>,
Test<ExpectType<Assign<B, ABC>, ABC>>,
Test<ExpectType<Assign<AB, B2>, AB2>>,
];
}
// #endregion Assign tests | the_stack |
import * as anchor from '@project-serum/anchor';
import { assert } from 'chai';
import { Program } from '@project-serum/anchor';
import {
Admin,
BN,
MARK_PRICE_PRECISION,
PositionDirection,
ClearingHouseUser,
OrderRecord,
getMarketOrderParams,
findComputeUnitConsumption,
AMM_RESERVE_PRECISION,
calculateTradeAcquiredAmounts,
convertToNumber,
FeeStructure,
QUOTE_PRECISION,
ZERO,
calculateQuoteAssetAmountSwapped,
} from '../sdk/src';
import {
mockOracle,
mockUSDCMint,
mockUserUSDCAccount,
setFeedPrice,
} from './testHelpers';
import {
calculateBaseAssetAmountMarketCanExecute,
calculateMarkPrice,
getLimitOrderParams,
getSwapDirection,
} from '../sdk';
describe('amm spread: market order', () => {
const provider = anchor.AnchorProvider.local(undefined, {
commitment: 'confirmed',
preflightCommitment: 'confirmed',
});
const connection = provider.connection;
anchor.setProvider(provider);
const chProgram = anchor.workspace.ClearingHouse as Program;
let clearingHouse: Admin;
let clearingHouseUser: ClearingHouseUser;
let usdcMint;
let userUSDCAccount;
// ammInvariant == k == x * y
const mantissaSqrtScale = new BN(Math.sqrt(MARK_PRICE_PRECISION.toNumber()));
const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 13).mul(
mantissaSqrtScale
);
const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 13).mul(
mantissaSqrtScale
);
const usdcAmount = new BN(10 * 10 ** 6);
const marketIndex = new BN(0);
let solUsd;
before(async () => {
usdcMint = await mockUSDCMint(provider);
userUSDCAccount = await mockUserUSDCAccount(usdcMint, usdcAmount, provider);
clearingHouse = Admin.from(
connection,
provider.wallet,
chProgram.programId,
{
commitment: 'confirmed',
}
);
await clearingHouse.initialize(usdcMint.publicKey, true);
await clearingHouse.subscribeToAll();
solUsd = await mockOracle(1);
const periodicity = new BN(60 * 60); // 1 HOUR
await clearingHouse.initializeMarket(
marketIndex,
solUsd,
ammInitialBaseAssetReserve,
ammInitialQuoteAssetReserve,
periodicity
);
await clearingHouse.updateMarketBaseSpread(marketIndex, 500);
const feeStructure: FeeStructure = {
feeNumerator: new BN(0), // 5bps
feeDenominator: new BN(10000),
discountTokenTiers: {
firstTier: {
minimumBalance: new BN(1),
discountNumerator: new BN(1),
discountDenominator: new BN(1),
},
secondTier: {
minimumBalance: new BN(1),
discountNumerator: new BN(1),
discountDenominator: new BN(1),
},
thirdTier: {
minimumBalance: new BN(1),
discountNumerator: new BN(1),
discountDenominator: new BN(1),
},
fourthTier: {
minimumBalance: new BN(1),
discountNumerator: new BN(1),
discountDenominator: new BN(1),
},
},
referralDiscount: {
referrerRewardNumerator: new BN(1),
referrerRewardDenominator: new BN(1),
refereeDiscountNumerator: new BN(1),
refereeDiscountDenominator: new BN(1),
},
};
await clearingHouse.updateFee(feeStructure);
await clearingHouse.initializeUserAccountAndDepositCollateral(
usdcAmount,
userUSDCAccount.publicKey
);
clearingHouseUser = ClearingHouseUser.from(
clearingHouse,
provider.wallet.publicKey
);
await clearingHouseUser.subscribe();
});
beforeEach(async () => {
await clearingHouse.moveAmmPrice(
ammInitialBaseAssetReserve,
ammInitialQuoteAssetReserve,
ZERO
);
await setFeedPrice(anchor.workspace.Pyth, 1, solUsd);
});
after(async () => {
await clearingHouse.unsubscribe();
await clearingHouseUser.unsubscribe();
});
it('Long market order base', async () => {
const initialCollateral = clearingHouseUser.getUserAccount().collateral;
const direction = PositionDirection.LONG;
const baseAssetAmount = new BN(AMM_RESERVE_PRECISION);
const tradeAcquiredAmountsNoSpread = calculateTradeAcquiredAmounts(
direction,
baseAssetAmount,
clearingHouse.getMarket(0),
'base',
false
);
const tradeAcquiredAmountsWithSpread = calculateTradeAcquiredAmounts(
direction,
baseAssetAmount,
clearingHouse.getMarket(0),
'base',
true
);
const expectedQuoteAssetAmount = calculateQuoteAssetAmountSwapped(
tradeAcquiredAmountsWithSpread[1].abs(),
clearingHouse.getMarket(marketIndex).amm.pegMultiplier,
getSwapDirection('base', direction)
);
console.log(
'expected quote with out spread',
calculateQuoteAssetAmountSwapped(
tradeAcquiredAmountsNoSpread[1].abs(),
clearingHouse.getMarket(marketIndex).amm.pegMultiplier,
getSwapDirection('base', direction)
).toString()
);
console.log(
'expected quote with spread',
calculateQuoteAssetAmountSwapped(
tradeAcquiredAmountsWithSpread[1].abs(),
clearingHouse.getMarket(marketIndex).amm.pegMultiplier,
getSwapDirection('base', direction)
).toString()
);
const orderParams = getMarketOrderParams(
marketIndex,
direction,
ZERO,
baseAssetAmount,
false
);
const txSig = await clearingHouse.placeAndFillOrder(orderParams);
const computeUnits = await findComputeUnitConsumption(
clearingHouse.program.programId,
connection,
txSig,
'confirmed'
);
console.log('compute units', computeUnits);
console.log(
'tx logs',
(await connection.getTransaction(txSig, { commitment: 'confirmed' })).meta
.logMessages
);
await clearingHouse.fetchAccounts();
await clearingHouseUser.fetchAccounts();
const unrealizedPnl = clearingHouseUser.getUnrealizedPNL();
console.log('unrealized pnl', unrealizedPnl.toString());
const market = clearingHouse.getMarket(marketIndex);
const expectedFeeToMarket = new BN(250);
console.log(market.amm.totalFee.toString());
assert(market.amm.totalFee.eq(expectedFeeToMarket));
const userPositionsAccount = clearingHouseUser.getUserPositionsAccount();
const firstPosition = userPositionsAccount.positions[0];
assert(firstPosition.baseAssetAmount.eq(baseAssetAmount));
assert(firstPosition.quoteAssetAmount.eq(expectedQuoteAssetAmount));
const tradeHistoryAccount = clearingHouse.getTradeHistoryAccount();
const tradeHistoryRecord = tradeHistoryAccount.tradeRecords[0];
assert.ok(tradeHistoryAccount.head.toNumber() === 1);
assert.ok(tradeHistoryRecord.baseAssetAmount.eq(baseAssetAmount));
assert.ok(tradeHistoryRecord.quoteAssetAmount.eq(expectedQuoteAssetAmount));
assert.ok(
tradeHistoryRecord.quoteAssetAmountSurplus.eq(expectedFeeToMarket)
);
console.log(
'surplus',
tradeHistoryRecord.quoteAssetAmountSurplus.toString()
);
const orderHistoryAccount = clearingHouse.getOrderHistoryAccount();
const orderRecord: OrderRecord = orderHistoryAccount.orderRecords[1];
assert(orderRecord.quoteAssetAmountSurplus.eq(expectedFeeToMarket));
await clearingHouse.closePosition(marketIndex);
await clearingHouse.fetchAccounts();
await clearingHouseUser.fetchAccounts();
const pnl = clearingHouseUser
.getUserAccount()
.collateral.sub(initialCollateral);
console.log(pnl.toString());
console.log(clearingHouse.getMarket(0).amm.totalFee.toString());
assert(clearingHouse.getMarket(0).amm.totalFee.eq(new BN(500)));
});
it('Long market order quote', async () => {
const initialCollateral = clearingHouseUser.getUserAccount().collateral;
const initialAmmTotalFee = clearingHouse.getMarket(0).amm.totalFee;
const direction = PositionDirection.LONG;
const quoteAssetAmount = new BN(QUOTE_PRECISION);
const tradeAcquiredAmountsNoSpread = calculateTradeAcquiredAmounts(
direction,
quoteAssetAmount,
clearingHouse.getMarket(0),
'quote',
false
);
const tradeAcquiredAmountsWithSpread = calculateTradeAcquiredAmounts(
direction,
quoteAssetAmount,
clearingHouse.getMarket(0),
'quote',
true
);
console.log(
'expected base with out spread',
tradeAcquiredAmountsNoSpread[0].abs().toString()
);
console.log(
'expected base with spread',
tradeAcquiredAmountsWithSpread[0].abs().toString()
);
const expectedBaseAssetAmount = tradeAcquiredAmountsWithSpread[0].abs();
const orderParams = getMarketOrderParams(
marketIndex,
direction,
quoteAssetAmount,
ZERO,
false
);
const txSig = await clearingHouse.placeAndFillOrder(orderParams);
const computeUnits = await findComputeUnitConsumption(
clearingHouse.program.programId,
connection,
txSig,
'confirmed'
);
console.log('compute units', computeUnits);
console.log(
'tx logs',
(await connection.getTransaction(txSig, { commitment: 'confirmed' })).meta
.logMessages
);
await clearingHouse.fetchAccounts();
await clearingHouseUser.fetchAccounts();
const unrealizedPnl = clearingHouseUser.getUnrealizedPNL();
console.log('unrealized pnl', unrealizedPnl.toString());
const tradeHistoryAccount = clearingHouse.getTradeHistoryAccount();
const tradeHistoryRecord = tradeHistoryAccount.tradeRecords[2];
assert.ok(tradeHistoryRecord.baseAssetAmount.eq(expectedBaseAssetAmount));
assert.ok(tradeHistoryRecord.quoteAssetAmount.eq(quoteAssetAmount));
assert.ok(tradeHistoryRecord.quoteAssetAmountSurplus.eq(new BN(250)));
console.log(
'surplus',
tradeHistoryRecord.quoteAssetAmountSurplus.toString()
);
const orderHistoryAccount = clearingHouse.getOrderHistoryAccount();
const orderRecord: OrderRecord = orderHistoryAccount.orderRecords[3];
assert(orderRecord.quoteAssetAmountSurplus.eq(new BN(250)));
await clearingHouse.closePosition(marketIndex);
await clearingHouse.fetchAccounts();
await clearingHouseUser.fetchAccounts();
const pnl = clearingHouseUser
.getUserAccount()
.collateral.sub(initialCollateral);
console.log(pnl.toString());
console.log(
clearingHouse.getMarket(0).amm.totalFee.sub(initialAmmTotalFee).toString()
);
assert(
clearingHouse
.getMarket(0)
.amm.totalFee.sub(initialAmmTotalFee)
.eq(new BN(500))
);
});
it('short market order base', async () => {
const initialCollateral = clearingHouseUser.getUserAccount().collateral;
const initialAmmTotalFee = clearingHouse.getMarket(0).amm.totalFee;
const direction = PositionDirection.SHORT;
const baseAssetAmount = new BN(AMM_RESERVE_PRECISION);
const tradeAcquiredAmountsNoSpread = calculateTradeAcquiredAmounts(
direction,
baseAssetAmount,
clearingHouse.getMarket(0),
'base',
false
);
const tradeAcquiredAmountsWithSpread = calculateTradeAcquiredAmounts(
direction,
baseAssetAmount,
clearingHouse.getMarket(0),
'base',
true
);
const expectedQuoteAssetAmount = calculateQuoteAssetAmountSwapped(
tradeAcquiredAmountsWithSpread[1].abs(),
clearingHouse.getMarket(marketIndex).amm.pegMultiplier,
getSwapDirection('base', direction)
);
console.log(
'expected quote with out spread',
calculateQuoteAssetAmountSwapped(
tradeAcquiredAmountsNoSpread[1].abs(),
clearingHouse.getMarket(marketIndex).amm.pegMultiplier,
getSwapDirection('base', direction)
).toString()
);
console.log(
'expected quote with spread',
calculateQuoteAssetAmountSwapped(
tradeAcquiredAmountsWithSpread[1].abs(),
clearingHouse.getMarket(marketIndex).amm.pegMultiplier,
getSwapDirection('base', direction)
).toString()
);
const orderParams = getMarketOrderParams(
marketIndex,
direction,
ZERO,
baseAssetAmount,
false
);
const txSig = await clearingHouse.placeAndFillOrder(orderParams);
const computeUnits = await findComputeUnitConsumption(
clearingHouse.program.programId,
connection,
txSig,
'confirmed'
);
console.log('compute units', computeUnits);
console.log(
'tx logs',
(await connection.getTransaction(txSig, { commitment: 'confirmed' })).meta
.logMessages
);
await clearingHouse.fetchAccounts();
await clearingHouseUser.fetchAccounts();
const unrealizedPnl = clearingHouseUser.getUnrealizedPNL();
console.log('unrealized pnl', unrealizedPnl.toString());
const tradeHistoryAccount = clearingHouse.getTradeHistoryAccount();
const tradeHistoryRecord = tradeHistoryAccount.tradeRecords[4];
assert.ok(tradeHistoryRecord.baseAssetAmount.eq(baseAssetAmount));
assert.ok(tradeHistoryRecord.quoteAssetAmount.eq(expectedQuoteAssetAmount));
assert.ok(tradeHistoryRecord.quoteAssetAmountSurplus.eq(new BN(250)));
console.log(
'surplus',
tradeHistoryRecord.quoteAssetAmountSurplus.toString()
);
const orderHistoryAccount = clearingHouse.getOrderHistoryAccount();
const orderRecord: OrderRecord = orderHistoryAccount.orderRecords[5];
console.log(orderRecord.quoteAssetAmountSurplus.toString());
assert(orderRecord.quoteAssetAmountSurplus.eq(new BN(250)));
await clearingHouse.closePosition(marketIndex);
await clearingHouse.fetchAccounts();
await clearingHouseUser.fetchAccounts();
const pnl = clearingHouseUser
.getUserAccount()
.collateral.sub(initialCollateral);
console.log(pnl.toString());
console.log(
clearingHouse.getMarket(0).amm.totalFee.sub(initialAmmTotalFee).toString()
);
assert(
clearingHouse
.getMarket(0)
.amm.totalFee.sub(initialAmmTotalFee)
.eq(new BN(500))
);
});
it('short market order quote', async () => {
const initialCollateral = clearingHouseUser.getUserAccount().collateral;
const initialAmmTotalFee = clearingHouse.getMarket(0).amm.totalFee;
const direction = PositionDirection.SHORT;
const quoteAssetAmount = new BN(QUOTE_PRECISION);
const tradeAcquiredAmountsNoSpread = calculateTradeAcquiredAmounts(
direction,
quoteAssetAmount,
clearingHouse.getMarket(0),
'quote',
false
);
const tradeAcquiredAmountsWithSpread = calculateTradeAcquiredAmounts(
direction,
quoteAssetAmount,
clearingHouse.getMarket(0),
'quote',
true
);
console.log(
'expected base with out spread',
tradeAcquiredAmountsNoSpread[0].abs().toString()
);
console.log(
'expected base with spread',
tradeAcquiredAmountsWithSpread[0].abs().toString()
);
const expectedBaseAssetAmount = tradeAcquiredAmountsWithSpread[0].abs();
const orderParams = getMarketOrderParams(
marketIndex,
direction,
quoteAssetAmount,
ZERO,
false
);
const txSig = await clearingHouse.placeAndFillOrder(orderParams);
const computeUnits = await findComputeUnitConsumption(
clearingHouse.program.programId,
connection,
txSig,
'confirmed'
);
console.log('compute units', computeUnits);
console.log(
'tx logs',
(await connection.getTransaction(txSig, { commitment: 'confirmed' })).meta
.logMessages
);
await clearingHouse.fetchAccounts();
await clearingHouseUser.fetchAccounts();
const unrealizedPnl = clearingHouseUser.getUnrealizedPNL();
console.log('unrealized pnl', unrealizedPnl.toString());
const tradeHistoryAccount = clearingHouse.getTradeHistoryAccount();
const tradeHistoryRecord = tradeHistoryAccount.tradeRecords[6];
assert.ok(tradeHistoryRecord.baseAssetAmount.eq(expectedBaseAssetAmount));
assert.ok(tradeHistoryRecord.quoteAssetAmount.eq(quoteAssetAmount));
assert.ok(tradeHistoryRecord.quoteAssetAmountSurplus.eq(new BN(250)));
console.log(
'surplus',
tradeHistoryRecord.quoteAssetAmountSurplus.toString()
);
const orderHistoryAccount = clearingHouse.getOrderHistoryAccount();
const orderRecord: OrderRecord = orderHistoryAccount.orderRecords[7];
console.log(orderRecord.quoteAssetAmountSurplus.toString());
assert(orderRecord.quoteAssetAmountSurplus.eq(new BN(250)));
await clearingHouse.closePosition(marketIndex);
await clearingHouse.fetchAccounts();
await clearingHouseUser.fetchAccounts();
const pnl = clearingHouseUser
.getUserAccount()
.collateral.sub(initialCollateral);
console.log(pnl.toString());
console.log(
clearingHouse.getMarket(0).amm.totalFee.sub(initialAmmTotalFee).toString()
);
assert(
clearingHouse
.getMarket(0)
.amm.totalFee.sub(initialAmmTotalFee)
.eq(new BN(500))
);
});
it('unable to fill bid between mark and ask price', async () => {
const direction = PositionDirection.LONG;
const baseAssetAmount = AMM_RESERVE_PRECISION;
const limitPrice = calculateMarkPrice(clearingHouse.getMarket(0)).add(
MARK_PRICE_PRECISION.div(new BN(10000))
); // limit price plus 1bp
const orderParams = getLimitOrderParams(
marketIndex,
direction,
baseAssetAmount,
limitPrice,
false,
undefined,
false,
1
);
await clearingHouse.placeOrder(orderParams);
await clearingHouse.fetchAccounts();
await clearingHouseUser.fetchAccounts();
const unfilledOrder = clearingHouseUser.getUserOrdersAccount().orders[0];
const expectedBaseAssetAmount = calculateBaseAssetAmountMarketCanExecute(
clearingHouse.getMarket(0),
unfilledOrder
);
assert(expectedBaseAssetAmount, ZERO);
// fill should fail because nothing to fill
try {
await clearingHouse.fillOrder(
await clearingHouseUser.getUserAccountPublicKey(),
await clearingHouseUser.getUserOrdersAccountPublicKey(),
unfilledOrder
);
assert(false);
} catch (e) {
// good
}
await clearingHouse.cancelOrderByUserId(1);
});
it('unable to fill ask between mark and bid price', async () => {
const direction = PositionDirection.SHORT;
const baseAssetAmount = AMM_RESERVE_PRECISION;
const limitPrice = calculateMarkPrice(clearingHouse.getMarket(0)).add(
MARK_PRICE_PRECISION.sub(new BN(10000))
); // limit price plus 1bp
const orderParams = getLimitOrderParams(
marketIndex,
direction,
baseAssetAmount,
limitPrice,
false,
undefined,
false,
1
);
await clearingHouse.placeOrder(orderParams);
await clearingHouse.fetchAccounts();
await clearingHouseUser.fetchAccounts();
const unfilledOrder = clearingHouseUser.getUserOrdersAccount().orders[0];
const expectedBaseAssetAmount = calculateBaseAssetAmountMarketCanExecute(
clearingHouse.getMarket(0),
unfilledOrder
);
assert(expectedBaseAssetAmount, ZERO);
// fill should fail because nothing to fill
try {
await clearingHouse.fillOrder(
await clearingHouseUser.getUserAccountPublicKey(),
await clearingHouseUser.getUserOrdersAccountPublicKey(),
unfilledOrder
);
assert(false);
} catch (e) {
// good
}
await clearingHouse.cancelOrderByUserId(1);
});
it('fill limit order above ask', async () => {
const initialAmmTotalFee = clearingHouse.getMarket(0).amm.totalFee;
const direction = PositionDirection.LONG;
const baseAssetAmount = AMM_RESERVE_PRECISION;
const limitPrice = calculateMarkPrice(clearingHouse.getMarket(0)).add(
MARK_PRICE_PRECISION.div(new BN(1000))
); // limit price plus 10bp
const orderParams = getLimitOrderParams(
marketIndex,
direction,
baseAssetAmount,
limitPrice,
false,
undefined,
false,
1
);
await clearingHouse.placeOrder(orderParams);
await clearingHouse.fetchAccounts();
await clearingHouseUser.fetchAccounts();
const order = clearingHouseUser.getUserOrdersAccount().orders[0];
const expectedBaseAssetAmount = calculateBaseAssetAmountMarketCanExecute(
clearingHouse.getMarket(0),
order
);
assert(expectedBaseAssetAmount, AMM_RESERVE_PRECISION);
const tradeAcquiredAmountsWithSpread = calculateTradeAcquiredAmounts(
direction,
baseAssetAmount,
clearingHouse.getMarket(0),
'base',
true
);
const expectedQuoteAssetAmount = calculateQuoteAssetAmountSwapped(
tradeAcquiredAmountsWithSpread[1].abs(),
clearingHouse.getMarket(marketIndex).amm.pegMultiplier,
getSwapDirection('base', direction)
);
await clearingHouse.fillOrder(
await clearingHouseUser.getUserAccountPublicKey(),
await clearingHouseUser.getUserOrdersAccountPublicKey(),
order
);
await clearingHouse.fetchAccounts();
await clearingHouseUser.fetchAccounts();
const userPositionsAccount = clearingHouseUser.getUserPositionsAccount();
const firstPosition = userPositionsAccount.positions[0];
assert(firstPosition.baseAssetAmount.eq(baseAssetAmount));
assert(firstPosition.quoteAssetAmount.eq(expectedQuoteAssetAmount));
await clearingHouse.closePosition(marketIndex);
await clearingHouse.fetchAccounts();
await clearingHouseUser.fetchAccounts();
assert(
clearingHouse
.getMarket(0)
.amm.totalFee.sub(initialAmmTotalFee)
.eq(new BN(500))
);
});
it('fill limit order below bid', async () => {
const initialAmmTotalFee = clearingHouse.getMarket(0).amm.totalFee;
const direction = PositionDirection.SHORT;
const baseAssetAmount = AMM_RESERVE_PRECISION;
const limitPrice = calculateMarkPrice(clearingHouse.getMarket(0)).sub(
MARK_PRICE_PRECISION.div(new BN(1000))
); // limit price minus 10bp
const orderParams = getLimitOrderParams(
marketIndex,
direction,
baseAssetAmount,
limitPrice,
false,
undefined,
false,
1
);
await clearingHouse.placeOrder(orderParams);
await clearingHouse.fetchAccounts();
await clearingHouseUser.fetchAccounts();
const order = clearingHouseUser.getUserOrdersAccount().orders[0];
const expectedBaseAssetAmount = calculateBaseAssetAmountMarketCanExecute(
clearingHouse.getMarket(0),
order
);
assert(expectedBaseAssetAmount, AMM_RESERVE_PRECISION);
const tradeAcquiredAmountsWithSpread = calculateTradeAcquiredAmounts(
direction,
baseAssetAmount,
clearingHouse.getMarket(0),
'base',
true
);
const expectedQuoteAssetAmount = calculateQuoteAssetAmountSwapped(
tradeAcquiredAmountsWithSpread[1].abs(),
clearingHouse.getMarket(marketIndex).amm.pegMultiplier,
getSwapDirection('base', direction)
);
await clearingHouse.fillOrder(
await clearingHouseUser.getUserAccountPublicKey(),
await clearingHouseUser.getUserOrdersAccountPublicKey(),
order
);
await clearingHouse.fetchAccounts();
await clearingHouseUser.fetchAccounts();
const userPositionsAccount = clearingHouseUser.getUserPositionsAccount();
const firstPosition = userPositionsAccount.positions[0];
assert(firstPosition.baseAssetAmount.abs().eq(baseAssetAmount));
assert(firstPosition.quoteAssetAmount.eq(expectedQuoteAssetAmount));
await clearingHouse.closePosition(marketIndex);
await clearingHouse.fetchAccounts();
await clearingHouseUser.fetchAccounts();
assert(
clearingHouse
.getMarket(0)
.amm.totalFee.sub(initialAmmTotalFee)
.eq(new BN(500))
);
});
it('Long market order base w/ variable reduce/close', async () => {
const marketIndex2Num = 1;
const marketIndex2 = new BN(marketIndex2Num);
const peg = 40000;
const btcUsd = await mockOracle(peg);
const periodicity = new BN(60 * 60); // 1 HOUR
const mantissaSqrtScale = new BN(
Math.sqrt(MARK_PRICE_PRECISION.toNumber())
);
const ammInitialQuoteAssetReserve = new anchor.BN(5 * 10 ** 15).mul(
mantissaSqrtScale
);
const ammInitialBaseAssetReserve = new anchor.BN(5 * 10 ** 15).mul(
mantissaSqrtScale
);
await clearingHouse.initializeMarket(
marketIndex2,
btcUsd,
ammInitialBaseAssetReserve,
ammInitialQuoteAssetReserve,
periodicity,
new BN(peg * 1e3)
);
await clearingHouse.updateMarketBaseSpread(marketIndex2, 500);
const initialCollateral = clearingHouseUser.getUserAccount().collateral;
const direction = PositionDirection.LONG;
const baseAssetAmount = new BN(AMM_RESERVE_PRECISION.toNumber() / 10000); // ~$4 of btc
const market2 = clearingHouse.getMarket(marketIndex2Num);
const tradeAcquiredAmountsNoSpread = calculateTradeAcquiredAmounts(
direction,
baseAssetAmount,
market2,
'base',
false
);
const tradeAcquiredAmountsWithSpread = calculateTradeAcquiredAmounts(
direction,
baseAssetAmount,
market2,
'base',
true
);
const expectedQuoteAssetAmount = calculateQuoteAssetAmountSwapped(
tradeAcquiredAmountsWithSpread[1].abs(),
clearingHouse.getMarket(marketIndex2Num).amm.pegMultiplier,
getSwapDirection('base', direction)
);
console.log(
'expected quote with out spread',
calculateQuoteAssetAmountSwapped(
tradeAcquiredAmountsNoSpread[1].abs(),
clearingHouse.getMarket(marketIndex2Num).amm.pegMultiplier,
getSwapDirection('base', direction)
).toString()
);
console.log(
'expected quote with spread',
calculateQuoteAssetAmountSwapped(
tradeAcquiredAmountsWithSpread[1].abs(),
clearingHouse.getMarket(marketIndex2Num).amm.pegMultiplier,
getSwapDirection('base', direction)
).toString()
);
const orderParams = getMarketOrderParams(
marketIndex2,
direction,
ZERO,
baseAssetAmount,
false
);
const txSig = await clearingHouse.placeAndFillOrder(orderParams);
const computeUnits = await findComputeUnitConsumption(
clearingHouse.program.programId,
connection,
txSig,
'confirmed'
);
console.log('compute units', computeUnits);
console.log(
'tx logs',
(await connection.getTransaction(txSig, { commitment: 'confirmed' })).meta
.logMessages
);
await clearingHouse.fetchAccounts();
await clearingHouseUser.fetchAccounts();
const unrealizedPnl = clearingHouseUser.getUnrealizedPNL();
console.log('unrealized pnl', unrealizedPnl.toString());
const expectedFeeToMarket = new BN(1000);
const userPositionsAccount = clearingHouseUser.getUserPositionsAccount();
const firstPosition = userPositionsAccount.positions[0];
assert(firstPosition.baseAssetAmount.eq(baseAssetAmount));
console.log(
convertToNumber(firstPosition.quoteAssetAmount),
convertToNumber(expectedQuoteAssetAmount)
);
assert(firstPosition.quoteAssetAmount.eq(expectedQuoteAssetAmount)); //todo
const tradeHistoryAccount = clearingHouse.getTradeHistoryAccount();
console.log(tradeHistoryAccount.head.toString());
const tradeHistoryRecord = tradeHistoryAccount.tradeRecords[12];
assert.ok(tradeHistoryRecord.baseAssetAmount.eq(baseAssetAmount));
assert.ok(tradeHistoryRecord.quoteAssetAmount.eq(expectedQuoteAssetAmount));
assert.ok(
tradeHistoryRecord.quoteAssetAmountSurplus.eq(expectedFeeToMarket)
);
console.log(
'surplus',
tradeHistoryRecord.quoteAssetAmountSurplus.toString()
);
const orderHistoryAccount = clearingHouse.getOrderHistoryAccount();
const orderRecord: OrderRecord = orderHistoryAccount.orderRecords[17];
assert(orderRecord.quoteAssetAmountSurplus.eq(expectedFeeToMarket));
const numCloses = 10;
const directionToClose = PositionDirection.SHORT;
for (let i = numCloses; i > 0; i--) {
const orderParams = getMarketOrderParams(
marketIndex2,
directionToClose,
ZERO,
baseAssetAmount.div(new BN(numCloses * i)), // variable sized close
false
);
await clearingHouse.placeAndFillOrder(orderParams);
}
await clearingHouse.closePosition(marketIndex2); // close rest
await clearingHouse.fetchAccounts();
await clearingHouseUser.fetchAccounts();
const pnl = clearingHouseUser
.getUserAccount()
.collateral.sub(initialCollateral);
console.log('pnl', pnl.toString());
console.log(
'total fee',
clearingHouse.getMarket(marketIndex2Num).amm.totalFee.toString()
);
assert(
clearingHouse.getMarket(marketIndex2Num).amm.totalFee.eq(new BN(2000))
);
});
}); | the_stack |
import { Action, useDispatch } from '../states/store';
import { AutomatonWithGUI } from '../../AutomatonWithGUI';
import { ChannelWithGUI } from '../../ChannelWithGUI';
import { CurveWithGUI } from '../../CurveWithGUI';
import { batch } from 'react-redux';
import { useAnimationFrame } from '../utils/useAnimationFrame';
import React, { useCallback, useEffect, useRef } from 'react';
import styled from 'styled-components';
// == utils ========================================================================================
const CURVE_RESO = 240;
function genCurvePath( curve: CurveWithGUI ): string {
let path = '';
for ( let i = 0; i <= CURVE_RESO; i ++ ) {
const x = i / CURVE_RESO;
const t = x * curve.length;
const v = curve.getValue( t );
const y = v;
path += `${ x },${ y } `;
}
return path;
}
// == styles =======================================================================================
const Root = styled.div`
display: none;
`;
// == element ======================================================================================
export interface AutomatonStateListenerProps {
automaton: AutomatonWithGUI;
}
const AutomatonStateListener = ( props: AutomatonStateListenerProps ): JSX.Element => {
const dispatch = useDispatch();
const automaton = props.automaton;
const refAccumActions = useRef<Action[]>( [] );
useAnimationFrame(
() => {
if ( refAccumActions.current.length > 0 ) {
batch( () => {
refAccumActions.current.forEach( ( action ) => dispatch( action ) );
} );
refAccumActions.current = [];
}
},
[ dispatch ],
);
const initChannelState = useCallback(
( name: string, channel: ChannelWithGUI, index: number ) => {
refAccumActions.current.push( {
type: 'Automaton/CreateChannel',
channel: name,
index,
} );
refAccumActions.current.push( {
type: 'Automaton/UpdateChannelValue',
channel: name,
value: channel.currentValue
} );
refAccumActions.current.push( {
type: 'Automaton/UpdateChannelStatus',
channel: name,
status: channel.status
} );
channel.items.forEach( ( item ) => {
refAccumActions.current.push( {
type: 'Automaton/UpdateChannelItem',
channel: name,
id: item.$id,
item: item.serializeGUI()
} );
} );
refAccumActions.current.push( {
type: 'Automaton/UpdateChannelLength',
channel: name,
length: channel.length
} );
channel.on( 'changeValue', ( { value } ) => {
refAccumActions.current.push( {
type: 'Automaton/UpdateChannelValue',
channel: name,
value
} );
} );
channel.on( 'updateStatus', () => {
refAccumActions.current.push( {
type: 'Automaton/UpdateChannelStatus',
channel: name,
status: channel.status
} );
} );
channel.on( 'createItem', ( { id, item } ) => {
refAccumActions.current.push( {
type: 'Automaton/UpdateChannelItem',
channel: name,
id,
item
} );
} );
channel.on( 'updateItem', ( { id, item } ) => {
refAccumActions.current.push( {
type: 'Automaton/UpdateChannelItem',
channel: name,
id,
item
} );
} );
channel.on( 'removeItem', ( { id } ) => {
dispatch( {
type: 'Timeline/SelectItemsSub',
items: [ { id } ],
} );
refAccumActions.current.push( {
type: 'Automaton/RemoveChannelItem',
channel: name,
id
} );
} );
channel.on( 'changeLength', ( { length } ) => {
refAccumActions.current.push( {
type: 'Automaton/UpdateChannelLength',
channel: name,
length,
} );
} );
},
[ dispatch ]
);
const initCurveState = useCallback(
( curveId: string, curve: CurveWithGUI ) => {
refAccumActions.current.push( {
type: 'Automaton/CreateCurve',
curveId,
length: curve.length,
path: genCurvePath( curve )
} );
refAccumActions.current.push( {
type: 'Automaton/UpdateCurveStatus',
curveId,
status: curve.status
} );
curve.nodes.forEach( ( node ) => {
refAccumActions.current.push( {
type: 'Automaton/UpdateCurveNode',
curveId,
id: node.$id,
node
} );
} );
curve.fxs.forEach( ( fx ) => {
refAccumActions.current.push( {
type: 'Automaton/UpdateCurveFx',
curveId,
id: fx.$id,
fx
} );
} );
curve.on( 'precalc', () => {
refAccumActions.current.push( {
type: 'Automaton/UpdateCurvePath',
curveId,
path: genCurvePath( curve )
} );
} );
curve.on( 'previewTime', ( { time, value, itemTime, itemSpeed, itemOffset } ) => {
refAccumActions.current.push( {
type: 'Automaton/UpdateCurvePreviewTimeValue',
curveId,
time,
value,
itemTime,
itemSpeed,
itemOffset,
} );
} );
curve.on( 'updateStatus', () => {
refAccumActions.current.push( {
type: 'Automaton/UpdateCurveStatus',
curveId,
status: curve.status
} );
} );
curve.on( 'createNode', ( { id, node } ) => {
refAccumActions.current.push( {
type: 'Automaton/UpdateCurveNode',
curveId,
id,
node
} );
} );
curve.on( 'updateNode', ( { id, node } ) => {
refAccumActions.current.push( {
type: 'Automaton/UpdateCurveNode',
curveId,
id,
node
} );
} );
curve.on( 'removeNode', ( { id } ) => {
dispatch( {
type: 'CurveEditor/SelectItemsSub',
nodes: [ id ],
} );
refAccumActions.current.push( {
type: 'Automaton/RemoveCurveNode',
curveId,
id
} );
} );
curve.on( 'createFx', ( { id, fx } ) => {
refAccumActions.current.push( {
type: 'Automaton/UpdateCurveFx',
curveId,
id,
fx
} );
} );
curve.on( 'updateFx', ( { id, fx } ) => {
refAccumActions.current.push( {
type: 'Automaton/UpdateCurveFx',
curveId,
id,
fx
} );
} );
curve.on( 'removeFx', ( { id } ) => {
dispatch( {
type: 'CurveEditor/SelectItemsSub',
fxs: [ id ],
} );
refAccumActions.current.push( {
type: 'Automaton/RemoveCurveFx',
curveId,
id
} );
} );
curve.on( 'changeLength', ( { length } ) => {
refAccumActions.current.push( {
type: 'Automaton/UpdateCurveLength',
curveId,
length,
} );
} );
},
[ dispatch ]
);
const initAutomaton = useCallback(
() => {
dispatch( {
type: 'History/Drop'
} );
dispatch( {
type: 'ContextMenu/Close'
} );
dispatch( {
type: 'Reset'
} );
refAccumActions.current.push( {
type: 'Automaton/UpdateTime',
time: automaton.time
} );
refAccumActions.current.push( {
type: 'Automaton/ChangeLength',
length: automaton.length
} );
refAccumActions.current.push( {
type: 'Automaton/ChangeResolution',
resolution: automaton.resolution
} );
refAccumActions.current.push( {
type: 'Automaton/UpdateIsPlaying',
isPlaying: automaton.isPlaying
} );
Object.entries( automaton.fxDefinitions ).forEach( ( [ name, fxDefinition ] ) => {
refAccumActions.current.push( {
type: 'Automaton/AddFxDefinition',
name,
fxDefinition
} );
} );
automaton.curves.forEach( ( curve ) => {
initCurveState( curve.$id, curve );
} );
automaton.channels.forEach( ( channel, index ) => {
const name = automaton.mapNameToChannel.getFromValue( channel )!;
initChannelState( name, channel, index );
} );
Object.entries( automaton.labels ).forEach( ( [ name, time ] ) => {
refAccumActions.current.push( {
type: 'Automaton/SetLabel',
name,
time
} );
} );
refAccumActions.current.push( {
type: 'Automaton/SetLoopRegion',
loopRegion: automaton.loopRegion
} );
refAccumActions.current.push( {
type: 'Automaton/SetShouldSave',
shouldSave: automaton.shouldSave
} );
refAccumActions.current.push( {
type: 'Automaton/UpdateGUISettings',
settings: automaton.guiSettings
} );
},
[ automaton, dispatch, initChannelState, initCurveState ],
);
useEffect(
() => {
refAccumActions.current.push( {
type: 'Automaton/SetInstance',
automaton
} );
initAutomaton();
const handleLoad = automaton.on( 'load', () => {
initAutomaton();
} );
const handleUpdate = automaton.on( 'update', ( { time } ): void => {
refAccumActions.current.push( {
type: 'Automaton/UpdateTime',
time
} );
} );
const handleChangeLength = automaton.on( 'changeLength', ( { length } ) => {
refAccumActions.current.push( {
type: 'Automaton/ChangeLength',
length
} );
} );
const handleChangeResolution = automaton.on( 'changeResolution', ( { resolution } ) => {
refAccumActions.current.push( {
type: 'Automaton/ChangeResolution',
resolution
} );
} );
const handlePlay = automaton.on( 'play', () => {
refAccumActions.current.push( {
type: 'Automaton/UpdateIsPlaying',
isPlaying: true
} );
} );
const handlePause = automaton.on( 'pause', () => {
refAccumActions.current.push( {
type: 'Automaton/UpdateIsPlaying',
isPlaying: false
} );
} );
const handleAddFxDefinitions = automaton.on( 'addFxDefinitions', ( { fxDefinitions } ) => {
Object.entries( fxDefinitions ).forEach( ( [ name, fxDefinition ] ) => {
refAccumActions.current.push( {
type: 'Automaton/AddFxDefinition',
name,
fxDefinition
} );
} );
} );
const handleUpdateGUISettings = automaton.on( 'updateGUISettings', ( { settings } ) => {
refAccumActions.current.push( {
type: 'Automaton/UpdateGUISettings',
settings
} );
} );
const handleCreateChannel = automaton.on( 'createChannel', ( event ) => {
initChannelState( event.name, event.channel, event.index );
} );
const handleRemoveChannel = automaton.on( 'removeChannel', ( event ) => {
dispatch( {
type: 'Timeline/UnselectChannelIfSelected',
channel: event.name,
} );
refAccumActions.current.push( {
type: 'Automaton/RemoveChannel',
channel: event.name
} );
} );
const handleReorderChannels = automaton.on( 'reorderChannels', ( event ) => {
refAccumActions.current.push( {
type: 'Automaton/ReorderChannels',
index: event.index,
length: event.length,
newIndex: event.newIndex,
} );
} );
const handleCreateCurve = automaton.on( 'createCurve', ( event ) => {
initCurveState( event.id, event.curve );
} );
const handleRemoveCurve = automaton.on( 'removeCurve', ( event ) => {
dispatch( {
type: 'CurveEditor/SelectCurve',
curveId: null,
} );
refAccumActions.current.push( {
type: 'Automaton/RemoveCurve',
curveId: event.id
} );
} );
const handleChangeShouldSave = automaton.on( 'changeShouldSave', ( event ) => {
refAccumActions.current.push( {
type: 'Automaton/SetShouldSave',
shouldSave: event.shouldSave
} );
} );
const handleSetLabel = automaton.on( 'setLabel', ( { name, time } ) => {
refAccumActions.current.push( {
type: 'Automaton/SetLabel',
name,
time
} );
} );
const handleDeleteLabel = automaton.on( 'deleteLabel', ( { name } ) => {
dispatch( {
type: 'Timeline/SelectLabelsSub',
labels: [ name ],
} );
refAccumActions.current.push( {
type: 'Automaton/DeleteLabel',
name
} );
} );
const handleSetLoopRegion = automaton.on( 'setLoopRegion', ( { loopRegion } ) => {
refAccumActions.current.push( {
type: 'Automaton/SetLoopRegion',
loopRegion
} );
} );
return () => {
automaton.off( 'load', handleLoad );
automaton.off( 'update', handleUpdate );
automaton.off( 'changeLength', handleChangeLength );
automaton.off( 'changeResolution', handleChangeResolution );
automaton.off( 'play', handlePlay );
automaton.off( 'pause', handlePause );
automaton.off( 'addFxDefinitions', handleAddFxDefinitions );
automaton.off( 'updateGUISettings', handleUpdateGUISettings );
automaton.off( 'createChannel', handleCreateChannel );
automaton.off( 'removeChannel', handleRemoveChannel );
automaton.off( 'reorderChannels', handleReorderChannels );
automaton.off( 'createCurve', handleCreateCurve );
automaton.off( 'removeCurve', handleRemoveCurve );
automaton.off( 'setLabel', handleSetLabel );
automaton.off( 'deleteLabel', handleDeleteLabel );
automaton.off( 'setLoopRegion', handleSetLoopRegion );
automaton.off( 'changeShouldSave', handleChangeShouldSave );
};
},
[ automaton, dispatch, initAutomaton, initChannelState, initCurveState ]
);
return (
<Root />
);
};
export { AutomatonStateListener }; | the_stack |
import { h } from "@siteimprove/alfa-dom";
import { Err, Ok } from "@siteimprove/alfa-result";
import { Property } from "@siteimprove/alfa-style";
import { test } from "@siteimprove/alfa-test";
import R62, { ComputedStyles, Outcomes } from "../../src/sia-r62/rule";
import { evaluate } from "../common/evaluate";
import { passed, failed, inapplicable } from "../common/outcome";
// default styling of links
// The initial value of border-top is medium, resolving as 3px. However, when
// computing and border-style is none, this is computed as 0px.
// As a consequence, even without changing `border` at all, the computed value
// of border-top is not equal to its initial value and needs to expressed here!
//
// Confused? Wait, same joke happens for outline-width except that now on focus
// outline-style is not none, so the computed value of outline-width is its
// initial value. As a consequence, we cannot just override properties since
// in this case we need to actually *remove* outline-width from the diagnostic!
const defaultProperties: Array<
[Property.Name | Property.Shorthand.Name, string]
> = [
["border-width", "0px"],
["color", "rgb(0% 0% 93.33333%)"],
["text-decoration", "underline"],
["outline", "0px"],
];
const focusProperties: Array<
[Property.Name | Property.Shorthand.Name, string]
> = [
["border-width", "0px"],
["color", "rgb(0% 0% 93.33333%)"],
["outline", "auto"],
["text-decoration", "underline"],
];
const noDistinguishingProperties: Array<
[Property.Name | Property.Shorthand.Name, string]
> = [
["border-width", "0px"],
["color", "rgb(0% 0% 93.33333%)"],
["outline", "0px"],
];
const defaultStyle = Ok.of(ComputedStyles.of(defaultProperties));
const focusStyle = Ok.of(ComputedStyles.of(focusProperties));
const noStyle = Err.of(ComputedStyles.of(noDistinguishingProperties));
test(`evaluate() passes an <a> element with a <p> parent element with non-link
text content`, async (t) => {
const target = <a href="#">Link</a>;
const document = h.document([<p>Hello {target}</p>]);
t.deepEqual(await evaluate(R62, { document }), [
passed(R62, target, {
1: Outcomes.IsDistinguishable(
[defaultStyle],
[defaultStyle],
[focusStyle]
),
}),
]);
});
test(`evaluate() passes an <a> element with a <p> parent element with non-link
text content in a <span> child element`, async (t) => {
const target = <a href="#">Link</a>;
const document = h.document([
<p>
<span>Hello</span> {target}
</p>,
]);
t.deepEqual(await evaluate(R62, { document }), [
passed(R62, target, {
1: Outcomes.IsDistinguishable(
[defaultStyle],
[defaultStyle],
[focusStyle]
),
}),
]);
});
test(`evaluate() fails an <a> element that removes the default text decoration
without replacing it with another distinguishing feature`, async (t) => {
const target = <a href="#">Link</a>;
const document = h.document(
[<p>Hello {target}</p>],
[
h.sheet([
h.rule.style("a", {
outline: "none",
textDecoration: "none",
}),
]),
]
);
t.deepEqual(await evaluate(R62, { document }), [
failed(R62, target, {
1: Outcomes.IsNotDistinguishable([noStyle], [noStyle], [noStyle]),
}),
]);
});
test(`evaluate() fails an <a> element that removes the default text decoration
on hover without replacing it with another distinguishing feature`, async (t) => {
const target = <a href="#">Link</a>;
const document = h.document(
[<p>Hello {target}</p>],
[
h.sheet([
h.rule.style("a:hover", {
textDecoration: "none",
}),
]),
]
);
t.deepEqual(await evaluate(R62, { document }), [
failed(R62, target, {
1: Outcomes.IsNotDistinguishable([defaultStyle], [noStyle], [focusStyle]),
}),
]);
});
test(`evaluate() fails an <a> element that removes the default text decoration
and focus outline on focus without replacing them with another
distinguishing feature`, async (t) => {
const target = <a href="#">Link</a>;
const document = h.document(
[<p>Hello {target}</p>],
[
h.sheet([
h.rule.style("a:focus", {
outline: "none",
textDecoration: "none",
}),
]),
]
);
t.deepEqual(await evaluate(R62, { document }), [
failed(R62, target, {
1: Outcomes.IsNotDistinguishable(
[defaultStyle],
[defaultStyle],
[noStyle]
),
}),
]);
});
test(`evaluate() fails an <a> element that removes the default text decoration
and focus outline on hover and focus without replacing them with another
distinguishing feature`, async (t) => {
const target = <a href="#">Link</a>;
const document = h.document(
[<p>Hello {target}</p>],
[
h.sheet([
h.rule.style("a:hover, a:focus", {
textDecoration: "none",
outline: "none",
}),
]),
]
);
t.deepEqual(await evaluate(R62, { document }), [
failed(R62, target, {
1: Outcomes.IsNotDistinguishable([defaultStyle], [noStyle], [noStyle]),
}),
]);
});
test(`evaluate() fails an <a> element that applies a text decoration only on
hover`, async (t) => {
const target = <a href="#">Link</a>;
const document = h.document(
[<p>Hello {target}</p>],
[
h.sheet([
h.rule.style("a", {
outline: "none",
textDecoration: "none",
}),
h.rule.style("a:hover", {
textDecoration: "underline",
}),
]),
]
);
t.deepEqual(await evaluate(R62, { document }), [
failed(R62, target, {
1: Outcomes.IsNotDistinguishable([noStyle], [defaultStyle], [noStyle]),
}),
]);
});
test(`evaluate() fails an <a> element that applies a text decoration only on
focus`, async (t) => {
const target = <a href="#">Link</a>;
const document = h.document(
[<p>Hello {target}</p>],
[
h.sheet([
h.rule.style("a", {
outline: "none",
textDecoration: "none",
}),
h.rule.style("a:focus", {
textDecoration: "underline",
}),
]),
]
);
t.deepEqual(await evaluate(R62, { document }), [
failed(R62, target, {
1: Outcomes.IsNotDistinguishable([noStyle], [noStyle], [defaultStyle]),
}),
]);
});
test(`evaluate() fails an <a> element that applies a text decoration only on
hover and focus`, async (t) => {
const target = <a href="#">Link</a>;
const document = h.document(
[<p>Hello {target}</p>],
[
h.sheet([
h.rule.style("a", {
outline: "none",
textDecoration: "none",
}),
h.rule.style("a:hover, a:focus", {
textDecoration: "underline",
}),
]),
]
);
t.deepEqual(await evaluate(R62, { document }), [
failed(R62, target, {
1: Outcomes.IsNotDistinguishable(
[noStyle],
[defaultStyle],
[defaultStyle]
),
}),
]);
});
test(`evaluate() passes an applicable <a> element that removes the default text
decoration and instead applies an outline`, async (t) => {
const target = <a href="#">Link</a>;
const document = h.document(
[<p>Hello {target}</p>],
[
h.sheet([
h.rule.style("a", {
textDecoration: "none",
outline: "auto",
}),
]),
]
);
const style = Ok.of(
ComputedStyles.of([
["border-width", "0px"],
["color", "rgb(0% 0% 93.33333%)"],
["outline", "auto"],
])
);
t.deepEqual(await evaluate(R62, { document }), [
passed(R62, target, {
1: Outcomes.IsDistinguishable([style], [style], [style]),
}),
]);
});
test(`evaluate() passes an applicable <a> element that removes the default text
decoration and instead applies a bottom border`, async (t) => {
const target = <a href="#">Link</a>;
const document = h.document(
[<p>Hello {target}</p>],
[
h.sheet([
h.rule.style("a", {
textDecoration: "none",
borderBottom: "1px solid #000",
}),
]),
]
);
const style = Ok.of(
ComputedStyles.of([
["border-width", "0px 0px 1px"],
["border-style", "none none solid"],
["border-color", "currentcolor currentcolor rgb(0% 0% 0%)"],
["color", "rgb(0% 0% 93.33333%)"],
["outline", "0px"],
])
);
t.deepEqual(await evaluate(R62, { document }), [
passed(R62, target, {
1: Outcomes.IsDistinguishable(
[style],
[style],
[
Ok.of(
ComputedStyles.of([
["color", "rgb(0% 0% 93.33333%)"],
["outline", "auto"],
["border-width", "0px 0px 1px"],
["border-style", "none none solid"],
["border-color", "currentcolor currentcolor rgb(0% 0% 0%)"],
])
),
]
),
}),
]);
});
test(`evaluate() fails an <a> element that has no distinguishing features and
has a transparent bottom border`, async (t) => {
const target = <a href="#">Link</a>;
const document = h.document(
[<p>Hello {target}</p>],
[
h.sheet([
h.rule.style("a", {
textDecoration: "none",
borderBottom: "1px solid transparent",
}),
]),
]
);
const style = Err.of(
ComputedStyles.of([
["color", "rgb(0% 0% 93.33333%)"],
["border-width", "0px 0px 1px"],
["border-style", "none none solid"],
["border-color", "currentcolor currentcolor rgb(0% 0% 0% / 0%)"],
["outline", "0px"],
])
);
t.deepEqual(await evaluate(R62, { document }), [
failed(R62, target, {
1: Outcomes.IsNotDistinguishable(
[style],
[style],
[
Ok.of(
ComputedStyles.of([
["color", "rgb(0% 0% 93.33333%)"],
["border-width", "0px 0px 1px"],
["border-style", "none none solid"],
["border-color", "currentcolor currentcolor rgb(0% 0% 0% / 0%)"],
["outline", "auto"],
])
),
]
),
}),
]);
});
test(`evaluate() fails an <a> element that has no distinguishing features and
has a 0px bottom border`, async (t) => {
const target = <a href="#">Link</a>;
const document = h.document(
[<p>Hello {target}</p>],
[
h.sheet([
h.rule.style("a", {
textDecoration: "none",
borderBottom: "0px solid #000",
}),
]),
]
);
const style = Err.of(
ComputedStyles.of([
["color", "rgb(0% 0% 93.33333%)"],
["border-width", "0px"],
["border-style", "none none solid"],
["border-color", "currentcolor currentcolor rgb(0% 0% 0%)"],
["outline", "0px"],
])
);
t.deepEqual(await evaluate(R62, { document }), [
failed(R62, target, {
1: Outcomes.IsNotDistinguishable(
[style],
[style],
[
Ok.of(
ComputedStyles.of([
["color", "rgb(0% 0% 93.33333%)"],
["outline", "auto"],
["border-width", "0px"],
["border-style", "none none solid"],
["border-color", "currentcolor currentcolor rgb(0% 0% 0%)"],
])
),
]
),
}),
]);
});
test(`evaluate() passes an applicable <a> element that removes the default text
decoration and instead applies a background color`, async (t) => {
const target = <a href="#">Link</a>;
const document = h.document(
[<p>Hello {target}</p>],
[
h.sheet([
h.rule.style("a", {
textDecoration: "none",
background: "red",
}),
]),
]
);
const style = Ok.of(
ComputedStyles.of([
["border-width", "0px"],
["color", "rgb(0% 0% 93.33333%)"],
["background", "rgb(100% 0% 0%)"],
["outline", "0px"],
])
);
t.deepEqual(await evaluate(R62, { document }), [
passed(R62, target, {
1: Outcomes.IsDistinguishable(
[style],
[style],
[
Ok.of(
ComputedStyles.of([
["border-width", "0px"],
["color", "rgb(0% 0% 93.33333%)"],
["background", "rgb(100% 0% 0%)"],
["outline", "auto"],
])
),
]
),
}),
]);
});
test(`evaluate() fails an <a> element that has no distinguishing features but is
part of a paragraph with a background color`, async (t) => {
const target = <a href="#">Link</a>;
const document = h.document(
[<p>Hello {target}</p>],
[
h.sheet([
h.rule.style("p", {
background: "red",
}),
h.rule.style("a", {
textDecoration: "none",
}),
]),
]
);
t.deepEqual(await evaluate(R62, { document }), [
failed(R62, target, {
1: Outcomes.IsNotDistinguishable(
[noStyle],
[noStyle],
[
Ok.of(
ComputedStyles.of([
["border-width", "0px"],
["color", "rgb(0% 0% 93.33333%)"],
["outline", "auto"],
])
),
]
),
}),
]);
});
test(`evaluate() fails an <a> element that has no distinguishing features and
has a background color equal to that of the paragraph`, async (t) => {
const target = <a href="#">Link</a>;
const document = h.document(
[<p>Hello {target}</p>],
[
h.sheet([
h.rule.style("p", {
background: "red",
}),
h.rule.style("a", {
textDecoration: "none",
background: "red",
}),
]),
]
);
const style = Err.of(
ComputedStyles.of([
["border-width", "0px"],
["color", "rgb(0% 0% 93.33333%)"],
["background", "rgb(100% 0% 0%)"],
["outline", "0px"],
])
);
t.deepEqual(await evaluate(R62, { document }), [
failed(R62, target, {
1: Outcomes.IsNotDistinguishable(
[style],
[style],
[
Ok.of(
ComputedStyles.of([
["border-width", "0px"],
["color", "rgb(0% 0% 93.33333%)"],
["background", "rgb(100% 0% 0%)"],
["outline", "auto"],
])
),
]
),
}),
]);
});
test(`evaluate() is inapplicable to an <a> element with no visible text content`, async (t) => {
const target = (
<a href="#">
<span hidden>Link</span>
</a>
);
const document = h.document([<p>Hello {target}</p>]);
t.deepEqual(await evaluate(R62, { document }), [inapplicable(R62)]);
});
test(`evaluate() is inapplicable to an <a> element with a <p> parent element
no non-link text content`, async (t) => {
const target = <a href="#">Link</a>;
const document = h.document([<p>{target}</p>]);
t.deepEqual(await evaluate(R62, { document }), [inapplicable(R62)]);
});
test(`evaluate() is inapplicable to an <a> element with a <p> parent element
no visible non-link text content`, async (t) => {
const target = <a href="#">Link</a>;
const document = h.document([
<p>
<span hidden>Hello</span> {target}
</p>,
]);
t.deepEqual(await evaluate(R62, { document }), [inapplicable(R62)]);
});
test(`evaluate() passes an <a> element with a <div role="paragraph"> parent element
with non-link text content in a <span> child element`, async (t) => {
const target = <a href="#">Link</a>;
const document = h.document([
<div role="paragraph">
<span>Hello</span> {target}
</div>,
]);
t.deepEqual(await evaluate(R62, { document }), [
passed(R62, target, {
1: Outcomes.IsDistinguishable(
[defaultStyle],
[defaultStyle],
[focusStyle]
),
}),
]);
});
test(`evaluate() is inapplicable to an <a> element with a <p> parent element
whose role has been changed`, async (t) => {
const target = <a href="#">Link</a>;
const document = h.document([
<p role="generic">
<span>Hello</span> {target}
</p>,
]);
t.deepEqual(await evaluate(R62, { document }), [inapplicable(R62)]);
});
test(`evaluate() passes a link whose bolder than surrounding text`, async (t) => {
const target = <a href="#">Link</a>;
const document = h.document(
[
<p>
<span>Hello</span> {target}
</p>,
],
[
h.sheet([
h.rule.style("a", {
textDecoration: "none",
fontWeight: "bold",
}),
]),
]
);
const style = Ok.of(
ComputedStyles.of([
["border-width", "0px"],
["color", "rgb(0% 0% 93.33333%)"],
["font-weight", "700"],
["outline", "0px"],
])
);
t.deepEqual(await evaluate(R62, { document }), [
passed(R62, target, {
1: Outcomes.IsDistinguishable(
[style],
[style],
[
Ok.of(
ComputedStyles.of([
["border-width", "0px"],
["color", "rgb(0% 0% 93.33333%)"],
["font-weight", "700"],
["outline", "auto"],
])
),
]
),
}),
]);
});
test(`evaluates() doesn't break when link text is nested`, async (t) => {
// Since text-decoration and focus outline is not inherited, the <span> has
// effectively no style other than color.
const target = (
<a href="#">
<span>Link</span>
</a>
);
const document = h.document([<p>Hello {target}</p>]);
t.deepEqual(await evaluate(R62, { document }), [
passed(R62, target, {
1: Outcomes.IsDistinguishable(
[defaultStyle, noStyle],
[defaultStyle, noStyle],
[focusStyle, noStyle]
),
}),
]);
});
test(`evaluates() accepts decoration on children of links`, async (t) => {
// Since text-decoration and focus outline is not inherited, the <span> has
// effectively no style other than color.
const target = (
<a href="#">
<span>Link</span>
</a>
);
const document = h.document(
[<p>Hello {target}</p>],
[
h.sheet([
h.rule.style("a", {
textDecoration: "none",
}),
h.rule.style("a:focus", {
textDecoration: "none",
outline: "none",
}),
h.rule.style("span", { fontWeight: "bold" }),
]),
]
);
const style = Ok.of(
ComputedStyles.of([
["border-width", "0px"],
["color", "rgb(0% 0% 93.33333%)"],
["font-weight", "700"],
["outline", "0px"],
])
);
t.deepEqual(await evaluate(R62, { document }), [
passed(R62, target, {
1: Outcomes.IsDistinguishable(
[style, noStyle],
[style, noStyle],
[style, noStyle]
),
}),
]);
});
test(`evaluates() accepts decoration on parents of links`, async (t) => {
// Since text-decoration and focus outline is not inherited, the <span> has
// effectively no style other than color.
const target = <a href="#">Link</a>;
const document = h.document(
[
<p>
Hello <span>{target}</span>
</p>,
],
[
h.sheet([
h.rule.style("a", {
textDecoration: "none",
}),
h.rule.style("a:focus", {
textDecoration: "none",
outline: "none",
}),
h.rule.style("span", { fontWeight: "bold" }),
]),
]
);
const linkStyle = Ok.of(
ComputedStyles.of([
["border-width", "0px"],
["color", "rgb(0% 0% 93.33333%)"],
["font-weight", "700"],
["outline", "0px"],
])
);
const spanStyle = Ok.of(
ComputedStyles.of([
["border-width", "0px"],
["font-weight", "700"],
["outline", "0px"],
])
);
t.deepEqual(await evaluate(R62, { document }), [
passed(R62, target, {
1: Outcomes.IsDistinguishable(
[linkStyle, spanStyle],
[linkStyle, spanStyle],
[linkStyle, spanStyle]
),
}),
]);
});
test(`evaluates() deduplicate styles in diagnostic`, async (t) => {
// Since text-decoration and focus outline is not inherited, the <span> have
// effectively no style other than color.
const target = (
<a href="#">
<span>click</span> <span>here</span>
</a>
);
const document = h.document([<p>Hello {target}</p>]);
t.deepEqual(await evaluate(R62, { document }), [
passed(R62, target, {
1: Outcomes.IsDistinguishable(
[defaultStyle, noStyle],
[defaultStyle, noStyle],
[focusStyle, noStyle]
),
}),
]);
});
test(`evaluates() passes on link with a different background-image than text`, async (t) => {
const target = <a href="#">Foo</a>;
const document = h.document(
[<p>Hello world {target}</p>],
[
h.sheet([
h.rule.style("a", {
textDecoration: "none",
backgroundImage:
"linear-gradient(to right, #046B99 50%, transparent 50%)",
}),
h.rule.style("a:focus", { outline: "none" }),
]),
]
);
const style = Ok.of(
ComputedStyles.of([
[
"background",
"linear-gradient(to right, rgb(1.56863% 41.96078% 60%) 50%, rgb(0% 0% 0% / 0%) 50%)",
],
...noDistinguishingProperties,
])
);
t.deepEqual(await evaluate(R62, { document }), [
passed(R62, target, {
1: Outcomes.IsDistinguishable([style], [style], [style]),
}),
]);
});
test(`evaluate() passes an <a> element in superscript`, async (t) => {
const target = (
<a href="#">
<sup>Link</sup>
</a>
);
const document = h.document(
[<p>Hello {target}</p>],
[
h.sheet([
h.rule.style("a", {
outline: "none",
textDecoration: "none",
}),
]),
]
);
const style = Ok.of(
ComputedStyles.of([
["vertical-align", "super"],
...noDistinguishingProperties,
])
);
t.deepEqual(await evaluate(R62, { document }), [
passed(R62, target, {
1: Outcomes.IsDistinguishable(
[style, noStyle],
[style, noStyle],
[style, noStyle]
),
}),
]);
}); | the_stack |
import { shell } from "electron";
import { normalize, join, extname } from "path";
import { readFile, watch, FSWatcher, pathExists } from "fs-extra";
import { transpile, ModuleKind, ScriptTarget } from "typescript";
import { Nullable } from "../../../shared/types";
import * as React from "react";
import { Spinner } from "@blueprintjs/core";
import { Scene, Node, Vector2, Vector3, Color4 } from "babylonjs";
import { IObjectInspectorProps } from "../components/inspector";
import { InspectorColor } from "../gui/inspector/fields/color";
import { InspectorNumber } from "../gui/inspector/fields/number";
import { InspectorButton } from "../gui/inspector/fields/button";
import { InspectorString } from "../gui/inspector/fields/string";
import { InspectorBoolean } from "../gui/inspector/fields/boolean";
import { InspectorSection } from "../gui/inspector/fields/section";
import { InspectorVector3 } from "../gui/inspector/fields/vector3";
import { InspectorVector2 } from "../gui/inspector/fields/vector2";
import { InspectorKeyMapButton } from "../gui/inspector/fields/keymap-button";
import { InspectorList, IInspectorListItem } from "../gui/inspector/fields/list";
import { WorkSpace } from "../project/workspace";
import { Tools } from "../tools/tools";
import { SandboxMain, IExportedInspectorValue } from "../../sandbox/main";
import { ScriptAssets } from "../assets/scripts";
import { IAssetComponentItem } from "../assets/abstract-assets";
import { AbstractInspector } from "./abstract-inspector";
export interface IScriptInspectorState {
/**
* Defines wether or not the script is being refreshing.
*/
refresing: boolean;
/**
* Defines the list of all available sripts.
*/
scripts: string[];
/**
* Defines the list of all decorated inspector values.
*/
inspectorValues: IExportedInspectorValue[];
}
export class ScriptInspector<T extends (Scene | Node), S extends IScriptInspectorState> extends AbstractInspector<T, S> {
private _scriptWatcher: Nullable<FSWatcher> = null;
/**
* Constructor.
* @param props defines the component's props.
*/
public constructor(props: IObjectInspectorProps) {
super(props);
this.state = {
...this.state,
scripts: [],
refresing: false,
inspectorValues: [],
};
}
/**
* Renders the content of the inspector.
*/
public renderContent(): React.ReactNode {
// Check metadata
this.selectedObject.metadata ??= { };
this.selectedObject.metadata.script ??= { };
this.selectedObject.metadata.script.name ??= "None";
// Check workspace
if (!WorkSpace.HasWorkspace()) { return null; }
return (
<InspectorSection title="Script">
{this._getDragAndDropZone()}
{this._getScriptsList()}
{this._getOpenButton()}
{this._getSpinner()}
{this._getInspectorValues()}
</InspectorSection>
);
}
/**
* Called on the component did mount.
*/
public componentDidMount(): void {
super.componentDidMount?.();
this.refreshAvailableScripts();
}
/**
* Called on the component will unmount.
*/
public componentWillUnmount(): void {
super.componentWillUnmount?.();
if (this._scriptWatcher) {
this._scriptWatcher.close();
this._scriptWatcher = null;
}
}
/**
* Returns the list of available items for the list.
*/
protected getScriptsListItems(): IInspectorListItem<string>[] {
return [{ label: "None", data: "None" }].concat(this.state.scripts.map((s) => ({
label: s,
data: s,
icon: <img src="../css/images/ts.png" style={{ width: "24px", height: "24px" }}></img>,
})));
}
/**
* Refreshes the list of all available scripts.
*/
protected async refreshAvailableScripts(): Promise<void> {
const scripts = await ScriptAssets.GetAllScripts();
this.setState({ scripts });
this._updateScriptVisibleProperties();
}
/**
* In case of existing scripts, it returns the list of all avaiable scripts to be attached.
*/
private _getScriptsList(): React.ReactNode {
return (
<InspectorList
object={this.selectedObject.metadata.script}
property="name"
label="Path"
items={async () => {
await this.refreshAvailableScripts();
return this.getScriptsListItems();
}}
onChange={() => this._updateScriptVisibleProperties()}
/>
)
}
/**
* In case of no script, draws a zone that supports drag'n'drop for scripts.
*/
private _getDragAndDropZone(): React.ReactNode {
if (this.selectedObject.metadata.script.name !== "None") {
return undefined;
}
return (
<div
style={{ width: "100%", height: "50px", border: "1px dashed black" }}
onDragEnter={(e) => (e.currentTarget as HTMLDivElement).style.border = "dashed red 1px"}
onDragLeave={(e) => (e.currentTarget as HTMLDivElement).style.border = "dashed black 1px"}
onDrop={(e) => {
(e.currentTarget as HTMLDivElement).style.border = "dashed black 1px";
try {
const data = JSON.parse(e.dataTransfer.getData("application/script-asset")) as IAssetComponentItem;
if (!data.extraData?.scriptPath) { throw new Error("Can't drag'n'drop script, extraData is misisng"); }
this.selectedObject.metadata.script.name = data.extraData.scriptPath;
this._updateScriptVisibleProperties();
} catch (e) {
this.editor.console.logError("Failed to parse data of drag'n'drop event.");
}
}}
>
<h2 style={{ textAlign: "center", color: "white", lineHeight: "50px", userSelect: "none" }}>Drag'n'drop script here.</h2>
</div>
);
}
/**
* In case of a script set, it returns the button component to open the script.
*/
private _getOpenButton(): React.ReactNode {
if (this.selectedObject.metadata.script.name === "None") {
return undefined;
}
const tsPath = join(WorkSpace.DirPath!, this.selectedObject.metadata.script.name);
return <InspectorButton label="Open..." onClick={() => shell.openItem(tsPath)} />
}
/**
* Returns the spinner shown in case of refreshing.
*/
private _getSpinner(): React.ReactNode {
if (!this.state.refresing) {
return undefined;
}
return <Spinner size={35} />;
}
/**
* Returns the list of all exported values.
*/
private _getInspectorValues(): React.ReactNode {
if (this.selectedObject.metadata.script.name === "None" || !this.state.inspectorValues.length) {
return undefined;
}
this.selectedObject.metadata.script.properties ??= { };
const children: React.ReactNode[] = [];
const properties = this.selectedObject.metadata.script.properties;
this.state.inspectorValues.forEach((iv) => {
properties[iv.propertyKey] ??= { type: iv.type };
const label = iv.name ?? iv.propertyKey;
const property = properties[iv.propertyKey];
switch (iv.type) {
case "number":
property.value ??= property.value ?? iv.defaultValue ?? 0;
children.push(
<InspectorNumber object={property} property="value" label={label} step={0.01} />
);
break;
case "string":
property.value ??= property.value ?? iv.defaultValue ?? "";
children.push(
<InspectorString object={property} property="value" label={label} />
);
break;
case "boolean":
property.value ??= property.value ?? iv.defaultValue ?? false;
children.push(
<InspectorBoolean object={property} property="value" label={label} />
);
break;
case "KeyMap":
property.value ??= property.value ?? iv.defaultValue ?? 0;
children.push(
<InspectorKeyMapButton object={property} property="value" label={label} />
);
break;
case "Vector2":
if (iv.defaultValue) {
const defaultValue = iv.defaultValue as Vector2;
property.value ??= property.value ?? { x: defaultValue.x, y: defaultValue.y };
} else {
property.value ??= property.value ?? { x: 0, y: 0 };
}
children.push(
<InspectorVector2 object={property} property="value" label={label} step={0.01} />
);
break;
case "Vector3":
if (iv.defaultValue) {
const defaultValue = iv.defaultValue as Vector3;
property.value ??= property.value ?? { x: defaultValue._x, y: defaultValue._y, z: defaultValue._z };
} else {
property.value ??= property.value ?? { x: 0, y: 0, z: 0 };
}
children.push(
<InspectorVector3 object={property} property="value" label={label} step={0.01} />
);
break;
case "Color3":
case "Color4":
if (iv.defaultValue) {
const defaultValue = iv.defaultValue as Color4;
property.value ??= property.value ?? { r: defaultValue.r, g: defaultValue.g, b: defaultValue.b, a: defaultValue.a };
} else {
property.value ??= property.value ?? { r: 0, g: 0, b: 0, a: iv.type === "Color4" ? 1 : undefined };
}
children.push(
<InspectorColor object={property} property="value" label={label} step={0.01} />
);
break;
}
});
return (
<InspectorSection title="Exported Values" children={children} />
)
}
/**
* Updates the visible properties from the script currently set.
*/
private async _updateScriptVisibleProperties(): Promise<void> {
// Stop watcher
this._scriptWatcher?.close();
this._scriptWatcher = null;
if (!this.isMounted) { return; }
// Check
if (this.selectedObject.metadata.script.name === "None") {
return this.isMounted && this.forceUpdate();
}
this.setState({ refresing: true });
await this._refreshDecorators();
const name = this.selectedObject.metadata.script.name as string;
if (!name) { return; }
const extension = extname(name);
const extensionIndex = name.lastIndexOf(extension);
if (extensionIndex === -1) { return; }
const jsName = normalize(`${name.substr(0, extensionIndex)}.js`);
const jsPath = join(WorkSpace.DirPath!, "build", jsName);
if (!this._scriptWatcher) {
while (this.isMounted && !(await pathExists(jsPath))) {
await Tools.Wait(500);
}
if (!this.isMounted) { return; }
this._scriptWatcher = watch(jsPath, { encoding: "utf-8" }, (ev) => {
if (ev === "change") {
this._updateScriptVisibleProperties();
}
});
}
const inspectorValues = await SandboxMain.GetInspectorValues(jsPath) ?? [];
this.setState({ refresing: false, inspectorValues });
}
/**
* Refreshes the decorators functions that are used in the project.
*/
private async _refreshDecorators(): Promise<void> {
const decorators = await readFile(join(Tools.GetAppPath(), "assets", "scripts", "decorators.ts"), { encoding: "utf-8" });
const transpiledScript = transpile(decorators, { module: ModuleKind.None, target: ScriptTarget.ES5, experimentalDecorators: true });
await SandboxMain.ExecuteCode(transpiledScript, "__editor__decorators__.js");
}
} | the_stack |
import utils = require("../common/utils");
import styles = require("./styles/styles");
import React = require("react");
import ReactDOMServer = require("react-dom/server");
import csx = require('./base/csx');
import {BaseComponent} from "./ui";
import * as ui from "./ui";
import {cast,server} from "../socket/socketClient";
import * as commands from "./commands/commands";
import * as types from "../common/types";
import {AvailableProjectConfig} from "../common/types";
import {Clipboard} from "./components/clipboard";
import {PendingRequestsIndicator} from "./pendingRequestsIndicator";
import {Icon} from "./components/icon";
import {ButtonBlack} from "./components/buttons";
import {InputBlack} from "./components/inputs";
import * as pure from "../common/pure";
let {DraggableCore} = ui;
import {connect} from "react-redux";
import {StoreState,expandErrors,collapseErrors} from "./state/state";
import * as state from "./state/state";
import * as gotoHistory from "./gotoHistory";
import {tabState,tabStateChanged} from "./tabs/v2/appTabsContainer";
import * as settings from "./state/settings";
import {errorsCache} from "./globalErrorCacheClient";
let notificationKeyboardStyle = {
border: '2px solid',
borderRadius: '6px',
display: 'inline-block',
padding: '5px',
background: 'grey',
}
export interface Props {
// from react-redux ... connected below
errorsExpanded?: boolean;
activeProject?: AvailableProjectConfig;
activeProjectFiles?: { [filePath: string]: boolean };
socketConnected?: boolean;
errorsDisplayMode?: types.ErrorsDisplayMode;
errorsFilter?: string;
}
export interface State {
/** height in pixels */
height?: number;
}
let resizerWidth = 5;
let resizerStyle = {
background: 'radial-gradient(#444,transparent)',
height: resizerWidth+'px',
cursor:'ns-resize',
color: '#666',
}
@connect((state: StoreState): Props => {
return {
errorsExpanded: state.errorsExpanded,
activeProject: state.activeProject,
activeProjectFiles: state.activeProjectFilePathTruthTable,
socketConnected: state.socketConnected,
errorsDisplayMode: state.errorsDisplayMode,
errorsFilter: state.errorsFilter,
};
})
export class MainPanel extends BaseComponent<Props, State>{
constructor(props:Props){
super(props);
this.state = {
height: 250,
}
}
componentDidMount() {
settings.mainPanelHeight.get().then(res => {
let height = res || this.state.height;
height = Math.min(window.innerHeight - 100, height);
this.setState({ height });
});
this.disposible.add(commands.toggleMessagePanel.on(()=>{
state.getState().errorsExpanded?state.collapseErrors({}):state.expandErrors({});
}));
this.disposible.add(tabStateChanged.on(()=>{
this.forceUpdate();
}));
this.disposible.add(errorsCache.errorsDelta.on(()=>{
this.forceUpdate();
}))
}
render(){
const errorsUpdate = errorsCache.getErrorsLimited();
let errorPanel = undefined;
if (this.props.errorsExpanded){
errorPanel = <div>
<DraggableCore onDrag={this.handleDrag} onStop={this.handleStop}>
<div style={csx.extend(csx.flexRoot, csx.centerCenter, resizerStyle)}><Icon name="ellipsis-h"/></div>
</DraggableCore>
<div style={csx.extend(styles.errorsPanel.main, { height: this.state.height }) }>
{
<div
style={styles.errorsPanel.headerSection}>
<div style={csx.horizontal}>
<div style={csx.extend(csx.horizontal, csx.flex, csx.center, {marginRight:'10px'})}>
<ButtonBlack
text={"Show All"}
onClick={()=>state.setErrorsDisplayMode(types.ErrorsDisplayMode.all)}
isActive={this.props.errorsDisplayMode == types.ErrorsDisplayMode.all}/>
<ButtonBlack
text={"Show Only Open Files"}
onClick={()=>state.setErrorsDisplayMode(types.ErrorsDisplayMode.openFiles)}
isActive={this.props.errorsDisplayMode == types.ErrorsDisplayMode.openFiles}/>
<label style={{marginLeft:'10px'}}>
Filter:
</label>
<InputBlack
style={{marginRight:'10px', maxWidth:'200px'}}
onChange={(value)=>state.setErrorsFilter(value)}
value={this.props.errorsFilter}/>
<ButtonBlack
text={"Clear"}
disabled={!this.props.errorsFilter.trim()}
onClick={()=>state.setErrorsFilter('')}/>
</div>
{errorsUpdate.tooMany
&& <div
style={styles.errorsPanel.tooMany as any}
className="hint--bottom-left hint--info"
data-hint="We only sync the top 50 per file with a limit of 250. That ensures that live linting doesn't slow anything else down.">
{errorsUpdate.totalCount} total. Showing top {errorsUpdate.syncCount}.
</div>}
</div>
</div>
}
{
errorsUpdate.totalCount
? this.renderErrors()
: <div style={styles.errorsPanel.success}>No Errors ❤</div>
}
</div>
</div>
}
return (
<div style={{zIndex:6 /* force over golden-layout */}}>
{errorPanel}
</div>
);
}
renderErrors() {
const errorsToRender: types.ErrorsByFilePath = tabState.errorsByFilePathFiltered().errorsByFilePath;
return (
<div style={{overflow:'auto'}}>{
Object.keys(errorsToRender)
.filter(filePath => !!errorsToRender[filePath].length)
.map((filePath, i) => {
const errors = errorsToRender[filePath];
return <ErrorRenders.ErrorsForFilePath key={i} errors={errors} filePath={filePath} />;
})
}</div>
);
}
toggleErrors = () => {
if (this.props.errorsExpanded){
collapseErrors({});
}
else{
expandErrors({});
}
}
openErrorLocation = (error: types.CodeError) => {
gotoHistory.gotoError(error);
}
openFile = (filePath: string) => {
commands.doOpenOrFocusFile.emit({ filePath });
}
handleDrag = (evt, ui: {
node: Node,
deltaX: number, deltaY: number,
lastX: number, lastY: number,
}) => {
this.setState({ height: utils.rangeLimited({ num: this.state.height - ui.deltaY, min: 100, max: window.innerHeight - 100 }) });
};
handleStop = () => {
const height = this.state.height;
settings.mainPanelHeight.set(height);
}
componentWillUpdate(nextProps: Props, nextState: State) {
if (nextState.height !== this.state.height
|| nextProps.errorsExpanded !== this.props.errorsExpanded) {
tabState.debouncedResize();
}
}
}
/**
* Pure components for rendering errors
*/
namespace ErrorRenders {
const openErrorLocation = (error: types.CodeError) => {
gotoHistory.gotoError(error);
}
interface ErrorsForFilePathProps {
filePath: string,
errors: types.CodeError[]
}
export class ErrorsForFilePath extends React.PureComponent<ErrorsForFilePathProps, {}> {
render() {
const codeErrors = this.props.errors;
const errors = codeErrors.filter(x=>x.level === 'error');
const warnings = codeErrors.filter(x=>x.level === 'warning');
let errorsRendered =
// error before warning
errors.concat(warnings)
.map((e, j) => (
<SingleError key={`${j}`} error={e}/>
));
return <div>
<div style={styles.errorsPanel.filePath as any} onClick={() => openErrorLocation(this.props.errors[0]) }>
<Icon name="file-code-o" style={{ fontSize: '.8rem' }}/>
{this.props.filePath}
(
{!!errors.length && <span style={{color: styles.errorColor}}>{errors.length}</span>}
{!!(errors.length && warnings.length) && ','}
{!!warnings.length && <span style={{color: styles.warningColor}}>{warnings.length}</span>}
)
</div>
<div style={styles.errorsPanel.perFileList}>
{errorsRendered}
</div>
</div>;
}
}
export class SingleError extends React.PureComponent<{error:types.CodeError},{}>{
render() {
const e = this.props.error;
const style = e.level === 'error'
? styles.errorsPanel.errorDetailsContainer
: styles.errorsPanel.warningDetailsContainer;
return (
<div style={style} onClick={() => openErrorLocation(e) }>
<div style={styles.errorsPanel.errorDetailsContent}>
<div style={styles.errorsPanel.errorMessage}>
🐛({e.from.line + 1}: {e.from.ch + 1}) {e.message}
{' '}<Clipboard text={`${e.filePath}:${e.from.line + 1} ${e.message}`}/>
</div>
{e.preview ? <div style={styles.errorsPanel.errorPreview}>{e.preview}</div> : ''}
</div>
</div>
);
}
}
} | the_stack |
import React from 'react';
type ReactProps = {
service?: any;
selectedContainer: string;
};
type DockerComposeCommands = {
[prop: string]: string;
};
type ServiceOverview = {
[prop: string]: any;
};
type TwoDimension = {
[prop: string]: any;
};
const ServiceInfo: React.FC<ReactProps> = ({ service, selectedContainer }) => {
// Create an object to house text intros for each docker-compose property
const dockerComposeCommands: DockerComposeCommands = {
build: 'Build: ',
image: 'Image: ',
command: 'Command: ',
environment: 'Environment: ',
env_file: 'Env_file: ',
ports: 'Ports: ',
};
// Objects to hold filtered 1D service Commands
const serviceOverview: ServiceOverview = {};
// Arrays/Objects to hold filtered 2D service Commands
const environmentVariables: TwoDimension = {};
const env_file: string[] = [];
const portsArray: string[] = [];
// loop through each command in the selected container,
// if the command exists in the DC properties, correspond it to an empty string in the serviceOverview object
// also, do the following for each of the specific commands with 2D values, as well as the "build" command because it has options:
// ENVIRONMENT: we want to take an environment variable such as: "JACOCO=${REPORT_COVERAGE}" and set the 2d line to look like - JACOCO: $(REPORT_COVERAGE)
// Thus, if its value is an array, loop through it, split the value at the the '=', and set the key in the environmentVariables cache to the first half, and the value to the second half
// Otherwise, if it's an object, it's already split for you, so set the serviceOverview key to the environment variable's key, and the serviceOverview value to the environment's value
// ENV_FILE: an env file can have a 1D string, so if it does, just set the key in serviceOverview equal to its value as passed down from state
// If it's an array, loop through the env_file values, and push them into the env_file "cache" on line 46
// PORTS: if ports incorrectly is given a string, just set the key in serviceOverview equal to its value as passed down from state
// Finally, for all commands with 1D values and no options (image and command), just set the key in serviceOverview equal to its value as passed down from state
if (service) {
Object.keys(service).forEach((command) => {
if (dockerComposeCommands[command]) {
serviceOverview[command] = '';
// *********************
// * Environment
// *********************
if (command === 'environment') {
if (Array.isArray(service[command])) {
service[command].forEach((value: string) => {
const valueArray = value.split('=');
environmentVariables[valueArray[0]] = valueArray[1];
});
} else {
const environment = service[command];
Object.keys(environment).forEach((key) => {
environmentVariables[key] = environment[key];
});
}
// *********************
// Env_File
// *********************
} else if (command === 'env_file') {
if (typeof service[command] === 'string') {
serviceOverview[command] = service[command];
} else {
for (let i = 0; i < service[command].length; i += 1) {
env_file.push(service[command][i]);
}
}
// *********************
// Ports
// *********************
} else if (command === 'ports') {
for (let i = 0; i < service[command].length; i += 1) {
if (typeof service[command][i] === 'object') {
portsArray.push(
`${service[command][i].published}:${
service[command][i].target
} - ${service[command][i].protocol.toUpperCase()} : ${
service[command][i].mode
}`,
);
} else if (!service[command][i].includes(':')) {
portsArray.push(`Auto-assigned:${service[command][i]}`);
} else portsArray.push(service[command][i]);
}
// *********************
// * Build
// *********************
} else if (
command === 'build' &&
typeof service[command] !== 'string'
) {
// *********************
// * Command
// *********************
} else if (command === 'command' && Array.isArray(service[command])) {
// *********************
// * General 1D Objects
// *********************
} else {
serviceOverview[command] = service[command];
}
}
});
}
const commandToJSX = (command: any) => {
const optionJSX = Object.keys(command).map((option) => {
if (typeof command[option] === 'string') {
return (
<div>
<span className="option-key">{option}:</span>
{command[option]}
</div>
);
} else if (Array.isArray(command[option])) {
const optionJSX = (command[option] as []).map((element: string, i) => {
const valueArray = element.split('=');
return (
<li key={i}>
<span>{valueArray[0]}:</span> {valueArray[1]}
</li>
);
});
return (
<div>
<span className="option-key">{option}:</span>
<ul>{optionJSX}</ul>
</div>
);
} else {
const optionJSX = Object.keys(command[option]).map((key: string, i) => {
return (
<li key={i}>
<span>{key}:</span> {command[option][key]}
</li>
);
});
return (
<div>
<span className="option-key">{option}:</span>
<ul>{optionJSX}</ul>
</div>
);
}
});
return <div className="options">{optionJSX}</div>;
};
const infoToJsx = (
serviceOverview: ServiceOverview,
dockerComposeCommands: DockerComposeCommands,
environmentVariables: TwoDimension,
env_file: string[],
portsArray: string[],
service: any,
) => {
return Object.keys(serviceOverview).length === 0
? 'Please select a container with details to display.'
: Object.keys(serviceOverview).map((command, i) => {
let commandJSX = (
<span className="command">{dockerComposeCommands[command]}</span>
);
let valueJSX: JSX.Element = <div></div>;
// *********************
// * Environment
// *********************
if (command === 'environment' && !serviceOverview[command].length) {
const environment: JSX.Element[] = [];
Object.keys(environmentVariables).forEach((key) => {
environment.push(
<li className="second-level" key={key}>
<span>{key}:</span> {environmentVariables[key]}
</li>,
);
});
valueJSX = (
<span className="command-values">
<ul>{environment}</ul>
</span>
);
// *********************
// Env_File
// *********************
} else if (command === 'env_file' && env_file.length) {
let envFileArray: JSX.Element[] = [];
env_file.forEach((el) => {
envFileArray.push(
<li className="second-level" key={el}>
{el}
</li>,
);
});
valueJSX = (
<span className="command-values">
<ul>{envFileArray}</ul>
</span>
);
// *********************
// Build
// *********************
} else if (command === 'build' && !serviceOverview[command].length) {
valueJSX = commandToJSX(service[command]);
// *********************
// Command
// *********************
} else if (
command === 'command' &&
!serviceOverview[command].length
) {
valueJSX = (
<span className="command-values">
{service[command].join(', ')}
</span>
);
// *********************
// Ports
// *********************
} else if (command === 'ports' && !serviceOverview[command].length) {
if (portsArray.length) {
let portsArraySquared: JSX.Element[] = [];
portsArray.forEach((el) => {
portsArraySquared.push(
<li className="second-level" key={el}>
{el}
</li>,
);
});
valueJSX = (
<span className="command-values">
<ul>{portsArraySquared}</ul>
</span>
);
}
} else {
valueJSX = (
<span className="command-values">{serviceOverview[command]}</span>
);
}
return (
<div key={`command${i}`}>
{commandJSX}
{valueJSX}
</div>
);
});
};
return (
<div className="info-dropdown">
<h3>
{selectedContainer !== ''
? selectedContainer[0].toUpperCase() + selectedContainer.slice(1)
: selectedContainer}
</h3>
<div className="content-wrapper">
<div className="overflow-container">
<div className="overview">
{infoToJsx(
serviceOverview,
dockerComposeCommands,
environmentVariables,
env_file,
portsArray,
service,
)}
</div>
</div>
</div>
</div>
);
};
export default ServiceInfo; | the_stack |
import {
BadRequestException,
Injectable,
InternalServerErrorException,
Logger,
NotFoundException
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { ShowTime } from './show-time.schema';
import * as mongoose from 'mongoose';
import { CreateDocumentDefinition, Model, Types } from 'mongoose';
import { Movie } from '../movies/movie.schema';
import { Theatre } from '../theatres/theatre.schema';
import * as dayjs from 'dayjs';
import { defer, forkJoin, from, Observable } from 'rxjs';
import { bufferCount, concatMap, filter, pairwise, take, tap, reduce, map } from 'rxjs/operators';
import { checkStaffPermission, constants, getSkipLimit } from '../common/utils';
import { AddShowTimeDto, TicketDto } from './show-time.dto';
import { PaginationDto } from "../common/pagination.dto";
import { Ticket } from "../seats/ticket.schema";
import { Seat } from "../seats/seat.schema";
import * as isBetween from 'dayjs/plugin/isBetween';
import * as utc from 'dayjs/plugin/utc';
import * as timezone from 'dayjs/plugin/timezone';
import * as customParseFormat from 'dayjs/plugin/customParseFormat';
import { SeatsService } from "../seats/seats.service";
import { UserPayload } from "../auth/get-user.decorator";
import { Reservation } from "../reservations/reservation.schema";
dayjs.extend(isBetween);
dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.extend(customParseFormat);
type RawShowTimeAndTheatre = {
theatre: Theatre;
show_time: ShowTime;
};
type ShowTimeAndMovie = {
movie: Movie,
show_time: ShowTime;
};
@Injectable()
export class ShowTimesService {
private readonly logger = new Logger('ShowTimesService');
private movieCount: number | null = null;
constructor(
@InjectModel(ShowTime.name) private readonly showTimeModel: Model<ShowTime>,
@InjectModel(Movie.name) private readonly movieModel: Model<Movie>,
@InjectModel(Theatre.name) private readonly theatreModel: Model<Theatre>,
@InjectModel(Ticket.name) private readonly ticketModel: Model<Ticket>,
@InjectModel(Seat.name) private readonly seatModel: Model<Seat>,
@InjectModel(Reservation.name) private readonly reservationModel: Model<Reservation>,
private readonly seatsService: SeatsService,
) {}
async seed() {
// const sts = await this.showTimeModel.find({});
// for (const st of sts) {
// const r = dayjs(st.start_time).add(-2, 'day').toDate();
// await this.movieModel.updateOne({ _id: st.movie }, { released_date: r }).exec();
// }
// return;
//
const current = dayjs(new Date());
const theatres = await this.theatreModel.find({});
for (const theatre of theatres) {
const [startHString, endHString] = theatre.opening_hours.split(' - ');
let startH = +startHString.split(':')[0];
const startM = +startHString.split(':')[1];
if (startM > 0) {
++startH;
}
const [endH, endM] = endHString.split(':').map(x => +x);
const hours: number[] = Array.from({ length: endH - startH + 1 }, (_, i) => i + startH);
this.logger.debug(`Hours for ${theatre.name} are ${JSON.stringify(hours)} -- ${startH}:${startM} -> ${endH}:${endM}`);
const startDay = current.utcOffset(420, false).startOf('day');
for (const room of theatre.rooms) {
for (let dDate = -1; dDate <= 10; dDate++) {
const day = startDay.add(dDate, 'day');
const thStartTime = day.set('hour', startH).set('minute', startM);
const thEndTime = day.set('hour', endH).set('minute', endM);
const movie: Movie | null = await this.pickAMovieReleasedBefore(day);
if (!movie) {
continue;
}
for (const hour of hours) {
const res = await this.checkAndSave(day, hour, movie, theatre, room, thStartTime, thEndTime);
this.logger.debug(res);
}
}
}
}
}
private async pickAMovieReleasedBefore(day: dayjs.Dayjs): Promise<Movie | null> {
let movie: Movie | null | undefined = null;
let retryCount = 0;
while (true) {
movie = await this.randomMovie(day);
if (movie) {
return movie;
}
retryCount++;
if (retryCount >= 3) {
break;
}
}
return movie;
}
private async checkAndSave(
day: dayjs.Dayjs,
hour: number,
movie: Movie,
theatre: Theatre,
room: string,
thStartTime: dayjs.Dayjs,
thEndTime: dayjs.Dayjs
): Promise<"Start time must be not before movie released date" |
"Start time must be not before theatre start time" |
"End time must be not after theatre end time" |
"Already have 1 showtime in this time period" |
"There's no more free time to create a new showtime" | 'Successfully'> {
const startTime = day
.set('hour', hour)
.set('minute', 0)
.set('second', 0)
.set('millisecond', 0);
const endTime = startTime.add(movie.duration, 'minute');
this.logger.debug(`Start saving show time: ${theatre.name} -- ${room} <> ${thStartTime.toDate()}-${thEndTime.toDate()} <> ${startTime.toDate()}-${endTime.toDate()}`);
if (startTime.isBefore(movie.released_date)) {
return `Start time must be not before movie released date`;
}
if (startTime.isBefore(thStartTime)) {
return `Start time must be not before theatre start time`;
}
if (endTime.isAfter(thEndTime)) {
return `End time must be not after theatre end time`;
}
const showTimes = await this.showTimeModel
.find({
theatre: theatre._id,
room,
is_active: true,
start_time: { $gte: thStartTime.toDate() },
end_time: { $lte: thEndTime.toDate() },
})
.sort({ start_time: 1 });
this.logger.debug(`showTimes ${showTimes.length}`);
showTimes.forEach(s => this.logger.debug(`${s.start_time} -> ${s.end_time}`));
if (showTimes.length == 1) {
const found = showTimes[0];
if (startTime.isBefore(found.end_time) && endTime.isAfter(found.start_time)) {
return `Already have 1 showtime in this time period`;
}
}
if (showTimes.length >= 2) {
const pair: [ShowTime, ShowTime] | undefined = [
null,
...showTimes,
null,
].pairwise().find(([prev, next]) => {
if (prev && next) {
return startTime.isBetween(prev.end_time, next.start_time)
&& endTime.isBetween(prev.end_time, next.start_time);
}
if (prev === null) {
return startTime.isBetween(thStartTime, next.start_time)
&& endTime.isBetween(thStartTime, next.start_time);
}
return startTime.isBetween(prev.end_time, thEndTime)
&& endTime.isBetween(prev.end_time, thEndTime);
});
if (pair === undefined) {
return `There's no more free time to create a new showtime`;
}
this.logger.debug(`Found pair ${pair[0]?.start_time}:${pair[0]?.end_time} -> ${pair[1]?.start_time}:${pair[1]?.end_time}`);
}
/*if (startTime.isBefore(movie.released_date)) {
return 0;
}
const endTime = startTime.add(movie.duration, 'minute');
this.logger.debug(`Start saving show time: ${theatre.name} -- ${room} <> ${thStartTime.toDate()}-${thEndTime.toDate()} <> ${startTime}-${endTime}`);
const showTimes = await this.showTimeModel
.find({
theatre: theatre._id,
room,
is_active: true,
start_time: { $gte: thStartTime.toDate() },
end_time: { $lte: thEndTime.toDate() },
})
.sort({ start_time: 1 });
if (showTimes.length == 1) {
if (startTime.isBefore(showTimes[0].end_time) && endTime.isAfter(showTimes[0].start_time)
|| startTime.isBefore(thStartTime) || endTime.isAfter(thEndTime)) {
return 1;
}
}
if (showTimes.length >= 2) {
const array = await from(showTimes)
.pipe(
pairwise(),
filter(([prev, next]) =>
(startTime as any).isBetween(prev.end_time, next.start_time)
&& (endTime as any).isBetween(prev.end_time, next.start_time)
&& (startTime as any).isBetween(thStartTime, thEndTime)
&& (endTime as any).isBetween(thStartTime, thEndTime)
),
take(1),
)
.toPromise();
if (array === undefined) {
return 2;
}
this.logger.debug(`>>> Array ${array}`);
}*/
const doc: Omit<CreateDocumentDefinition<ShowTime>, '_id'> = {
movie: movie._id,
theatre: theatre._id,
room,
is_active: true,
end_time: endTime.toDate(),
start_time: startTime.toDate(),
};
const showTime = await this.showTimeModel.create(doc);
await this.seatsService.seedTicketsForSingleShowTime(showTime);
this.logger.debug(`Saved show time: ${JSON.stringify(showTime)}`);
return 'Successfully';
}
private async randomMovie(day: dayjs.Dayjs): Promise<Movie | undefined> {
const count = this.movieCount = this.movieCount ?? await this.movieModel.count({});
const skip = Math.floor(count * Math.random());
return await this.movieModel.find({ released_date: { $lte: day.toDate() } })
.skip(skip)
.limit(1)
.exec()
.then(v => v[0]);
}
getShowTimesByMovieId(movieId: string, center: [number, number] | null): Promise<RawShowTimeAndTheatre[]> {
const currentDay = new Date();
const start = dayjs(currentDay).startOf('day').toDate();
const end = dayjs(currentDay).endOf('day').add(4, 'day').toDate();
return this.theatreModel.aggregate([
...(
center != null
?
[
{
$geoNear: {
near: {
type: 'Point',
coordinates: center,
},
distanceField: 'distance',
includeLocs: 'location',
maxDistance: constants.maxDistanceInMeters,
spherical: true,
},
},
{ $match: { is_active: true } }
]
: []
),
{
$addFields: {
theatre: '$$ROOT',
},
},
{
$project: {
theatre: 1,
}
},
{
$lookup: {
from: 'show_times',
localField: '_id',
foreignField: 'theatre',
as: 'show_time',
}
},
{ $unwind: '$show_time' },
{
$match: {
$and: [
{ 'show_time.movie': new mongoose.Types.ObjectId(movieId) },
{ 'show_time.start_time': { $gte: start } },
{ 'show_time.end_time': { $lte: end } },
{ 'show_time.is_active': true },
]
},
},
{
$lookup: {
from: 'movies',
localField: 'show_time.movie',
foreignField: '_id',
as: 'movie',
}
},
{ $unwind: '$movie' },
{
$match: {
'movie.released_date': { $lte: start },
},
},
{ $project: { movie: 0 } },
]).exec();
}
async getShowTimesByTheatreId(theatreId: string): Promise<ShowTimeAndMovie[]> {
const theatre = await this.theatreModel.findById(theatreId);
if (!theatre) {
throw new NotFoundException();
}
const currentDay = new Date();
const start = dayjs(currentDay).startOf('day').toDate();
const end = dayjs(currentDay).endOf('day').add(4, 'day').toDate();
return this.theatreModel.aggregate([
{ $match: { _id: new Types.ObjectId(theatreId) } },
{
$lookup: {
from: 'show_times',
localField: '_id',
foreignField: 'theatre',
as: 'show_time',
}
},
{ $unwind: '$show_time' },
{
$match: {
$and: [
{ 'show_time.start_time': { $gte: start } },
{ 'show_time.end_time': { $lte: end } },
{ 'show_time.is_active': true },
]
},
},
{
$lookup: {
from: 'movies',
localField: 'show_time.movie',
foreignField: '_id',
as: 'movie',
}
},
{ $unwind: '$movie' },
{
$match: {
'movie.released_date': { $lte: start },
},
},
{
$sort: {
'show_time.start_time': 1,
'movie.title': 1,
}
}
]).exec();
}
async addShowTime(dto: AddShowTimeDto, userPayload: UserPayload): Promise<ShowTime> {
const room = '2D 1';
const [movie, theatre]: [Movie, Theatre] = await Promise.all([
this.movieModel.findById(dto.movie).then(v => {
if (!v) {
throw new NotFoundException(`Movie with id ${dto.movie}`);
}
return v;
}),
this.theatreModel.findById(dto.theatre).then(v => {
if (!v) {
throw new NotFoundException(`Theatre with id ${dto.theatre}`);
}
return v;
}),
]);
checkStaffPermission(userPayload, dto.theatre);
const seats = await from(dto.tickets)
.pipe(
bufferCount(32),
concatMap(dtos => {
const tasks: Array<Observable<{ seat: Seat, dto: TicketDto }>> = dtos.map(dto => {
return defer(async () => {
const seat = await this.seatModel.findOne({ _id: dto.seat, room, theatre: theatre._id });
if (!seat) {
throw new NotFoundException(`Seat with id ${dto.seat}`);
}
return { seat, dto };
})
});
return forkJoin(tasks);
}),
reduce((acc, e) => acc.concat(e), [] as { seat: Seat, dto: TicketDto }[]),
)
.toPromise();
this.logger.debug(`dto.tickets ${dto.tickets.length} ... ${seats.length}`);
/*const startTime: dayjs.Dayjs = dayjs(dto.start_time);
const endTime: dayjs.Dayjs = startTime.add(movie.duration, 'minute');
const day: dayjs.Dayjs = startTime.startOf('day');
const [startHString, endHString]: string[] = theatre.opening_hours.split(' - ');
const [startH, startM]: number[] = startHString.split(':').map(x => +x);
const [endH, endM]: number[] = endHString.split(':').map(x => +x);
const thStartTime: dayjs.Dayjs = day.set('hour', startH).set('minute', startM);
const thEndTime: dayjs.Dayjs = day.set('hour', endH).set('minute', endM);*/
const start_time_date = dto.start_time;
this.logger.debug(start_time_date.toISOString() + ' '.repeat(26) + '[1] start_time_date');
this.logger.debug(start_time_date.toString() + '[1] start_time_date');
const start_time: dayjs.Dayjs = dayjs(start_time_date);
this.logger.debug(start_time.toISOString() + ' '.repeat(26) + '[2] start_time');
this.logger.debug(start_time.toDate().toString() + '[2] start_time');
const startTimeLocal = start_time.utcOffset(420, false);
this.logger.debug(startTimeLocal.toISOString() + ' '.repeat(26) + '[3] startTimeLocal');
this.logger.debug(startTimeLocal.toDate().toString() + '[3] startTimeLocal');
const endTimeLocal: dayjs.Dayjs = startTimeLocal.add(movie.duration, 'minute');
this.logger.debug(endTimeLocal.toISOString() + ' '.repeat(26) + '[4] endTimeLocal');
this.logger.debug(endTimeLocal.toDate().toString() + '[4] endTimeLocal');
const [startHString, endHString]: string[] = theatre.opening_hours.split(' - ');
const [startH, startM]: number[] = startHString.split(':').map(x => +x);
const [endH, endM]: number[] = endHString.split(':').map(x => +x);
const startOfDayLocal: dayjs.Dayjs = startTimeLocal.startOf('day');
this.logger.debug(startOfDayLocal.toISOString() + ' '.repeat(26) + '[5] startOfDayLocal');
this.logger.debug(startOfDayLocal.toDate().toString() + '[5] startOfDayLocal');
const thStartTime: dayjs.Dayjs = startOfDayLocal.set('hour', startH).set('minute', startM);
const thEndTime: dayjs.Dayjs = startOfDayLocal.set('hour', endH).set('minute', endM);
this.logger.debug(thStartTime.toISOString() + ' '.repeat(26) + '[6] thStartTime');
this.logger.debug(thStartTime.toDate().toString() + '[6] thStartTime');
this.logger.debug(thEndTime.toISOString() + ' '.repeat(26) + '[7] thEndTime');
this.logger.debug(thEndTime.toDate().toString() + '[7] thEndTime');
if (startTimeLocal.isBefore(movie.released_date)) {
throw new BadRequestException(`Start time must be not before movie released date`);
}
if (startTimeLocal.isBefore(thStartTime)) {
throw new BadRequestException(`Start time must be not before theatre start time`);
}
if (endTimeLocal.isAfter(thEndTime)) {
throw new BadRequestException(`End time must be not after theatre end time`);
}
const showTimes = await this.showTimeModel
.find({
theatre: theatre._id,
room,
is_active: true,
start_time: { $gte: thStartTime.toDate() },
end_time: { $lte: thEndTime.toDate() },
})
.sort({ start_time: 1 });
this.logger.debug(`showTimes ${showTimes.length}`);
showTimes.forEach(s => this.logger.debug(`${s.start_time} -> ${s.end_time}`));
if (showTimes.length == 1) {
const found = showTimes[0];
if (startTimeLocal.isBefore(found.end_time) && endTimeLocal.isAfter(found.start_time)) {
throw new BadRequestException(`Already have 1 showtime in this time period`);
}
}
if (showTimes.length >= 2) {
const pairwises = [
null,
...showTimes,
null,
].pairwise();
this.logger.debug(pairwises.map(([p, n]) => [p?.id, n?.id]));
const pair: [ShowTime, ShowTime] | undefined = pairwises.find(([prev, next]) => {
if (prev && next) {
return startTimeLocal.isBetween(prev.end_time, next.start_time)
&& endTimeLocal.isBetween(prev.end_time, next.start_time);
}
if (prev === null) {
return startTimeLocal.isBetween(thStartTime, next.start_time)
&& endTimeLocal.isBetween(thStartTime, next.start_time);
}
return startTimeLocal.isBetween(prev.end_time, thEndTime)
&& endTimeLocal.isBetween(prev.end_time, thEndTime);
});
if (pair === undefined) {
throw new BadRequestException(`There's no more free time to create a new showtime`);
}
this.logger.debug(`Found pair ${pair[0]?.start_time}:${pair[0]?.end_time} -> ${pair[1]?.start_time}:${pair[1]?.end_time}`);
}
const doc: Omit<CreateDocumentDefinition<ShowTime>, '_id'> = {
movie: movie._id,
theatre: theatre._id,
room: '2D 1',
is_active: true,
end_time: endTimeLocal.toDate(),
start_time: startTimeLocal.toDate(),
};
const showTime = await this.showTimeModel.create(doc);
const rr = await from(seats)
.pipe(
bufferCount(32),
concatMap(seats => {
const tasks: Observable<Ticket>[] = seats.map(({ seat, dto }) => {
return defer(async () => {
const doc: Omit<CreateDocumentDefinition<Ticket>, '_id'> = {
is_active: true,
price: dto.price,
reservation: null,
seat: seat._id,
show_time: showTime._id,
};
return this.ticketModel.create(doc);
});
});
return forkJoin(tasks);
}),
tap(tickets => this.logger.debug(`Created ${tickets.length} tickets`)),
map(tickets => tickets.length),
reduce((acc, e) => acc + e, 0),
)
.toPromise();
this.logger.debug(`Total Created ${rr} tickets`)
return showTime;
}
getShowTimesByTheatreIdAdmin(theatreId: string, dto: PaginationDto): Promise<ShowTime[]> {
const { limit, skip } = getSkipLimit(dto);
return this.showTimeModel
.find({ theatre: theatreId })
.sort({ start_time: -1 })
.skip(skip)
.limit(limit)
.populate('movie')
.exec();
}
async getAvailablePeriods(theatreId: string, dayStr: string) {
const theatre = await this.theatreModel.findById(theatreId).then(v => {
if (!v) {
throw new NotFoundException(`Theatre with id ${theatreId}`);
}
return v;
});
/*const day = dayjs(dayStr).startOf('day');
this.logger.debug(day.toDate(), 'day');
const [startHString, endHString]: string[] = theatre.opening_hours.split(' - ');
const [startH, startM]: number[] = startHString.split(':').map(x => +x);
const [endH, endM]: number[] = endHString.split(':').map(x => +x);
const thStartTime: dayjs.Dayjs = day.set('hour', startH).set('minute', startM);
const thEndTime: dayjs.Dayjs = day.set('hour', endH).set('minute', endM);*/
const start_time: dayjs.Dayjs = dayjs(dayStr);
this.logger.debug(start_time.toISOString() + ' '.repeat(26) + '[2] start_time');
this.logger.debug(start_time.toDate().toString() + '[2] start_time');
const [startHString, endHString]: string[] = theatre.opening_hours.split(' - ');
const [startH, startM]: number[] = startHString.split(':').map(x => +x);
const [endH, endM]: number[] = endHString.split(':').map(x => +x);
const startTimeLocal = start_time.utcOffset(420, false);
const startOfDayLocal: dayjs.Dayjs = startTimeLocal.startOf('day');
this.logger.debug(startOfDayLocal.toISOString() + ' '.repeat(26) + '[5] startOfDayLocal');
this.logger.debug(startOfDayLocal.toDate().toString() + '[5] startOfDayLocal');
const thStartTime: dayjs.Dayjs = startOfDayLocal.set('hour', startH).set('minute', startM);
const thEndTime: dayjs.Dayjs = startOfDayLocal.set('hour', endH).set('minute', endM);
this.logger.debug(thStartTime.toISOString() + ' '.repeat(26) + '[6] thStartTime');
this.logger.debug(thStartTime.toDate().toString() + '[6] thStartTime');
this.logger.debug(thEndTime.toISOString() + ' '.repeat(26) + '[7] thEndTime');
this.logger.debug(thEndTime.toDate().toString() + '[7] thEndTime');
const showTimes = await this.showTimeModel
.find({
theatre: theatre._id,
room: '2D 1',
is_active: true,
start_time: { $gte: thStartTime.toDate() },
end_time: { $lte: thEndTime.toDate() },
})
.sort({ start_time: 1 });
this.logger.debug(showTimes.map(e => ({ start_time: e.start_time, end_time: e.end_time })));
const times: { start_time: Date | null, end_time: Date | null }[] = [
{
start_time: null as Date,
end_time: thStartTime.toDate(),
},
...showTimes,
{
start_time: thEndTime.toDate(),
end_time: null as Date,
},
];
const res = times.pairwise().map(([prev, next]) => {
if (prev.end_time === null || next.start_time === null) {
throw new InternalServerErrorException();
}
return {
start: prev.end_time,
end: next.start_time,
};
});
this.logger.debug(res);
return res;
}
async report(MMyyyy: string, theatre_id: string) {
const theatre = await this.theatreModel.findById(theatre_id);
if (!theatre) {
throw new NotFoundException();
}
const dayString = `01/${MMyyyy}`;
const start = dayjs(dayString, 'DD/MM/YYYY')
.utcOffset(420, false)
.startOf('day').startOf('month');
const end = start.endOf('day').endOf('month');
this.logger.debug('START: ' + start.toDate().toString());
this.logger.debug('END : ' + end.toDate().toString());
const showTimes = await this.showTimeModel.find({
start_time: { $gte: start.toDate() },
end_time: { $lte: end.toDate() },
theatre: theatre._id,
});
const conditions = { show_time: { $in: showTimes.map(s => s._id) } };
const [reservations, ticketsCount] = await Promise.all([
this.reservationModel.aggregate([
{
$match: conditions
},
{
$group: {
_id: null,
total_price: { $sum: '$total_price' }
},
}
]).exec(),
this.ticketModel.count(conditions).exec(),
]);
const [ticketsSoldCount, amount] = await Promise.all([
this.ticketModel.count({ ...conditions, reservation: { $ne: null } }).exec(),
this.ticketModel.aggregate([
{
$match: conditions
},
{
$group: {
_id: null,
price: { $sum: '$price' }
},
}
]).exec(),
]);
this.logger.debug(reservations);
this.logger.debug(ticketsCount);
this.logger.debug(ticketsSoldCount);
this.logger.debug(amount);
const report = {
amount_sold: reservations[0]?.total_price ?? 0,
amount: amount[0]?.price ?? 0,
tickets_sold: ticketsSoldCount ?? 0,
tickets: ticketsCount ?? 0,
};
this.logger.debug(report);
return report;
}
}
declare global {
interface Array<T> {
pairwise(): [T, T][];
}
}
Array.prototype.pairwise = function <T>(this: T[]): [T, T][] {
const result: [T, T][] = [];
if (this.length < 2) {
return [];
}
let prev: T;
let hasPrev = false;
for (const cur of this) {
if (hasPrev) {
result.push([prev, cur]);
}
hasPrev = true;
prev = cur;
}
return result;
}; | the_stack |
import { GetTermsOperation, IDocumentStore } from "../../../../src";
import { disposeTestDocumentStore, testContext } from "../../../Utils/TestUtil";
import { AbstractRawJavaScriptCountersIndexCreationTask } from "../../../../src/Documents/Indexes/Counters/AbstractRawJavaScriptCountersIndexCreationTask";
import { Address, Company, User } from "../../../Assets/Entities";
import { assertThat } from "../../../Utils/AssertExtensions";
describe("BasicCountersIndexes_JavaScript", function () {
let store: IDocumentStore;
beforeEach(async function () {
store = await testContext.getDocumentStore();
});
afterEach(async () =>
await disposeTestDocumentStore(store));
it("basicMapIndex", async () => {
{
const session = store.openSession();
const company = new Company();
await session.store(company, "companies/1");
session.countersFor(company).increment("heartRate", 7);
await session.saveChanges();
}
const timeSeriesIndex = new MyCounterIndex();
const indexDefinition = timeSeriesIndex.createIndexDefinition();
await timeSeriesIndex.execute(store);
await testContext.waitForIndexing(store);
let terms = await store.maintenance.send(new GetTermsOperation("MyCounterIndex", "heartBeat", null));
assertThat(terms)
.hasSize(1);
assertThat(terms)
.contains("7");
terms = await store.maintenance.send(new GetTermsOperation("MyCounterIndex", "user", null));
assertThat(terms)
.hasSize(1)
.contains("companies/1");
terms = await store.maintenance.send(new GetTermsOperation("MyCounterIndex", "name", null));
assertThat(terms)
.hasSize(1)
.contains("heartrate");
{
const session = store.openSession();
const company1 = await session.load("companies/1", Company);
session.countersFor(company1)
.increment("heartRate", 3);
const company2 = new Company();
await session.store(company2, "companies/2");
session.countersFor(company2)
.increment("heartRate", 4);
const company3 = new Company();
await session.store(company3, "companies/3");
session.countersFor(company3)
.increment("heartRate", 6);
const company999 = new Company();
await session.store(company999, "companies/999");
session.countersFor(company999)
.increment("heartRate_Different", 999);
await session.saveChanges();
}
await testContext.waitForIndexing(store);
terms = await store.maintenance.send(new GetTermsOperation("MyCounterIndex", "heartBeat", null));
assertThat(terms)
.hasSize(3)
.contains("10")
.contains("4")
.contains("6");
terms = await store.maintenance.send(new GetTermsOperation("MyCounterIndex", "user", null));
assertThat(terms)
.hasSize(3)
.contains("companies/1")
.contains("companies/2")
.contains("companies/3");
terms = await store.maintenance.send(new GetTermsOperation("MyCounterIndex", "name", null));
assertThat(terms)
.hasSize(1)
.contains("heartrate");
// skipped rest of the test
});
it("basicMapReduceIndexWithLoad", async function () {
{
const session = store.openSession();
for (let i = 0; i < 10; i++) {
const address = new Address();
address.city = "NY";
await session.store(address, "addresses/" + i);
const user = new User();
user.addressId = address.id;
await session.store(user, "users/" + i);
session.countersFor(user)
.increment("heartRate", 180 + i);
}
await session.saveChanges();
}
const timeSeriesIndex = new AverageHeartRate_WithLoad();
const indexName = timeSeriesIndex.getIndexName();
const indexDefinition = timeSeriesIndex.createIndexDefinition();
await timeSeriesIndex.execute(store);
await testContext.waitForIndexing(store);
let terms = await store.maintenance.send(new GetTermsOperation(indexName, "heartBeat", null));
assertThat(terms)
.hasSize(1)
.contains("184.5");
terms = await store.maintenance.send(new GetTermsOperation(indexName, "count", null));
assertThat(terms)
.hasSize(1)
.contains("10");
terms = await store.maintenance.send(new GetTermsOperation(indexName, "city", null));
assertThat(terms)
.hasSize(1)
.contains("ny");
});
it("canMapAllCountersFromCollection", async function () {
{
const session = store.openSession();
const company = new Company();
await session.store(company, "companies/1");
session.countersFor(company)
.increment("heartRate", 7);
session.countersFor(company)
.increment("likes", 3);
await session.saveChanges();
}
const timeSeriesIndex = new MyCounterIndex_AllCounters();
const indexName = timeSeriesIndex.getIndexName();
const indexDefinition = timeSeriesIndex.createIndexDefinition();
await timeSeriesIndex.execute(store);
await testContext.waitForIndexing(store);
let terms = await store.maintenance.send(new GetTermsOperation(indexName, "heartBeat", null));
assertThat(terms)
.hasSize(2)
.contains("7")
.contains("3");
terms = await store.maintenance.send(new GetTermsOperation(indexName, "user", null));
assertThat(terms)
.hasSize(1)
.contains("companies/1");
terms = await store.maintenance.send(new GetTermsOperation(indexName, "name", null));
assertThat(terms)
.hasSize(2)
.contains("heartrate")
.contains("likes");
});
it("basicMultiMapIndex", async function () {
const timeSeriesIndex = new MyMultiMapCounterIndex();
await timeSeriesIndex.execute(store);
{
const session = store.openSession();
const company = new Company();
await session.store(company);
session.countersFor(company)
.increment("heartRate", 3);
session.countersFor(company)
.increment("heartRate2", 5);
const user = new User();
await session.store(user);
session.countersFor(user)
.increment("heartRate", 2);
await session.saveChanges();
}
await testContext.waitForIndexing(store);
{
const session = store.openSession();
const results = await session.query(MyMultiMapCounterIndexResult, MyMultiMapCounterIndex)
.all();
assertThat(results)
.hasSize(3);
}
});
it("counterNamesFor", async function () {
const index = new Companies_ByCounterNames();
await index.execute(store);
{
const session = store.openSession();
const company = new Company();
await session.store(company, "companies/1");
await session.saveChanges();
}
await testContext.waitForIndexing(store);
let terms = await store.maintenance.send(new GetTermsOperation(index.getIndexName(), "name", null));
assertThat(terms)
.hasSize(0);
terms = await store.maintenance.send(new GetTermsOperation(index.getIndexName(), "names_IsArray", null));
assertThat(terms)
.hasSize(1)
.contains("true");
{
const session = store.openSession();
const company = await session.load("companies/1", Company);
session.countersFor(company)
.increment("heartRate", 3);
session.countersFor(company)
.increment("heartRate2", 7);
await session.saveChanges();
}
await testContext.waitForIndexing(store);
terms = await store.maintenance.send(new GetTermsOperation(index.getIndexName(), "names", null));
assertThat(terms)
.hasSize(2)
.contains("heartrate")
.contains("heartrate2");
terms = await store.maintenance.send(new GetTermsOperation(index.getIndexName(), "names_IsArray", null));
assertThat(terms)
.hasSize(1)
.contains("true");
});
});
class MyCounterIndex extends AbstractRawJavaScriptCountersIndexCreationTask {
public constructor() {
super();
this.maps.add(
"counters.map('Companies', 'HeartRate', function (counter) {\n" +
"return {\n" +
" heartBeat: counter.Value,\n" +
" name: counter.Name,\n" +
" user: counter.DocumentId\n" +
"};\n" +
"})"
);
}
}
// tslint:disable-next-line:class-name
class AverageHeartRate_WithLoad extends AbstractRawJavaScriptCountersIndexCreationTask {
constructor() {
super();
this.maps.add("counters.map('Users', 'heartRate', function (counter) {\n" +
"var user = load(counter.DocumentId, 'Users');\n" +
"var address = load(user.addressId, 'Addresses');\n" +
"return {\n" +
" heartBeat: counter.Value,\n" +
" count: 1,\n" +
" city: address.city\n" +
"};\n" +
"})");
this.reduce = "groupBy(r => ({ city: r.city }))\n" +
" .aggregate(g => ({\n" +
" heartBeat: g.values.reduce((total, val) => val.heartBeat + total, 0) / g.values.reduce((total, val) => val.count + total, 0),\n" +
" city: g.key.city,\n" +
" count: g.values.reduce((total, val) => val.count + total, 0)\n" +
" }))";
}
}
// tslint:disable-next-line:class-name
class AverageHeartRate_WithLoadResult {
public heartBeat: number;
public city: string;
public count: number;
}
// tslint:disable-next-line:class-name
class MyCounterIndex_AllCounters extends AbstractRawJavaScriptCountersIndexCreationTask {
public constructor() {
super();
this.maps.add("counters.map('Companies', function (counter) {\n" +
"return {\n" +
" heartBeat: counter.Value,\n" +
" name: counter.Name,\n" +
" user: counter.DocumentId\n" +
"};\n" +
"})");
}
}
class MyMultiMapCounterIndex extends AbstractRawJavaScriptCountersIndexCreationTask {
public constructor() {
super();
this.maps.add("counters.map('Companies', 'heartRate', function (counter) {\n" +
"return {\n" +
" heartBeat: counter.Value,\n" +
" name: counter.Name,\n" +
" user: counter.DocumentId\n" +
"};\n" +
"})");
this.maps.add("counters.map('Companies', 'heartRate2', function (counter) {\n" +
"return {\n" +
" heartBeat: counter.Value,\n" +
" name: counter.Name,\n" +
" user: counter.DocumentId\n" +
"};\n" +
"})");
this.maps.add("counters.map('Users', 'heartRate', function (counter) {\n" +
"return {\n" +
" heartBeat: counter.Value,\n" +
" name: counter.Name,\n" +
" user: counter.DocumentId\n" +
"};\n" +
"})");
}
}
class MyMultiMapCounterIndexResult {
public heartBeat: number;
public name: string;
public user: string;
}
// tslint:disable-next-line:class-name
class Companies_ByCounterNames extends AbstractRawJavaScriptCountersIndexCreationTask {
public constructor() {
super();
this.maps.add("map('Companies', function (company) {\n" +
"return ({\n" +
" names: counterNamesFor(company)\n" +
"})\n" +
"})");
}
} | the_stack |
import { assert } from '@canvas-ui/assert'
import { Paint, PaintStyle } from '../canvas'
import { ContainerLayer, OffsetLayer, TransformLayer } from '../compositing'
import { DebugFlags } from '../debug'
import {
HitTestRoot,
SyntheticEvent,
SyntheticEventDispatcher,
SyntheticEventListener,
SyntheticEventManager,
SyntheticEventTarget,
SyntheticPointerEvent,
SyntheticWheelEvent
} from '../events'
import { AbstractNode, Log } from '../foundation'
import { Matrix, MutableMatrix, Point, Rect, Size } from '../math'
import { EventHandlers } from './event-handlers.mixin'
import { HitTestEntry, HitTestResult } from './hit-test'
import { PaintingContext } from './painting-context'
import { RenderPipeline } from './render-pipeline'
import { StyleMap } from './style-map'
import { Yoga, YogaMeasure } from './yoga'
/**
* 储存所有由父对象管理的数据
*/
export class ParentData {
/**
* RenderObject 被从 parent 移除时调用
*/
detach() {
//
}
}
export type Visitor<T extends RenderObject> = { bivarianceHack(child: T): void }['bivarianceHack']
export interface RenderObject {
onPointerMove?: SyntheticEventListener<SyntheticPointerEvent<any>>
onPointerOver?: SyntheticEventListener<SyntheticPointerEvent<any>>
onPointerEnter?: SyntheticEventListener<SyntheticPointerEvent<any>>
onPointerDown?: SyntheticEventListener<SyntheticPointerEvent<any>>
onPointerUp?: SyntheticEventListener<SyntheticPointerEvent<any>>
onPointerOut?: SyntheticEventListener<SyntheticPointerEvent<any>>
onPointerLeave?: SyntheticEventListener<SyntheticPointerEvent<any>>
onWheel?: SyntheticEventListener<SyntheticWheelEvent<any>>
onPointerMoveCapture?: SyntheticEventListener<SyntheticPointerEvent<any>>
onPointerOverCapture?: SyntheticEventListener<SyntheticPointerEvent<any>>
onPointerEnterCapture?: SyntheticEventListener<SyntheticPointerEvent<any>>
onPointerDownCapture?: SyntheticEventListener<SyntheticPointerEvent<any>>
onPointerUpCapture?: SyntheticEventListener<SyntheticPointerEvent<any>>
onPointerOutCapture?: SyntheticEventListener<SyntheticPointerEvent<any>>
onPointerLeaveCapture?: SyntheticEventListener<SyntheticPointerEvent<any>>
onWheelCapture?: SyntheticEventListener<SyntheticWheelEvent<any>>
}
/**
* RenderObject 是场景树中所有对象的基类
*
*/
export abstract class RenderObject<ParentDataType extends ParentData = ParentData>
extends AbstractNode<RenderPipeline>
implements SyntheticEventTarget {
/**
* `RenderObject` 的 parent,如果没有 parent,则为 undefined
*/
override get parent() {
return this._parent as RenderObject | undefined
}
/**
* 唯一 id
*/
id?: string | number
/**
* 样式
*/
readonly style = new StyleMap()
protected trackStyle() {
this.style.on('width', this.handleWidthChange, this)
this.style.on('height', this.handleHeightChange, this)
this.style.on('display', this.handleDisplayChange, this)
this.style.on('visibility', this.handleVisibilityChange, this)
if (this.style.has('display')) {
this.handleDisplayChange(this.style.display)
}
if (this.style.has('visibility')) {
this.handleVisibilityChange(this.style.visibility)
}
this.style.on('left', this.handleLeftChange, this)
this.style.on('top', this.handleTopChange, this)
}
/**
* 从样式更新 bounds
*/
protected updateOffsetAndSizeFromStyle() {
const { width, height, left, top } = this.style
if (typeof width === 'number' && typeof height === 'number') {
this.size = Size.fromWH(width, height)
} else if (typeof width === 'number') {
this.size = Size.fromWH(width, this._size.height)
} else if (typeof height === 'number') {
this.size = Size.fromWH(this._size.width, height)
}
if (typeof left === 'number' && typeof top === 'number') {
this.offset = Point.fromXY(left, top)
} else if (typeof left === 'number') {
this.offset = Point.fromXY(left, this._offset.y)
} else if (typeof top === 'number') {
this.offset = Point.fromXY(this._offset.x, top)
}
}
/**
* 父节点使用的信息,比如说保存一些布局相关信息,偏移量等等
* 对于子节点来说是不透明的
*/
parentData?: ParentDataType
protected setupParentData(child: RenderObject) {
if (!(child.parentData instanceof ParentData)) {
child.parentData = new ParentData()
}
}
override adoptChild(child: RenderObject) {
this.setupParentData(child)
this.markLayoutDirty()
this.markNeedsCompositingDirty()
super.adoptChild(child)
this.allocChildYogaNode(child)
}
protected allocChildYogaNode(child: RenderObject) {
if (this._yogaNode || child.alwaysHoldYogaNode) {
if (!child.yogaNode) {
const childYogaNode = Yoga.Node.create()
child.yogaNode = childYogaNode
child.allocChildrenYogaNode()
}
}
}
protected allocChildrenYogaNode() { }
override dropChild(child: RenderObject) {
assert(child.parentData)
super.dropChild(child)
child.cleanRelayoutBoundary()
child.parentData.detach()
child.parentData = undefined
this.deallocYogaNode(child)
this.markLayoutDirty()
this.markNeedsCompositingDirty()
}
protected deallocYogaNode(child: RenderObject) {
const { yogaNode } = child
if (yogaNode) {
// 先解引用,然后释放内存
child.yogaNode = undefined
yogaNode.free()
}
child.deallocYogaNodeChildren()
}
protected deallocYogaNodeChildren() { }
abstract visitChildren(visitor: Visitor<RenderObject>): void
/**
* 我们使用 Yoga 进行 Flex 布局,yogaNode 表示 RenderObject 的**伴生 yoga 节点**
*/
get yogaNode() {
return this._yogaNode
}
set yogaNode(value) {
if (this._yogaNode) {
this.disposeYogaNode()
}
this._yogaNode = value
if (this._yogaNode) {
this.setupYogaNode()
}
}
_yogaNode?: Yoga.YogaNode
/**
* 节点是否总是持有 YogaNode
*/
get alwaysHoldYogaNode() {
return false
}
/**
* 初始化 yogaNode
*/
protected setupYogaNode() {
assert(this.yogaNode)
if (this.yogaMeasure) {
this.yogaNode.setMeasureFunc(this.yogaMeasure)
}
// 同步样式到 yogaNode
const { style } = this
if (style.has('flexBasis')) {
this.handleFlexBasisChange(style.flexBasis)
}
if (style.has('flexGrow')) {
this.handleFlexGrowChange(style.flexGrow)
}
if (style.has('flexShrink')) {
this.handleFlexShrinkChange(style.flexShrink)
}
if (style.has('width')) {
this.handleWidthChange(style.width)
}
if (style.has('height')) {
this.handleHeightChange(style.height)
}
if (style.has('minWidth')) {
this.handleMinWidthChange(style.minWidth)
}
if (style.has('minHeight')) {
this.handleMinHeightChange(style.minHeight)
}
if (style.has('maxWidth')) {
this.handleMaxWidthChange(style.maxWidth)
}
if (style.has('maxHeight')) {
this.handleMaxHeightChange(style.maxHeight)
}
if (style.has('paddingTop')) {
this.handlePaddingTopChange(style.paddingTop)
}
if (style.has('paddingRight')) {
this.handlePaddingRightChange(style.paddingRight)
}
if (style.has('paddingBottom')) {
this.handlePaddingBottomChange(style.paddingBottom)
}
if (style.has('paddingLeft')) {
this.handlePaddingLeftChange(style.paddingLeft)
}
if (style.has('marginTop')) {
this.handleMarginTopChange(style.marginTop)
}
if (style.has('marginRight')) {
this.handleMarginRightChange(style.marginRight)
}
if (style.has('marginBottom')) {
this.handleMarginBottomChange(style.marginBottom)
}
if (style.has('marginLeft')) {
this.handleMarginLeftChange(style.marginLeft)
}
if (style.has('display')) {
this.handleDisplayChange(style.display)
}
if (style.has('position')) {
this.handlePositionChange(style.position)
}
if (style.has('right')) {
this.handleRightChange(style.right)
}
if (style.has('bottom')) {
this.handleBottomChange(style.bottom)
}
// 追踪变更
style.on('flexBasis', this.handleFlexBasisChange, this)
style.on('flexGrow', this.handleFlexGrowChange, this)
style.on('flexShrink', this.handleFlexShrinkChange, this)
// width 和 height 样式在 handleWidthChange 中已经追踪,这里无需重复追踪
// style.on('width', this.handleWidthChange, this)
// style.on('height', this.handleHeightChange, this)
style.on('minWidth', this.handleMinWidthChange, this)
style.on('minHeight', this.handleMinHeightChange, this)
style.on('maxWidth', this.handleMaxWidthChange, this)
style.on('maxHeight', this.handleMaxHeightChange, this)
style.on('paddingTop', this.handlePaddingTopChange, this)
style.on('paddingLeft', this.handlePaddingLeftChange, this)
style.on('paddingRight', this.handlePaddingRightChange, this)
style.on('paddingBottom', this.handlePaddingBottomChange, this)
style.on('marginTop', this.handleMarginTopChange, this)
style.on('marginLeft', this.handleMarginLeftChange, this)
style.on('marginRight', this.handleMarginRightChange, this)
style.on('marginBottom', this.handleMarginBottomChange, this)
style.on('position', this.handlePositionChange, this)
style.on('right', this.handleRightChange, this)
style.on('bottom', this.handleBottomChange, this)
// style.on('display', this.handleDisplayChange, this)
// let childIndex = 0
// this.visitChildren(child => {
// if (child.yogaNode) {
// this.yogaNode!.insertChild(child.yogaNode, childIndex++)
// }
// })
}
protected disposeYogaNode() {
assert(this._yogaNode)
const { style } = this
style.off('flexBasis', this.handleFlexBasisChange, this)
style.off('flexGrow', this.handleFlexGrowChange, this)
style.off('flexShrink', this.handleFlexShrinkChange, this)
// style.off('width', this.handleWidthChange, this)
// style.off('height', this.handleHeightChange, this)
style.off('minWidth', this.handleMinWidthChange, this)
style.off('minHeight', this.handleMinHeightChange, this)
style.off('maxWidth', this.handleMaxWidthChange, this)
style.off('maxHeight', this.handleMaxHeightChange, this)
style.off('paddingTop', this.handlePaddingTopChange, this)
style.off('paddingLeft', this.handlePaddingLeftChange, this)
style.off('paddingRight', this.handlePaddingRightChange, this)
style.off('paddingBottom', this.handlePaddingBottomChange, this)
style.off('marginTop', this.handleMarginTopChange, this)
style.off('marginLeft', this.handleMarginLeftChange, this)
style.off('marginRight', this.handleMarginRightChange, this)
style.off('marginBottom', this.handleMarginBottomChange, this)
// style.off('display', this.handleDisplayChange, this)
if (this.yogaMeasure) {
this._yogaNode.unsetMeasureFunc()
}
}
protected handleFlexBasisChange(value: StyleMap['flexBasis'] = 'auto') {
assert(this.yogaNode)
this.yogaNode.setFlexBasis(value)
this.markLayoutDirty()
}
protected handleFlexGrowChange(value: StyleMap['flexGrow'] = 0) {
assert(this.yogaNode)
this.yogaNode.setFlexGrow(value)
this.markLayoutDirty()
}
protected handleFlexShrinkChange(value: StyleMap['flexShrink'] = 1) {
assert(this.yogaNode)
this.yogaNode.setFlexShrink(value)
this.markLayoutDirty()
}
protected handleWidthChange(value: StyleMap['width'] = 'auto') {
this.yogaNode?.setWidth(value)
this.markLayoutDirty()
}
protected handleHeightChange(value: StyleMap['height'] = 'auto') {
this.yogaNode?.setHeight(value)
this.markLayoutDirty()
}
protected handleMinWidthChange(value: StyleMap['minWidth'] = 'auto') {
assert(this.yogaNode)
this.yogaNode.setMinWidth(value === 'auto' ? NaN : value)
this.markLayoutDirty()
}
protected handleMinHeightChange(value: StyleMap['minHeight'] = 'auto') {
assert(this.yogaNode)
this.yogaNode.setMinHeight(value === 'auto' ? NaN : value)
this.markLayoutDirty()
}
protected handleMaxWidthChange(value: StyleMap['maxWidth'] = 'auto') {
assert(this.yogaNode)
this.yogaNode.setMaxWidth(value === 'auto' ? NaN : value)
this.markLayoutDirty()
}
protected handleMaxHeightChange(value: StyleMap['maxHeight'] = 'auto') {
assert(this.yogaNode)
this.yogaNode.setMaxHeight(value === 'auto' ? NaN : value)
this.markLayoutDirty()
}
protected handlePaddingTopChange(value: StyleMap['paddingTop'] = 0) {
assert(this.yogaNode)
this.yogaNode.setPadding(Yoga.EDGE_TOP, value)
this.markLayoutDirty()
}
protected handlePaddingRightChange(value: StyleMap['paddingRight'] = 0) {
assert(this.yogaNode)
this.yogaNode.setPadding(Yoga.EDGE_RIGHT, value)
this.markLayoutDirty()
}
protected handlePaddingBottomChange(value: StyleMap['paddingBottom'] = 0) {
assert(this.yogaNode)
this.yogaNode.setPadding(Yoga.EDGE_BOTTOM, value)
this.markLayoutDirty()
}
protected handlePaddingLeftChange(value: StyleMap['paddingLeft'] = 0) {
assert(this.yogaNode)
this.yogaNode.setPadding(Yoga.EDGE_LEFT, value)
this.markLayoutDirty()
}
protected handleMarginTopChange(value: StyleMap['marginTop'] = 0) {
assert(this.yogaNode)
this.yogaNode.setMargin(Yoga.EDGE_TOP, value)
this.markLayoutDirty()
}
protected handleMarginRightChange(value: StyleMap['marginRight'] = 0) {
assert(this.yogaNode)
this.yogaNode.setMargin(Yoga.EDGE_RIGHT, value)
this.markLayoutDirty()
}
protected handleMarginBottomChange(value: StyleMap['marginBottom'] = 0) {
assert(this.yogaNode)
this.yogaNode.setMargin(Yoga.EDGE_BOTTOM, value)
this.markLayoutDirty()
}
protected handleMarginLeftChange(value: StyleMap['marginLeft'] = 0) {
assert(this.yogaNode)
this.yogaNode.setMargin(Yoga.EDGE_LEFT, value)
this.markLayoutDirty()
}
protected handleDisplayChange(value: StyleMap['display']) {
this.yogaNode?.setDisplay(value === 'none' ? Yoga.DISPLAY_NONE : Yoga.DISPLAY_FLEX)
this.hidden = value === 'none' || this.style.visibility === 'hidden'
}
protected handleVisibilityChange(value: StyleMap['visibility']) {
this.hidden = this.style.display === 'none' || value === 'hidden'
}
protected handleLeftChange(value: StyleMap['left'] = 0) {
assert(typeof value === 'number', 'style.left 仅支持 number')
if (this.yogaNode) {
this.yogaNode.setPosition(Yoga.EDGE_LEFT, value)
this.markLayoutDirty()
} else {
this.offset = Point.fromXY(value, this._offset.y)
// 仅标记父节点需要重新布局
this.parent?.markLayoutDirty(this)
}
}
protected handleTopChange(value: StyleMap['top'] = 0) {
assert(typeof value === 'number', 'style.top 仅支持 number')
if (this.yogaNode) {
this.yogaNode.setPosition(Yoga.EDGE_TOP, value)
this.markLayoutDirty()
} else {
this.offset = Point.fromXY(this._offset.x, value)
// 仅标记父节点需要重新布局
this.parent?.markLayoutDirty(this)
}
}
protected handleRightChange(value: StyleMap['right'] = 0) {
assert(typeof value === 'number', 'style.left 仅支持 number')
if (this.yogaNode) {
this.yogaNode.setPosition(Yoga.EDGE_RIGHT, value)
this.markLayoutDirty()
}
}
protected handleBottomChange(value: StyleMap['bottom'] = 0) {
assert(typeof value === 'number', 'style.bottom 仅支持 number')
if (this.yogaNode) {
this.yogaNode.setPosition(Yoga.EDGE_BOTTOM, value)
this.markLayoutDirty()
}
}
protected handlePositionChange(value: StyleMap['position']) {
assert(this.yogaNode)
this.yogaNode.setPositionType(
value === 'absolute'
? Yoga.POSITION_TYPE_ABSOLUTE
: Yoga.POSITION_TYPE_RELATIVE
)
this.markLayoutDirty()
}
protected updateOffsetAndSizeFromYogaNode() {
assert(this.yogaNode)
const layout = this.yogaNode.getComputedLayout()
this.size = Size.fromWH(layout.width, layout.height)
// 如果自己是布局边界,则不更新 offset,因为 offset 受 parent (例如 View) 控制
// todo(haocong): 这会导致根节点的 margin 不起作用,需要考虑一个方法解决
if (this._relayoutBoundary !== this) {
this._offset = Point.fromXY(layout.left, layout.top)
} else {
const { left, top } = this.style
if (typeof left === 'number' && typeof top === 'number') {
this.offset = Point.fromXY(left, top)
} else if (typeof left === 'number') {
this.offset = Point.fromXY(left, this._offset.y)
} else if (typeof top === 'number') {
this.offset = Point.fromXY(this._offset.x, top)
}
}
}
override attach(owner: RenderPipeline) {
super.attach(owner)
if (this._layoutDirty && this._relayoutBoundary !== undefined) {
this._layoutDirty = false
this.markLayoutDirty()
}
if (this._needsCompositingDirty) {
this._needsCompositingDirty = false
this.markNeedsCompositingDirty()
}
if (this._paintDirty && this._layer) {
this._paintDirty = false
this.markPaintDirty()
}
// 初始化样式
this.trackStyle()
}
override detach() {
super.detach()
// 结束样式追踪
this.style.eventNames().forEach(it => {
this.style.removeListener(it)
})
}
/**
* 设置或获取节节点的大小
*
* 默认情况下 `paintBounds` 返回该值,作为参考,指示你不可以超出画面进行绘制
*
* 设置该属性不会导致重新布局,但是会导致重新绘制
*
*/
get size() {
return this._size
}
set size(value) {
this.setSize(value)
}
protected setSize(value: Size) {
if (Size.eq(value, this._size)) {
return false
}
this._size = value
this.markPaintDirty()
return true
}
/**
* @internal
*/
_size = Size.zero
/**
* 设置或获取节点相对于 parent 的偏移
*
* 设置该属性不会导致重新布局,但是会导致重新绘制
*/
get offset() {
return this._offset
}
set offset(value) {
this.setOffset(value)
}
protected setOffset(value: Point) {
if (Point.eq(this._offset, value)) {
return false
}
this._offset = value
// 修改了 offset 不会影响自身,而是影响父对象,所以我们需要标记父对象需要重绘
this.parent?.markPaintDirty()
return true
}
/**
* @internal
*/
_offset = Point.zero
/**
* 设置或获取节点的视口
*
* 视口描述了一组裁剪区域和绘制偏移
*
* 组件在实现 `paint` 时应读取该属性执行不可见区域的剔除和绘制偏移
*
* 在实现 `hitTest` 系列方法时也需要应用偏移和裁剪
*
*/
get viewport() {
return this._viewport
}
set viewport(value) {
if (Rect.eq(this._viewport, value)) {
return
}
this._viewport = value
this.markPaintDirty()
}
protected _viewport = Rect.zero
get viewportOffset() {
return Point.invert(Point.fromRect(this._viewport))
}
/**
* 标记当前节点已离屏
*/
offstage = true
/**
* 标记当前节点已隐藏
*/
get hidden() {
return this._hidden
}
set hidden(value) {
if (value === this._hidden) {
return
}
this._hidden = value
this.markLayoutDirty()
}
protected _hidden = false
/**
* 如果设置了 yogaMeasure yogaNode 为 dirty
*/
protected markYogaNodeDirty() {
// 只有设置了自定义测量方法的 Yoga 节点才可以 markDirty
if (!this.yogaMeasure) {
return
}
this.yogaNode?.markDirty()
}
protected readonly yogaMeasure?: YogaMeasure
/** friend of RenderPipeline */ _layoutDirty = true
_relayoutBoundary?: RenderObject
/**
* 标记需要重新布局
*
* @param cause 指示本次标记产生的子节点
*
*/
@Log()
markLayoutDirty(cause?: RenderObject) {
assert(!cause || cause._parent === this)
if (this._relayoutBoundary !== this) {
this.markSelfAndParentLayoutDirty()
} else {
if (!this._layoutDirty) {
this._layoutDirty = true
// 如果使用了自定义测量方法,则需额外标记 Yoga 节点
this.markYogaNodeDirty()
if (this._owner) {
this._owner.addLayoutDirty(this)
this._owner.requestVisualUpdate()
}
}
}
}
/**
* 寻找布局边界并标记为 dirty
*/
protected markSelfAndParentLayoutDirty() {
this._layoutDirty = true
this.markYogaNodeDirty()
this.parent?.markLayoutDirty(this)
}
/**
* 调度首次布局
*/
scheduleInitialLayout() {
assert(this._owner)
assert(!(this._parent instanceof RenderObject))
assert(!this._relayoutBoundary)
this._relayoutBoundary = this
this._owner.addLayoutDirty(this)
}
layoutAsChild(parentUsesSize: boolean, force: boolean) {
if (this._hidden) {
this._layoutDirty = false
return
}
if (this._layoutDirty || force) {
let relayoutBoundary: RenderObject | undefined
if (!this.parent || !parentUsesSize) {
relayoutBoundary = this
} else {
relayoutBoundary = this.parent._relayoutBoundary
}
if (this._relayoutBoundary !== undefined && this._relayoutBoundary !== relayoutBoundary) {
this.visitChildren(RenderObject.cleanChildRelayoutBoundary)
}
this._relayoutBoundary = relayoutBoundary
try {
this.performLayout()
} catch (err) {
console.error(err)
}
this._layoutDirty = false
this.markPaintDirty()
}
}
private cleanRelayoutBoundary() {
if (this._relayoutBoundary !== this) {
this._relayoutBoundary = undefined
this._layoutDirty = true
this.visitChildren(RenderObject.cleanChildRelayoutBoundary)
}
}
layoutAsBoundary() {
if (this._hidden) {
this._layoutDirty = false
this.markPaintDirty()
return
}
assert(this._layoutDirty)
assert(this._relayoutBoundary === this, '节点的 _relayoutBoundary 不是自己')
try {
this.performLayout()
} catch (err) {
console.error(err)
}
this._layoutDirty = false
this.markPaintDirty()
}
private static cleanChildRelayoutBoundary(child: RenderObject) {
child.cleanRelayoutBoundary()
}
/**
* 子类实现的布局逻辑
*/
performLayout() {
this.updateOffsetAndSize()
}
/**
* 更新 offset 和 size
*/
protected updateOffsetAndSize() {
if (this.yogaNode) {
this.updateOffsetAndSizeFromYogaNode()
} else {
this.updateOffsetAndSizeFromStyle()
}
}
/**
* 当前对象是否是重绘边界
*/
get repaintBoundary() {
return this._repaintBoundary
}
set repaintBoundary(value) {
assert(this._repaintBoundaryLocked === false, '节点的 repaintBoundary 已锁定,不能修改')
if (value === this._repaintBoundary) {
return
}
this._repaintBoundary = value
this.markNeedsCompositingDirty()
// 自己和 parent 都需要重新绘制
this._paintDirty = true
this.parent?.markPaintDirty()
}
protected _repaintBoundary = false
protected _repaintBoundaryLocked = false
/**
* 指示是否总是需要合成
*/
get alwaysNeedsCompositing() {
return false
}
protected get layer() {
assert(
!this.repaintBoundary || (!this._layer || this._layer instanceof OffsetLayer),
'如果 RenderObject 不是 repaintBoundary,_layer 只能是 OffsetLayer 或 undefined',
)
return this._layer
}
protected set layer(value: ContainerLayer | undefined) {
assert(!this.repaintBoundary, '如果 RenderObject 不是 repaintBoundary,则 RenderPipeline 会自动创建 layer,你不能手动设置')
this._layer = value
}
_layer?: ContainerLayer
_needsCompositingDirty = false
markNeedsCompositingDirty() {
if (this._needsCompositingDirty) {
return
}
this._needsCompositingDirty = true
if (this._parent instanceof RenderObject) {
const parent = this._parent
if (parent._needsCompositingDirty) {
return
}
if (!this.repaintBoundary && !parent.repaintBoundary) {
parent.markNeedsCompositingDirty()
return
}
}
this._owner?.addNeedsCompositingDirty(this)
}
protected _needsCompositing = this.repaintBoundary || this.alwaysNeedsCompositing
/**
* 当前及子节点是否需要合成
*/
get needsCompositing() {
assert(!this._needsCompositingDirty, '不能在 _needsCompositingDirty=true 时访问 needsCompositing')
return this._needsCompositing
}
updateNeedsCompositing() {
if (!this._needsCompositingDirty) {
return
}
const prevNeedsCompositing = this._needsCompositing
this._needsCompositing = false
this.visitChildren(child => {
child.updateNeedsCompositing()
if (child.needsCompositing)
this._needsCompositing = true
})
if (this.repaintBoundary || this.alwaysNeedsCompositing) {
this._needsCompositing = true
}
if (prevNeedsCompositing !== this._needsCompositing) {
this.markPaintDirty()
}
this._needsCompositingDirty = false
}
_paintDirty = true
/**
* 标记节点需要重新绘制
*
* @param cause 指示本次标记产生的子节点
*/
markPaintDirty(cause?: RenderObject) {
assert(!cause || cause._parent === this)
if (this._paintDirty) {
return
}
// 先标记自己
this._paintDirty = true
if (this.repaintBoundary) {
// 当前是 RepaintBoundary,我们可以重绘自己
assert(this._layer instanceof TransformLayer, '当前节点是 repaintBoundary,但 _layer 不是 ')
if (this._owner) {
this._owner.addPaintDirty(this)
this._owner.requestVisualUpdate()
}
} else if (this._parent instanceof RenderObject) {
// 逐级寻找 parent,到 repaintBoundary 为止
this._parent.markPaintDirty(this)
} else {
// 根节点,例如 RenderCanvas,此时已经被加入 Pipeline.paintDirtyObjects
// 我们只需要 requestVisualUpdate 即可
this.owner?.requestVisualUpdate()
}
}
/**
* RenderPipeline.flushPaint 重绘 RenderObject,但所在图层还没有 attached
*
* 为了保证子树在图层被 attached 时最终可以得到重绘,我们标记所有祖先 paintDirty
*/
skipPaint() {
assert(this.attached)
assert(this.repaintBoundary)
assert(this._paintDirty)
assert(this._layer)
assert(!this._layer.attached)
let node = this._parent
while (node instanceof RenderObject) {
if (node.repaintBoundary) {
if (!node._layer)
break // 子树从未被渲染(图层也没有创建过):交给该节点自行处理后续绘制
if (node._layer.attached)
break // 该节点主动 detach 了当前图层:交给该节点自行处理后续绘制
node._paintDirty = true
}
node = node.parent
}
}
scheduleInitialPaint(rootLayer: ContainerLayer) {
assert(rootLayer.attached)
assert(!this.parent, '仅限根节点使用')
assert(this.repaintBoundary)
assert(!this._layer)
this._layer = rootLayer
assert(this._paintDirty)
assert(this._owner)
this._owner.addPaintDirty(this)
}
replaceRootLayer(rootLayer: TransformLayer) {
assert(rootLayer.attached)
assert(this._owner)
assert(!this.parent, '仅限根节点使用')
assert(this.repaintBoundary)
assert(this._layer, '首次绘制请使用 scheduleInitialPaint')
this._layer.detach()
this._layer = rootLayer
this.markPaintDirty()
}
/**
* 绘制边界,指示了当前节点的绘制区域
*
* 你可以绘制超出该区域
*
*/
get paintBounds() {
return Rect.fromSize(this._size)
}
/**
* 对象的边界,用于离屏检测
*/
get bounds() {
return Rect.fromLTWH(this._offset.x, this._offset.y, this._size.width, this._size.height)
}
_debugDoingThisPaint = false
static _debugActivePaint?: RenderObject
/* friend of RenderPipeline */paintWithContext(context: PaintingContext, offset: Point) {
assert(!this._debugDoingThisPaint, '节点不能单独重复调用 _paintWithContext')
if (this._layoutDirty) {
return
}
assert(() => {
if (this._needsCompositingDirty) {
if (this.parent) {
let visitedByParent = false
this.parent.visitChildren(child => {
if (child === this) {
visitedByParent = true
}
})
if (!visitedByParent) {
throw new Error(`节点未通过其父节点进行绘制`)
}
}
throw new Error(`不允许节点在 _needsCompositingDirty = true 时绘制`)
}
})
let debugLastActivePaint: RenderObject | undefined
assert(() => {
this._debugDoingThisPaint = true
debugLastActivePaint = RenderObject._debugActivePaint
RenderObject._debugActivePaint = this
assert(!this.repaintBoundary || this._layer !== null)
})
this._paintDirty = false
if (!this._hidden) {
try {
this.paint(context, offset)
assert(!this._layoutDirty, '检测到 paint 方法中重新将 _layoutDirty 标记为 true')
assert(!this._paintDirty, '检测到 paint 方法中重新将 _paintDirty 标记为 true')
} catch (err) {
console.error(err)
}
}
assert(() => {
this.debugPaint(context, offset)
RenderObject._debugActivePaint = debugLastActivePaint
this._debugDoingThisPaint = false
})
}
abstract paint(context: PaintingContext, offset: Point): void
debugPaint(context: PaintingContext, offset: Point) {
this.debugPaintSize(context, offset)
this.debugPaintId(context, offset)
}
protected debugPaintSize(context: PaintingContext, offset: Point) {
if (!DebugFlags.paintNodeBounds) {
return
}
const paint: Paint = {
style: PaintStyle.stroke,
strokeWidth: 1,
color: '#00FFFF',
}
context.canvas.drawRect(
offset.x + this.viewportOffset.x,
offset.y + this.viewportOffset.y,
this.size.width,
this.size.height,
paint,
)
}
protected debugPaintId(context: PaintingContext, offset: Point) {
if (!DebugFlags.paintNodeId) {
return
}
if (!this.id) {
return
}
context.canvas.debugDrawText(
String(this.id),
offset.x,
offset.y,
)
}
applyPaintTransform(child: RenderObject, transform: MutableMatrix) {
const { viewportOffset: childViewportOffset } = child
transform.translate(
child._offset.x + childViewportOffset.x,
child._offset.y + childViewportOffset.y,
)
}
localToGlobal(point: Point, ancestor?: RenderObject): Point {
const transform = this.getTransformTo(ancestor)
return Matrix.transformPoint(transform, point)
}
globalToLocal(point: Point, ancestor?: RenderObject): Point {
const transform = this.getTransformTo(ancestor)
return Matrix.inverseTransformPoint(transform, point)
}
@Log({ disabled: false })
getBoundingClientRect(ancestor?: RenderObject) {
const transform = this.getTransformTo(ancestor)
return Matrix.transformRect(transform, Rect.fromSize(this._size))
}
getTransformTo(ancestor?: RenderObject): Matrix {
assert(this._owner, '节点缺少 owner')
const stop = ancestor ?? this._owner.rootNode
const nodes: RenderObject[] = []
for (let node: RenderObject = this; node !== stop; node = node.parent as RenderObject) {
assert(node)
nodes.push(node)
}
if (ancestor) {
nodes.push(ancestor)
}
const transform = MutableMatrix.fromIdentity()
for (let index = nodes.length - 1; index > 0; index -= 1) {
nodes[index].applyPaintTransform(nodes[index - 1], transform)
}
return transform
}
protected get dispatcher(): SyntheticEventDispatcher {
return this._dispatcher ??= new SyntheticEventDispatcher()
}
protected _dispatcher?: SyntheticEventDispatcher
addEventListener(type: string, listener: SyntheticEventListener, options?: boolean | AddEventListenerOptions): void {
return this.dispatcher.addEventListener(type, listener, options)
}
dispatchEvent(event: SyntheticEvent<SyntheticEventTarget, Event>): boolean {
const rootNode = this._owner?.rootNode as unknown as HitTestRoot
if (rootNode) {
event.target = this
event.path = [this]
SyntheticEventManager.findInstance(rootNode)?.dispatchEvent(event)
}
return false
}
removeEventListener(type: string, listener: SyntheticEventListener, options?: boolean | EventListenerOptions): void {
return this._dispatcher?.removeEventListener(type, listener, options)
}
getDispatcher() {
return this._dispatcher
}
hitTestDisabled = false
hitTestSelfDisabled = false
hitTest(result: HitTestResult, position: Point): boolean {
if (this.offstage || this._hidden || this.hitTestDisabled) {
return false
}
if (
!this.hitTestSelfDisabled && (
!(Size.eq(this._size, Size.zero)
|| Size.contains(this._size, position)))
) {
return false
}
if (
this.hitTestChildren(result, position)
|| this.hitTestSelf(position)) {
result.add(new HitTestEntry(this, position))
return true
}
return false
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
protected hitTestSelf(_position: Point): boolean {
return !this.hitTestSelfDisabled
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
protected hitTestChildren(_result: HitTestResult, _position: Point): boolean {
return false
}
}
EventHandlers.mixin(RenderObject) | the_stack |
import { Component, ElementRef, Injector, OnDestroy, OnInit } from '@angular/core';
import { AbstractComponent } from '@common/component/abstract.component';
import { SourceType, Status } from '@domain/datasource/datasource';
import {PageResult} from '@domain/common/page';
import * as _ from 'lodash';
import { WorkspaceService } from '../../../../../../../workspace/service/workspace.service';
@Component({
selector: 'resources-viewer',
templateUrl: './resources-view.component.html',
styles : [
'table tbody tr:hover td { background-color : initial }',
'table tbody tr:nth-child(odd):hover td { background-color : #fafafa }'
]
})
export class ResourcesViewComponent extends AbstractComponent implements OnInit, OnDestroy{
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// workspace id
private _workspaceId: string;
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// resource mode
public mode: string;
// resource data list
public dataList: any;
// show flag
public isShowFl: boolean = false;
// 정렬
public selectedContentSort: Order = new Order();
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Constructor
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// 생성자
constructor(private workspaceService: WorkspaceService,
protected element: ElementRef,
protected injector: Injector) {
super(element, injector);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Override Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// Init
public ngOnInit() {
// Init
super.ngOnInit();
}
// Destory
public ngOnDestroy() {
// Destory
super.ngOnDestroy();
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* init
* @param {string} mode
* @param {string} workspaceId
* @param dataList
* @param {PageResult} pageResult
*/
public init(mode: string, workspaceId: string, dataList: any, pageResult: PageResult): void {
// ui init
this._initView();
// mode
this.mode = mode;
// data
this.dataList = _.cloneDeep(dataList);
// list count
this.pageResult = pageResult;
// workspace id
this._workspaceId = workspaceId;
// flag
this.isShowFl = true;
this.addBodyScrollHidden();
}
/**
* close popup
*/
public close() {
this.removeBodyScrollHidden();
this.isShowFl = false;
} // function - close
/**
* 정렬 버튼 클릭
* @param {string} key
*/
public onClickSort(key: string): void {
// 정렬 정보 저장
this.selectedContentSort.key = key;
// 정렬 key와 일치하면
if (this.selectedContentSort.key === key) {
// asc, desc
switch (this.selectedContentSort.sort) {
case 'asc':
this.selectedContentSort.sort = 'desc';
break;
case 'desc':
this.selectedContentSort.sort = 'asc';
break;
case 'default':
this.selectedContentSort.sort = 'desc';
break;
}
}
// 페이지 초기화
this.pageResult.number = 0;
// 리스트 조회
this._getDataList();
}
/**
* 더보기 버튼 클릭
*/
public onClickMoreList(): void {
// page 증가
this.pageResult.number++;
// 리스트 조회
this._getDataList();
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method - getter
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* 오픈데이터 라벨
* @returns {string}
*/
public getOpenLabel(): string {
return this.mode === 'connection' ? this.translateService.instant('msg.spaces.shared.detail.connection.open'): this.translateService.instant('msg.comm.ui.list.ds.opendata');
}
/**
* 타이틀 이름
* @returns {string}
*/
public getTitleName(): string {
if (this.isDatasourceMode()) {
return this.translateService.instant('msg.spaces.shared.detail.datasource');
} else if (this.isDataconnectionMode()) {
return this.translateService.instant('msg.spaces.shared.detail.dataconnection');
} else {
return this.translateService.instant('msg.spaces.shared.detail.nbook.connector');
}
}
/**
* 데이터소스 IngestedType | 데이터커넥션 DbType | 노트북 Type
* @returns {string}
*/
public getTableNameIngestionTypeOrDbTypeOrType(): string {
if (this.isDatasourceMode()) {
return this.translateService.instant('msg.spaces.shared.detail.statistics.ingested.type');
} else if (this.isDataconnectionMode()) {
return this.translateService.instant('msg.spaces.shared.detail.statistics.dbtype');
} else {
return this.translateService.instant('msg.spaces.shared.detail.statistics.type');
}
}
/**
* 데이터소스 IngestedType | 데이터커넥션 Implementor | 노트북 Type
* @param data
* @returns {string}
*/
public getIngestedTypeOrImplementorOrType(data: any): string {
// 데이터소스 인경우 ingested type
if (this.isDatasourceMode()) {
return this.getConnectionTypeString(data.connType);
// 데이터 커넥션 인경우 db type
} else if (this.isDataconnectionMode()) {
return data.implementor;
} else {
return data.type;
}
}
/**
* 테이블이름 데이터소스 Data type | 데이터커넥션 Host | 노트북 Host
* @returns {string}
*/
public getTableNameDataTypeOrHost(): string {
// mode가 데이터소스라면 data type
if (this.isDatasourceMode()) {
return this.translateService.instant('msg.spaces.shared.detail.statistics.data.type');
} else {
return this.translateService.instant('msg.spaces.shared.detail.statistics.host');
}
}
/**
* 데이터소스 srcType | 데이터커넥션 hostname | 노트북 hostname
* @param data
* @returns {string}
*/
public getImplementorOrHostname(data: any): string {
// mode가 데이터소스라면 implementor
if (this.isDatasourceMode()) {
return this.getDataTypeString(data.srcType);
} else {
return data.hostname;
}
}
/**
* 테이블이름 데이터소스 status | 데이터커넥션 port | 노트북 port
* @returns {string}
*/
public getTableNameStatusOrPort(): string {
// mode가 데이터소스라면 status
if (this.isDatasourceMode()) {
return this.translateService.instant('msg.spaces.shared.detail.statistics.status');
} else {
return this.translateService.instant('msg.spaces.shared.detail.statistics.port');
}
}
/**
* 데이터소스 status | 데이터커넥션 port | 노트북 port
* @param data
* @returns {string}
*/
public getStatusOrPort(data:any): string {
// mode가 데이터소스라면 status
if (this.isDatasourceMode()) {
return this.getSourceStatusString(data.status);
} else {
return data.port;
}
}
/**
* 데이터소스 커넥션 타입
* @param {string} connType
* @returns {string}
*/
public getConnectionTypeString(connType: string): string {
return connType === 'ENGINE' ? this.translateService.instant('msg.comm.ui.list.ds.type.engine'): this.translateService.instant('msg.comm.ui.list.ds.type.link');
}
/**
* 데이터소스 데이터 타입
* @param {SourceType} srcType
* @returns {string}
*/
public getDataTypeString(srcType: SourceType): string {
switch (srcType) {
case SourceType.IMPORT:
return this.translateService.instant('msg.storage.li.druid');
case SourceType.FILE:
return this.translateService.instant('msg.storage.li.file');
case SourceType.JDBC:
return this.translateService.instant('msg.storage.li.db');
case SourceType.HIVE:
return this.translateService.instant('msg.storage.li.hive');
case SourceType.REALTIME:
return this.translateService.instant('msg.storage.li.stream');
}
}
/**
* 데이터소스 status
* @param {Status} status
* @returns {string}
*/
public getSourceStatusString(status: Status): string {
switch (status) {
case Status.ENABLED:
return 'Enabled';
case Status.PREPARING:
return 'Preparing';
case Status.DISABLED:
return 'Disabled';
case Status.FAILED:
return 'Failed';
default:
return 'Disabled';
}
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method - validation
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* 현재 리소스가 데이터소스 인지
* @returns {boolean}
*/
public isDatasourceMode(): boolean {
return this.mode === 'datasource';
}
/**
* 현재 리소스가 데이터커넥션 인지
* @returns {boolean}
*/
public isDataconnectionMode(): boolean {
return this.mode === 'connection';
}
/**
* 현재 리소스가 노트북 인지
* @returns {boolean}
*/
public isNotebookMode(): boolean {
return this.mode === 'notebook';
}
/**
* 더 조회할 컨텐츠가 있는지
* @returns {boolean}
*/
public isMoreContents(): boolean {
return (this.pageResult.number < this.pageResult.totalPages -1);
}
/**
* 브라우저 언어가 영어인지
* @returns {boolean}
*/
public isBrowserLangEng(): boolean {
return this.translateService.getBrowserLang() === 'en';
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* ui init
* @private
*/
private _initView(): void {
// sort
this.selectedContentSort = new Order();
// dataList
this.dataList = [];
// page result init
this.pageResult.number = 0;
}
/**
* 데이터소스 리스트 조회
* @param {string} workspaceId
* @private
*/
private _getDatasourceList(workspaceId: string): void {
// 로딩 show
this.loadingShow();
// 데이터소스 조회
this.workspaceService.getDataSources(workspaceId, this._getListParams(), 'default')
.then((result) => {
// 리스트 초기화
if (this.pageResult.number === 0) {
this.dataList = [];
}
// page result
this.pageResult = result['page'];
// 리스트
this.dataList = result['_embedded'] ? this.dataList.concat(result['_embedded'].datasources) : [];
// 로딩 hide
this.loadingHide();
})
.catch(() => {
// 로딩 hide
this.loadingHide();
})
}
/**
* 데이터 커넥션 리스트 조회
* @param {string} workspaceId
* @private
*/
private _getDataConnectionList(workspaceId: string): void {
// 로딩 show
this.loadingShow();
// 커넥션 조회
this.workspaceService.getDataConnectionList(workspaceId, this._getListParams(), 'default')
.then((result) => {
// 리스트 초기화
if (this.pageResult.number === 0) {
this.dataList = [];
}
// page result
this.pageResult = result['page'];
// 리스트
this.dataList = result['_embedded'] ? this.dataList.concat(result['_embedded'].connections) : [];
// 로딩 hide
this.loadingHide();
})
.catch(() => {
// 로딩 hide
this.loadingHide();
})
}
/**
* 노트북 커넥터 리스트 조회
* @param {string} workspaceId
* @private
*/
private _getNotebookConnectorList(workspaceId: string): void {
// 로딩 show
this.loadingShow();
// 커넥션 조회
this.workspaceService.getNoteBookConnectorList(workspaceId, this._getListParams(), 'default')
.then((result) => {
// 리스트 초기화
if (this.pageResult.number === 0) {
this.dataList = [];
}
// page result
this.pageResult = result['page'];
// 리스트
this.dataList = result['_embedded'] ? this.dataList.concat(result['_embedded'].connectors) : [];
// 로딩 hide
this.loadingHide();
})
.catch(() => {
// 로딩 hide
this.loadingHide();
})
}
/**
* 리스트 조회시 파라메터
* @returns {Object}
* @private
*/
private _getListParams(): object {
return {
sort: this.selectedContentSort.key + ',' + this.selectedContentSort.sort,
page: this.pageResult.number,
size: 30
};
}
/**
* 리스트 조회
* @private
*/
private _getDataList(): void {
// 리스트 재조회
switch (this.mode) {
case 'datasource':
this._getDatasourceList(this._workspaceId);
break;
case 'connection':
this._getDataConnectionList(this._workspaceId);
break;
case 'connector':
this._getNotebookConnectorList(this._workspaceId);
break;
}
}
}
class Order {
key: string = 'name';
sort: string = 'asc';
} | the_stack |
import { store, resetApp } from "../../../../appStore"
import { IKeyState } from "../key.interface";
import { populateKeyStore3, mockKeyState, keyObjectBuilder } from "./key.methods.helpers";
import { paneType } from "../../../../utilities/interfaces";
import { pushKey, popToFront, popScreen, moveToFront, changeScreen } from "../key.actions";
describe('keyStore tests', () => {
beforeEach(() => {
store.dispatch(resetApp())
});
describe('onePane', () => {
it('PUSH_KEY', () => {
// Arrange
const expectedState = mockKeyState(paneType.ONE, false, `${paneType.ONE}_`);
// Act
store.dispatch(pushKey(paneType.ONE, `first`, false));
store.dispatch(pushKey(paneType.ONE, `second`, false));
store.dispatch(pushKey(paneType.ONE, `third`, false));
const data = store.getState().KeyReducers;
// Assert
expect(data).toStrictEqual(expectedState)
})
it('PUSH_KEY_EXPECT_DUPLICATION', () => {
// Arrange
const original = mockKeyState(paneType.ONE, false, `${paneType.ONE}_`);
const duplicate = mockKeyState(paneType.ONE, false, `${paneType.ONE}_`);
const expectedState: IKeyState = {
keys: [...original.keys, ...duplicate.keys]
}
// Act
store.dispatch(pushKey(paneType.ONE, `first`, false));
store.dispatch(pushKey(paneType.ONE, `second`, false));
store.dispatch(pushKey(paneType.ONE, `third`, false));
store.dispatch(pushKey(paneType.ONE, `first`, false));
store.dispatch(pushKey(paneType.ONE, `second`, false));
store.dispatch(pushKey(paneType.ONE, `third`, false));
const data = store.getState().KeyReducers;
// Assert
expect(data).toEqual(expectedState)
})
it('POP_TO_FRONT_KEY', () => {
// Arrange
const expectedState: IKeyState =
{
keys: [keyObjectBuilder(`${paneType.ONE}_first`, false, paneType.ONE)]
}
populateKeyStore3(paneType.ONE, false);
// Act
store.dispatch(popToFront(paneType.ONE))
const data = store.getState().KeyReducers;
// Assert
expect(data).toStrictEqual(expectedState)
})
it('POP_TO_FRONT_KEY twoPane untouched', () => {
// Arrange
const expectedONEState: IKeyState =
{
keys: [keyObjectBuilder(`${paneType.ONE}_first`, false, paneType.ONE)]
}
const expectedTWOState: IKeyState = mockKeyState(paneType.TWO, false, `${paneType.TWO}_`)
populateKeyStore3(paneType.ONE, false);
populateKeyStore3(paneType.TWO, false);
// Act
store.dispatch(popToFront(paneType.ONE))
const data = store.getState().KeyReducers;
const onePaneState = data.keys.filter(x => x.screen === paneType.ONE);
const twoPaneState = data.keys.filter(x => x.screen === paneType.TWO);
// Assert
expect(onePaneState).toStrictEqual(expectedONEState.keys)
expect(twoPaneState).toStrictEqual(expectedTWOState.keys)
})
it('POP_KEY', () => {
// Arrange
const expectedONEState: IKeyState =
{
keys: [keyObjectBuilder(`${paneType.ONE}_first`, false, paneType.ONE),
keyObjectBuilder(`${paneType.ONE}_second`, false, paneType.ONE)]
}
populateKeyStore3(paneType.ONE, false);
// Act
store.dispatch(popScreen(paneType.ONE))
const data = store.getState().KeyReducers;
// Assert
expect(data).toStrictEqual(expectedONEState)
})
it('POP_KEY Multiple', () => {
// Arrange
const expectedONEState: IKeyState =
{
keys: [keyObjectBuilder(`${paneType.ONE}_first`, false, paneType.ONE)]
}
populateKeyStore3(paneType.ONE, false);
populateKeyStore3(paneType.ONE, false);
// Act
store.dispatch(popScreen(paneType.ONE))
store.dispatch(popScreen(paneType.ONE))
store.dispatch(popScreen(paneType.ONE))
store.dispatch(popScreen(paneType.ONE))
store.dispatch(popScreen(paneType.ONE))
const data = store.getState().KeyReducers;
// Assert
expect(data).toStrictEqual(expectedONEState)
})
it('POP_KEY twoPane untouched', () => {
// Arrange
const expectedONEState: IKeyState =
{
keys: [keyObjectBuilder(`${paneType.ONE}_first`, false, paneType.ONE),
keyObjectBuilder(`${paneType.ONE}_second`, false, paneType.ONE)]
}
const expectedTWOState: IKeyState = mockKeyState(paneType.TWO, false, `${paneType.TWO}_`);
populateKeyStore3(paneType.ONE, false);
populateKeyStore3(paneType.TWO, false);
// Act
store.dispatch(popScreen(paneType.ONE))
const data = store.getState().KeyReducers;
const onePaneState = data.keys.filter(x => x.screen === paneType.ONE);
const twoPaneState = data.keys.filter(x => x.screen === paneType.TWO);
// Assert
expect(onePaneState).toStrictEqual(expectedONEState.keys)
expect(twoPaneState).toStrictEqual(expectedTWOState.keys)
})
it('MOVE_TO_FRONT_KEY', () => {
// Arrange
const expectedONEState: IKeyState =
{
keys: [keyObjectBuilder(`${paneType.ONE}_second`, false, paneType.ONE),
keyObjectBuilder(`${paneType.ONE}_third`, false, paneType.ONE),
keyObjectBuilder(`${paneType.ONE}_first`, false, paneType.ONE)]
}
// Act
populateKeyStore3(paneType.ONE, false);
store.dispatch(moveToFront(paneType.ONE, `${paneType.ONE}_first`));
const data = store.getState().KeyReducers;
// Assert
expect(data).toStrictEqual(expectedONEState)
})
it('MOVE_TO_FRONT_KEY twoPane untouched', () => {
// Arrange
const expectedONEState: IKeyState =
{
keys: [keyObjectBuilder(`${paneType.ONE}_second`, false, paneType.ONE),
keyObjectBuilder(`${paneType.ONE}_third`, false, paneType.ONE),
keyObjectBuilder(`${paneType.ONE}_first`, false, paneType.ONE)]
}
const expectedTWOState: IKeyState = mockKeyState(paneType.TWO, false, `${paneType.TWO}_`);
populateKeyStore3(paneType.ONE, false);
populateKeyStore3(paneType.TWO, false);
// Act
store.dispatch(moveToFront(paneType.ONE, `${paneType.ONE}_first`));
const data = store.getState().KeyReducers;
const onePaneState = data.keys.filter(x => x.screen === paneType.ONE);
const twoPaneState = data.keys.filter(x => x.screen === paneType.TWO);
// Assert
expect(onePaneState).toStrictEqual(expectedONEState.keys)
expect(twoPaneState).toStrictEqual(expectedTWOState.keys)
})
it('CHANGE_SCREEN_KEY', () => {
// Arrange
const expectedONEState: IKeyState =
{
keys: [keyObjectBuilder(`${paneType.ONE}_first`, false, paneType.ONE),
keyObjectBuilder(`${paneType.ONE}_second`, false, paneType.TWO),
keyObjectBuilder(`${paneType.ONE}_third`, false, paneType.ONE)]
}
// Act
populateKeyStore3(paneType.ONE, false);
store.dispatch(changeScreen(paneType.TWO, `${paneType.ONE}_second`));
const data = store.getState().KeyReducers;
// Assert
expect(data).toStrictEqual(expectedONEState)
})
});
describe('twoPane', () => {
it('PUSH_KEY', () => {
// Arrange
const expectedState = mockKeyState(paneType.TWO, false, `${paneType.TWO}_`);
// Act
store.dispatch(pushKey(paneType.TWO, `first`, false));
store.dispatch(pushKey(paneType.TWO, `second`, false));
store.dispatch(pushKey(paneType.TWO, `third`, false));
const data = store.getState().KeyReducers;
// Assert
expect(data).toStrictEqual(expectedState)
})
it('PUSH_KEY_EXPECT_DUPLICATION', () => {
// Arrange
const original = mockKeyState(paneType.TWO, false, `${paneType.TWO}_`);
const duplicate = mockKeyState(paneType.TWO, false, `${paneType.TWO}_`);
const expectedState: IKeyState = {
keys: [...original.keys, ...duplicate.keys]
}
// Act
store.dispatch(pushKey(paneType.TWO, `first`, false));
store.dispatch(pushKey(paneType.TWO, `second`, false));
store.dispatch(pushKey(paneType.TWO, `third`, false));
store.dispatch(pushKey(paneType.TWO, `first`, false));
store.dispatch(pushKey(paneType.TWO, `second`, false));
store.dispatch(pushKey(paneType.TWO, `third`, false));
const data = store.getState().KeyReducers;
// Assert
expect(data).toStrictEqual(expectedState)
})
it('POP_TO_FRONT_KEY', () => {
// Arrange
const expectedState: IKeyState =
{
keys: [keyObjectBuilder(`${paneType.TWO}_first`, false, paneType.TWO)]
}
populateKeyStore3(paneType.TWO, false);
// Act
store.dispatch(popToFront(paneType.TWO))
const data = store.getState().KeyReducers;
// Assert
expect(data).toStrictEqual(expectedState)
})
it('POP_TO_FRONT_KEY onePane untouched', () => {
// Arrange
const expectedONEState: IKeyState = mockKeyState(paneType.ONE, false, `${paneType.ONE}_`)
const expectedTWOState: IKeyState = {
keys: [keyObjectBuilder(`${paneType.TWO}_first`, false, paneType.TWO)]
}
populateKeyStore3(paneType.ONE, false);
populateKeyStore3(paneType.TWO, false);
// Act
store.dispatch(popToFront(paneType.TWO))
const data = store.getState().KeyReducers;
const onePaneState = data.keys.filter(x => x.screen === paneType.ONE);
const twoPaneState = data.keys.filter(x => x.screen === paneType.TWO);
// Assert
expect(onePaneState).toStrictEqual(expectedONEState.keys)
expect(twoPaneState).toStrictEqual(expectedTWOState.keys)
})
it('POP_KEY', () => {
// Arrange
const expectedTWOState: IKeyState =
{
keys: [keyObjectBuilder(`${paneType.TWO}_first`, false, paneType.TWO),
keyObjectBuilder(`${paneType.TWO}_second`, false, paneType.TWO)]
}
populateKeyStore3(paneType.TWO, false);
// Act
store.dispatch(popScreen(paneType.TWO))
const data = store.getState().KeyReducers;
// Assert
expect(data).toStrictEqual(expectedTWOState)
})
it('POP_KEY Multiple', () => {
// Arrange
const expectedTWOState: IKeyState =
{
keys: [keyObjectBuilder(`${paneType.TWO}_first`, false, paneType.TWO)]
}
populateKeyStore3(paneType.TWO, false);
populateKeyStore3(paneType.TWO, false);
// Act
store.dispatch(popScreen(paneType.TWO))
store.dispatch(popScreen(paneType.TWO))
store.dispatch(popScreen(paneType.TWO))
store.dispatch(popScreen(paneType.TWO))
store.dispatch(popScreen(paneType.TWO))
const data = store.getState().KeyReducers;
// Assert
expect(data).toStrictEqual(expectedTWOState)
})
it('POP_KEY onePane untouched', () => {
// Arrange
const expectedONEState: IKeyState = mockKeyState(paneType.ONE, false, `${paneType.ONE}_`);
const expectedTWOState: IKeyState =
{
keys: [keyObjectBuilder(`${paneType.TWO}_first`, false, paneType.TWO),
keyObjectBuilder(`${paneType.TWO}_second`, false, paneType.TWO)]
}
populateKeyStore3(paneType.ONE, false);
populateKeyStore3(paneType.TWO, false);
// Act
store.dispatch(popScreen(paneType.TWO))
const data = store.getState().KeyReducers;
const onePaneState = data.keys.filter(x => x.screen === paneType.ONE);
const twoPaneState = data.keys.filter(x => x.screen === paneType.TWO);
// Assert
expect(onePaneState).toStrictEqual(expectedONEState.keys)
expect(twoPaneState).toStrictEqual(expectedTWOState.keys)
})
it('MOVE_TO_FRONT_KEY', () => {
// Arrange
const expectedTWOState: IKeyState =
{
keys: [keyObjectBuilder(`${paneType.TWO}_second`, false, paneType.TWO),
keyObjectBuilder(`${paneType.TWO}_third`, false, paneType.TWO),
keyObjectBuilder(`${paneType.TWO}_first`, false, paneType.TWO)]
}
// Act
populateKeyStore3(paneType.TWO, false);
store.dispatch(moveToFront(paneType.TWO, `${paneType.TWO}_first`));
const data = store.getState().KeyReducers;
// Assert
expect(data).toStrictEqual(expectedTWOState)
})
it('MOVE_TO_FRONT_KEY onePane untouched', () => {
// Arrange
const expectedTWOState: IKeyState =
{
keys: [keyObjectBuilder(`${paneType.TWO}_second`, false, paneType.TWO),
keyObjectBuilder(`${paneType.TWO}_third`, false, paneType.TWO),
keyObjectBuilder(`${paneType.TWO}_first`, false, paneType.TWO)]
}
const expectedONEState: IKeyState = mockKeyState(paneType.ONE, false, `${paneType.ONE}_`);
populateKeyStore3(paneType.ONE, false);
populateKeyStore3(paneType.TWO, false);
// Act
store.dispatch(moveToFront(paneType.TWO, `${paneType.TWO}_first`));
const data = store.getState().KeyReducers;
const onePaneState = data.keys.filter(x => x.screen === paneType.ONE);
const twoPaneState = data.keys.filter(x => x.screen === paneType.TWO);
// Assert
expect(onePaneState).toStrictEqual(expectedONEState.keys)
expect(twoPaneState).toStrictEqual(expectedTWOState.keys)
})
it('CHANGE_SCREEN_KEY', () => {
// Arrange
const expectedONEState: IKeyState =
{
keys: [keyObjectBuilder(`${paneType.TWO}_first`, false, paneType.TWO),
keyObjectBuilder(`${paneType.TWO}_second`, false, paneType.ONE),
keyObjectBuilder(`${paneType.TWO}_third`, false, paneType.TWO)]
}
// Act
populateKeyStore3(paneType.TWO, false);
store.dispatch(changeScreen(paneType.ONE, `${paneType.TWO}_second`));
const data = store.getState().KeyReducers;
// Assert
expect(data).toStrictEqual(expectedONEState)
})
});
}); | the_stack |
import { Loader, FetchLoader, XhrLoader } from './Loader';
import Chunk from './Chunk';
import Clone from './Clone';
import getContext from './getContext';
import { slice } from './utils/buffer';
import isFrameHeader from './utils/isFrameHeader';
import parseMetadata from './utils/parseMetadata';
import warn from './utils/warn';
import { Metadata, RawMetadata } from './interfaces';
const CHUNK_SIZE = 64 * 1024;
const OVERLAP = 0.2;
class PhonographError extends Error {
phonographCode: string;
url: string;
constructor(message: string, opts: { phonographCode: string, url: string }) {
super(message);
this.phonographCode = opts.phonographCode;
this.url = opts.url;
}
}
export default class Clip {
url: string;
loop: boolean;
callbacks: Record<string, Array<(data?: any) => void>> = {};
context: AudioContext = getContext();
buffered = 0;
length = 0;
loaded = false;
canplaythrough = false;
loader: Loader;
metadata: Metadata;
playing = false;
ended = false;
_startTime: number;
_currentTime = 0;
_chunks: Chunk[] = [];
_contextTimeAtStart: number;
_connected: boolean;
_volume: number;
_gain: GainNode;
_loadStarted: boolean;
_referenceHeader: RawMetadata;
constructor({ url, loop, volume }: { url: string, loop?: boolean, volume?: number }) {
this.url = url;
this.loop = loop || false;
this.loader = new (window.fetch ? FetchLoader : XhrLoader)(url);
this._volume = volume || 1;
this._gain = this.context.createGain();
this._gain.gain.value = this._volume;
this._gain.connect(this.context.destination);
this._chunks = [];
}
buffer(bufferToCompletion = false) {
if (!this._loadStarted) {
this._loadStarted = true;
let tempBuffer = new Uint8Array(CHUNK_SIZE * 2);
let p = 0;
let loadStartTime = Date.now();
let totalLoadedBytes = 0;
const checkCanplaythrough = () => {
if (this.canplaythrough || !this.length) return;
let duration = 0;
let bytes = 0;
for (let chunk of this._chunks) {
if (!chunk.duration) break;
duration += chunk.duration;
bytes += chunk.raw.length;
}
if (!duration) return;
const scale = this.length / bytes;
const estimatedDuration = duration * scale;
const timeNow = Date.now();
const elapsed = timeNow - loadStartTime;
const bitrate = totalLoadedBytes / elapsed;
const estimatedTimeToDownload =
1.5 * (this.length - totalLoadedBytes) / bitrate / 1e3;
// if we have enough audio that we can start playing now
// and finish downloading before we run out, we've
// reached canplaythrough
const availableAudio = bytes / this.length * estimatedDuration;
if (availableAudio > estimatedTimeToDownload) {
this.canplaythrough = true;
this._fire('canplaythrough');
}
};
const drainBuffer = () => {
const isFirstChunk = this._chunks.length === 0;
const firstByte = isFirstChunk ? 32 : 0;
const chunk = new Chunk({
clip: this,
raw: slice(tempBuffer, firstByte, p),
onready: this.canplaythrough ? null : checkCanplaythrough,
onerror: (error: any) => {
error.url = this.url;
error.phonographCode = 'COULD_NOT_DECODE';
this._fire('loaderror', error);
}
});
const lastChunk = this._chunks[this._chunks.length - 1];
if (lastChunk) lastChunk.attach(chunk);
this._chunks.push(chunk);
p = 0;
return chunk;
};
this.loader.load({
onprogress: (progress: number, length: number, total: number) => {
this.buffered = length;
this.length = total;
this._fire('loadprogress', { progress, length, total });
},
ondata: (uint8Array: Uint8Array) => {
if (!this.metadata) {
for (let i = 0; i < uint8Array.length; i += 1) {
// determine some facts about this mp3 file from the initial header
if (
uint8Array[i] === 0b11111111 &&
(uint8Array[i + 1] & 0b11110000) === 0b11110000
) {
// http://www.datavoyage.com/mpgscript/mpeghdr.htm
this._referenceHeader = {
mpegVersion: uint8Array[i + 1] & 0b00001000,
mpegLayer: uint8Array[i + 1] & 0b00000110,
sampleRate: uint8Array[i + 2] & 0b00001100,
channelMode: uint8Array[i + 3] & 0b11000000
};
this.metadata = parseMetadata(this._referenceHeader);
break;
}
}
}
for (let i = 0; i < uint8Array.length; i += 1) {
// once the buffer is large enough, wait for
// the next frame header then drain it
if (
p > CHUNK_SIZE + 4 &&
isFrameHeader(uint8Array, i, this._referenceHeader)
) {
drainBuffer();
}
// write new data to buffer
tempBuffer[p++] = uint8Array[i];
}
totalLoadedBytes += uint8Array.length;
},
onload: () => {
if (p) {
const lastChunk = drainBuffer();
lastChunk.attach(null);
totalLoadedBytes += p;
}
this._chunks[0].onready(() => {
if (!this.canplaythrough) {
this.canplaythrough = true;
this._fire('canplaythrough');
}
this.loaded = true;
this._fire('load');
});
},
onerror: (error: any) => {
error.url = this.url;
error.phonographCode = 'COULD_NOT_LOAD';
this._fire('loaderror', error);
this._loadStarted = false;
}
});
}
return new Promise((fulfil, reject) => {
const ready = bufferToCompletion ? this.loaded : this.canplaythrough;
if (ready) {
fulfil();
} else {
this.once(bufferToCompletion ? 'load' : 'canplaythrough', fulfil);
this.once('loaderror', reject);
}
});
}
clone() {
return new Clone(this);
}
connect(destination: AudioNode, output?: number, input?: number) {
if (!this._connected) {
this._gain.disconnect();
this._connected = true;
}
this._gain.connect(destination, output, input);
return this;
}
disconnect(destination: AudioNode, output?: number, input?: number) {
this._gain.disconnect(destination, output, input);
}
dispose() {
if (this.playing) this.pause();
if (this._loadStarted) {
this.loader.cancel();
this._loadStarted = false;
}
this._currentTime = 0;
this.loaded = false;
this.canplaythrough = false;
this._chunks = [];
this._fire('dispose');
}
off(eventName: string, cb: (data?: any) => void) {
const callbacks = this.callbacks[eventName];
if (!callbacks) return;
const index = callbacks.indexOf(cb);
if (~index) callbacks.splice(index, 1);
}
on(eventName: string, cb: (data?: any) => void) {
const callbacks =
this.callbacks[eventName] || (this.callbacks[eventName] = []);
callbacks.push(cb);
return {
cancel: () => this.off(eventName, cb)
};
}
once(eventName: string, cb: (data?: any) => void) {
const _cb = (data?: any) => {
cb(data);
this.off(eventName, _cb);
};
return this.on(eventName, _cb);
}
play() {
const promise = new Promise((fulfil, reject) => {
this.once('ended', fulfil);
this.once('loaderror', reject);
this.once('playbackerror', reject);
this.once('dispose', () => {
if (this.ended) return;
const err = new PhonographError('Clip was disposed', {
phonographCode: 'CLIP_WAS_DISPOSED',
url: this.url
});
reject(err);
});
});
if (this.playing) {
warn(
`clip.play() was called on a clip that was already playing (${this.url})`
);
} else if (!this.canplaythrough) {
warn(
`clip.play() was called before clip.canplaythrough === true (${this.url})`
);
this.buffer().then(() => this._play());
} else {
this._play();
}
this.playing = true;
this.ended = false;
return promise;
}
pause() {
if (!this.playing) {
warn(
`clip.pause() was called on a clip that was already paused (${this.url})`
);
return this;
}
this.playing = false;
this._currentTime =
this._startTime + (this.context.currentTime - this._contextTimeAtStart);
this._fire('pause');
return this;
}
get currentTime() {
if (this.playing) {
return (
this._startTime + (this.context.currentTime - this._contextTimeAtStart)
);
} else {
return this._currentTime;
}
}
set currentTime(currentTime) {
if (this.playing) {
this.pause();
this._currentTime = currentTime;
this.play();
} else {
this._currentTime = currentTime;
}
}
get duration() {
let total = 0;
for (let chunk of this._chunks) {
if (!chunk.duration) return null;
total += chunk.duration;
}
return total;
}
get paused() {
return !this.playing;
}
get volume() {
return this._volume;
}
set volume(volume) {
this._gain.gain.value = this._volume = volume;
}
_fire(eventName: string, data?: any) {
const callbacks = this.callbacks[eventName];
if (!callbacks) return;
callbacks.slice().forEach(cb => cb(data));
}
_play() {
let chunkIndex: number;
let time = 0;
for (chunkIndex = 0; chunkIndex < this._chunks.length; chunkIndex += 1) {
const chunk = this._chunks[chunkIndex];
if (!chunk.duration) {
warn(`attempted to play content that has not yet buffered ${this.url}`);
setTimeout(() => {
this._play();
}, 100);
return;
}
const chunkEnd = time + chunk.duration;
if (chunkEnd > this._currentTime) break;
time = chunkEnd;
}
this._startTime = this._currentTime;
const timeOffset = this._currentTime - time;
this._fire('play');
let playing = true;
const pauseListener = this.on('pause', () => {
playing = false;
if (previousSource) previousSource.stop();
if (currentSource) currentSource.stop();
pauseListener.cancel();
});
const i = chunkIndex++ % this._chunks.length;
let chunk = this._chunks[i];
let previousSource: AudioBufferSourceNode;
let currentSource: AudioBufferSourceNode;
chunk.createSource(
timeOffset,
source => {
currentSource = source;
this._contextTimeAtStart = this.context.currentTime;
let lastStart = this._contextTimeAtStart;
let nextStart =
this._contextTimeAtStart + (chunk.duration - timeOffset);
const gain = this.context.createGain();
gain.connect(this._gain);
gain.gain.setValueAtTime(0, nextStart + OVERLAP);
source.connect(gain);
source.start(this.context.currentTime);
const endGame = () => {
if (this.context.currentTime >= nextStart) {
this.pause()._currentTime = 0;
this.ended = true;
this._fire('ended');
} else {
requestAnimationFrame(endGame);
}
};
const advance = () => {
if (!playing) return;
let i = chunkIndex++;
if (this.loop) i %= this._chunks.length;
chunk = this._chunks[i];
if (chunk) {
chunk.createSource(
0,
source => {
previousSource = currentSource;
currentSource = source;
const gain = this.context.createGain();
gain.connect(this._gain);
gain.gain.setValueAtTime(0, nextStart);
gain.gain.setValueAtTime(1, nextStart + OVERLAP);
source.connect(gain);
source.start(nextStart);
lastStart = nextStart;
nextStart += chunk.duration;
gain.gain.setValueAtTime(0, nextStart + OVERLAP);
tick();
},
(error: any) => {
error.url = this.url;
error.phonographCode = 'COULD_NOT_CREATE_SOURCE';
this._fire('playbackerror', error);
}
);
} else {
endGame();
}
};
const tick = () => {
if (this.context.currentTime > lastStart) {
advance();
} else {
setTimeout(tick, 500);
}
};
const frame = () => {
if (!playing) return;
requestAnimationFrame(frame);
this._fire('progress');
};
tick();
frame();
},
(error: any) => {
error.url = this.url;
error.phonographCode = 'COULD_NOT_START_PLAYBACK';
this._fire('playbackerror', error);
}
);
}
} | the_stack |
import { grafana, pcp, poller } from '../specs/fixtures';
import { TargetFormat } from '../types';
import { processQueries } from './data_processor';
describe('data processor', () => {
it('should create a dataframe and handle missing frames and backward counters', () => {
const target = poller.target({ query: { expr: 'disk.dev.read' } });
const dataQueryRequest = grafana.dataQueryRequest({ targets: [target.query] }); // request data between 10-20s
const values = [
{
timestampMs: 7000, // out of range
values: [
{ instance: 0, value: 7 },
{ instance: 1, value: 5 },
],
},
{
timestampMs: 8000, // request 1 value more to fill the graph
values: [
{ instance: 0, value: 8 },
{ instance: 1, value: 5 },
],
},
{
timestampMs: 9000, // request 1 value more because of counter metric
values: [
{ instance: 0, value: 9 },
{ instance: 1, value: 5 },
],
},
{
timestampMs: 10000,
values: [
{ instance: 0, value: 10 },
{ instance: 1, value: 6 },
],
},
{
timestampMs: 11000,
values: [
{ instance: 0, value: 13 },
{ instance: 1, value: 7 },
],
},
{
timestampMs: 12000,
values: [
{ instance: 0, value: 14 },
// instance 1 missing
],
},
{
timestampMs: 13000,
values: [
{ instance: 0, value: 15 },
{ instance: 1, value: 8 },
],
},
{
timestampMs: 14000,
values: [
{ instance: 0, value: 16 },
{ instance: 1, value: 9 },
],
},
{
timestampMs: 15000,
values: [
{ instance: 0, value: 18 },
{ instance: 1, value: 8 }, // counter went backwards
],
},
{
timestampMs: 16000,
values: [
{ instance: 0, value: 19 },
{ instance: 1, value: 9 },
],
},
{
timestampMs: 17000,
values: [
{ instance: 0, value: 20 },
{ instance: 1, value: 10 },
],
},
{
timestampMs: 21000, // request 1 value more to fill the graph
values: [
{ instance: 0, value: 21 },
{ instance: 1, value: 11 },
],
},
{
timestampMs: 22000, // out of range
values: [
{ instance: 0, value: 22 },
{ instance: 1, value: 12 },
],
},
];
const metric = {
...pcp.metrics['disk.dev.read'],
values,
};
const endpoint = poller.endpoint({ metrics: [metric], targets: [target] });
const result = processQueries(dataQueryRequest, [{ endpoint, query: target.query, metrics: [metric] }], 1);
expect({ fields: result[0].fields }).toMatchInlineSnapshot(
{
fields: [{}, { config: { custom: expect.anything() } }, { config: { custom: expect.anything() } }],
},
`
Object {
"fields": Array [
Object {
"config": Object {},
"name": "Time",
"type": "time",
"values": Array [
8000,
9000,
10000,
11000,
12000,
13000,
14000,
15000,
16000,
17000,
21000,
],
},
Object {
"config": Object {
"custom": Anything,
"displayNameFromDS": "",
},
"labels": Object {
"agent": "linux",
"device_type": "block",
"domainname": "localdomain",
"hostname": "dev",
"indom_name": "per disk",
"machineid": "6dabb302d60b402dabcc13dc4fd0fab8",
},
"name": "disk.dev.read[nvme0n1]",
"type": "number",
"values": Array [
undefined,
1,
1,
3,
1,
1,
1,
2,
1,
1,
0.25,
],
},
Object {
"config": Object {
"custom": Anything,
"displayNameFromDS": "",
},
"labels": Object {
"agent": "linux",
"device_type": "block",
"domainname": "localdomain",
"hostname": "dev",
"indom_name": "per disk",
"machineid": "6dabb302d60b402dabcc13dc4fd0fab8",
},
"name": "disk.dev.read[sda]",
"type": "number",
"values": Array [
undefined,
0,
1,
1,
undefined,
undefined,
1,
undefined,
1,
1,
0.25,
],
},
],
}
`
);
});
it('should process a metrics table', () => {
const targetA = poller.target({
query: { expr: 'some.string.A', refId: 'A', format: TargetFormat.MetricsTable },
});
const targetB = poller.target({
query: { expr: 'some.string.B', refId: 'B', format: TargetFormat.MetricsTable },
});
const metricA = {
metadata: pcp.metadata({
name: 'some.string.A',
type: 'string',
units: 'none',
}),
values: [
{
timestampMs: 10000,
values: [
{ instance: 0, value: 'A/0/10000' },
{ instance: 1, value: 'A/1/10000' },
],
},
{
timestampMs: 11000,
values: [
{ instance: 0, value: 'A/0/11000' },
{ instance: 1, value: 'A/1/11000' },
],
},
],
instanceDomain: {
instances: {
0: { name: 'Inst 0', instance: 0, labels: {} },
1: { name: 'Inst 1', instance: 1, labels: {} },
},
labels: {},
},
};
const metricB = {
metadata: pcp.metadata({
name: 'some.string.B',
type: 'string',
units: 'none',
}),
values: [
{
timestampMs: 10000,
values: [
{ instance: 0, value: 'B/0/10000' },
{ instance: 1, value: 'B/1/10000' },
],
},
{
timestampMs: 11000,
values: [
{ instance: 0, value: 'B/0/11000' },
{ instance: 1, value: 'B/1/11000' },
],
},
],
instanceDomain: {
instances: {
0: { name: 'Inst 0', instance: 0, labels: {} },
1: { name: 'Inst 1', instance: 1, labels: {} },
},
labels: {},
},
};
const endpoint = poller.endpoint({ metrics: [metricA, metricB], targets: [targetA, targetB] });
const dataQueryRequest = grafana.dataQueryRequest({ targets: [targetA.query, targetB.query] });
const result = processQueries(
dataQueryRequest,
[
{ endpoint, query: targetA.query, metrics: [metricA] },
{ endpoint, query: targetB.query, metrics: [metricB] },
],
1
);
expect({ fields: result[0].fields }).toMatchInlineSnapshot(
{ fields: [{}, { config: { custom: expect.anything() } }, { config: { custom: expect.anything() } }] },
`
Object {
"fields": Array [
Object {
"config": Object {},
"name": "instance",
"type": "string",
"values": Array [
"Inst 0",
"Inst 1",
],
},
Object {
"config": Object {
"custom": Anything,
"displayNameFromDS": "A",
},
"labels": Object {
"agent": "linux",
"hostname": "host1",
},
"name": "some.string.A",
"type": "string",
"values": Array [
"A/0/11000",
"A/1/11000",
],
},
Object {
"config": Object {
"custom": Anything,
"displayNameFromDS": "B",
},
"labels": Object {
"agent": "linux",
"hostname": "host1",
},
"name": "some.string.B",
"type": "string",
"values": Array [
"B/0/11000",
"B/1/11000",
],
},
],
}
`
);
});
it('should process a CSV table', () => {
const target = poller.target({
query: { expr: 'some.string', refId: 'A', format: TargetFormat.CsvTable },
});
const metric = {
metadata: pcp.metadata({
name: 'some.string',
type: 'string',
units: 'none',
}),
values: [
{
timestampMs: 10000,
values: [{ instance: null, value: 'a,b,c' }],
},
{
timestampMs: 11000,
values: [
{
instance: null,
value:
'col1,col2,col3\n' +
'row1 col1,row1 col2,row1 col3\n' +
'row2 col1,row2 col2,row2 col3',
},
],
},
],
};
const endpoint = poller.endpoint({ metrics: [metric], targets: [target] });
const dataQueryRequest = grafana.dataQueryRequest({ targets: [target.query] });
const result = processQueries(dataQueryRequest, [{ endpoint, query: target.query, metrics: [metric] }], 1);
expect(result[0].fields).toMatchInlineSnapshot(`
Array [
Object {
"config": Object {},
"name": "col1",
"type": "string",
"values": Array [
"row1 col1",
"row2 col1",
],
},
Object {
"config": Object {},
"name": "col2",
"type": "string",
"values": Array [
"row1 col2",
"row2 col2",
],
},
Object {
"config": Object {},
"name": "col3",
"type": "string",
"values": Array [
"row1 col3",
"row2 col3",
],
},
]
`);
});
}); | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.