text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { readFileSync, writeFileSync, existsSync } from 'fs'
import * as utillib from 'util'
import * as ts from '../../node_modules/typescript/lib/typescript'
import * as Path from 'path'
import { UInt64 } from "../int64"
import { OpInfo } from "../ir/op"
import {
RegSet,
RegInfo,
RegInfoEntry,
emptyRegSet,
nilRegInfo,
fmtRegSet,
} from "../ir/reg"
import { ArchInfo } from "../ir/arch_info"
import { PrimType, StrType, t_str } from '../ast'
import { Op, AuxType } from '../ir/op'
import { ArchDescr, OpDescription, parseOpDescr, t as dtypes } from './describe'
import * as sexpr from "../sexpr"
import arch_generic from "./arch_generic_ops"
import arch_covm from "./arch_covm_ops"
import nummath from "../nummath"
const archs :ArchDescr[] = [
arch_generic,
arch_covm,
]
const outDir = Path.dirname(__dirname) + "/ir"
const opsOutFile = outDir + "/ops.ts"
const opsTemplateFile = __dirname + "/ops_template.ts"
const genericOpnames = new Set<string>(
arch_generic.ops.map(op => op[0] as string))
let consts = new Map<string,string>() // value => js
let opcodes :string[] = []
let nextOpcode = 0
let ops :string[] = []
let opnamesPerArch = new Map<ArchDescr,Set<string>>() // names of ops constants
let opinfoMap = new Map<string,OpInfo>() // canonical opname => info
let opcodeMap = new Map<string,int>() // canonical opname => opcode number
let types = new Set<string>() // types we need to import
let outbuf = "" // used by opsGen
let archsWithValueRewriteRules = new Set<ArchDescr>()
function main() {
opsGen()
for (let a of archs) {
ruleGen(a)
}
archsGen()
}
function archsGen() {
let outFile = outDir + "/arch.ts"
let lines = [] as string[]
const ln = (s :any) => lines.push(String(s))
consts.clear()
for (let a of archs) {
// note: a is of type ArchDescr which extends ArchInfo
ln(`[ ${JSON.stringify(a.arch)}, {`)
for (let k in a) {
if (k == "ops") {
continue // not part of ArchInfo
}
let v = (a as any)[k]
if (v instanceof UInt64) {
ln(` ${k}: ${fmtRegSetJs(v, " ")},`)
} else {
ln(` ${k}: ${fmtjs(v).replace(/\n/g, "\n ")},`)
}
}
if (archsWithValueRewriteRules.has(a)) {
ln(` lowerValue: ${a.arch}_rewriteValue,`)
}
ln(`}],`)
}
let tscode = (
`// Generated from arch/arch_* -- do not edit.\n` +
`// Describes all available architectures.\n` +
`//\n` +
`import { UInt64 } from "../int64"\n` +
`import { ArchInfo } from "./arch_info"\n` +
Array.from(archsWithValueRewriteRules).map(a =>
`import { rewriteValue as ${a.arch}_rewriteValue } ` +
`from "./rewrite_${a.arch}"\n`
).join("") +
`\n` +
getConstantsCode() +
`export const archs = new Map<string,ArchInfo>([\n` +
" " + lines.join("\n ") + "\n" +
`]);\n`
)
// print("------------------------------------\n" + tscode)
print(`write ${rpath(outFile)}`)
writeFileSync(outFile, tscode, "utf8")
}
function ruleGen(a :ArchDescr) {
let rulesFile = __dirname + "/arch_" + a.arch + ".rewrite"
let outFile = outDir + "/rewrite_" + a.arch + ".ts"
let srcrules = loadRewriteRules(a, rulesFile, outFile)
if (!srcrules) {
return
}
let rules :RewriteRule[]
try {
rules = parseRewriteRules(a, srcrules, rulesFile)
} catch (err) {
print(`rules read from ${rpath(rulesFile)}:`, srcrules)
throw err
}
// print("rules:", repr(rules))
const syntaxError = (msg :string, v? :sexpr.Value) => {
let line = v instanceof sexpr.List ? v.line : 0
let col = v instanceof sexpr.List ? v.col : 0
throw newSyntaxErr(rulesFile, line, col, msg)
}
// map opname => list of rules with op as primary match condition
let matchmap = mapRewriteRules(rules, syntaxError)
// print("matchmap:", repr(matchmap))
// ruleFuns is used to ensure we only generate one function for each
// ruleset. This is needed for unions.
interface RuleFunInfo {
code :string // TypeScript function code
opnames :string[]
}
let ruleFuns = new Map<RewriteRule,RuleFunInfo>()
// helper libs
let helperlibs = {} as {[k:string]:string}
// generate code for each ruleset
let maxOpcode = 0
for (let [opname, rules] of matchmap) {
let e = ruleFuns.get(rules[0])
if (e) {
e.opnames.push(opname)
} else {
let code = genRewriteCode(opname, rules, syntaxError, helperlibs)
ruleFuns.set(rules[0], { code, opnames: [ opname ] })
}
let opcode = opcodeMap.get(opname)!
assert(opcode !== undefined && opcode !== null, `opcodeMap.get ${opname}`)
maxOpcode = Math.max(maxOpcode, opcode)
}
// generate rule function code
// generate opcode => fun dispatch code
let mapCode = [] as string[]
let funCode = [] as string[]
for (let e of ruleFuns.values()) {
let funname = "rw_" + e.opnames[0]
funCode.push(`function ${funname}${e.code}\n`)
for (let opname of e.opnames) {
mapCode.push(`rw[ops.${opname}] = ${funname}`)
}
}
let tscode = (
`// generated from arch/${Path.basename(rulesFile)} -- do not edit.\n` +
`import { Value } from "./ssa"\n` +
`import { ValueRewriter } from "./arch_info"\n` +
`import { ops } from "./ops"\n` +
`import { types, PrimType } from "../ast"\n` +
Object.keys(helperlibs).sort().map(
name => `import ${name} from "${helperlibs[name]}"\n`
).join("") +
`\n` +
funCode.join("\n") +
`\n` +
// `const rw = new Array<ValueRewriter>(${maxOpcode + 1})\n` +
`const rw = new Array<ValueRewriter>(${mapCode.length})\n` +
mapCode.join("\n") + "\n" +
`\n` +
`export function rewriteValue(v :Value) :bool {\n` +
` let f = rw[v.op]\n` +
` return f ? f(v) : false\n` +
`}\n`
)
// print("---------------------\n" + tscode)
print(`write ${rpath(outFile)}`)
writeFileSync(outFile, tscode, "utf8")
archsWithValueRewriteRules.add(a)
}
function genRewriteCode(
opname :string,
rules :RewriteRule[],
syntaxError: (msg:string,v?:sexpr.Value)=>void,
helperlibs: {[k:string]:string},
) :string {
let lines = [] as string[]
const ln = (s :any) => lines.push(String(s))
let lastIsBranch = true
let lasti = rules.length -1
for (let i = 0; i <= lasti; i++) {
let [ruleLines, branches] = genRuleRewriteCode(
opname,
rules[i],
syntaxError,
helperlibs,
i == lasti
)
lines = lines.concat(ruleLines)
lastIsBranch = branches
}
if (lastIsBranch) {
// add default return value. false = no rewrite
ln("return false")
}
return `(v :Value) :bool {\n ${lines.join("\n ")}\n}`
}
function genRuleRewriteCode(
opname :string,
r :RewriteRule,
syntaxError: (msg:string,v?:sexpr.Value)=>void,
helperlibs: {[k:string]:string},
isLastRule :bool,
) :[string[]/*lines*/, bool/*isBranch*/] {
let lines = [] as string[]
const ln = (s :any) => lines.push(String(s))
// write comments representing the input
ln(`// match: ${r.match}`)
if (r.cond) { ln(`// cond: ${r.cond}`) }
ln(`// sub: ${r.sub}`)
let hasAddedBlockVar = false
const addBlockVar = () => {
if (!hasAddedBlockVar) {
lines.unshift('let b = v.b')
hasAddedBlockVar = true
}
}
// reusable substitution generator
const genSub = (__ :string) => {
if (r.sub instanceof sexpr.Sym) {
if (r.vars.length > 0) {
// special case: Copy
assert(r.vars.length == 1) // checked by rule parser
ln(`${__}v.reset(ops.Copy)`)
ln(`${__}v.addArg(${r.vars[0]})`)
} else {
// simplest case: just swap out operator; don't touch args
ln(`${__}v.op = ops.${r.sub.value}`)
// ln(`${__}v.reset(ops.${r.sub.value})`)
}
ln(`${__}return true`)
return
}
// complex substitution
assert(r.sub instanceof sexpr.List)
let sub = r.sub as sexpr.List
let vcount = 0
function visitsub(l :sexpr.List, __ :string, fallbackType :string) :string { // returns own arg code
let vname = "v" + (vcount++)
let opname = l[0].toString()
let opcode = opcodeMap.get(opname) as int
assert(opcode !== undefined)
let opinfo = opinfoMap.get(opname) as OpInfo
assert(opinfo !== undefined)
let aux = ""
let auxInt = ""
let typ = opinfo.type ? `types.${opinfo.type.name}` : fallbackType
let args = [] as string[]
for (let i = 1; i < l.length; i++) {
let v = l[i]
if (v instanceof sexpr.List) {
args.push(visitsub(v, __ + " ", typ))
} else if (v instanceof sexpr.Pre) {
if (v.type == "[") { // aux value e.g. [x]
auxInt = transpileCode(v.value, helperlibs)
} else if (v.type == "{") { // aux value e.g. [x]
aux = v.value
} else if (v.type == "<") { // type value e.g. <x>
typ = v.value
} else {
panic(`unexpected ${v}`)
}
} else {
args.push(v.toString())
}
}
if (args.length > 2) {
syntaxError(`too many arguments`, l)
}
addBlockVar()
return (
`\n${__}b.newValue${args.length}(ops.${opname}, ${typ}` +
(args.length > 0 ? ", " + args.join(", ") : "") +
`, ${auxInt}, ${aux})`
)
}
ln(`${__}v.reset(ops.${r.sub[0]})`)
for (let i = 1; i < sub.length; i++) {
let v = sub[i]
if (v instanceof sexpr.List) {
let argVarname = visitsub(v, __ + " ", "null")
ln(`${__}v.addArg(${argVarname})`)
} else if (v instanceof sexpr.Pre) {
if (v.type == "[") { // auxInt value e.g. [x]
ln(`${__}v.auxInt = ${transpileCode(v.value, helperlibs)}`)
} else if (v.type == "{") { // aux value e.g. {x}
ln(`${__}v.aux = ${v.value}`)
} else if (v.type == "<") { // type value e.g. <x>
ln(`${__}v.type = ${v.value}`)
}
} else {
ln(`${__}v.addArg(${v})`)
}
}
ln(`${__}return true`)
}
// simple match on just the op -- return early
if (r.match instanceof sexpr.Sym) {
if (r.cond) {
ln(`if (${transpileCode(r.cond, helperlibs)}) {`)
genSub(" ")
ln(`}`)
return [lines, true]
} else {
// unconditional without args -- i.e. simple substitution
genSub("")
return [lines, false]
}
}
// complex match
assert(r.match instanceof sexpr.List)
let match = r.match as sexpr.List
let hasComplexCond = false
for (let i = 1; i < match.length; i++) {
if (match[i] instanceof sexpr.List) {
// match rule has at least one arg condition
hasComplexCond = true
break
}
}
let __ = ""
let hasSimpleCond = false
let isBlockScoped = false
let isWhileLoop = false
if (hasComplexCond || r.cond || !isLastRule) {
if (r.cond && !r.condRefVars && !hasComplexCond) {
// simplified test up front, avoiding loading of vars
ln(`if (${transpileCode(r.cond, helperlibs)}) {`)
} else {
ln(`while (true) {`)
isWhileLoop = true
}
__ = " "
isBlockScoped = true
}
let vcount = 0
// submatch
function visitm(l :sexpr.List, vname :string) { // returns own arg code
let argidx = 0
ln(`${__}if (${vname}.op != ops.${l[0]}) { break }`)
for (let i = 1; i < l.length; i++) {
let v = l[i]
if (v instanceof sexpr.List) {
let vname2 = `v_${vcount++}`
ln(`${__}let ${vname2} = ${vname}.args[${argidx++}]!;`)
visitm(v, vname2)
} else if (v instanceof sexpr.Pre) {
if (v.type == "[") { // auxInt value e.g. [x]
ln(`${__}let ${v.value} = ${vname}.auxInt`)
} else if (v.type == "{") { // aux value e.g. {x}
ln(`${__}let ${v.value} = ${vname}.aux`)
} else if (v.type == "<") { // type value e.g. <x>
ln(`${__}let ${v.value} = ${vname}.type`)
}
} else {
assert(v instanceof sexpr.Sym)
let s = v as sexpr.Sym
if (s.value != "_") {
ln(`${__}let ${s.value} = ${vname}.args[${argidx}]!;`)
}
argidx++
}
}
}
let argidx = 0
for (let i = 1; i < match.length; i++) {
let v = match[i]
if (v instanceof sexpr.List) {
let vname = `v_${vcount++}`
ln(`${__}let ${vname} = v.args[${argidx++}]!;`)
visitm(v, vname)
} else if (v instanceof sexpr.Pre) {
if (v.type == "[") { // auxInt value e.g. [x]
ln(`${__}let ${v.value} = v.auxInt`)
} else if (v.type == "{") { // aux value e.g. {x}
ln(`${__}let ${v.value} = v.aux`)
} else if (v.type == "<") { // type value e.g. <x>
ln(`${__}let ${v.value} = v.type`)
}
} else {
assert(v instanceof sexpr.Sym)
let s = v as sexpr.Sym
if (s.value != "_") {
ln(`${__}let ${s.value} = v.args[${argidx}]!;`)
}
argidx++
}
}
// condition
if (isWhileLoop && r.cond) {
ln(`${__}if (!(${transpileCode(r.cond, helperlibs)})) { break }`)
}
genSub(__)
if (isBlockScoped) {
ln(`}`)
}
return [ lines, isBlockScoped ]
}
interface RewriteRule {
// source syntax:
// rules = rule*
// rule = match [cond] "->" sub
// match = opcode | (opcode sexpr*) | opcode_or | (opcode_or sexpr*)
// sub = opcode | (opcode sexpr*)
// cond = quoted
// sexpr = (opcode sexpr*)
// | symbol
// | quoted
// | "<" type ">"
// | "[" auxInt "]"
// | "{" aux "}"
// type = symbol
// quoted = "'" <quoted-string> "'"
// symbol = <any non-whitespace character except "()[]{}<>">+
// opcode = symbol
// opcode_or = symbol "(" symbol [ "|" symbol ]* ")"
//
// `opcode` must be one of the opcodes in the arch's arch_*_ops.ts file
// or a generic opcode as defined by arch_generic_ops.ts.
//
// `opcode_or` is an expansion that represents a logical OR expression
// of many opcodes. For example, "Add(32|16)" means "Add32 || Add16".
//
// `cond` can be "extra conditions" (typescript code) that evaluates
// to boolean. It may use variables declared in `match`.
// The variable "v" is predefined to be the value matched by the entire rule.
//
matchops :string[] // canonical opnames this rule primarily matches on
match :sexpr.List|sexpr.Sym
cond :string // TypeScript code
condRefVars :bool // true if cond _probably_ refers to vars
sub :sexpr.List|sexpr.Sym
vars :string[] // ordered list of uniquely-named variables (also "_")
// auxIntvar? :string // [x]
// auxvar? :string // {x}
// typevar? :string // <x>
}
const nmathFunctions = new Set<string>(
Object.keys(nummath).filter(k => typeof nummath[k] == "function")
)
// returns [transpiled code, helpers]
function transpileCode(code :string, helpers :{[k:string]:string}) :string {
let f :ts.SourceFile = ts.createSourceFile(
"input.ts",
code,
ts.ScriptTarget.ESNext,
/*setParentNodes*/ false, // add "parent" property to nodes
ts.ScriptKind.TS
)
if (f.statements.length > 1) {
panic(`multiple statements in code ${repr(code)}`)
}
let needsNumMath = false
let transformers :ts.TransformerFactory<ts.Node>[] = [
(context: ts.TransformationContext) :ts.Transformer<ts.Node> => {
const visit: ts.Visitor = n => {
// print(`visit ${ts.SyntaxKind[n.kind]}`)
if (ts.isBinaryExpression(n)) {
let fname = ""
switch (n.operatorToken.kind) {
case ts.SyntaxKind.PlusToken: fname = "nmath.add"; break // +
case ts.SyntaxKind.MinusToken: fname = "nmath.sub"; break // -
case ts.SyntaxKind.AsteriskToken: fname = "nmath.mul"; break // *
case ts.SyntaxKind.SlashToken: fname = "nmath.div"; break // /
case ts.SyntaxKind.PercentToken: fname = "nmath.mod"; break // %
case ts.SyntaxKind.AmpersandToken: fname = "nmath.band"; break // &
case ts.SyntaxKind.BarToken: fname = "nmath.bor"; break // |
case ts.SyntaxKind.CaretToken: fname = "nmath.xor"; break // ^
case ts.SyntaxKind.AsteriskAsteriskToken:
// fname = "nmath.exp"; break // **
panic(`unsupported arithmetic operator ** in ${repr(code)}`)
break
case ts.SyntaxKind.LessThanToken:
fname = "nmath.lt"; break // <
case ts.SyntaxKind.GreaterThanToken:
fname = "nmath.gt"; break // >
case ts.SyntaxKind.LessThanEqualsToken:
fname = "nmath.lte"; break // <=
case ts.SyntaxKind.GreaterThanEqualsToken:
fname = "nmath.gte"; break // >=
case ts.SyntaxKind.ExclamationEqualsToken:
case ts.SyntaxKind.ExclamationEqualsEqualsToken:
fname = "nmath.neq"; break // !=, !==
case ts.SyntaxKind.EqualsEqualsToken:
case ts.SyntaxKind.EqualsEqualsEqualsToken:
fname = "nmath.eq"; break // ==, ===
case ts.SyntaxKind.LessThanLessThanToken:
fname = "nmath.lshift"; break // <<
case ts.SyntaxKind.GreaterThanGreaterThanToken:
fname = "nmath.rshift"; break // >>
case ts.SyntaxKind.GreaterThanGreaterThanGreaterThanToken:
fname = "nmath.rshiftz"; break // >>>
// default: print("BinaryExpression", n.operatorToken)
}
if (fname != "") {
needsNumMath = true
let left = ts.visitNode(n.left, visit)
let right = ts.visitNode(n.right, visit)
return ts.createCall(ts.createIdentifier(fname), undefined, [left, right])
}
} else if (ts.isPrefixUnaryExpression(n)) {
let fname = ""
switch (n.operator) {
case ts.SyntaxKind.PlusPlusToken: fname = "nmath.incr"; break // ++
case ts.SyntaxKind.MinusMinusToken: fname = "nmath.decr"; break // --
case ts.SyntaxKind.MinusToken: fname = "nmath.neg"; break // -
case ts.SyntaxKind.TildeToken: fname = "nmath.bnot"; break // ~
case ts.SyntaxKind.ExclamationToken: fname = "nmath.not"; break // !
}
if (fname != "") {
needsNumMath = true
let operand = ts.visitNode(n.operand, visit)
return ts.createCall(ts.createIdentifier(fname), undefined, [operand])
}
} else if (ts.isCallExpression(n) && ts.isIdentifier(n.expression)) {
// remap functions
let fname = n.expression.escapedText.toString()
if (nmathFunctions.has(fname)) {
n.expression = ts.createIdentifier("nmath." + fname)
}
}
return ts.visitEachChild(n, visit, context)
}
return node => ts.visitNode(node, visit);
}
]
let compilerOptions :ts.CompilerOptions = {
module: ts.ModuleKind.ESNext,
target: ts.ScriptTarget.ESNext,
}
let r = ts.transform(f.statements[0]!, transformers, compilerOptions)
let printer = ts.createPrinter({
removeComments: false,
newLine: ts.NewLineKind.LineFeed,
omitTrailingSemicolon: true,
noEmitHelpers: true,
})
let outcode = [] as string[]
for (let n of r.transformed) {
outcode.push(printer.printNode(ts.EmitHint.Unspecified, n, f))
}
if (needsNumMath) {
helpers["nmath"] = "../nummath"
}
return outcode.length > 1 ? "(" + outcode.join(", ") + ")" : outcode[0]
}
function mapRewriteRules(
rules :RewriteRule[],
syntaxError: (msg:string,v?:sexpr.Value)=>void,
) :Map<string,RewriteRule[]> {
let m = new Map<string,RewriteRule[]>() // op => rules with op as 1st
let matchesWithoutCond = new Set<string>()
for (let r of rules) {
let hasComplexCond = false
if (r.match instanceof sexpr.List) for (let n of r.match) {
for (let i = 1; i < r.match.length; i++) {
if (r.match[i] instanceof sexpr.List) {
// match rule has at least one arg condition
hasComplexCond = true
break
}
}
}
for (let opname of r.matchops) {
let rules2 = m.get(opname)
if (!rules2) {
rules2 = [ r ]
m.set(opname, rules2)
if (!r.cond && !hasComplexCond) {
matchesWithoutCond.add(opname)
}
} else {
if (!r.cond && !hasComplexCond) {
if (matchesWithoutCond.has(opname)) {
// case: there are multiple unconditional rules for the same op.
// e.g.
// (Add32 x) -> (ADDW x)
// (Add32 x) -> (ADDQ x)
syntaxError(
`Duplicate rule matching on ${opname} without condition.`,
r.match
)
}
matchesWithoutCond.add(opname)
} else if (matchesWithoutCond.has(opname)) {
// case: a conditional rule follows an unconditional rule for the
// same op. e.g.
// (Add32 x) -> (ADDW x)
// (Add32 x) '&& v.commutative' -> (ADDQ x)
// Since rules are evaluated in order, conditional rules must
// preceed unconditional "catch all" rules for an operator.
syntaxError(
`Rule is unreachable. An unconditional rule for ${opname} ` +
`preceeds this rule.`,
r.match
)
}
rules2.push(r)
}
}
}
return m
}
// visit lists recursively
function visitListR(list :sexpr.List, visitor :(v:sexpr.Sym|sexpr.Pre|sexpr.Union, parent:sexpr.List)=>void) {
let visitlists = [ list ] as sexpr.List[]
let l :sexpr.List|undefined
while (l = visitlists.pop()) {
for (let i = 1; i < l.length; i++) {
let v = l[i]
if (v instanceof sexpr.List) {
visitlists.push(v)
} else {
visitor(v, l)
}
}
}
}
function parseRewriteRules(a :ArchDescr, srcrules :sexpr.List, rulesFile :string) :RewriteRule[] {
let rules = [] as RewriteRule[]
let list = srcrules // current list, used for src location in error messages
let archOpnames = opnamesPerArch.get(a)!
let genericOpnames = opnamesPerArch.get(arch_generic)!
assert(archOpnames, "no arch opnames")
assert(genericOpnames, "no generic opnames")
let opnamePrefix = opcodeNamePrefix(a)
const syntaxErr = (msg :string, loc? :sexpr.Value) => {
throw newSyntaxErr(
rulesFile,
loc ? loc.line : 0,
loc ? loc.col : 0,
msg
)
}
const canonicalizeOp = (opname :sexpr.Sym, list? :sexpr.List) => {
if (archOpnames.has(opname.value)) {
opname.value = opnamePrefix + opname.value
} else if (!genericOpnames.has(opname.value)) {
syntaxErr(
`unknown operator ${opname} ` +
`(not defined by arch_${a.arch}_ops.ts nor a generic op)`,
opname
)
}
}
function canonicalizeOpnames<T extends sexpr.List|sexpr.Sym>(v :T, parent? :sexpr.List) {
if (v instanceof sexpr.List) {
// first name is expected to be an opname
let op = v[0]
if (op instanceof sexpr.Sym) {
canonicalizeOp(op, v)
} else if (op instanceof sexpr.Union) {
for (let i = 0; i < op.length; i++) {
let val = op[i]
if (val instanceof sexpr.Sym) {
canonicalizeOp(val, v)
} else {
syntaxErr(`invalid entry ${repr(val)} in op union`, val)
}
}
} else {
syntaxErr(`expected ${repr(v)} to begin with op`, op)
}
// visit other list members of v, e.g. (op1 x (op2 y (op3 z)))
for (let i = 1; i < v.length; i++) {
let v2 = v[i]
if (v2 instanceof sexpr.List) {
canonicalizeOpnames(v2, v)
}
}
} else if (v instanceof sexpr.Sym) {
canonicalizeOp(v, parent)
} else {
syntaxErr(`expected ${repr(v)} to begin with op`, v)
}
}
let i = 0
while (i < srcrules.length) {
// expect match list
let match = srcrules[i++] as sexpr.List|sexpr.Sym
let matchops = [] as string[]
if (!(match instanceof sexpr.List) && !(match instanceof sexpr.Sym)) {
syntaxErr(`expected a list or symbol but got ${repr(match)}`, match)
}
canonicalizeOpnames(match, list)
let varset = new Set<string>()
let vars = [] as string[]
let auxIntvar :string|undefined = undefined // [x]
let auxvar :string|undefined = undefined // {x}
let typevar :string|undefined = undefined // <x>
if (match instanceof sexpr.List) {
list = match
let op = match[0]
while (match.length == 1 && op instanceof sexpr.List) {
// (Op) => Op
match = op
}
if (op instanceof sexpr.Union) {
matchops = op.map(s => s.value)
} else {
assert(op instanceof sexpr.Sym)
matchops = [ (op as sexpr.Sym).value ]
}
// vars
visitListR(match as sexpr.List, (v, parent) => {
if (!(v instanceof sexpr.Sym)) {
return
}
let varname = v.value
if (varname == "_") {
varname = ""
} else {
if (!varset.has(varname)) {
varset.add(varname)
} else {
syntaxErr(`duplicate variable ${repr(varname)}`, v)
}
}
if (v instanceof sexpr.Pre) {
if (parent === match) {
if (v.type == "[") {
if (auxIntvar) {
syntaxErr(`secondary auxInt var ${v}`, v)
}
auxIntvar = v.value
} else if (v.type == "{") {
if (auxvar) {
syntaxErr(`secondary aux var ${v}`, v)
}
auxvar = v.value
} else if (v.type == "<") {
if (typevar) {
syntaxErr(`secondary type var ${v}`, v)
}
typevar = v.value
} else {
panic(`sexpr.Pre type ${v.type}`)
}
}
} else {
vars.push(varname)
}
})
} else {
matchops = [ (match as sexpr.Sym).value ]
}
// expect "->" or conditions followed by "->"
let arrow = srcrules[i++]
let condval = arrow
let cond = ""
if (condval instanceof sexpr.Pre) {
cond = condval.value
arrow = srcrules[i++]
}
if (!(arrow instanceof sexpr.Sym) || arrow.value != "->") {
if (cond == "") {
syntaxErr(`expected -> or quoted condition`)
} else {
syntaxErr(`expected ->`)
}
}
// does cond refer to vars?
let condRefVars = false
if (cond != "" && varset.size > 0) {
let scannerErrors = [] as string[]
// let varset2 = new Set<string>(Array.from(varset).map(s => {
// // simplify "special" variables like aux and type
// if (s[0] == "[" || s[0] == "{" || s[0] == "<") {
// return s.substring(1, s.length-1)
// }
// return s
// }))
condRefVars = tsCodeRefersToIdentifiers(
cond,
varset,
(m: ts.DiagnosticMessage, length: number) => {
scannerErrors.push(
ts.flattenDiagnosticMessageText(m.message, "\n") +
` (TS${m.code})`
)
},
)
if (scannerErrors.length > 0) {
throw newSyntaxErr(
rulesFile,
condval.line,
condval.col,
scannerErrors.join("\n")
)
}
}
// expect substitution
let sub = srcrules[i++] as sexpr.List|sexpr.Sym
if (!(sub instanceof sexpr.List) && !(sub instanceof sexpr.Sym)) {
syntaxErr(`expected a list or symbol but got ${repr(sub)}`)
}
let nvarsAccountedFor = 0
if (sub instanceof sexpr.Sym &&
(sub.value == "_" || varset.has(sub.value)))
{
// variable sub. e.g. (TruncI16to8 x) -> x
nvarsAccountedFor++
} else {
canonicalizeOpnames(sub)
if (sub instanceof sexpr.List) {
// verify vars
visitListR(sub, v => {
if (!(v instanceof sexpr.Sym)) {
return
}
if (v.value == "_") {
syntaxErr(
`invalid placeholder variable ${repr(v.value)} in substitution`,
v
)
} else if (varset.has(v.value)) {
nvarsAccountedFor++
}
// else: something else, like types.uint8 or 42
// else {
// syntaxErr(`undefined variable ${repr(v.toString())}`, v)
// }
})
}
}
// This check is intentionally disabled since we have no way of telling
// if variables are used in arbitrary code (sexpr.Pre).
// if (nvarsAccountedFor < varset.size) {
// syntaxErr(
// `not all variables are used in substitution. ` +
// `Use "_" to skip/discard a variable.`,
// sub
// )
// }
// produce rule
rules.push({
matchops,
match,
cond,
condRefVars,
sub,
vars,
// auxIntvar,
// auxvar,
// typevar,
})
}
return rules
}
// tsCodeRefersToIdentifiers scans tscode as TypeScript source tokens
// and returns true if any of idents are found as referencing identifiers.
//
function tsCodeRefersToIdentifiers(tscode :string, idents :Set<string>, onerror :ts.ErrorCallback) :bool {
let s :ts.Scanner = ts.createScanner(
ts.ScriptTarget.ESNext,
/*skipTrivia*/ true,
ts.LanguageVariant.Standard,
/*textInitial*/ tscode,
onerror,
// start?: number,
// length?: number
)
scan_loop: while (true) {
let t = s.scan()
switch (t) {
case ts.SyntaxKind.EndOfFileToken:
case ts.SyntaxKind.Unknown:
break scan_loop
case ts.SyntaxKind.DotToken:
// skip next
s.scan()
break
case ts.SyntaxKind.Identifier:
if (idents.has(s.getTokenValue())) {
return true
}
break
}
}
return false
}
function loadRewriteRules(a :ArchDescr, rulesFile :string, outFile :string) :sexpr.List|null {
try {
let src = readFileSync(rulesFile, "utf8")
return sexpr.parse(src, {
filename: rpath(rulesFile),
brack: sexpr.AS_PRE, // parse [...] as Pre
brace: sexpr.AS_PRE, // parse {...} as Pre
ltgt: sexpr.AS_PRE, // parse <...> as Pre
})
} catch (err) {
if (err.code == "ENOENT") {
// print(`${rpath(rulesFile)} not found; skipping arch "${a.arch}"`)
if (existsSync(outFile)) {
// there's an existing generated rewrite file.
// Let the user decide what to do here (i.e. rather than removing it.)
console.error(
`old generated file ${repr(outFile)} is lingering. ` +
`You should remove it or add ${rpath(rulesFile)}`
)
process.exit(1)
}
return null
}
throw err
}
}
function newSyntaxErr(file :string, line :int, col :int, msg :string) {
let e = new sexpr.SyntaxError(`${rpath(file)}:${line}:${col}: ${msg}`)
e.name = "SyntaxError"
e.file = file
e.line = line
e.col = col
return e
}
function opsGen() {
buildOpTables()
let body = outbuf
let tpl = readFileSync(opsTemplateFile, "utf8")
// imports
let imports = (
'import {\n ' +
Array.from(types).sort().join(",\n ") +
'\n} from "../ast"\n'
)
// glue it all together
let importsAt = tpl.match(/\/\/\$IMPORTS\n/) as any as {0:string,index:number}
let bodyStartAt = tpl.match(/\/\/\$BODY_START/) as any as {0:string,index:number}
let bodyEndAt = tpl.match(/\/\/\$BODY_END/) as any as {0:string,index:number}
assert(importsAt, "missing //$IMPORTS")
assert(bodyStartAt, "missing //$BODY_START")
assert(bodyEndAt, "missing //$BODY_END")
let importsStart = importsAt.index
let importsEnd = importsAt.index + importsAt[0].length
let bodyStart = bodyStartAt.index
let bodyEnd = bodyEndAt.index + bodyEndAt[0].length
let tscode = (
tpl.substr(0, importsStart) +
imports +
tpl.substring(importsEnd, bodyStart) +
getConstantsCode() +
body +
tpl.substr(bodyEnd)
)
// write file
print(`write ${rpath(opsOutFile)}`)
writeFileSync(opsOutFile, tscode, "utf8")
}
let longestOpName = 0
function buildOpTables() {
for (let a of archs) {
let opnames = buildOpTable(a)
opnamesPerArch.set(a, opnames)
}
opcodes.push("// END")
opcodes.push("OpcodeMax")
opcodeMap.set("OpcodeMax", opcodeMap.size)
write(`export const opnameMaxLen = ${longestOpName};\n`)
write(
"export const ops = {\n " +
opcodes.map(name => {
if (name.startsWith("//")) {
return "\n " + name
}
return `${name}: ${opcodeMap.get(name)},`
}).join("\n ").replace(/\n\s+\n/gm, "\n\n") +
"\n};\n"
)
write("\n")
write(
"export const opinfo :OpInfo[] = [\n" +
ops.join("\n") + "\n]; // ops\n"
)
write("\n")
}
function opcodeNamePrefix(a :ArchDescr) :string {
if (a === arch_generic) {
return ""
}
return a.arch[0].toUpperCase() + a.arch.substr(1)
}
function buildOpTable(a :ArchDescr) :Set<string> {
let opnames = new Set<string>()
let opnamePrefix = opcodeNamePrefix(a)
opcodes.push("// " + a.arch)
ops.push("\n // " + a.arch)
for (let d of a.ops) {
let op = parseOpDescr(d)
if (op.type) {
types.add(typename(op.type))
}
let opcode = nextOpcode++
if (a !== arch_generic && genericOpnames.has(op.name)) {
// rewrite rules are namespaced by context and thus require that
// opnames of an arch are not shared with the non-namespaced generic
// ops.
throw new Error(
`opname ${repr(op.name)} of arch ${repr(a.arch)} ` +
`has the same names as a generic op`
)
}
// add to arch-specific list of local names
assert(!opnames.has(op.name), `duplicate op ${op.name}`)
opnames.add(op.name)
// find longest name
longestOpName = Math.max(longestOpName, op.name.length)
// canonical opname
const opname = opnamePrefix + op.name
// add mapping of canonical opname => opinfo
assert(!opinfoMap.has(opname))
opinfoMap.set(opname, op)
opcodeMap.set(opname, opcode)
// add name to global set of opcodes (used to generate TypeScript code)
opcodes.push(opname)
// add name to global set of opinfo (used to generate TypeScript code)
ops.push(fmtop(op, opcode) + ",")
}
return opnames
}
// returns TS code for constant name+values in consts
//
function getConstantsCode() {
let constants = ""
let index = 0
for (let [name, js] of consts) {
if (constants == "") {
constants = "const "
} else {
constants += ",\n "
}
constants += `${name} = ${js}`
}
if (constants) {
constants += ";\n\n"
}
return constants
}
function typename(t :PrimType|StrType) :string {
if (t.isPrimType()) {
return "t_" + t.name
}
if (t === t_str) {
return "t_str"
}
throw new Error(`invalid type ${t}`)
}
function fmtop(op :OpInfo, opcode :int) :string {
let s = " { name: " + fmtjs(op.name) + ",\n"
for (let k of Object.keys(op).sort()) {
if (k != "name") {
let v = (op as any)[k]
if (k == "reg") {
assert(typeof v == "object")
v = fmtRegInfo(v as RegInfo)
} else if (k == "aux") {
if (typeof v == "string") {
assert(AuxType[v as string] !== undefined, `no AuxType.${v}`)
v = "AuxType." + v
} else {
let name = AuxType[v as int] as string
assert(name !== undefined, `no AuxType[${v}]`)
v = "AuxType." + name
}
} else if (v instanceof PrimType || v instanceof StrType) {
v = typename(v)
} else {
v = fmtjs(v)
}
s += ` ${k}: ${v},\n`
}
}
s += " }"
return s
}
function fmtRegInfo(ri :RegInfo) :string {
if (ri === nilRegInfo) {
return "nilRegInfo"
}
let props :string[][] = [
[ "inputs",
ri.inputs.length > 0 ?
"[\n " + ri.inputs.map(fmtRegInfoEntry).join(",\n ") + "\n ]" :
"[]"
],
[ "outputs",
ri.outputs.length > 0 ?
"[\n " + ri.outputs.map(fmtRegInfoEntry).join(",\n ") + "\n ]" :
"[]"
],
[ "clobbers", fmtRegSetJs(ri.clobbers, " ")],
]
return "{\n " + props.map(([k,v]) => `${k}: ${v}`).join(",\n ") + "\n }"
}
function fmtRegInfoEntry(e :RegInfoEntry) :string {
return `{idx:${e.idx},regs:${fmtRegSetJs(e.regs, " ")}}`
}
function fmtRegSetJs(u :RegSet, indent :string) :string {
// Note: RegSet is an alias for UInt64
if (u === emptyRegSet) {
assert(emptyRegSet === UInt64.ZERO)
return "UInt64.ZERO"
}
assert(!u.isSigned, "not a UInt64")
return `${getU64Const(u)} /*RegSet ${fmtRegSet(u)}*/`
}
function getU64Const(u :UInt64) :string {
let name = "u64_" + u.toString(16)
let cached = consts.get(name)
if (!cached) {
consts.set(name, `new UInt64(${u._low},${u._high})`)
}
return name
}
function fmtjs(value :any) :string {
return utillib.inspect(value, false, 4)
// return JSON.stringify(value)
}
function write(s :string) {
outbuf += s
}
function rpath(path :string) :string {
return Path.relative(".", path)
}
main() | the_stack |
import {
isLaunchInsideApp,
setTransparentBackground,
showActionSheet,
showModal,
showNotification,
showPreviewOptions,
useStorage,
request,
sleep,
} from '@app/lib/help'
import {FC} from 'react'
import {WtextProps, WstackProps} from '@app/types/widget'
/**手机卡数据列表*/
interface PhoneDatas {
data: {
dataList: PhoneData[]
}
}
/**手机卡数据*/
interface PhoneData {
pointUpdateTimeStamp: string
paperwork4: string
buttonBacImageUrlBig: string
type: PhoneDataType
remainTitle: string
buttonText7: string
buttonLinkMode: string
displayTime: string
buttonText7TextColor: string
buttonBacImageUrlSmall: string
button: string
remainTitleColoer: string
buttonBacImageUrl: string
buttonTextColor: string
isShake: string
number: string
isWarn?: string
paperwork4Coloer: string
url: string
buttonUrl7: string
unit: string
button7LinkMode: string
persent: string
persentColor: string
buttonAddress: string
usedTitle: string
ballRippleColor1: string
ballRippleColor2: string
markerImg?: string
warningTextColor?: string
warningPointColor?: string
}
/**有用的手机卡数据*/
interface UsefulPhoneData {
/**类型*/
type: PhoneDataType
/**剩余百分比数字*/
percent: number
/**单位*/
unit: string
/**剩余量数字*/
count: number
/**描述*/
label: string
}
/**手机卡数据类型*/
enum PhoneDataType {
/**流量*/
FLOW = 'flow',
/**话费*/
FEE = 'fee',
/**语音*/
VOICE = 'voice',
/**积分*/
POINT = 'point',
/**信用分*/
CREDIT = 'credit',
/**电子券*/
WOPAY = 'woPay',
}
const typeDesc: Record<PhoneDataType, string> = {
[PhoneDataType.FLOW]: '流量',
[PhoneDataType.FEE]: '话费',
[PhoneDataType.VOICE]: '语音',
[PhoneDataType.POINT]: '积分',
[PhoneDataType.CREDIT]: '信用分',
[PhoneDataType.WOPAY]: '电子券',
}
// 格式化数字
const formatNum = (num: number) => parseFloat(Number(num).toFixed(1))
const {setStorage, getStorage} = useStorage('china10010-xiaoming')
/**默认背景颜色*/
const defaultBgColor = Color.dynamic(new Color('#ffffff', 1), new Color('#000000', 1))
/**文字颜色*/
const textColor = getStorage<string>('textColor') || Color.dynamic(new Color('#000000', 1), new Color('#dddddd', 1))
/**透明背景*/
const transparentBg: Image | Color = getStorage<Image>('transparentBg') || defaultBgColor
/**背景颜色或背景图链接*/
const boxBg = getStorage<string>('boxBg') || defaultBgColor
class China10010 {
async init() {
if (isLaunchInsideApp()) {
return await this.showMenu()
}
const widget = (await this.render()) as ListWidget
Script.setWidget(widget)
Script.complete()
}
//渲染组件
async render(): Promise<unknown> {
if (isLaunchInsideApp()) {
await showNotification({title: '稍等片刻', body: '小部件渲染中...', sound: 'alert'})
}
// 多久(毫秒)更新一次小部件(默认3分钟)
const updateInterval = 1 * 60 * 1000
// 渲染尺寸
const size = config.widgetFamily
// 获取数据
const usefulPhoneDatas = await this.getUserfulPhoneData(getStorage<string>('phoneNumber') || '')
if (typeof usefulPhoneDatas === 'string') {
return (
<wbox>
<wtext textAlign="center" font={20}>
{usefulPhoneDatas}
</wtext>
</wbox>
)
}
console.log(usefulPhoneDatas)
return (
<wbox
padding={[0, 0, 0, 0]}
updateDate={new Date(Date.now() + updateInterval)}
background={typeof boxBg === 'string' && boxBg.match('透明背景') ? transparentBg : boxBg}
>
<wstack flexDirection="column" padding={[0, 16, 0, 16]}>
<wspacer></wspacer>
{/* 标题和logo */}
<wstack verticalAlign="center">
<wimage
src="https://p.pstatp.com/origin/1381a0002e9cbaedbc301"
width={20}
height={20}
borderRadius={4}
></wimage>
<wspacer length={8}></wspacer>
<wtext opacity={0.7} font={Font.boldSystemFont(14)} textColor={textColor}>
中国联通
</wtext>
</wstack>
<wspacer></wspacer>
{/* 内容 */}
{size === 'small' && this.renderSmall(usefulPhoneDatas)}
{size === 'medium' && this.renderMedium(usefulPhoneDatas)}
{size === 'large' && this.renderLarge(usefulPhoneDatas)}
</wstack>
</wbox>
)
}
// 渲染小尺寸
renderSmall(usefulPhoneDatas: UsefulPhoneData[]) {
// 流量
const flow = usefulPhoneDatas.find(item => item.type === PhoneDataType.FLOW) as UsefulPhoneData
// 话费
const fee = usefulPhoneDatas.find(item => item.type === PhoneDataType.FEE) as UsefulPhoneData
return (
<>
<wtext textColor={textColor} font={Font.lightSystemFont(14)}>
剩余流量{formatNum(flow.count || 0) + flow.unit}
</wtext>
<wspacer></wspacer>
<wtext textColor={textColor} font={Font.lightSystemFont(14)}>
剩余话费{formatNum(fee.count || 0) + fee.unit}
</wtext>
<wspacer></wspacer>
</>
)
}
// 渲染中尺寸
renderMedium(usefulPhoneDatas: UsefulPhoneData[]) {
const showDataType: PhoneDataType[] = [PhoneDataType.FLOW, PhoneDataType.FEE, PhoneDataType.VOICE]
return this.renderLarge(usefulPhoneDatas.filter(data => showDataType.indexOf(data.type) >= 0))
}
// 渲染大尺寸
renderLarge(usefulPhoneDatas: UsefulPhoneData[]) {
/**进度条*/
const Progress: FC<{
color: WstackProps['background']
bgcolor: WstackProps['background']
progress: number
width: number
height: number
borderRadius?: number
}> = ({...props}) => {
const {color, bgcolor, progress, width, height, borderRadius = 0} = props
return (
<wstack background={bgcolor} width={width} height={height} borderRadius={borderRadius}>
<wstack background={color} height={height} width={width * progress}>
<wtext></wtext>
</wstack>
{progress < 1 && <wspacer></wspacer>}
</wstack>
)
}
/**表格格子*/
const TableGrid: FC<
WtextProps & {text: string | React.ReactNode; width: number; align: 'left' | 'center' | 'right'}
> = ({text, width, align, ...props}) => (
<wstack width={width}>
{(align === 'center' || align === 'right') && <wspacer></wspacer>}
{typeof text === 'string' ? (
<wtext font={14} textColor={textColor} {...props}>
{text}
</wtext>
) : (
text
)}
{(align === 'center' || align === 'left') && <wspacer></wspacer>}
</wstack>
)
/**表格行*/
const TableRow: FC<WtextProps & {texts: (string | React.ReactNode)[]}> = ({texts, ...props}) => (
<wstack verticalAlign="center">
<TableGrid text={texts[0]} {...props} width={60} align="left"></TableGrid>
<wspacer></wspacer>
<TableGrid text={texts[1]} {...props} width={90} align="center"></TableGrid>
<wspacer></wspacer>
<TableGrid text={texts[2]} {...props} width={70} align="right"></TableGrid>
</wstack>
)
return (
<>
<TableRow texts={['类型', '剩余百分比', '剩余量']}></TableRow>
{usefulPhoneDatas.map(item => (
<>
<wspacer></wspacer>
<TableRow
font={Font.lightSystemFont(14)}
texts={[
typeDesc[item.type],
Progress({
color: '#39b54a',
bgcolor: '#dddddd',
width: 80,
height: 10,
borderRadius: 5,
progress: formatNum(item.percent) / 100,
}),
formatNum(item.count) + item.unit,
]}
></TableRow>
</>
))}
<wspacer></wspacer>
</>
)
}
// 显示菜单
async showMenu() {
const selectIndex = await showActionSheet({
title: '菜单',
itemList: ['登录获取cookie', '设置手机号和cookie', '设置颜色', '设置透明背景', '预览组件'],
})
switch (selectIndex) {
case 0:
const {cancel: cancelLogin} = await showModal({
title: '为什么要登录',
content:
'获取手机号码信息需要 cookie,而 cookie 不登录获取不到\n\n登录完成后,关闭网页,网页会再自动打开\n\n此时点击底部按钮复制 cookie ,然后关网页去设置cookie\n\n若 cookie 失效,再次登录复制即可',
confirmText: '去登录',
})
if (cancelLogin) return
const loginUrl = 'http://wap.10010.com/mobileService/myunicom.htm'
const webview = new WebView()
await webview.loadURL(loginUrl)
await webview.present()
/**循环插入脚本等待时间,单位:毫秒*/
const sleepTime = 1000
/**循环时间统计,单位:毫秒*/
let waitTimeCount = 0
/**最大循环时间,单位:毫秒*/
const maxWaitTime = 10 * 60 * sleepTime
while (true) {
if (waitTimeCount >= maxWaitTime) break
const {isAddCookieBtn} = (await webview.evaluateJavaScript(`
window.isAddCookieBtn = false
if (document.cookie.match('jsessionid')) {
const copyWrap = document.createElement('div')
copyWrap.innerHTML = \`
<div style="position: fixed; bottom: 0; left: 0; z-index: 999999; width: 100vw; height: 10vh; text-align: center; line-height: 10vh; background: #000000; color: #ffffff; font-size: 16px;" id="copy-btn">复制cookie</div>
\`
function copy(text) {
var input = document.createElement('input');
input.setAttribute('value', text);
document.body.appendChild(input);
input.select();
var result = document.execCommand('copy');
document.body.removeChild(input);
return result;
}
document.body.appendChild(copyWrap)
const copyBtn = document.querySelector('#copy-btn')
copyBtn.onclick = () => {
copy(document.cookie)
copyBtn.innerText = '复制成功'
copyBtn.style.background = 'green'
}
window.isAddCookieBtn = true
}
Object.assign({}, {isAddCookieBtn: window.isAddCookieBtn})
`)) as {isAddCookieBtn: boolean}
if (isAddCookieBtn) break
await sleep(sleepTime)
waitTimeCount += sleepTime
}
await webview.present()
break
case 1:
const {texts: phoneInfo, cancel: phoneInfoCancel} = await showModal({
title: '设置手机号和cookie',
content: '请务必先登录,在登录处复制好 cookie 再来,不懂就仔细看登录说明',
inputItems: [
{
text: getStorage<string>('phoneNumber') || '',
placeholder: '这里填你的手机号',
},
{
text: getStorage<string>('cookie') || '',
placeholder: '这里填cookie',
},
],
})
if (phoneInfoCancel) return
setStorage('phoneNumber', phoneInfo[0])
setStorage('cookie', phoneInfo[1])
await showNotification({title: '设置完成', sound: 'default'})
break
case 2:
const {texts, cancel} = await showModal({
title: '设置全局背景和颜色',
content: '如果为空,则还原默认',
inputItems: [
{
text: getStorage<string>('boxBg') || '',
placeholder: '全局背景:可以是颜色、图链接',
},
{
text: getStorage<string>('textColor') || '',
placeholder: '这里填文字颜色',
},
],
})
if (cancel) return
setStorage('boxBg', texts[0])
setStorage('textColor', texts[1])
await showNotification({title: '设置完成', sound: 'default'})
break
case 3:
const img: Image | null = (await setTransparentBackground()) || null
if (img) {
setStorage('transparentBg', img)
setStorage('boxBg', '透明背景')
await showNotification({title: '设置透明背景成功', sound: 'default'})
}
break
case 4:
await showPreviewOptions(this.render.bind(this))
break
}
}
// 获取手机卡数据
async getUserfulPhoneData(phoneNumber: string): Promise<UsefulPhoneData[] | string> {
if (!phoneNumber) return '请设置手机号'
if (!isLaunchInsideApp() && !getStorage('cookie')) return 'cookie 不存在,请先登录'
const api = `https://wap.10010.com/mobileService/home/queryUserInfoSeven.htm?version=iphone_c@7.0403&desmobiel=${phoneNumber}&showType=3`
// 获取手机卡信息列表
const res = await request<string>({
url: api,
dataType: 'text',
header: {
'user-agent':
'Mozilla/5.0 (iPhone; CPU iPhone OS 14_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1',
cookie: getStorage<string>('cookie') || '',
},
})
// isLaunchInsideApp() && cookie && setStorage('cookie', cookie)
let usefulPhoneDatas: UsefulPhoneData[] = []
try {
const phoneDatas: PhoneData[] = (JSON.parse(res.data || '') as PhoneDatas).data.dataList || []
// 提取有用的信息
usefulPhoneDatas = phoneDatas.map(info => {
const percent = info.usedTitle.replace(/(已用|剩余)([\d\.]+)?\%/, (...args) => {
return args[1] === '剩余' ? args[2] : 100 - args[2]
})
return {
type: info.type,
percent: Number(percent) > 100 ? 100 : Number(percent),
unit: info.unit,
count: Number(info.number),
label: info.remainTitle,
}
})
} catch (err) {
console.warn(`获取联通卡信息失败: ${err}`)
await showNotification({title: '获取联通卡信息失败', body: '检查一下网络,或重新登录', sound: 'failure'})
return '获取联通卡信息失败\n检查一下网络,或重新登录'
}
return usefulPhoneDatas
}
}
EndAwait(() => new China10010().init()) | the_stack |
// (Re-)generated by schema tool
// >>>> DO NOT CHANGE THIS FILE! <<<<
// Change the json schema instead
import * as wasmlib from "wasmlib";
import * as sc from "./index";
export function on_call(index: i32): void {
return wasmlib.onCall(index);
}
export function on_load(): void {
let exports = new wasmlib.ScExports();
exports.addFunc(sc.FuncCallOnChain, funcCallOnChainThunk);
exports.addFunc(sc.FuncCheckContextFromFullEP, funcCheckContextFromFullEPThunk);
exports.addFunc(sc.FuncDoNothing, funcDoNothingThunk);
exports.addFunc(sc.FuncGetMintedSupply, funcGetMintedSupplyThunk);
exports.addFunc(sc.FuncIncCounter, funcIncCounterThunk);
exports.addFunc(sc.FuncInit, funcInitThunk);
exports.addFunc(sc.FuncPassTypesFull, funcPassTypesFullThunk);
exports.addFunc(sc.FuncRunRecursion, funcRunRecursionThunk);
exports.addFunc(sc.FuncSendToAddress, funcSendToAddressThunk);
exports.addFunc(sc.FuncSetInt, funcSetIntThunk);
exports.addFunc(sc.FuncSpawn, funcSpawnThunk);
exports.addFunc(sc.FuncTestBlockContext1, funcTestBlockContext1Thunk);
exports.addFunc(sc.FuncTestBlockContext2, funcTestBlockContext2Thunk);
exports.addFunc(sc.FuncTestCallPanicFullEP, funcTestCallPanicFullEPThunk);
exports.addFunc(sc.FuncTestCallPanicViewEPFromFull, funcTestCallPanicViewEPFromFullThunk);
exports.addFunc(sc.FuncTestChainOwnerIDFull, funcTestChainOwnerIDFullThunk);
exports.addFunc(sc.FuncTestEventLogDeploy, funcTestEventLogDeployThunk);
exports.addFunc(sc.FuncTestEventLogEventData, funcTestEventLogEventDataThunk);
exports.addFunc(sc.FuncTestEventLogGenericData, funcTestEventLogGenericDataThunk);
exports.addFunc(sc.FuncTestPanicFullEP, funcTestPanicFullEPThunk);
exports.addFunc(sc.FuncWithdrawToChain, funcWithdrawToChainThunk);
exports.addView(sc.ViewCheckContextFromViewEP, viewCheckContextFromViewEPThunk);
exports.addView(sc.ViewFibonacci, viewFibonacciThunk);
exports.addView(sc.ViewGetCounter, viewGetCounterThunk);
exports.addView(sc.ViewGetInt, viewGetIntThunk);
exports.addView(sc.ViewGetStringValue, viewGetStringValueThunk);
exports.addView(sc.ViewJustView, viewJustViewThunk);
exports.addView(sc.ViewPassTypesView, viewPassTypesViewThunk);
exports.addView(sc.ViewTestCallPanicViewEPFromView, viewTestCallPanicViewEPFromViewThunk);
exports.addView(sc.ViewTestChainOwnerIDView, viewTestChainOwnerIDViewThunk);
exports.addView(sc.ViewTestPanicViewEP, viewTestPanicViewEPThunk);
exports.addView(sc.ViewTestSandboxCall, viewTestSandboxCallThunk);
for (let i = 0; i < sc.keyMap.length; i++) {
sc.idxMap[i] = wasmlib.Key32.fromString(sc.keyMap[i]);
}
}
function funcCallOnChainThunk(ctx: wasmlib.ScFuncContext): void {
ctx.log("testcore.funcCallOnChain");
let f = new sc.CallOnChainContext();
f.params.mapID = wasmlib.OBJ_ID_PARAMS;
f.results.mapID = wasmlib.OBJ_ID_RESULTS;
f.state.mapID = wasmlib.OBJ_ID_STATE;
ctx.require(f.params.intValue().exists(), "missing mandatory intValue");
sc.funcCallOnChain(ctx, f);
ctx.log("testcore.funcCallOnChain ok");
}
function funcCheckContextFromFullEPThunk(ctx: wasmlib.ScFuncContext): void {
ctx.log("testcore.funcCheckContextFromFullEP");
let f = new sc.CheckContextFromFullEPContext();
f.params.mapID = wasmlib.OBJ_ID_PARAMS;
f.state.mapID = wasmlib.OBJ_ID_STATE;
ctx.require(f.params.agentID().exists(), "missing mandatory agentID");
ctx.require(f.params.caller().exists(), "missing mandatory caller");
ctx.require(f.params.chainID().exists(), "missing mandatory chainID");
ctx.require(f.params.chainOwnerID().exists(), "missing mandatory chainOwnerID");
ctx.require(f.params.contractCreator().exists(), "missing mandatory contractCreator");
sc.funcCheckContextFromFullEP(ctx, f);
ctx.log("testcore.funcCheckContextFromFullEP ok");
}
function funcDoNothingThunk(ctx: wasmlib.ScFuncContext): void {
ctx.log("testcore.funcDoNothing");
let f = new sc.DoNothingContext();
f.state.mapID = wasmlib.OBJ_ID_STATE;
sc.funcDoNothing(ctx, f);
ctx.log("testcore.funcDoNothing ok");
}
function funcGetMintedSupplyThunk(ctx: wasmlib.ScFuncContext): void {
ctx.log("testcore.funcGetMintedSupply");
let f = new sc.GetMintedSupplyContext();
f.results.mapID = wasmlib.OBJ_ID_RESULTS;
f.state.mapID = wasmlib.OBJ_ID_STATE;
sc.funcGetMintedSupply(ctx, f);
ctx.log("testcore.funcGetMintedSupply ok");
}
function funcIncCounterThunk(ctx: wasmlib.ScFuncContext): void {
ctx.log("testcore.funcIncCounter");
let f = new sc.IncCounterContext();
f.state.mapID = wasmlib.OBJ_ID_STATE;
sc.funcIncCounter(ctx, f);
ctx.log("testcore.funcIncCounter ok");
}
function funcInitThunk(ctx: wasmlib.ScFuncContext): void {
ctx.log("testcore.funcInit");
let f = new sc.InitContext();
f.params.mapID = wasmlib.OBJ_ID_PARAMS;
f.state.mapID = wasmlib.OBJ_ID_STATE;
sc.funcInit(ctx, f);
ctx.log("testcore.funcInit ok");
}
function funcPassTypesFullThunk(ctx: wasmlib.ScFuncContext): void {
ctx.log("testcore.funcPassTypesFull");
let f = new sc.PassTypesFullContext();
f.params.mapID = wasmlib.OBJ_ID_PARAMS;
f.state.mapID = wasmlib.OBJ_ID_STATE;
ctx.require(f.params.address().exists(), "missing mandatory address");
ctx.require(f.params.agentID().exists(), "missing mandatory agentID");
ctx.require(f.params.chainID().exists(), "missing mandatory chainID");
ctx.require(f.params.contractID().exists(), "missing mandatory contractID");
ctx.require(f.params.hash().exists(), "missing mandatory hash");
ctx.require(f.params.hname().exists(), "missing mandatory hname");
ctx.require(f.params.hnameZero().exists(), "missing mandatory hnameZero");
ctx.require(f.params.int64().exists(), "missing mandatory int64");
ctx.require(f.params.int64Zero().exists(), "missing mandatory int64Zero");
ctx.require(f.params.string().exists(), "missing mandatory string");
ctx.require(f.params.stringZero().exists(), "missing mandatory stringZero");
sc.funcPassTypesFull(ctx, f);
ctx.log("testcore.funcPassTypesFull ok");
}
function funcRunRecursionThunk(ctx: wasmlib.ScFuncContext): void {
ctx.log("testcore.funcRunRecursion");
let f = new sc.RunRecursionContext();
f.params.mapID = wasmlib.OBJ_ID_PARAMS;
f.results.mapID = wasmlib.OBJ_ID_RESULTS;
f.state.mapID = wasmlib.OBJ_ID_STATE;
ctx.require(f.params.intValue().exists(), "missing mandatory intValue");
sc.funcRunRecursion(ctx, f);
ctx.log("testcore.funcRunRecursion ok");
}
function funcSendToAddressThunk(ctx: wasmlib.ScFuncContext): void {
ctx.log("testcore.funcSendToAddress");
ctx.require(ctx.caller().equals(ctx.contractCreator()), "no permission");
let f = new sc.SendToAddressContext();
f.params.mapID = wasmlib.OBJ_ID_PARAMS;
f.state.mapID = wasmlib.OBJ_ID_STATE;
ctx.require(f.params.address().exists(), "missing mandatory address");
sc.funcSendToAddress(ctx, f);
ctx.log("testcore.funcSendToAddress ok");
}
function funcSetIntThunk(ctx: wasmlib.ScFuncContext): void {
ctx.log("testcore.funcSetInt");
let f = new sc.SetIntContext();
f.params.mapID = wasmlib.OBJ_ID_PARAMS;
f.state.mapID = wasmlib.OBJ_ID_STATE;
ctx.require(f.params.intValue().exists(), "missing mandatory intValue");
ctx.require(f.params.name().exists(), "missing mandatory name");
sc.funcSetInt(ctx, f);
ctx.log("testcore.funcSetInt ok");
}
function funcSpawnThunk(ctx: wasmlib.ScFuncContext): void {
ctx.log("testcore.funcSpawn");
let f = new sc.SpawnContext();
f.params.mapID = wasmlib.OBJ_ID_PARAMS;
f.state.mapID = wasmlib.OBJ_ID_STATE;
ctx.require(f.params.progHash().exists(), "missing mandatory progHash");
sc.funcSpawn(ctx, f);
ctx.log("testcore.funcSpawn ok");
}
function funcTestBlockContext1Thunk(ctx: wasmlib.ScFuncContext): void {
ctx.log("testcore.funcTestBlockContext1");
let f = new sc.TestBlockContext1Context();
f.state.mapID = wasmlib.OBJ_ID_STATE;
sc.funcTestBlockContext1(ctx, f);
ctx.log("testcore.funcTestBlockContext1 ok");
}
function funcTestBlockContext2Thunk(ctx: wasmlib.ScFuncContext): void {
ctx.log("testcore.funcTestBlockContext2");
let f = new sc.TestBlockContext2Context();
f.state.mapID = wasmlib.OBJ_ID_STATE;
sc.funcTestBlockContext2(ctx, f);
ctx.log("testcore.funcTestBlockContext2 ok");
}
function funcTestCallPanicFullEPThunk(ctx: wasmlib.ScFuncContext): void {
ctx.log("testcore.funcTestCallPanicFullEP");
let f = new sc.TestCallPanicFullEPContext();
f.state.mapID = wasmlib.OBJ_ID_STATE;
sc.funcTestCallPanicFullEP(ctx, f);
ctx.log("testcore.funcTestCallPanicFullEP ok");
}
function funcTestCallPanicViewEPFromFullThunk(ctx: wasmlib.ScFuncContext): void {
ctx.log("testcore.funcTestCallPanicViewEPFromFull");
let f = new sc.TestCallPanicViewEPFromFullContext();
f.state.mapID = wasmlib.OBJ_ID_STATE;
sc.funcTestCallPanicViewEPFromFull(ctx, f);
ctx.log("testcore.funcTestCallPanicViewEPFromFull ok");
}
function funcTestChainOwnerIDFullThunk(ctx: wasmlib.ScFuncContext): void {
ctx.log("testcore.funcTestChainOwnerIDFull");
let f = new sc.TestChainOwnerIDFullContext();
f.results.mapID = wasmlib.OBJ_ID_RESULTS;
f.state.mapID = wasmlib.OBJ_ID_STATE;
sc.funcTestChainOwnerIDFull(ctx, f);
ctx.log("testcore.funcTestChainOwnerIDFull ok");
}
function funcTestEventLogDeployThunk(ctx: wasmlib.ScFuncContext): void {
ctx.log("testcore.funcTestEventLogDeploy");
let f = new sc.TestEventLogDeployContext();
f.state.mapID = wasmlib.OBJ_ID_STATE;
sc.funcTestEventLogDeploy(ctx, f);
ctx.log("testcore.funcTestEventLogDeploy ok");
}
function funcTestEventLogEventDataThunk(ctx: wasmlib.ScFuncContext): void {
ctx.log("testcore.funcTestEventLogEventData");
let f = new sc.TestEventLogEventDataContext();
f.state.mapID = wasmlib.OBJ_ID_STATE;
sc.funcTestEventLogEventData(ctx, f);
ctx.log("testcore.funcTestEventLogEventData ok");
}
function funcTestEventLogGenericDataThunk(ctx: wasmlib.ScFuncContext): void {
ctx.log("testcore.funcTestEventLogGenericData");
let f = new sc.TestEventLogGenericDataContext();
f.params.mapID = wasmlib.OBJ_ID_PARAMS;
f.state.mapID = wasmlib.OBJ_ID_STATE;
ctx.require(f.params.counter().exists(), "missing mandatory counter");
sc.funcTestEventLogGenericData(ctx, f);
ctx.log("testcore.funcTestEventLogGenericData ok");
}
function funcTestPanicFullEPThunk(ctx: wasmlib.ScFuncContext): void {
ctx.log("testcore.funcTestPanicFullEP");
let f = new sc.TestPanicFullEPContext();
f.state.mapID = wasmlib.OBJ_ID_STATE;
sc.funcTestPanicFullEP(ctx, f);
ctx.log("testcore.funcTestPanicFullEP ok");
}
function funcWithdrawToChainThunk(ctx: wasmlib.ScFuncContext): void {
ctx.log("testcore.funcWithdrawToChain");
let f = new sc.WithdrawToChainContext();
f.params.mapID = wasmlib.OBJ_ID_PARAMS;
f.state.mapID = wasmlib.OBJ_ID_STATE;
ctx.require(f.params.chainID().exists(), "missing mandatory chainID");
sc.funcWithdrawToChain(ctx, f);
ctx.log("testcore.funcWithdrawToChain ok");
}
function viewCheckContextFromViewEPThunk(ctx: wasmlib.ScViewContext): void {
ctx.log("testcore.viewCheckContextFromViewEP");
let f = new sc.CheckContextFromViewEPContext();
f.params.mapID = wasmlib.OBJ_ID_PARAMS;
f.state.mapID = wasmlib.OBJ_ID_STATE;
ctx.require(f.params.agentID().exists(), "missing mandatory agentID");
ctx.require(f.params.chainID().exists(), "missing mandatory chainID");
ctx.require(f.params.chainOwnerID().exists(), "missing mandatory chainOwnerID");
ctx.require(f.params.contractCreator().exists(), "missing mandatory contractCreator");
sc.viewCheckContextFromViewEP(ctx, f);
ctx.log("testcore.viewCheckContextFromViewEP ok");
}
function viewFibonacciThunk(ctx: wasmlib.ScViewContext): void {
ctx.log("testcore.viewFibonacci");
let f = new sc.FibonacciContext();
f.params.mapID = wasmlib.OBJ_ID_PARAMS;
f.results.mapID = wasmlib.OBJ_ID_RESULTS;
f.state.mapID = wasmlib.OBJ_ID_STATE;
ctx.require(f.params.intValue().exists(), "missing mandatory intValue");
sc.viewFibonacci(ctx, f);
ctx.log("testcore.viewFibonacci ok");
}
function viewGetCounterThunk(ctx: wasmlib.ScViewContext): void {
ctx.log("testcore.viewGetCounter");
let f = new sc.GetCounterContext();
f.results.mapID = wasmlib.OBJ_ID_RESULTS;
f.state.mapID = wasmlib.OBJ_ID_STATE;
sc.viewGetCounter(ctx, f);
ctx.log("testcore.viewGetCounter ok");
}
function viewGetIntThunk(ctx: wasmlib.ScViewContext): void {
ctx.log("testcore.viewGetInt");
let f = new sc.GetIntContext();
f.params.mapID = wasmlib.OBJ_ID_PARAMS;
f.results.mapID = wasmlib.OBJ_ID_RESULTS;
f.state.mapID = wasmlib.OBJ_ID_STATE;
ctx.require(f.params.name().exists(), "missing mandatory name");
sc.viewGetInt(ctx, f);
ctx.log("testcore.viewGetInt ok");
}
function viewGetStringValueThunk(ctx: wasmlib.ScViewContext): void {
ctx.log("testcore.viewGetStringValue");
let f = new sc.GetStringValueContext();
f.params.mapID = wasmlib.OBJ_ID_PARAMS;
f.results.mapID = wasmlib.OBJ_ID_RESULTS;
f.state.mapID = wasmlib.OBJ_ID_STATE;
ctx.require(f.params.varName().exists(), "missing mandatory varName");
sc.viewGetStringValue(ctx, f);
ctx.log("testcore.viewGetStringValue ok");
}
function viewJustViewThunk(ctx: wasmlib.ScViewContext): void {
ctx.log("testcore.viewJustView");
let f = new sc.JustViewContext();
f.state.mapID = wasmlib.OBJ_ID_STATE;
sc.viewJustView(ctx, f);
ctx.log("testcore.viewJustView ok");
}
function viewPassTypesViewThunk(ctx: wasmlib.ScViewContext): void {
ctx.log("testcore.viewPassTypesView");
let f = new sc.PassTypesViewContext();
f.params.mapID = wasmlib.OBJ_ID_PARAMS;
f.state.mapID = wasmlib.OBJ_ID_STATE;
ctx.require(f.params.address().exists(), "missing mandatory address");
ctx.require(f.params.agentID().exists(), "missing mandatory agentID");
ctx.require(f.params.chainID().exists(), "missing mandatory chainID");
ctx.require(f.params.contractID().exists(), "missing mandatory contractID");
ctx.require(f.params.hash().exists(), "missing mandatory hash");
ctx.require(f.params.hname().exists(), "missing mandatory hname");
ctx.require(f.params.hnameZero().exists(), "missing mandatory hnameZero");
ctx.require(f.params.int64().exists(), "missing mandatory int64");
ctx.require(f.params.int64Zero().exists(), "missing mandatory int64Zero");
ctx.require(f.params.string().exists(), "missing mandatory string");
ctx.require(f.params.stringZero().exists(), "missing mandatory stringZero");
sc.viewPassTypesView(ctx, f);
ctx.log("testcore.viewPassTypesView ok");
}
function viewTestCallPanicViewEPFromViewThunk(ctx: wasmlib.ScViewContext): void {
ctx.log("testcore.viewTestCallPanicViewEPFromView");
let f = new sc.TestCallPanicViewEPFromViewContext();
f.state.mapID = wasmlib.OBJ_ID_STATE;
sc.viewTestCallPanicViewEPFromView(ctx, f);
ctx.log("testcore.viewTestCallPanicViewEPFromView ok");
}
function viewTestChainOwnerIDViewThunk(ctx: wasmlib.ScViewContext): void {
ctx.log("testcore.viewTestChainOwnerIDView");
let f = new sc.TestChainOwnerIDViewContext();
f.results.mapID = wasmlib.OBJ_ID_RESULTS;
f.state.mapID = wasmlib.OBJ_ID_STATE;
sc.viewTestChainOwnerIDView(ctx, f);
ctx.log("testcore.viewTestChainOwnerIDView ok");
}
function viewTestPanicViewEPThunk(ctx: wasmlib.ScViewContext): void {
ctx.log("testcore.viewTestPanicViewEP");
let f = new sc.TestPanicViewEPContext();
f.state.mapID = wasmlib.OBJ_ID_STATE;
sc.viewTestPanicViewEP(ctx, f);
ctx.log("testcore.viewTestPanicViewEP ok");
}
function viewTestSandboxCallThunk(ctx: wasmlib.ScViewContext): void {
ctx.log("testcore.viewTestSandboxCall");
let f = new sc.TestSandboxCallContext();
f.results.mapID = wasmlib.OBJ_ID_RESULTS;
f.state.mapID = wasmlib.OBJ_ID_STATE;
sc.viewTestSandboxCall(ctx, f);
ctx.log("testcore.viewTestSandboxCall ok");
} | the_stack |
import React, { useRef, useEffect, useState } from 'react';
import { MDXProvider } from '@mdx-js/react';
import {
Title,
Text,
List,
ListItem,
Button,
ButtonRow,
TextArea,
} from '@thumbtack/thumbprint-react';
import * as tokens from '@thumbtack/thumbprint-tokens';
import { ScrollMarkerSection } from 'react-scroll-marker';
import InternalMDXRenderer from 'gatsby-plugin-mdx/mdx-renderer';
import { isString } from 'lodash';
import uuid from 'uuid';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import invariant from 'invariant';
import { Language } from 'prism-react-renderer';
import Wrap from '../wrap';
import PageHeader from '../page-header';
import Container from '../container';
import CodeBlock from './code-block';
import generateSlug from '../generate-slug';
import styles from './index.module.scss';
const HashAnchor = ({ children, id }: { children: React.ReactNode; id: string }): JSX.Element => (
<div className={styles.hashAnchor}>
<a href={`#${id}`} aria-hidden="true" className={styles.hashAnchorLink}>
<svg
aria-hidden="true"
viewBox="0 0 16 16"
height="16"
width="16"
fill={tokens.tpColorBlack300}
>
<path d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z" />
</svg>
</a>
{children}
</div>
);
export function H2(p: Parameters<typeof Title>[0]): JSX.Element {
return (
<ScrollMarkerSection id={generateSlug({ level: 'section', children: p.children }) || ''}>
{({ id }: { id: string }): JSX.Element => (
<HashAnchor id={id}>
<Title {...p} id={id} size={3} headingLevel={2} className="mt6 mb3" />
</HashAnchor>
)}
</ScrollMarkerSection>
);
}
export function H3(p: Parameters<typeof Title>[0]): JSX.Element {
const id = generateSlug({ level: 'example', children: p.children }) || '';
return (
<HashAnchor id={id}>
<Title {...p} id={id} size={5} headingLevel={3} className="mt5 mb2" />
</HashAnchor>
);
}
export function H4(p: Parameters<typeof Title>[0]): JSX.Element {
return (
<Title
{...p}
id={generateSlug({ level: 'example', children: p.children })}
size={6}
headingLevel={4}
className="mt5 mb1"
/>
);
}
export function P(p: Parameters<typeof Text>[0]): JSX.Element {
return <Text {...p} className={`mb3 black-300 ${styles.readingWidth}`} />;
}
export const InlineCode = ({
shouldCopyToClipboard = false,
children,
theme = 'default',
}: {
shouldCopyToClipboard?: boolean;
children?: React.ReactNode;
theme?: 'plain' | 'default';
}): JSX.Element => {
const plainStyles = {
fontFamily: tokens.tpFontFamilyMonospace,
fontSize: '95%',
};
const extendedStyles = {
background: '#f5f7f7',
padding: '1px 4px',
color: tokens.tpColorBlack,
borderRadius: '5px',
};
let inlineStyles = plainStyles;
if (theme !== 'plain') {
inlineStyles = { ...plainStyles, ...extendedStyles };
}
return shouldCopyToClipboard ? (
<CopyToClipboard text={children} className={styles.inlineCodeClipboard}>
<code style={inlineStyles}>{children}</code>
</CopyToClipboard>
) : (
<code style={inlineStyles}>{children}</code>
);
};
export function Pre(p: React.HTMLAttributes<HTMLDivElement>): JSX.Element {
return <div {...p} />;
}
export function LI(p: Parameters<typeof Text>[0]): JSX.Element {
return (
<ListItem>
<Text elementName="div" className={`black-300 ${styles.readingWidth}`} {...p} />
</ListItem>
);
}
export function OL(p: Parameters<typeof List>[0]): JSX.Element {
return (
<div className="mb3 ml4">
<List theme="decimal" {...p} />
</div>
);
}
export function UL(p: Parameters<typeof List>[0]): JSX.Element {
return (
<div className="mb3 ml4">
<List {...p} />
</div>
);
}
export function Code(p: {
className: string;
theme: 'white' | 'dark' | 'light';
shouldRender: 'true' | 'false';
children: string;
}): JSX.Element {
const language = p.className
? ((p.className.replace('language-', '') as unknown) as Language)
: undefined;
return (
<CodeBlock language={language} theme={p.theme} shouldRender={p.shouldRender !== 'false'}>
{p.children}
</CodeBlock>
);
}
export function Table(p: React.TableHTMLAttributes<HTMLTableElement>): JSX.Element {
return <table {...p} className="mb5 w-100 black-300" />;
}
export function TH(p: React.TableHTMLAttributes<HTMLTableHeaderCellElement>): JSX.Element {
return <th {...p} className="ph2 pb2 bb b-gray-300 tl" />;
}
export function TD(p: React.TableHTMLAttributes<HTMLTableDataCellElement>): JSX.Element {
return <td {...p} className="pa2 bb b-gray-300" />;
}
export function Img(p: React.ImgHTMLAttributes<HTMLImageElement>): JSX.Element {
return (
<img
src={p.src}
alt={p.alt}
className={p.className}
width={p.width}
height={p.height}
style={{ display: 'block', maxWidth: '100%' }}
/>
);
}
export function HR(p: React.HTMLAttributes<HTMLHRElement>): JSX.Element {
return <hr {...p} className="bt b-gray-300 mv4" style={{ height: '0', border: '0' }} />;
}
export function Iframe(p: React.IframeHTMLAttributes<HTMLIFrameElement>): JSX.Element {
return (
<iframe
{...p}
className="pa1 mb1 ba bw-2 br2 b-gray-300"
title="Image of component from Figma"
/>
);
}
export const MDXRenderer = ({ children }: { children: React.ReactNode }): JSX.Element => {
let renderedChildren = children;
if (isString(renderedChildren)) {
renderedChildren = <InternalMDXRenderer>{children}</InternalMDXRenderer>;
}
return (
<MDXProvider
components={{
h2: H2,
h3: H3,
h4: H4,
p: P,
inlineCode: InlineCode,
pre: Pre,
li: LI,
ol: OL,
ul: UL,
img: Img,
code: (p): JSX.Element => <Code {...p} />,
table: Table,
td: TD,
th: TH,
hr: HR,
iframe: Iframe,
}}
>
{renderedChildren}
</MDXProvider>
);
};
type Platform = 'React' | 'JavaScript' | 'SCSS' | 'Usage' | 'iOS' | 'Android';
const getPlatformByPathname = (pathname: string): Platform => {
const mappings: Record<string, Platform> = {
react: 'React',
javascript: 'JavaScript',
scss: 'SCSS',
usage: 'Usage',
ios: 'iOS',
android: 'Android',
};
const splitPathname = pathname.split('/');
// If input is `/components/button/react/`, this gets the word `react`.
const platformSlug = splitPathname[splitPathname.length - 2];
// Fail loudly so developers know they need to update the mapping.
invariant(
platformSlug,
`The first part of the pathname \`${pathname}\` does not have a platform name mapped to it. Add one to the \`mappings\` object in this function.`,
);
return mappings[platformSlug];
};
type Section =
| 'Overview'
| 'Guidelines'
| 'Components'
| 'Atomic'
| 'Tokens'
| 'Icons'
| 'Updates'
| 'Help';
const getSectionByPathname = (pathname: string): Section => {
// This needs to be updated if a new section is added or a section is renamed.
const mappings: Record<string, Section> = {
overview: 'Overview',
guide: 'Guidelines',
components: 'Components',
atomic: 'Atomic',
tokens: 'Tokens',
icons: 'Icons',
updates: 'Updates',
help: 'Help',
};
// If input is `/guide/product/brand-assets/`, this gets the word `guide`.
const firstPartOfPathname = pathname.split('/')[1];
const displayName = mappings[firstPartOfPathname];
// Fail loudly so developers know they need to update the mapping.
invariant(
displayName,
`The first part of the pathname \`${pathname}\` does not have a display name mapped to it. Add one to the \`mappings\` object in this function.`,
);
return displayName;
};
type FeedbackStep = 'feedback-score' | 'feedback-comment' | 'feedback-complete';
const FEEDBACK_STEPS: Record<FeedbackStep, FeedbackStep> = {
'feedback-score': 'feedback-score',
'feedback-comment': 'feedback-comment',
'feedback-complete': 'feedback-complete',
};
const FeedbackForm = ({ page }: { page: string }): JSX.Element => {
// Track the current step in the feedback flow.
const [feedbackStep, setFeedbackStep] = useState<FeedbackStep>(
FEEDBACK_STEPS['feedback-score'],
);
// "Yes" or "No" values
const [feedbackScore, setFeedbackScore] = useState<string>('');
// Freeform comment box for additional feedback
const [feedbackComment, setFeedbackComment] = useState<string>('');
const feebackScoreFormEl = useRef<HTMLFormElement>(null);
// We send the feedback to Netlify in two steps because we want to record a
// "Yes" or "No" even if the user doesn't leave a comment. Netlify doesn't
// allow us to update an existing form response, so we generate a UUID
// that we can later use to associate a score ("Yes"/"No") with a
// free-form comment. Storing it with `useRef` prevents the value from
// changing if the component re-renders.
const feedbackResponseId = useRef(uuid.v1());
// Submit the feedback programatically here instead of the form's
// `onSubmit`. This is because the "Yes" and "No" buttons are
// `<Button>` components. When clicked, they update an
// `input[hidden]` value. Putting the value in the hidden input
// allows us to easily include it in the form submission.
useEffect(() => {
if (feedbackScore) {
const form = feebackScoreFormEl.current;
if (!form) {
return;
}
// Unfortunately TypeScript's DOM types do not yet recognise FormData as a valid
// argument to URLSearchParams. Cast here to avoid an error
// See: https://github.com/Microsoft/TypeScript/issues/30584
const data = new URLSearchParams((new FormData(form) as unknown) as string).toString();
fetch(form.action, {
method: 'POST',
body: data,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
}).then(() => {
setFeedbackStep(FEEDBACK_STEPS['feedback-comment']);
});
}
}, [feedbackScore]);
// This helps prevent spam submissions:
// https://docs.netlify.com/forms/spam-filters/#honeypot-field
const honeypotInputName = 'netlify-trickyness';
return (
<>
<form
name="feedback-scores"
method="POST"
data-netlify="true"
netlify-honeypot={honeypotInputName}
ref={feebackScoreFormEl}
hidden={feedbackStep !== FEEDBACK_STEPS['feedback-score']}
>
<div className={`flex items-center flex-column m_flex-row ${styles.readingWidth}`}>
<div className="mb3 m_mb0 m_mr4">
<Title size={5} className="mb2">
Was this page helpful?
</Title>
<Text className="black-300 mw7">
We use this feedback to improve the quality of our documentation.
</Text>
</div>
<ButtonRow>
<Button
size="small"
theme="tertiary"
onClick={(): void => setFeedbackScore('yes')}
>
Yes
</Button>
<Button
size="small"
theme="tertiary"
onClick={(): void => setFeedbackScore('no')}
>
No
</Button>
</ButtonRow>
</div>
<input type="hidden" name="page" value={page} />
<input type="hidden" name="response-id" value={feedbackResponseId.current} />
<input type="text" className="visually-hidden" name={honeypotInputName} />
<input type="hidden" name="helpful" value={feedbackScore} />
<input type="hidden" name="form-name" value="feedback-scores" />
</form>
<form
name="feedback-comments"
method="POST"
data-netlify="true"
onSubmit={(e: React.FormEvent<HTMLFormElement>): void => {
// Show a success message (but don't send data to Netlify)
// if the user clicks on "Send" with an empty text area.
// The user may hit send without adding comments because they
// may not have realized that their answer to the first step
// of this two step form was already recorded.
if (feedbackComment === '') {
setFeedbackStep(FEEDBACK_STEPS['feedback-complete']);
return;
}
e.preventDefault();
const form = e.target as HTMLFormElement;
const data = new URLSearchParams(
(new FormData(form) as unknown) as string,
).toString();
fetch(form.action, {
method: 'POST',
body: data,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
}).then(() => {
setFeedbackStep(FEEDBACK_STEPS['feedback-complete']);
});
}}
hidden={feedbackStep !== FEEDBACK_STEPS['feedback-comment']}
>
<div className={`mb3 ${styles.readingWidth}`}>
<Title size={5} className="mb2">
Was this page helpful?
</Title>
<label htmlFor="feedback-comments">
<Text className="black-300 mw7">
{feedbackScore === 'yes' &&
'Thanks! We’re glad you found it helpful. You can optionally let us know what you liked about this page.'}
{feedbackScore === 'no' &&
'Sorry to hear that! How can we improve this page?'}{' '}
</Text>
</label>
</div>
<div className="mb3 mw7">
<TextArea
onChange={(v): void => setFeedbackComment(v)}
value={feedbackComment}
name="comment"
id="feedback-comments"
/>
</div>
<input type="hidden" name="page" value={page} />
<input type="hidden" name="form-name" value="feedback-comments" />
<input type="hidden" name="response-id" value={feedbackResponseId.current} />
<Button theme="primary" size="small" type="submit">
Send
</Button>
</form>
{feedbackStep === FEEDBACK_STEPS['feedback-complete'] && (
<div className={`mb3 ${styles.readingWidth}`}>
<Title size={5} className="mb2">
Was this page helpful?
</Title>
<Text className="black-300 mw7">
Thanks! We’ve submitted your feedback.{' '}
<span role="img" aria-label="">
🎉
</span>
</Text>
</div>
)}
</>
);
};
interface MdxPropTypes {
children: React.ReactNode;
location: { pathname: string };
pageContext: {
frontmatter: {
title: string;
description: string;
};
};
header?: React.ReactNode;
}
export default function MDX({
children,
location,
pageContext,
header,
}: MdxPropTypes): JSX.Element {
// Add the platform name to the page title when on a page within `components/` that has a
// platform.
const isComponentOrTokensPage =
(location.pathname.startsWith('/components/') ||
location.pathname.startsWith('/tokens/')) &&
getPlatformByPathname(location.pathname);
const pageTitle = isComponentOrTokensPage ? (
<span>
{pageContext.frontmatter.title}
<span className="visually-hidden">
{`(${getPlatformByPathname(location.pathname)})`}
</span>
</span>
) : (
pageContext.frontmatter.title
);
const metaTitle = isComponentOrTokensPage
? `${pageContext.frontmatter.title} (${getPlatformByPathname(location.pathname)})`
: pageContext.frontmatter.title;
return (
<Container location={location} activeSection={getSectionByPathname(location.pathname)}>
<Wrap>
{pageContext.frontmatter && (
<React.Fragment>
<PageHeader
pageTitle={pageTitle}
metaTitle={metaTitle}
description={pageContext.frontmatter.description}
/>
{header}
<MDXRenderer>{children}</MDXRenderer>
<div className="pt5 mt5 bt bw-2 b-gray-300">
<FeedbackForm page={location.pathname} />
</div>
</React.Fragment>
)}
</Wrap>
</Container>
);
} | the_stack |
import { createStyleProvider } from "./builder";
import { EnumTextTransform, EnumTextDecorationLine } from "./builder/types";
import { Platform } from "react-native";
import { getPlatformFontWeight } from "./builder/utils";
export const Colors = {
primary: "#4762E7",
"primary-10": "#F1F3FC",
"primary-50": "#E2E8FF",
"primary-100": "#B3BEF7",
"primary-200": "#8E9FF2",
"primary-300": "#7388F0",
"primary-400": "#4762E7",
"primary-500": "#2644DB",
"primary-600": "#102FCB",
"primary-700": "#0320B4",
"primary-800": "#001A9A",
"primary-900": "#00157D",
secondary: "#FF63B4",
"secondary-50": "#FCD1F4",
"secondary-100": "#F3B1E1",
"secondary-200": "#FA9DD9",
"secondary-300": "#FF86CE",
"secondary-400": "#FF63B4",
"secondary-500": "#E753A8",
"secondary-600": "#C84699",
"secondary-700": "#A23A83",
"secondary-800": "#762C64",
"secondary-900": "#471D40",
danger: "#F5365C",
"danger-10": "#FFF1F4",
"danger-50": "#FFD8E0",
"danger-100": "#FFBCC9",
"danger-200": "#FC91A6",
"danger-300": "#FD5778",
"danger-400": "#F5365C",
"danger-500": "#DD1E44",
"danger-600": "#BC1638",
"danger-700": "#9A0F2A",
"danger-800": "#810A22",
"danger-900": "#65081B",
"profile-sky-blue": "#80CAFF",
"profile-mint": "#47DDE7",
"profile-green": "#78F0C5",
"profile-yellow-green": "#ADE353",
"profile-purple": "#D378FE",
"profile-red": "#FF6D88",
"profile-orange": "#FEC078",
"profile-yellow": "#F2ED64",
icon: "#2C4163",
card: "rgba(255,255,255,0.95)",
success: "#2DCE89",
error: "#F5365C",
"text-black-very-high": "#030C1D",
"text-black-high": "#132340",
"text-black-medium": "#2C4163",
"text-black-low": "#83838F",
"text-black-very-low": "#899BB6",
"text-black-very-very-low": "#C6C6CD",
"text-black-very-very-very-low": "#DCDCE3",
"border-gray": "#C6C6CD",
"border-white": "#F5F5F5",
white: "#fff",
black: "#000",
disabled: "#EEEEF3",
divider: "#F5F5F5",
transparent: "rgba(255,255,255,0)",
"modal-backdrop": "rgba(9,18,50,0.6)",
"card-modal-handle": "#DCDCE3",
"setting-screen-background": "#FAFBFD",
"camera-loading-background": "rgba(255,255,255,0.95)",
"big-image-placeholder": "#E7E4EF",
"chain-list-element-dragging": "rgba(242, 242, 247, 0.8)",
};
export const { StyleProvider, useStyle } = createStyleProvider({
custom: {
h1: {
fontSize: 32,
lineHeight: 56,
letterSpacing: 0.3,
...getPlatformFontWeight("700"),
},
h2: {
fontSize: 28,
lineHeight: 36,
letterSpacing: 0.3,
...getPlatformFontWeight("700"),
},
h3: {
fontSize: 24,
lineHeight: 32,
letterSpacing: 0.3,
...getPlatformFontWeight("700"),
},
h4: {
fontSize: 20,
lineHeight: 28,
letterSpacing: 0.3,
...getPlatformFontWeight("600"),
},
h5: {
fontSize: 18,
lineHeight: 24,
letterSpacing: 0.3,
...getPlatformFontWeight("600"),
},
h6: {
fontSize: 16,
lineHeight: 22,
letterSpacing: 0.2,
...getPlatformFontWeight("600"),
},
h7: {
fontSize: 14,
lineHeight: 20,
letterSpacing: 0.2,
...getPlatformFontWeight("600"),
},
subtitle1: {
fontSize: 18,
lineHeight: 24,
...getPlatformFontWeight("500"),
},
subtitle2: {
fontSize: 16,
lineHeight: 22,
...getPlatformFontWeight("500"),
},
subtitle3: {
fontSize: 14,
lineHeight: 21,
letterSpacing: 0.1,
...getPlatformFontWeight("500"),
},
body1: {
fontSize: 18,
lineHeight: 26,
...getPlatformFontWeight("400"),
},
body2: {
fontSize: 16,
lineHeight: 22,
letterSpacing: 0.1,
...getPlatformFontWeight("400"),
},
body3: {
fontSize: 14,
lineHeight: 20,
letterSpacing: 0.1,
...getPlatformFontWeight("400"),
},
"text-button1": {
fontSize: 18,
lineHeight: 20,
letterSpacing: 0.2,
...getPlatformFontWeight("600"),
},
"text-button2": {
fontSize: 16,
lineHeight: 19,
letterSpacing: 0.2,
...getPlatformFontWeight("600"),
},
"text-button3": {
fontSize: 14,
lineHeight: 18,
letterSpacing: 0.2,
textTransform: "capitalize" as EnumTextTransform,
...getPlatformFontWeight("600"),
},
"text-caption1": {
fontSize: 13,
lineHeight: 18,
letterSpacing: 0.3,
...getPlatformFontWeight("400"),
},
"text-caption2": {
fontSize: 12,
lineHeight: 18,
letterSpacing: 0.3,
...getPlatformFontWeight("400"),
},
"text-overline": {
fontSize: 11,
lineHeight: 16,
letterSpacing: 0.5,
textTransform: "uppercase" as EnumTextTransform,
...getPlatformFontWeight("400"),
},
"text-underline": {
textDecorationLine: "underline" as EnumTextDecorationLine,
},
// This style is for the text input and aims to mock the body2 style.
// In IOS, it is hard to position the input text to the middle vertically.
// So, to solve this problem, decrease the line height and add the additional vertical padding.
"body2-in-text-input": Platform.select({
ios: {
fontSize: 16,
lineHeight: 19,
letterSpacing: 0.25,
paddingTop: 1.5,
paddingBottom: 1.5,
...getPlatformFontWeight("400"),
},
android: {
fontSize: 16,
lineHeight: 22,
letterSpacing: 0.25,
...getPlatformFontWeight("400"),
},
}),
},
colors: {
...Colors,
...{
"splash-background": "#FBF8FF",
// Belows are for the button props and may not be used as styles.
"rect-button-default-ripple": "#CCCCCC",
// Active opacity is 0.055 by default.
"rect-button-default-underlay": Colors["text-black-medium"],
"drawer-rect-button-underlay": "#F1F3FC",
// Belows are for the button props and may not be used as styles.
"button-primary": Colors.primary,
"button-secondary": Colors.secondary,
"button-danger": Colors.danger,
"button-primary-text-pressed": Colors["primary-500"],
"button-secondary-text-pressed": Colors["secondary-500"],
"button-danger-text-pressed": Colors["danger-500"],
"button-primary-disabled": Colors["text-black-very-very-low"],
"button-secondary-disabled": Colors["text-black-very-very-low"],
"button-danger-disabled": Colors["text-black-very-very-low"],
"button-primary-light": Colors["primary-50"],
"button-secondary-light": Colors["secondary-50"],
"button-danger-light": Colors["danger-50"],
// For Android, note that you can't set the opacity of the ripple color.
"button-primary-fill-ripple": Colors["primary-600"],
"button-primary-light-ripple": Colors["primary-100"],
"button-primary-outline-ripple": Colors["primary-100"],
"button-secondary-fill-ripple": Colors["secondary-600"],
"button-secondary-light-ripple": Colors["secondary-100"],
"button-secondary-outline-ripple": Colors["secondary-100"],
"button-danger-fill-ripple": Colors["danger-600"],
"button-danger-light-ripple": Colors["danger-100"],
"button-danger-outline-ripple": Colors["danger-100"],
// For IOS, note that we just set the active opacity as 1, thus, unlike Android, it is opaque.
"button-primary-fill-underlay": Colors["primary-500"],
"button-primary-light-underlay": Colors["primary-100"],
"button-primary-outline-underlay": Colors["primary-50"],
"button-secondary-fill-underlay": Colors["secondary-500"],
"button-secondary-light-underlay": Colors["secondary-100"],
"button-secondary-outline-underlay": Colors["secondary-50"],
"button-danger-fill-underlay": Colors["danger-500"],
"button-danger-light-underlay": Colors["danger-100"],
"button-danger-outline-underlay": Colors["danger-50"],
// Belows are for the chip props and may not be used as styles.
"chip-light-primary": Colors["primary-50"],
"chip-light-secondary": Colors["secondary-50"],
"chip-light-danger": Colors["danger-100"],
// Belows are for the loading spinner props and may not be used as styles.
"loading-spinner": Colors["text-black-low"],
},
},
widths: {
full: "100%",
half: "50%",
"1": 1,
"4": 4,
"8": 8,
"12": 12,
"16": 16,
"20": 20,
"24": 24,
"32": 32,
"34": 34,
"36": 36,
"38": 38,
"40": 40,
"44": 44,
"54": 54,
"56": 56,
"58": 58,
"72": 72,
"80": 80,
"122": 122,
"160": 160,
"240": 240,
"292": 292,
"300": 300,
"card-gap": 12,
"page-pad": 20,
},
heights: {
full: "100%",
half: "50%",
"0.5": 0.5,
"1": 1,
"4": 4,
"5": 5,
"8": 8,
"12": 12,
"16": 16,
"18": 18,
"20": 20,
"24": 24,
"30": 30,
"32": 32,
"36": 36,
"38": 38,
"40": 40,
"44": 44,
"50": 50,
"56": 56,
"58": 58,
"62": 62,
"66": 66,
"64": 64,
"72": 72,
"74": 74,
"80": 80,
"83": 83,
"84": 84,
"87": 87,
"90": 90,
"104": 104,
"116": 116,
"122": 122,
"214": 214,
"400": 400,
"600": 600,
"button-small": 38,
"button-default": 48,
"button-large": 52,
"governance-card-body-placeholder": 130,
"card-gap": 12,
"page-pad": 20,
},
paddingSizes: {
"0": 0,
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"8": 8,
"10": 10,
"11": 11,
"12": 12,
"14": 14,
"15": 15,
"16": 16,
"18": 18,
"20": 20,
"22": 22,
"24": 24,
"25.5": 25.5,
"26": 26,
"28": 28,
"31": 31,
"32": 32,
"36": 36,
"38": 38,
"40": 40,
"42": 42,
"48": 48,
"52": 52,
"64": 64,
"66": 66,
page: 20,
"card-horizontal": 20,
"card-vertical": 20,
"card-vertical-half": 10,
"card-gap": 12,
},
marginSizes: {
"0": 0,
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"6": 6,
"8": 8,
"10": 10,
"12": 12,
"14": 14,
"15": 15,
"16": 16,
"18": 18,
"20": 20,
"21": 21,
"24": 24,
"28": 28,
"30": 30,
"32": 32,
"34": 34,
"38": 38,
"40": 40,
"44": 44,
"46": 46,
"48": 48,
"58": 58,
"64": 64,
"68": 68,
"82": 82,
"87": 87,
"88": 88,
"92": 92,
"102": 102,
"106": 106,
"150": 150,
"288": 288,
page: 20,
"card-horizontal": 20,
"card-vertical": 20,
"card-gap": 12,
},
borderWidths: {
"0": 0,
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"6": 6,
"8": 8,
"12": 12,
"16": 16,
"32": 32,
"64": 64,
},
borderRadiuses: {
"0": 0,
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"6": 6,
"8": 8,
"12": 12,
"16": 16,
"32": 32,
"64": 64,
},
opacities: {
transparent: 0,
"10": 0.1,
"20": 0.2,
"30": 0.3,
"40": 0.4,
"50": 0.5,
"60": 0.6,
"70": 0.7,
"80": 0.8,
"90": 0.9,
"100": 1,
},
}); | the_stack |
import {
AbstractContract,
RevertError,
expect,
encodeMetaTransferFromData,
encodeMetaBatchTransferFromData,
encodeMetaApprovalData,
GasReceiptType,
ethSign,
createTestWallet
} from './utils'
import { BigNumber, utils, ContractTransaction, EventFilter } from 'ethers'
import {
ERC1155MetaMintBurnMock,
ERC1271WalletValidationMock,
ERC1155ReceiverMock,
ERC1155OperatorMock,
ERC20Mock
} from 'src/gen/typechain'
import { GasReceipt, TransferSignature, ApprovalSignature, BatchTransferSignature } from 'src/typings/tx-types'
// init test wallets from package.json mnemonic
import { web3 } from 'hardhat'
const { wallet: ownerWallet, provider: ownerProvider, signer: ownerSigner } = createTestWallet(web3, 1)
const { wallet: receiverWallet, provider: receiverProvider, signer: receiverSigner } = createTestWallet(web3, 2)
const { wallet: operatorWallet, provider: operatorProvider, signer: operatorSigner } = createTestWallet(web3, 4)
// Lower polling interval for faster tx send
ownerProvider.pollingInterval = 1000
operatorProvider.pollingInterval = 1000
receiverProvider.pollingInterval = 1000
describe('ERC1155Meta', () => {
const MAXVAL = BigNumber.from(2)
.pow(256)
.sub(1) // 2**256 - 1
const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'
const DOMAIN_SEPARATOR_TYPEHASH = '0x035aff83d86937d35b32e04f0ddc6ff469290eef2f1b692d8a815c89404d4749'
// Pass gas since ganache can't figure it out
const TX_PARAM = { gasLimit: 2000000 }
let ownerAddress: string
let receiverAddress: string
let operatorAddress: string
let erc1155Abstract: AbstractContract
let operatorAbstract: AbstractContract
let erc1155Contract: ERC1155MetaMintBurnMock
let operatorERC1155Contract: ERC1155MetaMintBurnMock
let receiverERC1155Contract: ERC1155MetaMintBurnMock
// load contract abi and deploy to test server
before(async () => {
ownerAddress = await ownerWallet.getAddress()
receiverAddress = await receiverWallet.getAddress()
operatorAddress = await operatorWallet.getAddress()
erc1155Abstract = await AbstractContract.fromArtifactName('ERC1155MetaMintBurnMock')
operatorAbstract = await AbstractContract.fromArtifactName('ERC1155OperatorMock')
})
// deploy before each test, to reset state of contract
beforeEach(async () => {
erc1155Contract = (await erc1155Abstract.deploy(ownerWallet)) as ERC1155MetaMintBurnMock
operatorERC1155Contract = (await erc1155Contract.connect(operatorSigner)) as ERC1155MetaMintBurnMock
receiverERC1155Contract = (await erc1155Contract.connect(receiverSigner)) as ERC1155MetaMintBurnMock
})
describe('metaSafeTransferFrom() (Meta) Function', () => {
let receiverContract: ERC1155ReceiverMock
let operatorContract: ERC1155OperatorMock
let transferData: string | null = 'Hello from the other side'
const initBalance = 100
const amount = 10
const nonce = BigNumber.from(0)
const id = 66
const feeTokenID = 666
let isGasReceipt: boolean = true
const feeTokenInitBalance = BigNumber.from(100000000)
const feeType = 0 // ERC-1155
let feeTokenAddress: string
let feeTokenDataERC1155: string | Uint8Array
let transferObj: TransferSignature
let domainHash: string
let gasReceipt: GasReceipt | null
let data: string
const conditions = [
[transferData, true, 'Gas receipt & transfer data'],
[null, true, 'Gas receipt w/o transfer data'],
[transferData, false, 'Transfer data w/o gas receipt '],
[null, false, 'No Gas receipt & No transfer data']
]
conditions.forEach(function(condition) {
context(condition[2] as string, () => {
beforeEach(async () => {
// Get conditions
transferData = condition[0] as string | null
isGasReceipt = condition[1] as boolean
// Deploy contracts
const abstract = await AbstractContract.fromArtifactName('ERC1155ReceiverMock')
receiverContract = (await abstract.deploy(ownerWallet)) as ERC1155ReceiverMock
operatorContract = (await operatorAbstract.deploy(operatorWallet)) as ERC1155OperatorMock
feeTokenAddress = erc1155Contract.address
feeTokenDataERC1155 = utils.defaultAbiCoder.encode(
['address', 'uint256', 'uint8'],
[feeTokenAddress, feeTokenID, feeType]
)
// Gas Receipt
gasReceipt = {
gasLimitCallback: 130000,
gasFee: 30000,
feeRecipient: operatorAddress,
feeTokenData: feeTokenDataERC1155
}
// Check if gas receipt is included
gasReceipt = isGasReceipt ? gasReceipt : null
// Transfer Signature Object
transferObj = {
contractAddress: erc1155Contract.address,
signerWallet: ownerWallet,
receiver: receiverAddress,
id: id,
amount: amount,
isGasFee: isGasReceipt,
transferData: transferData === null ? null : utils.toUtf8Bytes(transferData),
nonce: nonce
}
// Mint tokens
await erc1155Contract.mintMock(ownerAddress, id, initBalance, [])
// Mint tokens used to pay for gas
await erc1155Contract.mintMock(ownerAddress, feeTokenID, feeTokenInitBalance, [])
// Domain hash
domainHash = utils.keccak256(
utils.solidityPack(['bytes32', 'uint256'], [DOMAIN_SEPARATOR_TYPEHASH, erc1155Contract.address])
)
// Data to pass in transfer method
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
})
it("should REVERT if data is 'random", async () => {
const dataUint8 = utils.toUtf8Bytes('Breakthroughs! over the river! flips and crucifixions! gone down the flood!')
const data = BigNumber.from(dataUint8).toHexString()
// Check if data length is more than 69
expect(utils.arrayify(data).length).to.be.at.least(70)
const tx = erc1155Contract.metaSafeTransferFrom(ownerAddress, receiverContract.address, id, amount, isGasReceipt, data)
await expect(tx).to.be.rejectedWith(RevertError())
})
it('should REVERT if contract address is incorrect', async () => {
// Domain hash
domainHash = utils.keccak256(
utils.solidityPack(['bytes32', 'uint256'], [DOMAIN_SEPARATOR_TYPEHASH, receiverContract.address])
)
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeTransferFrom(ownerAddress, receiverAddress, id, amount, isGasReceipt, data)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should REVERT if signer address is incorrect', async () => {
transferObj.signerWallet = operatorWallet
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeTransferFrom(ownerAddress, receiverAddress, id, amount, isGasReceipt, data)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should REVERT if receiver address is incorrect', async () => {
transferObj.receiver = ownerAddress
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeTransferFrom(ownerAddress, receiverAddress, id, amount, isGasReceipt, data)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should REVERT if token id is incorrect', async () => {
transferObj.id = id + 1
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeTransferFrom(ownerAddress, receiverAddress, id, amount, isGasReceipt, data)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should REVERT if token amount is incorrect', async () => {
transferObj.amount = amount + 1
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeTransferFrom(ownerAddress, receiverAddress, id, amount, isGasReceipt, data)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should REVERT if transfer data is incorrect', async () => {
const sigArgTypes = ['address', 'address', 'address', 'uint256', 'uint256', 'uint256']
const txDataTypes = ['bytes', 'bytes']
const signer = await transferObj.signerWallet.getAddress()
// Packed encoding of transfer signature message
let sigData = utils.solidityPack(sigArgTypes, [
transferObj.contractAddress,
signer,
transferObj.receiver,
transferObj.id,
transferObj.amount,
transferObj.nonce
])
const transferData = transferObj.transferData == null ? utils.toUtf8Bytes('') : transferObj.transferData
let goodGasAndTransferData
let badGasAndTransferData
// Correct and incorrect transferData
if (isGasReceipt) {
goodGasAndTransferData = utils.defaultAbiCoder.encode([GasReceiptType, 'bytes'], [gasReceipt, transferData])
badGasAndTransferData = utils.defaultAbiCoder.encode(
[GasReceiptType, 'bytes'],
[gasReceipt, utils.toUtf8Bytes('Goodbyebyebye')]
)
} else {
goodGasAndTransferData = utils.defaultAbiCoder.encode(['bytes'], [transferData])
badGasAndTransferData = utils.defaultAbiCoder.encode(['bytes'], [utils.toUtf8Bytes('Goodbyebyebye')])
}
// Encode normally the whole thing
sigData = utils.solidityPack(['bytes', 'bytes'], [sigData, goodGasAndTransferData])
// Get signature
const sig = (await ethSign(transferObj.signerWallet, sigData)).slice(0, -2)
const paddedNonce = utils.solidityPack(['uint256'], [transferObj.nonce])
const ethsig_nonce = sig + paddedNonce.slice(2) + '02' // encode packed the nonce
// PASS BAD DATA
data = utils.defaultAbiCoder.encode(txDataTypes, [ethsig_nonce, badGasAndTransferData])
const tx = operatorERC1155Contract.metaSafeTransferFrom(ownerAddress, receiverAddress, id, amount, isGasReceipt, data)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should REVERT if nonce is incorrect', async () => {
transferObj.nonce = nonce.add(101)
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
// Nonce higher
const tx = operatorERC1155Contract.metaSafeTransferFrom(ownerAddress, receiverAddress, id, amount, isGasReceipt, data)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_NONCE'))
// Correct nonce
transferObj.nonce = nonce
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
await operatorERC1155Contract.metaSafeTransferFrom(ownerAddress, receiverAddress, id, amount, isGasReceipt, data)
// Nonce lower
const tx2 = operatorERC1155Contract.metaSafeTransferFrom(ownerAddress, receiverAddress, id, amount, isGasReceipt, data)
await expect(tx2).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_NONCE'))
})
it('should PASS if signature is valid', async () => {
const tx = operatorERC1155Contract.metaSafeTransferFrom(ownerAddress, receiverAddress, id, amount, isGasReceipt, data)
await expect(tx).to.be.fulfilled
})
describe('ERC-1271 Receiver', () => {
let erc1271WalletValidationMockContract: ERC1271WalletValidationMock
let ERC1271WalletValidationMockAbstract: AbstractContract
let erc1271WalletAddress
beforeEach(async () => {
ERC1271WalletValidationMockAbstract = await AbstractContract.fromArtifactName('ERC1271WalletValidationMock')
erc1271WalletValidationMockContract = (await ERC1271WalletValidationMockAbstract.deploy(ownerWallet, [
domainHash
])) as ERC1271WalletValidationMock
erc1271WalletAddress = erc1271WalletValidationMockContract.address
await erc1155Contract.mintMock(erc1271WalletAddress, id, initBalance, [])
await erc1155Contract.mintMock(erc1271WalletAddress, feeTokenID, feeTokenInitBalance, [])
})
describe(`EIP-1271 (bytes) signatures (03)`, () => {
it('should return REVERT if signature is invalid', async () => {
transferObj.from = erc1271WalletAddress
transferObj.signerWallet = receiverWallet
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt, '03')
const tx = operatorERC1155Contract.metaSafeTransferFrom(
erc1271WalletAddress,
receiverAddress,
id,
amount,
isGasReceipt,
data,
{ gasLimit: 2000000 }
)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should REVERT if token ID is not 66', async () => {
const badID = 77
await erc1155Contract.mintMock(erc1271WalletAddress, badID, initBalance, [])
transferObj.from = erc1271WalletAddress
transferObj.id = badID
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt, '03')
const tx = operatorERC1155Contract.metaSafeTransferFrom(
erc1271WalletAddress,
receiverAddress,
id,
amount,
isGasReceipt,
data,
{ gasLimit: 2000000 }
)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should REVERT if amount is more than 100', async () => {
await erc1155Contract.mintMock(erc1271WalletAddress, id, 101, [])
transferObj.from = erc1271WalletAddress
transferObj.amount = 101
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt, '03')
const tx = operatorERC1155Contract.metaSafeTransferFrom(
erc1271WalletAddress,
receiverAddress,
id,
amount,
isGasReceipt,
data,
{ gasLimit: 2000000 }
)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should PASS if signature is valid', async () => {
transferObj.from = erc1271WalletAddress
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt, '03')
const tx = operatorERC1155Contract.metaSafeTransferFrom(
erc1271WalletAddress,
receiverAddress,
id,
amount,
isGasReceipt,
data,
{ gasLimit: 2000000 }
)
await expect(tx).to.be.fulfilled
})
})
describe(`EIP-1271 (bytes32) signatures (04)`, () => {
it('should return REVERT if signature is invalid', async () => {
transferObj.from = erc1271WalletAddress
transferObj.signerWallet = receiverWallet
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt, '04')
const tx = operatorERC1155Contract.metaSafeTransferFrom(
erc1271WalletAddress,
receiverAddress,
id,
amount,
isGasReceipt,
data,
{ gasLimit: 2000000 }
)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should PASS if signature is valid', async () => {
transferObj.from = erc1271WalletAddress
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt, '04')
const tx = operatorERC1155Contract.metaSafeTransferFrom(
erc1271WalletAddress,
receiverAddress,
id,
amount,
isGasReceipt,
data,
{ gasLimit: 2000000 }
)
await expect(tx).to.be.fulfilled
})
})
})
describe('When signature is valid', () => {
it('should REVERT if insufficient balance', async () => {
transferObj.amount = initBalance + 1
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeTransferFrom(
ownerAddress,
receiverAddress,
id,
initBalance + 1,
isGasReceipt,
data
)
await expect(tx).to.be.rejectedWith(RevertError('SafeMath#sub: UNDERFLOW'))
})
it('should REVERT if sending to 0x0', async () => {
transferObj.receiver = ZERO_ADDRESS
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeTransferFrom(ownerAddress, ZERO_ADDRESS, id, amount, isGasReceipt, data)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#metaSafeTransferFrom: INVALID_RECIPIENT'))
})
it('should REVERT if transfer leads to overflow', async () => {
await erc1155Contract.mintMock(receiverAddress, id, MAXVAL, [])
const tx = operatorERC1155Contract.metaSafeTransferFrom(ownerAddress, receiverAddress, id, amount, isGasReceipt, data)
await expect(tx).to.be.rejectedWith(RevertError('SafeMath#add: OVERFLOW'))
})
it('should REVERT when sending to non-receiver contract', async () => {
transferObj.receiver = erc1155Contract.address
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeTransferFrom(
ownerAddress,
erc1155Contract.address,
id,
amount,
isGasReceipt,
data
)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155MetaMintBurnMock: INVALID_METHOD'))
})
it('should REVERT if invalid response from receiver contract', async () => {
transferObj.receiver = receiverContract.address
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
// Force invalid response
await receiverContract.setShouldReject(true)
const tx = operatorERC1155Contract.metaSafeTransferFrom(
ownerAddress,
receiverContract.address,
id,
amount,
isGasReceipt,
data
)
await expect(tx).to.be.rejectedWith(RevertError())
})
it('should PASS if valid response from receiver contract', async () => {
transferObj.receiver = receiverContract.address
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt, '02')
const tx = operatorERC1155Contract.metaSafeTransferFrom(
ownerAddress,
receiverContract.address,
id,
amount,
isGasReceipt,
data
)
//await expect(tx).to.be.fulfilled
await expect(tx).to.be.fulfilled
})
describe('When gas is reimbursed', () => {
before(async function() {
if (!condition[1]) {
this.test!.parent!.pending = true
this.skip()
}
})
it('should send gas fee to msg.sender is fee recipient ix 0x0', async () => {
gasReceipt!.feeRecipient = ZERO_ADDRESS
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
await receiverERC1155Contract.metaSafeTransferFrom(ownerAddress, receiverAddress, id, amount, isGasReceipt, data)
const receiverBalance = await erc1155Contract.balanceOf(receiverAddress, feeTokenID)
expect(gasReceipt!.gasFee).to.be.eql(receiverBalance.toNumber())
})
it('should send gas fee to specified fee recipient (if not 0x0), not tx.origin', async () => {
await receiverERC1155Contract.metaSafeTransferFrom(ownerAddress, receiverAddress, id, amount, isGasReceipt, data)
const operatorBalance = await erc1155Contract.balanceOf(operatorAddress, feeTokenID)
expect(gasReceipt!.gasFee).to.be.eql(operatorBalance.toNumber())
})
it('should REVERT if gasReceipt is incorrect', async () => {
const sigArgTypes = ['address', 'address', 'address', 'uint256', 'uint256', 'uint256']
const txDataTypes = ['bytes', 'bytes']
const signer = await transferObj.signerWallet.getAddress()
// Packed encoding of transfer signature message
let sigData = utils.solidityPack(sigArgTypes, [
transferObj.contractAddress,
signer,
transferObj.receiver,
transferObj.id,
transferObj.amount,
transferObj.nonce
])
// Form bad gas receipt
const badGasReceipt = { ...gasReceipt, gasPrice: 109284123 }
const transferData = transferObj.transferData == null ? utils.toUtf8Bytes('') : transferObj.transferData
// Correct and incorrect transferData
const goodGasAndTransferData = utils.defaultAbiCoder.encode([GasReceiptType, 'bytes'], [gasReceipt, transferData])
const badGasAndTransferData = utils.defaultAbiCoder.encode([GasReceiptType, 'bytes'], [badGasReceipt, transferData])
// Encode normally the whole thing
sigData = utils.solidityPack(['bytes', 'bytes'], [sigData, goodGasAndTransferData])
// Get signature
const sig = (await ethSign(transferObj.signerWallet, sigData)).slice(0, -2)
const paddedNonce = utils.solidityPack(['uint256'], [transferObj.nonce])
const ethsig_nonce = sig + paddedNonce.slice(2) + '02' // encode packed the nonce
// PASS BAD DATA
data = utils.defaultAbiCoder.encode(txDataTypes, [ethsig_nonce, badGasAndTransferData])
const tx = operatorERC1155Contract.metaSafeTransferFrom(
ownerAddress,
receiverAddress,
id,
amount,
isGasReceipt,
data
)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should PASS if another approved ERC-1155 is used for fee', async () => {
const erc1155Contract2 = (await erc1155Abstract.deploy(ownerWallet)) as ERC1155MetaMintBurnMock
await erc1155Contract2.mintMock(ownerAddress, feeTokenID, feeTokenInitBalance, [])
await erc1155Contract2.setApprovalForAll(operatorERC1155Contract.address, true)
feeTokenDataERC1155 = utils.defaultAbiCoder.encode(
['address', 'uint256', 'uint8'],
[erc1155Contract2.address, feeTokenID, 0]
)
gasReceipt = {
gasLimitCallback: 130000,
gasFee: 1000,
feeRecipient: operatorAddress,
feeTokenData: feeTokenDataERC1155
}
// Check if gas receipt is included
gasReceipt = isGasReceipt ? gasReceipt : null
// Data to pass in transfer method
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeTransferFrom(
ownerAddress,
receiverAddress,
id,
amount,
isGasReceipt,
data,
{ gasLimit: 2000000 }
)
await expect(tx).to.be.fulfilled
})
it('should REVERT if NOT approved ERC-1155 is used for fee', async () => {
const erc1155Contract2 = (await erc1155Abstract.deploy(ownerWallet)) as ERC1155MetaMintBurnMock
await erc1155Contract2.mintMock(ownerAddress, feeTokenID, feeTokenInitBalance, [])
feeTokenDataERC1155 = utils.defaultAbiCoder.encode(
['address', 'uint256', 'uint8'],
[erc1155Contract2.address, feeTokenID, 0]
)
gasReceipt = {
gasLimitCallback: 130000,
gasFee: 1000,
feeRecipient: operatorAddress,
feeTokenData: feeTokenDataERC1155
}
// Check if gas receipt is included
gasReceipt = isGasReceipt ? gasReceipt : null
// Data to pass in transfer method
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeTransferFrom(
ownerAddress,
receiverAddress,
id,
amount,
isGasReceipt,
data,
{ gasLimit: 2000000 }
)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155#safeTransferFrom: INVALID_OPERATOR'))
})
it('should REVERT if another ERC-1155 is used for fee without sufficient balance', async () => {
const erc1155Contract2 = (await erc1155Abstract.deploy(ownerWallet)) as ERC1155MetaMintBurnMock
await erc1155Contract2.mintMock(ownerAddress, feeTokenID, 100, [])
await erc1155Contract2.setApprovalForAll(operatorERC1155Contract.address, true)
feeTokenDataERC1155 = utils.defaultAbiCoder.encode(
['address', 'uint256', 'uint8'],
[erc1155Contract2.address, feeTokenID, 0]
)
gasReceipt = {
gasLimitCallback: 130000,
gasFee: 1000,
feeRecipient: operatorAddress,
feeTokenData: feeTokenDataERC1155
}
// Check if gas receipt is included
gasReceipt = isGasReceipt ? gasReceipt : null
// Data to pass in transfer method
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeTransferFrom(
ownerAddress,
receiverAddress,
id,
amount,
isGasReceipt,
data,
{ gasLimit: 2000000 }
)
await expect(tx).to.be.rejectedWith(RevertError('SafeMath#sub: UNDERFLOW'))
})
it('should PASS if approved ERC20 is used for fee', async () => {
const erc20Abstract = await AbstractContract.fromArtifactName('ERC20Mock')
const erc20Contract = (await erc20Abstract.deploy(ownerWallet)) as ERC20Mock
await erc20Contract.mockMint(ownerAddress, feeTokenInitBalance)
await erc20Contract.approve(operatorERC1155Contract.address, feeTokenInitBalance)
const feeTokenDataERC20 = utils.defaultAbiCoder.encode(['address', 'uint8'], [erc20Contract.address, 1])
gasReceipt = {
gasLimitCallback: 130000,
gasFee: 1000,
feeRecipient: operatorAddress,
feeTokenData: feeTokenDataERC20
}
// Check if gas receipt is included
gasReceipt = isGasReceipt ? gasReceipt : null
// Data to pass in transfer method
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeTransferFrom(
ownerAddress,
receiverAddress,
id,
amount,
isGasReceipt,
data,
{ gasLimit: 2000000 }
)
await expect(tx).to.be.fulfilled
})
it('should REVERT if NOT approved ERC20 is used for fee', async () => {
const erc20Abstract = await AbstractContract.fromArtifactName('ERC20Mock')
const erc20Contract = (await erc20Abstract.deploy(ownerWallet)) as ERC20Mock
await erc20Contract.mockMint(ownerAddress, feeTokenInitBalance)
const feeTokenDataERC20 = utils.defaultAbiCoder.encode(['address', 'uint8'], [erc20Contract.address, 1])
gasReceipt = {
gasLimitCallback: 130000,
gasFee: 1000,
feeRecipient: operatorAddress,
feeTokenData: feeTokenDataERC20
}
// Check if gas receipt is included
gasReceipt = isGasReceipt ? gasReceipt : null
// Data to pass in transfer method
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeTransferFrom(
ownerAddress,
receiverAddress,
id,
amount,
isGasReceipt,
data,
{ gasLimit: 2000000 }
)
await expect(tx).to.be.rejectedWith(RevertError('SafeMath#sub: UNDERFLOW'))
})
it('should REVERT if approved ERC20 balance is insufficient', async () => {
const erc20Abstract = await AbstractContract.fromArtifactName('ERC20Mock')
const erc20Contract = (await erc20Abstract.deploy(ownerWallet)) as ERC20Mock
await erc20Contract.mockMint(ownerAddress, 100)
await erc20Contract.approve(operatorERC1155Contract.address, feeTokenInitBalance)
const feeTokenDataERC20 = utils.defaultAbiCoder.encode(['address', 'uint8'], [erc20Contract.address, 1])
gasReceipt = {
gasLimitCallback: 130000,
gasFee: 1000,
feeRecipient: operatorAddress,
feeTokenData: feeTokenDataERC20
}
// Check if gas receipt is included
gasReceipt = isGasReceipt ? gasReceipt : null
// Data to pass in transfer method
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeTransferFrom(
ownerAddress,
receiverAddress,
id,
amount,
isGasReceipt,
data,
{ gasLimit: 2000000 }
)
await expect(tx).to.be.rejectedWith(RevertError('SafeMath#sub: UNDERFLOW'))
})
it('should REVERT if FeeTokenType is not supported', async () => {
const erc20Abstract = await AbstractContract.fromArtifactName('ERC20Mock')
const erc20Contract = (await erc20Abstract.deploy(ownerWallet)) as ERC20Mock
await erc20Contract.mockMint(ownerAddress, feeTokenInitBalance)
await erc20Contract.approve(operatorERC1155Contract.address, feeTokenInitBalance)
let feeTokenDataERC20 = utils.defaultAbiCoder.encode(['address', 'uint8'], [erc20Contract.address, 2])
gasReceipt = {
gasLimitCallback: 130000,
gasFee: 1000,
feeRecipient: operatorAddress,
feeTokenData: feeTokenDataERC20
}
// Check if gas receipt is included
gasReceipt = isGasReceipt ? gasReceipt : null
// Data to pass in transfer method
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeTransferFrom(
ownerAddress,
receiverAddress,
id,
amount,
isGasReceipt,
data,
{ gasLimit: 2000000 }
)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_transferGasFee: UNSUPPORTED_TOKEN'))
feeTokenDataERC20 = utils.defaultAbiCoder.encode(['address', 'uint8'], [erc20Contract.address, 3])
gasReceipt = {
gasLimitCallback: 130000,
gasFee: 1000,
feeRecipient: operatorAddress,
feeTokenData: feeTokenDataERC20
}
// Check if gas receipt is included
gasReceipt = isGasReceipt ? gasReceipt : null
// Data to pass in transfer method
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
const tx2 = operatorERC1155Contract.metaSafeTransferFrom(
ownerAddress,
receiverAddress,
id,
amount,
isGasReceipt,
data,
{ gasLimit: 2000000 }
)
await expect(tx2).to.be.rejectedWith(RevertError('ERC1155Meta#_transferGasFee: UNSUPPORTED_TOKEN'))
})
it('should REVERT if gas receipt is passed, but not claimed', async () => {
const tx = operatorERC1155Contract.metaSafeTransferFrom(ownerAddress, receiverAddress, id, amount, false, data)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should REVERT if gas receipt is passed but isGasFee is false', async () => {
transferObj.isGasFee = false
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeTransferFrom(ownerAddress, receiverAddress, id, amount, true, data)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should PASS if gas receipt is passed with isGasFee to false and not claimed', async () => {
transferObj.isGasFee = false
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeTransferFrom(ownerAddress, receiverAddress, id, amount, false, data)
await expect(tx).to.be.fulfilled
})
describe('When receiver is a contract', () => {
it('should REVERT if gas used in onERC1155Received exceeds limit', async () => {
const lowGasLimit = 1000
gasReceipt!.gasLimitCallback = lowGasLimit
transferObj.receiver = receiverContract.address
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeTransferFrom(
ownerAddress,
receiverContract.address,
id,
amount,
isGasReceipt,
data,
{ gasLimit: 2000000 }
)
await expect(tx).to.be.rejectedWith(RevertError())
})
it('should PASS if gas used in onERC1155Received does not exceed limit', async () => {
const okGasLimit = 9700
gasReceipt!.gasLimitCallback = okGasLimit
transferObj.receiver = receiverContract.address
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeTransferFrom(
ownerAddress,
receiverContract.address,
id,
amount,
isGasReceipt,
data,
{ gasLimit: 2000000 }
)
await expect(tx).to.be.fulfilled
})
it('should PASS if gasLimitCallback is higher than gas sent in transaction', async () => {
const highGasLimit = 30000000
gasReceipt!.gasLimitCallback = highGasLimit
transferObj.receiver = receiverContract.address
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeTransferFrom(
ownerAddress,
receiverContract.address,
id,
amount,
isGasReceipt,
data,
{ gasLimit: 2000000 }
)
await expect(tx).to.be.fulfilled
})
})
})
describe('When gas is NOT reimbursed', () => {
before(async function() {
if (condition[1]) {
this.test!.parent!.pending = true
this.skip()
}
})
it('should PASS if gas receipt is not passed and not claimed', async () => {
const tx = operatorERC1155Contract.metaSafeTransferFrom(ownerAddress, receiverAddress, id, amount, false, data)
await expect(tx).to.be.fulfilled
})
it('should REVER if gas receipt is not passed and claimed', async () => {
const tx = operatorERC1155Contract.metaSafeTransferFrom(ownerAddress, receiverAddress, id, amount, true, data)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should REVERT if gas receipt is not passed but isGasFee is set to true and is claimed', async () => {
transferObj.isGasFee = true
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeTransferFrom(ownerAddress, receiverAddress, id, amount, true, data)
await expect(tx).to.be.rejectedWith(RevertError())
})
})
context('When successful transfer', () => {
let tx: ContractTransaction
beforeEach(async () => {
tx = await operatorERC1155Contract.metaSafeTransferFrom(
ownerAddress,
receiverAddress,
id,
amount,
isGasReceipt,
data
)
})
it('should correctly update balance of sender', async () => {
const balance = await erc1155Contract.balanceOf(ownerAddress, id)
expect(balance).to.be.eql(BigNumber.from(initBalance - amount))
})
it('should correctly update balance of receiver', async () => {
const balance = await erc1155Contract.balanceOf(receiverAddress, id)
expect(balance).to.be.eql(BigNumber.from(amount))
})
describe('When gas is reimbursed', () => {
before(async function() {
if (!condition[1]) {
this.test!.parent!.pending = true
this.skip()
}
})
it('should update gas token balance of sender', async () => {
const senderBalance = await erc1155Contract.balanceOf(ownerAddress, feeTokenID)
expect(senderBalance).to.be.eql(feeTokenInitBalance.sub(gasReceipt!.gasFee))
})
it('should update gas token balance of executor', async () => {
const balance = await erc1155Contract.balanceOf(operatorAddress, feeTokenID)
expect(gasReceipt!.gasFee).to.be.eql(balance.toNumber())
})
})
describe('TransferSingle event', async () => {
let filterFromOperatorContract: EventFilter
it('should emit TransferSingle event', async () => {
const receipt = await tx.wait(1)
const ev = receipt.events!.pop()!
expect(ev.event).to.be.eql('TransferSingle')
})
it('should have `msg.sender` as `_operator` field, not _from', async () => {
const receipt = await tx.wait(1)
const ev = receipt.events!.pop()!
const args = ev.args! as any
expect(args._operator).to.be.eql(operatorAddress)
})
it('should have `msg.sender` as `_operator` field, not tx.origin', async () => {
// Get event filter to get internal tx event
filterFromOperatorContract = erc1155Contract.filters.TransferSingle(
operatorContract.address,
null,
null,
null,
null
)
// Increment nonce because it's the second transfer
transferObj.nonce = nonce.add(1)
data = await encodeMetaTransferFromData(transferObj, domainHash, gasReceipt)
// Execute transfer from operator contract
// @ts-ignore (https://github.com/ethereum-ts/TypeChain/issues/118)
await operatorContract.metaSafeTransferFrom(
erc1155Contract.address,
ownerAddress,
receiverAddress,
id,
amount,
isGasReceipt,
data,
{ gasLimit: 1000000 } // INCORRECT GAS ESTIMATION
)
// Get logs from internal transaction event
// @ts-ignore (https://github.com/ethers-io/ethers.js/issues/204#issuecomment-427059031)
filterFromOperatorContract.fromBlock = 0
const logs = await operatorProvider.getLogs(filterFromOperatorContract)
const args = erc1155Contract.interface.decodeEventLog(
erc1155Contract.interface.events['TransferSingle(address,address,address,uint256,uint256)'],
logs[0].data,
logs[0].topics
)
// operator arg should be equal to msg.sender, not tx.origin
expect(args._operator).to.be.eql(operatorContract.address)
})
it('should emit NonceChange event', async () => {
const receipt = await tx.wait(1)
const ev = receipt.events![0]
expect(ev.event).to.be.eql('NonceChange')
})
it('should have `_signer` as `signer` in NonceChange', async () => {
const receipt = await tx.wait(1)
const ev = receipt.events![0]
const args = ev.args! as any
expect(args.signer).to.be.eql(ownerWallet.address)
})
it('should have `nonce` as `nonce + 1` in NonceChange', async () => {
const receipt = await tx.wait(1)
const ev = receipt.events![0]
const args = ev.args! as any
expect(args.newNonce).to.be.eql(nonce.add(1))
})
})
})
})
})
})
})
describe('metaSafeBatchTransferFrom() Function', () => {
let receiverContract: ERC1155ReceiverMock
let operatorContract: ERC1155OperatorMock
const METATRANSFER_IDENTIFIER = '0xebc71fa5'
let transferData: string | null = 'Hello from the other side'
const initBalance = 100
const amount = 10
const nonce = BigNumber.from(0)
// Parameters for balances
let ids: any[], amounts: any[]
const nTokenTypes = 33
let isGasReceipt: boolean = true
const feeTokenInitBalance = BigNumber.from(100000000)
const feeType = 0
const feeTokenID = 666
let feeTokenAddress: string
let feeTokenDataERC1155: string | Uint8Array
let transferObj: BatchTransferSignature
let gasReceipt: GasReceipt | null
let domainHash: string
let data: string
const conditions = [
[transferData, true, 'Gas receipt & transfer data'],
[null, true, 'Gas receipt w/o transfer data'],
[transferData, false, 'Transfer data w/o gas receipt '],
[null, false, 'No Gas receipt & No transfer data']
]
conditions.forEach(function(condition) {
context(condition[2] as string, () => {
beforeEach(async () => {
// Get conditions
transferData = (await condition[0]) as string | null
isGasReceipt = (await condition[1]) as boolean
// Deploy contracts
const abstract = await AbstractContract.fromArtifactName('ERC1155ReceiverMock')
receiverContract = (await abstract.deploy(ownerWallet)) as ERC1155ReceiverMock
operatorContract = (await operatorAbstract.deploy(operatorWallet)) as ERC1155OperatorMock
// Mint tokens
;(ids = []), (amounts = [])
// Minting enough amounts for transfer for each types
for (let i = 0; i < nTokenTypes; i++) {
await erc1155Contract.mintMock(ownerAddress, i, initBalance, [])
ids.push(i)
amounts.push(amount)
}
feeTokenAddress = erc1155Contract.address
feeTokenDataERC1155 = utils.defaultAbiCoder.encode(
['address', 'uint256', 'uint8'],
[feeTokenAddress, feeTokenID, feeType]
)
// Gas Receipt
gasReceipt = {
gasLimitCallback: 160000,
gasFee: 30000,
feeRecipient: operatorAddress,
feeTokenData: feeTokenDataERC1155
}
// Check if gas receipt is included
gasReceipt = isGasReceipt ? gasReceipt : null
// Transfer Signature Object
transferObj = {
contractAddress: erc1155Contract.address,
signerWallet: ownerWallet,
receiver: receiverAddress,
ids: ids.slice(0),
amounts: amounts.slice(0),
isGasFee: isGasReceipt,
transferData: transferData === null ? null : utils.toUtf8Bytes(transferData),
nonce: nonce
}
// Mint tokens used to pay for gas
await erc1155Contract.mintMock(ownerAddress, feeTokenID, feeTokenInitBalance, [])
// Domain hash
domainHash = utils.keccak256(
utils.solidityPack(['bytes32', 'uint256'], [DOMAIN_SEPARATOR_TYPEHASH, erc1155Contract.address])
)
// Data to pass in transfer method
data = await encodeMetaBatchTransferFromData(transferObj, domainHash, gasReceipt)
})
it('should REVERT if contract address is incorrect', async () => {
domainHash = utils.keccak256(
utils.solidityPack(['bytes32', 'uint256'], [DOMAIN_SEPARATOR_TYPEHASH, receiverContract.address])
)
data = await encodeMetaBatchTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
receiverAddress,
ids,
amounts,
isGasReceipt,
data
)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should REVERT if signer address is incorrect', async () => {
transferObj.signerWallet = operatorWallet
data = await encodeMetaBatchTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
receiverAddress,
ids,
amounts,
isGasReceipt,
data
)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should REVERT if receiver address is incorrect', async () => {
transferObj.receiver = ownerAddress
data = await encodeMetaBatchTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
receiverAddress,
ids,
amounts,
isGasReceipt,
data
)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should REVERT if token id is incorrect', async () => {
transferObj.ids[0] = 6
data = await encodeMetaBatchTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
receiverAddress,
ids,
amounts,
isGasReceipt,
data
)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should REVERT if token amount is incorrect', async () => {
transferObj.amounts[0] = amount + 1
data = await encodeMetaBatchTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
receiverAddress,
ids,
amounts,
isGasReceipt,
data
)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should REVERT if transfer data is incorrect', async () => {
const sigArgTypes = ['address', 'address', 'address', 'uint256[]', 'uint256[]', 'uint256']
const txDataTypes = ['bytes', 'bytes']
const signer = await transferObj.signerWallet.getAddress()
// Packed encoding of transfer signature message
let sigData = utils.solidityPack(sigArgTypes, [
transferObj.contractAddress,
signer,
transferObj.receiver,
transferObj.ids,
transferObj.amounts,
transferObj.nonce
])
const transferData = transferObj.transferData == null ? utils.toUtf8Bytes('') : transferObj.transferData
let goodGasAndTransferData
let badGasAndTransferData
// Correct and incorrect transferData
if (isGasReceipt) {
goodGasAndTransferData = utils.defaultAbiCoder.encode([GasReceiptType, 'bytes'], [gasReceipt, transferData])
badGasAndTransferData = utils.defaultAbiCoder.encode(
[GasReceiptType, 'bytes'],
[gasReceipt, utils.toUtf8Bytes('Goodbyebyebye')]
)
} else {
goodGasAndTransferData = utils.defaultAbiCoder.encode(['bytes'], [transferData])
badGasAndTransferData = utils.defaultAbiCoder.encode(['bytes'], [utils.toUtf8Bytes('Goodbyebyebye')])
}
// Encode normally the whole thing
sigData = utils.solidityPack(['bytes', 'bytes'], [sigData, goodGasAndTransferData])
// Get signature
const sig = (await ethSign(transferObj.signerWallet, sigData)).slice(0, -2)
const paddedNonce = utils.solidityPack(['uint256'], [transferObj.nonce])
const ethsig_nonce = sig + paddedNonce.slice(2) + '02' // encode packed the nonce
// PASS BAD DATA
data = utils.defaultAbiCoder.encode(txDataTypes, [ethsig_nonce, badGasAndTransferData])
const tx = operatorERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
receiverAddress,
ids,
amounts,
isGasReceipt,
data
)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should REVERT if nonce is incorrect', async () => {
transferObj.nonce = nonce.add(101)
data = await encodeMetaBatchTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
receiverAddress,
ids,
amounts,
isGasReceipt,
data
)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_NONCE'))
// Correct nonce
transferObj.nonce = nonce
data = await encodeMetaBatchTransferFromData(transferObj, domainHash, gasReceipt)
await operatorERC1155Contract.metaSafeBatchTransferFrom(ownerAddress, receiverAddress, ids, amounts, isGasReceipt, data)
// Nonce lower
const tx2 = operatorERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
receiverAddress,
ids,
amounts,
isGasReceipt,
data
)
await expect(tx2).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_NONCE'))
})
it('should PASS if signature is valid', async () => {
const tx = operatorERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
receiverAddress,
ids,
amounts,
isGasReceipt,
data
)
await expect(tx).to.be.fulfilled
})
describe('ERC-1271 Receiver', () => {
let erc1271WalletValidationMockContract: ERC1271WalletValidationMock
let ERC1271WalletValidationMockAbstract: AbstractContract
let erc1271WalletAddress
beforeEach(async () => {
ERC1271WalletValidationMockAbstract = await AbstractContract.fromArtifactName('ERC1271WalletValidationMock')
erc1271WalletValidationMockContract = (await ERC1271WalletValidationMockAbstract.deploy(ownerWallet, [
domainHash
])) as ERC1271WalletValidationMock
erc1271WalletAddress = erc1271WalletValidationMockContract.address
await erc1155Contract.batchMintMock(erc1271WalletAddress, ids, amounts, [])
await erc1155Contract.mintMock(erc1271WalletAddress, feeTokenID, feeTokenInitBalance, [])
})
describe(`EIP-1271 (bytes) signatures (03)`, () => {
it('should return REVERT if signature is invalid', async () => {
transferObj.from = erc1271WalletAddress
transferObj.signerWallet = receiverWallet
data = await encodeMetaBatchTransferFromData(transferObj, domainHash, gasReceipt, '03')
const tx = operatorERC1155Contract.metaSafeBatchTransferFrom(
erc1271WalletAddress,
receiverAddress,
ids,
amounts,
isGasReceipt,
data
)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
})
describe(`EIP-1271 (bytes32) signatures (04)`, () => {
it('should return REVERT if signature is invalid', async () => {
transferObj.from = erc1271WalletAddress
transferObj.signerWallet = receiverWallet
data = await encodeMetaBatchTransferFromData(transferObj, domainHash, gasReceipt, '04')
const tx = operatorERC1155Contract.metaSafeBatchTransferFrom(
erc1271WalletAddress,
receiverAddress,
ids,
amounts,
isGasReceipt,
data
)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should PASS if signature is valid', async () => {
transferObj.from = erc1271WalletAddress
data = await encodeMetaBatchTransferFromData(transferObj, domainHash, gasReceipt, '04')
const tx = operatorERC1155Contract.metaSafeBatchTransferFrom(
erc1271WalletAddress,
receiverAddress,
ids,
amounts,
isGasReceipt,
data
)
await expect(tx).to.be.fulfilled
})
})
})
describe('When signature is valid', () => {
it('should REVERT if insufficient balance', async () => {
transferObj.amounts[0] = initBalance + 1
amounts[0] = initBalance + 1
data = await encodeMetaBatchTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
receiverAddress,
ids,
amounts,
isGasReceipt,
data
)
await expect(tx).to.be.rejectedWith(RevertError('SafeMath#sub: UNDERFLOW'))
})
it('should REVERT if sending to 0x0', async () => {
transferObj.receiver = ZERO_ADDRESS
data = await encodeMetaBatchTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
ZERO_ADDRESS,
ids,
amounts,
isGasReceipt,
data
)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#metaSafeBatchTransferFrom: INVALID_RECIPIENT'))
})
it('should REVERT if transfer leads to overflow', async () => {
await operatorERC1155Contract.mintMock(receiverAddress, ids[0], MAXVAL, [])
const tx = operatorERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
receiverAddress,
ids,
amounts,
isGasReceipt,
data
)
await expect(tx).to.be.rejectedWith(RevertError('SafeMath#add: OVERFLOW'))
})
it('should REVERT when sending to non-receiver contract', async () => {
transferObj.receiver = erc1155Contract.address
data = await encodeMetaBatchTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
erc1155Contract.address,
ids,
amounts,
isGasReceipt,
data
)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155MetaMintBurnMock: INVALID_METHOD'))
})
it('should REVERT if invalid response from receiver contract', async () => {
transferObj.receiver = receiverContract.address
data = await encodeMetaBatchTransferFromData(transferObj, domainHash, gasReceipt)
// Force invalid response
await receiverContract.setShouldReject(true)
const tx = operatorERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
receiverContract.address,
ids,
amounts,
isGasReceipt,
data
)
await expect(tx).to.be.rejectedWith(RevertError())
})
it('should PASS if valid response from receiver contract', async () => {
transferObj.receiver = receiverContract.address
data = await encodeMetaBatchTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
receiverContract.address,
ids,
amounts,
isGasReceipt,
data,
{ gasLimit: 2000000 }
)
await expect(tx).to.be.fulfilled
})
describe('When gas is reimbursed', () => {
before(async function() {
if (!condition[1]) {
this.test!.parent!.pending = true
this.skip()
}
})
it('should send gas fee to tx.origin is fee recipient ix 0x0', async () => {
gasReceipt!.feeRecipient = ZERO_ADDRESS
data = await encodeMetaBatchTransferFromData(transferObj, domainHash, gasReceipt)
await receiverERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
receiverAddress,
ids,
amounts,
isGasReceipt,
data
)
const receiverBalance = await operatorERC1155Contract.balanceOf(receiverAddress, feeTokenID)
expect(gasReceipt!.gasFee).to.be.eql(receiverBalance.toNumber())
})
it('should send gas fee to specified fee recipient (if not 0x0), not tx.origin', async () => {
await receiverERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
receiverAddress,
ids,
amounts,
isGasReceipt,
data
)
const operatorBalance = await operatorERC1155Contract.balanceOf(operatorAddress, feeTokenID)
expect(gasReceipt!.gasFee).to.be.eql(operatorBalance.toNumber())
})
it('should REVERT if gasReceipt is incorrect', async () => {
const sigArgTypes = ['address', 'address', 'address', 'uint256[]', 'uint256[]', 'uint256']
const txDataTypes = ['bytes', 'bytes']
const signer = await transferObj.signerWallet.getAddress()
// Packed encoding of transfer signature message
let sigData = utils.solidityPack(sigArgTypes, [
transferObj.contractAddress,
signer,
transferObj.receiver,
transferObj.ids,
transferObj.amounts,
transferObj.nonce
])
// Form bad gas receipt
const badGasReceipt = { ...gasReceipt, gasPrice: 109284123 }
const transferData = transferObj.transferData == null ? utils.toUtf8Bytes('') : transferObj.transferData
// Correct and incorrect transferData
const goodGasAndTransferData = utils.defaultAbiCoder.encode([GasReceiptType, 'bytes'], [gasReceipt, transferData])
const badGasAndTransferData = utils.defaultAbiCoder.encode([GasReceiptType, 'bytes'], [badGasReceipt, transferData])
// Encode normally the whole thing
sigData = utils.solidityPack(['bytes', 'bytes'], [sigData, goodGasAndTransferData])
// Get signature
const sig = (await ethSign(transferObj.signerWallet, sigData)).slice(0, -2)
const paddedNonce = utils.solidityPack(['uint256'], [transferObj.nonce])
const ethsig_nonce = sig + paddedNonce.slice(2) + '02' // encode packed the nonce
// PASS BAD DATA
data = utils.defaultAbiCoder.encode(txDataTypes, [ethsig_nonce, badGasAndTransferData])
const tx = operatorERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
receiverAddress,
ids,
amounts,
isGasReceipt,
data
)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should REVERT if gas receipt is passed, but not claimed', async () => {
const tx = operatorERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
receiverAddress,
ids,
amounts,
false,
data
)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should REVERT if gas receipt is passed but isGasFee is false', async () => {
transferObj.isGasFee = false
data = await encodeMetaBatchTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
receiverAddress,
ids,
amounts,
true,
data
)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should PASS if gas receipt is passed with isGasFee to false and not claimed', async () => {
transferObj.isGasFee = false
data = await encodeMetaBatchTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
receiverAddress,
ids,
amounts,
false,
data
)
await expect(tx).to.be.fulfilled
})
describe('When receiver is a contract', () => {
it('should REVERT if gas used in onERC1155BatchReceived exceeds limit', async () => {
const lowGasLimit = 1000
gasReceipt!.gasLimitCallback = lowGasLimit
transferObj.receiver = receiverContract.address
data = await encodeMetaBatchTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
receiverContract.address,
ids,
amounts,
isGasReceipt,
data,
{ gasLimit: 2000000 }
)
await expect(tx).to.be.rejectedWith(RevertError())
})
it('should PASS if gas used in onERC1155BatchReceived does not exceed limit', async () => {
const okGasLimit = 160000
gasReceipt!.gasLimitCallback = okGasLimit
transferObj.receiver = receiverContract.address
data = await encodeMetaBatchTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
receiverContract.address,
ids,
amounts,
isGasReceipt,
data,
{ gasLimit: 2000000 }
)
await expect(tx).to.be.fulfilled
})
it('should PASS if gasLimit is higher than gas sent in transaction', async () => {
const highGasLimit = 3000000
gasReceipt!.gasLimitCallback = highGasLimit
transferObj.receiver = receiverContract.address
data = await encodeMetaBatchTransferFromData(transferObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
receiverContract.address,
ids,
amounts,
isGasReceipt,
data,
{ gasLimit: 2000000 }
)
await expect(tx).to.be.fulfilled
})
})
})
describe('When gas is NOT reimbursed', () => {
before(async function() {
if (condition[1]) {
this.test!.parent!.pending = true
this.skip()
}
})
it('should PASS if gas receipt is not passed and not claimed', async () => {
const tx = operatorERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
receiverAddress,
ids,
amounts,
false,
data
)
await expect(tx).to.be.fulfilled
})
it('should REVER if gas receipt is not passed and claimed', async () => {
const tx = operatorERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
receiverAddress,
ids,
amounts,
true,
data
)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should REVERT if gas receipt is not passed but isGasFee is set to true and is claimed', async () => {
transferObj.isGasFee = true
data = await encodeMetaBatchTransferFromData(transferObj, domainHash)
const tx = operatorERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
receiverAddress,
ids,
amounts,
true,
data
)
await expect(tx).to.be.rejectedWith(RevertError())
})
})
context('When successful transfer', () => {
let tx: ContractTransaction
beforeEach(async () => {
tx = await operatorERC1155Contract.metaSafeBatchTransferFrom(
ownerAddress,
receiverAddress,
ids,
amounts,
isGasReceipt,
data
)
})
it('should correctly update balance of sender and receiver', async () => {
let balanceFrom: BigNumber
let balanceTo: BigNumber
for (let i = 0; i < ids.length; i++) {
balanceFrom = await operatorERC1155Contract.balanceOf(ownerAddress, ids[i])
balanceTo = await operatorERC1155Contract.balanceOf(receiverAddress, ids[i])
expect(balanceFrom).to.be.eql(BigNumber.from(initBalance - amounts[i]))
expect(balanceTo).to.be.eql(BigNumber.from(amounts[i]))
}
})
describe('When gas is reimbursed', () => {
before(async function() {
if (!condition[1]) {
this.test!.parent!.pending = true
this.skip()
}
})
it('should update gas token balance of sender', async () => {
const senderBalance = await operatorERC1155Contract.balanceOf(ownerAddress, feeTokenID)
expect(senderBalance).to.be.eql(feeTokenInitBalance.sub(gasReceipt!.gasFee))
})
it('should update gas token balance of executor', async () => {
const balance = await operatorERC1155Contract.balanceOf(operatorAddress, feeTokenID)
expect(gasReceipt!.gasFee).to.be.eql(balance.toNumber())
})
})
describe('TransferBatch event', async () => {
let filterFromOperatorContract: EventFilter
let operatorContract: ERC1155OperatorMock
beforeEach(async () => {
operatorContract = (await operatorAbstract.deploy(operatorWallet)) as ERC1155OperatorMock
})
it('should emit 1 TransferBatch events of N transfers', async () => {
const receipt = await tx.wait(1)
const ev = receipt.events![1]
expect(ev.event).to.be.eql('TransferBatch')
const args = ev.args! as any
expect(args._ids.length).to.be.eql(ids.length)
})
it('should have `msg.sender` as `_operator` field, not _from', async () => {
const receipt = await tx.wait(1)
const ev = receipt.events!.pop()!
const args = ev.args! as any
expect(args._operator).to.be.eql(operatorAddress)
})
it('should have `msg.sender` as `_operator` field, not tx.origin', async () => {
// Get event filter to get internal tx event
filterFromOperatorContract = erc1155Contract.filters.TransferBatch(
operatorContract.address,
null,
null,
null,
null
)
//Increment nonce because it's the second transfer
transferObj.nonce = nonce.add(1)
data = await encodeMetaBatchTransferFromData(transferObj, domainHash, gasReceipt)
// Execute transfer from operator contract
// @ts-ignore (https://github.com/ethereum-ts/TypeChain/issues/118)
await operatorContract.metaSafeBatchTransferFrom(
erc1155Contract.address,
ownerAddress,
receiverAddress,
ids,
amounts,
isGasReceipt,
data,
{ gasLimit: 2000000 } // INCORRECT GAS ESTIMATION
)
// Get logs from internal transaction event
// @ts-ignore (https://github.com/ethers-io/ethers.js/issues/204#issuecomment-427059031)
filterFromOperatorContract.fromBlock = 0
const logs = await operatorProvider.getLogs(filterFromOperatorContract)
const args = erc1155Contract.interface.decodeEventLog(
erc1155Contract.interface.events['TransferBatch(address,address,address,uint256[],uint256[])'],
logs[0].data,
logs[0].topics
)
// operator arg should be equal to msg.sender, not tx.origin
expect(args._operator).to.be.eql(operatorContract.address)
})
it('should emit NonceChange event', async () => {
const receipt = await tx.wait(1)
const ev = receipt.events![0]
expect(ev.event).to.be.eql('NonceChange')
})
it('should have `_signer` as `signer` in NonceChange', async () => {
const receipt = await tx.wait(1)
const ev = receipt.events![0]
const args = ev.args! as any
expect(args.signer).to.be.eql(ownerWallet.address)
})
it('should have `nonce` as `nonce + 1` in NonceChange', async () => {
const receipt = await tx.wait(1)
const ev = receipt.events![0]
const args = ev.args! as any
expect(args.newNonce).to.be.eql(nonce.add(1))
})
})
})
})
})
})
})
describe('metaSetApprovalForAll() function', () => {
const initBalance = 100
let isGasReimbursed = true
const approved = true
const nonce = BigNumber.from(0)
const id = 66
let approvalObj: ApprovalSignature
let gasReceipt: GasReceipt | null
let domainHash: string
let data: string
let isGasReceipt: boolean = true
const feeTokenInitBalance = BigNumber.from(100000000)
const feeType = 0
const feeTokenID = 666
let feeTokenAddress: string
let feeTokenDataERC1155: string | Uint8Array
const conditions = [
[true, 'Gas receipt'],
[false, 'No Gas receipt']
]
conditions.forEach(function(condition) {
context(condition[1] as string, () => {
beforeEach(async () => {
isGasReceipt = condition[0] as boolean
feeTokenAddress = erc1155Contract.address
feeTokenDataERC1155 = utils.defaultAbiCoder.encode(
['address', 'uint256', 'uint8'],
[feeTokenAddress, feeTokenID, feeType]
)
// Gas Receipt
gasReceipt = {
gasLimitCallback: 125000,
gasFee: 30000,
feeRecipient: operatorAddress,
feeTokenData: feeTokenDataERC1155
}
// Check if gas receipt is included
gasReceipt = isGasReceipt ? gasReceipt : null
isGasReimbursed = isGasReceipt ? true : false
// Approval Signture Object
approvalObj = {
contractAddress: erc1155Contract.address,
signerWallet: ownerWallet,
operator: operatorAddress,
approved: approved,
isGasFee: isGasReceipt,
nonce: nonce
}
// Mint tokens
await erc1155Contract.mintMock(ownerAddress, id, initBalance, [])
// Mint tokens used to pay for gas
await erc1155Contract.mintMock(ownerAddress, feeTokenID, feeTokenInitBalance, [])
// Domain hash
domainHash = utils.keccak256(
utils.solidityPack(['bytes32', 'uint256'], [DOMAIN_SEPARATOR_TYPEHASH, erc1155Contract.address])
)
// Data to pass in approval method
data = await encodeMetaApprovalData(approvalObj, domainHash, gasReceipt)
})
it('should PASS if signature is valid', async () => {
const tx = operatorERC1155Contract.metaSetApprovalForAll(ownerAddress, operatorAddress, approved, isGasReimbursed, data)
await expect(tx).to.be.fulfilled
})
describe('ERC-1271 Receiver', () => {
let erc1271WalletValidationMockContract: ERC1271WalletValidationMock
let ERC1271WalletValidationMockAbstract: AbstractContract
let erc1271WalletAddress
beforeEach(async () => {
ERC1271WalletValidationMockAbstract = await AbstractContract.fromArtifactName('ERC1271WalletValidationMock')
erc1271WalletValidationMockContract = (await ERC1271WalletValidationMockAbstract.deploy(ownerWallet, [
domainHash
])) as ERC1271WalletValidationMock
erc1271WalletAddress = erc1271WalletValidationMockContract.address
await erc1155Contract.mintMock(erc1271WalletAddress, feeTokenID, feeTokenInitBalance, [])
})
describe(`EIP-1271 (bytes) signatures (03)`, () => {
it('should return REVERT if signature is invalid', async () => {
approvalObj.owner = erc1271WalletAddress
approvalObj.signerWallet = receiverWallet
data = await encodeMetaApprovalData(approvalObj, domainHash, gasReceipt, '03')
const tx = operatorERC1155Contract.metaSetApprovalForAll(
erc1271WalletAddress,
operatorAddress,
approved,
isGasReimbursed,
data
)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
})
describe(`EIP-1271 (bytes32) signatures (04)`, () => {
it('should return REVERT if signature is invalid', async () => {
approvalObj.owner = erc1271WalletAddress
approvalObj.signerWallet = receiverWallet
data = await encodeMetaApprovalData(approvalObj, domainHash, gasReceipt, '04')
const tx = operatorERC1155Contract.metaSetApprovalForAll(
erc1271WalletAddress,
operatorAddress,
approved,
isGasReimbursed,
data
)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should PASS if signature is valid', async () => {
approvalObj.owner = erc1271WalletAddress
data = await encodeMetaApprovalData(approvalObj, domainHash, gasReceipt, '04')
const tx = operatorERC1155Contract.metaSetApprovalForAll(
erc1271WalletAddress,
operatorAddress,
approved,
isGasReimbursed,
data
)
await expect(tx).to.be.fulfilled
})
})
})
describe('When gas is reimbursed', () => {
before(async function() {
if (!condition[0]) {
this.test!.parent!.pending = true
this.skip()
}
})
it('should REVERT if gas receipt is passed, but not claimed', async () => {
const tx = operatorERC1155Contract.metaSetApprovalForAll(ownerAddress, operatorAddress, approved, false, data)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should REVERT if gas receipt is passed but isGasFee is false', async () => {
approvalObj.isGasFee = false
data = await encodeMetaApprovalData(approvalObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSetApprovalForAll(ownerAddress, operatorAddress, approved, true, data)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should PASS if gas receipt is passed with isGasFee to false and not claimed', async () => {
approvalObj.isGasFee = false
data = await encodeMetaApprovalData(approvalObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSetApprovalForAll(ownerAddress, operatorAddress, approved, false, data)
await expect(tx).to.be.fulfilled
})
})
describe('When gas is NOT reimbursed', () => {
before(async function() {
if (condition[0]) {
this.test!.parent!.pending = true
this.skip()
}
})
it('should PASS if gas receipt is not passed and not claimed', async () => {
const tx = operatorERC1155Contract.metaSetApprovalForAll(ownerAddress, operatorAddress, approved, false, data)
await expect(tx).to.be.fulfilled
})
it('should REVER if gas receipt is not passed and claimed', async () => {
const tx = operatorERC1155Contract.metaSetApprovalForAll(ownerAddress, operatorAddress, approved, true, data)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should REVERT if gas receipt is not passed but isGasFee is set to true and is claimed', async () => {
approvalObj.isGasFee = true
data = await encodeMetaApprovalData(approvalObj, domainHash)
const tx = operatorERC1155Contract.metaSetApprovalForAll(ownerAddress, operatorAddress, approved, true, data)
await expect(tx).to.be.rejectedWith(RevertError())
})
})
it('should REVERT if contract address is incorrect', async () => {
domainHash = utils.keccak256(utils.solidityPack(['bytes32', 'uint256'], [DOMAIN_SEPARATOR_TYPEHASH, receiverAddress]))
data = await encodeMetaApprovalData(approvalObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSetApprovalForAll(ownerAddress, operatorAddress, approved, isGasReimbursed, data)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should REVERT if operator address is incorrect', async () => {
approvalObj.operator = receiverAddress
data = await encodeMetaApprovalData(approvalObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSetApprovalForAll(ownerAddress, operatorAddress, approved, isGasReimbursed, data)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should REVERT if approved value is incorrect', async () => {
approvalObj.approved = false
data = await encodeMetaApprovalData(approvalObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSetApprovalForAll(ownerAddress, operatorAddress, approved, isGasReimbursed, data)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_SIGNATURE'))
})
it('should REVERT if nonce is incorrect', async () => {
approvalObj.nonce = nonce.add(101)
data = await encodeMetaApprovalData(approvalObj, domainHash, gasReceipt)
// Nonce higher
const tx = operatorERC1155Contract.metaSetApprovalForAll(ownerAddress, operatorAddress, approved, isGasReimbursed, data)
await expect(tx).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_NONCE'))
// Correct nonce
approvalObj.nonce = nonce
data = await encodeMetaApprovalData(approvalObj, domainHash, gasReceipt)
await operatorERC1155Contract.metaSetApprovalForAll(ownerAddress, operatorAddress, approved, isGasReimbursed, data)
// Nonce lower
const tx2 = operatorERC1155Contract.metaSetApprovalForAll(
ownerAddress,
operatorAddress,
approved,
isGasReimbursed,
data
)
await expect(tx2).to.be.rejectedWith(RevertError('ERC1155Meta#_signatureValidation: INVALID_NONCE'))
})
it('should emit an ApprovalForAll event', async () => {
const tx = await operatorERC1155Contract.metaSetApprovalForAll(
ownerAddress,
operatorAddress,
approved,
isGasReimbursed,
data
)
const receipt = await tx.wait(1)
expect(receipt.events![1].event).to.be.eql('ApprovalForAll')
})
it('should set the operator status to _status argument', async () => {
const tx = operatorERC1155Contract.metaSetApprovalForAll(ownerAddress, operatorAddress, approved, isGasReimbursed, data)
await expect(tx).to.be.fulfilled
const status = await erc1155Contract.isApprovedForAll(ownerAddress, operatorAddress)
expect(status).to.be.eql(true)
})
it('should emit NonceChange event', async () => {
const tx = await operatorERC1155Contract.metaSetApprovalForAll(
ownerAddress,
operatorAddress,
approved,
isGasReimbursed,
data
)
const receipt = await tx.wait(1)
const ev = receipt.events![0]
expect(ev.event).to.be.eql('NonceChange')
})
it('should have `_signer` as `signer` in NonceChange', async () => {
const tx = await operatorERC1155Contract.metaSetApprovalForAll(
ownerAddress,
operatorAddress,
approved,
isGasReimbursed,
data
)
const receipt = await tx.wait(1)
const ev = receipt.events![0]
const args = ev.args! as any
expect(args.signer).to.be.eql(ownerWallet.address)
})
it('should have `nonce` as `nonce + 1` in NonceChange', async () => {
const tx = await operatorERC1155Contract.metaSetApprovalForAll(
ownerAddress,
operatorAddress,
approved,
isGasReimbursed,
data
)
const receipt = await tx.wait(1)
const ev = receipt.events![0]
const args = ev.args! as any
expect(args.newNonce).to.be.eql(nonce.add(1))
})
context('When the operator was already an operator', () => {
beforeEach(async () => {
const tx = await operatorERC1155Contract.metaSetApprovalForAll(
ownerAddress,
operatorAddress,
approved,
isGasReimbursed,
data
)
// Update nonce of approval signature object for subsequent tests
approvalObj.nonce = nonce.add(1)
})
it('should leave the operator status to set to true again', async () => {
data = await encodeMetaApprovalData(approvalObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSetApprovalForAll(
ownerAddress,
operatorAddress,
approved,
isGasReimbursed,
data
)
await expect(tx).to.be.fulfilled
const status = await erc1155Contract.isApprovedForAll(ownerAddress, operatorAddress)
expect(status).to.be.eql(true)
})
it('should allow the operator status to be set to false', async () => {
approvalObj.approved = false
data = await encodeMetaApprovalData(approvalObj, domainHash, gasReceipt)
const tx = operatorERC1155Contract.metaSetApprovalForAll(ownerAddress, operatorAddress, false, isGasReimbursed, data)
await expect(tx).to.be.fulfilled
const status = await erc1155Contract.isApprovedForAll(operatorAddress, ownerAddress)
expect(status).to.be.eql(false)
})
})
})
})
})
}) | the_stack |
import * as XrmMock from "../xrm-mock/index";
import Control, { CreateMethods as ControlCreateMethods } from "./control";
export type BooleanControlComponent = XrmMock.IAttBooleanControlComponents | XrmMock.IAttBooleanControlComponents[];
export type DateControlComponent = XrmMock.IAttDateControlComponents | XrmMock.IAttDateControlComponents[];
export type LookupControlComponent = XrmMock.IAttLookupControlComponents | XrmMock.IAttLookupControlComponents[];
export type NumberControlComponent = XrmMock.IAttNumberControlComponents | XrmMock.IAttNumberControlComponents[];
export type OptionSetControlComponent = XrmMock.IAttOptionSetControlComponents | XrmMock.IAttOptionSetControlComponents[];
export type StringControlComponent = XrmMock.IAttStringControlComponents | XrmMock.IAttStringControlComponents[];
export default class Attribute {
private Control = new Control();
public createBoolean(attComponents: XrmMock.IBooleanAttributeComponents, controlComponents?: BooleanControlComponent): XrmMock.BooleanAttributeMock;
public createBoolean(name: string, value?: boolean): XrmMock.BooleanAttributeMock;
public createBoolean(nameOrComponents: string | XrmMock.IBooleanAttributeComponents,
valueOrControlComponents: BooleanControlComponent | boolean): XrmMock.BooleanAttributeMock {
if (typeof(nameOrComponents) === "string") {
const components = { name: nameOrComponents, value: valueOrControlComponents as boolean };
const controls = [{name: nameOrComponents}];
return this.associateAttribute(new XrmMock.BooleanAttributeMock(components), controls, "createBoolean");
} else {
return this.associateAttribute(new XrmMock.BooleanAttributeMock(nameOrComponents),
this.arrayify(valueOrControlComponents as BooleanControlComponent),
"createBoolean");
}
}
public createDate(attComponents: XrmMock.IDateAttributeComponents, controlComponents?: DateControlComponent): XrmMock.DateAttributeMock;
public createDate(name: string, value?: Date): XrmMock.DateAttributeMock;
public createDate(nameOrComponents: string | XrmMock.IDateAttributeComponents,
valueOrControlComponents?: Date | DateControlComponent): XrmMock.DateAttributeMock {
if (typeof(nameOrComponents) === "string") {
const components = { name: nameOrComponents, value: valueOrControlComponents as Date };
const controls = [{name: nameOrComponents}];
return this.associateAttribute(new XrmMock.DateAttributeMock(components), controls, "createDate");
} else {
return this.associateAttribute(new XrmMock.DateAttributeMock(nameOrComponents),
this.arrayify(valueOrControlComponents as StringControlComponent),
"createDate");
}
}
public createLookup(attComponents: XrmMock.ILookupAttributeComponents, controlComponents?: LookupControlComponent): XrmMock.LookupAttributeMock;
public createLookup(name: string, lookup: Xrm.LookupValue | Xrm.LookupValue[]): XrmMock.LookupAttributeMock;
public createLookup(nameOrComponents: string | XrmMock.ILookupAttributeComponents,
valueOrControlComponents?: Xrm.LookupValue | Xrm.LookupValue[] | LookupControlComponent): XrmMock.LookupAttributeMock {
if (typeof(nameOrComponents) === "string") {
const components: XrmMock.ILookupAttributeComponents = {
isPartyList: valueOrControlComponents && Array.isArray(valueOrControlComponents),
name: nameOrComponents,
value: this.arrayify(valueOrControlComponents as Xrm.LookupValue) };
const controls = [{name: nameOrComponents}];
return this.associateAttribute(new XrmMock.LookupAttributeMock(components), controls, "createLookup");
} else {
return this.associateAttribute(new XrmMock.LookupAttributeMock(nameOrComponents),
this.arrayify(valueOrControlComponents as LookupControlComponent),
"createLookup");
}
}
public createNumber(attComponents: XrmMock.INumberAttributeComponents, controlComponents?: NumberControlComponent): XrmMock.NumberAttributeMock;
public createNumber(name: string, value?: number): XrmMock.NumberAttributeMock;
public createNumber(nameOrComponents: string | XrmMock.INumberAttributeComponents,
valueOrControlComponents: NumberControlComponent | number): XrmMock.NumberAttributeMock {
if (typeof(nameOrComponents) === "string") {
const components = { name: nameOrComponents, value: valueOrControlComponents as number };
const controls = [{name: nameOrComponents}];
return this.associateAttribute(new XrmMock.NumberAttributeMock(components), controls, "createNumber");
} else {
return this.associateAttribute(new XrmMock.NumberAttributeMock(nameOrComponents),
this.arrayify(valueOrControlComponents as NumberControlComponent),
"createNumber");
}
}
public createOptionSet(attComponents: XrmMock.IOptionSetAttributeComponents, controlComponents?: OptionSetControlComponent): XrmMock.OptionSetAttributeMock;
public createOptionSet(name: string, value?: string | number, options?: Xrm.OptionSetValue[]): XrmMock.OptionSetAttributeMock;
public createOptionSet(nameOrComponents: string | XrmMock.IOptionSetAttributeComponents,
valueOrControlComponents?: string | number | OptionSetControlComponent,
options?: Xrm.OptionSetValue[]): XrmMock.OptionSetAttributeMock {
return typeof(nameOrComponents) === "string"
? this.createOptionSetFromParameters(nameOrComponents, valueOrControlComponents as string | number, options)
: this.createOptionSetFromComponents(nameOrComponents,
this.arrayify(valueOrControlComponents as OptionSetControlComponent));
}
public createString(attComponents: XrmMock.IStringAttributeComponents, controlComponents?: StringControlComponent): XrmMock.StringAttributeMock;
public createString(name: string, value?: string): XrmMock.StringAttributeMock;
public createString(nameOrComponents: string | XrmMock.IStringAttributeComponents,
valueOrControlComponents: StringControlComponent | string = ""): XrmMock.StringAttributeMock {
if (typeof(nameOrComponents) === "string") {
const components = { name: nameOrComponents, value: valueOrControlComponents as string };
const controls = [{name: nameOrComponents}];
return this.associateAttribute(new XrmMock.StringAttributeMock(components), controls, "createString");
} else {
return this.associateAttribute(new XrmMock.StringAttributeMock(nameOrComponents),
this.arrayify(valueOrControlComponents as StringControlComponent),
"createString");
}
}
private createOptionSetFromParameters(name: string,
value: string | number,
options: Xrm.OptionSetValue[]): XrmMock.OptionSetAttributeMock {
let num: number;
if (value !== null
&& value !== undefined) {
if (!options) {
options = [typeof value === "string"
? { text: value, value: 0 }
: { text: value.toString(), value }];
}
if (typeof value === "string") {
const option = options.filter((o) => o.text === value)[0];
num = option.value;
} else {
num = value;
}
} else {
num = undefined;
}
const components: XrmMock.IOptionSetAttributeComponents = {
name,
options,
};
if (num || num === 0) {
components.value = num;
}
const controls = [{ name, options }];
return this.associateAttribute(new XrmMock.OptionSetAttributeMock(components), controls, "createOptionSet");
}
private createOptionSetFromComponents(components: XrmMock.IOptionSetAttributeComponents,
controls: XrmMock.IAttOptionSetControlComponents[])
: XrmMock.OptionSetAttributeMock {
if (components.options && components.options.length > 0) {
controls.filter((c) => !c.options)
.forEach((c) => {
c.options = components.options;
});
}
return this.associateAttribute(new XrmMock.OptionSetAttributeMock(components), controls, "createOptionSet");
}
private createStringFromParameters(name: string, value: string): XrmMock.StringAttributeMock {
const components = { name, value };
const controls = [{name}];
return this. associateAttribute(new XrmMock.StringAttributeMock(components), controls, "createString");
}
private createAttribute(name: string, value: any): any {
const attribute = new XrmMock.AttributeMock({
isDirty: false,
name,
submitMode: "dirty",
value,
});
return attribute;
}
private addAttribute(attribute: Xrm.Attributes.Attribute): void {
(Xrm.Page.data.entity as XrmMock.EntityMock).attributes.push(attribute);
}
/**
* Creates the given attribute, as well as the controls for the attribute defined by the components
* @param attribute The newly created attribute to be added to the page colleciton of attributes
* @param controls Array of Control Components to create controls for the given attribute
* @param controlCreateFunction the name of the Control function to call to create the correct type of control
*/
private associateAttribute<TAtt extends Xrm.Attributes.Attribute>(attribute: TAtt,
controls: any[],
controlCreateFunction: ControlCreateMethods): TAtt {
this.addAttribute(attribute);
controls.forEach((c) => {
c.attribute = attribute;
this.defaultName(c, attribute);
(this.Control[controlCreateFunction] as any)(c);
});
return attribute;
}
private defaultName(control: any, attribute: Xrm.Attributes.Attribute) {
const names: string[] = [];
attribute.controls.forEach((c) => {
names.push(c.getName());
});
if (!control.name) {
control.name = attribute.getName();
} else if (names.indexOf(control.name) >= 0) {
throw new Error(`Name ${control.name} has already been defined for a control for attribute ${attribute.getName()}`);
}
let i = 1;
while (names.indexOf(control.name) >= 0) {
control.name = attribute.getName() + i++;
}
}
private arrayify<T>(possibleArray: T[] | T): T[] {
if (!possibleArray) {
return [];
} else if (possibleArray instanceof Array) {
return possibleArray;
} else {
return [possibleArray];
}
}
} | the_stack |
import { ApplyPluginsType, dynamic } from '/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/node_modules/@umijs/runtime';
import { plugin } from './plugin';
const routes = [
{
"path": "/xadmin/login",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'layouts__UserLayout' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/layouts/UserLayout'), loading: require('@/components/PageLoading/index').default}),
"routes": [
{
"name": "login",
"path": "/xadmin/login",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__TyAdminBuiltIn__UserLogin' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/TyAdminBuiltIn/UserLogin'), loading: require('@/components/PageLoading/index').default}),
"exact": true
}
]
},
{
"path": "/xadmin/",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'layouts__SecurityLayout' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/layouts/SecurityLayout'), loading: require('@/components/PageLoading/index').default}),
"routes": [
{
"path": "/xadmin/",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'layouts__BasicLayout' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/layouts/BasicLayout'), loading: require('@/components/PageLoading/index').default}),
"authority": [
"admin",
"user"
],
"routes": [
{
"name": "Home",
"path": "/xadmin/index",
"icon": "dashboard",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__TyAdminBuiltIn__DashBoard' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/TyAdminBuiltIn/DashBoard'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"path": "/xadmin/",
"redirect": "/xadmin/index",
"exact": true
},
{
"name": "认证和授权",
"icon": "BarsOutlined",
"path": "/xadmin/auth",
"routes": [
{
"name": "权限",
"path": "/xadmin/auth/permission",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__PermissionList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/PermissionList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "组",
"path": "/xadmin/auth/group",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__GroupList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/GroupList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
}
]
},
{
"name": "课程管理",
"icon": "VideoCamera",
"path": "/xadmin/lessson",
"routes": [
{
"name": "课程方向",
"icon": "smile",
"path": "/xadmin/lessson/label_type",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__LabelTypeList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/LabelTypeList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "课程分类",
"icon": "smile",
"path": "/xadmin/lessson/label",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__LabelList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/LabelList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "课程类型",
"icon": "smile",
"path": "/xadmin/lessson/lesson_type",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__LessonTypeList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/LessonTypeList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "课程本课",
"icon": "smile",
"path": "/xadmin/lessson/lesson",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__LessonList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/LessonList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "课程章节",
"icon": "smile",
"path": "/xadmin/lessson/chapter",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__ChapterList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/ChapterList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "章节小节",
"icon": "smile",
"path": "/xadmin/lessson/term",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__TermList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/TermList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "课程简介",
"icon": "smile",
"path": "/xadmin/lessson/catalog",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__CatalogList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/CatalogList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "课程评论",
"icon": "smile",
"path": "/xadmin/lessson/comment",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__CommentList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/CommentList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "课程提问",
"icon": "smile",
"path": "/xadmin/lessson/qa",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__QaList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/QaList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "问题状态",
"icon": "smile",
"path": "/xadmin/lessson/qa_type",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__QaTypeList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/QaTypeList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "课程难度",
"icon": "smile",
"path": "/xadmin/lessson/lesson_hard_type",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__LessonHardTypeList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/LessonHardTypeList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "课程角标",
"icon": "smile",
"path": "/xadmin/lessson/lesson_script",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__LessonScriptList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/LessonScriptList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
}
]
},
{
"name": "专栏管理",
"icon": "book",
"path": "/xadmin/read",
"routes": [
{
"name": "专栏分类",
"icon": "smile",
"path": "/xadmin/read/read_type",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__ReadTypeList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/ReadTypeList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "专栏章节",
"icon": "smile",
"path": "/xadmin/read/read_chapter",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__ReadChapterList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/ReadChapterList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "章节子节",
"icon": "smile",
"path": "/xadmin/read/read_chapter_item",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__ReadChapterItemList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/ReadChapterItemList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
}
]
},
{
"name": "猿问管理",
"icon": "QuestionCircle",
"path": "/xadmin/qa",
"routes": [
{
"name": "问题列表",
"icon": "smile",
"path": "/xadmin/qa/question",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__QuestionList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/QuestionList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "关注标签",
"icon": "smile",
"path": "/xadmin/qa/label_follow",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__LabelFollowList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/LabelFollowList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "回答列表",
"icon": "smile",
"path": "/xadmin/qa/answer",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__AnswerList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/AnswerList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
}
]
},
{
"name": "手记管理",
"icon": "PaperClip",
"path": "/xadmin/article",
"routes": [
{
"name": "文章列表",
"icon": "smile",
"path": "/xadmin/article/article",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__ArticleList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/ArticleList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "文章类型",
"icon": "smile",
"path": "/xadmin/article/article_type",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__ArticleTypeList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/ArticleTypeList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
}
]
},
{
"name": "优惠管理",
"icon": "MoneyCollect",
"path": "/xadmin/coupon",
"routes": [
{
"name": "优惠券码",
"icon": "smile",
"path": "/xadmin/coupon/coupon",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__CouponList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/CouponList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "优惠状态",
"icon": "smile",
"path": "/xadmin/coupon/coupon_status",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__CouponStatusList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/CouponStatusList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "优惠范围",
"icon": "smile",
"path": "/xadmin/coupon/coupon_range",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__CouponRangeList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/CouponRangeList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
}
]
},
{
"name": "订单管理",
"icon": "OrderedList",
"path": "/xadmin/order",
"routes": [
{
"name": "购物车车",
"icon": "smile",
"path": "/xadmin/order/cart",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__CartList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/CartList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "订单列表",
"icon": "smile",
"path": "/xadmin/order/order",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__OrderList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/OrderList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "订单子项",
"icon": "smile",
"path": "/xadmin/order/order_item",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__OrderItemList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/OrderItemList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "订单状态",
"icon": "smile",
"path": "/xadmin/order/order_status",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__OrderStatusList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/OrderStatusList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
}
]
},
{
"name": "充值管理",
"icon": "PayCircle",
"path": "/xadmin/pay",
"routes": [
{
"name": "充值记录",
"icon": "smile",
"path": "/xadmin/pay/recharge",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__RechargeList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/RechargeList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "充值类型",
"icon": "smile",
"path": "/xadmin/pay/recharge_action",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__RechargeActionList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/RechargeActionList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "充值方式",
"icon": "smile",
"path": "/xadmin/pay/recharge_pay",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__RechargePayList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/RechargePayList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
}
]
},
{
"name": "用户管理",
"icon": "UsergroupAdd",
"path": "/xadmin/user",
"routes": [
{
"name": "课程讲师",
"icon": "smile",
"path": "/xadmin/user/teacher",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__TeacherList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/TeacherList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "学生类型",
"icon": "smile",
"path": "/xadmin/user/student_type",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__StudentTypeList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/StudentTypeList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "学生列表",
"icon": "smile",
"path": "/xadmin/user/student",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__StudentList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/StudentList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
}
]
},
{
"name": "积分商城",
"icon": "Shop",
"path": "/xadmin/integral/",
"routes": [
{
"name": "商品类别",
"icon": "smile",
"path": "/xadmin/integral/integral_type",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__IntegralTypeList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/IntegralTypeList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "积分商品",
"icon": "smile",
"path": "/xadmin/integral/integral",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__IntegralList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/IntegralList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
}
]
},
{
"name": "用户中心",
"icon": "user",
"path": "/xadmin/user_info",
"routes": [
{
"name": "学习课程",
"icon": "smile",
"path": "/xadmin/user_info/user_lesson",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__UserLessonList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/UserLessonList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "用户通知",
"icon": "smile",
"path": "/xadmin/user_info/user_notice",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__UserNoticeList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/UserNoticeList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "搜索历史",
"icon": "smile",
"path": "/xadmin/user_info/history",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__HistoryList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/HistoryList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "用户咨询",
"icon": "smile",
"path": "/xadmin/user_info/consult",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__ConsultList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/ConsultList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "购买账单",
"icon": "smile",
"path": "/xadmin/user_info/bill",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__BillList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/BillList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "地址信息",
"icon": "smile",
"path": "/xadmin/user_info/address",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__AddressList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/AddressList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "登录类型",
"icon": "smile",
"path": "/xadmin/user_info/log_type",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__LogTypeList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/LogTypeList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "登录日志",
"icon": "smile",
"path": "/xadmin/user_info/log",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__LogList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/LogList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
}
]
},
{
"name": "首页管理",
"icon": "setting",
"path": "/xadmin/home",
"routes": [
{
"name": "首页大图",
"icon": "smile",
"path": "/xadmin/home/slider",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__SliderList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/SliderList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "首页菜单",
"icon": "smile",
"path": "/xadmin/home/navigation",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__NavigationList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/NavigationList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "公共配置",
"icon": "smile",
"path": "/xadmin/home/common_path_config",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__CommonPathConfigList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/CommonPathConfigList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "首页导航",
"icon": "smile",
"path": "/xadmin/home/nav",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__NavList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/NavList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "底部配置",
"icon": "smile",
"path": "/xadmin/home/footer",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__FooterList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/FooterList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
}
]
},
{
"name": "系统管理",
"icon": "setting",
"path": "/xadmin/sys",
"routes": [
{
"name": "系统日志",
"icon": "smile",
"path": "/xadmin/sys/sys_log",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__SysLogList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/SysLogList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "热搜榜单",
"icon": "smile",
"path": "/xadmin/sys/hot",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__HotList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/HotList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "系统通知",
"icon": "smile",
"path": "/xadmin/sys/notice",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__NoticeList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/NoticeList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "系统用户",
"icon": "smile",
"path": "/xadmin/sys/user",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__AutoGenPage__UserList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/AutoGenPage/UserList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
}
]
},
{
"name": "TyadminBuiltin",
"icon": "VideoCamera",
"path": "/xadmin/sys",
"routes": [
{
"name": "TyAdminLog",
"icon": "smile",
"path": "/xadmin/sys/ty_admin_sys_log",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__TyAdminBuiltIn__TyAdminSysLogList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/TyAdminBuiltIn/TyAdminSysLogList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"name": "TyAdminVerify",
"icon": "smile",
"path": "/xadmin/sys/ty_admin_email_verify_record",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__TyAdminBuiltIn__TyAdminEmailVerifyRecordList' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/TyAdminBuiltIn/TyAdminEmailVerifyRecordList'), loading: require('@/components/PageLoading/index').default}),
"exact": true
}
]
},
{
"name": "passwordModify",
"path": "/xadmin/account/change_password",
"hideInMenu": true,
"icon": "dashboard",
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__TyAdminBuiltIn__ChangePassword' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/TyAdminBuiltIn/ChangePassword'), loading: require('@/components/PageLoading/index').default}),
"exact": true
},
{
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__404' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/404'), loading: require('@/components/PageLoading/index').default}),
"exact": true
}
]
},
{
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__404' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/404'), loading: require('@/components/PageLoading/index').default}),
"exact": true
}
]
},
{
"component": dynamic({ loader: () => import(/* webpackChunkName: 'p__404' */'/Users/mtianyan/tyRepos/Python/OnlineMooc/tyadmin/src/pages/404'), loading: require('@/components/PageLoading/index').default}),
"exact": true
}
];
// allow user to extend routes
plugin.applyPlugins({
key: 'patchRoutes',
type: ApplyPluginsType.event,
args: { routes },
});
export { routes }; | the_stack |
import { PROF_COLS, UNICODE_BLOCK } from "../src/constants";
import { SelectionBroker } from "../src/selection-broker";
import { TextView } from "../src/text-view";
import { MySelection } from "./selection";
import { anyToString, interpolate } from "./util";
import { InstructionSelectionHandler } from "./selection-handler";
const toolboxHTML = `<div id="disassembly-toolbox">
<form>
<label><input id="show-instruction-address" type="checkbox" name="instruction-address">Show addresses</label>
<label><input id="show-instruction-binary" type="checkbox" name="instruction-binary">Show binary literal</label>
</form>
</div>`;
export class DisassemblyView extends TextView {
SOURCE_POSITION_HEADER_REGEX: any;
addrEventCounts: any;
totalEventCounts: any;
maxEventCounts: any;
posLines: Array<any>;
instructionSelectionHandler: InstructionSelectionHandler;
offsetSelection: MySelection;
showInstructionAddressHandler: () => void;
showInstructionBinaryHandler: () => void;
createViewElement() {
const pane = document.createElement('div');
pane.setAttribute('id', "disassembly");
pane.innerHTML =
`<pre id='disassembly-text-pre' class='prettyprint prettyprinted'>
<ul id='disassembly-list' class='nolinenums noindent'>
</ul>
</pre>`;
return pane;
}
constructor(parentId, broker: SelectionBroker) {
super(parentId, broker);
const view = this;
const ADDRESS_STYLE = {
associateData: (text, fragment: HTMLElement) => {
const matches = text.match(/(?<address>0?x?[0-9a-fA-F]{8,16})(?<addressSpace>\s+)(?<offset>[0-9a-f]+)(?<offsetSpace>\s*)/);
const offset = Number.parseInt(matches.groups["offset"], 16);
const addressElement = document.createElement("SPAN");
addressElement.className = "instruction-address";
addressElement.innerText = matches.groups["address"];
const offsetElement = document.createElement("SPAN");
offsetElement.innerText = matches.groups["offset"];
fragment.appendChild(addressElement);
fragment.appendChild(document.createTextNode(matches.groups["addressSpace"]));
fragment.appendChild(offsetElement);
fragment.appendChild(document.createTextNode(matches.groups["offsetSpace"]));
fragment.classList.add('tag');
if (!Number.isNaN(offset)) {
const pcOffset = view.sourceResolver.getKeyPcOffset(offset);
fragment.dataset.pcOffset = `${pcOffset}`;
addressElement.classList.add('linkable-text');
offsetElement.classList.add('linkable-text');
}
}
};
const UNCLASSIFIED_STYLE = {
css: 'com'
};
const NUMBER_STYLE = {
css: ['instruction-binary', 'lit']
};
const COMMENT_STYLE = {
css: 'com'
};
const OPCODE_ARGS = {
associateData: function (text, fragment) {
fragment.innerHTML = text;
const replacer = (match, hexOffset) => {
const offset = Number.parseInt(hexOffset, 16);
const keyOffset = view.sourceResolver.getKeyPcOffset(offset);
return `<span class="tag linkable-text" data-pc-offset="${keyOffset}">${match}</span>`;
};
const html = text.replace(/<.0?x?([0-9a-fA-F]+)>/g, replacer);
fragment.innerHTML = html;
}
};
const OPCODE_STYLE = {
css: 'kwd'
};
const BLOCK_HEADER_STYLE = {
associateData: function (text, fragment) {
const matches = /\d+/.exec(text);
if (!matches) return;
const blockId = matches[0];
fragment.dataset.blockId = blockId;
fragment.innerHTML = text;
fragment.className = "com block";
}
};
const SOURCE_POSITION_HEADER_STYLE = {
css: 'com'
};
view.SOURCE_POSITION_HEADER_REGEX = /^\s*--[^<]*<.*(not inlined|inlined\((\d+)\)):(\d+)>\s*--/;
const patterns = [
[
[/^0?x?[0-9a-fA-F]{8,16}\s+[0-9a-f]+\s+/, ADDRESS_STYLE, 1],
[view.SOURCE_POSITION_HEADER_REGEX, SOURCE_POSITION_HEADER_STYLE, -1],
[/^\s+-- B\d+ start.*/, BLOCK_HEADER_STYLE, -1],
[/^.*/, UNCLASSIFIED_STYLE, -1]
],
[
[/^\s*[0-9a-f]+\s+/, NUMBER_STYLE, 2],
[/^\s*[0-9a-f]+\s+[0-9a-f]+\s+/, NUMBER_STYLE, 2],
[/^.*/, null, -1]
],
[
[/^REX.W \S+\s+/, OPCODE_STYLE, 3],
[/^\S+\s+/, OPCODE_STYLE, 3],
[/^\S+$/, OPCODE_STYLE, -1],
[/^.*/, null, -1]
],
[
[/^\s+/, null],
[/^[^;]+$/, OPCODE_ARGS, -1],
[/^[^;]+/, OPCODE_ARGS, 4],
[/^;/, COMMENT_STYLE, 5]
],
[
[/^.+$/, COMMENT_STYLE, -1]
]
];
view.setPatterns(patterns);
const linkHandler = (e: MouseEvent) => {
if (!(e.target instanceof HTMLElement)) return;
const offsetAsString = e.target.dataset.pcOffset ? e.target.dataset.pcOffset : e.target.parentElement.dataset.pcOffset;
const offset = Number.parseInt(offsetAsString, 10);
if ((typeof offsetAsString) != "undefined" && !Number.isNaN(offset)) {
view.offsetSelection.select([offset], true);
const nodes = view.sourceResolver.nodesForPCOffset(offset)[0];
if (nodes.length > 0) {
e.stopPropagation();
if (!e.shiftKey) {
view.selectionHandler.clear();
}
view.selectionHandler.select(nodes, true);
} else {
view.updateSelection();
}
}
return undefined;
};
view.divNode.addEventListener('click', linkHandler);
const linkHandlerBlock = e => {
const blockId = e.target.dataset.blockId;
if (typeof blockId != "undefined" && !Number.isNaN(blockId)) {
e.stopPropagation();
if (!e.shiftKey) {
view.selectionHandler.clear();
}
view.blockSelectionHandler.select([blockId], true);
}
};
view.divNode.addEventListener('click', linkHandlerBlock);
this.offsetSelection = new MySelection(anyToString);
const instructionSelectionHandler = {
clear: function () {
view.offsetSelection.clear();
view.updateSelection();
broker.broadcastClear(instructionSelectionHandler);
},
select: function (instructionIds, selected) {
view.offsetSelection.select(instructionIds, selected);
view.updateSelection();
broker.broadcastBlockSelect(instructionSelectionHandler, instructionIds, selected);
},
brokeredInstructionSelect: function (instructionIds, selected) {
const firstSelect = view.offsetSelection.isEmpty();
const keyPcOffsets = view.sourceResolver.instructionsToKeyPcOffsets(instructionIds);
view.offsetSelection.select(keyPcOffsets, selected);
view.updateSelection(firstSelect);
},
brokeredClear: function () {
view.offsetSelection.clear();
view.updateSelection();
}
};
this.instructionSelectionHandler = instructionSelectionHandler;
broker.addInstructionHandler(instructionSelectionHandler);
const toolbox = document.createElement("div");
toolbox.id = "toolbox-anchor";
toolbox.innerHTML = toolboxHTML;
view.divNode.insertBefore(toolbox, view.divNode.firstChild);
const instructionAddressInput: HTMLInputElement = view.divNode.querySelector("#show-instruction-address");
const lastShowInstructionAddress = window.sessionStorage.getItem("show-instruction-address");
instructionAddressInput.checked = lastShowInstructionAddress == 'true';
const showInstructionAddressHandler = () => {
window.sessionStorage.setItem("show-instruction-address", `${instructionAddressInput.checked}`);
for (const el of view.divNode.querySelectorAll(".instruction-address")) {
el.classList.toggle("invisible", !instructionAddressInput.checked);
}
};
instructionAddressInput.addEventListener("change", showInstructionAddressHandler);
this.showInstructionAddressHandler = showInstructionAddressHandler;
const instructionBinaryInput: HTMLInputElement = view.divNode.querySelector("#show-instruction-binary");
const lastShowInstructionBinary = window.sessionStorage.getItem("show-instruction-binary");
instructionBinaryInput.checked = lastShowInstructionBinary == 'true';
const showInstructionBinaryHandler = () => {
window.sessionStorage.setItem("show-instruction-binary", `${instructionBinaryInput.checked}`);
for (const el of view.divNode.querySelectorAll(".instruction-binary")) {
el.classList.toggle("invisible", !instructionBinaryInput.checked);
}
};
instructionBinaryInput.addEventListener("change", showInstructionBinaryHandler);
this.showInstructionBinaryHandler = showInstructionBinaryHandler;
}
updateSelection(scrollIntoView: boolean = false) {
super.updateSelection(scrollIntoView);
const keyPcOffsets = this.sourceResolver.nodesToKeyPcOffsets(this.selection.selectedKeys());
if (this.offsetSelection) {
for (const key of this.offsetSelection.selectedKeys()) {
keyPcOffsets.push(Number(key));
}
}
for (const keyPcOffset of keyPcOffsets) {
const elementsToSelect = this.divNode.querySelectorAll(`[data-pc-offset='${keyPcOffset}']`);
for (const el of elementsToSelect) {
el.classList.toggle("selected", true);
}
}
}
initializeCode(sourceText, sourcePosition: number = 0) {
const view = this;
view.addrEventCounts = null;
view.totalEventCounts = null;
view.maxEventCounts = null;
view.posLines = new Array();
// Comment lines for line 0 include sourcePosition already, only need to
// add sourcePosition for lines > 0.
view.posLines[0] = sourcePosition;
if (sourceText && sourceText != "") {
const base = sourcePosition;
let current = 0;
const sourceLines = sourceText.split("\n");
for (let i = 1; i < sourceLines.length; i++) {
// Add 1 for newline character that is split off.
current += sourceLines[i - 1].length + 1;
view.posLines[i] = base + current;
}
}
}
initializePerfProfile(eventCounts) {
const view = this;
if (eventCounts !== undefined) {
view.addrEventCounts = eventCounts;
view.totalEventCounts = {};
view.maxEventCounts = {};
for (const evName in view.addrEventCounts) {
if (view.addrEventCounts.hasOwnProperty(evName)) {
const keys = Object.keys(view.addrEventCounts[evName]);
const values = keys.map(key => view.addrEventCounts[evName][key]);
view.totalEventCounts[evName] = values.reduce((a, b) => a + b);
view.maxEventCounts[evName] = values.reduce((a, b) => Math.max(a, b));
}
}
} else {
view.addrEventCounts = null;
view.totalEventCounts = null;
view.maxEventCounts = null;
}
}
showContent(data): void {
console.time("disassembly-view");
super.initializeContent(data, null);
this.showInstructionAddressHandler();
this.showInstructionBinaryHandler();
console.timeEnd("disassembly-view");
}
// Shorten decimals and remove trailing zeroes for readability.
humanize(num) {
return num.toFixed(3).replace(/\.?0+$/, "") + "%";
}
processLine(line) {
const view = this;
let fragments = super.processLine(line);
// Add profiling data per instruction if available.
if (view.totalEventCounts) {
const matches = /^(0x[0-9a-fA-F]+)\s+\d+\s+[0-9a-fA-F]+/.exec(line);
if (matches) {
const newFragments = [];
for (const event in view.addrEventCounts) {
if (!view.addrEventCounts.hasOwnProperty(event)) continue;
const count = view.addrEventCounts[event][matches[1]];
let str = " ";
const cssCls = "prof";
if (count !== undefined) {
const perc = count / view.totalEventCounts[event] * 100;
let col = { r: 255, g: 255, b: 255 };
for (let i = 0; i < PROF_COLS.length; i++) {
if (perc === PROF_COLS[i].perc) {
col = PROF_COLS[i].col;
break;
} else if (perc > PROF_COLS[i].perc && perc < PROF_COLS[i + 1].perc) {
const col1 = PROF_COLS[i].col;
const col2 = PROF_COLS[i + 1].col;
const val = perc - PROF_COLS[i].perc;
const max = PROF_COLS[i + 1].perc - PROF_COLS[i].perc;
col.r = Math.round(interpolate(val, max, col1.r, col2.r));
col.g = Math.round(interpolate(val, max, col1.g, col2.g));
col.b = Math.round(interpolate(val, max, col1.b, col2.b));
break;
}
}
str = UNICODE_BLOCK;
const fragment = view.createFragment(str, cssCls);
fragment.title = event + ": " + view.humanize(perc) + " (" + count + ")";
fragment.style.color = "rgb(" + col.r + ", " + col.g + ", " + col.b + ")";
newFragments.push(fragment);
} else {
newFragments.push(view.createFragment(str, cssCls));
}
}
fragments = newFragments.concat(fragments);
}
}
return fragments;
}
detachSelection() { return null; }
public searchInputAction(searchInput: HTMLInputElement, e: Event, onlyVisible: boolean): void {
throw new Error("Method not implemented.");
}
} | the_stack |
import * as zrUtil from 'zrender/src/core/util';
import LinearGradient, { LinearGradientObject } from 'zrender/src/graphic/LinearGradient';
import * as eventTool from 'zrender/src/core/event';
import VisualMapView from './VisualMapView';
import * as graphic from '../../util/graphic';
import * as numberUtil from '../../util/number';
import sliderMove from '../helper/sliderMove';
import * as helper from './helper';
import * as modelUtil from '../../util/model';
import VisualMapModel from './VisualMapModel';
import ContinuousModel from './ContinuousModel';
import GlobalModel from '../../model/Global';
import ExtensionAPI from '../../core/ExtensionAPI';
import Element, { ElementEvent } from 'zrender/src/Element';
import { TextVerticalAlign, TextAlign } from 'zrender/src/core/types';
import { ColorString, Payload } from '../../util/types';
import { parsePercent } from 'zrender/src/contain/text';
import { setAsHighDownDispatcher } from '../../util/states';
import { createSymbol } from '../../util/symbol';
import ZRImage from 'zrender/src/graphic/Image';
import { getECData } from '../../util/innerStore';
const linearMap = numberUtil.linearMap;
const each = zrUtil.each;
const mathMin = Math.min;
const mathMax = Math.max;
// Arbitrary value
const HOVER_LINK_SIZE = 12;
const HOVER_LINK_OUT = 6;
type Orient = VisualMapModel['option']['orient'];
type ShapeStorage = {
handleThumbs: graphic.Path[]
handleLabelPoints: number[][]
handleLabels: graphic.Text[]
inRange: graphic.Polygon
outOfRange: graphic.Polygon
mainGroup: graphic.Group
indicator: graphic.Path
indicatorLabel: graphic.Text
indicatorLabelPoint: number[]
};
type TargetDataIndices = ReturnType<ContinuousModel['findTargetDataIndices']>;
type BarVisual = {
barColor: LinearGradient,
barPoints: number[][]
handlesColor: ColorString[]
};
type Direction = 'left' | 'right' | 'top' | 'bottom';
// Notice:
// Any "interval" should be by the order of [low, high].
// "handle0" (handleIndex === 0) maps to
// low data value: this._dataInterval[0] and has low coord.
// "handle1" (handleIndex === 1) maps to
// high data value: this._dataInterval[1] and has high coord.
// The logic of transform is implemented in this._createBarGroup.
class ContinuousView extends VisualMapView {
static type = 'visualMap.continuous';
type = ContinuousView.type;
visualMapModel: ContinuousModel;
private _shapes = {} as ShapeStorage;
private _dataInterval: number[] = [];
private _handleEnds: number[] = [];
private _orient: Orient;
private _useHandle: boolean;
private _hoverLinkDataIndices: TargetDataIndices = [];
private _dragging: boolean;
private _hovering: boolean;
private _firstShowIndicator: boolean;
private _api: ExtensionAPI;
doRender(
visualMapModel: ContinuousModel,
ecModel: GlobalModel,
api: ExtensionAPI,
payload: {type: string, from: string}
) {
this._api = api;
if (!payload || payload.type !== 'selectDataRange' || payload.from !== this.uid) {
this._buildView();
}
}
private _buildView() {
this.group.removeAll();
const visualMapModel = this.visualMapModel;
const thisGroup = this.group;
this._orient = visualMapModel.get('orient');
this._useHandle = visualMapModel.get('calculable');
this._resetInterval();
this._renderBar(thisGroup);
const dataRangeText = visualMapModel.get('text');
this._renderEndsText(thisGroup, dataRangeText, 0);
this._renderEndsText(thisGroup, dataRangeText, 1);
// Do this for background size calculation.
this._updateView(true);
// After updating view, inner shapes is built completely,
// and then background can be rendered.
this.renderBackground(thisGroup);
// Real update view
this._updateView();
this._enableHoverLinkToSeries();
this._enableHoverLinkFromSeries();
this.positionGroup(thisGroup);
}
private _renderEndsText(group: graphic.Group, dataRangeText: string[], endsIndex?: 0 | 1) {
if (!dataRangeText) {
return;
}
// Compatible with ec2, text[0] map to high value, text[1] map low value.
let text = dataRangeText[1 - endsIndex];
text = text != null ? text + '' : '';
const visualMapModel = this.visualMapModel;
const textGap = visualMapModel.get('textGap');
const itemSize = visualMapModel.itemSize;
const barGroup = this._shapes.mainGroup;
const position = this._applyTransform(
[
itemSize[0] / 2,
endsIndex === 0 ? -textGap : itemSize[1] + textGap
],
barGroup
) as number[];
const align = this._applyTransform(
endsIndex === 0 ? 'bottom' : 'top',
barGroup
);
const orient = this._orient;
const textStyleModel = this.visualMapModel.textStyleModel;
this.group.add(new graphic.Text({
style: {
x: position[0],
y: position[1],
verticalAlign: orient === 'horizontal' ? 'middle' : align as TextVerticalAlign,
align: orient === 'horizontal' ? align as TextAlign : 'center',
text: text,
font: textStyleModel.getFont(),
fill: textStyleModel.getTextColor()
}
}));
}
private _renderBar(targetGroup: graphic.Group) {
const visualMapModel = this.visualMapModel;
const shapes = this._shapes;
const itemSize = visualMapModel.itemSize;
const orient = this._orient;
const useHandle = this._useHandle;
const itemAlign = helper.getItemAlign(visualMapModel, this.api, itemSize);
const mainGroup = shapes.mainGroup = this._createBarGroup(itemAlign);
const gradientBarGroup = new graphic.Group();
mainGroup.add(gradientBarGroup);
// Bar
gradientBarGroup.add(shapes.outOfRange = createPolygon());
gradientBarGroup.add(shapes.inRange = createPolygon(
null,
useHandle ? getCursor(this._orient) : null,
zrUtil.bind(this._dragHandle, this, 'all', false),
zrUtil.bind(this._dragHandle, this, 'all', true)
));
// A border radius clip.
gradientBarGroup.setClipPath(new graphic.Rect({
shape: {
x: 0,
y: 0,
width: itemSize[0],
height: itemSize[1],
r: 3
}
}));
const textRect = visualMapModel.textStyleModel.getTextRect('国');
const textSize = mathMax(textRect.width, textRect.height);
// Handle
if (useHandle) {
shapes.handleThumbs = [];
shapes.handleLabels = [];
shapes.handleLabelPoints = [];
this._createHandle(visualMapModel, mainGroup, 0, itemSize, textSize, orient);
this._createHandle(visualMapModel, mainGroup, 1, itemSize, textSize, orient);
}
this._createIndicator(visualMapModel, mainGroup, itemSize, textSize, orient);
targetGroup.add(mainGroup);
}
private _createHandle(
visualMapModel: ContinuousModel,
mainGroup: graphic.Group,
handleIndex: 0 | 1,
itemSize: number[],
textSize: number,
orient: Orient
) {
const onDrift = zrUtil.bind(this._dragHandle, this, handleIndex, false);
const onDragEnd = zrUtil.bind(this._dragHandle, this, handleIndex, true);
const handleSize = parsePercent(visualMapModel.get('handleSize'), itemSize[0]);
const handleThumb = createSymbol(
visualMapModel.get('handleIcon'),
-handleSize / 2, -handleSize / 2, handleSize, handleSize,
null, true
);
const cursor = getCursor(this._orient);
handleThumb.attr({
cursor: cursor,
draggable: true,
drift: onDrift,
ondragend: onDragEnd,
onmousemove(e) {
eventTool.stop(e.event);
}
});
handleThumb.x = itemSize[0] / 2;
handleThumb.useStyle(visualMapModel.getModel('handleStyle').getItemStyle());
(handleThumb as graphic.Path).setStyle({
strokeNoScale: true,
strokeFirst: true
});
(handleThumb as graphic.Path).style.lineWidth *= 2;
handleThumb.ensureState('emphasis').style = visualMapModel.getModel(['emphasis', 'handleStyle']).getItemStyle();
setAsHighDownDispatcher(handleThumb, true);
mainGroup.add(handleThumb);
// Text is always horizontal layout but should not be effected by
// transform (orient/inverse). So label is built separately but not
// use zrender/graphic/helper/RectText, and is located based on view
// group (according to handleLabelPoint) but not barGroup.
const textStyleModel = this.visualMapModel.textStyleModel;
const handleLabel = new graphic.Text({
cursor: cursor,
draggable: true,
drift: onDrift,
onmousemove(e) {
// Fot mobile devicem, prevent screen slider on the button.
eventTool.stop(e.event);
},
ondragend: onDragEnd,
style: {
x: 0, y: 0, text: '',
font: textStyleModel.getFont(),
fill: textStyleModel.getTextColor()
}
});
handleLabel.ensureState('blur').style = {
opacity: 0.1
};
handleLabel.stateTransition = { duration: 200 };
this.group.add(handleLabel);
const handleLabelPoint = [handleSize, 0];
const shapes = this._shapes;
shapes.handleThumbs[handleIndex] = handleThumb;
shapes.handleLabelPoints[handleIndex] = handleLabelPoint;
shapes.handleLabels[handleIndex] = handleLabel;
}
private _createIndicator(
visualMapModel: ContinuousModel,
mainGroup: graphic.Group,
itemSize: number[],
textSize: number,
orient: Orient
) {
const scale = parsePercent(visualMapModel.get('indicatorSize'), itemSize[0]);
const indicator = createSymbol(
visualMapModel.get('indicatorIcon'),
-scale / 2, -scale / 2, scale, scale,
null, true
);
indicator.attr({
cursor: 'move',
invisible: true,
silent: true,
x: itemSize[0] / 2
});
const indicatorStyle = visualMapModel.getModel('indicatorStyle').getItemStyle();
if (indicator instanceof ZRImage) {
const pathStyle = indicator.style;
indicator.useStyle(zrUtil.extend({
// TODO other properties like x, y ?
image: pathStyle.image,
x: pathStyle.x, y: pathStyle.y,
width: pathStyle.width, height: pathStyle.height
}, indicatorStyle));
}
else {
indicator.useStyle(indicatorStyle);
}
mainGroup.add(indicator);
const textStyleModel = this.visualMapModel.textStyleModel;
const indicatorLabel = new graphic.Text({
silent: true,
invisible: true,
style: {
x: 0, y: 0, text: '',
font: textStyleModel.getFont(),
fill: textStyleModel.getTextColor()
}
});
this.group.add(indicatorLabel);
const indicatorLabelPoint = [
(orient === 'horizontal' ? textSize / 2 : HOVER_LINK_OUT) + itemSize[0] / 2,
0
];
const shapes = this._shapes;
shapes.indicator = indicator;
shapes.indicatorLabel = indicatorLabel;
shapes.indicatorLabelPoint = indicatorLabelPoint;
this._firstShowIndicator = true;
}
private _dragHandle(
handleIndex: 0 | 1 | 'all',
isEnd?: boolean,
// dx is event from ondragend if isEnd is true. It's not used
dx?: number | ElementEvent,
dy?: number
) {
if (!this._useHandle) {
return;
}
this._dragging = !isEnd;
if (!isEnd) {
// Transform dx, dy to bar coordination.
const vertex = this._applyTransform([dx as number, dy], this._shapes.mainGroup, true) as number[];
this._updateInterval(handleIndex, vertex[1]);
this._hideIndicator();
// Considering realtime, update view should be executed
// before dispatch action.
this._updateView();
}
// dragEnd do not dispatch action when realtime.
if (isEnd === !this.visualMapModel.get('realtime')) { // jshint ignore:line
this.api.dispatchAction({
type: 'selectDataRange',
from: this.uid,
visualMapId: this.visualMapModel.id,
selected: this._dataInterval.slice()
});
}
if (isEnd) {
!this._hovering && this._clearHoverLinkToSeries();
}
else if (useHoverLinkOnHandle(this.visualMapModel)) {
this._doHoverLinkToSeries(this._handleEnds[handleIndex as 0 | 1], false);
}
}
private _resetInterval() {
const visualMapModel = this.visualMapModel;
const dataInterval = this._dataInterval = visualMapModel.getSelected();
const dataExtent = visualMapModel.getExtent();
const sizeExtent = [0, visualMapModel.itemSize[1]];
this._handleEnds = [
linearMap(dataInterval[0], dataExtent, sizeExtent, true),
linearMap(dataInterval[1], dataExtent, sizeExtent, true)
];
}
/**
* @private
* @param {(number|string)} handleIndex 0 or 1 or 'all'
* @param {number} dx
* @param {number} dy
*/
private _updateInterval(handleIndex: 0 | 1 | 'all', delta: number) {
delta = delta || 0;
const visualMapModel = this.visualMapModel;
const handleEnds = this._handleEnds;
const sizeExtent = [0, visualMapModel.itemSize[1]];
sliderMove(
delta,
handleEnds,
sizeExtent,
handleIndex,
// cross is forbiden
0
);
const dataExtent = visualMapModel.getExtent();
// Update data interval.
this._dataInterval = [
linearMap(handleEnds[0], sizeExtent, dataExtent, true),
linearMap(handleEnds[1], sizeExtent, dataExtent, true)
];
}
private _updateView(forSketch?: boolean) {
const visualMapModel = this.visualMapModel;
const dataExtent = visualMapModel.getExtent();
const shapes = this._shapes;
const outOfRangeHandleEnds = [0, visualMapModel.itemSize[1]];
const inRangeHandleEnds = forSketch ? outOfRangeHandleEnds : this._handleEnds;
const visualInRange = this._createBarVisual(
this._dataInterval, dataExtent, inRangeHandleEnds, 'inRange'
);
const visualOutOfRange = this._createBarVisual(
dataExtent, dataExtent, outOfRangeHandleEnds, 'outOfRange'
);
shapes.inRange
.setStyle({
fill: visualInRange.barColor
// opacity: visualInRange.opacity
})
.setShape('points', visualInRange.barPoints);
shapes.outOfRange
.setStyle({
fill: visualOutOfRange.barColor
// opacity: visualOutOfRange.opacity
})
.setShape('points', visualOutOfRange.barPoints);
this._updateHandle(inRangeHandleEnds, visualInRange);
}
private _createBarVisual(
dataInterval: number[],
dataExtent: number[],
handleEnds: number[],
forceState: ContinuousModel['stateList'][number]
): BarVisual {
const opts = {
forceState: forceState,
convertOpacityToAlpha: true
};
const colorStops = this._makeColorGradient(dataInterval, opts);
const symbolSizes = [
this.getControllerVisual(dataInterval[0], 'symbolSize', opts) as number,
this.getControllerVisual(dataInterval[1], 'symbolSize', opts) as number
];
const barPoints = this._createBarPoints(handleEnds, symbolSizes);
return {
barColor: new LinearGradient(0, 0, 0, 1, colorStops),
barPoints: barPoints,
handlesColor: [
colorStops[0].color,
colorStops[colorStops.length - 1].color
]
};
}
private _makeColorGradient(
dataInterval: number[],
opts: {
forceState?: ContinuousModel['stateList'][number]
convertOpacityToAlpha?: boolean
}
) {
// Considering colorHue, which is not linear, so we have to sample
// to calculate gradient color stops, but not only caculate head
// and tail.
const sampleNumber = 100; // Arbitrary value.
const colorStops: LinearGradientObject['colorStops'] = [];
const step = (dataInterval[1] - dataInterval[0]) / sampleNumber;
colorStops.push({
color: this.getControllerVisual(dataInterval[0], 'color', opts) as ColorString,
offset: 0
});
for (let i = 1; i < sampleNumber; i++) {
const currValue = dataInterval[0] + step * i;
if (currValue > dataInterval[1]) {
break;
}
colorStops.push({
color: this.getControllerVisual(currValue, 'color', opts) as ColorString,
offset: i / sampleNumber
});
}
colorStops.push({
color: this.getControllerVisual(dataInterval[1], 'color', opts) as ColorString,
offset: 1
});
return colorStops;
}
private _createBarPoints(handleEnds: number[], symbolSizes: number[]) {
const itemSize = this.visualMapModel.itemSize;
return [
[itemSize[0] - symbolSizes[0], handleEnds[0]],
[itemSize[0], handleEnds[0]],
[itemSize[0], handleEnds[1]],
[itemSize[0] - symbolSizes[1], handleEnds[1]]
];
}
private _createBarGroup(itemAlign: helper.ItemAlign) {
const orient = this._orient;
const inverse = this.visualMapModel.get('inverse');
return new graphic.Group(
(orient === 'horizontal' && !inverse)
? {scaleX: itemAlign === 'bottom' ? 1 : -1, rotation: Math.PI / 2}
: (orient === 'horizontal' && inverse)
? {scaleX: itemAlign === 'bottom' ? -1 : 1, rotation: -Math.PI / 2}
: (orient === 'vertical' && !inverse)
? {scaleX: itemAlign === 'left' ? 1 : -1, scaleY: -1}
: {scaleX: itemAlign === 'left' ? 1 : -1}
);
}
private _updateHandle(handleEnds: number[], visualInRange: BarVisual) {
if (!this._useHandle) {
return;
}
const shapes = this._shapes;
const visualMapModel = this.visualMapModel;
const handleThumbs = shapes.handleThumbs;
const handleLabels = shapes.handleLabels;
const itemSize = visualMapModel.itemSize;
const dataExtent = visualMapModel.getExtent();
each([0, 1], function (handleIndex) {
const handleThumb = handleThumbs[handleIndex];
handleThumb.setStyle('fill', visualInRange.handlesColor[handleIndex]);
handleThumb.y = handleEnds[handleIndex];
const val = linearMap(handleEnds[handleIndex], [0, itemSize[1]], dataExtent, true);
const symbolSize = this.getControllerVisual(val, 'symbolSize') as number;
handleThumb.scaleX = handleThumb.scaleY = symbolSize / itemSize[0];
handleThumb.x = itemSize[0] - symbolSize / 2;
// Update handle label position.
const textPoint = graphic.applyTransform(
shapes.handleLabelPoints[handleIndex],
graphic.getTransform(handleThumb, this.group)
);
handleLabels[handleIndex].setStyle({
x: textPoint[0],
y: textPoint[1],
text: visualMapModel.formatValueText(this._dataInterval[handleIndex]),
verticalAlign: 'middle',
align: this._orient === 'vertical' ? this._applyTransform(
'left',
shapes.mainGroup
) as TextAlign : 'center'
});
}, this);
}
private _showIndicator(
cursorValue: number,
textValue: number,
rangeSymbol?: string,
halfHoverLinkSize?: number
) {
const visualMapModel = this.visualMapModel;
const dataExtent = visualMapModel.getExtent();
const itemSize = visualMapModel.itemSize;
const sizeExtent = [0, itemSize[1]];
const shapes = this._shapes;
const indicator = shapes.indicator;
if (!indicator) {
return;
}
indicator.attr('invisible', false);
const opts = {convertOpacityToAlpha: true};
const color = this.getControllerVisual(cursorValue, 'color', opts) as ColorString;
const symbolSize = this.getControllerVisual(cursorValue, 'symbolSize') as number;
const y = linearMap(cursorValue, dataExtent, sizeExtent, true);
const x = itemSize[0] - symbolSize / 2;
const oldIndicatorPos = { x: indicator.x, y: indicator.y };
// Update handle label position.
indicator.y = y;
indicator.x = x;
const textPoint = graphic.applyTransform(
shapes.indicatorLabelPoint,
graphic.getTransform(indicator, this.group)
);
const indicatorLabel = shapes.indicatorLabel;
indicatorLabel.attr('invisible', false);
const align = this._applyTransform('left', shapes.mainGroup);
const orient = this._orient;
const isHorizontal = orient === 'horizontal';
indicatorLabel.setStyle({
text: (rangeSymbol ? rangeSymbol : '') + visualMapModel.formatValueText(textValue),
verticalAlign: isHorizontal ? align as TextVerticalAlign : 'middle',
align: isHorizontal ? 'center' : align as TextAlign
});
const indicatorNewProps = {
x: x,
y: y,
style: {
fill: color
}
};
const labelNewProps = {
style: {
x: textPoint[0],
y: textPoint[1]
}
};
if (visualMapModel.ecModel.isAnimationEnabled() && !this._firstShowIndicator) {
const animationCfg = {
duration: 100,
easing: 'cubicInOut',
additive: true
} as const;
indicator.x = oldIndicatorPos.x;
indicator.y = oldIndicatorPos.y;
indicator.animateTo(indicatorNewProps, animationCfg);
indicatorLabel.animateTo(labelNewProps, animationCfg);
}
else {
indicator.attr(indicatorNewProps);
indicatorLabel.attr(labelNewProps);
}
this._firstShowIndicator = false;
const handleLabels = this._shapes.handleLabels;
if (handleLabels) {
for (let i = 0; i < handleLabels.length; i++) {
// Fade out handle labels.
// NOTE: Must use api enter/leave on emphasis/blur/select state. Or the global states manager will change it.
this._api.enterBlur(handleLabels[i]);
}
}
}
private _enableHoverLinkToSeries() {
const self = this;
this._shapes.mainGroup
.on('mousemove', function (e) {
self._hovering = true;
if (!self._dragging) {
const itemSize = self.visualMapModel.itemSize;
const pos = self._applyTransform(
[e.offsetX, e.offsetY], self._shapes.mainGroup, true, true
);
// For hover link show when hover handle, which might be
// below or upper than sizeExtent.
pos[1] = mathMin(mathMax(0, pos[1]), itemSize[1]);
self._doHoverLinkToSeries(
pos[1],
0 <= pos[0] && pos[0] <= itemSize[0]
);
}
})
.on('mouseout', function () {
// When mouse is out of handle, hoverLink still need
// to be displayed when realtime is set as false.
self._hovering = false;
!self._dragging && self._clearHoverLinkToSeries();
});
}
private _enableHoverLinkFromSeries() {
const zr = this.api.getZr();
if (this.visualMapModel.option.hoverLink) {
zr.on('mouseover', this._hoverLinkFromSeriesMouseOver, this);
zr.on('mouseout', this._hideIndicator, this);
}
else {
this._clearHoverLinkFromSeries();
}
}
private _doHoverLinkToSeries(cursorPos: number, hoverOnBar?: boolean) {
const visualMapModel = this.visualMapModel;
const itemSize = visualMapModel.itemSize;
if (!visualMapModel.option.hoverLink) {
return;
}
const sizeExtent = [0, itemSize[1]];
const dataExtent = visualMapModel.getExtent();
// For hover link show when hover handle, which might be below or upper than sizeExtent.
cursorPos = mathMin(mathMax(sizeExtent[0], cursorPos), sizeExtent[1]);
const halfHoverLinkSize = getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent);
const hoverRange = [cursorPos - halfHoverLinkSize, cursorPos + halfHoverLinkSize];
const cursorValue = linearMap(cursorPos, sizeExtent, dataExtent, true);
const valueRange = [
linearMap(hoverRange[0], sizeExtent, dataExtent, true),
linearMap(hoverRange[1], sizeExtent, dataExtent, true)
];
// Consider data range is out of visualMap range, see test/visualMap-continuous.html,
// where china and india has very large population.
hoverRange[0] < sizeExtent[0] && (valueRange[0] = -Infinity);
hoverRange[1] > sizeExtent[1] && (valueRange[1] = Infinity);
// Do not show indicator when mouse is over handle,
// otherwise labels overlap, especially when dragging.
if (hoverOnBar) {
if (valueRange[0] === -Infinity) {
this._showIndicator(cursorValue, valueRange[1], '< ', halfHoverLinkSize);
}
else if (valueRange[1] === Infinity) {
this._showIndicator(cursorValue, valueRange[0], '> ', halfHoverLinkSize);
}
else {
this._showIndicator(cursorValue, cursorValue, '≈ ', halfHoverLinkSize);
}
}
// When realtime is set as false, handles, which are in barGroup,
// also trigger hoverLink, which help user to realize where they
// focus on when dragging. (see test/heatmap-large.html)
// When realtime is set as true, highlight will not show when hover
// handle, because the label on handle, which displays a exact value
// but not range, might mislead users.
const oldBatch = this._hoverLinkDataIndices;
let newBatch: TargetDataIndices = [];
if (hoverOnBar || useHoverLinkOnHandle(visualMapModel)) {
newBatch = this._hoverLinkDataIndices = visualMapModel.findTargetDataIndices(valueRange);
}
const resultBatches = modelUtil.compressBatches(oldBatch, newBatch);
this._dispatchHighDown('downplay', helper.makeHighDownBatch(resultBatches[0], visualMapModel));
this._dispatchHighDown('highlight', helper.makeHighDownBatch(resultBatches[1], visualMapModel));
}
private _hoverLinkFromSeriesMouseOver(e: ElementEvent) {
const el = e.target;
const visualMapModel = this.visualMapModel;
if (!el || getECData(el).dataIndex == null) {
return;
}
const ecData = getECData(el);
const dataModel = this.ecModel.getSeriesByIndex(ecData.seriesIndex);
if (!visualMapModel.isTargetSeries(dataModel)) {
return;
}
const data = dataModel.getData(ecData.dataType);
const value = data.getStore().get(visualMapModel.getDataDimensionIndex(data), ecData.dataIndex) as number;
if (!isNaN(value)) {
this._showIndicator(value, value);
}
}
private _hideIndicator() {
const shapes = this._shapes;
shapes.indicator && shapes.indicator.attr('invisible', true);
shapes.indicatorLabel && shapes.indicatorLabel.attr('invisible', true);
const handleLabels = this._shapes.handleLabels;
if (handleLabels) {
for (let i = 0; i < handleLabels.length; i++) {
// Fade out handle labels.
// NOTE: Must use api enter/leave on emphasis/blur/select state. Or the global states manager will change it.
this._api.leaveBlur(handleLabels[i]);
}
}
}
private _clearHoverLinkToSeries() {
this._hideIndicator();
const indices = this._hoverLinkDataIndices;
this._dispatchHighDown('downplay', helper.makeHighDownBatch(indices, this.visualMapModel));
indices.length = 0;
}
private _clearHoverLinkFromSeries() {
this._hideIndicator();
const zr = this.api.getZr();
zr.off('mouseover', this._hoverLinkFromSeriesMouseOver);
zr.off('mouseout', this._hideIndicator);
}
private _applyTransform(vertex: number[], element: Element, inverse?: boolean, global?: boolean): number[]
private _applyTransform(vertex: Direction, element: Element, inverse?: boolean, global?: boolean): Direction
private _applyTransform(
vertex: number[] | Direction,
element: Element,
inverse?: boolean,
global?: boolean
) {
const transform = graphic.getTransform(element, global ? null : this.group);
return zrUtil.isArray(vertex)
? graphic.applyTransform(vertex, transform, inverse)
: graphic.transformDirection(vertex, transform, inverse);
}
// TODO: TYPE more specified payload types.
private _dispatchHighDown(type: 'highlight' | 'downplay', batch: Payload['batch']) {
batch && batch.length && this.api.dispatchAction({
type: type,
batch: batch
});
}
/**
* @override
*/
dispose() {
this._clearHoverLinkFromSeries();
this._clearHoverLinkToSeries();
}
/**
* @override
*/
remove() {
this._clearHoverLinkFromSeries();
this._clearHoverLinkToSeries();
}
}
function createPolygon(
points?: number[][],
cursor?: string,
onDrift?: (x: number, y: number) => void,
onDragEnd?: () => void
) {
return new graphic.Polygon({
shape: {points: points},
draggable: !!onDrift,
cursor: cursor,
drift: onDrift,
onmousemove(e) {
// Fot mobile devicem, prevent screen slider on the button.
eventTool.stop(e.event);
},
ondragend: onDragEnd
});
}
function getHalfHoverLinkSize(visualMapModel: ContinuousModel, dataExtent: number[], sizeExtent: number[]) {
let halfHoverLinkSize = HOVER_LINK_SIZE / 2;
const hoverLinkDataSize = visualMapModel.get('hoverLinkDataSize');
if (hoverLinkDataSize) {
halfHoverLinkSize = linearMap(hoverLinkDataSize, dataExtent, sizeExtent, true) / 2;
}
return halfHoverLinkSize;
}
function useHoverLinkOnHandle(visualMapModel: ContinuousModel) {
const hoverLinkOnHandle = visualMapModel.get('hoverLinkOnHandle');
return !!(hoverLinkOnHandle == null ? visualMapModel.get('realtime') : hoverLinkOnHandle);
}
function getCursor(orient: Orient) {
return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
}
export default ContinuousView; | the_stack |
import { lazy } from 'react'
import Plugin from '@jbrowse/core/Plugin'
import DisplayType from '@jbrowse/core/pluggableElementTypes/DisplayType'
import AdapterType from '@jbrowse/core/pluggableElementTypes/AdapterType'
import ViewType from '@jbrowse/core/pluggableElementTypes/ViewType'
import AddIcon from '@material-ui/icons/Add'
import PluginManager from '@jbrowse/core/PluginManager'
import {
AbstractSessionModel,
isAbstractMenuManager,
getSession,
} from '@jbrowse/core/util'
import { getConf } from '@jbrowse/core/configuration'
import { Feature } from '@jbrowse/core/util/simpleFeature'
import TimelineIcon from '@material-ui/icons/Timeline'
import { MismatchParser } from '@jbrowse/plugin-alignments'
import { FileLocation } from '@jbrowse/core/util/types'
import {
configSchemaFactory as dotplotDisplayConfigSchemaFactory,
stateModelFactory as dotplotDisplayStateModelFactory,
ReactComponent as DotplotDisplayReactComponent,
} from './DotplotDisplay'
import DotplotRenderer, {
configSchema as dotplotRendererConfigSchema,
ReactComponent as DotplotRendererReactComponent,
} from './DotplotRenderer'
import stateModelFactory from './DotplotView/model'
import {
configSchema as PAFAdapterConfigSchema,
AdapterClass as PAFAdapter,
} from './PAFAdapter'
import ComparativeRender from './DotplotRenderer/ComparativeRenderRpc'
import { PluggableElementType } from '@jbrowse/core/pluggableElementTypes'
import { LinearPileupDisplayModel } from '@jbrowse/plugin-alignments'
import {
AdapterGuesser,
getFileName,
TrackTypeGuesser,
} from '@jbrowse/core/util/tracks'
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
}
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
}
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 { [key: string]: BasicFeature[] })
return Object.values(groups)
.map(group => mergeIntervals(group.sort((a, b) => a.start - b.start)))
.flat()
}
interface ReducedFeature {
refName: string
start: number
clipPos: number
end: number
seqLength: number
}
function onClick(feature: Feature, self: LinearPileupDisplayModel) {
const session = getSession(self)
try {
const cigar = feature.get('CIGAR')
const clipPos = getClip(cigar, 1)
const flags = feature.get('flags')
const origStrand = feature.get('strand')
const readName = feature.get('name')
const readAssembly = `${readName}_assembly_${Date.now()}`
const { parentTrack } = self
const [trackAssembly] = getConf(parentTrack, 'assemblyNames')
const assemblyNames = [trackAssembly, readAssembly]
const trackId = `track-${Date.now()}`
const trackName = `${readName}_vs_${trackAssembly}`
const SA: string = getTag(feature, 'SA') || ''
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.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 = getLength(
flags & 2048 ? supplementaryAlignments[0].CIGAR : cigar,
)
const features = [feat, ...supplementaryAlignments] as ReducedFeature[]
features.sort((a, b) => a.clipPos - b.clipPos)
const refLength = features.reduce((a, f) => a + f.end - f.start, 0)
session.addView('DotplotView', {
type: 'DotplotView',
hview: {
offsetPx: 0,
bpPerPx: refLength / 800,
displayedRegions: gatherOverlaps(
features.map((f, index) => {
const { start, end, refName } = f
return {
start,
end,
refName,
index,
assemblyName: trackAssembly,
}
}),
),
},
vview: {
offsetPx: 0,
bpPerPx: totalLength / 400,
minimumBlockWidth: 0,
interRegionPaddingWidth: 0,
displayedRegions: [
{
assemblyName: readAssembly,
start: 0,
end: totalLength,
refName: readName,
},
],
},
viewTrackConfigs: [
{
type: 'SyntenyTrack',
assemblyNames,
adapter: {
type: 'FromConfigAdapter',
features,
},
trackId,
name: trackName,
},
],
viewAssemblyConfigs: [
{
name: readAssembly,
sequence: {
type: 'ReferenceSequenceTrack',
trackId: `${readName}_${Date.now()}`,
adapter: {
type: 'FromConfigSequenceAdapter',
features: [feature.toJSON()],
},
},
},
],
assemblyNames,
tracks: [
{
configuration: trackId,
type: 'SyntenyTrack',
displays: [
{
type: 'DotplotDisplay',
configuration: `${trackId}-DotplotDisplay`,
},
],
},
],
displayName: `${readName} vs ${trackAssembly}`,
})
} catch (e) {
console.error(e)
session.notify(`${e}`, 'error')
}
}
export default class DotplotPlugin extends Plugin {
name = 'DotplotPlugin'
install(pluginManager: PluginManager) {
pluginManager.addViewType(() => {
return new ViewType({
name: 'DotplotView',
stateModel: stateModelFactory(pluginManager),
ReactComponent: lazy(
() => import('./DotplotView/components/DotplotView'),
),
})
})
pluginManager.addDisplayType(() => {
const configSchema = dotplotDisplayConfigSchemaFactory(pluginManager)
return new DisplayType({
name: 'DotplotDisplay',
configSchema,
stateModel: dotplotDisplayStateModelFactory(configSchema),
trackType: 'SyntenyTrack',
viewType: 'DotplotView',
ReactComponent: DotplotDisplayReactComponent,
})
})
pluginManager.addRendererType(
() =>
new DotplotRenderer({
name: 'DotplotRenderer',
configSchema: dotplotRendererConfigSchema,
ReactComponent: DotplotRendererReactComponent,
pluginManager,
}),
)
pluginManager.addAdapterType(
() =>
new AdapterType({
name: 'PAFAdapter',
configSchema: PAFAdapterConfigSchema,
adapterMetadata: {
category: null,
hiddenFromGUI: true,
displayName: null,
description: null,
},
AdapterClass: PAFAdapter,
}),
)
pluginManager.addToExtensionPoint(
'Core-guessAdapterForLocation',
(adapterGuesser: AdapterGuesser) => {
return (
file: FileLocation,
index?: FileLocation,
adapterHint?: string,
) => {
const regexGuess = /\.paf/i
const adapterName = 'PAFAdapter'
const fileName = getFileName(file)
if (regexGuess.test(fileName) || adapterHint === adapterName) {
return {
type: adapterName,
pafLocation: file,
}
}
return adapterGuesser(file, index, adapterHint)
}
},
)
pluginManager.addToExtensionPoint(
'Core-guessTrackTypeForLocation',
(trackTypeGuesser: TrackTypeGuesser) => {
return (adapterName: string) => {
if (adapterName === 'PAFAdapter') {
return 'SyntenyTrack'
}
return trackTypeGuesser(adapterName)
}
},
)
// install our comparative rendering rpc callback
pluginManager.addRpcMethod(() => new ComparativeRender(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: 'Dotplot of read vs ref',
icon: AddIcon,
onClick: () => onClick(feature, self),
},
]
return newMenuItems
},
},
}
},
)
;(pluggableElement as DisplayType).stateModel = newStateModel
}
return pluggableElement
},
)
}
configure(pluginManager: PluginManager) {
if (isAbstractMenuManager(pluginManager.rootModel)) {
pluginManager.rootModel.appendToSubMenu(['Add'], {
label: 'Dotplot view',
icon: TimelineIcon,
onClick: (session: AbstractSessionModel) => {
session.addView('DotplotView', {})
},
})
}
}
} | the_stack |
namespace corgio {
export enum CorgiFlags {
None = 0,
HorizontalMovement = 1 << 0,
VerticalMovement = 1 << 1,
UpdateSprite = 1 << 2,
CameraFollow = 1 << 3,
All = ~(~0 << 4)
}
export let _corgi_still: Image[] = [
img`
. . 4 . . . 4 . .
. 4 f 4 d 4 f 4 .
. 4 f 4 4 4 f 4 .
. e 4 d 4 d 4 4 .
. 4 4 f 4 f 4 f .
d e 4 4 4 4 4 e d
d d 4 e d e 4 d d
`,
img`
. . 4 . . . 4 . .
. 4 f 4 d 4 f 4 .
. 4 f 4 4 4 f 4 .
. e 4 d 4 d 4 4 .
. 4 4 f e f 4 f .
. e 4 4 4 4 4 e .
d e d 4 e 4 d e d
d d d e d e d d d
`,
img`
. . 4 . . . 4 . .
. 4 f 4 d 4 f 4 .
. 4 f 4 4 4 f 4 .
. e 4 d 4 d 4 4 .
. 4 4 f 4 f 4 f .
. e 4 4 4 4 4 e .
d e d 4 a 4 d e d
d d d e d e d d d
`,
img`
. . 4 . . . 4 . .
. 4 f 4 d 4 f 4 .
. 4 f 4 4 4 f 4 .
. e 4 d 4 d 4 4 .
. 4 4 f 4 f 4 f .
. e 4 4 4 4 4 e .
d e d 4 a 4 d e d
d d d e a e d d d
`,
img`
. . 4 . . . 4 . .
. 4 f 4 d 4 f 4 .
. 4 f 4 4 4 f 4 .
. e 4 d 4 d 4 4 .
. 4 4 f 4 f 4 f .
. e 4 4 4 4 4 e .
d e d 4 a 4 d e d
d d d e d e d d d
`,
img`
. . 4 . . . 4 . .
. 4 f 4 d 4 f 4 .
. 4 f 4 4 4 f 4 .
. e 4 d 4 d 4 4 .
. 4 4 f 4 f 4 f .
. e 4 4 4 4 4 e .
d e d 4 4 4 d e d
d d d e d e d d d
`,
];
export let _corgi_left: Image[] = [
img`
. . . . . . . . . . . . . . . .
. . 4 . . . 4 . . . . . . . . .
. 4 f 4 d 4 f 4 . . . . . . . .
. 4 f 4 4 4 f 4 . . . . . . . .
. 4 4 d 4 d 4 4 . . . . . . . .
. e 4 f 4 f 4 e . . . . e 4 f .
. e 4 4 4 4 4 4 d . . . e 4 f .
f d 4 4 4 4 4 d d e e e 4 4 4 .
. 4 d d d 4 f d 4 4 4 4 4 4 . .
. . 4 d d f f d d 4 4 4 4 4 4 .
. . . . . d d d 4 4 f 4 f 4 4 .
. . . . . . d 4 d 4 f f f 4 d d
. . . . . . f . . . . . . . d f
`,
img`
. . . . . . . . . . . . . . . .
. . 4 . . . 4 . . . . . . . . .
. 4 f 4 d 4 f 4 . . . . . . . .
. 4 f 4 4 4 f 4 . . . . . . . .
. 4 4 d 4 d 4 4 . . . . e 4 f .
. e 4 f 4 f 4 e . . . . e 4 f .
. e 4 4 4 4 4 4 d e e e 4 4 4 .
f d 4 4 4 4 4 d d 4 4 4 4 4 . .
. 4 d d d 4 f d 4 4 4 4 4 4 4 .
. . 4 d d f f d d 4 f 4 f 4 4 .
. . . . . d d d 4 d f f f 4 d d
. . . . . . d 4 d . . . . . d f
. . . . . . f . . . . . . . . .
`,
img`
. . 4 . . . 4 . . . . . . . . .
. 4 f 4 d 4 f 4 . . . . . . . .
. 4 f 4 4 4 f 4 . . . . . . . .
. 4 4 d 4 d 4 4 . . . . e 4 f .
. e 4 f 4 f 4 e . . . . e 4 f .
. e 4 4 4 4 4 4 d e e e 4 4 4 .
f d 4 4 4 4 4 d d 4 4 4 4 4 . .
. 4 d d d 4 f d 4 4 4 4 4 4 4 .
. . 4 d d f f d d 4 f 4 f 4 4 .
. . . . d d d 4 4 d f f f 4 d d
. . . f d 4 . . . . . . . . d f
. . . . f . . . . . . . . . . .
`,
img`
. . 4 . . . 4 . . . . . . . . .
. 4 f 4 d 4 f 4 . . . . . . . .
. 4 f 4 4 4 f 4 . . . . . . . .
. 4 4 d 4 d 4 4 . . . . e 4 f .
. e 4 f 4 f 4 e . . . . e 4 f .
. e 4 4 4 4 4 4 d e e e 4 4 4 .
f d 4 4 4 4 4 d d 4 4 4 4 4 . .
. 4 d d d 4 f d 4 4 4 4 4 4 . .
. . 4 d d f f d d 4 f 4 f 4 . .
. . . . d d d 4 4 d f f f 4 d .
. . . f d 4 . . . . . . 4 d d .
. . . . . . . . . . . . . f . .
`,
img`
. . 4 . . . 4 . . . . . . . . .
. 4 f 4 d 4 f 4 . . . . . . . .
. 4 f 4 4 4 f 4 . . . . . . . .
. 4 4 d 4 d 4 4 . . . . e 4 f .
. e 4 f 4 f 4 e . . . . e 4 f .
. e 4 4 4 4 4 4 d e e e 4 4 4 .
f d 4 4 4 4 4 d d 4 4 4 4 4 . .
. 4 d d d 4 f d 4 4 4 4 4 4 . .
. . 4 d d f f d d 4 f 4 f 4 . .
. . . . d 4 d 4 4 d f f f 4 d .
. . . . d 4 . . . . . . 4 d d .
. . . . . f . . . . . . . f . .
`
];
export let _corgi_right: Image[] = reflect(_corgi_left);
/**
* Creates a new dart from an image and kind
* @param kind the kind to make the corgi
* @param x optional initial x position, eg: 10
* @param y optional initial y position, eg: 70
*/
//% blockId=corgiCreate block="corgi of kind %kind=spritekind || at x %x y %y"
//% expandableArgumentMode=toggle
//% inlineInputMode=inline
//% blockSetVariable=myCorg
//% weight=100
//% group="Create"
export function create(kind: number,
x: number = 10,
y: number = 70): Corgio {
return new Corgio(kind, x, y);
}
// Round input towards 0; 1.4 becomes 1.0, -0.4 becomes 0.0
export function roundTowardsZero(input: number): number {
return Math.floor(input) + input < 0 ? 1 : 0;
}
// Normalize input number to 0, 1, or -1
export function normalize(input: number): number {
return input ? input / Math.abs(input) : 0;
}
// Set the animation for looking right to be the opposite of looking left
export function reflect(input: Image[]): Image[] {
let output: Image[] = [];
for (let i: number = 0; i < input.length; i++) {
let nextImage = input[i].clone();
nextImage.flipX();
output.push(nextImage);
}
return output;
}
}
/**
* A Corgi Platformer
**/
//% blockNamespace=corgio color="#d2b48c" blockGap=8
class Corgio {
private player: Sprite;
private stillAnimation: Image[];
private _leftAnimation: Image[];
private _rightAnimation: Image[];
//% group="Properties" blockSetVariable="myCorg"
//% blockCombine block="horizontal speed"
maxMoveVelocity: number;
//% group="Properties" blockSetVariable="myCorg"
//% blockCombine block="gravity"
gravity: number;
//% group="Properties" blockSetVariable="myCorg"
//% blockCombine block="jump speed"
jumpVelocity: number;
//% group="Properties" blockSetVariable="myCorg"
//% blockCombine block="max jumps in a row"
maxJump: number;
//% group="Properties" blockSetVariable="myCorg"
//% blockCombine block="rate horizontal movement is slowed"
decelerationRate: number;
private controlFlags: number;
private initJump: boolean;
private releasedJump: boolean;
private count: number;
private touching: number;
private remainingJump: number;
private script: string[];
public constructor(kind: number, x: number, y: number) {
this.maxMoveVelocity = 70;
this.gravity = 300;
this.jumpVelocity = 125;
this.initJump = true;
this.releasedJump = true;
this.maxJump = 2;
this.count = 0;
this.touching = 2;
this.remainingJump = this.maxJump;
this.script = [
"bark"
];
this.controlFlags = corgio.CorgiFlags.None;
this.stillAnimation = corgio._corgi_still;
this._leftAnimation = corgio._corgi_left;
this._rightAnimation = corgio._corgi_right;
this.player = sprites.create(this.stillAnimation[0], kind);
this.player.setFlag(SpriteFlag.StayInScreen, true);
this.player.ay = this.gravity;
this.player.x = x;
this.player.y = y;
}
/**
* Get the Corgio's sprite
*/
//% group="Properties"
//% blockId=corgSprite block="%corgio(myCorg) sprite"
//% weight=8
get sprite(): Sprite {
return this.player;
}
/**
* Make the character move in the direction indicated by the left and right arrow keys.
*/
//% group="Movement"
//% blockId=horizontalMovement block="make %corgio(myCorg) move left and right with arrow keys || %on=toggleOnOff"
//% weight=100 blockGap=5
horizontalMovement(on: boolean = true): void {
let _this = this;
this.updateFlags(on, corgio.CorgiFlags.HorizontalMovement);
game.onUpdate(function () {
if (!(_this.controlFlags & corgio.CorgiFlags.HorizontalMovement)) return;
let dir: number = controller.dx();
_this.player.vx = dir ? corgio.normalize(dir) * _this.maxMoveVelocity :
corgio.roundTowardsZero(_this.player.vx * _this.decelerationRate);
})
}
/**
* Make the character jump when the up arrow key is pressed, and grab onto the wall when falling.
*/
//% group="Movement"
//% blockId=verticalMovement block="make %corgio(myCorg) jump if up arrow key is pressed || %on=toggleOnOff"
//% weight=100 blockGap=5
verticalMovement(on: boolean = true): void {
let _this = this;
this.updateFlags(on, corgio.CorgiFlags.VerticalMovement);
controller.up.onEvent(ControllerButtonEvent.Released, function () {
_this.releasedJump = true;
})
game.onUpdate(function () {
if (!(_this.controlFlags & corgio.CorgiFlags.VerticalMovement)) return;
if (controller.up.isPressed()) {
if (_this.contactLeft() && controller.right.isPressed()
|| _this.contactRight() && controller.left.isPressed()) {
_this.remainingJump = Math.max(_this.remainingJump + 1, _this.maxJump);
}
_this.jumpImpulse();
}
if ((_this.contactLeft() && controller.left.isPressed()
|| _this.contactRight() && controller.right.isPressed())
&& _this.player.vy > - 10) {
_this.player.ay = _this.gravity >> 2;
} else {
_this.player.ay = _this.gravity;
}
if (_this.contactBelow()) {
if (_this.initJump) {
_this.remainingJump = _this.maxJump;
}
_this.initJump = true;
}
})
}
/**
* Set camera to follow corgio horizontally, while keeping the screen centered vertically.
*/
//% group="Movement"
//% blockId=followCorgi block="make camera follow %corgio(myCorg) left and right || %on=toggleOnOff"
//% weight=90 blockGap=5
follow(on: boolean = true): void {
let _this = this;
this.updateFlags(on, corgio.CorgiFlags.CameraFollow);
game.onUpdate(function () {
if (_this.controlFlags & corgio.CorgiFlags.CameraFollow) {
scene.centerCameraAt(_this.player.x, screen.height >> 1);
}
})
}
/**
* Make the character change sprites when moving.
*/
//% group="Movement"
//% blockId=updateSprite block="change image when %corgio(myCorg) is moving || %on=toggleOnOff"
//% weight=100 blockGap=5
updateSprite(on: boolean = true): void {
let _this = this;
this.updateFlags(on, corgio.CorgiFlags.UpdateSprite);
game.onUpdate(function () {
if (!(_this.controlFlags & corgio.CorgiFlags.UpdateSprite)) return;
_this.count++;
if (_this.player.vx == 0) {
_this.player.setImage(_this.pickNext(_this.stillAnimation, 6));
} else if (_this.player.vx < 0) {
_this.player.setImage(_this.pickNext(_this._leftAnimation));
} else {
_this.player.setImage(_this.pickNext(_this._rightAnimation));
}
})
}
/**
* Add new phrase for the character to bark
* @param input phrase to add to script, eg: "bark"
*/
//% group="Speak"
//% blockId=addScript block="teach %corgio(myCorg) the word %input"
//% weight=95 blockGap=5
addToScript(input: string): void {
this.script.push(input);
}
/**
* Have the character say one of the phrases in the script at random
*/
//% group="Speak"
//% blockId=bark block="make %corgio(myCorg) bark!"
//% weight=95 blockGap=5
bark(): void {
this.player.say(Math.pickRandom(this.script), 250);
}
private jumpImpulse() {
if (this.remainingJump > 0 && this.releasedJump) {
this.releasedJump = false;
if (this.initJump) {
this.player.vy = -1 * this.jumpVelocity;
this.initJump = false;
} else {
this.player.vy = Math.clamp((-4 * this.jumpVelocity) / 3, -30,
this.player.vy - this.jumpVelocity);
}
this.remainingJump--;
}
}
private updateFlags(on: boolean, flag: corgio.CorgiFlags): void {
if (on) this.controlFlags |= flag;
else this.controlFlags &= corgio.CorgiFlags.All ^ flag;
}
private pickNext(input: Image[], state: number = 3): Image {
return input[(this.count / state) % input.length];
}
private contactLeft(): boolean {
let screenEdge = game.currentScene().camera.offsetX;
return this.player.left - screenEdge <= this.touching
|| this.player.isHittingTile(CollisionDirection.Left);
}
private contactRight(): boolean {
let screenEdge = screen.width + game.currentScene().camera.offsetX;
return screenEdge - this.player.right <= this.touching
|| this.player.isHittingTile(CollisionDirection.Right);
}
private contactBelow(): boolean {
let screenEdge = screen.height + game.currentScene().camera.offsetY;
return screenEdge - this.player.bottom <= this.touching
|| this.player.isHittingTile(CollisionDirection.Bottom);
}
} | the_stack |
import { MASK_TYPES, MSAA_QUALITY } from '@pixi/constants';
import { Rectangle, Matrix } from '@pixi/math';
import { Renderer, MaskData, RenderTexture, Filter, Texture, BaseTexture, CanvasResource,
SpriteMaskFilter } from '@pixi/core';
import { Graphics } from '@pixi/graphics';
import { Sprite } from '@pixi/sprite';
import sinon from 'sinon';
import { expect } from 'chai';
describe('MaskSystem', function ()
{
function onePixelMask(worldTransform)
{
return {
isFastRect() { return true; },
worldTransform: worldTransform || Matrix.IDENTITY,
getBounds() { return new Rectangle(0, 0, 1, 1); },
render() { /* nothing*/ },
};
}
function createColorTexture(color)
{
const canvas = document.createElement('canvas');
canvas.width = 16;
canvas.height = 16;
const context = canvas.getContext('2d');
context.fillStyle = color;
context.fillRect(0, 0, 16, 16);
return new Texture(new BaseTexture(new CanvasResource(canvas)));
}
before(function ()
{
this.renderer = new Renderer();
this.renderer.mask.enableScissor = true;
this.textureRed = createColorTexture('#ff0000');
this.textureGreen = createColorTexture('#00ff00');
// Like SpriteMaskFilter, but with green instead of red channel
this.spriteMaskFilterGreen = new SpriteMaskFilter(undefined, `\
varying vec2 vMaskCoord;
varying vec2 vTextureCoord;
uniform sampler2D uSampler;
uniform sampler2D mask;
uniform float alpha;
uniform float npmAlpha;
uniform vec4 maskClamp;
void main(void)
{
float clip = step(3.5,
step(maskClamp.x, vMaskCoord.x) +
step(maskClamp.y, vMaskCoord.y) +
step(vMaskCoord.x, maskClamp.z) +
step(vMaskCoord.y, maskClamp.w));
vec4 original = texture2D(uSampler, vTextureCoord);
vec4 masky = texture2D(mask, vMaskCoord);
float alphaMul = 1.0 - npmAlpha * (1.0 - masky.a);
original *= (alphaMul * masky.g * alpha * clip);
gl_FragColor = original;
}`);
});
after(function ()
{
this.renderer.destroy();
this.renderer = null;
this.textureRed.destroy(true);
this.textureRed = null;
this.textureGreen.destroy(true);
this.textureGreen = null;
this.spriteMaskFilterGreen.destroy();
this.spriteMaskFilterGreen = null;
});
it('should have scissor-masks enabled', function ()
{
expect(this.renderer.mask.enableScissor).to.equal(true);
});
it('should use scissor masks with axis aligned squares', function ()
{
const context = {};
const maskObject = onePixelMask({ a: 1, b: 0, c: 0, d: 1 });
const maskObject2 = onePixelMask({ a: 0, b: 1, c: 1, d: 0 });
this.renderer.mask.push(context, maskObject);
expect(this.renderer.scissor.getStackLength()).to.equal(1);
this.renderer.mask.push(context, maskObject2);
expect(this.renderer.scissor.getStackLength()).to.equal(2);
this.renderer.mask.pop(context, maskObject2);
expect(this.renderer.scissor.getStackLength()).to.equal(1);
this.renderer.mask.pop(context, maskObject);
expect(this.renderer.scissor.getStackLength()).to.equal(0);
});
it('should return maskData to pool if it does not belong in the object', function ()
{
const context = {};
const maskObject = onePixelMask({ a: 1, b: 0, c: 0, d: 1 });
this.renderer.mask.maskDataPool.length = 0;
this.renderer.mask.push(context, maskObject);
this.renderer.mask.pop(context, maskObject);
const maskData = this.renderer.mask.maskDataPool[0];
expect(maskData).to.exist;
expect(maskData._scissorCounter).to.equal(1);
});
it('should not put maskData to pool if it belongs to object', function ()
{
const context = {};
const maskData = new MaskData(onePixelMask({ a: 1, b: 0, c: 0, d: 1 }));
this.renderer.mask.maskDataPool.length = 0;
for (let i = 0; i < 2; i++)
{
// repeat two times just to be sure
this.renderer.mask.push(context, maskData);
this.renderer.mask.pop(context, maskData);
expect(maskData._scissorCounter).to.equal(1);
expect(this.renderer.mask.maskDataPool.length).to.equal(0);
}
});
it('should not use scissor masks with non axis aligned squares', function ()
{
const context = {};
const maskObject = onePixelMask({ a: 0.1, b: 2, c: 2, d: -0.1 });
this.renderer.mask.push(context, maskObject);
expect(this.renderer.scissor.getStackLength()).to.equal(0);
this.renderer.mask.pop(context, maskObject);
});
it('should apply scissor with transform on canvas or renderTexture', function ()
{
const context = {};
const maskObject = {
isFastRect() { return true; },
worldTransform: Matrix.IDENTITY,
getBounds() { return new Rectangle(2, 3, 6, 5); },
render() { /* nothing*/ },
};
this.renderer.resolution = 2;
this.renderer.resize(30, 30);
const rt = RenderTexture.create({ width: 20, height: 20, resolution: 3 });
const scissor = sinon.spy(this.renderer.gl, 'scissor');
this.renderer.projection.transform = new Matrix(1, 0, 0, 1, 0.5, 1);
this.renderer.mask.push(context, maskObject);
this.renderer.mask.pop(context, maskObject);
// now , lets try it for renderTexture
this.renderer.renderTexture.bind(rt);
this.renderer.mask.push(context, maskObject);
this.renderer.mask.pop(context, maskObject);
expect(scissor.calledTwice).to.be.true;
// result Y is 2 because after transform y=8 h=10 and renderer H=60 is inverted , 8-18 becomes 52-42, e.g. Y=2
expect(scissor.args[0]).to.eql([Math.round(5), Math.round(42), Math.round(12), Math.round(10)]);
// resolution is 3 , and Y is not reversed
expect(scissor.args[1]).to.eql([Math.round(7.5), Math.round(12), Math.round(18), Math.round(15)]);
rt.destroy(true);
this.renderer.projection.transform = null;
this.renderer.resolution = 1;
});
it('should correctly calculate alpha mask area if filter is present', function ()
{
// fixes slow runs on CI #6604
this.timeout(5000);
// the bug was fixed in #5444
this.renderer.resize(10, 10);
const filteredObject = {
getBounds() { return new Rectangle(0, 0, 10, 10); },
render() { /* nothing*/ },
};
const maskBounds = new Rectangle(2, 3, 6, 5);
const maskObject = {
isSprite: true,
_texture: Texture.WHITE,
get texture() { return this._texture; },
anchor: { x: 0, y: 0 },
isFastRect() { return true; },
worldTransform: Matrix.IDENTITY,
getBounds() { return maskBounds.clone(); },
};
const filters = [new Filter()];
const maskSystem = this.renderer.mask;
for (let i = 0; i < 6; i++)
{
this.renderer.filter.push(filteredObject, filters);
maskSystem.push(filteredObject, maskObject);
expect(maskSystem.maskStack.length).to.equal(1);
expect(maskSystem.maskStack[0].type).to.equal(MASK_TYPES.SPRITE);
expect(this.renderer.renderTexture.current).to.exist;
const filterArea = this.renderer.renderTexture.current.filterFrame;
const expected = maskBounds.clone().ceil();
expected.fit(filteredObject.getBounds());
expect(filterArea).to.exist;
expect(filterArea.x).to.equal(expected.x);
expect(filterArea.y).to.equal(expected.y);
expect(filterArea.width).to.equal(expected.width);
expect(filterArea.height).to.equal(expected.height);
maskSystem.pop(filteredObject);
this.renderer.filter.pop();
expect(maskSystem.maskStack.length).to.equal(0);
expect(this.renderer.renderTexture.current).to.be.null;
maskBounds.x += 1.0;
maskBounds.y += 0.5;
}
});
it('should render correctly without a custom sprite mask filter and a red texture sprite mask', function ()
{
const graphics = new Graphics().beginFill(0xffffff, 1.0).drawRect(0, 0, 1, 1).endFill();
graphics.mask = new MaskData(new Sprite(this.textureRed));
const renderTexture = this.renderer.generateTexture(graphics);
graphics.destroy(true);
this.renderer.renderTexture.bind(renderTexture);
const pixel = new Uint8Array(4);
const gl = this.renderer.gl;
gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
renderTexture.destroy(true);
const [r, g, b, a] = pixel;
expect(r).to.equal(0xff);
expect(g).to.equal(0xff);
expect(b).to.equal(0xff);
expect(a).to.equal(0xff);
});
it('should render correctly without a custom sprite mask filter and a green texture sprite mask', function ()
{
const graphics = new Graphics().beginFill(0xffffff, 1.0).drawRect(0, 0, 1, 1).endFill();
graphics.mask = new MaskData(new Sprite(this.textureGreen));
const renderTexture = this.renderer.generateTexture(graphics);
graphics.destroy(true);
this.renderer.renderTexture.bind(renderTexture);
const pixel = new Uint8Array(4);
const gl = this.renderer.gl;
gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
renderTexture.destroy(true);
const [r, g, b, a] = pixel;
expect(r).to.equal(0x00);
expect(g).to.equal(0x00);
expect(b).to.equal(0x00);
expect(a).to.equal(0x00);
});
it('should render correctly with acustom sprite mask filter and a red texture sprite mask', function ()
{
const graphics = new Graphics().beginFill(0xffffff, 1.0).drawRect(0, 0, 1, 1).endFill();
graphics.mask = new MaskData(new Sprite(this.textureRed));
graphics.mask.filter = this.spriteMaskFilterGreen;
const renderTexture = this.renderer.generateTexture(graphics);
graphics.destroy(true);
this.renderer.renderTexture.bind(renderTexture);
const pixel = new Uint8Array(4);
const gl = this.renderer.gl;
gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
renderTexture.destroy(true);
const [r, g, b, a] = pixel;
expect(r).to.equal(0x00);
expect(g).to.equal(0x00);
expect(b).to.equal(0x00);
expect(a).to.equal(0x00);
});
it('should render correctly with a custom sprite mask filter and a green texture sprite mask', function ()
{
const graphics = new Graphics().beginFill(0xffffff, 1.0).drawRect(0, 0, 1, 1).endFill();
graphics.mask = new MaskData(new Sprite(this.textureGreen));
graphics.mask.filter = this.spriteMaskFilterGreen;
const renderTexture = this.renderer.generateTexture(graphics);
graphics.destroy(true);
this.renderer.renderTexture.bind(renderTexture);
const pixel = new Uint8Array(4);
const gl = this.renderer.gl;
gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
renderTexture.destroy(true);
const [r, g, b, a] = pixel;
expect(r).to.equal(0xff);
expect(g).to.equal(0xff);
expect(b).to.equal(0xff);
expect(a).to.equal(0xff);
});
it('should restore sprite of current sprite mask filter after pop', function ()
{
const renderTexture = RenderTexture.create({ width: 1, height: 1 });
this.renderer.renderTexture.bind(renderTexture);
const graphics1 = new Graphics();
const graphics2 = new Graphics();
const sprite1 = new Sprite(this.textureRed);
const sprite2 = new Sprite(this.textureGreen);
const maskData1 = new MaskData(sprite1);
const maskData2 = new MaskData(sprite2);
maskData1.filter = this.spriteMaskFilterGreen;
maskData2.filter = this.spriteMaskFilterGreen;
expect(maskData1.filter.maskSprite).to.be.null;
expect(maskData2.filter.maskSprite).to.be.null;
graphics1.mask = maskData1;
graphics2.mask = maskData2;
this.renderer.mask.push(graphics1, maskData1);
expect(maskData1.filter.maskSprite).to.equal(sprite1);
this.renderer.mask.push(graphics2, maskData2);
expect(maskData2.filter.maskSprite).to.equal(sprite2);
this.renderer.mask.pop(graphics2);
expect(maskData1.filter.maskSprite).to.equal(sprite1);
this.renderer.mask.pop(graphics1);
expect(maskData1.filter.maskSprite).to.be.null;
expect(maskData2.filter.maskSprite).to.be.null;
renderTexture.destroy(true);
});
}); | the_stack |
import { Resolvers } from '@apollo/client';
import { AddressZero, HashZero } from 'ethers/constants';
import { bigNumberify, LogDescription } from 'ethers/utils';
import {
ClientType,
ColonyVersion,
Extension,
TokenClientType,
extensions,
getExtensionHash,
ColonyClientV5,
ROOT_DOMAIN_ID,
getHistoricColonyRoles,
formatColonyRoles,
} from '@colony/colony-js';
import { Color } from '~core/ColorTag';
import ENS from '~lib/ENS';
import { Context, IpfsWithFallbackSkeleton } from '~context/index';
import {
Transfer,
SubgraphDomainsQuery,
SubgraphDomainsQueryVariables,
SubgraphDomainsDocument,
SubgraphSingleDomainQuery,
SubgraphSingleDomainQueryVariables,
SubgraphSingleDomainDocument,
SubgraphColonyQuery,
SubgraphColonyQueryVariables,
SubgraphColonyDocument,
SubgraphRoleEventsQuery,
SubgraphRoleEventsQueryVariables,
SubgraphRoleEventsDocument,
} from '~data/index';
import { createAddress } from '~utils/web3';
import { log } from '~utils/debug';
import { parseSubgraphEvent, sortSubgraphEventByIndex } from '~utils/events';
import { Address } from '~types/index';
import { COLONY_TOTAL_BALANCE_DOMAIN_ID } from '~constants';
import { getToken } from './token';
import {
getColonyFundsClaimedTransfers,
getPayoutClaimedTransfers,
getColonyUnclaimedTransfers,
} from './transactions';
export const getProcessedColony = async (
subgraphColony,
colonyAddress: Address,
ipfs: IpfsWithFallbackSkeleton,
) => {
const {
colonyChainId,
ensName,
metadata,
token,
metadataHistory = [],
extensions: colonyExtensions = [],
} = subgraphColony;
let displayName: string | null = null;
let avatar: string | null = null;
let avatarHash: string | null = null;
let avatarObject: { image: string | null } | null = { image: null };
let tokenAddresses: Array<Address> = [];
const prevIpfsHash = metadataHistory.slice(-1).pop();
const ipfsHash = metadata || prevIpfsHash?.metadata || null;
/*
* Fetch the colony's metadata
*/
let ipfsMetadata: string | null = null;
try {
ipfsMetadata = await ipfs.getString(ipfsHash);
} catch (error) {
log.verbose(
`Could not fetch IPFS metadata for colony:`,
ensName,
'with hash:',
metadata,
);
}
try {
if (ipfsMetadata) {
const {
colonyDisplayName = null,
colonyAvatarHash = null,
colonyTokens = [],
} = JSON.parse(ipfsMetadata);
displayName = colonyDisplayName;
avatarHash = colonyAvatarHash;
tokenAddresses = colonyTokens;
/*
* Fetch the colony's avatar
*/
try {
avatar = await ipfs.getString(colonyAvatarHash);
avatarObject = JSON.parse(avatar as string);
} catch (error) {
log.verbose('Could not fetch colony avatar', avatar);
log.verbose(
`Could not parse IPFS avatar for colony:`,
ensName,
'with hash:',
colonyAvatarHash,
);
}
}
} catch (error) {
log.verbose(
`Could not parse IPFS metadata for colony:`,
ensName,
'with object:',
ipfsMetadata,
);
}
return {
__typename: 'ProcessedColony',
id: parseInt(colonyChainId, 10),
colonyName: ENS.stripDomainParts('colony', ensName),
colonyAddress,
displayName,
avatarHash,
avatarURL: avatarObject?.image || null,
nativeTokenAddress: token?.tokenAddress
? createAddress(token.tokenAddress)
: null,
tokenAddresses: token?.tokenAddress
? [...tokenAddresses, token.tokenAddress].map(createAddress)
: [],
extensionAddresses: colonyExtensions.map(({ address }) => address),
};
};
export const getProcessedDomain = async (
subgraphDomain,
ipfs: IpfsWithFallbackSkeleton,
) => {
const {
metadata,
metadataHistory = [],
id,
domainChainId,
parent,
name: domainName,
} = subgraphDomain;
let name: string | null = null;
let color: string | null = null;
let description: string | null = null;
const prevIpfsHash = metadataHistory.slice(-1).pop();
const ipfsHash = metadata || prevIpfsHash?.metadata || null;
/*
* Fetch the domains's metadata
*/
let ipfsMetadata: string | null = null;
try {
ipfsMetadata = await ipfs.getString(ipfsHash);
} catch (error) {
log.verbose(
`Could not fetch IPFS metadata for domain:`,
domainName,
'with hash:',
metadata,
);
}
try {
if (ipfsMetadata) {
const {
domainName: metadataDomainName = null,
domainColor = null,
domainPurpose = null,
} = JSON.parse(ipfsMetadata);
name = metadataDomainName;
color = domainColor;
description = domainPurpose;
}
} catch (error) {
log.verbose(
`Could not parse IPFS metadata for domain:`,
domainChainId,
'with object:',
ipfsMetadata,
);
}
return {
__typename: 'ProcessedDomain',
id,
ethDomainId: parseInt(domainChainId, 10),
ethParentDomainId: parent?.domainChainId
? parseInt(parent.domainChainId, 10)
: null,
name: name || domainName,
color: color ? parseInt(color, 10) : Color.LightPink,
description,
};
};
export const colonyResolvers = ({
colonyManager: { networkClient },
colonyManager,
ens,
apolloClient,
ipfsWithFallback,
}: Required<Context>): Resolvers => ({
Query: {
async colonyExtension(_, { colonyAddress, extensionId }) {
const extensionAddress = await networkClient.getExtensionInstallation(
getExtensionHash(extensionId),
colonyAddress,
);
if (extensionAddress === AddressZero) {
return null;
}
return {
__typename: 'ColonyExtension',
id: extensionAddress,
address: extensionAddress,
colonyAddress,
extensionId,
};
},
async colonyAddress(_, { name }) {
try {
const address = await ens.getAddress(
ENS.getFullDomain('colony', name),
networkClient,
);
return address;
} catch (error) {
/*
* @NOTE This makes the server query fail in case of an unexistent/unregistered colony ENS name
*
* Otherwise, the ENS resolution will fail, but not this query.
* This will then not proceed further to the server query and the data
* will try to load indefinitely w/o an error
*/
return error;
}
},
async colonyName(_, { address }) {
const domain = await ens.getDomain(address, networkClient);
return ENS.stripDomainParts('colony', domain);
},
async colonyReputation(_, { address, domainId }) {
const colonyClient = await colonyManager.getClient(
ClientType.ColonyClient,
address,
);
const { skillId } = await colonyClient.getDomain(
domainId || ROOT_DOMAIN_ID,
);
const {
reputationAmount,
} = await colonyClient.getReputationWithoutProofs(skillId, AddressZero);
return reputationAmount.toString();
},
async colonyMembersWithReputation(
_,
{
colonyAddress,
domainId = COLONY_TOTAL_BALANCE_DOMAIN_ID,
}: { colonyAddress: Address; domainId: number },
) {
const colonyClient = await colonyManager.getClient(
ClientType.ColonyClient,
colonyAddress,
);
const { skillId } = await colonyClient.getDomain(domainId);
const { addresses } = await colonyClient.getMembersReputation(skillId);
return addresses || [];
},
async colonyDomain(_, { colonyAddress, domainId }) {
const { data } = await apolloClient.query<
SubgraphSingleDomainQuery,
SubgraphSingleDomainQueryVariables
>({
query: SubgraphSingleDomainDocument,
variables: {
/*
* Subgraph addresses are not checksummed
*/
colonyAddress: colonyAddress.toLowerCase(),
domainId,
},
fetchPolicy: 'network-only',
});
if (data?.domains) {
const [singleDomain] = data.domains;
return singleDomain
? getProcessedDomain(singleDomain, ipfsWithFallback)
: null;
}
return null;
},
async processedColony(_, { address }) {
try {
const { data } = await apolloClient.query<
SubgraphColonyQuery,
SubgraphColonyQueryVariables
>({
query: SubgraphColonyDocument,
variables: {
/*
* First convert it a string since in cases where the network name
* cannot be found via ENS it will throw an error
*
* Converting this to string basically converts the error object into
* a string form
*/
address: address.toString().toLowerCase(),
},
fetchPolicy: 'network-only',
});
return data?.colony
? await getProcessedColony(data.colony, address, ipfsWithFallback)
: null;
} catch (error) {
console.error(error);
return error;
}
},
async historicColonyRoles(_, { colonyAddress, blockNumber }) {
try {
const colonyClient = await colonyManager.getClient(
ClientType.ColonyClient,
colonyAddress,
);
return getHistoricColonyRoles(colonyClient, 0, blockNumber);
} catch (error) {
console.error(error);
return null;
}
},
},
ProcessedColony: {
async domains({ colonyAddress }) {
try {
const { data } = await apolloClient.query<
SubgraphDomainsQuery,
SubgraphDomainsQueryVariables
>({
query: SubgraphDomainsDocument,
variables: {
/*
* Subgraph addresses are not checksummed
*/
colonyAddress: colonyAddress.toLowerCase(),
},
fetchPolicy: 'network-only',
});
if (data?.domains) {
return Promise.all(
data.domains.map(async (domain) =>
getProcessedDomain(domain, ipfsWithFallback),
),
);
}
return null;
} catch (error) {
console.error(error);
return null;
}
},
async canMintNativeToken({ colonyAddress }) {
const colonyClient = await colonyManager.getClient(
ClientType.ColonyClient,
colonyAddress,
);
// fetch whether the user is allowed to mint tokens via the colony
let canMintNativeToken = true;
try {
await colonyClient.estimate.mintTokens(bigNumberify(1));
} catch (error) {
canMintNativeToken = false;
}
return canMintNativeToken;
},
async isInRecoveryMode({ colonyAddress }) {
const colonyClient = await colonyManager.getClient(
ClientType.ColonyClient,
colonyAddress,
);
return colonyClient.isInRecoveryMode();
},
async isNativeTokenLocked({ colonyAddress }) {
const colonyClient = await colonyManager.getClient(
ClientType.ColonyClient,
colonyAddress,
);
let isNativeTokenLocked: boolean;
try {
const locked = await colonyClient.tokenClient.locked();
isNativeTokenLocked = locked;
} catch (error) {
isNativeTokenLocked = false;
}
return isNativeTokenLocked;
},
async nativeToken({ nativeTokenAddress }, _, { client }) {
return getToken({ colonyManager, client }, nativeTokenAddress);
},
async tokens(
{ tokenAddresses }: { tokenAddresses: Address[] },
_,
{ client },
) {
const tokens = await Promise.all(
['0x0', ...tokenAddresses].map(async (tokenAddress) => {
try {
return getToken({ colonyManager, client }, tokenAddress);
} catch (error) {
console.error('Could not fetch Colony token:', tokenAddress);
console.error(error);
return undefined;
}
}),
);
return tokens.filter((token) => !!token);
},
async canUnlockNativeToken({ colonyAddress }) {
const colonyClient = (await colonyManager.getClient(
ClientType.ColonyClient,
colonyAddress,
)) as ColonyClientV5;
try {
await colonyClient.estimate.unlockToken();
} catch (error) {
return false;
}
return true;
},
async roles({ colonyAddress }) {
try {
const colonyClient = await colonyManager.getClient(
ClientType.ColonyClient,
colonyAddress,
);
if (colonyClient.clientVersion === ColonyVersion.GoerliGlider) {
throw new Error(`Not supported in this version of Colony`);
}
const { data } = await apolloClient.query<
SubgraphRoleEventsQuery,
SubgraphRoleEventsQueryVariables
>({
query: SubgraphRoleEventsDocument,
variables: {
/*
* Subgraph addresses are not checksummed
*/
colonyAddress: colonyAddress.toLowerCase(),
},
fetchPolicy: 'network-only',
});
if (data?.colonyRoleSetEvents && data?.recoveryRoleSetEvents) {
const {
colonyRoleSetEvents: colonyRoleSetSubgraphEvents,
recoveryRoleSetEvents: recoveryRoleSetSubgraphEvents,
} = data;
/*
* Parse and sort events coming from the subgraph
* Note that if the query doesn't have the blockNumber and event Id
* then the sort will be unreliable
*/
const colonyRoleEvents = colonyRoleSetSubgraphEvents
.map(parseSubgraphEvent)
.sort(sortSubgraphEventByIndex);
const recoveryRoleEvents = recoveryRoleSetSubgraphEvents
.map(parseSubgraphEvent)
.sort(sortSubgraphEventByIndex);
const roles = await formatColonyRoles(
colonyRoleEvents as LogDescription[],
recoveryRoleEvents as LogDescription[],
);
return roles.map((userRoles) => ({
...userRoles,
domains: userRoles.domains.map((domainRoles) => ({
...domainRoles,
__typename: 'DomainRoles',
})),
__typename: 'UserRoles',
}));
}
return [];
} catch (error) {
console.error(error);
return [];
}
},
async transfers({ colonyAddress }): Promise<Transfer[]> {
const colonyClient = await colonyManager.getClient(
ClientType.ColonyClient,
colonyAddress,
);
// eslint-disable-next-line max-len
const colonyFundsClaimedTransactions = await getColonyFundsClaimedTransfers(
apolloClient,
colonyAddress,
);
const payoutClaimedTransactions = await getPayoutClaimedTransfers(
apolloClient,
colonyClient,
);
return [
...colonyFundsClaimedTransactions,
...payoutClaimedTransactions,
].sort((a, b) => b.date - a.date);
},
async unclaimedTransfers({ colonyAddress }): Promise<Transfer[]> {
const colonyClient = await colonyManager.getClient(
ClientType.ColonyClient,
colonyAddress,
);
// eslint-disable-next-line max-len
const colonyUnclaimedTransfers = await getColonyUnclaimedTransfers(
apolloClient,
colonyClient,
networkClient,
);
// Get ether balance and add a fake transaction if there's any unclaimed
const colonyEtherBalance = await colonyClient.provider.getBalance(
colonyAddress,
);
// eslint-disable-next-line max-len
const colonyNonRewardsPotsTotal = await colonyClient.getNonRewardPotsTotal(
AddressZero,
);
const colonyRewardsPotTotal = await colonyClient.getFundingPotBalance(
0,
AddressZero,
);
const unclaimedEther = colonyEtherBalance
.sub(colonyNonRewardsPotsTotal)
.sub(colonyRewardsPotTotal);
if (unclaimedEther.gt(0)) {
colonyUnclaimedTransfers.push({
// @ts-ignore
__typename: 'Transfer',
amount: unclaimedEther.toString(),
colonyAddress,
date: new Date().getTime(),
from: AddressZero,
hash: HashZero,
incoming: true,
to: colonyClient.address,
token: AddressZero,
});
}
return colonyUnclaimedTransfers;
},
async version({ colonyAddress }) {
const colonyClient = await colonyManager.getClient(
ClientType.ColonyClient,
colonyAddress,
);
const version = await colonyClient.version();
return version.toString();
},
async isDeploymentFinished({ colonyAddress }) {
if (!colonyAddress) {
return null;
}
let isDeploymentFinished = true;
const colonyClient = await colonyManager.getClient(
ClientType.ColonyClient,
colonyAddress,
);
/*
* Check if the token autority is set up
*/
const { tokenClient } = colonyClient;
if (tokenClient.tokenClientType === TokenClientType.Colony) {
const tokenAuthority = await tokenClient.authority();
if (tokenAuthority === AddressZero) {
isDeploymentFinished = false;
}
}
return isDeploymentFinished;
},
async installedExtensions({ colonyAddress }) {
const promises = extensions.map((extensionId: Extension) =>
networkClient.getExtensionInstallation(
getExtensionHash(extensionId),
colonyAddress,
),
);
const extensionAddresses = await Promise.all(promises);
return extensionAddresses.reduce(
(
colonyExtensions: Array<Record<string, any>>,
address: Address,
index: number,
) => {
if (address !== AddressZero) {
return [
...colonyExtensions,
{
__typename: 'ColonyExtension',
colonyAddress,
id: address,
extensionId: extensions[index],
address,
},
];
}
return colonyExtensions;
},
[],
);
},
},
}); | the_stack |
import { Component, OnInit, Input, Output, ViewChild, ElementRef, EventEmitter, HostListener, AfterViewInit } from '@angular/core';
import { TYPE_MSG_IMAGE } from 'src/chat21-core/utils/constants';
import { NavParams, ModalController } from '@ionic/angular';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
// Logger
import { LoggerService } from 'src/chat21-core/providers/abstract/logger.service';
import { LoggerInstance } from 'src/chat21-core/providers/logger/loggerInstance';
@Component({
selector: 'app-loader-preview',
templateUrl: './loader-preview.page.html',
styleUrls: ['./loader-preview.page.scss'],
})
export class LoaderPreviewPage implements OnInit, AfterViewInit {
@ViewChild('thumbnailsPreview', { static: false }) thumbnailsPreview: ElementRef;
@ViewChild('messageTextArea', { static: false }) messageTextArea: ElementRef;
@ViewChild('imageCaptionTexarea', { static: false }) imageCaptionTexarea: any
// @Output() eventSendMessage = new EventEmitter<object>();
@Input() files: [any];
public arrayFiles = [];
public fileSelected: any;
public messageString: string;
public heightPreviewArea = '183';
private selectedFiles: any;
srcData: SafeResourceUrl;
public file_extension: string;
public file_name: string;
public file_name_ellipsis_the_middle: string;
private logger: LoggerService = LoggerInstance.getInstance();
constructor(
public viewCtrl: ModalController,
private sanitizer: DomSanitizer
) { }
ngOnInit() {
this.logger.log('[LOADER-PREVIEW-PAGE] Hello!');
// tslint:disable-next-line: prefer-for-of
this.selectedFiles = this.files;
for (let i = 0; i < this.files.length; i++) {
this.readAsDataURL(this.files[i]);
//this.fileChange(this.files[i]);
}
}
ngAfterViewInit() {
if (this.imageCaptionTexarea) {
setTimeout(() => {
// this.logger.log("[CONVS-DETAIL][MSG-TEXT-AREA] set focus on ", this.messageTextArea);
// Keyboard.show() // for android
this.logger.log("[CONVS-DETAIL][MSG-TEXT-AREA] ngAfterViewInit this.imageCaptionTexarea ", this.imageCaptionTexarea);
this.imageCaptionTexarea.setFocus();
}, 1000); //a least 150ms.
}
}
ionViewDidEnter() {
this.logger.log('[LOADER-PREVIEW-PAGE] ionViewDidEnter thumbnailsPreview.nativeElement.offsetHeight', this.thumbnailsPreview.nativeElement.offsetHeight);
this.calculateHeightPreviewArea();
}
readAsDataURL(file: any) {
this.logger.log('[LOADER-PREVIEW-PAGE] readAsDataURL file', file);
// ---------------------------------------------------------------------
// USE CASE IMAGE
// ---------------------------------------------------------------------
if (file.type.startsWith("image") && (!file.type.includes('svg'))) {
this.logger.log('[LOADER-PREVIEW-PAGE] - readAsDataURL - USE CASE IMAGE file TYPE', file.type);
const reader = new FileReader();
reader.onloadend = (evt) => {
const img = reader.result.toString();
this.logger.log('[LOADER-PREVIEW-PAGE] - readAsDataURL - FileReader success ', img);
this.arrayFiles.push(img);
if (!this.fileSelected) {
this.fileSelected = img;
}
};
reader.readAsDataURL(file);
// ---------------------------------------------------------------------
// USE CASE SVG
// ---------------------------------------------------------------------
} else if (file.type.startsWith("image") && (file.type.includes('svg'))) {
// this.previewFiles(file)
this.logger.log('[LOADER-PREVIEW-PAGE] - readAsDataURL file TYPE', file.type);
this.logger.log('[LOADER-PREVIEW-PAGE] - readAsDataURL file ', file);
const preview = document.querySelector('#img-preview') as HTMLImageElement;
const reader = new FileReader();
const that = this;
reader.addEventListener("load", function () {
// convert image file to base64 string
// const img = reader.result as string;
const img = reader.result.toString();
that.logger.log('FIREBASE-UPLOAD USE CASE SVG LoaderPreviewPage readAsDataURL img ', img);
// that.fileSelected = that.sanitizer.bypassSecurityTrustResourceUrl(img);
that.arrayFiles.push(that.sanitizer.bypassSecurityTrustResourceUrl(img));
if (!that.fileSelected) {
that.fileSelected = that.sanitizer.bypassSecurityTrustResourceUrl(img);
}
}, false);
if (file) {
reader.readAsDataURL(file);
}
// ---------------------------------------------------------------------
// USE CASE FILE
// ---------------------------------------------------------------------
// } else if (file.type.startsWith("application") || file.type.startsWith("video") || file.type.startsWith("audio") ) {
} else {
this.logger.log('[LOADER-PREVIEW-PAGE] - readAsDataURL - USE CASE FILE - FILE ', file);
this.logger.log('[LOADER-PREVIEW-PAGE] - readAsDataURL - USE CASE FILE - FILE TYPE', file.type);
this.file_extension = file.name.substring(file.name.lastIndexOf('.') + 1, file.name.length) || file.name;
this.logger.log('[LOADER-PREVIEW-PAGE] - readAsDataURL - USE CASE FILE - FILE EXTENSION', this.file_extension);
this.file_name = file.name
this.file_name_ellipsis_the_middle = this.start_and_end(file.name)
this.logger.log('[LOADER-PREVIEW-PAGE] - readAsDataURL - USE CASE FILE - FILE NAME', this.file_name);
// if (file.type) {
// const file_type_array = file.type.split('/');
// this.logger.log('FIREBASE-UPLOAD USE CASE FILE LoaderPreviewPage readAsDataURL file_type_array', file_type_array);
// this.file_type = file_type_array[1]
// } else {
// this.file_type = file.name.substring(file.name.lastIndexOf('.')+1, file.name.length) || file.name;
// }
this.createFile();
}
}
start_and_end(str) {
if (str.length > 70) {
return str.substr(0, 20) + '...' + str.substr(str.length - 10, str.length);
}
return str;
}
// file-alt-solid.png
async createFile() {
let response = await fetch('./assets/images/file-alt-solid.png');
let data = await response.blob();
let metadata = {
type: 'image/png'
};
let file = new File([data], "test.png", metadata);
this.logger.log('[LOADER-PREVIEW-PAGE] - createFile file - file', file);
const reader = new FileReader();
reader.onloadend = (evt) => {
const img = reader.result.toString();
this.logger.log('[LOADER-PREVIEW-PAGE] - createFile file - FileReader success img', img);
this.arrayFiles.push(img);
if (!this.fileSelected) {
this.fileSelected = img;
}
};
reader.readAsDataURL(file);
}
// for svg
// previewFiles(file) {
// this.logger.log('LoaderPreviewPage readAsDataURL file TYPE', file.type);
// this.logger.log('LoaderPreviewPage readAsDataURL file ', file);
// const preview = document.querySelector('#img-preview');
// this.logger.log('LoaderPreviewPage readAsDataURL preview ', preview);
// this.readAndPreview(file, preview)
// }
// readAndPreview(file, preview) {
// this.logger.log('LoaderPreviewPage readAsDataURL preview HERE 1');
// // Make sure `file.name` matches our extensions criteria
// if (/\.(jpe?g|png|gif|svg)$/i.test(file.name)) {
// var reader = new FileReader();
// reader.addEventListener("load", function () {
// var image = new Image();
// image.height = 100;
// image.title = file.name;
// image.src = this.result.toString();
// this.logger.log('LoaderPreviewPage readAsDataURL preview image.src ', image.src);
// // preview.appendChild(image);
// preview.src(image);
// }, false);
// reader.readAsDataURL(file);
// }
// if (file) {
// [].forEach.call(file, this.readAndPreview);
// }
// }
// NOT USED
fileChange(file) {
this.logger.log('fileChange');
const that = this;
if (file) {
const nameImg = file.name;
const typeFile = file.type;
this.logger.log('nameImg: ', nameImg);
this.logger.log('typeFile: ', typeFile);
const reader = new FileReader();
reader.addEventListener('load', function () {
const img = reader.result.toString();
that.logger.log('FileReader success');
that.arrayFiles.push(img);
if (!that.fileSelected) {
that.fileSelected = img;
}
if (typeFile.indexOf('image') !== -1) {
const file4Load = new Image;
file4Load.src = reader.result.toString();
file4Load.title = nameImg;
file4Load.onload = function () {
that.logger.log('that.file4Load: ', file4Load);
//that.arrayFiles.push(file4Load);
const uid = file4Load.src.substring(file4Load.src.length - 16);
const metadata = {
'name': file4Load.title,
'src': file4Load.src,
'width': file4Load.width,
'height': file4Load.height,
'type': typeFile,
'uid': uid
};
// const type_msg = 'image';
// 1 - invio messaggio
//that.viewCtrl.dismiss({fileSelected: file4Load, messageString: that.messageString});
//that.addLocalMessage(metadata, type_msg);
// 2 - carico immagine
//that.uploadSingle(metadata, type_msg);
};
}
/*
else if (typeFile.indexOf('application') !== -1) {
const type_msg = 'file';
const file = that.selectedFiles.item(0);
const metadata = {
'name': file.name,
'src': event.target.files[0].src,
'type': type_msg
};
// 1 - invio messaggio
that.addLocalMessage(metadata, type_msg);
// 2 - carico immagine
that.uploadSingle(metadata, type_msg);
}
*/
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
}
calculateHeightPreviewArea() {
const heightThumbnailsPreview = this.thumbnailsPreview.nativeElement.offsetHeight;
const heightMessageTextArea = this.messageTextArea.nativeElement.offsetHeight;
this.heightPreviewArea = (heightMessageTextArea + heightThumbnailsPreview).toString();
// this.logger.log('heightThumbnailsPreview', heightThumbnailsPreview);
// this.logger.log('heightMessageTextArea', this.messageTextArea);
// this.logger.log('heightPreviewArea', this.heightPreviewArea);
}
uploadImages() { }
/** */
onChangeTextArea(e: any) {
this.logger.log('onChangeTextArea', e.target.clientHeight);
this.calculateHeightPreviewArea();
// try {
// let height: number = e.target.offsetHeight;
// if (height < 37 ) {
// height = 37;
// }
// this.heightPreviewArea = (height + 139).toString();
// } catch (e) {
// this.heightPreviewArea = '176';
// }
}
/** */
onSelectImage(file: any) {
this.fileSelected = file;
}
@HostListener('document:keydown', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
if (event.key === 'Enter') {
this.onSendMessage()
}
}
pressedOnKeyboard(e: any, text: string) {
this.logger.log('[LOADER-PREVIEW-PAGE] pressedOnKeyboard - event:: ', e);
// const message = e.target.textContent.trim();
// if (e.inputType === 'insertLineBreak' && message === '') {
// this.messageString = '';
// return;
// } else {
// this.messageString = '';
// }
this.onSendMessage()
}
/** */
onSendMessage() {
this.logger.log('[LOADER-PREVIEW-PAGE] onSendMessage messageString:', this.messageString);
let file = this.selectedFiles.item(0);
const file4Load = new Image;
const nameImg = file.name;
const typeFile = file.type;
file4Load.src = this.fileSelected;
file4Load.title = nameImg;
const uid = file4Load.src.substring(file4Load.src.length - 16);
const metadata = {
'name': file4Load.title,
'src': file4Load.src,
'width': file4Load.width,
'height': file4Load.height,
'type': typeFile,
'uid': uid
};
this.viewCtrl.dismiss({ fileSelected: file, messageString: this.messageString, metadata: metadata, type: TYPE_MSG_IMAGE });
}
async onClose() {
this.viewCtrl.dismiss();
}
} | the_stack |
// Type definitions for blockly
// Project: https://developers.google.com/blockly/
// Definitions by: Troy McKinnon <https://github.com/trodi>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module Blockly {
class Block extends Block__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class Block__Class {
/**
* Class for one block.
* Not normally called directly, workspace.newBlock() is preferred.
* @param {!Blockly.Workspace} workspace The block's workspace.
* @param {?string} prototypeName Name of the language object containing
* type-specific functions for this block.
* @param {string=} opt_id Optional ID. Use this ID if provided, otherwise
* create a new id.
* @constructor
*/
constructor(workspace: Blockly.Workspace, prototypeName: string, opt_id?: string);
/** @type {string} */
id: string;
/** @type {Blockly.Connection} */
outputConnection: Blockly.Connection;
/** @type {Blockly.Connection} */
nextConnection: Blockly.Connection;
/** @type {Blockly.Connection} */
previousConnection: Blockly.Connection;
/** @type {!Array.<!Blockly.Input>} */
inputList: Blockly.Input[];
/** @type {boolean|undefined} */
inputsInline: boolean|any /*undefined*/;
/** @type {boolean} */
disabled: boolean;
/** @type {string|!Function} */
tooltip: string|Function;
/** @type {boolean} */
contextMenu: boolean;
init: Function;
/**
* @type {Blockly.Block}
* @private
*/
parentBlock_: Blockly.Block;
/**
* @type {!Array.<!Blockly.Block>}
* @private
*/
childBlocks_: Blockly.Block[];
/**
* @type {boolean}
* @private
*/
deletable_: boolean;
/**
* @type {boolean}
* @private
*/
movable_: boolean;
/**
* @type {boolean}
* @private
*/
editable_: boolean;
/**
* @type {boolean}
* @private
*/
isShadow_: boolean;
/**
* @type {boolean}
* @private
*/
collapsed_: boolean;
/** @type {string|Blockly.Comment} */
comment: string|Blockly.Comment;
/**
* @type {!goog.math.Coordinate}
* @private
*/
xy_: goog.math.Coordinate;
/** @type {!Blockly.Workspace} */
workspace: Blockly.Workspace;
/** @type {boolean} */
isInFlyout: boolean;
/** @type {boolean} */
isInMutator: boolean;
/** @type {boolean} */
RTL: boolean;
/** @type {string} */
type: string;
/** @type {boolean|undefined} */
inputsInlineDefault: boolean|any /*undefined*/;
/**
* Optional text data that round-trips beween blocks and XML.
* Has no effect. May be used by 3rd parties for meta information.
* @type {?string}
*/
data: string;
/**
* Colour of the block in '#RRGGBB' format.
* @type {string}
* @private
*/
colour_: string;
/**
* Dispose of this block.
* @param {boolean} healStack If true, then try to heal any gap by connecting
* the next statement with the previous statement. Otherwise, dispose of
* all children of this block.
*/
dispose(healStack: boolean): void;
/**
* Unplug this block from its superior block. If this block is a statement,
* optionally reconnect the block underneath with the block on top.
* @param {boolean} opt_healStack Disconnect child statement and reconnect
* stack. Defaults to false.
*/
unplug(opt_healStack: boolean): void;
/**
* Returns all connections originating from this block.
* @return {!Array.<!Blockly.Connection>} Array of connections.
* @private
*/
getConnections_(): Blockly.Connection[];
/**
* Walks down a stack of blocks and finds the last next connection on the stack.
* @return {Blockly.Connection} The last next connection on the stack, or null.
* @private
*/
lastConnectionInStack_(): Blockly.Connection;
/**
* Bump unconnected blocks out of alignment. Two blocks which aren't actually
* connected should not coincidentally line up on screen.
* @private
*/
bumpNeighbours_(): void;
/**
* Return the parent block or null if this block is at the top level.
* @return {Blockly.Block} The block that holds the current block.
*/
getParent(): Blockly.Block;
/**
* Return the input that connects to the specified block.
* @param {!Blockly.Block} block A block connected to an input on this block.
* @return {Blockly.Input} The input that connects to the specified block.
*/
getInputWithBlock(block: Blockly.Block): Blockly.Input;
/**
* Return the parent block that surrounds the current block, or null if this
* block has no surrounding block. A parent block might just be the previous
* statement, whereas the surrounding block is an if statement, while loop, etc.
* @return {Blockly.Block} The block that surrounds the current block.
*/
getSurroundParent(): Blockly.Block;
/**
* Return the next statement block directly connected to this block.
* @return {Blockly.Block} The next statement block or null.
*/
getNextBlock(): Blockly.Block;
/**
* Return the top-most block in this block's tree.
* This will return itself if this block is at the top level.
* @return {!Blockly.Block} The root block.
*/
getRootBlock(): Blockly.Block;
/**
* Find all the blocks that are directly nested inside this one.
* Includes value and block inputs, as well as any following statement.
* Excludes any connection on an output tab or any preceding statement.
* @return {!Array.<!Blockly.Block>} Array of blocks.
*/
getChildren(): Blockly.Block[];
/**
* Set parent of this block to be a new block or null.
* @param {Blockly.Block} newParent New parent block.
*/
setParent(newParent: Blockly.Block): void;
/**
* Find all the blocks that are directly or indirectly nested inside this one.
* Includes this block in the list.
* Includes value and block inputs, as well as any following statements.
* Excludes any connection on an output tab or any preceding statements.
* @return {!Array.<!Blockly.Block>} Flattened array of blocks.
*/
getDescendants(): Blockly.Block[];
/**
* Get whether this block is deletable or not.
* @return {boolean} True if deletable.
*/
isDeletable(): boolean;
/**
* Set whether this block is deletable or not.
* @param {boolean} deletable True if deletable.
*/
setDeletable(deletable: boolean): void;
/**
* Get whether this block is movable or not.
* @return {boolean} True if movable.
*/
isMovable(): boolean;
/**
* Set whether this block is movable or not.
* @param {boolean} movable True if movable.
*/
setMovable(movable: boolean): void;
/**
* Get whether this block is a shadow block or not.
* @return {boolean} True if a shadow.
*/
isShadow(): boolean;
/**
* Set whether this block is a shadow block or not.
* @param {boolean} shadow True if a shadow.
*/
setShadow(shadow: boolean): void;
/**
* Get whether this block is editable or not.
* @return {boolean} True if editable.
*/
isEditable(): boolean;
/**
* Set whether this block is editable or not.
* @param {boolean} editable True if editable.
*/
setEditable(editable: boolean): void;
/**
* Set whether the connections are hidden (not tracked in a database) or not.
* Recursively walk down all child blocks (except collapsed blocks).
* @param {boolean} hidden True if connections are hidden.
*/
setConnectionsHidden(hidden: boolean): void;
/**
* Set the URL of this block's help page.
* @param {string|Function} url URL string for block help, or function that
* returns a URL. Null for no help.
*/
setHelpUrl(url: string|Function): void;
/**
* Change the tooltip text for a block.
* @param {string|!Function} newTip Text for tooltip or a parent element to
* link to for its tooltip. May be a function that returns a string.
*/
setTooltip(newTip: string|Function): void;
/**
* Get the colour of a block.
* @return {string} #RRGGBB string.
*/
getColour(): string;
/**
* Change the colour of a block.
* @param {number|string} colour HSV hue value, or #RRGGBB string.
*/
setColour(colour: number|string): void;
/**
* Returns the named field from a block.
* @param {string} name The name of the field.
* @return {Blockly.Field} Named field, or null if field does not exist.
*/
getField(name: string): Blockly.Field;
/**
* Return all variables referenced by this block.
* @return {!Array.<string>} List of variable names.
*/
getVars(): string[];
/**
* Notification that a variable is renaming.
* If the name matches one of this block's variables, rename it.
* @param {string} oldName Previous name of variable.
* @param {string} newName Renamed variable.
*/
renameVar(oldName: string, newName: string): void;
/**
* Returns the language-neutral value from the field of a block.
* @param {string} name The name of the field.
* @return {?string} Value from the field or null if field does not exist.
*/
getFieldValue(name: string): string;
/**
* Returns the language-neutral value from the field of a block.
* @param {string} name The name of the field.
* @return {?string} Value from the field or null if field does not exist.
* @deprecated December 2013
*/
getTitleValue(name: string): string;
/**
* Change the field value for a block (e.g. 'CHOOSE' or 'REMOVE').
* @param {string} newValue Value to be the new field.
* @param {string} name The name of the field.
*/
setFieldValue(newValue: string, name: string): void;
/**
* Change the field value for a block (e.g. 'CHOOSE' or 'REMOVE').
* @param {string} newValue Value to be the new field.
* @param {string} name The name of the field.
* @deprecated December 2013
*/
setTitleValue(newValue: string, name: string): void;
/**
* Set whether this block can chain onto the bottom of another block.
* @param {boolean} newBoolean True if there can be a previous statement.
* @param {string|Array.<string>|null|undefined} opt_check Statement type or
* list of statement types. Null/undefined if any type could be connected.
*/
setPreviousStatement(newBoolean: boolean, opt_check: string|string[]|any /*null*/|any /*undefined*/): void;
/**
* Set whether another block can chain onto the bottom of this block.
* @param {boolean} newBoolean True if there can be a next statement.
* @param {string|Array.<string>|null|undefined} opt_check Statement type or
* list of statement types. Null/undefined if any type could be connected.
*/
setNextStatement(newBoolean: boolean, opt_check: string|string[]|any /*null*/|any /*undefined*/): void;
/**
* Set whether this block returns a value.
* @param {boolean} newBoolean True if there is an output.
* @param {string|Array.<string>|null|undefined} opt_check Returned type or list
* of returned types. Null or undefined if any type could be returned
* (e.g. variable get).
*/
setOutput(newBoolean: boolean, opt_check: string|string[]|any /*null*/|any /*undefined*/): void;
/**
* Set whether value inputs are arranged horizontally or vertically.
* @param {boolean} newBoolean True if inputs are horizontal.
*/
setInputsInline(newBoolean: boolean): void;
/**
* Get whether value inputs are arranged horizontally or vertically.
* @return {boolean} True if inputs are horizontal.
*/
getInputsInline(): boolean;
/**
* Set whether the block is disabled or not.
* @param {boolean} disabled True if disabled.
*/
setDisabled(disabled: boolean): void;
/**
* Get whether the block is disabled or not due to parents.
* The block's own disabled property is not considered.
* @return {boolean} True if disabled.
*/
getInheritedDisabled(): boolean;
/**
* Get whether the block is collapsed or not.
* @return {boolean} True if collapsed.
*/
isCollapsed(): boolean;
/**
* Set whether the block is collapsed or not.
* @param {boolean} collapsed True if collapsed.
*/
setCollapsed(collapsed: boolean): void;
/**
* Create a human-readable text representation of this block and any children.
* @param {number=} opt_maxLength Truncate the string to this length.
* @param {string=} opt_emptyToken The placeholder string used to denote an
* empty field. If not specified, '?' is used.
* @return {string} Text of block.
*/
toString(opt_maxLength?: number, opt_emptyToken?: string): string;
/**
* Shortcut for appending a value input row.
* @param {string} name Language-neutral identifier which may used to find this
* input again. Should be unique to this block.
* @return {!Blockly.Input} The input object created.
*/
appendValueInput(name: string): Blockly.Input;
/**
* Shortcut for appending a statement input row.
* @param {string} name Language-neutral identifier which may used to find this
* input again. Should be unique to this block.
* @return {!Blockly.Input} The input object created.
*/
appendStatementInput(name: string): Blockly.Input;
/**
* Shortcut for appending a dummy input row.
* @param {string=} opt_name Language-neutral identifier which may used to find
* this input again. Should be unique to this block.
* @return {!Blockly.Input} The input object created.
*/
appendDummyInput(opt_name?: string): Blockly.Input;
/**
* Initialize this block using a cross-platform, internationalization-friendly
* JSON description.
* @param {!Object} json Structured data describing the block.
*/
jsonInit(json: Object): void;
/**
* Interpolate a message description onto the block.
* @param {string} message Text contains interpolation tokens (%1, %2, ...)
* that match with fields or inputs defined in the args array.
* @param {!Array} args Array of arguments to be interpolated.
* @param {string=} lastDummyAlign If a dummy input is added at the end,
* how should it be aligned?
* @private
*/
interpolate_(message: string, args: any[], lastDummyAlign?: string): void;
/**
* Add a value input, statement input or local variable to this block.
* @param {number} type Either Blockly.INPUT_VALUE or Blockly.NEXT_STATEMENT or
* Blockly.DUMMY_INPUT.
* @param {string} name Language-neutral identifier which may used to find this
* input again. Should be unique to this block.
* @return {!Blockly.Input} The input object created.
* @private
*/
appendInput_(type: number, name: string): Blockly.Input;
/**
* Move a named input to a different location on this block.
* @param {string} name The name of the input to move.
* @param {?string} refName Name of input that should be after the moved input,
* or null to be the input at the end.
*/
moveInputBefore(name: string, refName: string): void;
/**
* Move a numbered input to a different location on this block.
* @param {number} inputIndex Index of the input to move.
* @param {number} refIndex Index of input that should be after the moved input.
*/
moveNumberedInputBefore(inputIndex: number, refIndex: number): void;
/**
* Remove an input from this block.
* @param {string} name The name of the input.
* @param {boolean=} opt_quiet True to prevent error if input is not present.
* @throws {goog.asserts.AssertionError} if the input is not present and
* opt_quiet is not true.
*/
removeInput(name: string, opt_quiet?: boolean): void;
/**
* Fetches the named input object.
* @param {string} name The name of the input.
* @return {Blockly.Input} The input object, or null if input does not exist.
*/
getInput(name: string): Blockly.Input;
/**
* Fetches the block attached to the named input.
* @param {string} name The name of the input.
* @return {Blockly.Block} The attached value block, or null if the input is
* either disconnected or if the input does not exist.
*/
getInputTargetBlock(name: string): Blockly.Block;
/**
* Returns the comment on this block (or '' if none).
* @return {string} Block's comment.
*/
getCommentText(): string;
/**
* Set this block's comment text.
* @param {?string} text The text, or null to delete.
*/
setCommentText(text: string): void;
/**
* Set this block's warning text.
* @param {?string} text The text, or null to delete.
*/
setWarningText(text: string): void;
/**
* Give this block a mutator dialog.
* @param {Blockly.Mutator} mutator A mutator dialog instance or null to remove.
*/
setMutator(mutator: Blockly.Mutator): void;
/**
* Return the coordinates of the top-left corner of this block relative to the
* drawing surface's origin (0,0).
* @return {!goog.math.Coordinate} Object with .x and .y properties.
*/
getRelativeToSurfaceXY(): goog.math.Coordinate;
/**
* Move a block by a relative offset.
* @param {number} dx Horizontal offset.
* @param {number} dy Vertical offset.
*/
moveBy(dx: number, dy: number): void;
/**
* Create a connection of the specified type.
* @param {number} type The type of the connection to create.
* @return {!Blockly.Connection} A new connection of the specified type.
* @private
*/
makeConnection_(type: number): Blockly.Connection;
}
}
declare module Blockly {
/**
* The main workspace most recently used.
* Set by Blockly.WorkspaceSvg.prototype.markFocused
* @type {Blockly.Workspace}
*/
var mainWorkspace: Blockly.Workspace;
/**
* Currently selected block.
* @type {Blockly.Block}
*/
var selected: Blockly.Block;
/**
* Currently highlighted connection (during a drag).
* @type {Blockly.Connection}
* @private
*/
var highlightedConnection_: Blockly.Connection;
/**
* Connection on dragged block that matches the highlighted connection.
* @type {Blockly.Connection}
* @private
*/
var localConnection_: Blockly.Connection;
/**
* All of the connections on blocks that are currently being dragged.
* @type {!Array.<!Blockly.Connection>}
* @private
*/
var draggingConnections_: Blockly.Connection[];
/**
* Contents of the local clipboard.
* @type {Element}
* @private
*/
var clipboardXml_: Element;
/**
* Source of the local clipboard.
* @type {Blockly.WorkspaceSvg}
* @private
*/
var clipboardSource_: Blockly.WorkspaceSvg;
/**
* Is the mouse dragging a block?
* DRAG_NONE - No drag operation.
* DRAG_STICKY - Still inside the sticky DRAG_RADIUS.
* DRAG_FREE - Freely draggable.
* @private
*/
var dragMode_: any /*missing*/;
/**
* Convert a hue (HSV model) into an RGB hex triplet.
* @param {number} hue Hue on a colour wheel (0-360).
* @return {string} RGB code, e.g. '#5ba65b'.
*/
function hueToRgb(hue: number): string;
/**
* Returns the dimensions of the specified SVG image.
* @param {!Element} svg SVG image.
* @return {!Object} Contains width and height properties.
*/
function svgSize(svg: Element): Object;
/**
* Size the workspace when the contents change. This also updates
* scrollbars accordingly.
* @param {!Blockly.WorkspaceSvg} workspace The workspace to resize.
*/
function resizeSvgContents(workspace: Blockly.WorkspaceSvg): void;
/**
* Size the SVG image to completely fill its container. Call this when the view
* actually changes sizes (e.g. on a window resize/device orientation change).
* See Blockly.resizeSvgContents to resize the workspace when the contents
* change (e.g. when a block is added or removed).
* Record the height/width of the SVG image.
* @param {!Blockly.WorkspaceSvg} workspace Any workspace in the SVG.
*/
function svgResize(workspace: Blockly.WorkspaceSvg): void;
/**
* Handle a key-down on SVG drawing surface.
* @param {!Event} e Key down event.
* @private
*/
function onKeyDown_(e: Event): void;
/**
* Stop binding to the global mouseup and mousemove events.
* @private
*/
function terminateDrag_(): void;
/**
* Copy a block onto the local clipboard.
* @param {!Blockly.Block} block Block to be copied.
* @private
*/
function copy_(block: Blockly.Block): void;
/**
* Duplicate this block and its children.
* @param {!Blockly.Block} block Block to be copied.
* @private
*/
function duplicate_(block: Blockly.Block): void;
/**
* Cancel the native context menu, unless the focus is on an HTML input widget.
* @param {!Event} e Mouse down event.
* @private
*/
function onContextMenu_(e: Event): void;
/**
* Close tooltips, context menus, dropdown selections, etc.
* @param {boolean=} opt_allowToolbox If true, don't close the toolbox.
*/
function hideChaff(opt_allowToolbox?: boolean): void;
/**
* When something in Blockly's workspace changes, call a function.
* @param {!Function} func Function to call.
* @return {!Array.<!Array>} Opaque data that can be passed to
* removeChangeListener.
* @deprecated April 2015
*/
function addChangeListener(func: Function): any[][];
/**
* Returns the main workspace. Returns the last used main workspace (based on
* focus). Try not to use this function, particularly if there are multiple
* Blockly instances on a page.
* @return {!Blockly.Workspace} The main workspace.
*/
function getMainWorkspace(): Blockly.Workspace;
}
declare module Blockly {
class BlockSvg extends BlockSvg__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class BlockSvg__Class extends Blockly.Block__Class {
/**
* Class for a block's SVG representation.
* Not normally called directly, workspace.newBlock() is preferred.
* @param {!Blockly.Workspace} workspace The block's workspace.
* @param {?string} prototypeName Name of the language object containing
* type-specific functions for this block.
* @param {string=} opt_id Optional ID. Use this ID if provided, otherwise
* create a new id.
* @extends {Blockly.Block}
* @constructor
*/
constructor(workspace: Blockly.Workspace, prototypeName: string, opt_id?: string);
/**
* @type {SVGElement}
* @private
*/
svgGroup_: SVGElement;
/**
* @type {SVGElement}
* @private
*/
svgPathDark_: SVGElement;
/**
* @type {SVGElement}
* @private
*/
svgPath_: SVGElement;
/**
* @type {SVGElement}
* @private
*/
svgPathLight_: SVGElement;
/** @type {boolean} */
rendered: boolean;
/**
* Height of this block, not including any statement blocks above or below.
*/
height: any /*missing*/;
/**
* Width of this block, including any connected value blocks.
*/
width: any /*missing*/;
/**
* Original location of block being dragged.
* @type {goog.math.Coordinate}
* @private
*/
dragStartXY_: goog.math.Coordinate;
/**
* Create and initialize the SVG representation of the block.
* May be called more than once.
*/
initSvg(): void;
/**
* Select this block. Highlight it visually.
*/
select(): void;
/**
* Unselect this block. Remove its highlighting.
*/
unselect(): void;
/**
* Block's mutator icon (if any).
* @type {Blockly.Mutator}
*/
mutator: Blockly.Mutator;
/**
* Block's comment icon (if any).
* @type {Blockly.Comment}
*/
comment: Blockly.Comment;
/**
* Block's warning icon (if any).
* @type {Blockly.Warning}
*/
warning: Blockly.Warning;
/**
* Returns a list of mutator, comment, and warning icons.
* @return {!Array} List of icons.
*/
getIcons(): any[];
/**
* Set parent of this block to be a new block or null.
* @param {Blockly.BlockSvg} newParent New parent block.
*/
setParent(newParent: Blockly.BlockSvg): void;
/**
* Return the coordinates of the top-left corner of this block relative to the
* drawing surface's origin (0,0).
* @return {!goog.math.Coordinate} Object with .x and .y properties.
*/
getRelativeToSurfaceXY(): goog.math.Coordinate;
/**
* Move a block by a relative offset.
* @param {number} dx Horizontal offset.
* @param {number} dy Vertical offset.
*/
moveBy(dx: number, dy: number): void;
/**
* Snap this block to the nearest grid point.
*/
snapToGrid(): void;
/**
* Returns a bounding box describing the dimensions of this block
* and any blocks stacked below it.
* @return {!{height: number, width: number}} Object with height and width
* properties.
*/
getHeightWidth(): { height: number; width: number };
/**
* Returns the coordinates of a bounding box describing the dimensions of this
* block and any blocks stacked below it.
* @return {!{topLeft: goog.math.Coordinate, bottomRight: goog.math.Coordinate}}
* Object with top left and bottom right coordinates of the bounding box.
*/
getBoundingRectangle(): { topLeft: goog.math.Coordinate; bottomRight: goog.math.Coordinate };
/**
* Set whether the block is collapsed or not.
* @param {boolean} collapsed True if collapsed.
*/
setCollapsed(collapsed: boolean): void;
/**
* Open the next (or previous) FieldTextInput.
* @param {Blockly.Field|Blockly.Block} start Current location.
* @param {boolean} forward If true go forward, otherwise backward.
*/
tab(start: Blockly.Field|Blockly.Block, forward: boolean): void;
/**
* Handle a mouse-down on an SVG block.
* @param {!Event} e Mouse down event or touch start event.
* @private
*/
onMouseDown_(e: Event): void;
/**
* Handle a mouse-up anywhere in the SVG pane. Is only registered when a
* block is clicked. We can't use mouseUp on the block since a fast-moving
* cursor can briefly escape the block before it catches up.
* @param {!Event} e Mouse up event.
* @private
*/
onMouseUp_(e: Event): void;
/**
* Load the block's help page in a new window.
* @private
*/
showHelp_(): void;
/**
* Show the context menu for this block.
* @param {!Event} e Mouse event.
* @private
*/
showContextMenu_(e: Event): void;
/**
* Move the connections for this block and all blocks attached under it.
* Also update any attached bubbles.
* @param {number} dx Horizontal offset from current location.
* @param {number} dy Vertical offset from current location.
* @private
*/
moveConnections_(dx: number, dy: number): void;
/**
* Recursively adds or removes the dragging class to this node and its children.
* @param {boolean} adding True if adding, false if removing.
* @private
*/
setDragging_(adding: boolean): void;
/**
* Drag this block to follow the mouse.
* @param {!Event} e Mouse move event.
* @private
*/
onMouseMove_(e: Event): void;
/**
* Add or remove the UI indicating if this block is movable or not.
*/
updateMovable(): void;
/**
* Set whether this block is movable or not.
* @param {boolean} movable True if movable.
*/
setMovable(movable: boolean): void;
/**
* Set whether this block is editable or not.
* @param {boolean} editable True if editable.
*/
setEditable(editable: boolean): void;
/**
* Set whether this block is a shadow block or not.
* @param {boolean} shadow True if a shadow.
*/
setShadow(shadow: boolean): void;
/**
* Return the root node of the SVG or null if none exists.
* @return {Element} The root SVG node (probably a group).
*/
getSvgRoot(): Element;
/**
* Dispose of this block.
* @param {boolean} healStack If true, then try to heal any gap by connecting
* the next statement with the previous statement. Otherwise, dispose of
* all children of this block.
* @param {boolean} animate If true, show a disposal animation and sound.
*/
dispose(healStack: boolean, animate?: boolean): void;
/**
* Play some UI effects (sound, animation) when disposing of a block.
*/
disposeUiEffect(): void;
/**
* Play some UI effects (sound, ripple) after a connection has been established.
*/
connectionUiEffect(): void;
/**
* Play some UI effects (sound, animation) when disconnecting a block.
*/
disconnectUiEffect(): void;
/**
* Change the colour of a block.
*/
updateColour(): void;
/**
* Enable or disable a block.
*/
updateDisabled(): void;
/**
* Returns the comment on this block (or '' if none).
* @return {string} Block's comment.
*/
getCommentText(): string;
/**
* Set this block's comment text.
* @param {?string} text The text, or null to delete.
*/
setCommentText(text: string): void;
/**
* Set this block's warning text.
* @param {?string} text The text, or null to delete.
* @param {string=} opt_id An optional ID for the warning text to be able to
* maintain multiple warnings.
*/
setWarningText(text: string, opt_id?: string): void;
/**
* Give this block a mutator dialog.
* @param {Blockly.Mutator} mutator A mutator dialog instance or null to remove.
*/
setMutator(mutator: Blockly.Mutator): void;
/**
* Set whether the block is disabled or not.
* @param {boolean} disabled True if disabled.
*/
setDisabled(disabled: boolean): void;
/**
* Select this block. Highlight it visually.
*/
addSelect(): void;
/**
* Unselect this block. Remove its highlighting.
*/
removeSelect(): void;
/**
* Adds the dragging class to this block.
* Also disables the highlights/shadows to improve performance.
*/
addDragging(): void;
/**
* Removes the dragging class from this block.
*/
removeDragging(): void;
/**
* Change the colour of a block.
* @param {number|string} colour HSV hue value, or #RRGGBB string.
*/
setColour(colour: number|string): void;
/**
* Set whether this block can chain onto the bottom of another block.
* @param {boolean} newBoolean True if there can be a previous statement.
* @param {string|Array.<string>|null|undefined} opt_check Statement type or
* list of statement types. Null/undefined if any type could be connected.
*/
setPreviousStatement(newBoolean: boolean, opt_check: string|string[]|any /*null*/|any /*undefined*/): void;
/**
* Set whether another block can chain onto the bottom of this block.
* @param {boolean} newBoolean True if there can be a next statement.
* @param {string|Array.<string>|null|undefined} opt_check Statement type or
* list of statement types. Null/undefined if any type could be connected.
*/
setNextStatement(newBoolean: boolean, opt_check: string|string[]|any /*null*/|any /*undefined*/): void;
/**
* Set whether this block returns a value.
* @param {boolean} newBoolean True if there is an output.
* @param {string|Array.<string>|null|undefined} opt_check Returned type or list
* of returned types. Null or undefined if any type could be returned
* (e.g. variable get).
*/
setOutput(newBoolean: boolean, opt_check: string|string[]|any /*null*/|any /*undefined*/): void;
/**
* Set whether value inputs are arranged horizontally or vertically.
* @param {boolean} newBoolean True if inputs are horizontal.
*/
setInputsInline(newBoolean: boolean): void;
/**
* Remove an input from this block.
* @param {string} name The name of the input.
* @param {boolean=} opt_quiet True to prevent error if input is not present.
* @throws {goog.asserts.AssertionError} if the input is not present and
* opt_quiet is not true.
*/
removeInput(name: string, opt_quiet?: boolean): void;
/**
* Move a numbered input to a different location on this block.
* @param {number} inputIndex Index of the input to move.
* @param {number} refIndex Index of input that should be after the moved input.
*/
moveNumberedInputBefore(inputIndex: number, refIndex: number): void;
/**
* Add a value input, statement input or local variable to this block.
* @param {number} type Either Blockly.INPUT_VALUE or Blockly.NEXT_STATEMENT or
* Blockly.DUMMY_INPUT.
* @param {string} name Language-neutral identifier which may used to find this
* input again. Should be unique to this block.
* @return {!Blockly.Input} The input object created.
* @private
*/
appendInput_(type: number, name: string): Blockly.Input;
/**
* Returns connections originating from this block.
* @param {boolean} all If true, return all connections even hidden ones.
* Otherwise, for a non-rendered block return an empty list, and for a
* collapsed block don't return inputs connections.
* @return {!Array.<!Blockly.Connection>} Array of connections.
* @private
*/
getConnections_(all?: boolean): Blockly.Connection[];
/**
* Create a connection of the specified type.
* @param {number} type The type of the connection to create.
* @return {!Blockly.RenderedConnection} A new connection of the specified type.
* @private
*/
makeConnection_(type: number): Blockly.RenderedConnection;
}
}
declare module Blockly {
class Bubble extends Bubble__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class Bubble__Class {
/**
* Class for UI bubble.
* @param {!Blockly.WorkspaceSvg} workspace The workspace on which to draw the
* bubble.
* @param {!Element} content SVG content for the bubble.
* @param {Element} shape SVG element to avoid eclipsing.
* @param {!goog.math.Coodinate} anchorXY Absolute position of bubble's anchor
* point.
* @param {?number} bubbleWidth Width of bubble, or null if not resizable.
* @param {?number} bubbleHeight Height of bubble, or null if not resizable.
* @constructor
*/
constructor(workspace: Blockly.WorkspaceSvg, content: Element, shape: Element, anchorXY: goog.math.Coordinate, bubbleWidth: number, bubbleHeight: number);
/**
* Function to call on resize of bubble.
* @type {Function}
*/
resizeCallback_: Function;
/**
* Flag to stop incremental rendering during construction.
* @private
*/
rendered_: any /*missing*/;
/**
* Absolute coordinate of anchor point.
* @type {goog.math.Coordinate}
* @private
*/
anchorXY_: goog.math.Coordinate;
/**
* Relative X coordinate of bubble with respect to the anchor's centre.
* In RTL mode the initial value is negated.
* @private
*/
relativeLeft_: any /*missing*/;
/**
* Relative Y coordinate of bubble with respect to the anchor's centre.
* @private
*/
relativeTop_: any /*missing*/;
/**
* Width of bubble.
* @private
*/
width_: any /*missing*/;
/**
* Height of bubble.
* @private
*/
height_: any /*missing*/;
/**
* Automatically position and reposition the bubble.
* @private
*/
autoLayout_: any /*missing*/;
/**
* Create the bubble's DOM.
* @param {!Element} content SVG content for the bubble.
* @param {boolean} hasResize Add diagonal resize gripper if true.
* @return {!Element} The bubble's SVG group.
* @private
*/
createDom_(content: Element, hasResize: boolean): Element;
/**
* Handle a mouse-down on bubble's border.
* @param {!Event} e Mouse down event.
* @private
*/
bubbleMouseDown_(e: Event): void;
/**
* Drag this bubble to follow the mouse.
* @param {!Event} e Mouse move event.
* @private
*/
bubbleMouseMove_(e: Event): void;
/**
* Handle a mouse-down on bubble's resize corner.
* @param {!Event} e Mouse down event.
* @private
*/
resizeMouseDown_(e: Event): void;
/**
* Resize this bubble to follow the mouse.
* @param {!Event} e Mouse move event.
* @private
*/
resizeMouseMove_(e: Event): void;
/**
* Register a function as a callback event for when the bubble is resized.
* @param {!Function} callback The function to call on resize.
*/
registerResizeEvent(callback: Function): void;
/**
* Move this bubble to the top of the stack.
* @private
*/
promote_(): void;
/**
* Notification that the anchor has moved.
* Update the arrow and bubble accordingly.
* @param {!goog.math.Coordinate} xy Absolute location.
*/
setAnchorLocation(xy: goog.math.Coordinate): void;
/**
* Position the bubble so that it does not fall off-screen.
* @private
*/
layoutBubble_(): void;
/**
* Move the bubble to a location relative to the anchor's centre.
* @private
*/
positionBubble_(): void;
/**
* Get the dimensions of this bubble.
* @return {!Object} Object with width and height properties.
*/
getBubbleSize(): Object;
/**
* Size this bubble.
* @param {number} width Width of the bubble.
* @param {number} height Height of the bubble.
*/
setBubbleSize(width: number, height: number): void;
/**
* Draw the arrow between the bubble and the origin.
* @private
*/
renderArrow_(): void;
/**
* Change the colour of a bubble.
* @param {string} hexColour Hex code of colour.
*/
setColour(hexColour: string): void;
/**
* Dispose of this bubble.
*/
dispose(): void;
}
}
declare module Blockly {
class Comment extends Comment__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class Comment__Class extends Blockly.Icon__Class {
/**
* Class for a comment.
* @param {!Blockly.Block} block The block associated with this comment.
* @extends {Blockly.Icon}
* @constructor
*/
constructor(block: Blockly.Block);
/**
* Comment text (if bubble is not visible).
* @private
*/
text_: any /*missing*/;
/**
* Width of bubble.
* @private
*/
width_: any /*missing*/;
/**
* Height of bubble.
* @private
*/
height_: any /*missing*/;
/**
* Draw the comment icon.
* @param {!Element} group The icon group.
* @private
*/
drawIcon_(group: Element): void;
/**
* Create the editor for the comment's bubble.
* @return {!Element} The top-level node of the editor.
* @private
*/
createEditor_(): Element;
/**
* Callback function triggered when the bubble has resized.
* Resize the text area accordingly.
* @private
*/
resizeBubble_(): void;
/**
* Show or hide the comment bubble.
* @param {boolean} visible True if the bubble should be visible.
*/
setVisible(visible: boolean): void;
/**
* Bring the comment to the top of the stack when clicked on.
* @param {!Event} e Mouse up event.
* @private
*/
textareaFocus_(e: Event): void;
/**
* Get the dimensions of this comment's bubble.
* @return {!Object} Object with width and height properties.
*/
getBubbleSize(): Object;
/**
* Size this comment's bubble.
* @param {number} width Width of the bubble.
* @param {number} height Height of the bubble.
*/
setBubbleSize(width: number, height: number): void;
/**
* Returns this comment's text.
* @return {string} Comment text.
*/
getText(): string;
/**
* Set this comment's text.
* @param {string} text Comment text.
*/
setText(text: string): void;
/**
* Dispose of this comment.
*/
dispose(): void;
}
}
declare module Blockly {
class ConnectionDB extends ConnectionDB__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class ConnectionDB__Class {
/**
* Database of connections.
* Connections are stored in order of their vertical component. This way
* connections in an area may be looked up quickly using a binary search.
* @constructor
*/
constructor();
/**
* Add a connection to the database. Must not already exist in DB.
* @param {!Blockly.Connection} connection The connection to be added.
*/
addConnection(connection: Blockly.Connection): void;
/**
* Find the given connection.
* Starts by doing a binary search to find the approximate location, then
* linearly searches nearby for the exact connection.
* @param {!Blockly.Connection} conn The connection to find.
* @return {number} The index of the connection, or -1 if the connection was
* not found.
*/
findConnection(conn: Blockly.Connection): number;
/**
* Finds a candidate position for inserting this connection into the list.
* This will be in the correct y order but makes no guarantees about ordering in
* the x axis.
* @param {!Blockly.Connection} connection The connection to insert.
* @return {number} The candidate index.
* @private
*/
findPositionForConnection_(connection: Blockly.Connection): number;
/**
* Remove a connection from the database. Must already exist in DB.
* @param {!Blockly.Connection} connection The connection to be removed.
* @private
*/
removeConnection_(connection: Blockly.Connection): void;
/**
* Find all nearby connections to the given connection.
* Type checking does not apply, since this function is used for bumping.
* @param {!Blockly.Connection} connection The connection whose neighbours
* should be returned.
* @param {number} maxRadius The maximum radius to another connection.
* @return {!Array.<Blockly.Connection>} List of connections.
*/
getNeighbours(connection: Blockly.Connection, maxRadius: number): Blockly.Connection[];
/**
* Is the candidate connection close to the reference connection.
* Extremely fast; only looks at Y distance.
* @param {number} index Index in database of candidate connection.
* @param {number} baseY Reference connection's Y value.
* @param {number} maxRadius The maximum radius to another connection.
* @return {boolean} True if connection is in range.
* @private
*/
isInYRange_(index: number, baseY: number, maxRadius: number): boolean;
/**
* Find the closest compatible connection to this connection.
* @param {!Blockly.Connection} conn The connection searching for a compatible
* mate.
* @param {number} maxRadius The maximum radius to another connection.
* @param {!goog.math.Coordinate} dxy Offset between this connection's location
* in the database and the current location (as a result of dragging).
* @return {!{connection: ?Blockly.Connection, radius: number}} Contains two
* properties:' connection' which is either another connection or null,
* and 'radius' which is the distance.
*/
searchForClosest(conn: Blockly.Connection, maxRadius: number, dxy: goog.math.Coordinate): { connection: Blockly.Connection; radius: number };
}
}
declare module Blockly {
class Connection extends Connection__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class Connection__Class {
/**
* Class for a connection between blocks.
* @param {!Blockly.Block} source The block establishing this connection.
* @param {number} type The type of the connection.
* @constructor
*/
constructor(source: Blockly.Block, type: number);
/**
* @type {!Blockly.Block}
* @private
*/
sourceBlock_: Blockly.Block;
/** @type {number} */
type: number;
/**
* Connection this connection connects to. Null if not connected.
* @type {Blockly.Connection}
*/
targetConnection: Blockly.Connection;
/**
* List of compatible value types. Null if all types are compatible.
* @type {Array}
* @private
*/
check_: any[];
/**
* DOM representation of a shadow block, or null if none.
* @type {Element}
* @private
*/
shadowDom_: Element;
/**
* Horizontal location of this connection.
* @type {number}
* @private
*/
x_: number;
/**
* Vertical location of this connection.
* @type {number}
* @private
*/
y_: number;
/**
* Has this connection been added to the connection database?
* @type {boolean}
* @private
*/
inDB_: boolean;
/**
* Connection database for connections of this type on the current workspace.
* @type {Blockly.ConnectionDB}
* @private
*/
db_: Blockly.ConnectionDB;
/**
* Connection database for connections compatible with this type on the
* current workspace.
* @type {Blockly.ConnectionDB}
* @private
*/
dbOpposite_: Blockly.ConnectionDB;
/**
* Whether this connections is hidden (not tracked in a database) or not.
* @type {boolean}
* @private
*/
hidden_: boolean;
/**
* Connect two connections together. This is the connection on the superior
* block.
* @param {!Blockly.Connection} childConnection Connection on inferior block.
* @private
*/
connect_(childConnection: Blockly.Connection): void;
/**
* Sever all links to this connection (not including from the source object).
*/
dispose(): void;
/**
* Get the source block for this connection.
* @return {Blockly.Block} The source block, or null if there is none.
*/
getSourceBlock(): Blockly.Block;
/**
* Does the connection belong to a superior block (higher in the source stack)?
* @return {boolean} True if connection faces down or right.
*/
isSuperior(): boolean;
/**
* Is the connection connected?
* @return {boolean} True if connection is connected to another connection.
*/
isConnected(): boolean;
/**
* Checks whether the current connection can connect with the target
* connection.
* @param {Blockly.Connection} target Connection to check compatibility with.
* @return {number} Blockly.Connection.CAN_CONNECT if the connection is legal,
* an error code otherwise.
* @private
*/
canConnectWithReason_(target: Blockly.Connection): number;
/**
* Checks whether the current connection and target connection are compatible
* and throws an exception if they are not.
* @param {Blockly.Connection} target The connection to check compatibility
* with.
* @private
*/
checkConnection_(target: Blockly.Connection): void;
/**
* Check if the two connections can be dragged to connect to each other.
* @param {!Blockly.Connection} candidate A nearby connection to check.
* @return {boolean} True if the connection is allowed, false otherwise.
*/
isConnectionAllowed(candidate: Blockly.Connection): boolean;
/**
* Connect this connection to another connection.
* @param {!Blockly.Connection} otherConnection Connection to connect to.
*/
connect(otherConnection: Blockly.Connection): void;
/**
* Disconnect this connection.
*/
disconnect(): void;
/**
* Disconnect two blocks that are connected by this connection.
* @param {!Blockly.Block} parentBlock The superior block.
* @param {!Blockly.Block} childBlock The inferior block.
* @private
*/
disconnectInternal_(parentBlock: Blockly.Block, childBlock: Blockly.Block): void;
/**
* Respawn the shadow block if there was one connected to the this connection.
* @private
*/
respawnShadow_(): void;
/**
* Returns the block that this connection connects to.
* @return {Blockly.Block} The connected block or null if none is connected.
*/
targetBlock(): Blockly.Block;
/**
* Is this connection compatible with another connection with respect to the
* value type system. E.g. square_root("Hello") is not compatible.
* @param {!Blockly.Connection} otherConnection Connection to compare against.
* @return {boolean} True if the connections share a type.
* @private
*/
checkType_(otherConnection: Blockly.Connection): boolean;
/**
* Change a connection's compatibility.
* @param {*} check Compatible value type or list of value types.
* Null if all types are compatible.
* @return {!Blockly.Connection} The connection being modified
* (to allow chaining).
*/
setCheck(check: any): Blockly.Connection;
/**
* Change a connection's shadow block.
* @param {Element} shadow DOM representation of a block or null.
*/
setShadowDom(shadow: Element): void;
/**
* Return a connection's shadow block.
* @return {Element} shadow DOM representation of a block or null.
*/
getShadowDom(): Element;
}
}
declare module Blockly {
/**
* Number of pixels the mouse must move before a drag starts.
*/
var DRAG_RADIUS: any /*missing*/;
/**
* Maximum misalignment between connections for them to snap together.
*/
var SNAP_RADIUS: any /*missing*/;
/**
* Delay in ms between trigger and bumping unconnected block out of alignment.
*/
var BUMP_DELAY: any /*missing*/;
/**
* Number of characters to truncate a collapsed block to.
*/
var COLLAPSE_CHARS: any /*missing*/;
/**
* Length in ms for a touch to become a long press.
*/
var LONGPRESS: any /*missing*/;
/**
* Prevent a sound from playing if another sound preceded it within this many
* miliseconds.
*/
var SOUND_LIMIT: any /*missing*/;
/**
* The richness of block colours, regardless of the hue.
* Must be in the range of 0 (inclusive) to 1 (exclusive).
*/
var HSV_SATURATION: any /*missing*/;
/**
* The intensity of block colours, regardless of the hue.
* Must be in the range of 0 (inclusive) to 1 (exclusive).
*/
var HSV_VALUE: any /*missing*/;
/**
* Sprited icons and images.
*/
var SPRITE: any /*missing*/;
/**
* Required name space for SVG elements.
* @const
*/
var SVG_NS: any /*missing*/;
/**
* Required name space for HTML elements.
* @const
*/
var HTML_NS: any /*missing*/;
/**
* ENUM for a right-facing value input. E.g. 'set item to' or 'return'.
* @const
*/
var INPUT_VALUE: any /*missing*/;
/**
* ENUM for a left-facing value output. E.g. 'random fraction'.
* @const
*/
var OUTPUT_VALUE: any /*missing*/;
/**
* ENUM for a down-facing block stack. E.g. 'if-do' or 'else'.
* @const
*/
var NEXT_STATEMENT: any /*missing*/;
/**
* ENUM for an up-facing block stack. E.g. 'break out of loop'.
* @const
*/
var PREVIOUS_STATEMENT: any /*missing*/;
/**
* ENUM for an dummy input. Used to add field(s) with no input.
* @const
*/
var DUMMY_INPUT: any /*missing*/;
/**
* ENUM for left alignment.
* @const
*/
var ALIGN_LEFT: any /*missing*/;
/**
* ENUM for centre alignment.
* @const
*/
var ALIGN_CENTRE: any /*missing*/;
/**
* ENUM for right alignment.
* @const
*/
var ALIGN_RIGHT: any /*missing*/;
/**
* ENUM for no drag operation.
* @const
*/
var DRAG_NONE: any /*missing*/;
/**
* ENUM for inside the sticky DRAG_RADIUS.
* @const
*/
var DRAG_STICKY: any /*missing*/;
/**
* ENUM for inside the non-sticky DRAG_RADIUS, for differentiating between
* clicks and drags.
* @const
*/
var DRAG_BEGIN: any /*missing*/;
/**
* ENUM for freely draggable (outside the DRAG_RADIUS, if one applies).
* @const
*/
var DRAG_FREE: any /*missing*/;
/**
* Lookup table for determining the opposite type of a connection.
* @const
*/
var OPPOSITE_TYPE: any /*missing*/;
/**
* ENUM for toolbox and flyout at top of screen.
* @const
*/
var TOOLBOX_AT_TOP: any /*missing*/;
/**
* ENUM for toolbox and flyout at bottom of screen.
* @const
*/
var TOOLBOX_AT_BOTTOM: any /*missing*/;
/**
* ENUM for toolbox and flyout at left of screen.
* @const
*/
var TOOLBOX_AT_LEFT: any /*missing*/;
/**
* ENUM for toolbox and flyout at right of screen.
* @const
*/
var TOOLBOX_AT_RIGHT: any /*missing*/;
}
declare module Blockly {
class FieldAngle extends FieldAngle__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class FieldAngle__Class extends Blockly.FieldTextInput__Class {
/**
* Class for an editable angle field.
* @param {string} text The initial content of the field.
* @param {Function=} opt_validator An optional function that is called
* to validate any constraints on what the user entered. Takes the new
* text as an argument and returns the accepted text or null to abort
* the change.
* @extends {Blockly.FieldTextInput}
* @constructor
*/
constructor(text: string, opt_validator?: Function);
/**
* Clean up this FieldAngle, as well as the inherited FieldTextInput.
* @return {!Function} Closure to call on destruction of the WidgetDiv.
* @private
*/
dispose_(): Function;
/**
* Show the inline free-text editor on top of the text.
* @private
*/
showEditor_(): void;
/**
* Set the angle to match the mouse's position.
* @param {!Event} e Mouse move event.
*/
onMouseMove(e: Event): void;
/**
* Insert a degree symbol.
* @param {?string} text New text.
*/
setText(text: string): void;
/**
* Redraw the graph with the current angle.
* @private
*/
updateGraph_(): void;
/**
* Ensure that only an angle may be entered.
* @param {string} text The user's text.
* @return {?string} A string representing a valid angle, or null if invalid.
*/
classValidator(text: string): string;
}
}
declare module Blockly {
class FieldCheckbox extends FieldCheckbox__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class FieldCheckbox__Class extends Blockly.Field__Class {
/**
* Class for a checkbox field.
* @param {string} state The initial state of the field ('TRUE' or 'FALSE').
* @param {Function=} opt_validator A function that is executed when a new
* option is selected. Its sole argument is the new checkbox state. If
* it returns a value, this becomes the new checkbox state, unless the
* value is null, in which case the change is aborted.
* @extends {Blockly.Field}
* @constructor
*/
constructor(state: string, opt_validator?: Function);
/**
* Mouse cursor style when over the hotspot that initiates editability.
*/
CURSOR: any /*missing*/;
/**
* Install this checkbox on a block.
*/
init(): void;
/**
* Return 'TRUE' if the checkbox is checked, 'FALSE' otherwise.
* @return {string} Current state.
*/
getValue(): string;
/**
* Set the checkbox to be checked if strBool is 'TRUE', unchecks otherwise.
* @param {string} strBool New state.
*/
setValue(strBool: string): void;
/**
* Toggle the state of the checkbox.
* @private
*/
showEditor_(): void;
}
}
declare module Blockly {
class FieldImage extends FieldImage__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class FieldImage__Class extends Blockly.Field__Class {
/**
* Class for an image.
* @param {string} src The URL of the image.
* @param {number} width Width of the image.
* @param {number} height Height of the image.
* @param {string=} opt_alt Optional alt text for when block is collapsed.
* @extends {Blockly.Field}
* @constructor
*/
constructor(src: string, width: number, height: number, opt_alt?: string);
/**
* Due to a Firefox bug which eats mouse events on image elements,
* a transparent rectangle needs to be placed on top of the image.
* @type {SVGElement}
*/
rectElement_: SVGElement;
/**
* Editable fields are saved by the XML renderer, non-editable fields are not.
*/
EDITABLE: any /*missing*/;
/**
* Install this image on a block.
*/
init(): void;
/** @type {SVGElement} */
fieldGroup_: SVGElement;
/** @type {SVGElement} */
imageElement_: SVGElement;
/**
* Dispose of all DOM objects belonging to this text.
*/
dispose(): void;
/**
* Change the tooltip text for this field.
* @param {string|!Element} newTip Text for tooltip or a parent element to
* link to for its tooltip.
*/
setTooltip(newTip: string|Element): void;
/**
* Images are fixed width, no need to render.
* @private
*/
render_(): void;
}
}
declare module Blockly {
class FieldLabel extends FieldLabel__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class FieldLabel__Class extends Blockly.Field__Class {
/**
* Class for a non-editable field.
* @param {string} text The initial content of the field.
* @param {string=} opt_class Optional CSS class for the field's text.
* @extends {Blockly.Field}
* @constructor
*/
constructor(text: string, opt_class?: string);
/**
* Editable fields are saved by the XML renderer, non-editable fields are not.
*/
EDITABLE: any /*missing*/;
/**
* Install this text on a block.
*/
init(): void;
/**
* Dispose of all DOM objects belonging to this text.
*/
dispose(): void;
/**
* Gets the group element for this field.
* Used for measuring the size and for positioning.
* @return {!Element} The group element.
*/
getSvgRoot(): Element;
/**
* Change the tooltip text for this field.
* @param {string|!Element} newTip Text for tooltip or a parent element to
* link to for its tooltip.
*/
setTooltip(newTip: string|Element): void;
}
}
declare module Blockly {
class FieldNumber extends FieldNumber__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class FieldNumber__Class extends Blockly.FieldTextInput__Class {
/**
* Class for an editable number field.
* @param {number|string} value The initial content of the field.
* @param {number|string|undefined} opt_min Minimum value.
* @param {number|string|undefined} opt_max Maximum value.
* @param {number|string|undefined} opt_precision Precision for value.
* @param {Function=} opt_validator An optional function that is called
* to validate any constraints on what the user entered. Takes the new
* text as an argument and returns either the accepted text, a replacement
* text, or null to abort the change.
* @extends {Blockly.FieldTextInput}
* @constructor
*/
constructor(value: number|string, opt_min: number|string|any /*undefined*/, opt_max: number|string|any /*undefined*/, opt_precision: number|string|any /*undefined*/, opt_validator?: Function);
/**
* Set the maximum, minimum and precision constraints on this field.
* Any of these properties may be undefiend or NaN to be disabled.
* Setting precision (usually a power of 10) enforces a minimum step between
* values. That is, the user's value will rounded to the closest multiple of
* precision. The least significant digit place is inferred from the precision.
* Integers values can be enforces by choosing an integer precision.
* @param {number|string|undefined} min Minimum value.
* @param {number|string|undefined} max Maximum value.
* @param {number|string|undefined} precision Precision for value.
*/
setConstraints(min: number|string|any /*undefined*/, max: number|string|any /*undefined*/, precision: number|string|any /*undefined*/): void;
/**
* Ensure that only a number in the correct range may be entered.
* @param {string} text The user's text.
* @return {?string} A string representing a valid number, or null if invalid.
*/
classValidator(text: string): string;
}
}
declare module Blockly {
class FieldTextInput extends FieldTextInput__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class FieldTextInput__Class extends Blockly.Field__Class {
/**
* Class for an editable text field.
* @param {string} text The initial content of the field.
* @param {Function=} opt_validator An optional function that is called
* to validate any constraints on what the user entered. Takes the new
* text as an argument and returns either the accepted text, a replacement
* text, or null to abort the change.
* @extends {Blockly.Field}
* @constructor
*/
constructor(text: string, opt_validator?: Function);
/**
* Mouse cursor style when over the hotspot that initiates the editor.
*/
CURSOR: any /*missing*/;
/**
* Allow browser to spellcheck this field.
* @private
*/
spellcheck_: any /*missing*/;
/**
* Close the input widget if this input is being deleted.
*/
dispose(): void;
/**
* Set whether this field is spellchecked by the browser.
* @param {boolean} check True if checked.
*/
setSpellcheck(check: boolean): void;
/**
* Show the inline free-text editor on top of the text.
* @param {boolean=} opt_quietInput True if editor should be created without
* focus. Defaults to false.
* @private
*/
showEditor_(opt_quietInput?: boolean): void;
/**
* Handle key down to the editor.
* @param {!Event} e Keyboard event.
* @private
*/
onHtmlInputKeyDown_(e: Event): void;
/**
* Handle a change to the editor.
* @param {!Event} e Keyboard event.
* @private
*/
onHtmlInputChange_(e: Event): void;
/**
* Check to see if the contents of the editor validates.
* Style the editor accordingly.
* @private
*/
validate_(): void;
/**
* Resize the editor and the underlying block to fit the text.
* @private
*/
resizeEditor_(): void;
/**
* Close the editor, save the results, and dispose of the editable
* text field's elements.
* @return {!Function} Closure to call on destruction of the WidgetDiv.
* @private
*/
widgetDispose_(): Function;
}
}
declare module Blockly {
/**
* PID of queued long-press task.
* @private
*/
var longPid_: any /*missing*/;
/**
* Context menus on touch devices are activated using a long-press.
* Unfortunately the contextmenu touch event is currently (2015) only suported
* by Chrome. This function is fired on any touchstart event, queues a task,
* which after about a second opens the context menu. The tasks is killed
* if the touch event terminates early.
* @param {!Event} e Touch start event.
* @param {!Blockly.Block|!Blockly.WorkspaceSvg} uiObject The block or workspace
* under the touchstart event.
* @private
*/
function longStart_(e: Event, uiObject: Blockly.Block|Blockly.WorkspaceSvg): void;
/**
* Nope, that's not a long-press. Either touchend or touchcancel was fired,
* or a drag hath begun. Kill the queued long-press task.
* @private
*/
function longStop_(): void;
/**
* Handle a mouse-up anywhere on the page.
* @param {!Event} e Mouse up event.
* @private
*/
function onMouseUp_(e: Event): void;
/**
* Handle a mouse-move on SVG drawing surface.
* @param {!Event} e Mouse move event.
* @private
*/
function onMouseMove_(e: Event): void;
}
declare module Blockly {
class Trashcan extends Trashcan__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class Trashcan__Class {
/**
* Class for a trash can.
* @param {!Blockly.Workspace} workspace The workspace to sit in.
* @constructor
*/
constructor(workspace: Blockly.Workspace);
/**
* Width of both the trash can and lid images.
* @type {number}
* @private
*/
WIDTH_: number;
/**
* Height of the trashcan image (minus lid).
* @type {number}
* @private
*/
BODY_HEIGHT_: number;
/**
* Height of the lid image.
* @type {number}
* @private
*/
LID_HEIGHT_: number;
/**
* Distance between trashcan and bottom edge of workspace.
* @type {number}
* @private
*/
MARGIN_BOTTOM_: number;
/**
* Distance between trashcan and right edge of workspace.
* @type {number}
* @private
*/
MARGIN_SIDE_: number;
/**
* Extent of hotspot on all sides beyond the size of the image.
* @type {number}
* @private
*/
MARGIN_HOTSPOT_: number;
/**
* Location of trashcan in sprite image.
* @type {number}
* @private
*/
SPRITE_LEFT_: number;
/**
* Location of trashcan in sprite image.
* @type {number}
* @private
*/
SPRITE_TOP_: number;
/**
* Current open/close state of the lid.
* @type {boolean}
*/
isOpen: boolean;
/**
* The SVG group containing the trash can.
* @type {Element}
* @private
*/
svgGroup_: Element;
/**
* The SVG image element of the trash can lid.
* @type {Element}
* @private
*/
svgLid_: Element;
/**
* Task ID of opening/closing animation.
* @type {number}
* @private
*/
lidTask_: number;
/**
* Current state of lid opening (0.0 = closed, 1.0 = open).
* @type {number}
* @private
*/
lidOpen_: number;
/**
* Left coordinate of the trash can.
* @type {number}
* @private
*/
left_: number;
/**
* Top coordinate of the trash can.
* @type {number}
* @private
*/
top_: number;
/**
* Create the trash can elements.
* @return {!Element} The trash can's SVG group.
*/
createDom(): Element;
/**
* Initialize the trash can.
* @param {number} bottom Distance from workspace bottom to bottom of trashcan.
* @return {number} Distance from workspace bottom to the top of trashcan.
*/
init(bottom: number): number;
/**
* Dispose of this trash can.
* Unlink from all DOM elements to prevent memory leaks.
*/
dispose(): void;
/**
* Move the trash can to the bottom-right corner.
*/
position(): void;
/**
* Return the deletion rectangle for this trash can.
* @return {goog.math.Rect} Rectangle in which to delete.
*/
getClientRect(): goog.math.Rect;
/**
* Flip the lid open or shut.
* @param {boolean} state True if open.
* @private
*/
setOpen_(state: boolean): void;
/**
* Rotate the lid open or closed by one step. Then wait and recurse.
* @private
*/
animateLid_(): void;
/**
* Flip the lid shut.
* Called externally after a drag.
*/
close(): void;
/**
* Inspect the contents of the trash.
*/
click(): void;
}
}
declare module Blockly {
/**
* Add a CSS class to a element.
* Similar to Closure's goog.dom.classes.add, except it handles SVG elements.
* @param {!Element} element DOM element to add class to.
* @param {string} className Name of class to add.
* @private
*/
function addClass_(element: Element, className: string): void;
/**
* Remove a CSS class from a element.
* Similar to Closure's goog.dom.classes.remove, except it handles SVG elements.
* @param {!Element} element DOM element to remove class from.
* @param {string} className Name of class to remove.
* @private
*/
function removeClass_(element: Element, className: string): void;
/**
* Checks if an element has the specified CSS class.
* Similar to Closure's goog.dom.classes.has, except it handles SVG elements.
* @param {!Element} element DOM element to check.
* @param {string} className Name of class to check.
* @return {boolean} True if class exists, false otherwise.
* @private
*/
function hasClass_(element: Element, className: string): boolean;
/**
* Bind an event to a function call. When calling the function, verifies that
* it belongs to the touch stream that is currently being processsed, and splits
* multitouch events into multiple events as needed.
* @param {!Node} node Node upon which to listen.
* @param {string} name Event name to listen to (e.g. 'mousedown').
* @param {Object} thisObject The value of 'this' in the function.
* @param {!Function} func Function to call when event is triggered.
* @param {boolean} opt_noCaptureIdentifier True if triggering on this event
* should not block execution of other event handlers on this touch or other
* simultaneous touches.
* @return {!Array.<!Array>} Opaque data that can be passed to unbindEvent_.
* @private
*/
function bindEventWithChecks_(node: Node, name: string, thisObject: Object, func: Function, opt_noCaptureIdentifier: boolean): any[][];
/**
* Bind an event to a function call. Handles multitouch events by using the
* coordinates of the first changed touch, and doesn't do any safety checks for
* simultaneous event processing.
* @deprecated in favor of bindEventWithChecks_, but preserved for external
* users.
* @param {!Node} node Node upon which to listen.
* @param {string} name Event name to listen to (e.g. 'mousedown').
* @param {Object} thisObject The value of 'this' in the function.
* @param {!Function} func Function to call when event is triggered.
* @return {!Array.<!Array>} Opaque data that can be passed to unbindEvent_.
* @private
*/
function bindEvent_(node: Node, name: string, thisObject: Object, func: Function): any[][];
/**
* Unbind one or more events event from a function call.
* @param {!Array.<!Array>} bindData Opaque data from bindEvent_. This list is
* emptied during the course of calling this function.
* @return {!Function} The function call.
* @private
*/
function unbindEvent_(bindData: any[][]): Function;
/**
* Don't do anything for this event, just halt propagation.
* @param {!Event} e An event.
*/
function noEvent(e: Event): void;
/**
* Is this event targeting a text input widget?
* @param {!Event} e An event.
* @return {boolean} True if text input.
* @private
*/
function isTargetInput_(e: Event): boolean;
/**
* Return the coordinates of the top-left corner of this element relative to
* its parent. Only for SVG elements and children (e.g. rect, g, path).
* @param {!Element} element SVG element to find the coordinates of.
* @return {!goog.math.Coordinate} Object with .x and .y properties.
* @private
*/
function getRelativeXY_(element: Element): goog.math.Coordinate;
/**
* Return the absolute coordinates of the top-left corner of this element,
* scales that after canvas SVG element, if it's a descendant.
* The origin (0,0) is the top-left corner of the Blockly SVG.
* @param {!Element} element Element to find the coordinates of.
* @param {!Blockly.Workspace} workspace Element must be in this workspace.
* @return {!goog.math.Coordinate} Object with .x and .y properties.
* @private
*/
function getSvgXY_(element: Element, workspace: Blockly.Workspace): goog.math.Coordinate;
/**
* Helper method for creating SVG elements.
* @param {string} name Element's tag name.
* @param {!Object} attrs Dictionary of attribute names and values.
* @param {Element} parent Optional parent on which to append the element.
* @param {Blockly.Workspace=} opt_workspace Optional workspace for access to
* context (scale...).
* @return {!SVGElement} Newly created SVG element.
*/
function createSvgElement(name: string, attrs: Object, parent: Element, opt_workspace?: Blockly.Workspace): SVGElement;
/**
* Is this event a right-click?
* @param {!Event} e Mouse event.
* @return {boolean} True if right-click.
*/
function isRightButton(e: Event): boolean;
/**
* Return the converted coordinates of the given mouse event.
* The origin (0,0) is the top-left corner of the Blockly svg.
* @param {!Event} e Mouse event.
* @param {!Element} svg SVG element.
* @param {SVGMatrix} matrix Inverted screen CTM to use.
* @return {!Object} Object with .x and .y properties.
*/
function mouseToSvg(e: Event, svg: Element, matrix: SVGMatrix): Object;
/**
* Given an array of strings, return the length of the shortest one.
* @param {!Array.<string>} array Array of strings.
* @return {number} Length of shortest string.
*/
function shortestStringLength(array: string[]): number;
/**
* Given an array of strings, return the length of the common prefix.
* Words may not be split. Any space after a word is included in the length.
* @param {!Array.<string>} array Array of strings.
* @param {number=} opt_shortest Length of shortest string.
* @return {number} Length of common prefix.
*/
function commonWordPrefix(array: string[], opt_shortest?: number): number;
/**
* Given an array of strings, return the length of the common suffix.
* Words may not be split. Any space after a word is included in the length.
* @param {!Array.<string>} array Array of strings.
* @param {number=} opt_shortest Length of shortest string.
* @return {number} Length of common suffix.
*/
function commonWordSuffix(array: string[], opt_shortest?: number): number;
/**
* Is the given string a number (includes negative and decimals).
* @param {string} str Input string.
* @return {boolean} True if number, false otherwise.
*/
function isNumber(str: string): boolean;
/**
* Generate a unique ID. This should be globally unique.
* 87 characters ^ 20 length > 128 bits (better than a UUID).
* @return {string} A globally unique ID string.
*/
function genUid(): string;
}
declare module Blockly {
class FieldColour extends FieldColour__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class FieldColour__Class extends Blockly.Field__Class {
/**
* Class for a colour input field.
* @param {string} colour The initial colour in '#rrggbb' format.
* @param {Function=} opt_validator A function that is executed when a new
* colour is selected. Its sole argument is the new colour value. Its
* return value becomes the selected colour, unless it is undefined, in
* which case the new colour stands, or it is null, in which case the change
* is aborted.
* @extends {Blockly.Field}
* @constructor
*/
constructor(colour: string, opt_validator?: Function);
/**
* By default use the global constants for colours.
* @type {Array.<string>}
* @private
*/
colours_: string[];
/**
* By default use the global constants for columns.
* @type {number}
* @private
*/
columns_: number;
/**
* Install this field on a block.
*/
init(): void;
/**
* Mouse cursor style when over the hotspot that initiates the editor.
*/
CURSOR: any /*missing*/;
/**
* Close the colour picker if this input is being deleted.
*/
dispose(): void;
/**
* Return the current colour.
* @return {string} Current colour in '#rrggbb' format.
*/
getValue(): string;
/**
* Set the colour.
* @param {string} colour The new colour in '#rrggbb' format.
*/
setValue(colour: string): void;
/**
* Get the text from this field. Used when the block is collapsed.
* @return {string} Current text.
*/
getText(): string;
/**
* Set a custom colour grid for this field.
* @param {Array.<string>} colours Array of colours for this block,
* or null to use default (Blockly.FieldColour.COLOURS).
* @return {!Blockly.FieldColour} Returns itself (for method chaining).
*/
setColours(colours: string[]): Blockly.FieldColour;
/**
* Set a custom grid size for this field.
* @param {number} columns Number of columns for this block,
* or 0 to use default (Blockly.FieldColour.COLUMNS).
* @return {!Blockly.FieldColour} Returns itself (for method chaining).
*/
setColumns(columns: number): Blockly.FieldColour;
/**
* Create a palette under the colour field.
* @private
*/
showEditor_(): void;
}
}
declare module Blockly {
class FieldDate extends FieldDate__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class FieldDate__Class extends Blockly.Field__Class {
/**
* Class for a date input field.
* @param {string} date The initial date.
* @param {Function=} opt_validator A function that is executed when a new
* date is selected. Its sole argument is the new date value. Its
* return value becomes the selected date, unless it is undefined, in
* which case the new date stands, or it is null, in which case the change
* is aborted.
* @extends {Blockly.Field}
* @constructor
*/
constructor(date: string, opt_validator?: Function);
/**
* Mouse cursor style when over the hotspot that initiates the editor.
*/
CURSOR: any /*missing*/;
/**
* Close the colour picker if this input is being deleted.
*/
dispose(): void;
/**
* Return the current date.
* @return {string} Current date.
*/
getValue(): string;
/**
* Set the date.
* @param {string} date The new date.
*/
setValue(date: string): void;
/**
* Create a date picker under the date field.
* @private
*/
showEditor_(): void;
}
}
declare module Blockly {
class FieldDropdown extends FieldDropdown__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class FieldDropdown__Class extends Blockly.Field__Class {
/**
* Class for an editable dropdown field.
* @param {(!Array.<!Array.<string>>|!Function)} menuGenerator An array of
* options for a dropdown list, or a function which generates these options.
* @param {Function=} opt_validator A function that is executed when a new
* option is selected, with the newly selected value as its sole argument.
* If it returns a value, that value (which must be one of the options) will
* become selected in place of the newly selected option, unless the return
* value is null, in which case the change is aborted.
* @extends {Blockly.Field}
* @constructor
*/
constructor(menuGenerator: string[][]|Function, opt_validator?: Function);
/**
* Mouse cursor style when over the hotspot that initiates the editor.
*/
CURSOR: any /*missing*/;
/**
* Install this dropdown on a block.
*/
init(): void;
/**
* Create a dropdown menu under the text.
* @private
*/
showEditor_(): void;
/**
* Factor out common words in statically defined options.
* Create prefix and/or suffix labels.
* @private
*/
trimOptions_(): void;
/**
* Return a list of the options for this dropdown.
* @return {!Array.<!Array.<string>>} Array of option tuples:
* (human-readable text, language-neutral name).
* @private
*/
getOptions_(): string[][];
/**
* Get the language-neutral value from this dropdown menu.
* @return {string} Current text.
*/
getValue(): string;
/**
* Set the language-neutral value for this dropdown menu.
* @param {string} newValue New value to set.
*/
setValue(newValue: string): void;
/**
* Set the text in this field. Trigger a rerender of the source block.
* @param {?string} text New text.
*/
setText(text: string): void;
/**
* Close the dropdown menu if this input is being deleted.
*/
dispose(): void;
}
}
declare module Blockly {
class Input extends Input__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class Input__Class {
/**
* Class for an input with an optional field.
* @param {number} type The type of the input.
* @param {string} name Language-neutral identifier which may used to find this
* input again.
* @param {!Blockly.Block} block The block containing this input.
* @param {Blockly.Connection} connection Optional connection for this input.
* @constructor
*/
constructor(type: number, name: string, block: Blockly.Block, connection: Blockly.Connection);
/** @type {number} */
type: number;
/** @type {string} */
name: string;
/**
* @type {!Blockly.Block}
* @private
*/
sourceBlock_: Blockly.Block;
/** @type {Blockly.Connection} */
connection: Blockly.Connection;
/** @type {!Array.<!Blockly.Field>} */
fieldRow: Blockly.Field[];
/**
* Alignment of input's fields (left, right or centre).
* @type {number}
*/
align: number;
/**
* Is the input visible?
* @type {boolean}
* @private
*/
visible_: boolean;
/**
* Add an item to the end of the input's field row.
* @param {string|!Blockly.Field} field Something to add as a field.
* @param {string=} opt_name Language-neutral identifier which may used to find
* this field again. Should be unique to the host block.
* @return {!Blockly.Input} The input being append to (to allow chaining).
*/
appendField(field: string|Blockly.Field, opt_name?: string): Blockly.Input;
/**
* Add an item to the end of the input's field row.
* @param {*} field Something to add as a field.
* @param {string=} opt_name Language-neutral identifier which may used to find
* this field again. Should be unique to the host block.
* @return {!Blockly.Input} The input being append to (to allow chaining).
* @deprecated December 2013
*/
appendTitle(field: any, opt_name?: string): Blockly.Input;
/**
* Remove a field from this input.
* @param {string} name The name of the field.
* @throws {goog.asserts.AssertionError} if the field is not present.
*/
removeField(name: string): void;
/**
* Gets whether this input is visible or not.
* @return {boolean} True if visible.
*/
isVisible(): boolean;
/**
* Sets whether this input is visible or not.
* Used to collapse/uncollapse a block.
* @param {boolean} visible True if visible.
* @return {!Array.<!Blockly.Block>} List of blocks to render.
*/
setVisible(visible: boolean): Blockly.Block[];
/**
* Change a connection's compatibility.
* @param {string|Array.<string>|null} check Compatible value type or
* list of value types. Null if all types are compatible.
* @return {!Blockly.Input} The input being modified (to allow chaining).
*/
setCheck(check: string|string[]|any /*null*/): Blockly.Input;
/**
* Change the alignment of the connection's field(s).
* @param {number} align One of Blockly.ALIGN_LEFT, ALIGN_CENTRE, ALIGN_RIGHT.
* In RTL mode directions are reversed, and ALIGN_RIGHT aligns to the left.
* @return {!Blockly.Input} The input being modified (to allow chaining).
*/
setAlign(align: number): Blockly.Input;
/**
* Initialize the fields on this input.
*/
init(): void;
/**
* Sever all links to this input.
*/
dispose(): void;
}
}
declare module Blockly {
class Field extends Field__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class Field__Class {
/**
* Abstract class for an editable field.
* @param {string} text The initial content of the field.
* @param {Function=} opt_validator An optional function that is called
* to validate any constraints on what the user entered. Takes the new
* text as an argument and returns either the accepted text, a replacement
* text, or null to abort the change.
* @constructor
*/
constructor(text: string, opt_validator?: Function);
/**
* Name of field. Unique within each block.
* Static labels are usually unnamed.
* @type {string=}
*/
name: any /*missing*/;
/**
* Maximum characters of text to display before adding an ellipsis.
* @type {number}
*/
maxDisplayLength: number;
/**
* Visible text to display.
* @type {string}
* @private
*/
text_: string;
value_: string;
/**
* Block this field is attached to. Starts as null, then in set in init.
* @type {Blockly.Block}
* @private
*/
public sourceBlock_: Blockly.Block;
/**
* Is the field visible, or hidden due to the block being collapsed?
* @type {boolean}
* @private
*/
visible_: boolean;
/**
* Validation function called when user edits an editable field.
* @type {Function}
* @private
*/
validator_: Function;
/**
* Editable fields are saved by the XML renderer, non-editable fields are not.
*/
EDITABLE: any /*missing*/;
/**
* Attach this field to a block.
* @param {!Blockly.Block} block The block containing this field.
*/
setSourceBlock(block: Blockly.Block): void;
/**
* Install this field on a block.
*/
init(): void;
/** @type {!Element} */
textElement_: Element;
/**
* Dispose of all DOM objects belonging to this editable field.
*/
dispose(): void;
/**
* Add or remove the UI indicating if this field is editable or not.
*/
updateEditable(): void;
/**
* Gets whether this editable field is visible or not.
* @return {boolean} True if visible.
*/
isVisible(): boolean;
/**
* Sets whether this editable field is visible or not.
* @param {boolean} visible True if visible.
*/
setVisible(visible: boolean): void;
/**
* Sets a new validation function for editable fields.
* @param {Function} handler New validation function, or null.
*/
setValidator(handler: Function): void;
/**
* Gets the validation function for editable fields.
* @return {Function} Validation function, or null.
*/
getValidator(): Function;
/**
* Validates a change. Does nothing. Subclasses may override this.
* @param {string} text The user's text.
* @return {string} No change needed.
*/
classValidator(text: string): string;
/**
* Calls the validation function for this field, as well as all the validation
* function for the field's class and its parents.
* @param {string} text Proposed text.
* @return {?string} Revised text, or null if invalid.
*/
callValidator(text: string): string;
/**
* Gets the group element for this editable field.
* Used for measuring the size and for positioning.
* @return {!Element} The group element.
*/
getSvgRoot(): Element;
/**
* Draws the border with the correct width.
* Saves the computed width in a property.
* @private
*/
render_(): void;
/**
* Returns the height and width of the field.
* @return {!goog.math.Size} Height and width.
*/
getSize(): goog.math.Size;
/**
* Returns the height and width of the field,
* accounting for the workspace scaling.
* @return {!goog.math.Size} Height and width.
* @private
*/
getScaledBBox_(): goog.math.Size;
/**
* Get the text from this field.
* @return {string} Current text.
*/
getText(): string;
/**
* Set the text in this field. Trigger a rerender of the source block.
* @param {*} text New text.
*/
setText(text: any): void;
/**
* Update the text node of this field to display the current text.
* @private
*/
updateTextNode_(): void;
/**
* By default there is no difference between the human-readable text and
* the language-neutral values. Subclasses (such as dropdown) may define this.
* @return {string} Current text.
*/
getValue(): string;
/**
* By default there is no difference between the human-readable text and
* the language-neutral values. Subclasses (such as dropdown) may define this.
* @param {string} newText New text.
*/
setValue(newText: string): void;
/**
* Handle a mouse up event on an editable field.
* @param {!Event} e Mouse up event.
* @private
*/
onMouseUp_(e: Event): void;
/**
* Change the tooltip text for this field.
* @param {string|!Element} newTip Text for tooltip or a parent element to
* link to for its tooltip.
*/
setTooltip(newTip: string|Element): void;
/**
* Return the absolute coordinates of the top-left corner of this field.
* The origin (0,0) is the top-left corner of the page body.
* @return {!goog.math.Coordinate} Object with .x and .y properties.
* @private
*/
getAbsoluteXY_(): goog.math.Coordinate;
}
interface BlockDefinition {
codeCard?: any;
init: () => void;
getVars?: () => any[];
renameVar?: (oldName: string, newName: string) => void;
customContextMenu?: any;
mutationToDom?: () => any;
domToMutation?: (xmlElement: any) => void;
}
const Blocks: {
[index: string]: BlockDefinition;
}
}
declare module Blockly {
class FieldVariable extends FieldVariable__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class FieldVariable__Class extends Blockly.FieldDropdown__Class {
/**
* Class for a variable's dropdown field.
* @param {?string} varname The default name for the variable. If null,
* a unique variable name will be generated.
* @param {Function=} opt_validator A function that is executed when a new
* option is selected. Its sole argument is the new option value.
* @extends {Blockly.FieldDropdown}
* @constructor
*/
constructor(varname: string, opt_validator?: Function);
/**
* Install this dropdown on a block.
*/
init(): void;
/**
* Get the variable's name (use a variableDB to convert into a real name).
* Unline a regular dropdown, variables are literal and have no neutral value.
* @return {string} Current text.
*/
getValue(): string;
/**
* Set the variable name.
* @param {string} newValue New text.
*/
setValue(newValue: string): void;
/**
* Event handler for a change in variable name.
* Special case the 'Rename variable...' and 'Delete variable...' options.
* In the rename case, prompt the user for a new name.
* @param {string} text The selected dropdown menu option.
* @return {null|undefined|string} An acceptable new variable name, or null if
* change is to be either aborted (cancel button) or has been already
* handled (rename), or undefined if an existing variable was chosen.
*/
classValidator(text: string): any /*null*/|any /*undefined*/|string;
}
}
declare module Blockly {
class FlyoutButton extends FlyoutButton__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class FlyoutButton__Class {
/**
* Class for a button in the flyout.
* @param {!Blockly.Workspace} workspace The workspace in which to place this
* button.
* @param {!Blockly.Workspace} targetWorkspace The flyout's target workspace.
* @param {string} text The text to display on the button.
* @constructor
*/
constructor(workspace: Blockly.Workspace, targetWorkspace: Blockly.Workspace, text: string);
/**
* @type {!Blockly.Workspace}
* @private
*/
workspace_: Blockly.Workspace;
/**
* @type {!Blockly.Workspace}
* @private
*/
targetWorkspace_: Blockly.Workspace;
/**
* @type {string}
* @private
*/
text_: string;
/**
* @type {!goog.math.Coordinate}
* @private
*/
position_: goog.math.Coordinate;
/**
* The width of the button's rect.
* @type {number}
*/
width: number;
/**
* The height of the button's rect.
* @type {number}
*/
height: number;
/**
* Create the button elements.
* @return {!Element} The button's SVG group.
*/
createDom(): Element;
/**
* Correctly position the flyout button and make it visible.
*/
show(): void;
/**
* Update svg attributes to match internal state.
* @private
*/
updateTransform_(): void;
/**
* Move the button to the given x, y coordinates.
* @param {number} x The new x coordinate.
* @param {number} y The new y coordinate.
*/
moveTo(x: number, y: number): void;
/**
* Dispose of this button.
*/
dispose(): void;
/**
* Do something when the button is clicked.
* @param {!Event} e Mouse up event.
*/
onMouseUp(e: Event): void;
}
}
declare module Blockly {
class Flyout extends Flyout__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class Flyout__Class {
/**
* Class for a flyout.
* @param {!Object} workspaceOptions Dictionary of options for the workspace.
* @constructor
*/
constructor(workspaceOptions: Object);
/**
* @type {!Blockly.Workspace}
* @private
*/
workspace_: Blockly.Workspace;
/**
* Is RTL vs LTR.
* @type {boolean}
*/
RTL: boolean;
/**
* Flyout should be laid out horizontally vs vertically.
* @type {boolean}
* @private
*/
horizontalLayout_: boolean;
/**
* Position of the toolbox and flyout relative to the workspace.
* @type {number}
* @private
*/
toolboxPosition_: number;
/**
* Opaque data that can be passed to Blockly.unbindEvent_.
* @type {!Array.<!Array>}
* @private
*/
eventWrappers_: any[][];
/**
* List of background buttons that lurk behind each block to catch clicks
* landing in the blocks' lakes and bays.
* @type {!Array.<!Element>}
* @private
*/
backgroundButtons_: Element[];
/**
* List of visible buttons.
* @type {!Array.<!Blockly.FlyoutButton>}
* @private
*/
buttons_: Blockly.FlyoutButton[];
/**
* List of event listeners.
* @type {!Array.<!Array>}
* @private
*/
listeners_: any[][];
/**
* List of blocks that should always be disabled.
* @type {!Array.<!Blockly.Block>}
* @private
*/
permanentlyDisabled_: Blockly.Block[];
/**
* y coordinate of mousedown - used to calculate scroll distances.
* @type {number}
* @private
*/
startDragMouseY_: number;
/**
* x coordinate of mousedown - used to calculate scroll distances.
* @type {number}
* @private
*/
startDragMouseX_: number;
/**
* Does the flyout automatically close when a block is created?
* @type {boolean}
*/
autoClose: boolean;
/**
* Corner radius of the flyout background.
* @type {number}
* @const
*/
CORNER_RADIUS: number;
/**
* Number of pixels the mouse must move before a drag/scroll starts. Because the
* drag-intention is determined when this is reached, it is larger than
* Blockly.DRAG_RADIUS so that the drag-direction is clearer.
*/
DRAG_RADIUS: any /*missing*/;
/**
* Margin around the edges of the blocks in the flyout.
* @type {number}
* @const
*/
MARGIN: number;
/**
* Gap between items in horizontal flyouts. Can be overridden with the "sep"
* element.
* @const {number}
*/
GAP_X: any /*missing*/;
/**
* Gap between items in vertical flyouts. Can be overridden with the "sep"
* element.
* @const {number}
*/
GAP_Y: any /*missing*/;
/**
* Top/bottom padding between scrollbar and edge of flyout background.
* @type {number}
* @const
*/
SCROLLBAR_PADDING: number;
/**
* Width of flyout.
* @type {number}
* @private
*/
width_: number;
/**
* Height of flyout.
* @type {number}
* @private
*/
height_: number;
/**
* Is the flyout dragging (scrolling)?
* DRAG_NONE - no drag is ongoing or state is undetermined.
* DRAG_STICKY - still within the sticky drag radius.
* DRAG_FREE - in scroll mode (never create a new block).
* @private
*/
dragMode_: any /*missing*/;
/**
* Range of a drag angle from a flyout considered "dragging toward workspace".
* Drags that are within the bounds of this many degrees from the orthogonal
* line to the flyout edge are considered to be "drags toward the workspace".
* Example:
* Flyout Edge Workspace
* [block] / <-within this angle, drags "toward workspace" |
* [block] ---- orthogonal to flyout boundary ---- |
* [block] \ |
* The angle is given in degrees from the orthogonal.
*
* This is used to know when to create a new block and when to scroll the
* flyout. Setting it to 360 means that all drags create a new block.
* @type {number}
* @private
*/
dragAngleRange_: number;
/**
* Creates the flyout's DOM. Only needs to be called once.
* @return {!Element} The flyout's SVG group.
*/
createDom(): Element;
/**
* Initializes the flyout.
* @param {!Blockly.Workspace} targetWorkspace The workspace in which to create
* new blocks.
*/
init(targetWorkspace: Blockly.Workspace): void;
/**
* Dispose of this flyout.
* Unlink from all DOM elements to prevent memory leaks.
*/
dispose(): void;
/**
* Get the width of the flyout.
* @return {number} The width of the flyout.
*/
getWidth(): number;
/**
* Get the height of the flyout.
* @return {number} The width of the flyout.
*/
getHeight(): number;
/**
* Return an object with all the metrics required to size scrollbars for the
* flyout. The following properties are computed:
* .viewHeight: Height of the visible rectangle,
* .viewWidth: Width of the visible rectangle,
* .contentHeight: Height of the contents,
* .contentWidth: Width of the contents,
* .viewTop: Offset of top edge of visible rectangle from parent,
* .contentTop: Offset of the top-most content from the y=0 coordinate,
* .absoluteTop: Top-edge of view.
* .viewLeft: Offset of the left edge of visible rectangle from parent,
* .contentLeft: Offset of the left-most content from the x=0 coordinate,
* .absoluteLeft: Left-edge of view.
* @return {Object} Contains size and position metrics of the flyout.
* @private
*/
getMetrics_(): Object;
/**
* Sets the translation of the flyout to match the scrollbars.
* @param {!Object} xyRatio Contains a y property which is a float
* between 0 and 1 specifying the degree of scrolling and a
* similar x property.
* @private
*/
setMetrics_(xyRatio: Object): void;
/**
* Move the flyout to the edge of the workspace.
*/
position(): void;
/**
* Create and set the path for the visible boundaries of the flyout.
* @param {number} width The width of the flyout, not including the
* rounded corners.
* @param {number} height The height of the flyout, not including
* rounded corners.
* @private
*/
setBackgroundPath_(width: number, height: number): void;
/**
* Create and set the path for the visible boundaries of the flyout in vertical
* mode.
* @param {number} width The width of the flyout, not including the
* rounded corners.
* @param {number} height The height of the flyout, not including
* rounded corners.
* @private
*/
setBackgroundPathVertical_(width: number, height: number): void;
/**
* Create and set the path for the visible boundaries of the flyout in
* horizontal mode.
* @param {number} width The width of the flyout, not including the
* rounded corners.
* @param {number} height The height of the flyout, not including
* rounded corners.
* @private
*/
setBackgroundPathHorizontal_(width: number, height: number): void;
/**
* Scroll the flyout to the top.
*/
scrollToStart(): void;
/**
* Scroll the flyout.
* @param {!Event} e Mouse wheel scroll event.
* @private
*/
wheel_(e: Event): void;
/**
* Is the flyout visible?
* @return {boolean} True if visible.
*/
isVisible(): boolean;
/**
* Hide and empty the flyout.
*/
hide(): void;
/**
* Show and populate the flyout.
* @param {!Array|string} xmlList List of blocks to show.
* Variables and procedures have a custom set of blocks.
*/
show(xmlList: any[]|string): void;
/**
* Lay out the blocks in the flyout.
* @param {!Array.<!Object>} contents The blocks and buttons to lay out.
* @param {!Array.<number>} gaps The visible gaps between blocks.
* @private
*/
layout_(contents: Object[], gaps: number[]): void;
/**
* Delete blocks and background buttons from a previous showing of the flyout.
* @private
*/
clearOldBlocks_(): void;
/**
* Add listeners to a block that has been added to the flyout.
* @param {!Element} root The root node of the SVG group the block is in.
* @param {!Blockly.Block} block The block to add listeners for.
* @param {!Element} rect The invisible rectangle under the block that acts as
* a button for that block.
* @private
*/
addBlockListeners_(root: Element, block: Blockly.Block, rect: Element): void;
/**
* Handle a mouse-down on an SVG block in a non-closing flyout.
* @param {!Blockly.Block} block The flyout block to copy.
* @return {!Function} Function to call when block is clicked.
* @private
*/
blockMouseDown_(block: Blockly.Block): Function;
/**
* Mouse down on the flyout background. Start a vertical scroll drag.
* @param {!Event} e Mouse down event.
* @private
*/
onMouseDown_(e: Event): void;
/**
* Handle a mouse-up anywhere in the SVG pane. Is only registered when a
* block is clicked. We can't use mouseUp on the block since a fast-moving
* cursor can briefly escape the block before it catches up.
* @param {!Event} e Mouse up event.
* @private
*/
onMouseUp_(e: Event): void;
/**
* Handle a mouse-move to vertically drag the flyout.
* @param {!Event} e Mouse move event.
* @private
*/
onMouseMove_(e: Event): void;
/**
* Mouse button is down on a block in a non-closing flyout. Create the block
* if the mouse moves beyond a small radius. This allows one to play with
* fields without instantiating blocks that instantly self-destruct.
* @param {!Event} e Mouse move event.
* @private
*/
onMouseMoveBlock_(e: Event): void;
/**
* Determine the intention of a drag.
* Updates dragMode_ based on a drag delta and the current mode,
* and returns true if we should create a new block.
* @param {number} dx X delta of the drag.
* @param {number} dy Y delta of the drag.
* @return {boolean} True if a new block should be created.
* @private
*/
determineDragIntention_(dx: number, dy: number): boolean;
/**
* Determine if a drag delta is toward the workspace, based on the position
* and orientation of the flyout. This is used in determineDragIntention_ to
* determine if a new block should be created or if the flyout should scroll.
* @param {number} dx X delta of the drag.
* @param {number} dy Y delta of the drag.
* @return {boolean} true if the drag is toward the workspace.
* @private
*/
isDragTowardWorkspace_(dx: number, dy: number): boolean;
/**
* Create a copy of this block on the workspace.
* @param {!Blockly.Block} originBlock The flyout block to copy.
* @return {!Function} Function to call when block is clicked.
* @private
*/
createBlockFunc_(originBlock: Blockly.Block): Function;
/**
* Copy a block from the flyout to the workspace and position it correctly.
* @param {!Blockly.Block} originBlock The flyout block to copy..
* @return {!Blockly.Block} The new block in the main workspace.
* @private
*/
placeNewBlock_(originBlock: Blockly.Block): Blockly.Block;
/**
* Filter the blocks on the flyout to disable the ones that are above the
* capacity limit.
* @private
*/
filterForCapacity_(): void;
/**
* Return the deletion rectangle for this flyout.
* @return {goog.math.Rect} Rectangle in which to delete.
*/
getClientRect(): goog.math.Rect;
/**
* Compute height of flyout. Position button under each block.
* For RTL: Lay out the blocks right-aligned.
* @param {!Array<!Blockly.Block>} blocks The blocks to reflow.
*/
reflowHorizontal(blocks: Blockly.Block[]): void;
/**
* Compute width of flyout. Position button under each block.
* For RTL: Lay out the blocks right-aligned.
* @param {!Array<!Blockly.Block>} blocks The blocks to reflow.
*/
reflowVertical(blocks: Blockly.Block[]): void;
/**
* Reflow blocks and their buttons.
*/
reflow(): void;
}
}
declare module Blockly {
class Generator extends Generator__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class Generator__Class {
/**
* Class for a code generator that translates the blocks into a language.
* @param {string} name Language name of this generator.
* @constructor
*/
constructor(name: string);
/**
* Arbitrary code to inject into locations that risk causing infinite loops.
* Any instances of '%1' will be replaced by the block ID that failed.
* E.g. ' checkTimeout(%1);\n'
* @type {?string}
*/
INFINITE_LOOP_TRAP: string;
/**
* Arbitrary code to inject before every statement.
* Any instances of '%1' will be replaced by the block ID of the statement.
* E.g. 'highlight(%1);\n'
* @type {?string}
*/
STATEMENT_PREFIX: string;
/**
* The method of indenting. Defaults to two spaces, but language generators
* may override this to increase indent or change to tabs.
* @type {string}
*/
INDENT: string;
/**
* Maximum length for a comment before wrapping. Does not account for
* indenting level.
* @type {number}
*/
COMMENT_WRAP: number;
/**
* List of outer-inner pairings that do NOT require parentheses.
* @type {!Array.<!Array.<number>>}
*/
ORDER_OVERRIDES: number[][];
/**
* Generate code for all blocks in the workspace to the specified language.
* @param {Blockly.Workspace} workspace Workspace to generate code from.
* @return {string} Generated code.
*/
workspaceToCode(workspace: Blockly.Workspace): string;
/**
* Prepend a common prefix onto each line of code.
* @param {string} text The lines of code.
* @param {string} prefix The common prefix.
* @return {string} The prefixed lines of code.
*/
prefixLines(text: string, prefix: string): string;
/**
* Recursively spider a tree of blocks, returning all their comments.
* @param {!Blockly.Block} block The block from which to start spidering.
* @return {string} Concatenated list of comments.
*/
allNestedComments(block: Blockly.Block): string;
/**
* Generate code for the specified block (and attached blocks).
* @param {Blockly.Block} block The block to generate code for.
* @return {string|!Array} For statement blocks, the generated code.
* For value blocks, an array containing the generated code and an
* operator order value. Returns '' if block is null.
*/
blockToCode(block: Blockly.Block): string|any[];
/**
* Generate code representing the specified value input.
* @param {!Blockly.Block} block The block containing the input.
* @param {string} name The name of the input.
* @param {number} outerOrder The maximum binding strength (minimum order value)
* of any operators adjacent to "block".
* @return {string} Generated code or '' if no blocks are connected or the
* specified input does not exist.
*/
valueToCode(block: Blockly.Block, name: string, outerOrder: number): string;
/**
* Generate code representing the statement. Indent the code.
* @param {!Blockly.Block} block The block containing the input.
* @param {string} name The name of the input.
* @return {string} Generated code or '' if no blocks are connected.
*/
statementToCode(block: Blockly.Block, name: string): string;
/**
* Add an infinite loop trap to the contents of a loop.
* If loop is empty, add a statment prefix for the loop block.
* @param {string} branch Code for loop contents.
* @param {string} id ID of enclosing block.
* @return {string} Loop contents, with infinite loop trap added.
*/
addLoopTrap(branch: string, id: string): string;
/**
* Comma-separated list of reserved words.
* @type {string}
* @private
*/
RESERVED_WORDS_: string;
/**
* Add one or more words to the list of reserved words for this language.
* @param {string} words Comma-separated list of words to add to the list.
* No spaces. Duplicates are ok.
*/
addReservedWords(words: string): void;
/**
* This is used as a placeholder in functions defined using
* Blockly.Generator.provideFunction_. It must not be legal code that could
* legitimately appear in a function definition (or comment), and it must
* not confuse the regular expression parser.
* @type {string}
* @private
*/
FUNCTION_NAME_PLACEHOLDER_: string;
/**
* Define a function to be included in the generated code.
* The first time this is called with a given desiredName, the code is
* saved and an actual name is generated. Subsequent calls with the
* same desiredName have no effect but have the same return value.
*
* It is up to the caller to make sure the same desiredName is not
* used for different code values.
*
* The code gets output when Blockly.Generator.finish() is called.
*
* @param {string} desiredName The desired name of the function (e.g., isPrime).
* @param {!Array.<string>} code A list of statements. Use ' ' for indents.
* @return {string} The actual name of the new function. This may differ
* from desiredName if the former has already been taken by the user.
* @private
*/
provideFunction_(desiredName: string, code: string[]): string;
}
}
declare module Blockly {
class WorkspaceSvg extends WorkspaceSvg__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class WorkspaceSvg__Class extends Blockly.Workspace__Class {
/**
* Class for a workspace. This is an onscreen area with optional trashcan,
* scrollbars, bubbles, and dragging.
* @param {!Blockly.Options} options Dictionary of options.
* @extends {Blockly.Workspace}
* @constructor
*/
constructor(options: Blockly.Options);
/**
* Database of pre-loaded sounds.
* @private
* @const
*/
SOUNDS_: any /*missing*/;
/**
* A wrapper function called when a resize event occurs. You can pass the result to `unbindEvent_`.
* @type {Array.<!Array>}
*/
resizeHandlerWrapper_: any[][];
/**
* The render status of an SVG workspace.
* Returns `true` for visible workspaces and `false` for non-visible, or headless, workspaces.
* @type {boolean}
*/
rendered: boolean;
/**
* Is this workspace the surface for a flyout?
* @type {boolean}
*/
isFlyout: boolean;
/**
* Is this workspace the surface for a mutator?
* @type {boolean}
* @package
*/
isMutator: boolean;
/**
* Is this workspace currently being dragged around?
* DRAG_NONE - No drag operation.
* DRAG_BEGIN - Still inside the initial DRAG_RADIUS.
* DRAG_FREE - Workspace has been dragged further than DRAG_RADIUS.
* @private
*/
dragMode_: any /*missing*/;
/**
* Current horizontal scrolling offset.
* @type {number}
*/
scrollX: number;
/**
* Current vertical scrolling offset.
* @type {number}
*/
scrollY: number;
/**
* Horizontal scroll value when scrolling started.
* @type {number}
*/
startScrollX: number;
/**
* Vertical scroll value when scrolling started.
* @type {number}
*/
startScrollY: number;
/**
* Distance from mouse to object being dragged.
* @type {goog.math.Coordinate}
* @private
*/
dragDeltaXY_: goog.math.Coordinate;
/**
* Current scale.
* @type {number}
*/
scale: number;
/** @type {Blockly.Trashcan} */
trashcan: Blockly.Trashcan;
/**
* This workspace's scrollbars, if they exist.
* @type {Blockly.ScrollbarPair}
*/
scrollbar: Blockly.ScrollbarPair;
/**
* Time that the last sound was played.
* @type {Date}
* @private
*/
lastSound_: Date;
/**
* Last known position of the page scroll.
* This is used to determine whether we have recalculated screen coordinate
* stuff since the page scrolled.
* @type {!goog.math.Coordinate}
* @private
*/
lastRecordedPageScroll_: goog.math.Coordinate;
/**
* Inverted screen CTM, for use in mouseToSvg.
* @type {SVGMatrix}
* @private
*/
inverseScreenCTM_: SVGMatrix;
/**
* Getter for the inverted screen CTM.
* @return {SVGMatrix} The matrix to use in mouseToSvg
*/
getInverseScreenCTM(): SVGMatrix;
/**
* Update the inverted screen CTM.
*/
updateInverseScreenCTM(): void;
/**
* Save resize handler data so we can delete it later in dispose.
* @param {!Array.<!Array>} handler Data that can be passed to unbindEvent_.
*/
setResizeHandlerWrapper(handler: any[][]): void;
/**
* Create the workspace DOM elements.
* @param {string=} opt_backgroundClass Either 'blocklyMainBackground' or
* 'blocklyMutatorBackground'.
* @return {!Element} The workspace's SVG group.
*/
createDom(opt_backgroundClass?: string): Element;
/**
* <g class="blocklyWorkspace">
* <rect class="blocklyMainBackground" height="100%" width="100%"></rect>
* [Trashcan and/or flyout may go here]
* <g class="blocklyBlockCanvas"></g>
* <g class="blocklyBubbleCanvas"></g>
* [Scrollbars may go here]
* </g>
* @type {SVGElement}
*/
svgGroup_: SVGElement;
/** @type {SVGElement} */
svgBackground_: SVGElement;
/** @type {SVGElement} */
svgBlockCanvas_: SVGElement;
/** @type {SVGElement} */
svgBubbleCanvas_: SVGElement;
/**
* Dispose of this workspace.
* Unlink from all DOM elements to prevent memory leaks.
*/
dispose(): void;
/**
* Obtain a newly created block.
* @param {?string} prototypeName Name of the language object containing
* type-specific functions for this block.
* @param {string=} opt_id Optional ID. Use this ID if provided, otherwise
* create a new ID.
* @return {!Blockly.BlockSvg} The created block.
*/
newBlock(prototypeName: string, opt_id?: string): any;
/**
* Add a trashcan.
* @param {number} bottom Distance from workspace bottom to bottom of trashcan.
* @return {number} Distance from workspace bottom to the top of trashcan.
* @private
*/
addTrashcan_(bottom: number): number;
/**
* Add zoom controls.
* @param {number} bottom Distance from workspace bottom to bottom of controls.
* @return {number} Distance from workspace bottom to the top of controls.
* @private
*/
addZoomControls_(bottom: number): number;
/** @type {Blockly.ZoomControls} */
zoomControls_: any;
/**
* Add a flyout.
* @private
*/
addFlyout_(): void;
/** @type {Blockly.Flyout} */
flyout_: Blockly.Flyout;
/**
* Update items that use screen coordinate calculations
* because something has changed (e.g. scroll position, window size).
* @private
*/
updateScreenCalculations_(): void;
/**
* Resize the parts of the workspace that change when the workspace
* contents (e.g. block positions) change. This will also scroll the
* workspace contents if needed.
* @package
*/
resizeContents(): void;
/**
* Resize and reposition all of the workspace chrome (toolbox,
* trash, scrollbars etc.)
* This should be called when something changes that
* requires recalculating dimensions and positions of the
* trash, zoom, toolbox, etc. (e.g. window resize).
*/
resize(): void;
/**
* Resizes and repositions workspace chrome if the page has a new
* scroll position.
* @package
*/
updateScreenCalculationsIfScrolled(): void;
/**
* Get the SVG element that forms the drawing surface.
* @return {!Element} SVG element.
*/
getCanvas(): Element;
/**
* Get the SVG element that forms the bubble surface.
* @return {!SVGGElement} SVG element.
*/
getBubbleCanvas(): SVGGElement;
/**
* Get the SVG element that contains this workspace.
* @return {!Element} SVG element.
*/
getParentSvg(): Element;
/**
* Translate this workspace to new coordinates.
* @param {number} x Horizontal translation.
* @param {number} y Vertical translation.
*/
translate(x: number, y: number): void;
/**
* Returns the horizontal offset of the workspace.
* Intended for LTR/RTL compatibility in XML.
* @return {number} Width.
*/
getWidth(): number;
/**
* Toggles the visibility of the workspace.
* Currently only intended for main workspace.
* @param {boolean} isVisible True if workspace should be visible.
*/
setVisible(isVisible: boolean): void;
/**
* Render all blocks in workspace.
*/
render(): void;
/**
* Turn the visual trace functionality on or off.
* @param {boolean} armed True if the trace should be on.
*/
traceOn(armed: boolean): void;
/**
* Highlight a block in the workspace.
* @param {?string} id ID of block to find.
*/
highlightBlock(id: string): void;
/**
* Paste the provided block onto the workspace.
* @param {!Element} xmlBlock XML block element.
*/
paste(xmlBlock: Element): void;
/**
* Create a new variable with the given name. Update the flyout to show the new
* variable immediately.
* TODO: #468
* @param {string} name The new variable's name.
*/
createVariable(name: string): void;
/**
* Make a list of all the delete areas for this workspace.
*/
recordDeleteAreas(): void;
/**
* Is the mouse event over a delete area (toolbox or non-closing flyout)?
* Opens or closes the trashcan and sets the cursor as a side effect.
* @param {!Event} e Mouse move event.
* @return {boolean} True if event is in a delete area.
*/
isDeleteArea(e: Event): boolean;
/**
* Handle a mouse-down on SVG drawing surface.
* @param {!Event} e Mouse down event.
* @private
*/
onMouseDown_(e: Event): void;
/**
* Start tracking a drag of an object on this workspace.
* @param {!Event} e Mouse down event.
* @param {!goog.math.Coordinate} xy Starting location of object.
*/
startDrag(e: Event, xy: goog.math.Coordinate): void;
/**
* Track a drag of an object on this workspace.
* @param {!Event} e Mouse move event.
* @return {!goog.math.Coordinate} New location of object.
*/
moveDrag(e: Event): goog.math.Coordinate;
/**
* Is the user currently dragging a block or scrolling the flyout/workspace?
* @return {boolean} True if currently dragging or scrolling.
*/
isDragging(): boolean;
/**
* Handle a mouse-wheel on SVG drawing surface.
* @param {!Event} e Mouse wheel event.
* @private
*/
onMouseWheel_(e: Event): void;
/**
* Calculate the bounding box for the blocks on the workspace.
*
* @return {Object} Contains the position and size of the bounding box
* containing the blocks on the workspace.
*/
getBlocksBoundingBox(): Object;
/**
* Clean up the workspace by ordering all the blocks in a column.
*/
cleanUp(): void;
/**
* Show the context menu for the workspace.
* @param {!Event} e Mouse event.
* @private
*/
showContextMenu_(e: Event): void;
/**
* Load an audio file. Cache it, ready for instantaneous playing.
* @param {!Array.<string>} filenames List of file types in decreasing order of
* preference (i.e. increasing size). E.g. ['media/go.mp3', 'media/go.wav']
* Filenames include path from Blockly's root. File extensions matter.
* @param {string} name Name of sound.
* @private
*/
loadAudio_(filenames: string[], name: string): void;
/**
* Preload all the audio files so that they play quickly when asked for.
* @private
*/
preloadAudio_(): void;
/**
* Play a named sound at specified volume. If volume is not specified,
* use full volume (1).
* @param {string} name Name of sound.
* @param {number=} opt_volume Volume of sound (0-1).
*/
playAudio(name: string, opt_volume?: number): void;
/**
* Modify the block tree on the existing toolbox.
* @param {Node|string} tree DOM tree of blocks, or text representation of same.
*/
updateToolbox(tree: Node|string): void;
/**
* Mark this workspace as the currently focused main workspace.
*/
markFocused(): void;
/**
* Zooming the blocks centered in (x, y) coordinate with zooming in or out.
* @param {number} x X coordinate of center.
* @param {number} y Y coordinate of center.
* @param {number} type Type of zooming (-1 zooming out and 1 zooming in).
*/
zoom(x: number, y: number, type: number): void;
/**
* Zooming the blocks centered in the center of view with zooming in or out.
* @param {number} type Type of zooming (-1 zooming out and 1 zooming in).
*/
zoomCenter(type: number): void;
/**
* Zoom the blocks to fit in the workspace if possible.
*/
zoomToFit(): void;
/**
* Center the workspace.
*/
scrollCenter(): void;
/**
* Set the workspace's zoom factor.
* @param {number} newScale Zoom factor.
*/
setScale(newScale: number): void;
/**
* Updates the grid pattern.
* @private
*/
updateGridPattern_(): void;
}
}
declare module Blockly {
class Warning extends Warning__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class Warning__Class extends Blockly.Icon__Class {
/**
* Class for a warning.
* @param {!Blockly.Block} block The block associated with this warning.
* @extends {Blockly.Icon}
* @constructor
*/
constructor(block: Blockly.Block);
/**
* Does this icon get hidden when the block is collapsed.
*/
collapseHidden: any /*missing*/;
/**
* Draw the warning icon.
* @param {!Element} group The icon group.
* @private
*/
drawIcon_(group: Element): void;
/**
* Show or hide the warning bubble.
* @param {boolean} visible True if the bubble should be visible.
*/
setVisible(visible: boolean): void;
/**
* Bring the warning to the top of the stack when clicked on.
* @param {!Event} e Mouse up event.
* @private
*/
bodyFocus_(e: Event): void;
/**
* Set this warning's text.
* @param {string} text Warning text (or '' to delete).
* @param {string} id An ID for this text entry to be able to maintain
* multiple warnings.
*/
setText(text: string, id: string): void;
/**
* Get this warning's texts.
* @return {string} All texts concatenated into one string.
*/
getText(): string;
/**
* Dispose of this warning.
*/
dispose(): void;
}
}
declare module Blockly {
class Icon extends Icon__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class Icon__Class {
/**
* Class for an icon.
* @param {Blockly.Block} block The block associated with this icon.
* @constructor
*/
constructor(block: Blockly.Block);
/**
* Does this icon get hidden when the block is collapsed.
*/
collapseHidden: any /*missing*/;
/**
* Height and width of icons.
*/
SIZE: any /*missing*/;
/**
* Bubble UI (if visible).
* @type {Blockly.Bubble}
* @private
*/
bubble_: Blockly.Bubble;
/**
* Absolute coordinate of icon's center.
* @type {goog.math.Coordinate}
* @private
*/
iconXY_: goog.math.Coordinate;
/**
* Create the icon on the block.
*/
createIcon(): void;
/**
* Dispose of this icon.
*/
dispose(): void;
/**
* Add or remove the UI indicating if this icon may be clicked or not.
*/
updateEditable(): void;
/**
* Is the associated bubble visible?
* @return {boolean} True if the bubble is visible.
*/
isVisible(): boolean;
/**
* Clicking on the icon toggles if the bubble is visible.
* @param {!Event} e Mouse click event.
* @private
*/
iconClick_(e: Event): void;
/**
* Change the colour of the associated bubble to match its block.
*/
updateColour(): void;
/**
* Render the icon.
* @param {number} cursorX Horizontal offset at which to position the icon.
* @return {number} Horizontal offset for next item to draw.
*/
renderIcon(cursorX: number): number;
/**
* Notification that the icon has moved. Update the arrow accordingly.
* @param {!goog.math.Coordinate} xy Absolute location.
*/
setIconLocation(xy: goog.math.Coordinate): void;
/**
* Notification that the icon has moved, but we don't really know where.
* Recompute the icon's location from scratch.
*/
computeIconLocation(): void;
/**
* Returns the center of the block's icon relative to the surface.
* @return {!goog.math.Coordinate} Object with x and y properties.
*/
getIconLocation(): goog.math.Coordinate;
}
}
declare module Blockly {
/**
* Inject a Blockly editor into the specified container element (usually a div).
* @param {!Element|string} container Containing element, or its ID,
* or a CSS selector.
* @param {Object=} opt_options Optional dictionary of options.
* @return {!Blockly.Workspace} Newly created main workspace.
*/
function inject(container: Element|string, opt_options?: Object): Blockly.Workspace;
/**
* Create the SVG image.
* @param {!Element} container Containing element.
* @param {!Blockly.Options} options Dictionary of options.
* @return {!Element} Newly created SVG image.
* @private
*/
function createDom_(container: Element, options: Blockly.Options): Element;
/**
* Create a main workspace and add it to the SVG.
* @param {!Element} svg SVG element with pattern defined.
* @param {!Blockly.Options} options Dictionary of options.
* @return {!Blockly.Workspace} Newly created main workspace.
* @private
*/
function createMainWorkspace_(svg: Element, options: Blockly.Options): Blockly.Workspace;
/**
* Initialize Blockly with various handlers.
* @param {!Blockly.Workspace} mainWorkspace Newly created main workspace.
* @private
*/
function init_(mainWorkspace: Blockly.Workspace): void;
/**
* Modify the block tree on the existing toolbox.
* @param {Node|string} tree DOM tree of blocks, or text representation of same.
*/
function updateToolbox(tree: Node|string): void;
}
declare module Blockly {
class RenderedConnection extends RenderedConnection__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class RenderedConnection__Class extends Blockly.Connection__Class {
/**
* Class for a connection between blocks that may be rendered on screen.
* @param {!Blockly.Block} source The block establishing this connection.
* @param {number} type The type of the connection.
* @extends {Blockly.Connection}
* @constructor
*/
constructor(source: Blockly.Block, type: number);
/**
* Returns the distance between this connection and another connection.
* @param {!Blockly.Connection} otherConnection The other connection to measure
* the distance to.
* @return {number} The distance between connections.
*/
distanceFrom(otherConnection: Blockly.Connection): number;
/**
* Move the block(s) belonging to the connection to a point where they don't
* visually interfere with the specified connection.
* @param {!Blockly.Connection} staticConnection The connection to move away
* from.
* @private
*/
bumpAwayFrom_(staticConnection: Blockly.Connection): void;
/**
* Change the connection's coordinates.
* @param {number} x New absolute x coordinate.
* @param {number} y New absolute y coordinate.
*/
moveTo(x: number, y: number): void;
/**
* Change the connection's coordinates.
* @param {number} dx Change to x coordinate.
* @param {number} dy Change to y coordinate.
*/
moveBy(dx: number, dy: number): void;
/**
* Move this connection to the location given by its offset within the block and
* the coordinate of the block's top left corner.
* @param {!goog.math.Coordinate} blockTL The coordinate of the top left corner
* of the block.
*/
moveToOffset(blockTL: goog.math.Coordinate): void;
/**
* Set the offset of this connection relative to the top left of its block.
* @param {number} x The new relative x.
* @param {number} y The new relative y.
*/
setOffsetInBlock(x: number, y: number): void;
/**
* Move the blocks on either side of this connection right next to each other.
* @private
*/
tighten_(): void;
/**
* Find the closest compatible connection to this connection.
* @param {number} maxLimit The maximum radius to another connection.
* @param {number} dx Horizontal offset between this connection's location
* in the database and the current location (as a result of dragging).
* @param {number} dy Vertical offset between this connection's location
* in the database and the current location (as a result of dragging).
* @return {!{connection: ?Blockly.Connection, radius: number}} Contains two
* properties: 'connection' which is either another connection or null,
* and 'radius' which is the distance.
*/
closest(maxLimit: number, dx: number, dy: number): { connection: Blockly.Connection; radius: number };
/**
* Add highlighting around this connection.
*/
highlight(): void;
/**
* Unhide this connection, as well as all down-stream connections on any block
* attached to this connection. This happens when a block is expanded.
* Also unhides down-stream comments.
* @return {!Array.<!Blockly.Block>} List of blocks to render.
*/
unhideAll(): Blockly.Block[];
/**
* Remove the highlighting around this connection.
*/
unhighlight(): void;
/**
* Set whether this connections is hidden (not tracked in a database) or not.
* @param {boolean} hidden True if connection is hidden.
*/
setHidden(hidden: boolean): void;
/**
* Hide this connection, as well as all down-stream connections on any block
* attached to this connection. This happens when a block is collapsed.
* Also hides down-stream comments.
*/
hideAll(): void;
/**
* Check if the two connections can be dragged to connect to each other.
* @param {!Blockly.Connection} candidate A nearby connection to check.
* @param {number} maxRadius The maximum radius allowed for connections.
* @return {boolean} True if the connection is allowed, false otherwise.
*/
isConnectionAllowed(candidate: Blockly.Connection, maxRadius?: number): boolean;
/**
* Disconnect two blocks that are connected by this connection.
* @param {!Blockly.Block} parentBlock The superior block.
* @param {!Blockly.Block} childBlock The inferior block.
* @private
*/
disconnectInternal_(parentBlock: Blockly.Block, childBlock: Blockly.Block): void;
/**
* Respawn the shadow block if there was one connected to the this connection.
* Render/rerender blocks as needed.
* @private
*/
respawnShadow_(): void;
/**
* Find all nearby compatible connections to this connection.
* Type checking does not apply, since this function is used for bumping.
* @param {number} maxLimit The maximum radius to another connection.
* @return {!Array.<!Blockly.Connection>} List of connections.
* @private
*/
neighbours_(maxLimit: number): Blockly.Connection[];
/**
* Connect two connections together. This is the connection on the superior
* block. Rerender blocks as needed.
* @param {!Blockly.Connection} childConnection Connection on inferior block.
* @private
*/
connect_(childConnection: Blockly.Connection): void;
}
}
declare module Blockly {
class ScrollbarPair extends ScrollbarPair__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class ScrollbarPair__Class {
/**
* Class for a pair of scrollbars. Horizontal and vertical.
* @param {!Blockly.Workspace} workspace Workspace to bind the scrollbars to.
* @constructor
*/
constructor(workspace: Blockly.Workspace);
/**
* Previously recorded metrics from the workspace.
* @type {Object}
* @private
*/
oldHostMetrics_: Object;
/**
* Dispose of this pair of scrollbars.
* Unlink from all DOM elements to prevent memory leaks.
*/
dispose(): void;
/**
* Recalculate both of the scrollbars' locations and lengths.
* Also reposition the corner rectangle.
*/
resize(): void;
/**
* Set the sliders of both scrollbars to be at a certain position.
* @param {number} x Horizontal scroll value.
* @param {number} y Vertical scroll value.
*/
set(x: number, y: number): void;
/**
* Helper to calculate the ratio of handle position to scrollbar view size.
* @param {number} handlePosition The value of the handle.
* @param {number} viewSize The total size of the scrollbar's view.
* @return {number} Ratio.
* @private
*/
getRatio_(handlePosition: number, viewSize: number): number;
}
class Scrollbar extends Scrollbar__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class Scrollbar__Class {
/**
* Class for a pure SVG scrollbar.
* This technique offers a scrollbar that is guaranteed to work, but may not
* look or behave like the system's scrollbars.
* @param {!Blockly.Workspace} workspace Workspace to bind the scrollbar to.
* @param {boolean} horizontal True if horizontal, false if vertical.
* @param {boolean=} opt_pair True if scrollbar is part of a horiz/vert pair.
* @constructor
*/
constructor(workspace: Blockly.Workspace, horizontal: boolean, opt_pair?: boolean);
/**
* The upper left corner of the scrollbar's svg group.
* @type {goog.math.Coordinate}
* @private
*/
position_: goog.math.Coordinate;
/**
* The size of the area within which the scrollbar handle can move.
* @type {number}
* @private
*/
scrollViewSize_: number;
/**
* The length of the scrollbar handle.
* @type {number}
* @private
*/
handleLength_: number;
/**
* The offset of the start of the handle from the start of the scrollbar range.
* @type {number}
* @private
*/
handlePosition_: number;
/**
* Whether the scrollbar handle is visible.
* @type {boolean}
* @private
*/
isVisible_: boolean;
/**
* Dispose of this scrollbar.
* Unlink from all DOM elements to prevent memory leaks.
*/
dispose(): void;
/**
* Set the length of the scrollbar's handle and change the SVG attribute
* accordingly.
* @param {number} newLength The new scrollbar handle length.
*/
setHandleLength_(newLength: number): void;
/**
* Set the offset of the scrollbar's handle and change the SVG attribute
* accordingly.
* @param {number} newPosition The new scrollbar handle offset.
*/
setHandlePosition(newPosition: number): void;
/**
* Set the size of the scrollbar's background and change the SVG attribute
* accordingly.
* @param {number} newSize The new scrollbar background length.
* @private
*/
setScrollViewSize_(newSize: number): void;
/**
* Set the position of the scrollbar's svg group.
* @param {number} x The new x coordinate.
* @param {number} y The new y coordinate.
*/
setPosition(x: number, y: number): void;
/**
* Recalculate the scrollbar's location and its length.
* @param {Object=} opt_metrics A data structure of from the describing all the
* required dimensions. If not provided, it will be fetched from the host
* object.
*/
resize(opt_metrics?: Object): void;
/**
* Recalculate a horizontal scrollbar's location and length.
* @param {!Object} hostMetrics A data structure describing all the
* required dimensions, possibly fetched from the host object.
* @private
*/
resizeHorizontal_(hostMetrics: Object): void;
/**
* Recalculate a horizontal scrollbar's location on the screen and path length.
* This should be called when the layout or size of the window has changed.
* @param {!Object} hostMetrics A data structure describing all the
* required dimensions, possibly fetched from the host object.
*/
resizeViewHorizontal(hostMetrics: Object): void;
/**
* Recalculate a horizontal scrollbar's location within its path and length.
* This should be called when the contents of the workspace have changed.
* @param {!Object} hostMetrics A data structure describing all the
* required dimensions, possibly fetched from the host object.
*/
resizeContentHorizontal(hostMetrics: Object): void;
/**
* Recalculate a vertical scrollbar's location and length.
* @param {!Object} hostMetrics A data structure describing all the
* required dimensions, possibly fetched from the host object.
* @private
*/
resizeVertical_(hostMetrics: Object): void;
/**
* Recalculate a vertical scrollbar's location on the screen and path length.
* This should be called when the layout or size of the window has changed.
* @param {!Object} hostMetrics A data structure describing all the
* required dimensions, possibly fetched from the host object.
*/
resizeViewVertical(hostMetrics: Object): void;
/**
* Recalculate a vertical scrollbar's location within its path and length.
* This should be called when the contents of the workspace have changed.
* @param {!Object} hostMetrics A data structure describing all the
* required dimensions, possibly fetched from the host object.
*/
resizeContentVertical(hostMetrics: Object): void;
/**
* Create all the DOM elements required for a scrollbar.
* The resulting widget is not sized.
* @private
*/
createDom_(): void;
/**
* Is the scrollbar visible. Non-paired scrollbars disappear when they aren't
* needed.
* @return {boolean} True if visible.
*/
isVisible(): boolean;
/**
* Set whether the scrollbar is visible.
* Only applies to non-paired scrollbars.
* @param {boolean} visible True if visible.
*/
setVisible(visible: boolean): void;
/**
* Scroll by one pageful.
* Called when scrollbar background is clicked.
* @param {!Event} e Mouse down event.
* @private
*/
onMouseDownBar_(e: Event): void;
/**
* Start a dragging operation.
* Called when scrollbar handle is clicked.
* @param {!Event} e Mouse down event.
* @private
*/
onMouseDownHandle_(e: Event): void;
/**
* Drag the scrollbar's handle.
* @param {!Event} e Mouse up event.
* @private
*/
onMouseMoveHandle_(e: Event): void;
/**
* Release the scrollbar handle and reset state accordingly.
* @private
*/
onMouseUpHandle_(): void;
/**
* Hide chaff and stop binding to mouseup and mousemove events. Call this to
* wrap up lose ends associated with the scrollbar.
* @private
*/
cleanUp_(): void;
/**
* Constrain the handle's position within the minimum (0) and maximum
* (length of scrollbar) values allowed for the scrollbar.
* @param {number} value Value that is potentially out of bounds.
* @return {number} Constrained value.
* @private
*/
constrainHandle_(value: number): number;
/**
* Called when scrollbar is moved.
* @private
*/
onScroll_(): void;
/**
* Set the scrollbar slider's position.
* @param {number} value The distance from the top/left end of the bar.
*/
set(value: number): void;
}
}
declare module Blockly {
class Workspace extends Workspace__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class Workspace__Class {
/**
* Class for a workspace. This is a data structure that contains blocks.
* There is no UI, and can be created headlessly.
* @param {Blockly.Options} opt_options Dictionary of options.
* @constructor
*/
constructor(opt_options?: Blockly.Options);
/** @type {string} */
id: string;
/** @type {!Blockly.Options} */
options: Blockly.Options;
/** @type {boolean} */
RTL: boolean;
/** @type {boolean} */
horizontalLayout: boolean;
/** @type {number} */
toolboxPosition: number;
/**
* @type {!Array.<!Blockly.Block>}
* @private
*/
topBlocks_: Blockly.Block[];
/**
* @type {!Array.<!Function>}
* @private
*/
listeners_: Function[];
/**
* @type {!Array.<!Blockly.Events.Abstract>}
* @private
*/
undoStack_: Blockly.Events.Abstract[];
/**
* @type {!Array.<!Blockly.Events.Abstract>}
* @private
*/
redoStack_: Blockly.Events.Abstract[];
/**
* @type {!Object}
* @private
*/
blockDB_: Object;
/**
* Returns `true` if the workspace is visible and `false` if it's headless.
* @type {boolean}
*/
rendered: boolean;
/**
* Maximum number of undo events in stack. `0` turns off undo, `Infinity` sets it to unlimited.
* @type {number}
*/
MAX_UNDO: number;
/**
* Dispose of this workspace.
* Unlink from all DOM elements to prevent memory leaks.
*/
dispose(): void;
/**
* Add a block to the list of top blocks.
* @param {!Blockly.Block} block Block to remove.
*/
addTopBlock(block: Blockly.Block): void;
/**
* Remove a block from the list of top blocks.
* @param {!Blockly.Block} block Block to remove.
*/
removeTopBlock(block: Blockly.Block): void;
/**
* Finds the top-level blocks and returns them. Blocks are optionally sorted
* by position; top to bottom (with slight LTR or RTL bias).
* @param {boolean} ordered Sort the list if true.
* @return {!Array.<!Blockly.Block>} The top-level block objects.
*/
getTopBlocks(ordered: boolean): Blockly.Block[];
/**
* Find all blocks in workspace. No particular order.
* @return {!Array.<!Blockly.Block>} Array of blocks.
*/
getAllBlocks(): Blockly.Block[];
/**
* Dispose of all blocks in workspace.
*/
clear(): void;
/**
* Walk the workspace and update the list of variables to only contain ones in
* use on the workspace. Use when loading new workspaces from disk.
* @param {boolean} clearList True if the old variable list should be cleared.
*/
updateVariableList(clearList: boolean): void;
/**
* Rename a variable by updating its name in the variable list.
* TODO: #468
* @param {string} oldName Variable to rename.
* @param {string} newName New variable name.
*/
renameVariable(oldName: string, newName: string): void;
/**
* Create a variable with the given name.
* TODO: #468
* @param {string} name The new variable's name.
*/
createVariable(name: string): void;
/**
* Find all the uses of a named variable.
* @param {string} name Name of variable.
* @return {!Array.<!Blockly.Block>} Array of block usages.
*/
getVariableUses(name: string): Blockly.Block[];
/**
* Delete a variables and all of its uses from this workspace.
* @param {string} name Name of variable to delete.
*/
deleteVariable(name: string): void;
/**
* Check whether a variable exists with the given name. The check is
* case-insensitive.
* @param {string} name The name to check for.
* @return {number} The index of the name in the variable list, or -1 if it is
* not present.
*/
variableIndexOf(name: string): number;
/**
* Returns the horizontal offset of the workspace.
* Intended for LTR/RTL compatibility in XML.
* Not relevant for a headless workspace.
* @return {number} Width.
*/
getWidth(): number;
/**
* Obtain a newly created block.
* @param {?string} prototypeName Name of the language object containing
* type-specific functions for this block.
* @param {string=} opt_id Optional ID. Use this ID if provided, otherwise
* create a new id.
* @return {!Blockly.Block} The created block.
*/
newBlock(prototypeName: string, opt_id?: string): any;
/**
* The number of blocks that may be added to the workspace before reaching
* the maxBlocks.
* @return {number} Number of blocks left.
*/
remainingCapacity(): number;
/**
* Undo or redo the previous action.
* @param {boolean} redo False if undo, true if redo.
*/
undo(redo: boolean): void;
/**
* Clear the undo/redo stacks.
*/
clearUndo(): void;
/**
* When something in this workspace changes, call a function.
* @param {!Function} func Function to call.
* @return {!Function} Function that can be passed to
* removeChangeListener.
*/
addChangeListener(func: Function): Function;
/**
* Stop listening for this workspace's changes.
* @param {Function} func Function to stop calling.
*/
removeChangeListener(func: Function): void;
/**
* Fire a change event.
* @param {!Blockly.Events.Abstract} event Event to fire.
*/
fireChangeListener(event: Blockly.Events.Abstract): void;
/**
* Find the block on this workspace with the specified ID.
* @param {string} id ID of block to find.
* @return {Blockly.Block} The sought after block or null if not found.
*/
getBlockById(id: string): Blockly.Block;
}
}
declare module Blockly {
class Toolbox extends Toolbox__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class Toolbox__Class {
/**
* Class for a Toolbox.
* Creates the toolbox's DOM.
* @param {!Blockly.Workspace} workspace The workspace in which to create new
* blocks.
* @constructor
*/
constructor(workspace: Blockly.Workspace);
/**
* @type {!Blockly.Workspace}
* @private
*/
workspace_: Blockly.Workspace;
/**
* Is RTL vs LTR.
* @type {boolean}
*/
RTL: boolean;
/**
* Whether the toolbox should be laid out horizontally.
* @type {boolean}
* @private
*/
horizontalLayout_: boolean;
/**
* Position of the toolbox and flyout relative to the workspace.
* @type {number}
*/
toolboxPosition: number;
/**
* Configuration constants for Closure's tree UI.
* @type {Object.<string,*>}
* @private
*/
config_: { [key: string]: any };
/**
* Configuration constants for tree separator.
* @type {Object.<string,*>}
* @private
*/
treeSeparatorConfig_: { [key: string]: any };
/**
* Width of the toolbox, which changes only in vertical layout.
* @type {number}
*/
width: number;
/**
* Height of the toolbox, which changes only in horizontal layout.
* @type {number}
*/
height: number;
/**
* The SVG group currently selected.
* @type {SVGGElement}
* @private
*/
selectedOption_: SVGGElement;
/**
* The tree node most recently selected.
* @type {goog.ui.tree.BaseNode}
* @private
*/
lastCategory_: goog.ui.tree.BaseNode;
/**
* Initializes the toolbox.
*/
init(): void;
/**
* @type {!Blockly.Flyout}
* @private
*/
flyout_: Blockly.Flyout;
/**
* Dispose of this toolbox.
*/
dispose(): void;
/**
* Get the width of the toolbox.
* @return {number} The width of the toolbox.
*/
getWidth(): number;
/**
* Get the height of the toolbox.
* @return {number} The width of the toolbox.
*/
getHeight(): number;
/**
* Move the toolbox to the edge.
*/
position(): void;
/**
* Fill the toolbox with categories and blocks.
* @param {!Node} newTree DOM tree of blocks.
* @return {Node} Tree node to open at startup (or null).
* @private
*/
populate_(newTree: Node): Node;
/**
* Sync trees of the toolbox.
* @param {!Node} treeIn DOM tree of blocks.
* @param {!Blockly.Toolbox.TreeControl} treeOut
* @param {string} pathToMedia
* @return {Node} Tree node to open at startup (or null).
* @private
*/
syncTrees_(treeIn: Node, treeOut: Blockly.Toolbox.TreeControl, pathToMedia: string): Node;
/**
* Recursively add colours to this toolbox.
* @param {Blockly.Toolbox.TreeNode} opt_tree Starting point of tree.
* Defaults to the root node.
* @private
*/
addColour_(opt_tree: Blockly.Toolbox.TreeNode): void;
/**
* Unhighlight any previously specified option.
*/
clearSelection(): void;
/**
* Return the deletion rectangle for this toolbox.
* @return {goog.math.Rect} Rectangle in which to delete.
*/
getClientRect(): goog.math.Rect;
/**
* Update the flyout's contents without closing it. Should be used in response
* to a change in one of the dynamic categories, such as variables or
* procedures.
*/
refreshSelection(): void;
}
}
declare module Blockly {
class Options extends Options__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class Options__Class {
/**
* Parse the user-specified options, using reasonable defaults where behaviour
* is unspecified.
* @param {!Object} options Dictionary of options. Specification:
* https://developers.google.com/blockly/guides/get-started/web#configuration
* @constructor
*/
constructor(options: Object);
/**
* The parent of the current workspace, or null if there is no parent workspace.
* @type {Blockly.Workspace}
**/
parentWorkspace: Blockly.Workspace;
/**
* If set, sets the translation of the workspace to match the scrollbars.
*/
setMetrics: any /*missing*/;
/**
* Return an object with the metrics required to size the workspace.
* @return {Object} Contains size and position metrics, or null.
*/
getMetrics(): Object;
}
}
declare module Blockly {
class Names extends Names__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class Names__Class {
/**
* Class for a database of entity names (variables, functions, etc).
* @param {string} reservedWords A comma-separated string of words that are
* illegal for use as names in a language (e.g. 'new,if,this,...').
* @param {string=} opt_variablePrefix Some languages need a '$' or a namespace
* before all variable names.
* @constructor
*/
constructor(reservedWords: string, opt_variablePrefix?: string);
/**
* Empty the database and start from scratch. The reserved words are kept.
*/
reset(): void;
/**
* Convert a Blockly entity name to a legal exportable entity name.
* @param {string} name The Blockly entity name (no constraints).
* @param {string} type The type of entity in Blockly
* ('VARIABLE', 'PROCEDURE', 'BUILTIN', etc...).
* @return {string} An entity name legal for the exported language.
*/
getName(name: string, type: string): string;
/**
* Convert a Blockly entity name to a legal exportable entity name.
* Ensure that this is a new name not overlapping any previously defined name.
* Also check against list of reserved words for the current language and
* ensure name doesn't collide.
* @param {string} name The Blockly entity name (no constraints).
* @param {string} type The type of entity in Blockly
* ('VARIABLE', 'PROCEDURE', 'BUILTIN', etc...).
* @return {string} An entity name legal for the exported language.
*/
getDistinctName(name: string, type: string): string;
/**
* Given a proposed entity name, generate a name that conforms to the
* [_A-Za-z][_A-Za-z0-9]* format that most languages consider legal for
* variables.
* @param {string} name Potentially illegal entity name.
* @return {string} Safe entity name.
* @private
*/
safeName_(name: string): string;
}
}
declare module Blockly {
class Mutator extends Mutator__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class Mutator__Class extends Blockly.Icon__Class {
/**
* Class for a mutator dialog.
* @param {!Array.<string>} quarkNames List of names of sub-blocks for flyout.
* @extends {Blockly.Icon}
* @constructor
*/
constructor(quarkNames: string[]);
/**
* Width of workspace.
* @private
*/
workspaceWidth_: any /*missing*/;
/**
* Height of workspace.
* @private
*/
workspaceHeight_: any /*missing*/;
/**
* Draw the mutator icon.
* @param {!Element} group The icon group.
* @private
*/
drawIcon_(group: Element): void;
/**
* Create the editor for the mutator's bubble.
* @return {!Element} The top-level node of the editor.
* @private
*/
createEditor_(): Element;
/**
* Add or remove the UI indicating if this icon may be clicked or not.
*/
updateEditable(): void;
/**
* Callback function triggered when the bubble has resized.
* Resize the workspace accordingly.
* @private
*/
resizeBubble_(): void;
/**
* Show or hide the mutator bubble.
* @param {boolean} visible True if the bubble should be visible.
*/
setVisible(visible: boolean): void;
/**
* Update the source block when the mutator's blocks are changed.
* Bump down any block that's too high.
* Fired whenever a change is made to the mutator's workspace.
* @private
*/
workspaceChanged_(): void;
/**
* Return an object with all the metrics required to size scrollbars for the
* mutator flyout. The following properties are computed:
* .viewHeight: Height of the visible rectangle,
* .viewWidth: Width of the visible rectangle,
* .absoluteTop: Top-edge of view.
* .absoluteLeft: Left-edge of view.
* @return {!Object} Contains size and position metrics of mutator dialog's
* workspace.
* @private
*/
getFlyoutMetrics_(): Object;
/**
* Dispose of this mutator.
*/
dispose(): void;
}
}
declare module Blockly.Block {
/**
* Obtain a newly created block.
* @param {!Blockly.Workspace} workspace The block's workspace.
* @param {?string} prototypeName Name of the language object containing
* type-specific functions for this block.
* @return {!Blockly.Block} The created block.
* @deprecated December 2015
*/
function obtain(workspace: Blockly.Workspace, prototypeName: string): Blockly.Block;
}
declare module Blockly.BlockSvg {
/**
* Horizontal space between elements.
* @const
*/
var SEP_SPACE_X: any /*missing*/;
/**
* Vertical space between elements.
* @const
*/
var SEP_SPACE_Y: any /*missing*/;
/**
* Vertical padding around inline elements.
* @const
*/
var INLINE_PADDING_Y: any /*missing*/;
/**
* Minimum height of a block.
* @const
*/
var MIN_BLOCK_Y: any /*missing*/;
/**
* Height of horizontal puzzle tab.
* @const
*/
var TAB_HEIGHT: any /*missing*/;
/**
* Width of horizontal puzzle tab.
* @const
*/
var TAB_WIDTH: any /*missing*/;
/**
* Width of vertical tab (inc left margin).
* @const
*/
var NOTCH_WIDTH: any /*missing*/;
/**
* Rounded corner radius.
* @const
*/
var CORNER_RADIUS: any /*missing*/;
/**
* Do blocks with no previous or output connections have a 'hat' on top?
* @const
*/
var START_HAT: any /*missing*/;
/**
* Height of the top hat.
* @const
*/
var START_HAT_HEIGHT: any /*missing*/;
/**
* Path of the top hat's curve.
* @const
*/
var START_HAT_PATH: any /*missing*/;
/**
* Path of the top hat's curve's highlight in LTR.
* @const
*/
var START_HAT_HIGHLIGHT_LTR: any /*missing*/;
/**
* Path of the top hat's curve's highlight in RTL.
* @const
*/
var START_HAT_HIGHLIGHT_RTL: any /*missing*/;
/**
* Distance from shape edge to intersect with a curved corner at 45 degrees.
* Applies to highlighting on around the inside of a curve.
* @const
*/
var DISTANCE_45_INSIDE: any /*missing*/;
/**
* Distance from shape edge to intersect with a curved corner at 45 degrees.
* Applies to highlighting on around the outside of a curve.
* @const
*/
var DISTANCE_45_OUTSIDE: any /*missing*/;
/**
* SVG path for drawing next/previous notch from left to right.
* @const
*/
var NOTCH_PATH_LEFT: any /*missing*/;
/**
* SVG path for drawing next/previous notch from left to right with
* highlighting.
* @const
*/
var NOTCH_PATH_LEFT_HIGHLIGHT: any /*missing*/;
/**
* SVG path for drawing next/previous notch from right to left.
* @const
*/
var NOTCH_PATH_RIGHT: any /*missing*/;
/**
* SVG path for drawing jagged teeth at the end of collapsed blocks.
* @const
*/
var JAGGED_TEETH: any /*missing*/;
/**
* Height of SVG path for jagged teeth at the end of collapsed blocks.
* @const
*/
var JAGGED_TEETH_HEIGHT: any /*missing*/;
/**
* Width of SVG path for jagged teeth at the end of collapsed blocks.
* @const
*/
var JAGGED_TEETH_WIDTH: any /*missing*/;
/**
* SVG path for drawing a horizontal puzzle tab from top to bottom.
* @const
*/
var TAB_PATH_DOWN: any /*missing*/;
/**
* SVG path for drawing a horizontal puzzle tab from top to bottom with
* highlighting from the upper-right.
* @const
*/
var TAB_PATH_DOWN_HIGHLIGHT_RTL: any /*missing*/;
/**
* SVG start point for drawing the top-left corner.
* @const
*/
var TOP_LEFT_CORNER_START: any /*missing*/;
/**
* SVG start point for drawing the top-left corner's highlight in RTL.
* @const
*/
var TOP_LEFT_CORNER_START_HIGHLIGHT_RTL: any /*missing*/;
/**
* SVG start point for drawing the top-left corner's highlight in LTR.
* @const
*/
var TOP_LEFT_CORNER_START_HIGHLIGHT_LTR: any /*missing*/;
/**
* SVG path for drawing the rounded top-left corner.
* @const
*/
var TOP_LEFT_CORNER: any /*missing*/;
/**
* SVG path for drawing the highlight on the rounded top-left corner.
* @const
*/
var TOP_LEFT_CORNER_HIGHLIGHT: any /*missing*/;
/**
* SVG path for drawing the top-left corner of a statement input.
* Includes the top notch, a horizontal space, and the rounded inside corner.
* @const
*/
var INNER_TOP_LEFT_CORNER: any /*missing*/;
/**
* SVG path for drawing the bottom-left corner of a statement input.
* Includes the rounded inside corner.
* @const
*/
var INNER_BOTTOM_LEFT_CORNER: any /*missing*/;
/**
* SVG path for drawing highlight on the top-left corner of a statement
* input in RTL.
* @const
*/
var INNER_TOP_LEFT_CORNER_HIGHLIGHT_RTL: any /*missing*/;
/**
* SVG path for drawing highlight on the bottom-left corner of a statement
* input in RTL.
* @const
*/
var INNER_BOTTOM_LEFT_CORNER_HIGHLIGHT_RTL: any /*missing*/;
/**
* SVG path for drawing highlight on the bottom-left corner of a statement
* input in LTR.
* @const
*/
var INNER_BOTTOM_LEFT_CORNER_HIGHLIGHT_LTR: any /*missing*/;
}
declare module Blockly.BlockSvg {
/**
* Constant for identifying rows that are to be rendered inline.
* Don't collide with Blockly.INPUT_VALUE and friends.
* @const
*/
var INLINE: any /*missing*/;
/**
* Wrapper function called when a mouseUp occurs during a drag operation.
* @type {Array.<!Array>}
* @private
*/
var onMouseUpWrapper_: any[][];
/**
* Wrapper function called when a mouseMove occurs during a drag operation.
* @type {Array.<!Array>}
* @private
*/
var onMouseMoveWrapper_: any[][];
/**
* Stop binding to the global mouseup and mousemove events.
* @package
*/
function terminateDrag(): void;
/**
* Animate a cloned block and eventually dispose of it.
* This is a class method, not an instace method since the original block has
* been destroyed and is no longer accessible.
* @param {!Element} clone SVG element to animate and dispose of.
* @param {boolean} rtl True if RTL, false if LTR.
* @param {!Date} start Date of animation's start.
* @param {number} workspaceScale Scale of workspace.
* @private
*/
function disposeUiStep_(clone: Element, rtl: boolean, start: Date, workspaceScale: number): void;
/**
* Expand a ripple around a connection.
* @param {!Element} ripple Element to animate.
* @param {!Date} start Date of animation's start.
* @param {number} workspaceScale Scale of workspace.
* @private
*/
function connectionUiStep_(ripple: Element, start: Date, workspaceScale: number): void;
/**
* Animate a brief wiggle of a disconnected block.
* @param {!Element} group SVG element to animate.
* @param {number} magnitude Maximum degrees skew (reversed for RTL).
* @param {!Date} start Date of animation's start.
* @private
*/
function disconnectUiStep_(group: Element, magnitude: number, start: Date): void;
/**
* Stop the disconnect UI animation immediately.
* @private
*/
function disconnectUiStop_(): void;
}
declare module Blockly.BlockSvg.disconnectUiStop_ {
/**
* PID of disconnect UI animation. There can only be one at a time.
* @type {number}
*/
var pid: number;
/**
* SVG group of wobbling block. There can only be one at a time.
* @type {Element}
*/
var group: Element;
}
declare module Blockly.Bubble {
/**
* Width of the border around the bubble.
*/
var BORDER_WIDTH: any /*missing*/;
/**
* Determines the thickness of the base of the arrow in relation to the size
* of the bubble. Higher numbers result in thinner arrows.
*/
var ARROW_THICKNESS: any /*missing*/;
/**
* The number of degrees that the arrow bends counter-clockwise.
*/
var ARROW_ANGLE: any /*missing*/;
/**
* The sharpness of the arrow's bend. Higher numbers result in smoother arrows.
*/
var ARROW_BEND: any /*missing*/;
/**
* Distance between arrow point and anchor point.
*/
var ANCHOR_RADIUS: any /*missing*/;
/**
* Wrapper function called when a mouseUp occurs during a drag operation.
* @type {Array.<!Array>}
* @private
*/
var onMouseUpWrapper_: any[][];
/**
* Wrapper function called when a mouseMove occurs during a drag operation.
* @type {Array.<!Array>}
* @private
*/
var onMouseMoveWrapper_: any[][];
/**
* Stop binding to the global mouseup and mousemove events.
* @private
*/
function unbindDragEvents_(): void;
}
declare module Blockly.ConnectionDB {
/**
* Don't inherit the constructor from Array.
* @type {!Function}
*/
var constructor: Function;
/**
* Initialize a set of connection DBs for a specified workspace.
* @param {!Blockly.Workspace} workspace The workspace this DB is for.
*/
function init(workspace: Blockly.Workspace): void;
}
declare module Blockly.Connection {
/**
* Constants for checking whether two connections are compatible.
*/
var CAN_CONNECT: any /*missing*/;
/**
* Update two connections to target each other.
* @param {Blockly.Connection} first The first connection to update.
* @param {Blockly.Connection} second The second conneciton to update.
* @private
*/
function connectReciprocally_(first: Blockly.Connection, second: Blockly.Connection): void;
/**
* Does the given block have one and only one connection point that will accept
* an orphaned block?
* @param {!Blockly.Block} block The superior block.
* @param {!Blockly.Block} orphanBlock The inferior block.
* @return {Blockly.Connection} The suitable connection point on 'block',
* or null.
* @private
*/
function singleConnection_(block: Blockly.Block, orphanBlock: Blockly.Block): Blockly.Connection;
/**
* Walks down a row a blocks, at each stage checking if there are any
* connections that will accept the orphaned block. If at any point there
* are zero or multiple eligible connections, returns null. Otherwise
* returns the only input on the last block in the chain.
* Terminates early for shadow blocks.
* @param {!Blockly.Block} startBlock The block on which to start the search.
* @param {!Blockly.Block} orphanBlock The block that is looking for a home.
* @return {Blockly.Connection} The suitable connection point on the chain
* of blocks, or null.
* @private
*/
function lastConnectionInRow_(startBlock: Blockly.Block, orphanBlock: Blockly.Block): Blockly.Connection;
}
declare module Blockly.ContextMenu {
/**
* Which block is the context menu attached to?
* @type {Blockly.Block}
*/
var currentBlock: Blockly.Block;
/**
* Construct the menu based on the list of options and show the menu.
* @param {!Event} e Mouse event.
* @param {!Array.<!Object>} options Array of menu options.
* @param {boolean} rtl True if RTL, false if LTR.
*/
function show(e: Event, options: Object[], rtl: boolean): void;
/**
* Hide the context menu.
*/
function hide(): void;
/**
* Create a callback function that creates and configures a block,
* then places the new block next to the original.
* @param {!Blockly.Block} block Original block.
* @param {!Element} xml XML representation of new block.
* @return {!Function} Function that creates a block.
*/
function callbackFactory(block: Blockly.Block, xml: Element): Function;
}
declare module Blockly.Css {
/**
* List of cursors.
* @enum {string}
*/
enum Cursor { OPEN, CLOSED, DELETE }
/**
* Current cursor (cached value).
* @type {string}
* @private
*/
var currentCursor_: string;
/**
* Large stylesheet added by Blockly.Css.inject.
* @type {Element}
* @private
*/
var styleSheet_: Element;
/**
* Path to media directory, with any trailing slash removed.
* @type {string}
* @private
*/
var mediaPath_: string;
/**
* Inject the CSS into the DOM. This is preferable over using a regular CSS
* file since:
* a) It loads synchronously and doesn't force a redraw later.
* b) It speeds up loading by not blocking on a separate HTTP transfer.
* c) The CSS content may be made dynamic depending on init options.
* @param {boolean} hasCss If false, don't inject CSS
* (providing CSS becomes the document's responsibility).
* @param {string} pathToMedia Path from page to the Blockly media directory.
*/
function inject(hasCss: boolean, pathToMedia: string): void;
/**
* Set the cursor to be displayed when over something draggable.
* @param {Blockly.Css.Cursor} cursor Enum.
*/
function setCursor(cursor: Blockly.Css.Cursor): void;
/**
* Array making up the CSS content for Blockly.
*/
var CONTENT: any /*missing*/;
}
declare module Blockly.Events {
class Abstract extends Abstract__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class Abstract__Class {
/**
* Abstract class for an event.
* @param {Blockly.Block} block The block.
* @constructor
*/
constructor(block: Blockly.Block);
/**
* Encode the event as JSON.
* @return {!Object} JSON representation.
*/
toJson(): Object;
/**
* Decode the JSON event.
* @param {!Object} json JSON representation.
*/
fromJson(json: Object): void;
/**
* Does this event record any change of state?
* @return {boolean} True if null, false if something changed.
*/
isNull(): boolean;
/**
* Run an event.
* @param {boolean} forward True if run forward, false if run backward (undo).
*/
run(forward: boolean): void;
}
class Create extends Create__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class Create__Class extends Blockly.Events.Abstract__Class {
/**
* Class for a block creation event.
* @param {Blockly.Block} block The created block. Null for a blank event.
* @extends {Blockly.Events.Abstract}
* @constructor
*/
constructor(block: Blockly.Block);
/**
* Type of this event.
* @type {string}
*/
type: string;
/**
* Encode the event as JSON.
* @return {!Object} JSON representation.
*/
toJson(): Object;
/**
* Decode the JSON event.
* @param {!Object} json JSON representation.
*/
fromJson(json: Object): void;
/**
* Run a creation event.
* @param {boolean} forward True if run forward, false if run backward (undo).
*/
run(forward: boolean): void;
}
class Delete extends Delete__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class Delete__Class extends Blockly.Events.Abstract__Class {
/**
* Class for a block deletion event.
* @param {Blockly.Block} block The deleted block. Null for a blank event.
* @extends {Blockly.Events.Abstract}
* @constructor
*/
constructor(block: Blockly.Block);
/**
* Type of this event.
* @type {string}
*/
type: string;
/**
* Encode the event as JSON.
* @return {!Object} JSON representation.
*/
toJson(): Object;
/**
* Decode the JSON event.
* @param {!Object} json JSON representation.
*/
fromJson(json: Object): void;
/**
* Run a deletion event.
* @param {boolean} forward True if run forward, false if run backward (undo).
*/
run(forward: boolean): void;
}
class Change extends Change__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class Change__Class extends Blockly.Events.Abstract__Class {
/**
* Class for a block change event.
* @param {Blockly.Block} block The changed block. Null for a blank event.
* @param {string} element One of 'field', 'comment', 'disabled', etc.
* @param {?string} name Name of input or field affected, or null.
* @param {string} oldValue Previous value of element.
* @param {string} newValue New value of element.
* @extends {Blockly.Events.Abstract}
* @constructor
*/
constructor(block: Blockly.Block, element: string, name: string, oldValue: string, newValue: string);
/**
* Type of this event.
* @type {string}
*/
type: string;
/**
* Encode the event as JSON.
* @return {!Object} JSON representation.
*/
toJson(): Object;
/**
* Decode the JSON event.
* @param {!Object} json JSON representation.
*/
fromJson(json: Object): void;
/**
* Does this event record any change of state?
* @return {boolean} True if something changed.
*/
isNull(): boolean;
/**
* Run a change event.
* @param {boolean} forward True if run forward, false if run backward (undo).
*/
run(forward: boolean): void;
}
class Move extends Move__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class Move__Class extends Blockly.Events.Abstract__Class {
/**
* Class for a block move event. Created before the move.
* @param {Blockly.Block} block The moved block. Null for a blank event.
* @extends {Blockly.Events.Abstract}
* @constructor
*/
constructor(block: Blockly.Block);
/**
* Type of this event.
* @type {string}
*/
type: string;
/**
* Encode the event as JSON.
* @return {!Object} JSON representation.
*/
toJson(): Object;
/**
* Decode the JSON event.
* @param {!Object} json JSON representation.
*/
fromJson(json: Object): void;
/**
* Record the block's new location. Called after the move.
*/
recordNew(): void;
/**
* Returns the parentId and input if the block is connected,
* or the XY location if disconnected.
* @return {!Object} Collection of location info.
* @private
*/
currentLocation_(): Object;
/**
* Does this event record any change of state?
* @return {boolean} True if something changed.
*/
isNull(): boolean;
/**
* Run a move event.
* @param {boolean} forward True if run forward, false if run backward (undo).
*/
run(forward: boolean): void;
}
class Ui extends Ui__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class Ui__Class extends Blockly.Events.Abstract__Class {
/**
* Class for a UI event.
* @param {Blockly.Block} block The affected block.
* @param {string} element One of 'selected', 'comment', 'mutator', etc.
* @param {string} oldValue Previous value of element.
* @param {string} newValue New value of element.
* @extends {Blockly.Events.Abstract}
* @constructor
*/
constructor(block: Blockly.Block, element: string, oldValue: string, newValue: string);
/**
* Type of this event.
* @type {string}
*/
type: string;
/**
* Encode the event as JSON.
* @return {!Object} JSON representation.
*/
toJson(): Object;
/**
* Decode the JSON event.
* @param {!Object} json JSON representation.
*/
fromJson(json: Object): void;
}
/**
* Group ID for new events. Grouped events are indivisible.
* @type {string}
* @private
*/
var group_: string;
/**
* Sets whether events should be added to the undo stack.
* @type {boolean}
*/
var recordUndo: boolean;
/**
* Allow change events to be created and fired.
* @type {number}
* @private
*/
var disabled_: number;
/**
* Name of event that creates a block.
* @const
*/
var CREATE: any /*missing*/;
/**
* Name of event that deletes a block.
* @const
*/
var DELETE: any /*missing*/;
/**
* Name of event that changes a block.
* @const
*/
var CHANGE: any /*missing*/;
/**
* Name of event that moves a block.
* @const
*/
var MOVE: any /*missing*/;
/**
* Name of event that records a UI change.
* @const
*/
var UI: any /*missing*/;
/**
* List of events queued for firing.
* @private
*/
var FIRE_QUEUE_: any /*missing*/;
/**
* Create a custom event and fire it.
* @param {!Blockly.Events.Abstract} event Custom data for event.
*/
function fire(event: Blockly.Events.Abstract): void;
/**
* Fire all queued events.
* @private
*/
function fireNow_(): void;
/**
* Filter the queued events and merge duplicates.
* @param {!Array.<!Blockly.Events.Abstract>} queueIn Array of events.
* @param {boolean} forward True if forward (redo), false if backward (undo).
* @return {!Array.<!Blockly.Events.Abstract>} Array of filtered events.
*/
function filter(queueIn: Blockly.Events.Abstract[], forward: boolean): Blockly.Events.Abstract[];
/**
* Modify pending undo events so that when they are fired they don't land
* in the undo stack. Called by Blockly.Workspace.clearUndo.
*/
function clearPendingUndo(): void;
/**
* Stop sending events. Every call to this function MUST also call enable.
*/
function disable(): void;
/**
* Start sending events. Unless events were already disabled when the
* corresponding call to disable was made.
*/
function enable(): void;
/**
* Returns whether events may be fired or not.
* @return {boolean} True if enabled.
*/
function isEnabled(): boolean;
/**
* Current group.
* @return {string} ID string.
*/
function getGroup(): string;
/**
* Start or stop a group.
* @param {boolean|string} state True to start new group, false to end group.
* String to set group explicitly.
*/
function setGroup(state: boolean|string): void;
/**
* Compute a list of the IDs of the specified block and all its descendants.
* @param {!Blockly.Block} block The root block.
* @return {!Array.<string>} List of block IDs.
* @private
*/
function getDescendantIds_(block: Blockly.Block): string[];
/**
* Decode the JSON into an event.
* @param {!Object} json JSON representation.
* @param {!Blockly.Workspace} workspace Target workspace for event.
* @return {!Blockly.Events.Abstract} The event represented by the JSON.
*/
function fromJson(json: Object, workspace: Blockly.Workspace): Blockly.Events.Abstract;
/**
* Enable/disable a block depending on whether it is properly connected.
* Use this on applications where all blocks should be connected to a top block.
* Recommend setting the 'disable' option to 'false' in the config so that
* users don't try to reenable disabled orphan blocks.
* @param {!Blockly.Events.Abstract} event Custom data for event.
*/
function disableOrphans(event: Blockly.Events.Abstract): void;
}
declare module Blockly.FieldAngle {
/**
* Round angles to the nearest 15 degrees when using mouse.
* Set to 0 to disable rounding.
*/
var ROUND: any /*missing*/;
/**
* Half the width of protractor image.
*/
var HALF: any /*missing*/;
/**
* Angle increases clockwise (true) or counterclockwise (false).
*/
var CLOCKWISE: any /*missing*/;
/**
* Offset the location of 0 degrees (and all angles) by a constant.
* Usually either 0 (0 = right) or 90 (0 = up).
*/
var OFFSET: any /*missing*/;
/**
* Maximum allowed angle before wrapping.
* Usually either 360 (for 0 to 359.9) or 180 (for -179.9 to 180).
*/
var WRAP: any /*missing*/;
/**
* Radius of protractor circle. Slightly smaller than protractor size since
* otherwise SVG crops off half the border at the edges.
*/
var RADIUS: any /*missing*/;
}
declare module Blockly.FieldCheckbox {
/**
* Character for the checkmark.
*/
var CHECK_CHAR: any /*missing*/;
}
declare module Blockly.FieldColour {
/**
* An array of colour strings for the palette.
* See bottom of this page for the default:
* http://docs.closure-library.googlecode.com/git/closure_goog_ui_colorpicker.js.source.html
* @type {!Array.<string>}
*/
var COLOURS: string[];
/**
* Number of columns in the palette.
*/
var COLUMNS: any /*missing*/;
/**
* Hide the colour palette.
* @private
*/
function widgetDispose_(): void;
}
declare module Blockly.FieldDate {
/**
* Hide the date picker.
* @private
*/
function widgetDispose_(): void;
/**
* Load the best language pack by scanning the Blockly.Msg object for a
* language that matches the available languages in Closure.
* @private
*/
function loadLanguage_(): void;
/**
* CSS for date picker. See css.js for use.
*/
var CSS: any /*missing*/;
}
declare module Blockly.FieldDropdown {
/**
* Horizontal distance that a checkmark ovehangs the dropdown.
*/
var CHECKMARK_OVERHANG: any /*missing*/;
/**
* Android can't (in 2014) display "▾", so use "▼" instead.
*/
var ARROW_CHAR: any /*missing*/;
}
declare module Blockly.Field {
/**
* Temporary cache of text widths.
* @type {Object}
* @private
*/
var cacheWidths_: Object;
/**
* Number of current references to cache.
* @type {number}
* @private
*/
var cacheReference_: number;
/**
* Non-breaking space.
* @const
*/
var NBSP: any /*missing*/;
/**
* Start caching field widths. Every call to this function MUST also call
* stopCache. Caches must not survive between execution threads.
*/
function startCache(): void;
/**
* Stop caching field widths. Unless caching was already on when the
* corresponding call to startCache was made.
*/
function stopCache(): void;
}
declare module Blockly.FieldTextInput {
/**
* Point size of text. Should match blocklyText's font-size in CSS.
*/
var FONTSIZE: any /*missing*/;
/** @type {!HTMLInputElement} */
var htmlInput_: HTMLInputElement;
/**
* Ensure that only a number may be entered.
* @param {string} text The user's text.
* @return {?string} A string representing a valid number, or null if invalid.
*/
function numberValidator(text: string): string;
/**
* Ensure that only a nonnegative integer may be entered.
* @param {string} text The user's text.
* @return {?string} A string representing a valid int, or null if invalid.
*/
function nonnegativeIntegerValidator(text: string): string;
}
declare module Blockly.FieldVariable {
/**
* Return a sorted list of variable names for variable dropdown menus.
* Include a special option at the end for creating a new variable name.
* @return {!Array.<string>} Array of variable names.
* @this {!Blockly.FieldVariable}
*/
function dropdownCreate(): string[];
}
declare module Blockly.FlyoutButton {
/**
* The margin around the text in the button.
*/
var MARGIN: any /*missing*/;
}
declare module Blockly.Flyout {
/**
* When a flyout drag is in progress, this is a reference to the flyout being
* dragged. This is used by Flyout.terminateDrag_ to reset dragMode_.
* @type {Blockly.Flyout}
* @private
*/
var startFlyout_: Blockly.Flyout;
/**
* Event that started a drag. Used to determine the drag distance/direction and
* also passed to BlockSvg.onMouseDown_() after creating a new block.
* @type {Event}
* @private
*/
var startDownEvent_: Event;
/**
* Flyout block where the drag/click was initiated. Used to fire click events or
* create a new block.
* @type {Event}
* @private
*/
var startBlock_: Event;
/**
* Wrapper function called when a mouseup occurs during a background or block
* drag operation.
* @type {Array.<!Array>}
* @private
*/
var onMouseUpWrapper_: any[][];
/**
* Wrapper function called when a mousemove occurs during a background drag.
* @type {Array.<!Array>}
* @private
*/
var onMouseMoveWrapper_: any[][];
/**
* Wrapper function called when a mousemove occurs during a block drag.
* @type {Array.<!Array>}
* @private
*/
var onMouseMoveBlockWrapper_: any[][];
/**
* Actions to take when a block in the flyout is right-clicked.
* @param {!Event} e Event that triggered the right-click. Could originate from
* a long-press in a touch environment.
* @param {Blockly.BlockSvg} block The block that was clicked.
*/
function blockRightClick_(e: Event, block: Blockly.BlockSvg): void;
/**
* Stop binding to the global mouseup and mousemove events.
* @private
*/
function terminateDrag_(): void;
}
declare module Blockly.Generator {
/**
* Category to separate generated function names from variables and procedures.
*/
var NAME_TYPE: any /*missing*/;
}
declare module Blockly.inject {
/**
* Bind document events, but only once. Destroying and reinjecting Blockly
* should not bind again.
* Bind events for scrolling the workspace.
* Most of these events should be bound to the SVG's surface.
* However, 'mouseup' has to be on the whole document so that a block dragged
* out of bounds and released will know that it has been released.
* Also, 'keydown' has to be on the whole document since the browser doesn't
* understand a concept of focus on the SVG image.
* @private
*/
function bindDocumentEvents_(): void;
/**
* Load sounds for the given workspace.
* @param {string} pathToMedia The path to the media directory.
* @param {!Blockly.Workspace} workspace The workspace to load sounds for.
* @private
*/
function loadSounds_(pathToMedia: string, workspace: Blockly.Workspace): void;
}
declare module goog {
/**
* Back up original getMsg function.
* @type {!Function}
*/
var getMsgOrig: Function;
/**
* Gets a localized message.
* Overrides the default Closure function to check for a Blockly.Msg first.
* Used infrequently, only known case is TODAY button in date picker.
* @param {string} str Translatable string, places holders in the form {$foo}.
* @param {Object<string, string>=} opt_values Maps place holder name to value.
* @return {string} message with placeholders filled.
* @suppress {duplicate}
*/
function getMsg(str: string, opt_values?: { [key: string]: string }): string;
}
declare module goog.getMsg {
/**
* Mapping of Closure messages to Blockly.Msg names.
*/
var blocklyMsgMap: any /*missing*/;
}
declare module Blockly.Mutator {
/**
* Reconnect an block to a mutated input.
* @param {Blockly.Connection} connectionChild Connection on child block.
* @param {!Blockly.Block} block Parent block.
* @param {string} inputName Name of input on parent block.
* @return {boolean} True iff a reconnection was made, false otherwise.
*/
function reconnect(connectionChild: Blockly.Connection, block: Blockly.Block, inputName: string): boolean;
}
declare module Blockly.Names {
/**
* Do the given two entity names refer to the same entity?
* Blockly names are case-insensitive.
* @param {string} name1 First name.
* @param {string} name2 Second name.
* @return {boolean} True if names are the same.
*/
function equals(name1: string, name2: string): boolean;
}
declare module Blockly.Options {
/**
* Parse the user-specified zoom options, using reasonable defaults where
* behaviour is unspecified. See zoom documentation:
* https://developers.google.com/blockly/guides/configure/web/zoom
* @param {!Object} options Dictionary of options.
* @return {!Object} A dictionary of normalized options.
* @private
*/
function parseZoomOptions_(options: Object): Object;
/**
* Parse the user-specified grid options, using reasonable defaults where
* behaviour is unspecified. See grid documentation:
* https://developers.google.com/blockly/guides/configure/web/grid
* @param {!Object} options Dictionary of options.
* @return {!Object} A dictionary of normalized options.
* @private
*/
function parseGridOptions_(options: Object): Object;
/**
* Parse the provided toolbox tree into a consistent DOM format.
* @param {Node|string} tree DOM tree of blocks, or text representation of same.
* @return {Node} DOM tree of blocks, or null.
*/
function parseToolboxTree(tree: Node|string): Node;
}
declare module Blockly.Procedures {
/**
* Category to separate procedure names from variables and generated functions.
*/
var NAME_TYPE: any /*missing*/;
/**
* Find all user-created procedure definitions in a workspace.
* @param {!Blockly.Workspace} root Root workspace.
* @return {!Array.<!Array.<!Array>>} Pair of arrays, the
* first contains procedures without return variables, the second with.
* Each procedure is defined by a three-element list of name, parameter
* list, and return value boolean.
*/
function allProcedures(root: Blockly.Workspace): any[][][];
/**
* Comparison function for case-insensitive sorting of the first element of
* a tuple.
* @param {!Array} ta First tuple.
* @param {!Array} tb Second tuple.
* @return {number} -1, 0, or 1 to signify greater than, equality, or less than.
* @private
*/
function procTupleComparator_(ta: any[], tb: any[]): number;
/**
* Ensure two identically-named procedures don't exist.
* @param {string} name Proposed procedure name.
* @param {!Blockly.Block} block Block to disambiguate.
* @return {string} Non-colliding name.
*/
function findLegalName(name: string, block: Blockly.Block): string;
/**
* Does this procedure have a legal name? Illegal names include names of
* procedures already defined.
* @param {string} name The questionable name.
* @param {!Blockly.Workspace} workspace The workspace to scan for collisions.
* @param {Blockly.Block=} opt_exclude Optional block to exclude from
* comparisons (one doesn't want to collide with oneself).
* @return {boolean} True if the name is legal.
* @private
*/
function isLegalName_(name: string, workspace: Blockly.Workspace, opt_exclude?: Blockly.Block): boolean;
/**
* Rename a procedure. Called by the editable field.
* @param {string} name The proposed new name.
* @return {string} The accepted name.
* @this {!Blockly.Field}
*/
function rename(name: string): string;
/**
* Construct the blocks required by the flyout for the procedure category.
* @param {!Blockly.Workspace} workspace The workspace contianing procedures.
* @return {!Array.<!Element>} Array of XML block elements.
*/
function flyoutCategory(workspace: Blockly.Workspace): Element[];
/**
* Find all the callers of a named procedure.
* @param {string} name Name of procedure.
* @param {!Blockly.Workspace} workspace The workspace to find callers in.
* @return {!Array.<!Blockly.Block>} Array of caller blocks.
*/
function getCallers(name: string, workspace: Blockly.Workspace): Blockly.Block[];
/**
* When a procedure definition changes its parameters, find and edit all its
* callers.
* @param {!Blockly.Block} defBlock Procedure definition block.
*/
function mutateCallers(defBlock: Blockly.Block): void;
/**
* Find the definition block for the named procedure.
* @param {string} name Name of procedure.
* @param {!Blockly.Workspace} workspace The workspace to search.
* @return {Blockly.Block} The procedure definition block, or null not found.
*/
function getDefinition(name: string, workspace: Blockly.Workspace): Blockly.Block;
}
declare module Blockly.Scrollbar {
/**
* Width of vertical scrollbar or height of horizontal scrollbar.
* Increase the size of scrollbars on touch devices.
* Don't define if there is no document object (e.g. node.js).
*/
var scrollbarThickness: any /*missing*/;
/**
* @param {!Object} first An object containing computed measurements of a
* workspace.
* @param {!Object} second Another object containing computed measurements of a
* workspace.
* @return {boolean} Whether the two sets of metrics are equivalent.
* @private
*/
function metricsAreEquivalent_(first: Object, second: Object): boolean;
/**
* Insert a node after a reference node.
* Contrast with node.insertBefore function.
* @param {!Element} newNode New element to insert.
* @param {!Element} refNode Existing element to precede new node.
* @private
*/
function insertAfter_(newNode: Element, refNode: Element): void;
}
declare module Blockly.Toolbox {
class TreeControl extends TreeControl__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class TreeControl__Class extends goog.ui.tree.TreeControl {
/**
* Extention of a TreeControl object that uses a custom tree node.
* @param {Blockly.Toolbox} toolbox The parent toolbox for this tree.
* @param {Object} config The configuration for the tree. See
* goog.ui.tree.TreeControl.DefaultConfig.
* @constructor
* @extends {goog.ui.tree.TreeControl}
*/
constructor(toolbox: Blockly.Toolbox, config: Object);
/**
* Handles touch events.
* @param {!goog.events.BrowserEvent} e The browser event.
* @private
*/
handleTouchEvent_(e: goog.events.BrowserEvent): void;
}
class TreeNode extends TreeNode__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class TreeNode__Class extends goog.ui.tree.TreeNode {
/**
* A single node in the tree, customized for Blockly's UI.
* @param {Blockly.Toolbox} toolbox The parent toolbox for this tree.
* @param {!goog.html.SafeHtml} html The HTML content of the node label.
* @param {Object=} opt_config The configuration for the tree. See
* goog.ui.tree.TreeControl.DefaultConfig. If not specified, a default config
* will be used.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
* @constructor
* @extends {goog.ui.tree.TreeNode}
*/
constructor(toolbox: Blockly.Toolbox, html: goog.html.SafeHtml, opt_config?: Object, opt_domHelper?: goog.dom.DomHelper);
}
class TreeSeparator extends TreeSeparator__Class { }
/** Fake class which should be extended to avoid inheriting static properties */
class TreeSeparator__Class extends Blockly.Toolbox.TreeNode__Class {
/**
* A blank separator node in the tree.
* @param {Object=} config The configuration for the tree. See
* goog.ui.tree.TreeControl.DefaultConfig. If not specified, a default config
* will be used.
* @constructor
* @extends {Blockly.Toolbox.TreeNode}
*/
constructor(config?: Object);
}
}
declare module Blockly.Tooltip {
/**
* Is a tooltip currently showing?
*/
var visible: any /*missing*/;
/**
* Maximum width (in characters) of a tooltip.
*/
var LIMIT: any /*missing*/;
/**
* PID of suspended thread to clear tooltip on mouse out.
* @private
*/
var mouseOutPid_: any /*missing*/;
/**
* PID of suspended thread to show the tooltip.
* @private
*/
var showPid_: any /*missing*/;
/**
* Last observed X location of the mouse pointer (freezes when tooltip appears).
* @private
*/
var lastX_: any /*missing*/;
/**
* Last observed Y location of the mouse pointer (freezes when tooltip appears).
* @private
*/
var lastY_: any /*missing*/;
/**
* Current element being pointed at.
* @private
*/
var element_: any /*missing*/;
/**
* Once a tooltip has opened for an element, that element is 'poisoned' and
* cannot respawn a tooltip until the pointer moves over a different element.
* @private
*/
var poisonedElement_: any /*missing*/;
/**
* Horizontal offset between mouse cursor and tooltip.
*/
var OFFSET_X: any /*missing*/;
/**
* Vertical offset between mouse cursor and tooltip.
*/
var OFFSET_Y: any /*missing*/;
/**
* Radius mouse can move before killing tooltip.
*/
var RADIUS_OK: any /*missing*/;
/**
* Delay before tooltip appears.
*/
var HOVER_MS: any /*missing*/;
/**
* Horizontal padding between tooltip and screen edge.
*/
var MARGINS: any /*missing*/;
/**
* The HTML container. Set once by Blockly.Tooltip.createDom.
* @type {Element}
*/
var DIV: Element;
/**
* Create the tooltip div and inject it onto the page.
*/
function createDom(): void;
/**
* Binds the required mouse events onto an SVG element.
* @param {!Element} element SVG element onto which tooltip is to be bound.
*/
function bindMouseEvents(element: Element): void;
/**
* Hide the tooltip if the mouse is over a different object.
* Initialize the tooltip to potentially appear for this object.
* @param {!Event} e Mouse event.
* @private
*/
function onMouseOver_(e: Event): void;
/**
* Hide the tooltip if the mouse leaves the object and enters the workspace.
* @param {!Event} e Mouse event.
* @private
*/
function onMouseOut_(e: Event): void;
/**
* When hovering over an element, schedule a tooltip to be shown. If a tooltip
* is already visible, hide it if the mouse strays out of a certain radius.
* @param {!Event} e Mouse event.
* @private
*/
function onMouseMove_(e: Event): void;
/**
* Hide the tooltip.
*/
function hide(): void;
/**
* Create the tooltip and show it.
* @private
*/
function show_(): void;
}
declare module Blockly.Touch {
/**
* Which touch events are we currently paying attention to?
* @type {DOMString}
* @private
*/
var touchIdentifier_: any;
/**
* Wrapper function called when a touch mouseUp occurs during a drag operation.
* @type {Array.<!Array>}
* @private
*/
var onTouchUpWrapper_: any[][];
/**
* The TOUCH_MAP lookup dictionary specifies additional touch events to fire,
* in conjunction with mouse events.
* @type {Object}
*/
var TOUCH_MAP: Object;
/**
* Clear the touch identifier that tracks which touch stream to pay attention
* to. This ends the current drag/gesture and allows other pointers to be
* captured.
*/
function clearTouchIdentifier(): void;
/**
* Decide whether Blockly should handle or ignore this event.
* Mouse and touch events require special checks because we only want to deal
* with one touch stream at a time. All other events should always be handled.
* @param {!Event} e The event to check.
* @return {boolean} True if this event should be passed through to the
* registered handler; false if it should be blocked.
*/
function shouldHandleEvent(e: Event): boolean;
/**
* Check whether the touch identifier on the event matches the current saved
* identifier. If there is no identifier, that means it's a mouse event and
* we'll use the identifier "mouse". This means we won't deal well with
* multiple mice being used at the same time. That seems okay.
* If the current identifier was unset, save the identifier from the
* event. This starts a drag/gesture, during which touch events with other
* identifiers will be silently ignored.
* @param {!Event} e Mouse event or touch event.
* @return {boolean} Whether the identifier on the event matches the current
* saved identifier.
*/
function checkTouchIdentifier(e: Event): boolean;
/**
* Set an event's clientX and clientY from its first changed touch. Use this to
* make a touch event work in a mouse event handler.
* @param {!Event} e A touch event.
*/
function setClientFromTouch(e: Event): void;
/**
* Check whether a given event is a mouse or touch event.
* @param {!Event} e An event.
* @return {boolean} true if it is a mouse or touch event; false otherwise.
*/
function isMouseOrTouchEvent(e: Event): boolean;
/**
* Split an event into an array of events, one per changed touch or mouse
* point.
* @param {!Event} e A mouse event or a touch event with one or more changed
* touches.
* @return {!Array.<!Event>} An array of mouse or touch events. Each touch
* event will have exactly one changed touch.
*/
function splitEventByTouches(e: Event): Event[];
}
declare module Blockly.getRelativeXY_ {
/**
* Static regex to pull the x,y values out of an SVG translate() directive.
* Note that Firefox and IE (9,10) return 'translate(12)' instead of
* 'translate(12, 0)'.
* Note that IE (9,10) returns 'translate(16 8)' instead of 'translate(16, 8)'.
* Note that IE has been reported to return scientific notation (0.123456e-42).
* @type {!RegExp}
* @private
*/
var XY_REGEXP_: RegExp;
}
declare module Blockly.utils {
/**
* Parse a string with any number of interpolation tokens (%1, %2, ...).
* '%' characters may be self-escaped (%%).
* @param {string} message Text containing interpolation tokens.
* @return {!Array.<string|number>} Array of strings and numbers.
*/
function tokenizeInterpolation(message: string): string|number[];
/**
* Wrap text to the specified width.
* @param {string} text Text to wrap.
* @param {number} limit Width to wrap each line.
* @return {string} Wrapped text.
*/
function wrap(text: string, limit: number): string;
/**
* Wrap single line of text to the specified width.
* @param {string} text Text to wrap.
* @param {number} limit Width to wrap each line.
* @return {string} Wrapped text.
* @private
*/
function wrap_line_(text: string, limit: number): string;
/**
* Compute a score for how good the wrapping is.
* @param {!Array.<string>} words Array of each word.
* @param {!Array.<boolean>} wordBreaks Array of line breaks.
* @param {number} limit Width to wrap each line.
* @return {number} Larger the better.
* @private
*/
function wrapScore_(words: string[], wordBreaks: boolean[], limit: number): number;
/**
* Mutate the array of line break locations until an optimal solution is found.
* No line breaks are added or deleted, they are simply moved around.
* @param {!Array.<string>} words Array of each word.
* @param {!Array.<boolean>} wordBreaks Array of line breaks.
* @param {number} limit Width to wrap each line.
* @return {!Array.<boolean>} New array of optimal line breaks.
* @private
*/
function wrapMutate_(words: string[], wordBreaks: boolean[], limit: number): boolean[];
/**
* Reassemble the array of words into text, with the specified line breaks.
* @param {!Array.<string>} words Array of each word.
* @param {!Array.<boolean>} wordBreaks Array of line breaks.
* @return {string} Plain text.
* @private
*/
function wrapToText_(words: string[], wordBreaks: boolean[]): string;
}
declare module Blockly.genUid {
/**
* Legal characters for the unique ID. Should be all on a US keyboard.
* No characters that conflict with XML or JSON. Requests to remove additional
* 'problematic' characters from this soup will be denied. That's your failure
* to properly escape in your own environment. Issues #251, #625, #682.
* @private
*/
var soup_: any /*missing*/;
}
declare module Blockly.Variables {
/**
* Category to separate variable names from procedures and generated functions.
*/
var NAME_TYPE: any /*missing*/;
/**
* Find all user-created variables that are in use in the workspace.
* For use by generators.
* @param {!Blockly.Block|!Blockly.Workspace} root Root block or workspace.
* @return {!Array.<string>} Array of variable names.
*/
function allUsedVariables(root: Blockly.Block|Blockly.Workspace): string[];
/**
* Find all variables that the user has created through the workspace or
* toolbox. For use by generators.
* @param {!Blockly.Workspace} root The workspace to inspect.
* @return {!Array.<string>} Array of variable names.
*/
function allVariables(root: Blockly.Workspace): string[];
/**
* Construct the blocks required by the flyout for the variable category.
* @param {!Blockly.Workspace} workspace The workspace contianing variables.
* @return {!Array.<!Element>} Array of XML block elements.
*/
function flyoutCategory(workspace: Blockly.Workspace): Element[];
/**
* Return a new variable name that is not yet being used. This will try to
* generate single letter variable names in the range 'i' to 'z' to start with.
* If no unique name is located it will try 'i' to 'z', 'a' to 'h',
* then 'i2' to 'z2' etc. Skip 'l'.
* @param {!Blockly.Workspace} workspace The workspace to be unique in.
* @return {string} New variable name.
*/
function generateUniqueName(workspace: Blockly.Workspace): string;
/**
* Create a new variable on the given workspace.
* @param {!Blockly.Workspace} workspace The workspace on which to create the
* variable.
* @return {null|undefined|string} An acceptable new variable name, or null if
* change is to be aborted (cancel button), or undefined if an existing
* variable was chosen.
*/
function createVariable(workspace: Blockly.Workspace): any /*null*/|any /*undefined*/|string;
/**
* Prompt the user for a new variable name.
* @param {string} promptText The string of the prompt.
* @param {string} defaultText The default value to show in the prompt's field.
* @return {?string} The new variable name, or null if the user picked
* something illegal.
*/
function promptName(promptText: string, defaultText: string): string;
}
declare module Blockly.Warning {
/**
* Create the text for the warning's bubble.
* @param {string} text The text to display.
* @return {!SVGTextElement} The top-level node of the text.
* @private
*/
function textToDom_(text: string): SVGTextElement;
}
declare module Blockly.WidgetDiv {
/**
* The HTML container. Set once by Blockly.WidgetDiv.createDom.
* @type {Element}
*/
var DIV: Element;
/**
* The object currently using this container.
* @type {Object}
* @private
*/
var owner_: Object;
/**
* Optional cleanup function set by whichever object uses the widget.
* @type {Function}
* @private
*/
var dispose_: Function;
/**
* Create the widget div and inject it onto the page.
*/
function createDom(): void;
/**
* Initialize and display the widget div. Close the old one if needed.
* @param {!Object} newOwner The object that will be using this container.
* @param {boolean} rtl Right-to-left (true) or left-to-right (false).
* @param {Function} dispose Optional cleanup function to be run when the widget
* is closed.
*/
function show(newOwner: Object, rtl: boolean, dispose: Function): void;
/**
* Destroy the widget and hide the div.
*/
function hide(): void;
/**
* Is the container visible?
* @return {boolean} True if visible.
*/
function isVisible(): boolean;
/**
* Destroy the widget and hide the div if it is being used by the specified
* object.
* @param {!Object} oldOwner The object that was using this container.
*/
function hideIfOwner(oldOwner: Object): void;
/**
* Position the widget at a given location. Prevent the widget from going
* offscreen top or left (right in RTL).
* @param {number} anchorX Horizontal location (window coorditates, not body).
* @param {number} anchorY Vertical location (window coorditates, not body).
* @param {!goog.math.Size} windowSize Height/width of window.
* @param {!goog.math.Coordinate} scrollOffset X/y of window scrollbars.
* @param {boolean} rtl True if RTL, false if LTR.
*/
function position(anchorX: number, anchorY: number, windowSize: goog.math.Size, scrollOffset: goog.math.Coordinate, rtl: boolean): void;
}
declare module Blockly.Workspace {
/**
* Angle away from the horizontal to sweep for blocks. Order of execution is
* generally top to bottom, but a small angle changes the scan to give a bit of
* a left to right bias (reversed in RTL). Units are in degrees.
* See: http://tvtropes.org/pmwiki/pmwiki.php/Main/DiagonalBilling.
*/
var SCAN_ANGLE: any /*missing*/;
/**
* Database of all workspaces.
* @private
*/
var WorkspaceDB_: any /*missing*/;
/**
* Find the workspace with the specified ID.
* @param {string} id ID of workspace to find.
* @return {Blockly.Workspace} The sought after workspace or null if not found.
*/
function getById(id: string): Blockly.Workspace;
}
declare module Blockly.WorkspaceSvg {
/**
* Return an object with all the metrics required to size scrollbars for a
* top level workspace. The following properties are computed:
* .viewHeight: Height of the visible rectangle,
* .viewWidth: Width of the visible rectangle,
* .contentHeight: Height of the contents,
* .contentWidth: Width of the content,
* .viewTop: Offset of top edge of visible rectangle from parent,
* .viewLeft: Offset of left edge of visible rectangle from parent,
* .contentTop: Offset of the top-most content from the y=0 coordinate,
* .contentLeft: Offset of the left-most content from the x=0 coordinate.
* .absoluteTop: Top-edge of view.
* .absoluteLeft: Left-edge of view.
* .toolboxWidth: Width of toolbox, if it exists. Otherwise zero.
* .toolboxHeight: Height of toolbox, if it exists. Otherwise zero.
* .flyoutWidth: Width of the flyout if it is always open. Otherwise zero.
* .flyoutHeight: Height of flyout if it is always open. Otherwise zero.
* .toolboxPosition: Top, bottom, left or right.
* @return {!Object} Contains size and position metrics of a top level
* workspace.
* @private
* @this Blockly.WorkspaceSvg
*/
function getTopLevelWorkspaceMetrics_(): Object;
/**
* Sets the X/Y translations of a top level workspace to match the scrollbars.
* @param {!Object} xyRatio Contains an x and/or y property which is a float
* between 0 and 1 specifying the degree of scrolling.
* @private
* @this Blockly.WorkspaceSvg
*/
function setTopLevelWorkspaceMetrics_(xyRatio: Object): void;
}
declare module Blockly.Xml {
/**
* Encode a block tree as XML.
* @param {!Blockly.Workspace} workspace The workspace containing blocks.
* @param {boolean} opt_noId True if the encoder should skip the block ids.
* @return {!Element} XML document.
*/
function workspaceToDom(workspace: Blockly.Workspace, opt_noId: boolean): Element;
/**
* Encode a block subtree as XML with XY coordinates.
* @param {!Blockly.Block} block The root block to encode.
* @param {boolean} opt_noId True if the encoder should skip the block id.
* @return {!Element} Tree of XML elements.
*/
function blockToDomWithXY(block: Blockly.Block, opt_noId: boolean): Element;
/**
* Encode a block subtree as XML.
* @param {!Blockly.Block} block The root block to encode.
* @param {boolean} opt_noId True if the encoder should skip the block id.
* @return {!Element} Tree of XML elements.
*/
function blockToDom(block: Blockly.Block, opt_noId: boolean): Element;
/**
* Deeply clone the shadow's DOM so that changes don't back-wash to the block.
* @param {!Element} shadow A tree of XML elements.
* @return {!Element} A tree of XML elements.
* @private
*/
function cloneShadow_(shadow: Element): Element;
/**
* Converts a DOM structure into plain text.
* Currently the text format is fairly ugly: all one line with no whitespace.
* @param {!Element} dom A tree of XML elements.
* @return {string} Text representation.
*/
function domToText(dom: Element): string;
/**
* Converts a DOM structure into properly indented text.
* @param {!Element} dom A tree of XML elements.
* @return {string} Text representation.
*/
function domToPrettyText(dom: Element): string;
/**
* Converts plain text into a DOM structure.
* Throws an error if XML doesn't parse.
* @param {string} text Text representation.
* @return {!Element} A tree of XML elements.
*/
function textToDom(text: string): Element;
/**
* Decode an XML DOM and create blocks on the workspace.
* @param {!Element} xml XML DOM.
* @param {!Blockly.Workspace} workspace The workspace.
*/
function domToWorkspace(xml: Element, workspace: Blockly.Workspace): void;
/**
* Decode an XML block tag and create a block (and possibly sub blocks) on the
* workspace.
* @param {!Element} xmlBlock XML block element.
* @param {!Blockly.Workspace} workspace The workspace.
* @return {!Blockly.Block} The root block created.
*/
function domToBlock(xmlBlock: Element, workspace: Blockly.Workspace): Blockly.Block;
/**
* Decode an XML block tag and create a block (and possibly sub blocks) on the
* workspace.
* @param {!Element} xmlBlock XML block element.
* @param {!Blockly.Workspace} workspace The workspace.
* @return {!Blockly.Block} The root block created.
* @private
*/
function domToBlockHeadless_(xmlBlock: Element, workspace: Blockly.Workspace): Blockly.Block;
/**
* Remove any 'next' block (statements in a stack).
* @param {!Element} xmlBlock XML block element.
*/
function deleteNext(xmlBlock: Element): void;
} | the_stack |
import {
Column,
CompositeColumn,
Ranking,
ReduceColumn,
StackColumn,
createAggregateDesc,
createGroupDesc,
createImpositionBoxPlotDesc,
createImpositionDesc,
createImpositionsDesc,
createNestedDesc,
createRankDesc,
createReduceDesc,
createScriptDesc,
createSelectionDesc,
createStackDesc,
EAdvancedSortMethod,
IColumnDesc,
ISortCriteria,
} from '../model';
import type { DataProvider } from '../provider';
export interface IImposeColumnBuilder {
type: 'impose';
column: string;
label?: string;
colorColumn: string;
}
export interface INestedBuilder {
type: 'nested';
label?: string;
columns: string[];
}
export interface IWeightedSumBuilder {
type: 'weightedSum';
columns: string[];
label?: string;
weights: number[];
}
export interface IReduceBuilder {
type: 'min' | 'max' | 'mean' | 'median';
columns: string[];
label?: string;
}
export interface IScriptedBuilder {
type: 'script';
code: string;
columns: string[];
label?: string;
}
/**
* builder for a ranking
*/
export class RankingBuilder {
private static readonly ALL_MAGIC_FLAG = '*';
private readonly columns: (
| string
| { desc: IColumnDesc | ((data: DataProvider) => IColumnDesc); columns: string[]; post?: (col: Column) => void }
)[] = [];
private readonly sort: { column: string; asc: boolean }[] = [];
private readonly groupSort: { column: string; asc: boolean }[] = [];
private readonly groups: string[] = [];
/**
* specify another sorting criteria
* @param {string} column the column name optionally with encoded sorting separated by colon, e.g. a:desc
* @param {boolean | "asc" | "desc"} asc ascending or descending order
*/
sortBy(column: string, asc: boolean | 'asc' | 'desc' = true) {
if (column.includes(':')) {
// encoded sorting order
const index = column.indexOf(':');
asc = column.slice(index + 1) as 'asc' | 'desc';
column = column.slice(0, index);
}
this.sort.push({ column, asc: asc === true || String(asc)[0] === 'a' });
return this;
}
/**
* specify grouping criteria
* @returns {this}
*/
groupBy(...columns: (string | string[])[]) {
for (const col of columns) {
if (Array.isArray(col)) {
this.groups.push(...col);
} else {
this.groups.push(col);
}
}
return this;
}
/**
* specify another grouping sorting criteria
* @param {string} column the column name optionally with encoded sorting separated by colon, e.g. a:desc
* @param {boolean | "asc" | "desc"} asc ascending or descending order
*/
groupSortBy(column: string, asc: boolean | 'asc' | 'desc' = true) {
if (column.includes(':')) {
// encoded sorting order
const index = column.indexOf(':');
asc = column.slice(index + 1) as 'asc' | 'desc';
column = column.slice(0, index);
}
this.groupSort.push({ column, asc: asc === true || String(asc)[0] === 'a' });
return this;
}
/**
* add another column to this ranking, identified by column name or label. magic names are used for special columns:
* <ul>
* <li>'*' = all columns</li>
* <li>'_*' = all support columns</li>
* <li>'_aggregate' = aggregate column</li>
* <li>'_selection' = selection column</li>
* <li>'_group' = group column</li>
* <li>'_rank' = rank column</li>
* </ul>
* In addition build objects for combined columns are supported.
* @param {string | IImposeColumnBuilder | INestedBuilder | IWeightedSumBuilder | IReduceBuilder | IScriptedBuilder} column
*/
column(
column: string | IImposeColumnBuilder | INestedBuilder | IWeightedSumBuilder | IReduceBuilder | IScriptedBuilder
) {
if (typeof column === 'string') {
switch (column) {
case '_aggregate':
return this.aggregate();
case '_selection':
return this.selection();
case '_group':
return this.group();
case '_rank':
return this.rank();
case '_*':
return this.supportTypes();
case '*':
return this.allColumns();
}
this.columns.push(column);
return this;
}
const label = column.label || null;
// builder ish
switch (column.type) {
case 'impose':
return this.impose(label, column.column, column.colorColumn);
case 'min':
case 'max':
case 'median':
case 'mean':
console.assert(column.columns.length >= 2);
return this.reduce(label, column.type as any, column.columns[0], column.columns[1], ...column.columns.slice(2));
case 'nested':
console.assert(column.columns.length >= 1);
return this.nested(label, column.columns[0], ...column.columns.slice(1));
case 'script':
return this.scripted(label, column.code, ...column.columns);
case 'weightedSum':
console.assert(column.columns.length >= 2);
console.assert(column.columns.length === column.weights.length);
const mixed: (string | number)[] = [];
column.columns.slice(2).forEach((c, i) => {
mixed.push(c);
mixed.push(column.weights[i + 2]);
});
return this.weightedSum(
label,
column.columns[0],
column.weights[0],
column.columns[1],
column.weights[1],
...mixed
);
}
}
/**
* add an imposed column (numerical column colored by categorical column) to this ranking
* @param {string | null} label optional label
* @param {string} numberColumn numerical column reference
* @param {string} colorColumn categorical column reference
*/
impose(label: string | null, numberColumn: string, colorColumn: string) {
this.columns.push({
desc: (data) => {
const base = data.getColumns().find((d) => d.label === numberColumn || (d as any).column === numberColumn);
switch (base ? base.type : '') {
case 'boxplot':
return createImpositionBoxPlotDesc(label ? label : undefined);
case 'numbers':
return createImpositionsDesc(label ? label : undefined);
default:
return createImpositionDesc(label ? label : undefined);
}
},
columns: [numberColumn, colorColumn],
});
return this;
}
/**
* add a nested / group composite column
* @param {string | null} label optional label
* @param {string} column first element of the group enforcing not empty ones
* @param {string} columns additional columns
*/
nested(label: string | null, column: string, ...columns: string[]) {
this.columns.push({
desc: createNestedDesc(label ? label : undefined),
columns: [column].concat(columns),
});
return this;
}
/**
* @param {IColumnDesc} desc the composite column description
* @param {string} columns additional columns to add as children
*/
composite(desc: IColumnDesc, ...columns: string[]) {
this.columns.push({
desc,
columns,
});
return this;
}
/**
* add a weighted sum / stack column
* @param {string | null} label optional label
* @param {string} numberColumn1 the first numerical column
* @param {number} weight1 its weight (0..1)
* @param {string} numberColumn2 the second numerical column
* @param {number} weight2 its weight (0..1)
* @param {string | number} numberColumnAndWeights alternating column weight references
*/
weightedSum(
label: string | null,
numberColumn1: string,
weight1: number,
numberColumn2: string,
weight2: number,
...numberColumnAndWeights: (string | number)[]
) {
const weights = [weight1, weight2].concat(numberColumnAndWeights.filter((_, i) => i % 2 === 1) as number[]);
this.columns.push({
desc: createStackDesc(label ? label : undefined),
columns: [numberColumn1, numberColumn2].concat(numberColumnAndWeights.filter((_, i) => i % 2 === 0) as string[]),
post: (col) => {
(col as StackColumn).setWeights(weights);
},
});
return this;
}
/**
* add reducing column (min, max, median, mean, ...)
* @param {string | null} label optional label
* @param {EAdvancedSortMethod} operation operation to apply (min, max, median, mean, ...)
* @param {string} numberColumn1 first numerical column
* @param {string} numberColumn2 second numerical column
* @param {string} numberColumns additional numerical columns
*/
reduce(
label: string | null,
operation: EAdvancedSortMethod,
numberColumn1: string,
numberColumn2: string,
...numberColumns: string[]
) {
this.columns.push({
desc: createReduceDesc(label ? label : undefined),
columns: [numberColumn1, numberColumn2].concat(numberColumns),
post: (col) => {
(col as ReduceColumn).setReduce(operation);
},
});
return this;
}
/**
* add a scripted / formula column
* @param {string | null} label optional label
* @param {string} code the JS code see ScriptColumn for details
* @param {string} numberColumns additional script columns
*/
scripted(label: string | null, code: string, ...numberColumns: string[]) {
this.columns.push({
desc: Object.assign(createScriptDesc(label ? label : undefined), { script: code }),
columns: numberColumns,
});
return this;
}
/**
* add a selection column for easier multi selections
*/
selection() {
this.columns.push({
desc: createSelectionDesc(),
columns: [],
});
return this;
}
/**
* add a group column to show the current group name
*/
group() {
this.columns.push({
desc: createGroupDesc(),
columns: [],
});
return this;
}
/**
* add an aggregate column to this ranking to collapse/expand groups
*/
aggregate() {
this.columns.push({
desc: createAggregateDesc(),
columns: [],
});
return this;
}
/**
* add a ranking column
*/
rank() {
this.columns.push({
desc: createRankDesc(),
columns: [],
});
return this;
}
/**
* add suporttypes (aggregate, rank, selection) to the ranking
*/
supportTypes() {
return this.aggregate().rank().selection();
}
/**
* add all columns to this ranking
*/
allColumns() {
this.columns.push(RankingBuilder.ALL_MAGIC_FLAG);
return this;
}
build(data: DataProvider): Ranking {
const r = data.pushRanking();
const cols = data.getColumns();
const findDesc = (c: string) => cols.find((d) => d.label === c || (d as any).column === c);
const addColumn = (c: string) => {
const desc = findDesc(c);
if (desc) {
return data.push(r, desc) != null;
}
console.warn('invalid column: ', c);
return false;
};
this.columns.forEach((c) => {
if (c === RankingBuilder.ALL_MAGIC_FLAG) {
cols.forEach((col) => data.push(r, col));
return;
}
if (typeof c === 'string') {
addColumn(c);
return;
}
const col = data.create(typeof c.desc === 'function' ? c.desc(data) : c.desc)!;
r.push(col);
c.columns.forEach((ci) => {
const d = findDesc(ci);
const child = d ? data.create(d) : null;
if (!child) {
console.warn('invalid column: ', ci);
return;
}
(col as CompositeColumn).push(child);
});
if (c.post) {
c.post(col);
}
});
const children = r.children;
{
const groups: Column[] = [];
this.groups.forEach((column) => {
const col = children.find((d) => d.desc.label === column || (d as any).desc.column === column);
if (col) {
groups.push(col);
return;
}
const desc = findDesc(column);
if (!desc) {
console.warn('invalid group criteria column: ', column);
return;
}
const col2 = data.push(r, desc);
if (col2) {
groups.push(col2);
return;
}
console.warn('invalid group criteria column: ', column);
});
if (groups.length > 0) {
r.setGroupCriteria(groups);
}
}
{
const sorts: ISortCriteria[] = [];
this.sort.forEach(({ column, asc }) => {
const col = children.find((d) => d.desc.label === column || (d as any).desc.column === column);
if (col) {
sorts.push({ col, asc });
return;
}
const desc = findDesc(column);
if (!desc) {
console.warn('invalid sort criteria column: ', column);
return;
}
const col2 = data.push(r, desc);
if (col2) {
sorts.push({ col: col2, asc });
return;
}
console.warn('invalid sort criteria column: ', column);
});
if (sorts.length > 0) {
r.setSortCriteria(sorts);
}
}
{
const sorts: ISortCriteria[] = [];
this.groupSort.forEach(({ column, asc }) => {
const col = children.find((d) => d.desc.label === column || (d as any).desc.column === column);
if (col) {
sorts.push({ col, asc });
return;
}
const desc = findDesc(column);
if (!desc) {
console.warn('invalid group sort criteria column: ', column);
return;
}
const col2 = data.push(r, desc);
if (col2) {
sorts.push({ col: col2, asc });
return;
}
console.warn('invalid group sort criteria column: ', column);
});
if (sorts.length > 0) {
r.setGroupSortCriteria(sorts);
}
}
return r;
}
}
/**
* creates a new instance of a ranking builder
* @returns {RankingBuilder}
*/
export function buildRanking() {
return new RankingBuilder();
} | the_stack |
import {IApp} from '../../IApp';
import IDisplayContext = etch.drawing.IDisplayContext;
import Point = etch.primitives.Point;
import {SamplerBase} from './SamplerBase';
declare var App: IApp;
export class Recorder extends SamplerBase {
public Sources : Tone.Simpler[];
public Recorder: any;
//public PrimaryBuffer;
public Filename: string;
public IsRecording: boolean = false;
public RecordedBlob;
//private WaveForm: number[];
public Params: SamplerParams;
public Defaults: SamplerParams;
Init(drawTo: IDisplayContext): void {
this.BlockName = App.L10n.Blocks.Source.Blocks.Recorder.name;
this.Defaults = {
playbackRate: 0,
detune: 0,
reverse: false,
startPosition: 0,
endPosition: 0,
loop: true,
loopStart: 0,
loopEnd: 0,
volume: 20,
track: null,
trackName: '',
permalink: ''
};
this.PopulateParams();
this.WaveForm = [];
super.Init(drawTo);
this.PrimaryBuffer = App.Audio.ctx.createBufferSource();
this.Recorder = new RecorderJS(App.Audio.Master, {
workerPath: App.Config.RecorderWorkerPath
});
this.Envelopes.forEach((e: Tone.AmplitudeEnvelope, i: number)=> {
e = this.Sources[i].envelope;
});
this.Sources.forEach((s: Tone.Simpler) => {
s.connect(this.AudioInput);
s.volume.value = this.Params.volume;
});
this.Filename = "BlokdustRecording.wav"; //TODO: make an input box for filename download
// Define Outline for HitTest
this.Outline.push(new Point(-1, 0),new Point(0, -1),new Point(1, -1),new Point(2, 0),new Point(2, 1),new Point(1, 2));
}
Update() {
super.Update();
}
Draw() {
super.Draw();
this.DrawSprite(this.BlockName);
}
ToggleRecording(){
if (this.IsRecording) {
this.StopRecording();
} else {
this.StartRecording();
}
}
StartRecording() {
this.Recorder.clear();
App.Message('Started Recording', {
'seconds': 1,
});
this.IsRecording = true;
this.Recorder.record();
this.ReverseBuffer = null;
this.Params.reverse = false;
}
StopRecording() {
this.Recorder.stop();
this.IsRecording = false;
App.Message('Stopped Recording', {
'seconds': 1,
});
this.SetBuffers();
}
SetBuffers() {
this.Recorder.getBuffers((buffers) => {
// if BufferSource doesn't exist create it
if (!this.PrimaryBuffer) {
this.PrimaryBuffer = App.Audio.ctx.createBufferSource();
}
// If we already have a BufferSource and the buffer is set, reset it to null and create a new one
else if (this.PrimaryBuffer && this.PrimaryBuffer.buffer !== null){
this.PrimaryBuffer = null;
this.PrimaryBuffer = App.Audio.ctx.createBufferSource();
}
// TODO: add an overlay function which would merge new buffers with old buffers
// Create a new buffer and set the buffers to the recorded data
this.PrimaryBuffer.buffer = App.Audio.ctx.createBuffer(1, buffers[0].length, 44100);
this.PrimaryBuffer.buffer.getChannelData(0).set(buffers[0]);
this.PrimaryBuffer.buffer.getChannelData(0).set(buffers[1]);
this.UpdateWaveform();
// Set the buffers for each source
this.Sources.forEach((s: Tone.Simpler)=> {
s.player.buffer = this.PrimaryBuffer.buffer;
s.player.loopStart = this.Params.loopStart;
s.player.loopEnd = this.Params.loopEnd;
//s.player.reverse = this.Params.reverse;
});
// start immediately if powered
this.RetriggerActiveVoices();
});
}
UpdateWaveform(){
// Update waveform
this.WaveForm = App.Audio.Waveform.GetWaveformFromBuffer(this.PrimaryBuffer.buffer,200,2,95);
var duration = this.GetDuration();
this.Params.startPosition = 0;
this.Params.endPosition = duration;
this.Params.loopStart = duration * 0.5;
this.Params.loopEnd = duration;
this.RefreshOptionsPanel();
}
GetDuration(): number {
if (this.PrimaryBuffer && this.PrimaryBuffer.buffer !== null){
return this.PrimaryBuffer.buffer.duration;
} else {
return 10;
}
}
DownloadRecording() {
this.Recorder.exportWAV((blob) => {
console.log(`Downloading audio... Filename: ${this.Filename}, Size: ${blob.size} bytes`);
this.Recorder.setupDownload(blob, this.Filename);
});
}
Dispose(){
super.Dispose();
this.PrimaryBuffer = null;
this.Recorder.clear();
this.Recorder = null;
this.RecordedBlob = null;
}
CreateSource(){
this.Sources.push( new Tone.Simpler(this.PrimaryBuffer) );
this.Sources.forEach((s: Tone.Simpler, i: number)=> {
s.player.loop = this.Params.loop;
s.player.loopStart = this.Params.loopStart;
s.player.loopEnd = this.Params.loopEnd;
//s.player.reverse = this.Params.reverse;
s.volume.value = this.Params.volume;
if (i > 0){
s.player.buffer = this.Sources[0].player.buffer;
}
});
if (this.Sources[this.Sources.length-1]){
return this.Sources[this.Sources.length-1];
}
}
UpdateOptionsForm() {
super.UpdateOptionsForm();
this.OptionsForm =
{
"name" : "Recorder",
"parameters" : [
{
"type" : "waveregion",
"name" : "Recording",
"setting" :"region",
"props" : {
"value" : 5,
"min" : 0,
"max" : this.GetDuration(),
"quantised" : false,
"centered" : false,
"wavearray" : this.WaveForm,
"mode" : this.Params.loop,
"emptystring" : "No Sample"
},
"nodes": [
{
"setting": "startPosition",
"value": this.Params.startPosition
},
{
"setting": "endPosition",
"value": this.Params.endPosition
},
{
"setting": "loopStart",
"value": this.Params.loopStart
},
{
"setting": "loopEnd",
"value": this.Params.loopEnd
}
]
},
{
"type" : "switches",
"name" : "Loop",
"setting" :"loop",
"switches": [
{
"name": "Reverse",
"setting": "reverse",
"value": this.Params.reverse,
"lit" : true,
"mode": "offOn"
},
{
"name": "Looping",
"setting": "loop",
"value": this.Params.loop,
"lit" : true,
"mode": "offOn"
}
]
},
{
"type" : "slider",
"name" : "playback",
"setting" :"playbackRate",
"props" : {
"value" : this.Params.playbackRate,
"min" : -App.Config.PlaybackRange,
"max" : App.Config.PlaybackRange,
"quantised" : false,
"centered" : true
}
},
{
"type" : "actionbutton",
"name" : "",
"setting" :"download",
"props" : {
"text" : "Download Recording"
}
}
]
};
}
SetParam(param: string,value: any) {
super.SetParam(param,value);
var val = value;
switch(param) {
case "playbackRate":
/*if ((<any>Tone).isSafari) {
this.Sources[0].player.playbackRate = value;
} else {
this.Sources[0].player.playbackRate.value = value;
}*/
this.Params.playbackRate = value;
this.NoteUpdate();
break;
case "reverse":
value = value? true : false;
this.Params[param] = val;
this.ReverseTrack();
break;
case "loop":
value = value? true : false;
this.Sources.forEach((s: Tone.Simpler)=> {
s.player.loop = value;
});
if (value === true && this.IsPowered()) {
this.Sources.forEach((s: Tone.Simpler) => {
s.player.stop();
s.player.start(s.player.startPosition);
});
}
// update showing loop sliders
this.Params[param] = val;
this.RefreshOptionsPanel();
break;
case "loopStart":
this.Sources.forEach((s: Tone.Simpler)=> {
s.player.loopStart = value;
});
break;
case "loopEnd":
this.Sources.forEach((s: Tone.Simpler)=> {
s.player.loopEnd = value;
});
break;
case "download":
if (this.PrimaryBuffer.buffer===null) {
App.Message("This block doesn't have a recording to download yet.");
} else {
this.DownloadRecording();
}
break;
}
this.Params[param] = val;
}
} | the_stack |
import * as assert from 'assert';
import * as fs from 'fs-extra';
import * as sinon from 'sinon';
import * as uuid from 'uuid';
import { Constants } from '../src/Constants';
import * as helpers from '../src/helpers';
import { userSettings } from '../src/helpers';
import { BlobServiceClient } from '../src/services/storageAccountService/BlobServiceClient';
describe('Storage Account Resource Explorer', () => {
let getConfigurationAsyncStub: sinon.SinonStub<any>;
let updateConfigurationAsyncStub: sinon.SinonStub<any>;
let storageAccountResourceExplorerRequire: any;
let storageAccountResourceExplorer: any;
beforeEach(() => {
getConfigurationAsyncStub = sinon.stub(userSettings, 'getConfigurationAsync')
.returns(Promise.resolve({ userValue: '', defaultValue: '' }));
updateConfigurationAsyncStub = sinon.stub(userSettings, 'updateConfigurationAsync').resolves();
storageAccountResourceExplorerRequire = require('../src/resourceExplorers/StorageAccountResourceExplorer');
storageAccountResourceExplorer = storageAccountResourceExplorerRequire.StorageAccountResourceExplorer;
});
afterEach(() => {
sinon.restore();
});
it('getFileBlobUrls should executed all methods for delete BDM application', async () => {
// Arrange
const contentArray = [uuid.v4(), uuid.v4()];
const fileNameArray = [uuid.v4(), uuid.v4()];
const localFilePaths = uuid.v4();
const subscriptionId = uuid.v4();
const resourceGroup = uuid.v4();
const waitForLoginStub = sinon.stub(storageAccountResourceExplorer.prototype, 'waitForLogin');
const getStorageAccountClientStub = sinon.stub(storageAccountResourceExplorer.prototype, 'getStorageAccountClient')
.returns(Promise.resolve({ location: uuid.v4()}));
const getStorageAccountNameStub = sinon.stub(storageAccountResourceExplorer.prototype, 'getStorageAccountName');
const createStorageAccountIfDoesNotExistStub = sinon.stub(storageAccountResourceExplorer.prototype, 'createStorageAccountIfDoesNotExist');
const getStorageAccountSasStub = sinon.stub(storageAccountResourceExplorer.prototype, 'getStorageAccountSas');
const createContainerIfDoesNotExistStub = sinon.stub(storageAccountResourceExplorer.prototype, 'createContainerIfDoesNotExist');
const createBlobStub = sinon.stub(storageAccountResourceExplorer.prototype, 'createBlob');
// Act
await storageAccountResourceExplorer.prototype
.getFileBlobUrls(contentArray, fileNameArray, localFilePaths, subscriptionId, resourceGroup);
// Assert
assert.strictEqual(waitForLoginStub.calledOnce, true, 'waitForLogin should be called');
assert.strictEqual(getStorageAccountClientStub.calledOnce, true, 'getStorageAccountClient should be called');
assert.strictEqual(getStorageAccountNameStub.calledOnce, true, 'getStorageAccountName should be called');
assert.strictEqual(createStorageAccountIfDoesNotExistStub.calledOnce, true, 'createStorageAccountIfDoesNotExist should be called');
assert.strictEqual(getStorageAccountSasStub.calledOnce, true, 'getStorageAccountSas should be called');
assert.strictEqual(createContainerIfDoesNotExistStub.calledOnce, true, 'createContainerIfDoesNotExist should be called');
assert.strictEqual(createBlobStub.callCount, fileNameArray.length, `createBlob should be called ${fileNameArray.length} times`);
});
it('getStorageAccountName should return storage account name', async () => {
// Arrange
const storageAccountName = uuid.v4();
getConfigurationAsyncStub.returns(Promise.resolve({ userValue: storageAccountName, defaultValue: '' }));
// Act
await storageAccountResourceExplorer.prototype.getStorageAccountName();
// Assert
assert.strictEqual(getConfigurationAsyncStub.calledOnce, true, 'getConfigurationAsync should be called');
assert.strictEqual(updateConfigurationAsyncStub.calledOnce, false, 'updateConfigurationAsync should not called');
});
it('getStorageAccountName should set and return storage account name', async () => {
// Arrange
getConfigurationAsyncStub.returns(Promise.resolve({ userValue: '', defaultValue: '' }));
// Act
await storageAccountResourceExplorer.prototype.getStorageAccountName();
// Assert
assert.strictEqual(getConfigurationAsyncStub.calledOnce, true, 'getConfigurationAsync should be called');
assert.strictEqual(updateConfigurationAsyncStub.calledOnce, true, 'updateConfigurationAsync should be called');
assert.strictEqual(
updateConfigurationAsyncStub.args[0][0],
Constants.userSettings.storageAccountUserSettingsKey,
'updateConfigurationAsync should have special user settings key');
});
it('createStorageAccountIfDoesNotExist should check existing storage account', async () => {
// Arrange
const client = {
storageResource: { getStorageAccount: () => Promise.resolve({}) },
};
const location = uuid.v4();
const storageAccountName = uuid.v4();
const getStorageAccountStub = sinon.stub(client.storageResource, 'getStorageAccount')
.returns(Promise.resolve( { properties: { provisioningState: Constants.provisioningState.succeeded } }));
const createStorageAccountStub = sinon.stub(storageAccountResourceExplorer.prototype, 'createStorageAccount');
// Act
await storageAccountResourceExplorer.prototype
.createStorageAccountIfDoesNotExist(client, location, storageAccountName);
// Assert
assert.strictEqual(getStorageAccountStub.calledOnce, true, 'getStorageAccount should be called');
assert.strictEqual(createStorageAccountStub.calledOnce, false, 'createStorageAccount should not called');
});
it('createStorageAccountIfDoesNotExist should wait when storage account will be created ' +
'when provisioning state equal creating', async () => {
// Arrange
const client = {
storageResource: { getStorageAccount: () => Promise.resolve({}) },
};
const location = uuid.v4();
const storageAccountName = uuid.v4();
const getStorageAccountStub = sinon.stub(client.storageResource, 'getStorageAccount')
.returns(Promise.resolve( { properties: { provisioningState: Constants.provisioningState.creating } }));
const createStorageAccountStub = sinon.stub(storageAccountResourceExplorer.prototype, 'createStorageAccount');
// Act
await storageAccountResourceExplorer.prototype
.createStorageAccountIfDoesNotExist(client, location, storageAccountName);
// Assert
assert.strictEqual(getStorageAccountStub.calledOnce, true, 'getStorageAccount should be called');
assert.strictEqual(createStorageAccountStub.calledOnce, true, 'createStorageAccount should be called');
});
it('createStorageAccountIfDoesNotExist should wait when storage account will be created ' +
'when provisioning state equal resolvingDns', async () => {
// Arrange
const client = {
storageResource: { getStorageAccount: () => Promise.resolve({}) },
};
const location = uuid.v4();
const storageAccountName = uuid.v4();
const getStorageAccountStub = sinon.stub(client.storageResource, 'getStorageAccount')
.returns(Promise.resolve( { properties: { provisioningState: Constants.provisioningState.resolvingDns } }));
const createStorageAccountStub = sinon.stub(storageAccountResourceExplorer.prototype, 'createStorageAccount');
// Act
await storageAccountResourceExplorer.prototype
.createStorageAccountIfDoesNotExist(client, location, storageAccountName);
// Assert
assert.strictEqual(getStorageAccountStub.calledOnce, true, 'getStorageAccount should be called');
assert.strictEqual(createStorageAccountStub.calledOnce, true, 'createStorageAccount should be called');
assert.strictEqual(
createStorageAccountStub.args[0][3],
true,
'createStorageAccount should be executed with true flag');
});
it('createStorageAccountIfDoesNotExist throws ResourceNotFound error and create new storage account', async () => {
// Arrange
const client = {
storageResource: { getStorageAccount: () => Promise.resolve({}) },
};
const location = uuid.v4();
const storageAccountName = uuid.v4();
const getStorageAccountStub = sinon.stub(client.storageResource, 'getStorageAccount')
.throwsException({ message: 'ResourceNotFound'});
const createStorageAccountStub = sinon.stub(storageAccountResourceExplorer.prototype, 'createStorageAccount');
// Act
await storageAccountResourceExplorer.prototype
.createStorageAccountIfDoesNotExist(client, location, storageAccountName);
// Assert
assert.strictEqual(getStorageAccountStub.calledOnce, true, 'getStorageAccount should be called');
assert.strictEqual(createStorageAccountStub.calledOnce, true, 'createStorageAccount should be called');
});
it('createStorageAccountIfDoesNotExist throws not ResourceNotFound error', async () => {
// Arrange
const client = {
storageResource: { getStorageAccount: () => Promise.resolve({}) },
};
const location = uuid.v4();
const storageAccountName = uuid.v4();
const getStorageAccountStub = sinon.stub(client.storageResource, 'getStorageAccount')
.throwsException({ message: uuid.v4()});
const createStorageAccountStub = sinon.stub(storageAccountResourceExplorer.prototype, 'createStorageAccount');
try {
// Act
await storageAccountResourceExplorer.prototype
.createStorageAccountIfDoesNotExist(client, location, storageAccountName);
} catch (error) {
// Assert
assert.strictEqual(getStorageAccountStub.calledOnce, true, 'getStorageAccount should be called');
assert.strictEqual(createStorageAccountStub.calledOnce, false, 'createStorageAccount should not called');
}
});
it('createStorageAccount should create new storage account', async () => {
// Arrange
const client = {
storageResource: {
createStorageAccount: () => Promise.resolve({}),
getStorageAccount: () => Promise.resolve({}) },
};
const location = uuid.v4();
const storageAccountName = uuid.v4();
const awaiterStub = sinon.stub(helpers.outputCommandHelper, 'awaiter');
// Act
await storageAccountResourceExplorer.prototype.createStorageAccount(client, location, storageAccountName, false);
// Assert
assert.strictEqual(awaiterStub.calledOnce, true, 'awaiter should be called');
assert.strictEqual(typeof awaiterStub.args[0][0], 'function', 'awaiter should be called called with first parameter like function');
});
it('createStorageAccount should check status of storage account', async () => {
// Arrange
const client = {
storageResource: {
createStorageAccount: () => Promise.resolve({}),
getStorageAccount: () => Promise.resolve({}) },
};
const location = uuid.v4();
const storageAccountName = uuid.v4();
const awaiterSpy = sinon.spy(helpers.outputCommandHelper, 'awaiter');
const getStorageAccountStub = sinon.stub(client.storageResource, 'getStorageAccount')
.returns(Promise.resolve({ properties: { provisioningState: Constants.provisioningState.succeeded }}));
const createStorageAccountStub = sinon.stub(client.storageResource, 'createStorageAccount');
// Act
await storageAccountResourceExplorer.prototype.createStorageAccount(client, location, storageAccountName, true);
// Assert
assert.strictEqual(awaiterSpy.calledOnce, true, 'awaiter should be called');
assert.strictEqual(createStorageAccountStub.calledOnce, false, 'createStorageAccount should not called');
assert.strictEqual(getStorageAccountStub.calledOnce, true, 'getStorageAccount should be called');
});
it('createStorageAccount should check status of storage account', async () => {
// Arrange
const client = {
storageResource: {
createStorageAccount: () => Promise.resolve({}),
getStorageAccount: () => Promise.resolve({}) },
};
const location = uuid.v4();
const storageAccountName = uuid.v4();
const awaiterSpy = sinon.spy(helpers.outputCommandHelper, 'awaiter');
const getStorageAccountStub = sinon.stub(client.storageResource, 'getStorageAccount')
.returns(Promise.resolve({ properties: { provisioningState: Constants.provisioningState.succeeded }}));
const createStorageAccountStub = sinon.stub(client.storageResource, 'createStorageAccount');
// Act
await storageAccountResourceExplorer.prototype.createStorageAccount(client, location, storageAccountName, false);
// Assert
assert.strictEqual(awaiterSpy.calledOnce, true, 'awaiter should be called');
assert.strictEqual(createStorageAccountStub.calledOnce, true, 'createStorageAccount should be called');
assert.strictEqual(getStorageAccountStub.calledOnce, true, 'getStorageAccount should be called');
});
it('createContainerIfDoesNotExist should only check container', async () => {
// Arrange
const getContainerStub = sinon.stub(BlobServiceClient, 'getContainer');
const createContainerStub = sinon.stub(BlobServiceClient, 'createContainer');
// Act
await storageAccountResourceExplorer.prototype.createContainerIfDoesNotExist(uuid.v4(), uuid.v4(), uuid.v4());
// Assert
assert.strictEqual(getContainerStub.calledOnce, true, 'getContainer should be called');
assert.strictEqual(createContainerStub.calledOnce, false, 'createContainer should not called');
});
it('createContainerIfDoesNotExist throws ContainerNotFound error and create new container', async () => {
// Arrange
const getContainerStub = sinon.stub(BlobServiceClient, 'getContainer').throwsException({ message: 'ContainerNotFound'});
const createContainerStub = sinon.stub(BlobServiceClient, 'createContainer');
// Act
await storageAccountResourceExplorer.prototype.createContainerIfDoesNotExist(uuid.v4(), uuid.v4(), uuid.v4());
// Assert
assert.strictEqual(getContainerStub.calledOnce, true, 'getContainer should be called');
assert.strictEqual(createContainerStub.calledOnce, true, 'createContainer should be called');
});
it('createContainerIfDoesNotExist throws not ContainerNotFound error', async () => {
// Arrange
const getContainerStub = sinon.stub(BlobServiceClient, 'getContainer').throwsException({ message: uuid.v4()});
const createContainerStub = sinon.stub(BlobServiceClient, 'createContainer');
try {
// Act
await storageAccountResourceExplorer.prototype.createContainerIfDoesNotExist(uuid.v4(), uuid.v4(), uuid.v4());
} catch (error) {
// Assert
assert.strictEqual(getContainerStub.calledOnce, true, 'getContainer should be called');
assert.strictEqual(createContainerStub.calledOnce, false, 'createContainer should not called');
}
});
it('createBlob should create blob to Azure and create file in build directory', async () => {
// Arrange
const createBlobStub = sinon.stub(BlobServiceClient, 'createBlob');
const mkdirpStub = sinon.stub(fs, 'mkdirp');
const writeFileStub = sinon.stub(fs, 'writeFile');
// Act
await storageAccountResourceExplorer.prototype
.createBlob(uuid.v4(), uuid.v4(), uuid.v4(), uuid.v4(), uuid.v4(), uuid.v4());
// Assert
assert.strictEqual(createBlobStub.calledOnce, true, 'createBlob should be called');
assert.strictEqual(mkdirpStub.calledOnce, true, 'mkdirp should be called');
assert.strictEqual(writeFileStub.calledOnce, true, 'writeFile should be called');
});
it('deleteBlob should delete blob to Azure and delete file in build directory', async () => {
// Arrange
const testUrl = 'https://storageaccountname.blob.core.windows.net/containername/file.json';
const deleteBlobStub = sinon.stub(BlobServiceClient, 'deleteBlob');
const removeStub = sinon.stub(fs, 'remove');
const getStorageAccountSasStub = sinon.stub(storageAccountResourceExplorer.prototype, 'getStorageAccountSas');
const storageAccountClient = require('../src/ARMBlockchain/StorageAccountClient');
sinon.stub(storageAccountClient.__proto__, 'constructor');
const serviceClient = new storageAccountClient.StorageAccountClient(
{ signRequest: () => undefined },
uuid.v4(),
uuid.v4(),
uuid.v4(),
{},
);
// Act
await storageAccountResourceExplorer.prototype.deleteBlob(new URL(testUrl), serviceClient, uuid.v4());
// Assert
assert.strictEqual(deleteBlobStub.calledOnce, true, 'deleteBlob should be called');
assert.strictEqual(removeStub.calledOnce, true, 'remove should be called');
assert.strictEqual(getStorageAccountSasStub.calledOnce, true, 'getStorageAccountSas should be called');
});
}); | the_stack |
import { TestBed } from "@angular/core/testing";
import { Glue42Initializer } from "../glue-initializer.service";
import { Subject, Observable, Subscription } from "rxjs";
import { Glue42NgConfig, Glue42NgFactory, Glue42NgSettings } from "../types";
import { GlueConfigService } from "../glue-config.service";
describe("Glue42Initializer ", () => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let glueInstanceMock: any;
let service: Glue42Initializer;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
let factorySpy: jasmine.Spy<Glue42NgFactory>;
let configMock: Glue42NgConfig = {};
let settingsMock: Glue42NgSettings = {};
let configSpy: jasmine.SpyObj<GlueConfigService>;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const waitFor = (callCount: number, done: DoneFn) => {
return (): void => {
--callCount;
if (!callCount) {
done();
}
};
};
beforeEach(() => {
glueInstanceMock = { test: 42 };
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(window as any).GlueWeb = undefined;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(window as any).Glue = undefined;
factorySpy = jasmine
.createSpy().and
.resolveTo(glueInstanceMock);
configMock = {};
settingsMock = {
config: configMock,
factory: factorySpy
};
configSpy = jasmine.createSpyObj<GlueConfigService>("GlueConfigService", ["getSettings"]);
configSpy.getSettings.and.returnValue(settingsMock);
TestBed.configureTestingModule({
providers: [
Glue42Initializer,
{
provide: GlueConfigService,
useValue: configSpy
}
]
});
service = TestBed.inject(Glue42Initializer);
});
it("should be created", () => {
expect(service).toBeTruthy();
});
it("should be created with default timeout of 3000 milliseconds", () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((service as any).defaultInitTimeoutMilliseconds).toEqual(3000);
});
it("should be creates with a subject observable", () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((service as any).initializationSource).toBeInstanceOf(Subject);
});
describe("onState() ", () => {
let subscription: Subscription;
afterEach(() => {
if (subscription) {
subscription.unsubscribe();
subscription = null;
}
});
it("should show exist and return an observable", () => {
expect(service.onState).toBeTruthy();
const functionResult = service.onState();
expect(functionResult).toBeInstanceOf(Observable);
});
it("should not emit when start was never called", (done: DoneFn) => {
const timeout: NodeJS.Timeout = setTimeout(() => {
expect().nothing();
done();
}, 3000);
service
.onState()
.subscribe(() => {
clearTimeout(timeout);
done.fail("Something was emitted even though start was never called");
});
});
it("should emit an error when start was called and there is no factory", (done: DoneFn) => {
settingsMock.factory = undefined;
service
.onState()
.subscribe((data) => {
try {
expect(data.glueInstance).toBeFalsy();
expect(data.error).toBeTruthy();
done();
} catch (error) {
done.fail(error);
}
});
service.start().catch(() => { });
});
it("should emit an error when start was called, but the factory call threw", (done: DoneFn) => {
factorySpy.and.rejectWith("Factory threw");
service
.onState()
.subscribe((data) => {
try {
expect(data.glueInstance).toBeFalsy();
expect(data.error).toBeTruthy();
done();
} catch (error) {
done.fail(error);
}
});
service.start().catch(() => { });
});
it("should emit an error when start was called, but the factory timed out", (done: DoneFn) => {
factorySpy.and.returnValue(new Promise(() => {
// never resolve
}));
service
.onState()
.subscribe((data) => {
try {
expect(data.glueInstance).toBeFalsy();
expect(data.error).toBeTruthy();
done();
} catch (error) {
done.fail(error);
}
});
service.start().catch(() => { });
});
it("should not emit an error object when start was called and the factory resolved", (done: DoneFn) => {
service
.onState()
.subscribe((data) => {
try {
expect(data.glueInstance).toBeTruthy();
expect(data.error).toBeFalsy();
done();
} catch (error) {
done.fail(error);
}
});
service.start().catch(() => { });
});
it("should emit the object returned by the factory when start was called and the factory resolved", (done: DoneFn) => {
service
.onState()
.subscribe((data) => {
try {
expect(data.error).toBeFalsy();
expect(data.glueInstance as unknown).toEqual({ test: 42 });
done();
} catch (error) {
done.fail(error);
}
});
service.start().catch(() => { });
});
});
describe("start() ", () => {
let subscription: Subscription;
afterEach(() => {
if (subscription) {
subscription.unsubscribe();
subscription = null;
}
});
it("should exist and return a promise", async () => {
expect(service.onState).toBeTruthy();
const functionResult = service.start();
expect(functionResult).toBeInstanceOf(Promise);
await functionResult;
});
it("should resolve when config was not provided, but there is a factory function", async () => {
settingsMock.config = undefined;
await service.start();
expect().nothing();
});
it("should resolve and emit the value returned from the factory as glueInstance", (done: DoneFn) => {
const ready = waitFor(2, done);
service.onState().subscribe((result) => {
try {
expect(result.glueInstance as unknown).toEqual({ test: 42 });
ready();
} catch (error) {
done.fail(error);
}
});
service.start().then(ready).catch(done.fail);
});
it("should use the provided factory function when it is provided but there is also a window factory", async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(window as any).GlueWeb = jasmine
.createSpy().and
.resolveTo({ test: 24 });
await service.start();
expect(factorySpy).toHaveBeenCalled();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((window as any).GlueWeb).toHaveBeenCalledTimes(0);
});
it("should use the window factory function when no factory function was provided", async () => {
settingsMock.factory = undefined;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(window as any).GlueWeb = jasmine
.createSpy().and
.resolveTo({ test: 24 });
await service.start();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((window as any).GlueWeb).toHaveBeenCalled();
});
it("should call the factory function with the provided config", async () => {
await service.start();
expect(factorySpy).toHaveBeenCalledWith(configMock);
});
it("should resolve, but emit an error when no factory was provided and the window object does not have a factory", (done: DoneFn) => {
const ready = waitFor(2, done);
settingsMock.factory = undefined;
subscription = service.onState().subscribe((result) => {
try {
expect(result.error).toBeTruthy();
expect(result.glueInstance).toBeFalsy();
ready();
} catch (error) {
done.fail(error);
}
});
service.start().then(ready).catch(done.fail);
});
it("should resolve, but emit an error when the factory function threw", (done: DoneFn) => {
const ready = waitFor(2, done);
factorySpy.and.rejectWith("Factory threw");
service
.onState()
.subscribe((data) => {
try {
expect(data.glueInstance).toBeFalsy();
expect(data.error).toBeTruthy();
ready();
} catch (error) {
done.fail(error);
}
});
service.start().then(ready).catch(done.fail);
});
it("should resolve, but emit an error when the factory function timed out", (done: DoneFn) => {
const ready = waitFor(2, done);
factorySpy.and.returnValue(new Promise(() => {
// never resolve
}));
service
.onState()
.subscribe((data) => {
try {
expect(data.glueInstance).toBeFalsy();
expect(data.error).toBeTruthy();
ready();
} catch (error) {
done.fail(error);
}
});
service.start().then(ready).catch(done.fail);
});
it("should resolve without waiting for the factory when holdInit is false", (done: DoneFn) => {
const ready = waitFor(2, done);
let factoryResolve = false;
settingsMock.holdInit = false;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
settingsMock.factory = (): Promise<any> => {
return new Promise((resolve) => {
setImmediate(() => {
factoryResolve = true;
resolve();
ready();
});
});
};
const startPromise = service.start();
startPromise
.then(() => {
expect(factoryResolve).toBeFalse();
ready();
})
.catch(() => {
done.fail("The factory resolved before the start, with holdInit: false");
});
});
it("should wait for the factory to resolve when holdInit is true", (done: DoneFn) => {
const ready = waitFor(2, done);
let factoryResolve = false;
settingsMock.holdInit = true;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
settingsMock.factory = (): Promise<any> => {
return new Promise((resolve) => {
setImmediate(() => {
factoryResolve = true;
resolve();
ready();
});
});
};
const startPromise = service.start();
startPromise
.then(() => {
expect(factoryResolve).toBeTrue();
ready();
})
.catch(() => {
done.fail("The factory resolved after the start, with holdInit: true");
});
});
});
}); | the_stack |
import * as nodeGit from 'nodegit';
import { CloneOptions, Commit, DiffDelta, DiffFile, FetchOptions, Oid, Repository, Revwalk, StatusFile } from 'nodegit';
import * as path from 'path';
import {
GitAuthenticationFailError,
GitCloneOptions,
GitCommitOptions,
GitError,
GitErrorCodes,
gitErrorRegexes,
GitFindRemoteOptions,
GitGetHistoryOptions,
GitGetHistoryResult,
GitMergeConflictedError,
GitNetworkError,
GitRemoteNotFoundError,
GitSetRemoteOptions,
GitSyncWithRemoteOptions,
GitSyncWithRemoteResult,
} from '../../core/git';
import { logMonitor } from '../../core/log-monitor';
import {
VcsAuthenticationInfo,
VcsAuthenticationTypes,
VcsCommitItem,
VcsFileChange,
VcsFileChangeStatusTypes,
} from '../../core/vcs';
import { datetime, DateUnits } from '../../libs/datetime';
import { IpcActionHandler } from '../../libs/ipc';
import { Service } from './service';
let uniqueId = 0;
interface FetchOptionsWithTriesInfo {
fetchOptions: FetchOptions;
triesKey: string | null;
}
export class GitService extends Service {
private git = nodeGit;
private fetchTriesMap = new Map<string, number>();
constructor() {
super('git');
}
init(): void {
}
destroy(): void {
super.destroy();
this.fetchTriesMap.clear();
}
async isRepositoryExists(dirPath: string): Promise<boolean> {
try {
const repository = await this.openRepository(dirPath);
repository.free();
return true;
} catch (error) {
return false;
}
}
async openRepository(dirPath: string): Promise<Repository> {
return this.git.Repository.open(dirPath);
}
@IpcActionHandler('createRepository')
async createRepository(dirPath: string): Promise<void> {
const repository = await this.git.Repository.init(dirPath, 0);
repository.free();
}
@IpcActionHandler('cloneRepository')
async cloneRepository(options: GitCloneOptions): Promise<void> {
const { triesKey, fetchOptions } = this.getFetchOptions(options.authentication);
const cloneOptions: CloneOptions = {
fetchOpts: fetchOptions,
bare: 0,
};
const repository = await this.git.Clone.clone(
options.url,
options.localPath,
cloneOptions,
);
if (triesKey) {
this.fetchTriesMap.delete(triesKey);
}
repository.free();
}
@IpcActionHandler('getFileChanges')
async getFileChanges(dirPath: string): Promise<VcsFileChange[]> {
const repository = await this.openRepository(dirPath);
const statues = await repository.getStatusExt({
// This give us to track re-named files.
// See: https://github.com/libgit2/libgit2/issues/429
flags: this.git.Status.OPT.INCLUDE_UNTRACKED,
});
const fileChanges = statues.map(status => this.parseFileChange(dirPath, status));
repository.free();
return fileChanges;
}
@IpcActionHandler('commit')
async commit(option: GitCommitOptions): Promise<string> {
const repository = await this.openRepository(option.workspaceDirPath);
// First add all files to index. Un-tracked file.
const index = await repository.refreshIndex();
const allTasks: Promise<any>[] = [];
option.fileChanges.forEach(({ status, filePath }) => {
if (status === VcsFileChangeStatusTypes.REMOVED) {
allTasks.push(index.removeByPath(filePath));
} else if (status === VcsFileChangeStatusTypes.NEW
|| status === VcsFileChangeStatusTypes.MODIFIED
|| status === VcsFileChangeStatusTypes.RENAMED) {
allTasks.push(index.addByPath(filePath));
}
// TODO(@seokju-na): Handle conflicted, ignored files.
});
await Promise.all(allTasks);
await index.write();
const signature = option.createdAt
? this.git.Signature.create(
option.author.name,
option.author.email,
option.createdAt.time,
option.createdAt.offset,
)
: this.git.Signature.now(option.author.name, option.author.email);
const treeOId = await index.writeTree();
let parentCommit: Commit;
try {
const head = await this.git.Reference.nameToId(repository, 'HEAD');
parentCommit = await repository.getCommit(head);
} catch (err) {
}
const commitId = await repository.createCommit(
'HEAD',
signature,
signature,
option.message,
treeOId,
parentCommit ? [parentCommit] : [],
);
signature.free();
repository.free();
return commitId.tostrS();
}
@IpcActionHandler('getCommitHistory')
async getCommitHistory(options: GitGetHistoryOptions): Promise<GitGetHistoryResult> {
const repository = await this.openRepository(options.workspaceDirPath);
const walker = repository.createRevWalk();
options.commitId
? walker.push(Oid.fromString(options.commitId))
: walker.pushHead();
walker.sorting(Revwalk.SORT.TIME);
let history: VcsCommitItem[];
// If date range provided, find commits for period.
if (options.dateRange) {
const until = new Date(options.dateRange.until);
const since = new Date(options.dateRange.since);
// Unexpected behavior.
// We need to check if the last item aborted the checkFn.
// 'getCommitsUntil' returns the last item, even if it does not satisfied the checkFn.
// So we should drop the last item.
let isLastAborted = false;
const isCommitCreatedAfterSince = (commit: Commit) => {
const isAfterOrSame = datetime.isAfterOrSame(new Date(commit.timeMs()), since, DateUnits.DAY);
isLastAborted = !isAfterOrSame;
return isAfterOrSame;
};
const isCommitCreatedBeforeUntil =
(commit: Commit) => datetime.isBeforeOrSame(new Date(commit.timeMs()), until, DateUnits.DAY);
const foundCommits = await walker.getCommitsUntil(isCommitCreatedAfterSince) as Commit[];
foundCommits.reverse();
// Drop the last item (but in this line, array has been reversed, so it would be the first item)
if (isLastAborted) {
foundCommits.shift();
}
const startIndex = foundCommits.findIndex(commit => !isCommitCreatedBeforeUntil(commit));
if (startIndex !== -1) {
const removedCommits = foundCommits.splice(startIndex, foundCommits.length - startIndex);
removedCommits.forEach(commit => commit.free());
}
history = foundCommits.reverse().map(commit => this.parseCommit(commit));
foundCommits.forEach(commit => commit.free());
} else {
const commits = await walker.getCommits(options.size);
history = commits.map(commit => this.parseCommit(commit));
commits.forEach(commit => commit.free());
}
const result = {
history,
next: null,
previous: { ...options },
};
// Check for next request.
try {
const next = await walker.next();
result.next = {
workspaceDirPath: options.workspaceDirPath,
commitId: next.tostrS(),
size: options.size,
};
} catch (error) {
// There is no next commit.
}
/** NOTE: '@types/nodegit' is incorrect. */
(<any>walker).free();
repository.free();
return result;
}
@IpcActionHandler('isRemoteExists')
async isRemoteExists(options: GitFindRemoteOptions): Promise<boolean> {
const repository = await this.openRepository(options.workspaceDirPath);
try {
const remote = await repository.getRemote(options.remoteName);
remote.free();
return true;
} catch (error) {
if (gitErrorRegexes[GitErrorCodes.REMOTE_NOT_FOUND].test(error.message)) {
return false;
} else {
throw error;
}
}
}
@IpcActionHandler('getRemoteUrl')
async getRemoteUrl(options: GitFindRemoteOptions): Promise<string> {
const repository = await this.openRepository(options.workspaceDirPath);
const remote = await repository.getRemote(options.remoteName);
const remoteUrl = remote.url();
remote.free();
repository.free();
return remoteUrl;
}
@IpcActionHandler('setRemote')
async setRemote(options: GitSetRemoteOptions): Promise<void> {
const { remoteName, remoteUrl } = options;
const repository = await this.openRepository(options.workspaceDirPath);
// If remote already exists, delete first.
try {
await this.git.Remote.lookup(repository, remoteName);
await this.git.Remote.delete(repository, remoteName);
} catch (error) {
const message = error.message ? error.message : '';
// Only remote not found error accepted. Other should be thrown.
if (!gitErrorRegexes[GitErrorCodes.REMOTE_NOT_FOUND].test(message)) {
repository.free();
throw error;
}
}
try {
await this.git.Remote.create(repository, remoteName, remoteUrl);
} catch (error) {
throw error;
} finally {
repository.free();
}
}
@IpcActionHandler('syncWithRemote')
async syncWithRemote(options: GitSyncWithRemoteOptions): Promise<GitSyncWithRemoteResult> {
const repository = await this.openRepository(options.workspaceDirPath);
const remote = await repository.getRemote(options.remoteName);
// Fetch remote
const pullFetchOptions = this.getFetchOptions(options.authentication);
const signature = this.git.Signature.now(options.author.name, options.author.email);
await repository.fetch(remote, pullFetchOptions.fetchOptions);
// Pull if master head exists.
const refList = await remote.referenceList();
const refHeadNames = refList.map(head => head.name());
if (refHeadNames.includes('refs/heads/master')) {
try {
await repository.mergeBranches(
'master',
`${options.remoteName}/master`,
signature,
this.git.Merge.PREFERENCE.NONE,
);
} catch (index) { // Repository#mergeBranchs throws index as error.
throw new GitMergeConflictedError();
}
this.fetchTriesMap.delete(pullFetchOptions.triesKey);
}
// Push
const pushFetchOptions = this.getFetchOptions(options.authentication);
await remote.push(
['refs/heads/master:refs/heads/master'],
{ callbacks: pushFetchOptions.fetchOptions.callbacks },
);
this.fetchTriesMap.delete(pushFetchOptions.triesKey);
const result: GitSyncWithRemoteResult = {
timestamp: Date.now(),
remoteUrl: remote.url(),
};
remote.free();
repository.free();
return result;
}
handleError(error: any): GitError | any {
const out = error.message;
if (out) {
for (const code of Object.keys(gitErrorRegexes)) {
if (gitErrorRegexes[code].test(out)) {
return this.createMatchedError(code as GitErrorCodes);
}
}
}
logMonitor.logException(error);
return error;
}
private createMatchedError(code: GitErrorCodes): GitError {
switch (code) {
case GitErrorCodes.AUTHENTICATION_FAIL:
return new GitAuthenticationFailError();
case GitErrorCodes.REMOTE_NOT_FOUND:
return new GitRemoteNotFoundError();
case GitErrorCodes.NETWORK_ERROR:
return new GitNetworkError();
}
}
private parseFileChange(workingDir: string, status: StatusFile): VcsFileChange {
let fileChange = {
filePath: status.path(),
workingDirectoryPath: workingDir,
absoluteFilePath: path.resolve(workingDir, status.path()),
} as VcsFileChange;
if (status.isNew()) {
fileChange = { ...fileChange, status: VcsFileChangeStatusTypes.NEW };
} else if (status.isRenamed()) {
fileChange = {
...fileChange,
status: VcsFileChangeStatusTypes.RENAMED,
};
let diff: DiffDelta;
if (status.inIndex()) {
diff = status.headToIndex();
} else if (status.inWorkingTree()) {
diff = status.indexToWorkdir();
}
if (diff) {
/** NOTE: '@types/nodegit' is incorrect. */
const oldFile = (diff as any).oldFile() as DiffFile;
const newFile = (diff as any).newFile() as DiffFile;
fileChange = {
...fileChange,
headToIndexDiff: {
oldFilePath: oldFile.path(),
newFilePath: newFile.path(),
},
};
}
} else if (status.isModified()) {
fileChange = { ...fileChange, status: VcsFileChangeStatusTypes.MODIFIED };
} else if (status.isDeleted()) {
fileChange = { ...fileChange, status: VcsFileChangeStatusTypes.REMOVED };
}
// TODO: Handle ignored, conflicted file changes.
return fileChange;
}
private parseCommit(commit: Commit): VcsCommitItem {
return {
commitId: commit.id().tostrS(),
commitHash: commit.sha(),
authorName: commit.author().name(),
authorEmail: commit.author().email(),
committerName: commit.author().name(),
committerEmail: commit.author().email(),
summary: commit.summary(),
description: commit.body(),
timestamp: commit.timeMs(),
};
}
/** Get fetch options. */
private getFetchOptions(authentication?: VcsAuthenticationInfo): FetchOptionsWithTriesInfo {
let key: string = null;
const options: FetchOptions = {
callbacks: {},
};
// Github will fail cert check on some OSX machines
// This overrides that check.
options.callbacks.certificateCheck = () => 1;
if (authentication) {
key = `git-fetch-try-${uniqueId++}`;
this.fetchTriesMap.set(key, 0);
options.callbacks.credentials = () => {
const tries = this.fetchTriesMap.get(key);
/**
* Note that this is important.
* libgit2 doesn't stop checking credential even if authorize failed.
* So if we do not take proper action, we will end up in an infinite loop.
* See also:
* https://github.com/nodegit/nodegit/issues/1133
*
* Check if tries goes at least 5, throw error to exit the infinite loop.
*/
if (tries > 5) {
throw new Error('Authentication Error');
}
this.fetchTriesMap.set(key, tries + 1);
switch (authentication.type) {
case VcsAuthenticationTypes.BASIC:
return this.git.Cred.userpassPlaintextNew(
authentication.username,
authentication.password,
);
case VcsAuthenticationTypes.OAUTH2_TOKEN:
return this.git.Cred.userpassPlaintextNew(
authentication.token,
'x-oauth-basic',
);
}
};
}
return {
triesKey: key,
fetchOptions: options,
};
}
} | the_stack |
module android.widget {
import Canvas = android.graphics.Canvas;
import Rect = android.graphics.Rect;
import Animatable = android.graphics.drawable.Animatable;
import AnimationDrawable = android.graphics.drawable.AnimationDrawable;
import Drawable = android.graphics.drawable.Drawable;
import LayerDrawable = android.graphics.drawable.LayerDrawable;
import StateListDrawable = android.graphics.drawable.StateListDrawable;
import ClipDrawable = android.graphics.drawable.ClipDrawable;
import SynchronizedPool = android.util.Pools.SynchronizedPool;
import Gravity = android.view.Gravity;
import View = android.view.View;
import AlphaAnimation = android.view.animation.AlphaAnimation;
import Animation = android.view.animation.Animation;
import AnimationUtils = android.view.animation.AnimationUtils;
import Interpolator = android.view.animation.Interpolator;
import LinearInterpolator = android.view.animation.LinearInterpolator;
import Transformation = android.view.animation.Transformation;
import ArrayList = java.util.ArrayList;
import LinearLayout = android.widget.LinearLayout;
import TextView = android.widget.TextView;
import R = android.R;
import NetDrawable = androidui.image.NetDrawable;
import AttrBinder = androidui.attr.AttrBinder;
/**
* <p>
* Visual indicator of progress in some operation. Displays a bar to the user
* representing how far the operation has progressed; the application can
* change the amount of progress (modifying the length of the bar) as it moves
* forward. There is also a secondary progress displayable on a progress bar
* which is useful for displaying intermediate progress, such as the buffer
* level during a streaming playback progress bar.
* </p>
*
* <p>
* A progress bar can also be made indeterminate. In indeterminate mode, the
* progress bar shows a cyclic animation without an indication of progress. This mode is used by
* applications when the length of the task is unknown. The indeterminate progress bar can be either
* a spinning wheel or a horizontal bar.
* </p>
*
* <p>The following code example shows how a progress bar can be used from
* a worker thread to update the user interface to notify the user of progress:
* </p>
*
* <pre>
* public class MyActivity extends Activity {
* private static final int PROGRESS = 0x1;
*
* private ProgressBar mProgress;
* private int mProgressStatus = 0;
*
* private Handler mHandler = new Handler();
*
* protected void onCreate(Bundle icicle) {
* super.onCreate(icicle);
*
* setContentView(R.layout.progressbar_activity);
*
* mProgress = (ProgressBar) findViewById('progress'_bar);
*
* // Start lengthy operation in a background thread
* new Thread(new Runnable() {
* public void run() {
* while (mProgressStatus < 100) {
* mProgressStatus = doWork();
*
* // Update the progress bar
* mHandler.post(new Runnable() {
* public void run() {
* mProgress.setProgress(mProgressStatus);
* }
* });
* }
* }
* }).start();
* }
* }</pre>
*
* <p>To add a progress bar to a layout file, you can use the {@code <ProgressBar>} element.
* By default, the progress bar is a spinning wheel (an indeterminate indicator). To change to a
* horizontal progress bar, apply the {@link android.R.style#Widget_ProgressBar_Horizontal
* Widget.ProgressBar.Horizontal} style, like so:</p>
*
* <pre>
* <ProgressBar
* style="@android:style/Widget.ProgressBar.Horizontal"
* ... /></pre>
*
* <p>If you will use the progress bar to show real progress, you must use the horizontal bar. You
* can then increment the progress with {@link #incrementProgressBy incrementProgressBy()} or
* {@link #setProgress setProgress()}. By default, the progress bar is full when it reaches 100. If
* necessary, you can adjust the maximum value (the value for a full bar) using the {@link
* android.R.styleable#ProgressBar_max android:max} attribute. Other attributes available are listed
* below.</p>
*
* <p>Another common style to apply to the progress bar is {@link
* android.R.style#Widget_ProgressBar_Small Widget.ProgressBar.Small}, which shows a smaller
* version of the spinning wheel—useful when waiting for content to load.
* For example, you can insert this kind of progress bar into your default layout for
* a view that will be populated by some content fetched from the Internet—the spinning wheel
* appears immediately and when your application receives the content, it replaces the progress bar
* with the loaded content. For example:</p>
*
* <pre>
* <LinearLayout
* android:orientation="horizontal"
* ... >
* <ProgressBar
* android:layout_width="wrap_content"
* android:layout_height="wrap_content"
* style="@android:style/Widget.ProgressBar.Small"
* android:layout_marginRight="5dp" />
* <TextView
* android:layout_width="wrap_content"
* android:layout_height="wrap_content"
* android:text="@string/loading" />
* </LinearLayout></pre>
*
* <p>Other progress bar styles provided by the system include:</p>
* <ul>
* <li>{@link android.R.style#Widget_ProgressBar_Horizontal Widget.ProgressBar.Horizontal}</li>
* <li>{@link android.R.style#Widget_ProgressBar_Small Widget.ProgressBar.Small}</li>
* <li>{@link android.R.style#Widget_ProgressBar_Large Widget.ProgressBar.Large}</li>
* <li>{@link android.R.style#Widget_ProgressBar_Inverse Widget.ProgressBar.Inverse}</li>
* <li>{@link android.R.style#Widget_ProgressBar_Small_Inverse
* Widget.ProgressBar.Small.Inverse}</li>
* <li>{@link android.R.style#Widget_ProgressBar_Large_Inverse
* Widget.ProgressBar.Large.Inverse}</li>
* </ul>
* <p>The "inverse" styles provide an inverse color scheme for the spinner, which may be necessary
* if your application uses a light colored theme (a white background).</p>
*
* <p><strong>XML attributes</b></strong>
* <p>
* See {@link android.R.styleable#ProgressBar ProgressBar Attributes},
* {@link android.R.styleable#View View Attributes}
* </p>
*
* @attr ref android.R.styleable#ProgressBar_animationResolution
* @attr ref android.R.styleable#ProgressBar_indeterminate
* @attr ref android.R.styleable#ProgressBar_indeterminateBehavior
* @attr ref android.R.styleable#ProgressBar_indeterminateDrawable
* @attr ref android.R.styleable#ProgressBar_indeterminateDuration
* @attr ref android.R.styleable#ProgressBar_indeterminateOnly
* @attr ref android.R.styleable#ProgressBar_interpolator
* @attr ref android.R.styleable#ProgressBar_max
* @attr ref android.R.styleable#ProgressBar_maxHeight
* @attr ref android.R.styleable#ProgressBar_maxWidth
* @attr ref android.R.styleable#ProgressBar_minHeight
* @attr ref android.R.styleable#ProgressBar_minWidth
* @attr ref android.R.styleable#ProgressBar_mirrorForRtl
* @attr ref android.R.styleable#ProgressBar_progress
* @attr ref android.R.styleable#ProgressBar_progressDrawable
* @attr ref android.R.styleable#ProgressBar_secondaryProgress
*/
export class ProgressBar extends View {
private static MAX_LEVEL:number = 10000;
private static TIMEOUT_SEND_ACCESSIBILITY_EVENT:number = 200;
mMinWidth:number = 0;
mMaxWidth:number = 0;
mMinHeight:number = 0;
mMaxHeight:number = 0;
private mProgress:number = 0;
private mSecondaryProgress:number = 0;
private mMax:number = 0;
private mBehavior:number = 0;
private mDuration:number = 0;
private mIndeterminate:boolean;
private mOnlyIndeterminate:boolean;
private mTransformation:Transformation;
private mAnimation:AlphaAnimation;
private mHasAnimation:boolean;
private mIndeterminateDrawable:Drawable;
private mProgressDrawable:Drawable;
private mCurrentDrawable:Drawable;
protected mSampleTile:NetDrawable;
private mNoInvalidate:boolean;
private mInterpolator:Interpolator;
//private mRefreshProgressRunnable:ProgressBar.RefreshProgressRunnable;
//private mUiThreadId:number = 0;
private mShouldStartAnimationDrawable:boolean;
private mInDrawing:boolean;
private mAttached:boolean;
private mRefreshIsPosted:boolean;
mMirrorForRtl:boolean = false;
private mRefreshData:ArrayList<ProgressBar.RefreshData> = new ArrayList<ProgressBar.RefreshData>();
//private mAccessibilityEventSender:ProgressBar.AccessibilityEventSender;
constructor(context:android.content.Context, bindElement?:HTMLElement, defStyle=android.R.attr.progressBarStyle) {
super(context, bindElement, defStyle);
//this.mUiThreadId = Thread.currentThread().getId();
this.initProgressBar();
let a = context.obtainStyledAttributes(bindElement, defStyle);
this.mNoInvalidate = true;
let drawable: Drawable = a.getDrawable('progressDrawable');
if (drawable != null) {
drawable = this.tileify(drawable, false);
// Calling this method can set mMaxHeight, make sure the corresponding
// XML attribute for mMaxHeight is read after calling this method
this.setProgressDrawable(drawable);
}
this.mDuration = a.getInt('indeterminateDuration', this.mDuration);
this.mMinWidth = a.getDimensionPixelSize('minWidth', this.mMinWidth);
this.mMaxWidth = a.getDimensionPixelSize('maxWidth', this.mMaxWidth);
this.mMinHeight = a.getDimensionPixelSize('minHeight', this.mMinHeight);
this.mMaxHeight = a.getDimensionPixelSize('maxHeight', this.mMaxHeight);
if(a.getAttrValue('indeterminateBehavior') == 'cycle') {
this.mBehavior = Animation.REVERSE;
} else {
this.mBehavior = Animation.RESTART;
}
// const resID: number = a.getResourceId(com.android.internal.R.styleable.ProgressBar_interpolator, // default to linear interpolator
// android.R.anim.linear_interpolator);
// if (resID > 0) {
// this.setInterpolator(context, resID);
// }
this.setMax(a.getInt('max', this.mMax));
this.setProgress(a.getInt('progress', this.mProgress));
this.setSecondaryProgress(a.getInt('secondaryProgress', this.mSecondaryProgress));
drawable = a.getDrawable('indeterminateDrawable');
if (drawable != null) {
drawable = this.tileifyIndeterminate(drawable);
this.setIndeterminateDrawable(drawable);
}
this.mOnlyIndeterminate = a.getBoolean('indeterminateOnly', this.mOnlyIndeterminate);
this.mNoInvalidate = false;
this.setIndeterminate(this.mOnlyIndeterminate || a.getBoolean('indeterminate', this.mIndeterminate));
this.mMirrorForRtl = a.getBoolean('mirrorForRtl', this.mMirrorForRtl);
a.recycle();
}
protected createClassAttrBinder(): androidui.attr.AttrBinder.ClassBinderMap {
return super.createClassAttrBinder().set('progressDrawable', {
setter(v:ProgressBar, value:any, a:AttrBinder) {
let drawable = a.parseDrawable(value);
if(drawable!=null){
drawable = v.tileify(drawable, false);
v.setProgressDrawable(drawable);
}
}, getter(v:ProgressBar) {
return v.getProgressDrawable();
}
}).set('indeterminateDuration', {
setter(v:ProgressBar, value:any, a:AttrBinder) {
v.mDuration = Math.floor(a.parseInt(value, v.mDuration));
}, getter(v:ProgressBar) {
return v.mDuration;
}
}).set('minWidth', {
setter(v:ProgressBar, value:any, a:AttrBinder) {
v.mMinWidth = Math.floor(a.parseNumberPixelSize(value, v.mMinWidth));
}, getter(v:ProgressBar) {
return v.mMinWidth;
}
}).set('maxWidth', {
setter(v:ProgressBar, value:any, a:AttrBinder) {
v.mMaxWidth = Math.floor(a.parseNumberPixelSize(value, v.mMaxWidth));
}, getter(v:ProgressBar) {
return v.mMaxWidth;
}
}).set('minHeight', {
setter(v:ProgressBar, value:any, a:AttrBinder) {
v.mMinHeight = Math.floor(a.parseNumberPixelSize(value, v.mMinHeight));
}, getter(v:ProgressBar) {
return v.mMinHeight;
}
}).set('maxHeight', {
setter(v:ProgressBar, value:any, a:AttrBinder) {
v.mMaxHeight = Math.floor(a.parseNumberPixelSize(value, v.mMaxHeight));
}, getter(v:ProgressBar) {
return v.mMaxHeight;
}
}).set('indeterminateBehavior', {
setter(v:ProgressBar, value:any, a:AttrBinder) {
if (Number.isInteger(Number.parseInt(value))) {
v.mBehavior = Number.parseInt(value);
} else {
if (value + ''.toLowerCase() == 'cycle') {
v.mBehavior = Animation.REVERSE;
} else {
v.mBehavior = Animation.RESTART;
}
}
}, getter(v:ProgressBar) {
return v.mBehavior;
}
}).set('interpolator', {
setter(v:ProgressBar, value:any, a:AttrBinder) {
}, getter(v:ProgressBar) {
}
}).set('max', {
setter(v:ProgressBar, value:any, a:AttrBinder) {
v.setMax(a.parseInt(value, v.mMax));
}, getter(v:ProgressBar) {
return v.mMax;
}
}).set('progress', {
setter(v:ProgressBar, value:any, a:AttrBinder) {
v.setProgress(a.parseInt(value, v.mProgress));
}, getter(v:ProgressBar) {
return v.mProgress;
}
}).set('secondaryProgress', {
setter(v:ProgressBar, value:any, a:AttrBinder) {
v.setSecondaryProgress(a.parseInt(value, v.mSecondaryProgress));
}, getter(v:ProgressBar) {
return v.mSecondaryProgress;
}
}).set('indeterminateDrawable', {
setter(v:ProgressBar, value:any, a:AttrBinder) {
let drawable = a.parseDrawable(value);
if(drawable!=null){
drawable = v.tileifyIndeterminate(drawable);
v.setIndeterminateDrawable(drawable);
}
}, getter(v:ProgressBar) {
return v.mIndeterminateDrawable;
}
}).set('indeterminateOnly', {
setter(v:ProgressBar, value:any, a:AttrBinder) {
v.mOnlyIndeterminate = a.parseBoolean(value, v.mOnlyIndeterminate);
v.setIndeterminate(v.mOnlyIndeterminate || v.mIndeterminate);
}, getter(v:ProgressBar) {
return v.mOnlyIndeterminate;
}
}).set('indeterminate', {
setter(v:ProgressBar, value:any, a:AttrBinder) {
v.setIndeterminate(v.mOnlyIndeterminate || a.parseBoolean(value, v.mIndeterminate));
}, getter(v:ProgressBar) {
return v.mIndeterminate;
}
});
}
/**
* Converts a drawable to a tiled version of itself. It will recursively
* traverse layer and state list drawables.
*/
private tileify(drawable:Drawable, clip:boolean):Drawable {
if (drawable instanceof LayerDrawable) {
let background:LayerDrawable = <LayerDrawable> drawable;
const N:number = background.getNumberOfLayers();
let outDrawables:Drawable[] = new Array<Drawable>(N);
let drawableChange = false;
for (let i:number = 0; i < N; i++) {
let id:string = background.getId(i);
let orig = background.getDrawable(i);
outDrawables[i] = this.tileify(orig, (id == R.id.progress || id == R.id.secondaryProgress));
drawableChange = drawableChange || outDrawables[i] !== orig;
}
if(!drawableChange) return background;
let newBg:LayerDrawable = new LayerDrawable(outDrawables);
for (let i:number = 0; i < N; i++) {
newBg.setId(i, background.getId(i));
}
return newBg;
} else if (drawable instanceof StateListDrawable) {
let _in:StateListDrawable = <StateListDrawable> drawable;
let out:StateListDrawable = new StateListDrawable();
let numStates:number = _in.getStateCount();
for (let i:number = 0; i < numStates; i++) {
out.addState(_in.getStateSet(i), this.tileify(_in.getStateDrawable(i), clip));
}
return out;
//} else if (drawable instanceof BitmapDrawable) {
// const tileBitmap:Bitmap = (<BitmapDrawable> drawable).getBitmap();
// if (this.mSampleTile == null) {
// this.mSampleTile = tileBitmap;
// }
// const shapeDrawable:ShapeDrawable = new ShapeDrawable(this.getDrawableShape());
// const bitmapShader:BitmapShader = new BitmapShader(tileBitmap, Shader.TileMode.REPEAT, Shader.TileMode.CLAMP);
// shapeDrawable.getPaint().setShader(bitmapShader);
// return (clip) ? new ClipDrawable(shapeDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL) : shapeDrawable;
} else if (drawable instanceof NetDrawable) {
const netDrawable = (<NetDrawable> drawable);
if (this.mSampleTile == null) {
this.mSampleTile = netDrawable;
}
netDrawable.setTileMode(NetDrawable.TileMode.REPEAT, null);
return (clip) ? new ClipDrawable(netDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL) : netDrawable;
}
return drawable;
}
//getDrawableShape():Shape {
// const roundedCorners:number[] = [ 5, 5, 5, 5, 5, 5, 5, 5 ];
// return new RoundRectShape(roundedCorners, null, null);
//}
/**
* Convert a AnimationDrawable for use as a barberpole animation.
* Each frame of the animation is wrapped in a ClipDrawable and
* given a tiling BitmapShader.
*/
private tileifyIndeterminate(drawable:Drawable):Drawable {
if (drawable instanceof AnimationDrawable) {
let background:AnimationDrawable = <AnimationDrawable> drawable;
const N:number = background.getNumberOfFrames();
let newBg:AnimationDrawable = new AnimationDrawable();
newBg.setOneShot(background.isOneShot());
for (let i:number = 0; i < N; i++) {
let frame:Drawable = this.tileify(background.getFrame(i), true);
frame.setLevel(10000);
newBg.addFrame(frame, background.getDuration(i));
}
newBg.setLevel(10000);
drawable = newBg;
}
return drawable;
}
/**
* <p>
* Initialize the progress bar's default values:
* </p>
* <ul>
* <li>progress = 0</li>
* <li>max = 100</li>
* <li>animation duration = 4000 ms</li>
* <li>indeterminate = false</li>
* <li>behavior = repeat</li>
* </ul>
*/
private initProgressBar():void {
this.mMax = 100;
this.mProgress = 0;
this.mSecondaryProgress = 0;
this.mIndeterminate = false;
this.mOnlyIndeterminate = false;
this.mDuration = 4000;
this.mBehavior = AlphaAnimation.RESTART;
this.mMinWidth = 24;
this.mMaxWidth = 48;
this.mMinHeight = 24;
this.mMaxHeight = 48;
}
/**
* <p>Indicate whether this progress bar is in indeterminate mode.</p>
*
* @return true if the progress bar is in indeterminate mode
*/
isIndeterminate():boolean {
return this.mIndeterminate;
}
/**
* <p>Change the indeterminate mode for this progress bar. In indeterminate
* mode, the progress is ignored and the progress bar shows an infinite
* animation instead.</p>
*
* If this progress bar's style only supports indeterminate mode (such as the circular
* progress bars), then this will be ignored.
*
* @param indeterminate true to enable the indeterminate mode
*/
setIndeterminate(indeterminate:boolean):void {
if ((!this.mOnlyIndeterminate || !this.mIndeterminate) && indeterminate != this.mIndeterminate) {
this.mIndeterminate = indeterminate;
if (indeterminate) {
// swap between indeterminate and regular backgrounds
this.mCurrentDrawable = this.mIndeterminateDrawable;
this.startAnimation();
} else {
this.mCurrentDrawable = this.mProgressDrawable;
this.stopAnimation();
}
}
}
/**
* <p>Get the drawable used to draw the progress bar in
* indeterminate mode.</p>
*
* @return a {@link android.graphics.drawable.Drawable} instance
*
* @see #setIndeterminateDrawable(android.graphics.drawable.Drawable)
* @see #setIndeterminate(boolean)
*/
getIndeterminateDrawable():Drawable {
return this.mIndeterminateDrawable;
}
/**
* <p>Define the drawable used to draw the progress bar in
* indeterminate mode.</p>
*
* @param d the new drawable
*
* @see #getIndeterminateDrawable()
* @see #setIndeterminate(boolean)
*/
setIndeterminateDrawable(d:Drawable):void {
if (d != null) {
d.setCallback(this);
}
this.mIndeterminateDrawable = d;
//if (this.mIndeterminateDrawable != null && this.canResolveLayoutDirection()) {
// this.mIndeterminateDrawable.setLayoutDirection(this.getLayoutDirection());
//}
if (this.mIndeterminate) {
this.mCurrentDrawable = d;
this.postInvalidate();
}
}
/**
* <p>Get the drawable used to draw the progress bar in
* progress mode.</p>
*
* @return a {@link android.graphics.drawable.Drawable} instance
*
* @see #setProgressDrawable(android.graphics.drawable.Drawable)
* @see #setIndeterminate(boolean)
*/
getProgressDrawable():Drawable {
return this.mProgressDrawable;
}
/**
* <p>Define the drawable used to draw the progress bar in
* progress mode.</p>
*
* @param d the new drawable
*
* @see #getProgressDrawable()
* @see #setIndeterminate(boolean)
*/
setProgressDrawable(d:Drawable):void {
let needUpdate:boolean;
if (this.mProgressDrawable != null && d != this.mProgressDrawable) {
this.mProgressDrawable.setCallback(null);
needUpdate = true;
} else {
needUpdate = false;
}
if (d != null) {
d.setCallback(this);
//if (this.canResolveLayoutDirection()) {
// d.setLayoutDirection(this.getLayoutDirection());
//}
// Make sure the ProgressBar is always tall enough
let drawableHeight:number = d.getMinimumHeight();
if (this.mMaxHeight < drawableHeight) {
this.mMaxHeight = drawableHeight;
this.requestLayout();
}
}
this.mProgressDrawable = d;
if (!this.mIndeterminate) {
this.mCurrentDrawable = d;
this.postInvalidate();
}
if (needUpdate) {
this.updateDrawableBounds(this.getWidth(), this.getHeight());
this.updateDrawableState();
this.doRefreshProgress(R.id.progress, this.mProgress, false, false);
this.doRefreshProgress(R.id.secondaryProgress, this.mSecondaryProgress, false, false);
}
}
/**
* @return The drawable currently used to draw the progress bar
*/
getCurrentDrawable():Drawable {
return this.mCurrentDrawable;
}
protected verifyDrawable(who:Drawable):boolean {
return who == this.mProgressDrawable || who == this.mIndeterminateDrawable || super.verifyDrawable(who);
}
jumpDrawablesToCurrentState():void {
super.jumpDrawablesToCurrentState();
if (this.mProgressDrawable != null)
this.mProgressDrawable.jumpToCurrentState();
if (this.mIndeterminateDrawable != null)
this.mIndeterminateDrawable.jumpToCurrentState();
}
///**
// * @hide
// */
//onResolveDrawables(layoutDirection:number):void {
// const d:Drawable = this.mCurrentDrawable;
// if (d != null) {
// d.setLayoutDirection(layoutDirection);
// }
// if (this.mIndeterminateDrawable != null) {
// this.mIndeterminateDrawable.setLayoutDirection(layoutDirection);
// }
// if (this.mProgressDrawable != null) {
// this.mProgressDrawable.setLayoutDirection(layoutDirection);
// }
//}
postInvalidate():void {
if (!this.mNoInvalidate) {
super.postInvalidate();
}
}
private doRefreshProgress(id:string, progress:number, fromUser:boolean, callBackToApp:boolean):void {
let scale:number = this.mMax > 0 ? <number> progress / <number> this.mMax : 0;
const d:Drawable = this.mCurrentDrawable;
if (d != null) {
let progressDrawable:Drawable = null;
if (d instanceof LayerDrawable) {
progressDrawable = (<LayerDrawable> d).findDrawableByLayerId(id);
//if (progressDrawable != null && this.canResolveLayoutDirection()) {
// progressDrawable.setLayoutDirection(this.getLayoutDirection());
//}
}
const level:number = Math.floor((scale * ProgressBar.MAX_LEVEL));
(progressDrawable != null ? progressDrawable : d).setLevel(level);
} else {
this.invalidate();
}
if (callBackToApp && id == R.id.progress) {
this.onProgressRefresh(scale, fromUser);
}
}
onProgressRefresh(scale:number, fromUser:boolean):void {
//if (AccessibilityManager.getInstance(this.mContext).isEnabled()) {
// this.scheduleAccessibilityEventSender();
//}
}
private refreshProgress(id:string, progress:number, fromUser:boolean):void {
//if (this.mUiThreadId == Thread.currentThread().getId()) {
this.doRefreshProgress(id, progress, fromUser, true);
//} else {
// if (this.mRefreshProgressRunnable == null) {
// this.mRefreshProgressRunnable = new ProgressBar.RefreshProgressRunnable(this);
// }
// const rd:ProgressBar.RefreshData = ProgressBar.RefreshData.obtain(id, progress, fromUser);
// this.mRefreshData.add(rd);
// if (this.mAttached && !this.mRefreshIsPosted) {
// this.post(this.mRefreshProgressRunnable);
// this.mRefreshIsPosted = true;
// }
//}
}
/**
* <p>Set the current progress to the specified value. Does not do anything
* if the progress bar is in indeterminate mode.</p>
*
* @param progress the new progress, between 0 and {@link #getMax()}
*
* @see #setIndeterminate(boolean)
* @see #isIndeterminate()
* @see #getProgress()
* @see #incrementProgressBy(int)
*/
setProgress(progress:number, fromUser = false):void {
if (this.mIndeterminate) {
return;
}
if (progress < 0) {
progress = 0;
}
if (progress > this.mMax) {
progress = this.mMax;
}
if (progress != this.mProgress) {
this.mProgress = progress;
this.refreshProgress(R.id.progress, this.mProgress, fromUser);
}
}
/**
* <p>
* Set the current secondary progress to the specified value. Does not do
* anything if the progress bar is in indeterminate mode.
* </p>
*
* @param secondaryProgress the new secondary progress, between 0 and {@link #getMax()}
* @see #setIndeterminate(boolean)
* @see #isIndeterminate()
* @see #getSecondaryProgress()
* @see #incrementSecondaryProgressBy(int)
*/
setSecondaryProgress(secondaryProgress:number):void {
if (this.mIndeterminate) {
return;
}
if (secondaryProgress < 0) {
secondaryProgress = 0;
}
if (secondaryProgress > this.mMax) {
secondaryProgress = this.mMax;
}
if (secondaryProgress != this.mSecondaryProgress) {
this.mSecondaryProgress = secondaryProgress;
this.refreshProgress(R.id.secondaryProgress, this.mSecondaryProgress, false);
}
}
/**
* <p>Get the progress bar's current level of progress. Return 0 when the
* progress bar is in indeterminate mode.</p>
*
* @return the current progress, between 0 and {@link #getMax()}
*
* @see #setIndeterminate(boolean)
* @see #isIndeterminate()
* @see #setProgress(int)
* @see #setMax(int)
* @see #getMax()
*/
getProgress():number {
return this.mIndeterminate ? 0 : this.mProgress;
}
/**
* <p>Get the progress bar's current level of secondary progress. Return 0 when the
* progress bar is in indeterminate mode.</p>
*
* @return the current secondary progress, between 0 and {@link #getMax()}
*
* @see #setIndeterminate(boolean)
* @see #isIndeterminate()
* @see #setSecondaryProgress(int)
* @see #setMax(int)
* @see #getMax()
*/
getSecondaryProgress():number {
return this.mIndeterminate ? 0 : this.mSecondaryProgress;
}
/**
* <p>Return the upper limit of this progress bar's range.</p>
*
* @return a positive integer
*
* @see #setMax(int)
* @see #getProgress()
* @see #getSecondaryProgress()
*/
getMax():number {
return this.mMax;
}
/**
* <p>Set the range of the progress bar to 0...<tt>max</tt>.</p>
*
* @param max the upper range of this progress bar
*
* @see #getMax()
* @see #setProgress(int)
* @see #setSecondaryProgress(int)
*/
setMax(max:number):void {
if (max < 0) {
max = 0;
}
if (max != this.mMax) {
this.mMax = max;
this.postInvalidate();
if (this.mProgress > max) {
this.mProgress = max;
}
this.refreshProgress(R.id.progress, this.mProgress, false);
}
}
/**
* <p>Increase the progress bar's progress by the specified amount.</p>
*
* @param diff the amount by which the progress must be increased
*
* @see #setProgress(int)
*/
incrementProgressBy(diff:number):void {
this.setProgress(this.mProgress + diff);
}
/**
* <p>Increase the progress bar's secondary progress by the specified amount.</p>
*
* @param diff the amount by which the secondary progress must be increased
*
* @see #setSecondaryProgress(int)
*/
incrementSecondaryProgressBy(diff:number):void {
this.setSecondaryProgress(this.mSecondaryProgress + diff);
}
/**
* <p>Start the indeterminate progress animation.</p>
*/
startAnimation():void {
if (this.getVisibility() != ProgressBar.VISIBLE) {
return;
}
if (Animatable.isImpl(this.mIndeterminateDrawable)) {
this.mShouldStartAnimationDrawable = true;
this.mHasAnimation = false;
} else {
this.mHasAnimation = true;
if (this.mInterpolator == null) {
this.mInterpolator = new LinearInterpolator();
}
if (this.mTransformation == null) {
this.mTransformation = new Transformation();
} else {
this.mTransformation.clear();
}
if (this.mAnimation == null) {
this.mAnimation = new AlphaAnimation(0.0, 1.0);
} else {
this.mAnimation.reset();
}
this.mAnimation.setRepeatMode(this.mBehavior);
this.mAnimation.setRepeatCount(Animation.INFINITE);
this.mAnimation.setDuration(this.mDuration);
this.mAnimation.setInterpolator(this.mInterpolator);
this.mAnimation.setStartTime(Animation.START_ON_FIRST_FRAME);
}
this.postInvalidate();
}
/**
* <p>Stop the indeterminate progress animation.</p>
*/
stopAnimation():void {
this.mHasAnimation = false;
if (Animatable.isImpl(this.mIndeterminateDrawable)) {
(<Animatable><any>this.mIndeterminateDrawable).stop();
this.mShouldStartAnimationDrawable = false;
}
this.postInvalidate();
}
///**
// * Sets the acceleration curve for the indeterminate animation.
// * The interpolator is loaded as a resource from the specified context.
// *
// * @param context The application environment
// * @param resID The resource identifier of the interpolator to load
// */
//setInterpolator(context:Context, resID:number):void {
// this.setInterpolator(AnimationUtils.loadInterpolator(context, resID));
//}
/**
* Sets the acceleration curve for the indeterminate animation.
* Defaults to a linear interpolation.
*
* @param interpolator The interpolator which defines the acceleration curve
*/
setInterpolator(interpolator:Interpolator):void {
this.mInterpolator = interpolator;
}
/**
* Gets the acceleration curve type for the indeterminate animation.
*
* @return the {@link Interpolator} associated to this animation
*/
getInterpolator():Interpolator {
return this.mInterpolator;
}
setVisibility(v:number):void {
if (this.getVisibility() != v) {
super.setVisibility(v);
if (this.mIndeterminate) {
// let's be nice with the UI thread
if (v == ProgressBar.GONE || v == ProgressBar.INVISIBLE) {
this.stopAnimation();
} else {
this.startAnimation();
}
}
}
}
protected onVisibilityChanged(changedView:View, visibility:number):void {
super.onVisibilityChanged(changedView, visibility);
if (this.mIndeterminate) {
// let's be nice with the UI thread
if (visibility == ProgressBar.GONE || visibility == ProgressBar.INVISIBLE) {
this.stopAnimation();
} else {
this.startAnimation();
}
}
}
invalidateDrawable(dr:Drawable):void {
if (!this.mInDrawing) {
if (this.verifyDrawable(dr)) {
const dirty:Rect = dr.getBounds();
const scrollX:number = this.mScrollX + this.mPaddingLeft;
const scrollY:number = this.mScrollY + this.mPaddingTop;
this.invalidate(dirty.left + scrollX, dirty.top + scrollY, dirty.right + scrollX, dirty.bottom + scrollY);
} else {
super.invalidateDrawable(dr);
}
}
}
protected onSizeChanged(w:number, h:number, oldw:number, oldh:number):void {
this.updateDrawableBounds(w, h);
}
private updateDrawableBounds(w:number, h:number):void {
// onDraw will translate the canvas so we draw starting at 0,0.
// Subtract out padding for the purposes of the calculations below.
w -= this.mPaddingRight + this.mPaddingLeft;
h -= this.mPaddingTop + this.mPaddingBottom;
let right:number = w;
let bottom:number = h;
let top:number = 0;
let left:number = 0;
if (this.mIndeterminateDrawable != null) {
// Aspect ratio logic does not apply to AnimationDrawables
if (this.mOnlyIndeterminate && !(this.mIndeterminateDrawable instanceof AnimationDrawable)) {
// Maintain aspect ratio. Certain kinds of animated drawables
// get very confused otherwise.
const intrinsicWidth:number = this.mIndeterminateDrawable.getIntrinsicWidth();
const intrinsicHeight:number = this.mIndeterminateDrawable.getIntrinsicHeight();
const intrinsicAspect:number = <number> intrinsicWidth / intrinsicHeight;
const boundAspect:number = <number> w / h;
if (intrinsicAspect != boundAspect) {
if (boundAspect > intrinsicAspect) {
// New width is larger. Make it smaller to match height.
const width:number = Math.floor((h * intrinsicAspect));
left = (w - width) / 2;
right = left + width;
} else {
// New height is larger. Make it smaller to match width.
const height:number = Math.floor((w * (1 / intrinsicAspect)));
top = (h - height) / 2;
bottom = top + height;
}
}
}
if (this.isLayoutRtl() && this.mMirrorForRtl) {
let tempLeft:number = left;
left = w - right;
right = w - tempLeft;
}
this.mIndeterminateDrawable.setBounds(left, top, right, bottom);
}
if (this.mProgressDrawable != null) {
this.mProgressDrawable.setBounds(0, 0, right, bottom);
}
}
protected onDraw(canvas:Canvas):void {
super.onDraw(canvas);
let d:Drawable = this.mCurrentDrawable;
if (d != null) {
// Translate canvas so a indeterminate circular progress bar with padding
// rotates properly in its animation
canvas.save();
if (this.isLayoutRtl() && this.mMirrorForRtl) {
canvas.translate(this.getWidth() - this.mPaddingRight, this.mPaddingTop);
canvas.scale(-1.0, 1.0);
} else {
canvas.translate(this.mPaddingLeft, this.mPaddingTop);
}
let time:number = this.getDrawingTime();
if (this.mHasAnimation) {
this.mAnimation.getTransformation(time, this.mTransformation);
let scale:number = this.mTransformation.getAlpha();
try {
this.mInDrawing = true;
d.setLevel(Math.floor((scale * ProgressBar.MAX_LEVEL)));
} finally {
this.mInDrawing = false;
}
this.postInvalidateOnAnimation();
}
d.draw(canvas);
canvas.restore();
if (this.mShouldStartAnimationDrawable && Animatable.isImpl(d) ) {
(<Animatable><any>d).start();
this.mShouldStartAnimationDrawable = false;
}
}
}
protected onMeasure(widthMeasureSpec:number, heightMeasureSpec:number):void {
let d:Drawable = this.mCurrentDrawable;
let dw:number = 0;
let dh:number = 0;
if (d != null) {
dw = Math.max(this.mMinWidth, Math.min(this.mMaxWidth, d.getIntrinsicWidth()));
dh = Math.max(this.mMinHeight, Math.min(this.mMaxHeight, d.getIntrinsicHeight()));
}
this.updateDrawableState();
dw += this.mPaddingLeft + this.mPaddingRight;
dh += this.mPaddingTop + this.mPaddingBottom;
this.setMeasuredDimension(ProgressBar.resolveSizeAndState(dw, widthMeasureSpec, 0), ProgressBar.resolveSizeAndState(dh, heightMeasureSpec, 0));
}
protected drawableStateChanged():void {
super.drawableStateChanged();
this.updateDrawableState();
}
private updateDrawableState():void {
let state:number[] = this.getDrawableState();
if (this.mProgressDrawable != null && this.mProgressDrawable.isStateful()) {
this.mProgressDrawable.setState(state);
}
if (this.mIndeterminateDrawable != null && this.mIndeterminateDrawable.isStateful()) {
this.mIndeterminateDrawable.setState(state);
}
}
protected onAttachedToWindow():void {
super.onAttachedToWindow();
if (this.mIndeterminate) {
this.startAnimation();
}
if (this.mRefreshData != null) {
{
const count:number = this.mRefreshData.size();
for (let i:number = 0; i < count; i++) {
const rd:ProgressBar.RefreshData = this.mRefreshData.get(i);
this.doRefreshProgress(rd.id, rd.progress, rd.fromUser, true);
rd.recycle();
}
this.mRefreshData.clear();
}
}
this.mAttached = true;
}
protected onDetachedFromWindow():void {
if (this.mIndeterminate) {
this.stopAnimation();
}
//if (this.mRefreshProgressRunnable != null) {
// this.removeCallbacks(this.mRefreshProgressRunnable);
//}
//if (this.mRefreshProgressRunnable != null && this.mRefreshIsPosted) {
// this.removeCallbacks(this.mRefreshProgressRunnable);
//}
//if (this.mAccessibilityEventSender != null) {
// this.removeCallbacks(this.mAccessibilityEventSender);
//}
// This should come after stopAnimation(), otherwise an invalidate message remains in the
// queue, which can prevent the entire view hierarchy from being GC'ed during a rotation
super.onDetachedFromWindow();
this.mAttached = false;
}
}
export module ProgressBar{
//export class RefreshProgressRunnable implements Runnable {
// _ProgressBar_this:ProgressBar;
// constructor(arg:ProgressBar){
// this._ProgressBar_this = arg;
// }
//
// run():void {
// {
// const count:number = this._ProgressBar_this.mRefreshData.size();
// for (let i:number = 0; i < count; i++) {
// const rd:ProgressBar.RefreshData = this._ProgressBar_this.mRefreshData.get(i);
// this._ProgressBar_this.doRefreshProgress(rd.id, rd.progress, rd.fromUser, true);
// rd.recycle();
// }
// this._ProgressBar_this.mRefreshData.clear();
// this._ProgressBar_this.mRefreshIsPosted = false;
// }
// }
//}
export class RefreshData {
private static POOL_MAX:number = 24;
private static sPool:SynchronizedPool<RefreshData> = new SynchronizedPool<RefreshData>(RefreshData.POOL_MAX);
id:string;
progress:number = 0;
fromUser:boolean;
static obtain(id:string, progress:number, fromUser:boolean):RefreshData {
let rd:RefreshData = RefreshData.sPool.acquire();
if (rd == null) {
rd = new RefreshData();
}
rd.id = id;
rd.progress = progress;
rd.fromUser = fromUser;
return rd;
}
recycle():void {
RefreshData.sPool.release(this);
}
}
}
} | the_stack |
import {
EventDispatcher,
MOUSE,
Matrix4,
OrthographicCamera,
PerspectiveCamera,
Quaternion,
Spherical,
TOUCH,
Vector2,
Vector3,
} from 'three'
export type CHANGE_EVENT = {
type: 'change' | 'start' | 'end'
}
export enum STATE {
NONE = -1,
ROTATE = 0,
DOLLY = 1,
PAN = 2,
TOUCH_ROTATE = 3,
TOUCH_PAN = 4,
TOUCH_DOLLY_PAN = 5,
TOUCH_DOLLY_ROTATE = 6,
}
class CameraControls extends EventDispatcher {
object: PerspectiveCamera | OrthographicCamera
domElement: HTMLElement
/** Set to false to disable this control */
enabled = true
/** "target" sets the location of focus, where the object orbits around */
target = new Vector3()
/** Set to true to enable trackball behavior */
trackball = false
/** How far you can dolly in ( PerspectiveCamera only ) */
minDistance = 0
/** How far you can dolly out ( PerspectiveCamera only ) */
maxDistance = Infinity
// How far you can zoom in and out ( OrthographicCamera only )
minZoom = 0
maxZoom = Infinity
// How far you can orbit vertically, upper and lower limits.
// Range is 0 to Math.PI radians.
minPolarAngle = 0
maxPolarAngle = Math.PI
// How far you can orbit horizontally, upper and lower limits.
// If set, must be a sub-interval of the interval [ - Math.PI, Math.PI ].
minAzimuthAngle = -Infinity // radians
maxAzimuthAngle = Infinity // radians
// Set to true to enable damping (inertia)
// If damping is enabled, you must call controls.update() in your animation loop
enableDamping = false
dampingFactor = 0.05
/**
* This option enables dollying in and out; property named as "zoom" for backwards compatibility
* Set to false to disable zooming
*/
enableZoom = true
zoomSpeed = 1.0
/** Set to false to disable rotating */
enableRotate = true
rotateSpeed = 1.0
/** Set to false to disable panning */
enablePan = true
panSpeed = 1.0
/** if true, pan in screen-space */
screenSpacePanning = false
/** pixels moved per arrow key push */
keyPanSpeed = 7.0
/**
* Set to true to automatically rotate around the target
* If auto-rotate is enabled, you must call controls.update() in your animation loop
* auto-rotate is not supported for trackball behavior
*/
autoRotate = false
autoRotateSpeed = 2.0 // 30 seconds per round when fps is 60
/** Set to false to disable use of the keys */
enableKeys = true
/** The four arrow keys */
keys = { LEFT: 'ArrowLeft', UP: 'ArrowUp', RIGHT: 'ArrowRight', BOTTOM: 'ArrowDown' }
mouseButtons: {
LEFT: MOUSE
MIDDLE?: MOUSE
RIGHT: MOUSE
}
/** Touch fingers */
touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN }
// for reset
target0: Vector3
position0: Vector3
quaternion0: Quaternion
zoom0: number
// current position in spherical coordinates
spherical = new Spherical()
sphericalDelta = new Spherical()
private changeEvent = { type: 'change' }
private startEvent = { type: 'start' }
private endEvent = { type: 'end' }
private state = STATE.NONE
private EPS = 0.000001
private scale = 1
private panOffset = new Vector3()
private zoomChanged = false
private rotateStart = new Vector2()
private rotateEnd = new Vector2()
private rotateDelta = new Vector2()
private panStart = new Vector2()
private panEnd = new Vector2()
private panDelta = new Vector2()
private dollyStart = new Vector2()
private dollyEnd = new Vector2()
private dollyDelta = new Vector2()
private offset = new Vector3()
private lastPosition = new Vector3()
private lastQuaternion = new Quaternion()
private q = new Quaternion()
private v = new Vector3()
private vec = new Vector3()
private quat: Quaternion
private quatInverse: Quaternion
constructor(object: PerspectiveCamera | OrthographicCamera, domElement: HTMLElement) {
super()
if (domElement === undefined) {
console.warn('THREE.CameraControls: The second parameter "domElement" is now mandatory.')
}
if (domElement instanceof Document) {
console.error(
'THREE.CameraControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.',
)
}
this.object = object
this.domElement = domElement
this.mouseButtons = {
LEFT: MOUSE.ROTATE,
MIDDLE: MOUSE.DOLLY,
RIGHT: MOUSE.PAN,
}
// for reset
this.target0 = this.target.clone()
this.position0 = this.object.position.clone()
this.quaternion0 = this.object.quaternion.clone()
this.zoom0 = this.object.zoom
//
// internals
//
// so camera.up is the orbit axis
this.quat = new Quaternion().setFromUnitVectors(this.object.up, new Vector3(0, 1, 0))
this.quatInverse = this.quat.clone().invert()
this.lastPosition = new Vector3()
this.lastQuaternion = new Quaternion()
this.domElement.addEventListener('contextmenu', this.onContextMenu, false)
this.domElement.addEventListener('mousedown', this.onMouseDown, false)
this.domElement.addEventListener('wheel', this.onMouseWheel, false)
this.domElement.addEventListener('touchstart', this.onTouchStart, false)
this.domElement.addEventListener('touchend', this.onTouchEnd, false)
this.domElement.addEventListener('touchmove', this.onTouchMove, false)
this.domElement.addEventListener('keydown', this.onKeyDown, false)
// make sure element can receive keys.
if (this.domElement.tabIndex === -1) {
this.domElement.tabIndex = 0
}
// force an update at start
this.object.lookAt(this.target)
this.update()
this.saveState()
}
getPolarAngle = (): number => this.spherical.phi
getAzimuthalAngle = (): number => this.spherical.theta
saveState = (): void => {
this.target0.copy(this.target)
this.position0.copy(this.object.position)
this.quaternion0.copy(this.object.quaternion)
this.zoom0 = this.object.zoom
}
reset = (): void => {
this.target.copy(this.target0)
this.object.position.copy(this.position0)
this.object.quaternion.copy(this.quaternion0)
this.object.zoom = this.zoom0
this.object.updateProjectionMatrix()
this.dispatchEvent(this.changeEvent)
this.update()
this.state = STATE.NONE
}
dispose = (): void => {
this.domElement.removeEventListener('contextmenu', this.onContextMenu, false)
this.domElement.removeEventListener('mousedown', this.onMouseDown, false)
this.domElement.removeEventListener('wheel', this.onMouseWheel, false)
this.domElement.removeEventListener('touchstart', this.onTouchStart, false)
this.domElement.removeEventListener('touchend', this.onTouchEnd, false)
this.domElement.removeEventListener('touchmove', this.onTouchMove, false)
document.removeEventListener('mousemove', this.onMouseMove, false)
document.removeEventListener('mouseup', this.onMouseUp, false)
this.domElement.removeEventListener('keydown', this.onKeyDown, false)
//this.dispatchEvent( { type: 'dispose' } ); // should this be added here?
}
private update = (): boolean => {
const position = this.object.position
this.offset.copy(position).sub(this.target)
if (this.trackball) {
// rotate around screen-space y-axis
if (this.sphericalDelta.theta) {
this.vec.set(0, 1, 0).applyQuaternion(this.object.quaternion)
const factor = this.enableDamping ? this.dampingFactor : 1
this.q.setFromAxisAngle(this.vec, this.sphericalDelta.theta * factor)
this.object.quaternion.premultiply(this.q)
this.offset.applyQuaternion(this.q)
}
// rotate around screen-space x-axis
if (this.sphericalDelta.phi) {
this.vec.set(1, 0, 0).applyQuaternion(this.object.quaternion)
const factor = this.enableDamping ? this.dampingFactor : 1
this.q.setFromAxisAngle(this.vec, this.sphericalDelta.phi * factor)
this.object.quaternion.premultiply(this.q)
this.offset.applyQuaternion(this.q)
}
this.offset.multiplyScalar(this.scale)
this.offset.clampLength(this.minDistance, this.maxDistance)
} else {
// rotate offset to "y-axis-is-up" space
this.offset.applyQuaternion(this.quat)
if (this.autoRotate && this.state === STATE.NONE) {
this.rotateLeft(this.getAutoRotationAngle())
}
this.spherical.setFromVector3(this.offset)
if (this.enableDamping) {
this.spherical.theta += this.sphericalDelta.theta * this.dampingFactor
this.spherical.phi += this.sphericalDelta.phi * this.dampingFactor
} else {
this.spherical.theta += this.sphericalDelta.theta
this.spherical.phi += this.sphericalDelta.phi
}
// restrict theta to be between desired limits
this.spherical.theta = Math.max(this.minAzimuthAngle, Math.min(this.maxAzimuthAngle, this.spherical.theta))
// restrict phi to be between desired limits
this.spherical.phi = Math.max(this.minPolarAngle, Math.min(this.maxPolarAngle, this.spherical.phi))
this.spherical.makeSafe()
this.spherical.radius *= this.scale
// restrict radius to be between desired limits
this.spherical.radius = Math.max(this.minDistance, Math.min(this.maxDistance, this.spherical.radius))
this.offset.setFromSpherical(this.spherical)
// rotate offset back to "camera-up-vector-is-up" space
this.offset.applyQuaternion(this.quatInverse)
}
// move target to panned location
if (this.enableDamping === true) {
this.target.addScaledVector(this.panOffset, this.dampingFactor)
} else {
this.target.add(this.panOffset)
}
position.copy(this.target).add(this.offset)
if (this.trackball === false) {
this.object.lookAt(this.target)
}
if (this.enableDamping === true) {
this.sphericalDelta.theta *= 1 - this.dampingFactor
this.sphericalDelta.phi *= 1 - this.dampingFactor
this.panOffset.multiplyScalar(1 - this.dampingFactor)
} else {
this.sphericalDelta.set(0, 0, 0)
this.panOffset.set(0, 0, 0)
}
this.scale = 1
// update condition is:
// min(camera displacement, camera rotation in radians)^2 > EPS
// using small-angle approximation cos(x/2) = 1 - x^2 / 8
if (
this.zoomChanged ||
this.lastPosition.distanceToSquared(this.object.position) > this.EPS ||
8 * (1 - this.lastQuaternion.dot(this.object.quaternion)) > this.EPS
) {
this.dispatchEvent(this.changeEvent)
this.lastPosition.copy(this.object.position)
this.lastQuaternion.copy(this.object.quaternion)
this.zoomChanged = false
return true
}
return false
}
private getAutoRotationAngle = (): number => ((2 * Math.PI) / 60 / 60) * this.autoRotateSpeed
private getZoomScale = (): number => Math.pow(0.95, this.zoomSpeed)
private rotateLeft = (angle: number): void => {
this.sphericalDelta.theta -= angle
}
private rotateUp = (angle: number): void => {
this.sphericalDelta.phi -= angle
}
private panLeft = (distance: number, objectMatrix: Matrix4): void => {
this.v.setFromMatrixColumn(objectMatrix, 0) // get X column of objectMatrix
this.v.multiplyScalar(-distance)
this.panOffset.add(this.v)
}
private panUp = (distance: number, objectMatrix: Matrix4): void => {
if (this.screenSpacePanning === true) {
this.v.setFromMatrixColumn(objectMatrix, 1)
} else {
this.v.setFromMatrixColumn(objectMatrix, 0)
this.v.crossVectors(this.object.up, this.v)
}
this.v.multiplyScalar(distance)
this.panOffset.add(this.v)
}
// deltaX and deltaY are in pixels; right and down are positive
private pan = (deltaX: number, deltaY: number): void => {
const element = this.domElement
if (this.object instanceof PerspectiveCamera) {
// perspective
const position = this.object.position
this.offset.copy(position).sub(this.target)
let targetDistance = this.offset.length()
// half of the fov is center to top of screen
targetDistance *= Math.tan(((this.object.fov / 2) * Math.PI) / 180.0)
// we use only clientHeight here so aspect ratio does not distort speed
this.panLeft((2 * deltaX * targetDistance) / element.clientHeight, this.object.matrix)
this.panUp((2 * deltaY * targetDistance) / element.clientHeight, this.object.matrix)
} else if (this.object.isOrthographicCamera) {
// orthographic
this.panLeft(
(deltaX * (this.object.right - this.object.left)) / this.object.zoom / element.clientWidth,
this.object.matrix,
)
this.panUp(
(deltaY * (this.object.top - this.object.bottom)) / this.object.zoom / element.clientHeight,
this.object.matrix,
)
} else {
// camera neither orthographic nor perspective
console.warn('WARNING: CameraControls.js encountered an unknown camera type - pan disabled.')
this.enablePan = false
}
}
private dollyIn = (dollyScale: number): void => {
// TODO: replace w/.isPerspectiveCamera ?
if (this.object instanceof PerspectiveCamera) {
this.scale /= dollyScale
// TODO: replace w/.isOrthographicCamera ?
} else if (this.object instanceof OrthographicCamera) {
this.object.zoom = Math.max(this.minZoom, Math.min(this.maxZoom, this.object.zoom * dollyScale))
this.object.updateProjectionMatrix()
this.zoomChanged = true
} else {
console.warn('WARNING: CameraControls.js encountered an unknown camera type - dolly/zoom disabled.')
this.enableZoom = false
}
}
private dollyOut = (dollyScale: number): void => {
// TODO: replace w/.isPerspectiveCamera ?
if (this.object instanceof PerspectiveCamera) {
this.scale *= dollyScale
// TODO: replace w/.isOrthographicCamera ?
} else if (this.object instanceof OrthographicCamera) {
this.object.zoom = Math.max(this.minZoom, Math.min(this.maxZoom, this.object.zoom / dollyScale))
this.object.updateProjectionMatrix()
this.zoomChanged = true
} else {
console.warn('WARNING: CameraControls.js encountered an unknown camera type - dolly/zoom disabled.')
this.enableZoom = false
}
}
// event callbacks - update the object state
private handleMouseDownRotate = (event: MouseEvent): void => {
this.rotateStart.set(event.clientX, event.clientY)
}
// TODO: confirm if worthwhile to return the Vector2 instead of void
private handleMouseDownDolly = (event: MouseEvent): void => {
this.dollyStart.set(event.clientX, event.clientY)
}
private handleMouseDownPan = (event: MouseEvent): void => {
this.panStart.set(event.clientX, event.clientY)
}
private handleMouseMoveRotate = (event: MouseEvent): void => {
this.rotateEnd.set(event.clientX, event.clientY)
this.rotateDelta.subVectors(this.rotateEnd, this.rotateStart).multiplyScalar(this.rotateSpeed)
const element = this.domElement
this.rotateLeft((2 * Math.PI * this.rotateDelta.x) / element.clientHeight) // yes, height
this.rotateUp((2 * Math.PI * this.rotateDelta.y) / element.clientHeight)
this.rotateStart.copy(this.rotateEnd)
this.update()
}
private handleMouseMoveDolly = (event: MouseEvent): void => {
this.dollyEnd.set(event.clientX, event.clientY)
this.dollyDelta.subVectors(this.dollyEnd, this.dollyStart)
if (this.dollyDelta.y > 0) {
this.dollyIn(this.getZoomScale())
} else if (this.dollyDelta.y < 0) {
this.dollyOut(this.getZoomScale())
}
this.dollyStart.copy(this.dollyEnd)
this.update()
}
private handleMouseMovePan = (event: MouseEvent): void => {
this.panEnd.set(event.clientX, event.clientY)
this.panDelta.subVectors(this.panEnd, this.panStart).multiplyScalar(this.panSpeed)
this.pan(this.panDelta.x, this.panDelta.y)
this.panStart.copy(this.panEnd)
this.update()
}
private handleMouseUp(/*event*/): void {
// no-op
}
private handleMouseWheel = (event: WheelEvent): void => {
if (event.deltaY < 0) {
this.dollyOut(this.getZoomScale())
} else if (event.deltaY > 0) {
this.dollyIn(this.getZoomScale())
}
this.update()
}
private handleKeyDown = (event: KeyboardEvent): void => {
let needsUpdate = false
switch (event.code) {
case this.keys.UP:
this.pan(0, this.keyPanSpeed)
needsUpdate = true
break
case this.keys.BOTTOM:
this.pan(0, -this.keyPanSpeed)
needsUpdate = true
break
case this.keys.LEFT:
this.pan(this.keyPanSpeed, 0)
needsUpdate = true
break
case this.keys.RIGHT:
this.pan(-this.keyPanSpeed, 0)
needsUpdate = true
break
}
if (needsUpdate) {
// prevent the browser from scrolling on cursor keys
event.preventDefault()
this.update()
}
}
private handleTouchStartRotate = (event: TouchEvent): void => {
if (event.touches.length == 1) {
this.rotateStart.set(event.touches[0].pageX, event.touches[0].pageY)
} else {
const x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX)
const y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY)
this.rotateStart.set(x, y)
}
}
private handleTouchStartPan = (event: TouchEvent): void => {
if (event.touches.length == 1) {
this.panStart.set(event.touches[0].pageX, event.touches[0].pageY)
} else {
const x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX)
const y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY)
this.panStart.set(x, y)
}
}
private handleTouchStartDolly = (event: TouchEvent): void => {
const dx = event.touches[0].pageX - event.touches[1].pageX
const dy = event.touches[0].pageY - event.touches[1].pageY
const distance = Math.sqrt(dx * dx + dy * dy)
this.dollyStart.set(0, distance)
}
private handleTouchStartDollyPan = (event: TouchEvent): void => {
if (this.enableZoom) this.handleTouchStartDolly(event)
if (this.enablePan) this.handleTouchStartPan(event)
}
private handleTouchStartDollyRotate = (event: TouchEvent): void => {
if (this.enableZoom) this.handleTouchStartDolly(event)
if (this.enableRotate) this.handleTouchStartRotate(event)
}
private handleTouchMoveRotate = (event: TouchEvent): void => {
if (event.touches.length == 1) {
this.rotateEnd.set(event.touches[0].pageX, event.touches[0].pageY)
} else {
const x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX)
const y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY)
this.rotateEnd.set(x, y)
}
this.rotateDelta.subVectors(this.rotateEnd, this.rotateStart).multiplyScalar(this.rotateSpeed)
const element = this.domElement
this.rotateLeft((2 * Math.PI * this.rotateDelta.x) / element.clientHeight) // yes, height
this.rotateUp((2 * Math.PI * this.rotateDelta.y) / element.clientHeight)
this.rotateStart.copy(this.rotateEnd)
}
private handleTouchMovePan = (event: TouchEvent): void => {
if (event.touches.length == 1) {
this.panEnd.set(event.touches[0].pageX, event.touches[0].pageY)
} else {
const x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX)
const y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY)
this.panEnd.set(x, y)
}
this.panDelta.subVectors(this.panEnd, this.panStart).multiplyScalar(this.panSpeed)
this.pan(this.panDelta.x, this.panDelta.y)
this.panStart.copy(this.panEnd)
}
private handleTouchMoveDolly = (event: TouchEvent): void => {
const dx = event.touches[0].pageX - event.touches[1].pageX
const dy = event.touches[0].pageY - event.touches[1].pageY
const distance = Math.sqrt(dx * dx + dy * dy)
this.dollyEnd.set(0, distance)
this.dollyDelta.set(0, Math.pow(this.dollyEnd.y / this.dollyStart.y, this.zoomSpeed))
this.dollyIn(this.dollyDelta.y)
this.dollyStart.copy(this.dollyEnd)
}
private handleTouchMoveDollyPan = (event: TouchEvent): void => {
if (this.enableZoom) this.handleTouchMoveDolly(event)
if (this.enablePan) this.handleTouchMovePan(event)
}
private handleTouchMoveDollyRotate = (event: TouchEvent): void => {
if (this.enableZoom) this.handleTouchMoveDolly(event)
if (this.enableRotate) this.handleTouchMoveRotate(event)
}
private handleTouchEnd(/*event*/): void {
// no-op
}
//
// event handlers - FSM: listen for events and reset state
//
private onMouseDown = (event: MouseEvent): void => {
if (this.enabled === false) return
// Prevent the browser from scrolling.
event.preventDefault()
// Manually set the focus since calling preventDefault above
// prevents the browser from setting it automatically.
this.domElement.focus ? this.domElement.focus() : window.focus()
let mouseAction
switch (event.button) {
case 0:
mouseAction = this.mouseButtons.LEFT
break
case 1:
mouseAction = this.mouseButtons.MIDDLE
break
case 2:
mouseAction = this.mouseButtons.RIGHT
break
default:
mouseAction = -1
}
switch (mouseAction) {
case MOUSE.DOLLY:
if (this.enableZoom === false) return
this.handleMouseDownDolly(event)
this.state = STATE.DOLLY
break
case MOUSE.ROTATE:
if (event.ctrlKey || event.metaKey || event.shiftKey) {
if (this.enablePan === false) return
this.handleMouseDownPan(event)
this.state = STATE.PAN
} else {
if (this.enableRotate === false) return
this.handleMouseDownRotate(event)
this.state = STATE.ROTATE
}
break
case MOUSE.PAN:
if (event.ctrlKey || event.metaKey || event.shiftKey) {
if (this.enableRotate === false) return
this.handleMouseDownRotate(event)
this.state = STATE.ROTATE
} else {
if (this.enablePan === false) return
this.handleMouseDownPan(event)
this.state = STATE.PAN
}
break
default:
this.state = STATE.NONE
}
if (this.state !== STATE.NONE) {
document.addEventListener('mousemove', this.onMouseMove, false)
document.addEventListener('mouseup', this.onMouseUp, false)
this.dispatchEvent(this.startEvent)
}
}
private onMouseMove = (event: MouseEvent): void => {
if (this.enabled === false) return
event.preventDefault()
switch (this.state) {
case STATE.ROTATE:
if (this.enableRotate === false) return
this.handleMouseMoveRotate(event)
break
case STATE.DOLLY:
if (this.enableZoom === false) return
this.handleMouseMoveDolly(event)
break
case STATE.PAN:
if (this.enablePan === false) return
this.handleMouseMovePan(event)
break
}
}
private onMouseUp = (): void => {
if (this.enabled === false) return
// this.handleMouseUp()
document.removeEventListener('mousemove', this.onMouseMove, false)
document.removeEventListener('mouseup', this.onMouseUp, false)
this.dispatchEvent(this.endEvent)
this.state = STATE.NONE
}
private onMouseWheel = (event: WheelEvent): void => {
if (
this.enabled === false ||
this.enableZoom === false ||
(this.state !== STATE.NONE && this.state !== STATE.ROTATE)
) {
return
}
event.preventDefault()
this.dispatchEvent(this.startEvent)
this.handleMouseWheel(event)
this.dispatchEvent(this.endEvent)
}
private onKeyDown = (event: KeyboardEvent): void => {
if (this.enabled === false || this.enableKeys === false || this.enablePan === false) return
this.handleKeyDown(event)
}
private onTouchStart = (event: TouchEvent): void => {
if (this.enabled === false) return
event.preventDefault()
switch (event.touches.length) {
case 1:
switch (this.touches.ONE) {
case TOUCH.ROTATE:
if (this.enableRotate === false) return
this.handleTouchStartRotate(event)
this.state = STATE.TOUCH_ROTATE
break
case TOUCH.PAN:
if (this.enablePan === false) return
this.handleTouchStartPan(event)
this.state = STATE.TOUCH_PAN
break
default:
this.state = STATE.NONE
}
break
case 2:
switch (this.touches.TWO) {
case TOUCH.DOLLY_PAN:
if (this.enableZoom === false && this.enablePan === false) return
this.handleTouchStartDollyPan(event)
this.state = STATE.TOUCH_DOLLY_PAN
break
case TOUCH.DOLLY_ROTATE:
if (this.enableZoom === false && this.enableRotate === false) return
this.handleTouchStartDollyRotate(event)
this.state = STATE.TOUCH_DOLLY_ROTATE
break
default:
this.state = STATE.NONE
}
break
default:
this.state = STATE.NONE
}
if (this.state !== STATE.NONE) {
this.dispatchEvent(this.startEvent)
}
}
private onTouchMove = (event: TouchEvent): void => {
if (this.enabled === false) return
event.preventDefault()
switch (this.state) {
case STATE.TOUCH_ROTATE:
if (this.enableRotate === false) return
this.handleTouchMoveRotate(event)
this.update()
break
case STATE.TOUCH_PAN:
if (this.enablePan === false) return
this.handleTouchMovePan(event)
this.update()
break
case STATE.TOUCH_DOLLY_PAN:
if (this.enableZoom === false && this.enablePan === false) return
this.handleTouchMoveDollyPan(event)
this.update()
break
case STATE.TOUCH_DOLLY_ROTATE:
if (this.enableZoom === false && this.enableRotate === false) return
this.handleTouchMoveDollyRotate(event)
this.update()
break
default:
this.state = STATE.NONE
}
}
private onTouchEnd = (): void => {
if (this.enabled === false) return
// this.handleTouchEnd()
this.dispatchEvent(this.endEvent)
this.state = STATE.NONE
}
private onContextMenu = (event: Event): void => {
if (this.enabled === false) return
event.preventDefault()
}
}
/**
* OrbitControls maintains the "up" direction, camera.up (+Y by default).
*
* @event Orbit - left mouse / touch: one-finger move
* @event Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
* @event Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
*/
class OrbitControlsExp extends CameraControls {
mouseButtons: {
LEFT: MOUSE
RIGHT: MOUSE
}
touches: {
ONE: TOUCH
TWO: TOUCH
}
constructor(object: PerspectiveCamera | OrthographicCamera, domElement: HTMLElement) {
super(object, domElement)
this.mouseButtons = {
LEFT: MOUSE.ROTATE,
RIGHT: MOUSE.PAN,
}
this.touches = {
ONE: TOUCH.ROTATE,
TWO: TOUCH.DOLLY_PAN,
}
}
}
/**
* MapControls maintains the "up" direction, camera.up (+Y by default)
*
* @event Orbit - right mouse, or left mouse + ctrl/meta/shiftKey / touch: two-finger rotate
* @event Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
* @event Pan - left mouse, or left right + ctrl/meta/shiftKey, or arrow keys / touch: one-finger move
*/
class MapControlsExp extends CameraControls {
mouseButtons: {
LEFT: MOUSE
RIGHT: MOUSE
}
touches: {
ONE: TOUCH
TWO: TOUCH
}
constructor(object: PerspectiveCamera | OrthographicCamera, domElement: HTMLElement) {
super(object, domElement)
this.mouseButtons = {
LEFT: MOUSE.PAN,
RIGHT: MOUSE.ROTATE,
}
this.touches = {
ONE: TOUCH.PAN,
TWO: TOUCH.DOLLY_ROTATE,
}
}
}
/**
* TrackballControls allows the camera to rotate over the polls and does not maintain camera.up
*
* @event Orbit - left mouse / touch: one-finger move
* @event Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
* @event Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
*/
class TrackballControlsExp extends CameraControls {
trackball: boolean
screenSpacePanning: boolean
autoRotate: boolean
mouseButtons: {
LEFT: MOUSE
RIGHT: MOUSE
}
touches: {
ONE: TOUCH
TWO: TOUCH
}
constructor(object: PerspectiveCamera | OrthographicCamera, domElement: HTMLElement) {
super(object, domElement)
this.trackball = true
this.screenSpacePanning = true
this.autoRotate = false
this.mouseButtons = {
LEFT: MOUSE.ROTATE,
RIGHT: MOUSE.PAN,
}
this.touches = {
ONE: TOUCH.ROTATE,
TWO: TOUCH.DOLLY_PAN,
}
}
}
export { CameraControls, OrbitControlsExp, MapControlsExp, TrackballControlsExp } | the_stack |
import {
Props,
Type,
Container,
ElementContainer,
Instance,
TextInstance,
HydratableInstance,
PublicInstance,
HostContext,
UpdatePayload,
NoTimeout,
isElementContainer,
} from './types'
import { HostConfig } from 'react-reconciler'
import { FacetProp, isFacet, Unsubscribe } from '@react-facet/core'
/**
* Custom React Renderer with support for Facets
*
* Based on https://blog.atulr.com/react-custom-renderer-1/
* For more information check the official docs: https://github.com/facebook/react/tree/main/packages/react-reconciler
*/
export const setupHostConfig = (): HostConfig<
Type,
Props<HTMLElement>,
Container,
Instance,
TextInstance,
HydratableInstance,
PublicInstance,
HostContext,
UpdatePayload,
null,
NodeJS.Timeout,
NoTimeout
> => ({
isPrimaryRenderer: true,
supportsMutation: true,
supportsPersistence: false,
supportsHydration: false,
now: Date.now,
/**
* We need to support setting up the host config in an environment where window is not available globally yet
* Ex: screenshot testing
*/
setTimeout:
typeof window !== 'undefined'
? window.setTimeout
: (handler, timeout) => window.setTimeout(handler, timeout) as unknown as NodeJS.Timeout,
/**
* We need to support setting up the host config in an environment where window is not available globally yet
* Ex: screenshot testing
*/
clearTimeout:
typeof window !== 'undefined' ? window.clearTimeout : (id) => window.clearTimeout(id as unknown as NodeJS.Timeout),
noTimeout: noop,
scheduleDeferredCallback: function (callback, options) {
return window.setTimeout(callback, options ? options.timeout : 0)
},
cancelDeferredCallback: function (id) {
return window.clearTimeout(id)
},
getRootHostContext: function () {
return EMPTY
},
getChildHostContext: function () {
return EMPTY
},
shouldSetTextContent: function () {
return false
},
createTextInstance: function (newText) {
return {
element: document.createTextNode(newText),
}
},
createInstance: function (externalType, newProps) {
if (externalType === 'fast-text') {
const element = document.createTextNode('')
return {
children: new Set(),
element,
text: setupTextUpdate(newProps.text, element),
}
}
const type = fastTypeMap[externalType] ?? externalType
const element = document.createElement(type)
let style: CSSStyleDeclaration | undefined
let styleUnsubscribers: Map<string | number, Unsubscribe> | undefined
if (newProps.style != null) {
style = element.style
styleUnsubscribers = new Map()
// We know for sure here that style will never be null (we created it above)
const notNullStyle = style as unknown as Record<string, unknown>
const notNullStyleUnsubscribers = styleUnsubscribers as unknown as Map<string | number, Unsubscribe>
const styleProp = newProps.style
for (const key in styleProp) {
const value = styleProp[key]
if (value != null) {
if (isFacet(value)) {
notNullStyleUnsubscribers.set(
key,
value.observe((value) => {
notNullStyle[key] = value
}),
)
} else {
notNullStyle[key] = value
}
}
}
}
if (newProps.dangerouslySetInnerHTML != null) {
element.innerHTML = newProps.dangerouslySetInnerHTML.__html
}
if (newProps.onClick) {
element.addEventListener('click', newProps.onClick as EventListener)
}
if (newProps.onFocus) {
element.addEventListener('focus', newProps.onFocus as EventListener)
}
if (newProps.onBlur) {
element.addEventListener('blur', newProps.onBlur as EventListener)
}
if (newProps.onMouseDown) {
element.addEventListener('mousedown', newProps.onMouseDown as EventListener)
}
if (newProps.onMouseUp) {
element.addEventListener('mouseup', newProps.onMouseUp as EventListener)
}
if (newProps.onTouchStart) {
element.addEventListener('touchstart', newProps.onTouchStart as EventListener)
}
if (newProps.onTouchMove) {
element.addEventListener('touchmove', newProps.onTouchMove as EventListener)
}
if (newProps.onTouchEnd) {
element.addEventListener('touchend', newProps.onTouchEnd as EventListener)
}
if (newProps.onMouseEnter) {
element.addEventListener('mouseenter', newProps.onMouseEnter as EventListener)
}
if (newProps.onMouseLeave) {
element.addEventListener('mouseleave', newProps.onMouseLeave as EventListener)
}
if (newProps.onKeyPress) {
element.addEventListener('keypress', newProps.onKeyPress as EventListener)
}
if (newProps.onKeyDown) {
element.addEventListener('keydown', newProps.onKeyDown as EventListener)
}
if (newProps.onKeyUp) {
element.addEventListener('keyup', newProps.onKeyUp as EventListener)
}
return {
element,
styleUnsubscribers,
style,
children: new Set(),
className: newProps.className != null ? setupClassUpdate(newProps.className, element) : undefined,
id: newProps.id != null ? setupIdUpdate(newProps.id, element) : undefined,
autoPlay: newProps.autoPlay != null ? setupAutoPlayUpdate(newProps.autoPlay, element) : undefined,
loop: newProps.loop != null ? setupLoopUpdate(newProps.loop, element) : undefined,
href: newProps.href != null ? setupHrefUpdate(newProps.href, element) : undefined,
target: newProps.target != null ? setupTargetUpdate(newProps.target, element) : undefined,
disabled: newProps.disabled != null ? setupDisabledUpdate(newProps.disabled, element) : undefined,
maxLength: newProps.maxLength != null ? setupMaxLengthUpdate(newProps.maxLength, element) : undefined,
rows: newProps.rows != null ? setupRowsUpdate(newProps.rows, element) : undefined,
type: newProps.type != null ? setupTypeUpdate(newProps.type, element) : undefined,
value: newProps.value != null ? setupValueUpdate(newProps.value, element) : undefined,
src: newProps.src != null ? setupSrcUpdate(newProps.src, element) : undefined,
['data-droppable']:
newProps['data-droppable'] != null ? setupDataDroppableUpdate(newProps['data-droppable'], element) : undefined,
['data-testid']:
newProps['data-testid'] != null ? setupDataTestidUpdate(newProps['data-testid'], element) : undefined,
['data-x-ray']: newProps['data-x-ray'] != null ? setupDataXRayUpdate(newProps['data-x-ray'], element) : undefined,
}
},
finalizeInitialChildren: function () {
return false
},
prepareForCommit: function () {},
resetAfterCommit: function () {},
commitMount: function () {},
prepareUpdate: function () {
return true
},
commitUpdate: function (instance, updatePayload, type, oldProps, newProps) {
const { element: uncastElement } = instance
if (type === 'fast-text') {
const textElement = uncastElement as Text
if (newProps.text !== oldProps.text) {
instance.text?.()
instance.text = setupTextUpdate(newProps.text, textElement)
}
return
}
const element = uncastElement as HTMLElement
if (newProps.style !== oldProps.style) {
const style = instance.style || element.style
const styleUnsubscribers = instance.styleUnsubscribers || new Map()
instance.style = style
instance.styleUnsubscribers = styleUnsubscribers
const notNullStyle = style as unknown as Record<string, unknown>
const oldStyleProp = oldProps.style
const newStyleProp = newProps.style
if (oldStyleProp != null) {
for (const key in oldStyleProp) {
const oldValue = oldStyleProp[key]
const newValue = newStyleProp?.[key]
if (oldValue !== newValue || newStyleProp == null) {
if (isFacet(oldValue)) {
styleUnsubscribers.get(key)?.()
}
}
}
}
if (newStyleProp != null) {
for (const key in newStyleProp) {
const oldValue = oldStyleProp?.[key]
const newValue = newStyleProp[key]
if (oldValue !== newValue || oldStyleProp == null) {
if (isFacet(newValue)) {
styleUnsubscribers.set(
key,
newValue.observe((value) => {
notNullStyle[key] = value
}),
)
} else {
notNullStyle[key] = newValue
}
}
}
}
}
if (newProps.dangerouslySetInnerHTML != oldProps.dangerouslySetInnerHTML) {
if (newProps.dangerouslySetInnerHTML != null) {
element.innerHTML = newProps.dangerouslySetInnerHTML.__html
} else {
element.innerHTML = ''
}
}
if (newProps.autoPlay !== oldProps.autoPlay) {
instance.autoPlay?.()
if (newProps.autoPlay == null) {
element.removeAttribute('autoplay')
} else {
instance.autoPlay = setupAutoPlayUpdate(newProps.autoPlay, element)
}
}
if (newProps.className !== oldProps.className) {
instance.className?.()
if (newProps.className == null) {
element.className = ''
} else {
instance.className = setupClassUpdate(newProps.className, element)
}
}
if (newProps['data-droppable'] !== oldProps['data-droppable']) {
instance['data-droppable']?.()
if (newProps['data-droppable'] == null) {
element.removeAttribute('data-droppable')
} else {
instance['data-droppable'] = setupDataDroppableUpdate(newProps['data-droppable'], element)
}
}
if (newProps['data-testid'] !== oldProps['data-testid']) {
instance['data-testid']?.()
if (newProps['data-testid'] == null) {
element.removeAttribute('data-testid')
} else {
instance['data-testid'] = setupDataTestidUpdate(newProps['data-testid'], element)
}
}
if (newProps['data-x-ray'] !== oldProps['data-x-ray']) {
instance['data-x-ray']?.()
if (newProps['data-x-ray'] == null) {
element.removeAttribute('data-x-ray')
} else {
instance['data-x-ray'] = setupDataXRayUpdate(newProps['data-x-ray'], element)
}
}
if (newProps.id !== oldProps.id) {
instance.id?.()
if (newProps.id == null) {
element.id = ''
} else {
instance.id = setupIdUpdate(newProps.id, element)
}
}
if (newProps.loop !== oldProps.loop) {
instance.loop?.()
if (newProps.loop == null) {
element.removeAttribute('loop')
} else {
instance.loop = setupLoopUpdate(newProps.loop, element)
}
}
if (newProps.href !== oldProps.href) {
instance.href?.()
if (newProps.href == null) {
element.removeAttribute('href')
} else {
instance.href = setupHrefUpdate(newProps.href, element)
}
}
if (newProps.target !== oldProps.target) {
instance.target?.()
if (newProps.target == null) {
element.removeAttribute('target')
} else {
instance.target = setupTargetUpdate(newProps.target, element)
}
}
if (newProps.disabled !== oldProps.disabled) {
instance.disabled?.()
if (newProps.disabled == null) {
element.removeAttribute('disabled')
} else {
instance.disabled = setupDisabledUpdate(newProps.disabled, element)
}
}
if (newProps.maxLength !== oldProps.maxLength) {
instance.maxLength?.()
if (newProps.maxLength == null) {
const textElement = element as HTMLTextAreaElement
textElement.removeAttribute('maxlength')
} else {
instance.maxLength = setupMaxLengthUpdate(newProps.maxLength, element)
}
}
if (newProps.rows !== oldProps.rows) {
instance.rows?.()
if (newProps.rows == null) {
const textElement = element as HTMLTextAreaElement
textElement.removeAttribute('rows')
} else {
instance.rows = setupRowsUpdate(newProps.rows, element)
}
}
if (newProps.type !== oldProps.type) {
instance.type?.()
if (newProps.type == null) {
const textElement = element as HTMLTextAreaElement
textElement.removeAttribute('type')
} else {
instance.type = setupTypeUpdate(newProps.type, element)
}
}
if (newProps.value !== oldProps.value) {
instance.value?.()
if (newProps.value == null) {
const textElement = element as HTMLTextAreaElement
textElement.removeAttribute('value')
} else {
instance.value = setupValueUpdate(newProps.value, element)
}
}
if (newProps.src !== oldProps.src) {
instance.src?.()
if (newProps.src == null) {
const textElement = element as HTMLTextAreaElement
textElement.removeAttribute('src')
} else {
instance.src = setupSrcUpdate(newProps.src, element)
}
}
if (newProps.onClick !== oldProps.onClick) {
if (oldProps.onClick) element.removeEventListener('click', oldProps.onClick)
if (newProps.onClick) element.addEventListener('click', newProps.onClick)
}
if (newProps.onFocus !== oldProps.onFocus) {
if (oldProps.onFocus) element.removeEventListener('focus', oldProps.onFocus)
if (newProps.onFocus) element.addEventListener('focus', newProps.onFocus)
}
if (newProps.onBlur !== oldProps.onBlur) {
if (oldProps.onBlur) element.removeEventListener('blur', oldProps.onBlur)
if (newProps.onBlur) element.addEventListener('blur', newProps.onBlur)
}
if (newProps.onMouseDown !== oldProps.onMouseDown) {
if (oldProps.onMouseDown) element.removeEventListener('mousedown', oldProps.onMouseDown)
if (newProps.onMouseDown) element.addEventListener('mousedown', newProps.onMouseDown)
}
if (newProps.onMouseEnter !== oldProps.onMouseEnter) {
if (oldProps.onMouseEnter) element.removeEventListener('mouseenter', oldProps.onMouseEnter)
if (newProps.onMouseEnter) element.addEventListener('mouseenter', newProps.onMouseEnter)
}
if (newProps.onMouseLeave !== oldProps.onMouseLeave) {
if (oldProps.onMouseLeave) element.removeEventListener('mouseleave', oldProps.onMouseLeave)
if (newProps.onMouseLeave) element.addEventListener('mouseleave', newProps.onMouseLeave)
}
if (newProps.onMouseUp !== oldProps.onMouseUp) {
if (oldProps.onMouseUp) element.removeEventListener('mouseup', oldProps.onMouseUp)
if (newProps.onMouseUp) element.addEventListener('mouseup', newProps.onMouseUp)
}
if (newProps.onTouchStart !== oldProps.onTouchStart) {
if (oldProps.onTouchStart) element.removeEventListener('touchstart', oldProps.onTouchStart)
if (newProps.onTouchStart) element.addEventListener('touchstart', newProps.onTouchStart)
}
if (newProps.onTouchMove !== oldProps.onTouchMove) {
if (oldProps.onTouchMove) element.removeEventListener('touchmove', oldProps.onTouchMove)
if (newProps.onTouchMove) element.addEventListener('touchmove', newProps.onTouchMove)
}
if (newProps.onTouchEnd !== oldProps.onTouchEnd) {
if (oldProps.onTouchEnd) element.removeEventListener('touchend', oldProps.onTouchEnd)
if (newProps.onTouchEnd) element.addEventListener('touchend', newProps.onTouchEnd)
}
if (newProps.onTouchMove !== oldProps.onTouchMove) {
if (oldProps.onTouchMove) element.removeEventListener('touchmove', oldProps.onTouchMove)
if (newProps.onTouchMove) element.addEventListener('touchmove', newProps.onTouchMove)
}
if (newProps.onTouchEnd !== oldProps.onTouchEnd) {
if (oldProps.onTouchEnd) element.removeEventListener('touchend', oldProps.onTouchEnd)
if (newProps.onTouchEnd) element.addEventListener('touchend', newProps.onTouchEnd)
}
if (newProps.onKeyPress !== oldProps.onKeyPress) {
if (oldProps.onKeyPress) element.removeEventListener('keypress', oldProps.onKeyPress)
if (newProps.onKeyPress) element.addEventListener('keypress', newProps.onKeyPress)
}
if (newProps.onKeyDown !== oldProps.onKeyDown) {
if (oldProps.onKeyDown) element.removeEventListener('keydown', oldProps.onKeyDown)
if (newProps.onKeyDown) element.addEventListener('keydown', newProps.onKeyDown)
}
if (newProps.onKeyUp !== oldProps.onKeyUp) {
if (oldProps.onKeyUp) element.removeEventListener('keyup', oldProps.onKeyUp)
if (newProps.onKeyUp) element.addEventListener('keyup', newProps.onKeyUp)
}
},
commitTextUpdate: function (textInstance, oldText, newText) {
textInstance.element.nodeValue = newText
},
appendInitialChild: function (parent, child) {
if (isElementContainer(child)) {
parent.children.add(child)
}
parent.element.appendChild(child.element)
},
appendChildToContainer: function (parent, child) {
if (isElementContainer(child)) {
parent.children.add(child)
}
parent.element.appendChild(child.element)
},
appendChild: function (parentInstance, child) {
if (isElementContainer(child)) {
parentInstance.children.add(child)
}
parentInstance.element.appendChild(child.element)
},
insertBefore: function (parentInstance, child, beforeChild) {
parentInstance.element.insertBefore(child.element, beforeChild.element)
},
removeChild: function (parentInstance, child) {
if (isElementContainer(child)) {
cleanupElementContainer(child)
}
parentInstance.element.removeChild(child.element)
},
insertInContainerBefore: function (container, child, beforeChild) {
container.element.insertBefore(child.element, beforeChild.element)
},
removeChildFromContainer: function (container, child) {
if (isElementContainer(child)) {
cleanupElementContainer(child)
}
container.element.removeChild(child.element)
},
resetTextContent: function (instance) {
instance.element.textContent = ''
},
shouldDeprioritizeSubtree: function () {
return false
},
getPublicInstance: function (instance) {
return instance.element
},
})
const cleanupElementContainer = (instance: ElementContainer) => {
instance.styleUnsubscribers?.forEach((unsubscribe) => unsubscribe())
instance.styleUnsubscribers?.clear()
instance.children.forEach(cleanupElementContainer)
instance.children.clear()
instance.className?.()
instance['data-droppable']?.()
instance['data-testid']?.()
instance['data-x-ray']?.()
instance.id?.()
instance.src?.()
instance.href?.()
instance.target?.()
instance.autoPlay?.()
instance.loop?.()
instance.disabled?.()
instance.maxLength?.()
instance.rows?.()
instance.value?.()
instance.type?.()
instance.text?.()
}
const setupClassUpdate = (className: FacetProp<string | undefined>, element: HTMLElement) => {
if (isFacet(className)) {
return className.observe((className) => {
element.className = className ?? ''
})
} else {
element.className = className ?? ''
}
}
const setupIdUpdate = (id: FacetProp<string | undefined>, element: HTMLElement) => {
if (isFacet(id)) {
return id.observe((id) => {
element.id = id ?? ''
})
} else {
element.id = id ?? ''
}
}
/**
* The React prop is called autoPlay (capital P) while the DOM
* attribute is all lowercase (i.e. autoplay), so we handle that here.
*/
const setupAutoPlayUpdate = (autoPlay: FacetProp<boolean | undefined>, element: HTMLElement) => {
if (isFacet(autoPlay)) {
return autoPlay.observe((autoPlay) => {
if (autoPlay) {
element.setAttribute('autoplay', '')
} else {
element.removeAttribute('autoplay')
}
})
} else {
if (autoPlay) {
element.setAttribute('autoplay', '')
} else {
element.removeAttribute('autoplay')
}
}
}
const setupDataDroppableUpdate = (dataDroppable: FacetProp<boolean | undefined>, element: HTMLElement) => {
if (isFacet(dataDroppable)) {
return dataDroppable.observe((dataDroppable) => {
if (dataDroppable) {
element.setAttribute('data-droppable', '')
} else {
element.removeAttribute('data-droppable')
}
})
} else {
if (dataDroppable) {
element.setAttribute('data-droppable', '')
} else {
element.removeAttribute('data-droppable')
}
}
}
const setupDataTestidUpdate = (dataTestid: FacetProp<string | undefined>, element: HTMLElement) => {
if (isFacet(dataTestid)) {
return dataTestid.observe((dataTestid) => {
if (dataTestid != null) {
element.setAttribute('data-testid', dataTestid)
} else {
element.removeAttribute('data-testid')
}
})
} else {
if (dataTestid != null) {
element.setAttribute('data-testid', dataTestid)
} else {
element.removeAttribute('data-testid')
}
}
}
const setupDataXRayUpdate = (dataXRay: FacetProp<boolean | undefined>, element: HTMLElement) => {
if (isFacet(dataXRay)) {
return dataXRay.observe((dataXRay) => {
if (dataXRay) {
element.setAttribute('data-x-ray', '')
} else {
element.removeAttribute('data-x-ray')
}
})
} else {
if (dataXRay) {
element.setAttribute('data-x-ray', '')
} else {
element.removeAttribute('data-x-ray')
}
}
}
const setupLoopUpdate = (loop: FacetProp<boolean | undefined>, element: HTMLElement) => {
if (isFacet(loop)) {
return loop.observe((loop) => {
if (loop) {
element.setAttribute('loop', '')
} else {
element.removeAttribute('loop')
}
})
} else {
if (loop) {
element.setAttribute('loop', '')
} else {
element.removeAttribute('loop')
}
}
}
const setupHrefUpdate = (href: FacetProp<string | undefined>, element: HTMLElement) => {
if (isFacet(href)) {
return href.observe((href) => {
if (href != null) {
element.setAttribute('href', href)
} else {
element.removeAttribute('href')
}
})
} else {
if (href != null) {
element.setAttribute('href', href)
} else {
element.removeAttribute('href')
}
}
}
const setupTargetUpdate = (target: FacetProp<string | undefined>, element: HTMLElement) => {
if (isFacet(target)) {
return target.observe((target) => {
if (target != null) {
element.setAttribute('target', target)
} else {
element.removeAttribute('target')
}
})
} else {
if (target != null) {
element.setAttribute('target', target)
} else {
element.removeAttribute('target')
}
}
}
const setupDisabledUpdate = (disabled: FacetProp<boolean | undefined>, element: HTMLElement) => {
if (isFacet(disabled)) {
return disabled.observe((disabled) => {
if (disabled) {
element.setAttribute('disabled', '')
} else {
element.removeAttribute('disabled')
}
})
} else {
if (disabled) {
element.setAttribute('disabled', '')
} else {
element.removeAttribute('disabled')
}
}
}
const setupMaxLengthUpdate = (maxLength: FacetProp<number | undefined>, element: HTMLElement) => {
if (isFacet(maxLength)) {
return maxLength.observe((maxLength) => {
const textElement = element as HTMLTextAreaElement
textElement.maxLength = maxLength ?? Number.MAX_SAFE_INTEGER
})
} else {
const textElement = element as HTMLTextAreaElement
textElement.maxLength = maxLength ?? Number.MAX_SAFE_INTEGER
}
}
const setupRowsUpdate = (rows: FacetProp<number | undefined>, element: HTMLElement) => {
if (isFacet(rows)) {
return rows.observe((rows) => {
const textElement = element as HTMLTextAreaElement
textElement.rows = rows ?? Number.MAX_SAFE_INTEGER
})
} else {
const textElement = element as HTMLTextAreaElement
textElement.rows = rows ?? Number.MAX_SAFE_INTEGER
}
}
const setupTypeUpdate = (type: FacetProp<string | undefined>, element: HTMLElement) => {
if (isFacet(type)) {
return type.observe((type) => {
if (type != null) {
element.setAttribute('type', type)
} else {
element.removeAttribute('type')
}
})
} else {
if (type != null) {
element.setAttribute('type', type)
} else {
element.removeAttribute('type')
}
}
}
/**
* The value attribute seems to behave differently to other
* attributes. When using `setAttribute`, browsers and gameface
* don't always update the element to have what's in the value,
* so we need to set the `value` attribute directly to solve this.
* ref: https://github.com/facebook/react/blob/master/packages/react-dom/src/client/ReactDOMInput.js
*/
const setupValueUpdate = (value: FacetProp<string | undefined>, element: HTMLElement) => {
if (isFacet(value)) {
return value.observe((value) => {
const inputElement = element as HTMLInputElement
inputElement.value = value ?? ''
if (value != null) {
inputElement.setAttribute('value', value)
} else {
inputElement.removeAttribute('value')
}
})
} else {
const inputElement = element as HTMLInputElement
inputElement.value = value ?? ''
if (value != null) {
inputElement.setAttribute('value', value)
} else {
inputElement.removeAttribute('value')
}
}
}
const setupSrcUpdate = (src: FacetProp<string | undefined>, element: HTMLElement) => {
if (isFacet(src)) {
return src.observe((src) => {
const textElement = element as HTMLImageElement
textElement.src = src ?? ''
})
} else {
const textElement = element as HTMLImageElement
textElement.src = src ?? ''
}
}
const setupTextUpdate = (text: FacetProp<string | number | undefined>, element: Text) => {
if (isFacet(text)) {
return text.observe((text) => {
const textElement = element as Text
textElement.nodeValue = (text ?? '') as string
})
} else {
const textElement = element as Text
textElement.nodeValue = (text ?? '') as string
}
}
const noop = () => {}
const EMPTY = {}
const fastTypeMap: Record<Type, keyof HTMLElementTagNameMap> = {
'fast-a': 'a',
'fast-div': 'div',
'fast-p': 'p',
'fast-img': 'img',
'fast-textarea': 'textarea',
'fast-input': 'input',
'fast-span': 'span',
// TODO: fix weird map
'fast-text': 'span',
a: 'a',
div: 'div',
p: 'p',
img: 'img',
textarea: 'textarea',
input: 'input',
style: 'style',
} | the_stack |
import { Injectable } from '@angular/core';
import { CoreCourse } from '@features/course/services/course';
import { CoreUser } from '@features/user/services/user';
import { CoreNavigator } from '@services/navigator';
import { CoreSites, CoreSitesReadingStrategy } from '@services/sites';
import { CoreDomUtils } from '@services/utils/dom';
import { CoreTextUtils } from '@services/utils/text';
import { CoreTimeUtils } from '@services/utils/time';
import { CoreUtils } from '@services/utils/utils';
import { makeSingleton, Translate } from '@singletons';
import {
AddonModFeedback,
AddonModFeedbackGetNonRespondentsWSResponse,
AddonModFeedbackGetResponsesAnalysisWSResponse,
AddonModFeedbackGroupPaginatedOptions,
AddonModFeedbackItem,
AddonModFeedbackProvider,
AddonModFeedbackResponseValue,
AddonModFeedbackWSAttempt,
AddonModFeedbackWSNonRespondent,
} from './feedback';
import { AddonModFeedbackModuleHandlerService } from './handlers/module';
const MODE_RESPONSETIME = 1;
const MODE_COURSE = 2;
const MODE_CATEGORY = 3;
/**
* Service that provides helper functions for feedbacks.
*/
@Injectable({ providedIn: 'root' })
export class AddonModFeedbackHelperProvider {
/**
* Retrieves a list of students who didn't submit the feedback with extra info.
*
* @param feedbackId Feedback ID.
* @param options Other options.
* @return Promise resolved when the info is retrieved.
*/
async getNonRespondents(
feedbackId: number,
options: AddonModFeedbackGroupPaginatedOptions = {},
): Promise<AddonModFeedbackGetNonRespondents> {
const responses: AddonModFeedbackGetNonRespondents = await AddonModFeedback.getNonRespondents(feedbackId, options);
responses.users = await this.addImageProfile(responses.users);
return responses;
}
/**
* Get page items responses to be sent.
*
* @param items Items where the values are.
* @return Responses object to be sent.
*/
getPageItemsResponses(items: AddonModFeedbackFormItem[]): Record<string, AddonModFeedbackResponseValue> {
const responses: Record<string, AddonModFeedbackResponseValue> = {};
items.forEach((itemData) => {
let answered = false;
itemData.hasError = false;
if (itemData.typ == 'captcha') {
const value = itemData.value || '';
const name = itemData.typ + '_' + itemData.id;
answered = !!value;
responses[name] = 1;
responses['g-recaptcha-response'] = value;
responses['recaptcha_element'] = 'dummyvalue';
if (itemData.required && !answered) {
// Check if it has any value.
itemData.isEmpty = true;
} else {
itemData.isEmpty = false;
}
} else if (itemData.hasvalue) {
let name: string;
let value: AddonModFeedbackResponseValue;
const nameTemp = itemData.typ + '_' + itemData.id;
if (this.isMultiChoiceItem(itemData) && itemData.subtype == 'c') {
name = nameTemp + '[0]';
responses[name] = 0;
itemData.choices.forEach((choice, index) => {
name = nameTemp + '[' + (index + 1) + ']';
value = choice.checked ? choice.value : 0;
if (!answered && value) {
answered = true;
}
responses[name] = value;
});
} else {
if (this.isMultiChoiceItem(itemData) && itemData.subtype != 'r') {
name = nameTemp + '[0]';
} else {
name = nameTemp;
}
if (itemData.typ == 'multichoice' || itemData.typ == 'multichoicerated') {
value = itemData.value || 0;
} else if (this.isNumericItem(itemData)) {
value = itemData.value || itemData.value == 0 ? itemData.value : '';
if (value != '') {
if ((itemData.rangefrom != '' && value < itemData.rangefrom) ||
(itemData.rangeto != '' && value > itemData.rangeto)) {
itemData.hasError = true;
}
}
} else {
value = itemData.value || itemData.value == 0 ? itemData.value : '';
}
answered = !!value;
responses[name] = value;
}
if (itemData.required && !answered) {
// Check if it has any value.
itemData.isEmpty = true;
} else {
itemData.isEmpty = false;
}
}
});
return responses;
}
/**
* Returns the feedback user responses with extra info.
*
* @param feedbackId Feedback ID.
* @param options Other options.
* @return Promise resolved when the info is retrieved.
*/
async getResponsesAnalysis(
feedbackId: number,
options: AddonModFeedbackGroupPaginatedOptions = {},
): Promise<AddonModFeedbackResponsesAnalysis> {
const responses: AddonModFeedbackResponsesAnalysis = await AddonModFeedback.getResponsesAnalysis(feedbackId, options);
responses.attempts = await this.addImageProfile(responses.attempts);
return responses;
}
/**
* Handle a show entries link.
*
* @param params URL params.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when done.
*/
async handleShowEntriesLink(params: Record<string, string>, siteId?: string): Promise<void> {
siteId = siteId || CoreSites.getCurrentSiteId();
const modal = await CoreDomUtils.showModalLoading();
try {
const module = await CoreCourse.getModuleBasicInfo(
Number(params.id),
{ siteId, readingStrategy: CoreSitesReadingStrategy.PREFER_CACHE },
);
if (params.showcompleted === undefined) {
// Param showcompleted not defined. Show entry list.
await CoreNavigator.navigateToSitePath(
AddonModFeedbackModuleHandlerService.PAGE_NAME + `/${module.course}/${module.id}/attempts`,
{ siteId },
);
return;
}
const attempt = await AddonModFeedback.getAttempt(module.instance, Number(params.showcompleted), {
cmId: module.id,
readingStrategy: CoreSitesReadingStrategy.ONLY_NETWORK,
siteId,
});
await CoreNavigator.navigateToSitePath(
AddonModFeedbackModuleHandlerService.PAGE_NAME + `/${module.course}/${module.id}/attempt/${attempt.id}`,
{
params: {
feedbackId: module.instance,
attempt: attempt,
},
siteId,
},
);
} catch (error) {
CoreDomUtils.showErrorModalDefault(error, 'Error opening link.');
} finally {
modal.dismiss();
}
}
/**
* Add Image profile url field on some entries.
*
* @param entries Entries array to get profile from.
* @return Returns the same array with the profileimageurl added if found.
*/
protected async addImageProfile(entries: AddonModFeedbackWSAttempt[]): Promise<AddonModFeedbackAttempt[]>;
protected async addImageProfile(entries: AddonModFeedbackWSNonRespondent[]): Promise<AddonModFeedbackNonRespondent[]>;
protected async addImageProfile(
entries: (AddonModFeedbackWSAttempt | AddonModFeedbackWSNonRespondent)[],
): Promise<(AddonModFeedbackAttempt | AddonModFeedbackNonRespondent)[]> {
return await Promise.all(entries.map(async (entry: AddonModFeedbackAttempt | AddonModFeedbackNonRespondent) => {
try {
const user = await CoreUser.getProfile(entry.userid, entry.courseid, true);
entry.profileimageurl = user.profileimageurl;
} catch {
// Error getting profile, resolve promise without adding any extra data.
}
return entry;
}));
}
/**
* Helper funtion for item type Label.
*
* @param item Item to process.
* @return Item processed to show form.
*/
protected getItemFormLabel(item: AddonModFeedbackItem): AddonModFeedbackFormBasicItem {
item.name = '';
item.presentation = CoreTextUtils.replacePluginfileUrls(item.presentation, item.itemfiles);
return Object.assign(item, {
templateName: 'label',
value: '',
hasTextInput: false,
});
}
/**
* Helper funtion for item type Info.
*
* @param item Item to process.
* @return Item processed to show form.
*/
protected getItemFormInfo(item: AddonModFeedbackItem): AddonModFeedbackFormBasicItem | undefined {
const formItem: AddonModFeedbackFormBasicItem = Object.assign(item, {
templateName: 'label',
value: '',
hasTextInput: false,
});
const type = parseInt(formItem.presentation, 10);
if (type == MODE_COURSE || type == MODE_CATEGORY) {
formItem.presentation = formItem.otherdata;
formItem.value = formItem.rawValue !== undefined ? formItem.rawValue : formItem.otherdata;
} else if (type == MODE_RESPONSETIME) {
formItem.value = '__CURRENT__TIMESTAMP__';
const rawValue = Number(formItem.rawValue);
const tempValue = isNaN(rawValue) ? Date.now() : rawValue * 1000;
formItem.presentation = CoreTimeUtils.userDate(tempValue);
} else {
// Errors on item, return false.
return undefined;
}
return formItem;
}
/**
* Helper funtion for item type Numeric.
*
* @param item Item to process.
* @return Item processed to show form.
*/
protected getItemFormNumeric(item: AddonModFeedbackItem): AddonModFeedbackNumericItem {
const range = item.presentation.split(AddonModFeedbackProvider.LINE_SEP) || [];
const rangeFrom = range.length > 0 ? parseInt(range[0], 10) : undefined;
const rangeTo = range.length > 1 ? parseInt(range[1], 10) : undefined;
const formItem: AddonModFeedbackNumericItem = Object.assign(item, {
templateName: 'numeric',
value: item.rawValue !== undefined ? Number(item.rawValue) : '',
rangefrom: typeof rangeFrom == 'number' && !isNaN(rangeFrom) ? range[0] : '',
rangeto: typeof rangeTo == 'number' && !isNaN(rangeTo) ? rangeTo : '',
hasTextInput: true,
});
formItem.postfix = this.getNumericBoundariesForDisplay(formItem.rangefrom, formItem.rangeto);
return formItem;
}
/**
* Helper funtion for item type Text field.
*
* @param item Item to process.
* @return Item processed to show form.
*/
protected getItemFormTextfield(item: AddonModFeedbackItem): AddonModFeedbackTextItem {
return Object.assign(item, {
templateName: 'textfield',
length: Number(item.presentation.split(AddonModFeedbackProvider.LINE_SEP)[1]) || 255,
value: item.rawValue !== undefined ? item.rawValue : '',
hasTextInput: true,
});
}
/**
* Helper funtion for item type Textarea.
*
* @param item Item to process.
* @return Item processed to show form.
*/
protected getItemFormTextarea(item: AddonModFeedbackItem): AddonModFeedbackFormBasicItem {
return Object.assign(item, {
templateName: 'textarea',
value: item.rawValue !== undefined ? item.rawValue : '',
hasTextInput: true,
});
}
/**
* Helper funtion for item type Multichoice.
*
* @param item Item to process.
* @return Item processed to show form.
*/
protected getItemFormMultichoice(item: AddonModFeedbackItem): AddonModFeedbackMultichoiceItem {
let parts = item.presentation.split(AddonModFeedbackProvider.MULTICHOICE_TYPE_SEP) || [];
const subType = parts.length > 0 && parts[0] ? parts[0] : 'r';
const formItem: AddonModFeedbackMultichoiceItem = Object.assign(item, {
templateName: 'multichoice-' + subType,
subtype: subType,
value: '',
choices: [],
hasTextInput: false,
});
formItem.presentation = parts.length > 1 ? parts[1] : '';
if (formItem.subtype != 'd') {
parts = formItem.presentation.split(AddonModFeedbackProvider.MULTICHOICE_ADJUST_SEP) || [];
formItem.presentation = parts.length > 0 ? parts[0] : '';
// Horizontal are not supported right now. item.horizontal = parts.length > 1 && !!parts[1];
}
const choices = formItem.presentation.split(AddonModFeedbackProvider.LINE_SEP) || [];
formItem.choices = choices.map((choice, index) => {
const weightValue = choice.split(AddonModFeedbackProvider.MULTICHOICERATED_VALUE_SEP) || [''];
choice = weightValue.length == 1 ? weightValue[0] : '(' + weightValue[0] + ') ' + weightValue[1];
return { value: index + 1, label: choice };
});
if (formItem.subtype === 'r' && formItem.options.search(AddonModFeedbackProvider.MULTICHOICE_HIDENOSELECT) == -1) {
formItem.choices.unshift({ value: 0, label: Translate.instant('addon.mod_feedback.not_selected') });
formItem.value = formItem.rawValue !== undefined ? Number(formItem.rawValue) : 0;
} else if (formItem.subtype === 'd') {
formItem.choices.unshift({ value: 0, label: '' });
formItem.value = formItem.rawValue !== undefined ? Number(formItem.rawValue) : 0;
} else if (formItem.subtype === 'c') {
if (formItem.rawValue !== undefined) {
formItem.rawValue = String(formItem.rawValue);
const values = formItem.rawValue.split(AddonModFeedbackProvider.LINE_SEP);
formItem.choices.forEach((choice) => {
for (const x in values) {
if (choice.value == Number(values[x])) {
choice.checked = true;
return;
}
}
});
}
} else {
formItem.value = formItem.rawValue !== undefined ? Number(formItem.rawValue) : '';
}
return formItem;
}
/**
* Helper funtion for item type Captcha.
*
* @param item Item to process.
* @return Item processed to show form.
*/
protected getItemFormCaptcha(item: AddonModFeedbackItem): AddonModFeedbackCaptchaItem {
const formItem: AddonModFeedbackCaptchaItem = Object.assign(item, {
templateName: 'captcha',
value: '',
hasTextInput: false,
});
const data = <string[]> CoreTextUtils.parseJSON(item.otherdata);
if (data && data.length > 3) {
formItem.captcha = {
recaptchapublickey: data[3],
};
}
return formItem;
}
/**
* Process and returns item to print form.
*
* @param item Item to process.
* @param preview Previewing options.
* @return Item processed to show form.
*/
getItemForm(item: AddonModFeedbackItem, preview: boolean): AddonModFeedbackFormItem | undefined {
switch (item.typ) {
case 'label':
return this.getItemFormLabel(item);
case 'info':
return this.getItemFormInfo(item);
case 'numeric':
return this.getItemFormNumeric(item);
case 'textfield':
return this.getItemFormTextfield(item);
case 'textarea':
return this.getItemFormTextarea(item);
case 'multichoice':
return this.getItemFormMultichoice(item);
case 'multichoicerated':
return this.getItemFormMultichoice(item);
case 'pagebreak':
if (!preview) {
// Pagebreaks are only used on preview.
return undefined;
}
break;
case 'captcha':
// Captcha is not supported right now. However label will be shown.
return this.getItemFormCaptcha(item);
default:
return undefined;
}
}
/**
* Returns human-readable boundaries (min - max).
* Based on Moodle's get_boundaries_for_display.
*
* @param rangeFrom Range from.
* @param rangeTo Range to.
* @return Human-readable boundaries.
*/
protected getNumericBoundariesForDisplay(rangeFrom: number | string, rangeTo: number | string): string {
const rangeFromSet = typeof rangeFrom == 'number';
const rangeToSet = typeof rangeTo == 'number';
if (!rangeFromSet && rangeToSet) {
return ' (' + Translate.instant('addon.mod_feedback.maximal') + ': ' + CoreUtils.formatFloat(rangeTo) + ')';
} else if (rangeFromSet && !rangeToSet) {
return ' (' + Translate.instant('addon.mod_feedback.minimal') + ': ' + CoreUtils.formatFloat(rangeFrom) + ')';
} else if (!rangeFromSet && !rangeToSet) {
return '';
}
return ' (' + CoreUtils.formatFloat(rangeFrom) + ' - ' + CoreUtils.formatFloat(rangeTo) + ')';
}
/**
* Check if a form item is multichoice.
*
* @param item Item.
* @return Whether item is multichoice.
*/
protected isMultiChoiceItem(item: AddonModFeedbackFormItem): item is AddonModFeedbackMultichoiceItem {
return item.typ == 'multichoice';
}
/**
* Check if a form item is numeric.
*
* @param item Item.
* @return Whether item is numeric.
*/
protected isNumericItem(item: AddonModFeedbackFormItem): item is AddonModFeedbackNumericItem {
return item.typ == 'numeric';
}
}
export const AddonModFeedbackHelper = makeSingleton(AddonModFeedbackHelperProvider);
/**
* Attempt with some calculated data.
*/
export type AddonModFeedbackAttempt = AddonModFeedbackWSAttempt & {
profileimageurl?: string;
};
/**
* Non respondent with some calculated data.
*/
export type AddonModFeedbackNonRespondent = AddonModFeedbackWSNonRespondent & {
profileimageurl?: string;
};
/**
* Non respondents with some calculated data.
*/
export type AddonModFeedbackResponsesAnalysis = Omit<AddonModFeedbackGetResponsesAnalysisWSResponse, 'attempts'> & {
attempts: AddonModFeedbackAttempt[];
};
/**
* Non respondents with some calculated data.
*/
export type AddonModFeedbackGetNonRespondents = Omit<AddonModFeedbackGetNonRespondentsWSResponse, 'users'> & {
users: AddonModFeedbackNonRespondent[];
};
/**
* Item with form data.
*/
export type AddonModFeedbackFormItem =
AddonModFeedbackFormBasicItem | AddonModFeedbackNumericItem | AddonModFeedbackTextItem | AddonModFeedbackMultichoiceItem |
AddonModFeedbackCaptchaItem;
/**
* Common calculated data for all form items.
*/
export type AddonModFeedbackFormBasicItem = AddonModFeedbackItem & {
templateName: string;
value: AddonModFeedbackResponseValue;
hasTextInput: boolean;
isEmpty?: boolean;
hasError?: boolean;
};
/**
* Numeric item.
*/
export type AddonModFeedbackNumericItem = AddonModFeedbackFormBasicItem & {
rangefrom: number | string;
rangeto: number | string;
postfix?: string;
};
/**
* Text item.
*/
export type AddonModFeedbackTextItem = AddonModFeedbackFormBasicItem & {
length: number;
};
/**
* Multichoice item.
*/
export type AddonModFeedbackMultichoiceItem = AddonModFeedbackFormBasicItem & {
subtype: string;
choices: { value: number; label: string; checked?: boolean }[];
};
/**
* Captcha item.
*/
export type AddonModFeedbackCaptchaItem = AddonModFeedbackFormBasicItem & {
captcha?: {
recaptchapublickey: string;
};
}; | the_stack |
import { Component, EventEmitter, Input, OnChanges, Output, OnInit, OnDestroy, ElementRef, SimpleChanges, NgZone, Injector } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { Subscription, timer } from 'rxjs';
export interface CircleProgressOptionsInterface {
class?: string;
backgroundGradient?: boolean;
backgroundColor?: string;
backgroundGradientStopColor?: string;
backgroundOpacity?: number;
backgroundStroke?: string;
backgroundStrokeWidth?: number;
backgroundPadding?: number;
percent?: number;
radius?: number;
space?: number;
toFixed?: number;
maxPercent?: number;
renderOnClick?: boolean;
units?: string;
unitsFontSize?: string;
unitsFontWeight?: string;
unitsColor?: string;
outerStrokeGradient?: boolean;
outerStrokeWidth?: number;
outerStrokeColor?: string;
outerStrokeGradientStopColor?: string;
outerStrokeLinecap?: string;
innerStrokeColor?: string;
innerStrokeWidth?: number;
titleFormat?: Function;
title?: string | Array<String>;
titleColor?: string;
titleFontSize?: string;
titleFontWeight?: string;
subtitleFormat?: Function;
subtitle?: string | Array<String>;
subtitleColor?: string;
subtitleFontSize?: string;
subtitleFontWeight?: string;
imageSrc?: string;
imageHeight?: number;
imageWidth?: number;
animation?: boolean;
animateTitle?: boolean;
animateSubtitle?: boolean;
animationDuration?: number;
showTitle?: boolean;
showSubtitle?: boolean;
showUnits?: boolean;
showImage?: boolean;
showBackground?: boolean;
showInnerStroke?: boolean;
clockwise?: boolean;
responsive?: boolean;
startFromZero?: boolean;
showZeroOuterStroke?: boolean;
lazy?: boolean;
}
export class CircleProgressOptions implements CircleProgressOptionsInterface {
class = '';
backgroundGradient = false;
backgroundColor = 'transparent';
backgroundGradientStopColor = 'transparent';
backgroundOpacity = 1;
backgroundStroke = 'transparent';
backgroundStrokeWidth = 0;
backgroundPadding = 5;
percent = 0;
radius = 90;
space = 4;
toFixed = 0;
maxPercent = 1000;
renderOnClick = true;
units = '%';
unitsFontSize = '10';
unitsFontWeight = 'normal';
unitsColor = '#444444';
outerStrokeGradient = false;
outerStrokeWidth = 8;
outerStrokeColor = '#78C000';
outerStrokeGradientStopColor = 'transparent';
outerStrokeLinecap = 'round';
innerStrokeColor = '#C7E596';
innerStrokeWidth = 4;
titleFormat = undefined;
title: string | Array<String> = 'auto';
titleColor = '#444444';
titleFontSize = '20';
titleFontWeight = 'normal';
subtitleFormat = undefined;
subtitle: string | Array<String> = 'progress';
subtitleColor = '#A9A9A9';
subtitleFontSize = '10';
subtitleFontWeight = 'normal';
imageSrc = undefined;
imageHeight = undefined;
imageWidth = undefined;
animation = true;
animateTitle = true;
animateSubtitle = false;
animationDuration = 500;
showTitle = true;
showSubtitle = true;
showUnits = true;
showImage = false;
showBackground = true;
showInnerStroke = true;
clockwise = true;
responsive = false;
startFromZero = true;
showZeroOuterStroke = true;
lazy = false;
}
@Component({
selector: 'circle-progress',
template: `
<svg xmlns="http://www.w3.org/2000/svg" *ngIf="svg"
[attr.viewBox]="svg.viewBox" preserveAspectRatio="xMidYMid meet"
[attr.height]="svg.height" [attr.width]="svg.width" (click)="emitClickEvent($event)" [attr.class]="options.class">
<defs>
<linearGradient *ngIf="options.outerStrokeGradient" [attr.id]="svg.outerLinearGradient.id">
<stop offset="5%" [attr.stop-color]="svg.outerLinearGradient.colorStop1" [attr.stop-opacity]="1"/>
<stop offset="95%" [attr.stop-color]="svg.outerLinearGradient.colorStop2" [attr.stop-opacity]="1"/>
</linearGradient>
<radialGradient *ngIf="options.backgroundGradient" [attr.id]="svg.radialGradient.id">
<stop offset="5%" [attr.stop-color]="svg.radialGradient.colorStop1" [attr.stop-opacity]="1"/>
<stop offset="95%" [attr.stop-color]="svg.radialGradient.colorStop2" [attr.stop-opacity]="1"/>
</radialGradient>
</defs>
<ng-container *ngIf="options.showBackground">
<circle *ngIf="!options.backgroundGradient"
[attr.cx]="svg.backgroundCircle.cx"
[attr.cy]="svg.backgroundCircle.cy"
[attr.r]="svg.backgroundCircle.r"
[attr.fill]="svg.backgroundCircle.fill"
[attr.fill-opacity]="svg.backgroundCircle.fillOpacity"
[attr.stroke]="svg.backgroundCircle.stroke"
[attr.stroke-width]="svg.backgroundCircle.strokeWidth"/>
<circle *ngIf="options.backgroundGradient"
[attr.cx]="svg.backgroundCircle.cx"
[attr.cy]="svg.backgroundCircle.cy"
[attr.r]="svg.backgroundCircle.r"
attr.fill="url({{window.location.href}}#{{svg.radialGradient.id}})"
[attr.fill-opacity]="svg.backgroundCircle.fillOpacity"
[attr.stroke]="svg.backgroundCircle.stroke"
[attr.stroke-width]="svg.backgroundCircle.strokeWidth"/>
</ng-container>
<circle *ngIf="options.showInnerStroke"
[attr.cx]="svg.circle.cx"
[attr.cy]="svg.circle.cy"
[attr.r]="svg.circle.r"
[attr.fill]="svg.circle.fill"
[attr.stroke]="svg.circle.stroke"
[attr.stroke-width]="svg.circle.strokeWidth"/>
<ng-container *ngIf="+options.percent!==0 || options.showZeroOuterStroke">
<path *ngIf="!options.outerStrokeGradient"
[attr.d]="svg.path.d"
[attr.stroke]="svg.path.stroke"
[attr.stroke-width]="svg.path.strokeWidth"
[attr.stroke-linecap]="svg.path.strokeLinecap"
[attr.fill]="svg.path.fill"/>
<path *ngIf="options.outerStrokeGradient"
[attr.d]="svg.path.d"
attr.stroke="url({{window.location.href}}#{{svg.outerLinearGradient.id}})"
[attr.stroke-width]="svg.path.strokeWidth"
[attr.stroke-linecap]="svg.path.strokeLinecap"
[attr.fill]="svg.path.fill"/>
</ng-container>
<text *ngIf="!options.showImage && (options.showTitle || options.showUnits || options.showSubtitle)"
alignment-baseline="baseline"
[attr.x]="svg.circle.cx"
[attr.y]="svg.circle.cy"
[attr.text-anchor]="svg.title.textAnchor">
<ng-container *ngIf="options.showTitle">
<tspan *ngFor="let tspan of svg.title.tspans"
[attr.x]="svg.title.x"
[attr.y]="svg.title.y"
[attr.dy]="tspan.dy"
[attr.font-size]="svg.title.fontSize"
[attr.font-weight]="svg.title.fontWeight"
[attr.fill]="svg.title.color">{{tspan.span}}</tspan>
</ng-container>
<tspan *ngIf="options.showUnits"
[attr.font-size]="svg.units.fontSize"
[attr.font-weight]="svg.units.fontWeight"
[attr.fill]="svg.units.color">{{svg.units.text}}</tspan>
<ng-container *ngIf="options.showSubtitle">
<tspan *ngFor="let tspan of svg.subtitle.tspans"
[attr.x]="svg.subtitle.x"
[attr.y]="svg.subtitle.y"
[attr.dy]="tspan.dy"
[attr.font-size]="svg.subtitle.fontSize"
[attr.font-weight]="svg.subtitle.fontWeight"
[attr.fill]="svg.subtitle.color">{{tspan.span}}</tspan>
</ng-container>
</text>
<image *ngIf="options.showImage" preserveAspectRatio="none"
[attr.height]="svg.image.height"
[attr.width]="svg.image.width"
[attr.xlink:href]="svg.image.src"
[attr.x]="svg.image.x"
[attr.y]="svg.image.y"
/>
</svg>
`
})
export class CircleProgressComponent implements OnChanges, OnInit, OnDestroy {
@Output() onClick = new EventEmitter<MouseEvent>();
@Input() name: string;
@Input() class: string;
@Input() backgroundGradient: boolean;
@Input() backgroundColor: string;
@Input() backgroundGradientStopColor: String;
@Input() backgroundOpacity: number;
@Input() backgroundStroke: string;
@Input() backgroundStrokeWidth: number;
@Input() backgroundPadding: number;
@Input() radius: number;
@Input() space: number;
@Input() percent: number;
@Input() toFixed: number;
@Input() maxPercent: number;
@Input() renderOnClick: boolean;
@Input() units: string;
@Input() unitsFontSize: string;
@Input() unitsFontWeight: string;
@Input() unitsColor: string;
@Input() outerStrokeGradient: boolean;
@Input() outerStrokeWidth: number;
@Input() outerStrokeColor: string;
@Input() outerStrokeGradientStopColor: String;
@Input() outerStrokeLinecap: string;
@Input() innerStrokeColor: string;
@Input() innerStrokeWidth: string | number;
@Input() titleFormat: Function;
@Input() title: string | Array<String>;
@Input() titleColor: string;
@Input() titleFontSize: string;
@Input() titleFontWeight: string;
@Input() subtitleFormat: Function;
@Input() subtitle: string | string[];
@Input() subtitleColor: string;
@Input() subtitleFontSize: string;
@Input() subtitleFontWeight: string;
@Input() imageSrc: string;
@Input() imageHeight: number;
@Input() imageWidth: number;
@Input() animation: boolean;
@Input() animateTitle: boolean;
@Input() animateSubtitle: boolean;
@Input() animationDuration: number;
@Input() showTitle: boolean;
@Input() showSubtitle: boolean;
@Input() showUnits: boolean;
@Input() showImage: boolean;
@Input() showBackground: boolean;
@Input() showInnerStroke: boolean;
@Input() clockwise: boolean;
@Input() responsive: boolean;
@Input() startFromZero: boolean;
@Input() showZeroOuterStroke: boolean;
@Input() lazy: boolean;
@Input('options') templateOptions: CircleProgressOptions;
// <svg> of component
svgElement: HTMLElement = null;
// whether <svg> is in viewport
isInViewport: Boolean = false;
// event for notifying viewport change caused by scrolling or resizing
onViewportChanged: EventEmitter<{ oldValue: Boolean, newValue: Boolean }> = new EventEmitter();
window: Window;
_viewportChangedSubscriber: Subscription = null;
svg: any;
options: CircleProgressOptions = new CircleProgressOptions();
defaultOptions: CircleProgressOptions = new CircleProgressOptions();
_lastPercent: number = 0;
_gradientUUID: string = null;
render = () => {
this.applyOptions();
if (this.options.lazy) {
// Draw svg if it doesn't exist
this.svgElement === null && this.draw(this._lastPercent);
// Draw it only when it's in the viewport
if (this.isInViewport) {
// Draw it at the latest position when I am in.
if (this.options.animation && this.options.animationDuration > 0) {
this.animate(this._lastPercent, this.options.percent);
} else {
this.draw(this.options.percent);
}
this._lastPercent = this.options.percent;
}
} else {
if (this.options.animation && this.options.animationDuration > 0) {
this.animate(this._lastPercent, this.options.percent);
} else {
this.draw(this.options.percent);
}
this._lastPercent = this.options.percent;
}
};
polarToCartesian = (centerX: number, centerY: number, radius: number, angleInDegrees: number) => {
let angleInRadius = angleInDegrees * Math.PI / 180;
let x = centerX + Math.sin(angleInRadius) * radius;
let y = centerY - Math.cos(angleInRadius) * radius;
return { x: x, y: y };
};
draw = (percent: number) => {
// make percent reasonable
percent = (percent === undefined) ? this.options.percent : Math.abs(percent);
// circle percent shouldn't be greater than 100%.
let circlePercent = (percent > 100) ? 100 : percent;
// determine box size
let boxSize = this.options.radius * 2 + this.options.outerStrokeWidth * 2;
if (this.options.showBackground) {
boxSize += (this.options.backgroundStrokeWidth * 2 + this.max(0, this.options.backgroundPadding * 2));
}
// the centre of the circle
let centre = { x: boxSize / 2, y: boxSize / 2 };
// the start point of the arc
let startPoint = { x: centre.x, y: centre.y - this.options.radius };
// get the end point of the arc
let endPoint = this.polarToCartesian(centre.x, centre.y, this.options.radius, 360 * (this.options.clockwise ?
circlePercent :
(100 - circlePercent)) / 100); // ####################
// We'll get an end point with the same [x, y] as the start point when percent is 100%, so move x a little bit.
if (circlePercent === 100) {
endPoint.x = endPoint.x + (this.options.clockwise ? -0.01 : +0.01);
}
// largeArcFlag and sweepFlag
let largeArcFlag: any, sweepFlag: any;
if (circlePercent > 50) {
[largeArcFlag, sweepFlag] = this.options.clockwise ? [1, 1] : [1, 0];
} else {
[largeArcFlag, sweepFlag] = this.options.clockwise ? [0, 1] : [0, 0];
}
// percent may not equal the actual percent
let titlePercent = this.options.animateTitle ? percent : this.options.percent;
let titleTextPercent = titlePercent > this.options.maxPercent ?
`${this.options.maxPercent.toFixed(this.options.toFixed)}+` : titlePercent.toFixed(this.options.toFixed);
let subtitlePercent = this.options.animateSubtitle ? percent : this.options.percent;
// get title object
let title = {
x: centre.x,
y: centre.y,
textAnchor: 'middle',
color: this.options.titleColor,
fontSize: this.options.titleFontSize,
fontWeight: this.options.titleFontWeight,
texts: [],
tspans: []
};
// from v0.9.9, both title and titleFormat(...) may be an array of string.
if (this.options.titleFormat !== undefined && this.options.titleFormat.constructor.name === 'Function') {
let formatted = this.options.titleFormat(titlePercent);
if (formatted instanceof Array) {
title.texts = [...formatted];
} else {
title.texts.push(formatted.toString());
}
} else {
if (this.options.title === 'auto') {
title.texts.push(titleTextPercent);
} else {
if (this.options.title instanceof Array) {
title.texts = [...this.options.title]
} else {
title.texts.push(this.options.title.toString());
}
}
}
// get subtitle object
let subtitle = {
x: centre.x,
y: centre.y,
textAnchor: 'middle',
color: this.options.subtitleColor,
fontSize: this.options.subtitleFontSize,
fontWeight: this.options.subtitleFontWeight,
texts: [],
tspans: []
}
// from v0.9.9, both subtitle and subtitleFormat(...) may be an array of string.
if (this.options.subtitleFormat !== undefined && this.options.subtitleFormat.constructor.name === 'Function') {
let formatted = this.options.subtitleFormat(subtitlePercent);
if (formatted instanceof Array) {
subtitle.texts = [...formatted];
} else {
subtitle.texts.push(formatted.toString());
}
} else {
if (this.options.subtitle instanceof Array) {
subtitle.texts = [...this.options.subtitle]
} else {
subtitle.texts.push(this.options.subtitle.toString());
}
}
// get units object
let units = {
text: `${this.options.units}`,
fontSize: this.options.unitsFontSize,
fontWeight: this.options.unitsFontWeight,
color: this.options.unitsColor
};
// get total count of text lines to be shown
let rowCount = 0, rowNum = 1;
this.options.showTitle && (rowCount += title.texts.length);
this.options.showSubtitle && (rowCount += subtitle.texts.length);
// calc dy for each tspan for title
if (this.options.showTitle) {
for (let span of title.texts) {
title.tspans.push({ span: span, dy: this.getRelativeY(rowNum, rowCount) });
rowNum++;
}
}
// calc dy for each tspan for subtitle
if (this.options.showSubtitle) {
for (let span of subtitle.texts) {
subtitle.tspans.push({ span: span, dy: this.getRelativeY(rowNum, rowCount) })
rowNum++;
}
}
// create ID for gradient element
if (null === this._gradientUUID) {
this._gradientUUID = this.uuid();
}
// Bring it all together
this.svg = {
viewBox: `0 0 ${boxSize} ${boxSize}`,
// Set both width and height to '100%' if it's responsive
width: this.options.responsive ? '100%' : boxSize,
height: this.options.responsive ? '100%' : boxSize,
backgroundCircle: {
cx: centre.x,
cy: centre.y,
r: this.options.radius + this.options.outerStrokeWidth / 2 + this.options.backgroundPadding,
fill: this.options.backgroundColor,
fillOpacity: this.options.backgroundOpacity,
stroke: this.options.backgroundStroke,
strokeWidth: this.options.backgroundStrokeWidth,
},
path: {
// A rx ry x-axis-rotation large-arc-flag sweep-flag x y (https://developer.mozilla.org/en/docs/Web/SVG/Tutorial/Paths#Arcs)
d: `M ${startPoint.x} ${startPoint.y}
A ${this.options.radius} ${this.options.radius} 0 ${largeArcFlag} ${sweepFlag} ${endPoint.x} ${endPoint.y}`,
stroke: this.options.outerStrokeColor,
strokeWidth: this.options.outerStrokeWidth,
strokeLinecap: this.options.outerStrokeLinecap,
fill: 'none'
},
circle: {
cx: centre.x,
cy: centre.y,
r: this.options.radius - this.options.space - this.options.outerStrokeWidth / 2 - this.options.innerStrokeWidth / 2,
fill: 'none',
stroke: this.options.innerStrokeColor,
strokeWidth: this.options.innerStrokeWidth,
},
title: title,
units: units,
subtitle: subtitle,
image: {
x: centre.x - this.options.imageWidth / 2,
y: centre.y - this.options.imageHeight / 2,
src: this.options.imageSrc,
width: this.options.imageWidth,
height: this.options.imageHeight,
},
outerLinearGradient: {
id: 'outer-linear-' + this._gradientUUID,
colorStop1: this.options.outerStrokeColor,
colorStop2: this.options.outerStrokeGradientStopColor === 'transparent' ? '#FFF' : this.options.outerStrokeGradientStopColor,
},
radialGradient: {
id: 'radial-' + this._gradientUUID,
colorStop1: this.options.backgroundColor,
colorStop2: this.options.backgroundGradientStopColor === 'transparent' ? '#FFF' : this.options.backgroundGradientStopColor,
}
};
};
getAnimationParameters = (previousPercent: number, currentPercent: number) => {
const MIN_INTERVAL = 10;
let times: number, step: number, interval: number;
let fromPercent = this.options.startFromZero ? 0 : (previousPercent < 0 ? 0 : previousPercent);
let toPercent = currentPercent < 0 ? 0 : this.min(currentPercent, this.options.maxPercent);
let delta = Math.abs(Math.round(toPercent - fromPercent));
if (delta >= 100) {
// we will finish animation in 100 times
times = 100;
if (!this.options.animateTitle && !this.options.animateSubtitle) {
step = 1;
} else {
// show title or subtitle animation even if the arc is full, we also need to finish it in 100 times.
step = Math.round(delta / times);
}
} else {
// we will finish in as many times as the number of percent.
times = delta;
step = 1;
}
// Get the interval of timer
interval = Math.round(this.options.animationDuration / times);
// Readjust all values if the interval of timer is extremely small.
if (interval < MIN_INTERVAL) {
interval = MIN_INTERVAL;
times = this.options.animationDuration / interval;
if (!this.options.animateTitle && !this.options.animateSubtitle && delta > 100) {
step = Math.round(100 / times);
} else {
step = Math.round(delta / times);
}
}
// step must be greater than 0.
if (step < 1) {
step = 1;
}
return { times: times, step: step, interval: interval };
};
animate = (previousPercent: number, currentPercent: number) => {
if (this._timerSubscription && !this._timerSubscription.closed) {
this._timerSubscription.unsubscribe();
}
let fromPercent = this.options.startFromZero ? 0 : previousPercent;
let toPercent = currentPercent;
let { step: step, interval: interval } = this.getAnimationParameters(fromPercent, toPercent);
let count = fromPercent;
if (fromPercent < toPercent) {
this._timerSubscription = timer(0, interval).subscribe(() => {
count += step;
if (count <= toPercent) {
if (!this.options.animateTitle && !this.options.animateSubtitle && count >= 100) {
this.draw(toPercent);
this._timerSubscription.unsubscribe();
} else {
this.draw(count);
}
} else {
this.draw(toPercent);
this._timerSubscription.unsubscribe();
}
});
} else {
this._timerSubscription = timer(0, interval).subscribe(() => {
count -= step;
if (count >= toPercent) {
if (!this.options.animateTitle && !this.options.animateSubtitle && toPercent >= 100) {
this.draw(toPercent);
this._timerSubscription.unsubscribe();
} else {
this.draw(count);
}
} else {
this.draw(toPercent);
this._timerSubscription.unsubscribe();
}
});
}
};
emitClickEvent(event: MouseEvent): void {
if (this.options.renderOnClick) {
this.animate(0, this.options.percent);
}
if (this.onClick.observers.length > 0) {
this.onClick.emit(event);
}
}
private _timerSubscription: Subscription;
private applyOptions = () => {
// the options of <circle-progress> may change already
for (let name of Object.keys(this.options)) {
if (this.hasOwnProperty(name) && this[name] !== undefined) {
this.options[name] = this[name];
} else if (this.templateOptions && this.templateOptions[name] !== undefined) {
this.options[name] = this.templateOptions[name];
}
}
// make sure key options valid
this.options.radius = Math.abs(+this.options.radius);
this.options.space = +this.options.space;
this.options.percent = +this.options.percent > 0 ? +this.options.percent : 0;
this.options.maxPercent = Math.abs(+this.options.maxPercent);
this.options.animationDuration = Math.abs(this.options.animationDuration);
this.options.outerStrokeWidth = Math.abs(+this.options.outerStrokeWidth);
this.options.innerStrokeWidth = Math.abs(+this.options.innerStrokeWidth);
this.options.backgroundPadding = +this.options.backgroundPadding;
};
private getRelativeY = (rowNum: number, rowCount: number): string => {
// why '-0.18em'? It's a magic number when property 'alignment-baseline' equals 'baseline'. :)
let initialOffset = -0.18, offset = 1;
return (initialOffset + offset * (rowNum - rowCount / 2)).toFixed(2) + 'em';
};
private min = (a: number, b: number) => {
return a < b ? a : b;
};
private max = (a: number, b: number) => {
return a > b ? a : b;
};
private uuid = () => {
// https://www.w3resource.com/javascript-exercises/javascript-math-exercise-23.php
var dt = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (dt + Math.random() * 16) % 16 | 0;
dt = Math.floor(dt / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
}
public isDrawing(): boolean {
return (this._timerSubscription && !this._timerSubscription.closed);
}
public findSvgElement(): void {
if (this.svgElement === null) {
let tags = this.elRef.nativeElement.getElementsByTagName('svg');
if (tags.length > 0) {
this.svgElement = tags[0];
}
}
}
private isElementInViewport(el): Boolean {
// Return false if el has not been created in page.
if (el === null || el === undefined) return false;
// Check if the element is out of view due to a container scrolling
let rect = el.getBoundingClientRect(), parent = el.parentNode, parentRect;
do {
parentRect = parent.getBoundingClientRect();
if (rect.top >= parentRect.bottom) return false;
if (rect.bottom <= parentRect.top) return false;
if (rect.left >= parentRect.right) return false;
if (rect.right <= parentRect.left) return false;
parent = parent.parentNode;
} while (parent != this.document.body);
// Check its within the document viewport
if (rect.top >= (this.window.innerHeight || this.document.documentElement.clientHeight)) return false;
if (rect.bottom <= 0) return false;
if (rect.left >= (this.window.innerWidth || this.document.documentElement.clientWidth)) return false;
if (rect.right <= 0) return false;
return true;
}
checkViewport = () => {
this.findSvgElement();
let previousValue = this.isInViewport;
this.isInViewport = this.isElementInViewport(this.svgElement);
if (previousValue !== this.isInViewport && this.onViewportChanged.observers.length > 0) {
this.ngZone.run(() => {
this.onViewportChanged.emit({ oldValue: previousValue, newValue: this.isInViewport });
});
}
}
onScroll = (event: Event) => {
this.checkViewport();
}
loadEventsForLazyMode = () => {
if (this.options.lazy) {
this.ngZone.runOutsideAngular(() => {
this.document.addEventListener('scroll', this.onScroll, true);
this.window.addEventListener('resize', this.onScroll, true);
});
if (this._viewportChangedSubscriber === null) {
this._viewportChangedSubscriber = this.onViewportChanged.subscribe(({ oldValue, newValue }) => {
newValue ? this.render() : null;
});
}
// svgElement must be created in DOM before being checked.
// Is there a better way to check the existence of svgElemnt?
let _timer = timer(0, 50).subscribe(() => {
this.svgElement === null ? this.checkViewport() : _timer.unsubscribe();
})
}
}
unloadEventsForLazyMode = () => {
// Remove event listeners
this.document.removeEventListener('scroll', this.onScroll, true);
this.window.removeEventListener('resize', this.onScroll, true);
// Unsubscribe onViewportChanged
if (this._viewportChangedSubscriber !== null) {
this._viewportChangedSubscriber.unsubscribe();
this._viewportChangedSubscriber = null;
}
}
ngOnInit() {
this.loadEventsForLazyMode();
}
ngOnDestroy() {
this.unloadEventsForLazyMode();
}
ngOnChanges(changes: SimpleChanges) {
this.render();
if ('lazy' in changes) {
changes.lazy.currentValue ? this.loadEventsForLazyMode() : this.unloadEventsForLazyMode();
}
}
private document: Document;
constructor(
defaultOptions: CircleProgressOptions,
private ngZone: NgZone,
private elRef: ElementRef,
injector: Injector,
) {
this.document = injector.get(DOCUMENT);
this.window = this.document.defaultView;
Object.assign(this.options, defaultOptions);
Object.assign(this.defaultOptions, defaultOptions);
}
} | the_stack |
import {
BytecodeEventHandlerDescriptor,
BytecodeHelpers,
BytecodeNode,
BytecodeOptions,
BytecodeTimelines,
Curve,
HaikuBytecode,
IHaikuClock,
IHaikuComponent,
IHaikuContext,
ParsedValueCluster,
ParsedValueClusterCollection,
TwoPointFiveDimensionalLayoutProperty,
} from './api';
import Config, {DEFAULTS} from './Config';
import HaikuBase, {GLOBAL_LISTENER_KEY} from './HaikuBase';
import HaikuElement from './HaikuElement';
import HaikuHelpers from './HaikuHelpers';
import {ascend, cssMatchOne, cssQueryList, manaFlattenTree, visit} from './HaikuNode';
import HaikuTimeline, {PlaybackFlag, TimeUnit} from './HaikuTimeline';
import ColorUtils from './helpers/ColorUtils';
import consoleErrorOnce from './helpers/consoleErrorOnce';
import {isLiveMode} from './helpers/interactionModes';
import isMutableProperty from './helpers/isMutableProperty';
import {getSortedKeyframes} from './helpers/KeyframeUtils';
import {synchronizePathStructure} from './helpers/PathUtils';
import SVGPoints from './helpers/SVGPoints';
import Layout3D from './Layout3D';
import {
MigrationOptions,
runMigrationsPostPhase,
runMigrationsPrePhase,
} from './Migration';
import enhance from './reflection/enhance';
import functionToRFO, {RFO} from './reflection/functionToRFO';
import StateTransitionManager, {StateTransitionParameters, StateValues} from './StateTransitionManager';
import {calculateValue} from './Transitions';
import assign from './vendor/assign';
import invert from './vendor/gl-mat4/invert';
import {CurveSpec} from './vendor/svg-points/types';
const FUNCTION = 'function';
const KEYFRAME_ZERO = 0;
const OBJECT = 'object';
const MAX_INT = 2147483646;
const SCOPE_STRATA = {div: 'div', svg: 'svg'};
const CDN_ROOT_STR = 'HAIKU|CDN|PROJECT|ROOT'.split('|').join('_'); // Split to avoid server-side munging
// HACK: Required until DOM subtree-hydration race is fixed
const ALWAYS_UPDATED_PROPERTIES = {'controlFlow.placeholder': true};
export interface IComputedValue {
computedValue: any;
didValueChangeSinceLastRequest: boolean;
didValueOriginateFromExplicitKeyframeDefinition: boolean;
}
const parseD = (value: string|CurveSpec[]): CurveSpec[] => {
// in case of d="" for any reason, don't try to expand this otherwise this will choke
// #TODO: arguably we should preprocess SVGs before things get this far; try svgo?
if (!value || value.length === 0) {
return [];
}
// Allow points to return an array for convenience, and let downstream marshal it
if (Array.isArray(value)) {
return value;
}
return SVGPoints.pathToPoints(value);
};
const generateD = (value: string|CurveSpec[]): string => {
if (typeof value === 'string') {
return value;
}
return SVGPoints.pointsToPath(value);
};
const parseColor = (value) => {
return ColorUtils.parseString(value);
};
const generateColor = (value) => {
return ColorUtils.generateString(value);
};
const parsePoints = (value) => {
if (Array.isArray(value)) {
return value;
}
return SVGPoints.polyPointsStringToPoints(value);
};
const generatePoints = (value) => {
if (typeof value === 'string') {
return value;
}
return SVGPoints.pointsToPolyString(value);
};
const isFunction = (value) => {
return typeof value === FUNCTION;
};
const INJECTABLES: any = {};
declare var window: any;
const pkg = require('./../package.json');
export const VERSION = pkg.version;
const STRING_TYPE = 'string';
const OBJECT_TYPE = 'object';
const HAIKU_ID_ATTRIBUTE = 'haiku-id';
const DEFAULT_TIMELINE_NAME = 'Default';
const CSS_QUERY_MAPPING = {
name: 'elementName',
attributes: 'attributes',
children: 'children',
};
/**
* An interface for a "hot component" to patch into the renderer.
*
* Hot components are intended to be applied during hot editing when an immutable-looking thing happens to mutate
* without marking the owner HaikuComponent instance for a full flush render.
*/
export interface HotComponent {
timelineName: string;
selector: string;
propertyNames: string[];
}
export interface ClearCacheOptions {
clearStates?: boolean;
}
// tslint:disable:variable-name function-name
export default class HaikuComponent extends HaikuElement implements IHaikuComponent {
isDeactivated;
isSleeping;
private mutableTimelines: BytecodeTimelines;
private parsedValueClusters: ParsedValueClusterCollection = {};
_states;
bytecode: HaikuBytecode;
/**
* @deprecated
*/
_bytecode;
config;
container;
context: IHaikuContext;
CORE_VERSION;
doAlwaysFlush;
doesNeedFullFlush;
doPreserve3d;
guests: {[haikuId: string]: HaikuComponent};
helpers;
lastHoveredElement: HaikuElement;
hooks;
host: HaikuComponent;
playback;
PLAYER_VERSION;
registeredEventHandlers;
state;
stateTransitionManager: StateTransitionManager;
needsExpand = true;
patches: BytecodeNode[] = [];
constructor (
bytecode: HaikuBytecode,
context: IHaikuContext,
host: HaikuComponent,
config: BytecodeOptions,
container,
) {
super();
if (!bytecode.template) {
console.warn('[haiku core] adding missing template object');
bytecode.template = {elementName: 'div', attributes: {}, children: []};
}
if (!bytecode.timelines) {
console.warn('[haiku core] adding missing timelines object');
bytecode.timelines = {};
}
if (!bytecode.timelines[DEFAULT_TIMELINE_NAME]) {
console.warn('[haiku core] adding missing default timeline');
bytecode.timelines[DEFAULT_TIMELINE_NAME] = {};
}
if (!context) {
throw new Error('Component requires a context');
}
if (!config) {
throw new Error('Config options required');
}
if (!config.seed) {
throw new Error('Seed value must be provided');
}
this.PLAYER_VERSION = VERSION; // #LEGACY
this.CORE_VERSION = VERSION;
this.context = context;
this.container = container;
this.host = host;
this.guests = {};
this.bytecode = (config.hotEditingMode)
? bytecode
: clone(bytecode, this); // Important because migrations mutate the bytecode
assertTemplate(this.bytecode.template);
// Allow users to expose methods that can be called in event handlers
if (this.bytecode.methods) {
for (const methodNameGiven in this.bytecode.methods) {
if (!this[methodNameGiven]) {
this[methodNameGiven] = this.bytecode.methods[methodNameGiven].bind(this);
}
}
}
this._states = {}; // Storage for getter/setter actions in userland logic
this.state = {}; // Public accessor object, e.g. this.state.foo = 1
// Instantiate StateTransitions. Responsible to store and execute any state transition.
this.stateTransitionManager = new StateTransitionManager(this);
this.hooks = {};
this.helpers = Object.assign({}, this.bytecode.helpers, {
data: {},
});
// `assignConfig` calls bindStates because our incoming config, which
// could occur at any point during runtime, e.g. in React, may need to update internal states, etc.
// It also may populate hooks and helpers if passed in via configuration.
this.assignConfig(config);
// Flag used internally to determine whether we need to re-render the full tree or can survive by just patching
this.doesNeedFullFlush = false;
// If true, will continually flush the entire tree until explicitly set to false again
this.doAlwaysFlush = false;
// If true, the component will assign 3D-preservation setting if one hasn't been set explicitly.
// If config.preserve3d is 'auto', the migration pre-phase will try to detect whether 3d is needed.
this.doPreserve3d = (this.config.preserve3d === true) ? true : false;
// Dictionary of event handler names to handler functions; used to efficiently manage multiple subscriptions
this.registeredEventHandlers = {};
// The last HaikuElement in this scope to be hovered; used to help manage hover/unhover
this.lastHoveredElement = null;
// Flag to determine whether this component should continue doing any work
this.isDeactivated = false;
// Flag to indicate whether we are sleeping, an ephemeral condition where no rendering occurs
this.isSleeping = false;
this.helpers = {
data: {},
};
const helpers = Object.assign({}, HaikuHelpers.helpers, this.getHelpers());
for (const helperName in helpers) {
this.helpers[helperName] = helpers[helperName];
}
this.helpers.now = () => {
if (this.isLiveMode()) {
return (this.config.timestamp || 1) + (this.helpers.data.lastTimelineTime || 1);
}
return 1;
};
this.helpers.rand = () => {
if (this.isLiveMode()) {
const scopeKey = [
this.helpers.data.lastTimelineName,
this.helpers.data.lastTimelineTime,
this.helpers.data.lastPropertyName,
this.helpers.data.lastFlexId,
].join('|');
const randKey = `${this.config.seed}@${scopeKey}`;
const keyInt = stringToInt(randKey);
const outFloat = ((keyInt + 1) % MAX_INT) / MAX_INT;
return outFloat;
}
return 1;
};
this.helpers.find = (selector) => {
return this.querySelectorAll(selector);
};
const migrationOptions: MigrationOptions = {
attrsHyphToCamel: ATTRS_HYPH_TO_CAMEL,
// During editing, we handle mutations directly in the app.
mutations: config.hotEditingMode ? undefined : {
// Random seed for adding instance uniqueness to ids at runtime.
referenceUniqueness: (config.hotEditingMode)
? undefined // During editing, Haiku.app pads ids unless this is undefined
: Math.random().toString(36).slice(2),
haikuRoot: this.getProjectRootPathWithTerminatingSlash(),
},
};
try {
runMigrationsPrePhase(this, migrationOptions);
} catch (exception) {
console.warn('[haiku core] caught error during migration pre-phase', exception);
}
// Ensure full tree is are properly set up and all render nodes are connected to their models
this.render({...this.config});
try {
// If the bytecode we got happens to be in an outdated format, we automatically update it to the latest.
runMigrationsPostPhase(
this,
migrationOptions,
VERSION,
);
} catch (exception) {
console.warn('[haiku core] caught error during migration post-phase', exception);
}
this.hydrateMutableTimelines();
if (!this.host) {
this.routeEventToHandlerAndEmit(GLOBAL_LISTENER_KEY, 'component:did-initialize', [this]);
} else {
this.routeEventToHandlerAndEmitWithoutBubbling(GLOBAL_LISTENER_KEY, 'component:did-initialize', [this]);
}
// #FIXME: some handlers may still reference `_bytecode` directly.
this._bytecode = this.bytecode;
}
/**
* @description Track elements that are at the horizon of what we want to render, i.e., a list of
* virtual elements that we don't want to make any updates lower than in the tree.
*/
markHorizonElement (virtualElement) {
if (virtualElement && virtualElement.attributes) {
virtualElement.__horizon = true;
}
}
/**
* @description Returns true/false whether this element is one that we don't want to make any
* updates further down its tree.
*/
isHorizonElement (virtualElement): boolean {
if (virtualElement && virtualElement.attributes) {
return virtualElement.__horizon;
}
return false;
}
isLiveMode (): boolean {
return isLiveMode(this.config.interactionMode);
}
isEditMode (): boolean {
return !this.isLiveMode();
}
registerGuest (subcomponent: HaikuComponent) {
this.guests[subcomponent.getId()] = subcomponent;
}
visitGuestHierarchy (visitor: Function) {
visitor(this, this.$id, this.host);
for (const $id in this.guests) {
this.guests[$id].visitGuestHierarchy(visitor);
}
}
visitGuests (visitor: Function) {
for (const $id in this.guests) {
visitor(this.guests[$id], $id);
}
}
// If the component needs to remount itself for some reason, make sure we fire the right events
callRemount (incomingConfig, skipMarkForFullFlush = false) {
this.visitGuestHierarchy((guest) => {
if (guest === this) {
guest.routeEventToHandlerAndEmit(GLOBAL_LISTENER_KEY, 'component:will-mount', [guest]);
} else {
guest.routeEventToHandlerAndEmitWithoutBubbling(GLOBAL_LISTENER_KEY, 'component:will-mount', [guest]);
}
});
// Note!: Only update config if we actually got incoming options!
if (incomingConfig) {
this.assignConfig(incomingConfig);
}
if (!skipMarkForFullFlush) {
this.markForFullFlush();
this.clearCaches(null);
}
// If autoplay is not wanted, stop the all timelines immediately after we've mounted
// (We have to mount first so that the component displays, but then pause it at that state.)
// If you don't want the component to show up at all, use options.automount=false.
const timelineInstances = this.getTimelines();
for (const timelineName in timelineInstances) {
const timelineInstance = timelineInstances[timelineName];
if (this.config.autoplay) {
if (timelineName === DEFAULT_TIMELINE_NAME) {
// Assume we want to start the timeline from the beginning upon remount.
// NOTE:
// timeline.play() will normally trigger markForFullFlush because it assumes we need to render
// from the get-go. However, in case of a callRemount, we might not want to do that since it can be kind of
// like running the first frame twice. So we pass the option into play so it can conditionally skip the
// markForFullFlush step.
if (!timelineInstance.isPaused()) {
timelineInstance.play({skipMarkForFullFlush});
}
}
} else {
timelineInstance.pause();
}
}
this.context.contextMount();
this.visitGuestHierarchy((guest) => {
if (guest === this) {
guest.routeEventToHandlerAndEmit(GLOBAL_LISTENER_KEY, 'component:did-mount', [guest]);
} else {
guest.routeEventToHandlerAndEmitWithoutBubbling(GLOBAL_LISTENER_KEY, 'component:did-mount', [guest]);
}
});
}
destroy () {
super.destroy();
// Destroy all timelines we host.
const timelineInstances = this.getTimelines();
for (const timelineName in timelineInstances) {
const timelineInstance = timelineInstances[timelineName];
timelineInstance.destroy();
}
this.visitGuestHierarchy((component) => {
// Clean up HaikuComponent dependents.
// TODO: is this step necessary?
if (component !== this) {
component.destroy();
}
});
this.visitDescendants((child) => {
// Clean up HaikuElement dependents.
child.destroy();
});
}
callUnmount () {
// Since we're unmounting, pause all animations to avoid unnecessary calc while detached
const timelineInstances = this.getTimelines();
for (const timelineName in timelineInstances) {
const timelineInstance = timelineInstances[timelineName];
timelineInstance.pause();
}
this.context.contextUnmount();
this.visitGuestHierarchy((guest) => {
if (guest === this) {
guest.routeEventToHandlerAndEmit(GLOBAL_LISTENER_KEY, 'component:will-unmount', [guest]);
} else {
guest.routeEventToHandlerAndEmitWithoutBubbling(GLOBAL_LISTENER_KEY, 'component:will-unmount', [guest]);
}
});
}
assignConfig (incomingConfig) {
this.config = Config.build(this.config || {}, incomingConfig || {});
// Don't assign the context config if we're a guest component;
// assume only the top-level component should have this power
if (this.host) {
// Don't forget to update the configuration values shared by the context,
// but skip component assignment so we don't end up in an infinite loop
this.context.assignConfig(this.config, {skipComponentAssign: true});
}
const timelines = this.getTimelines();
for (const name in timelines) {
const timeline = timelines[name];
timeline.assignOptions(this.config);
}
this.bindStates();
assign(this.hooks, this.config.hooks);
assign(this.helpers, this.config.helpers);
assign(this.bytecode.timelines, this.config.timelines);
return this;
}
set (key, value) {
this.callHook('state:change', {state: key, from: this.state[key], to: value});
this.state[key] = value;
return this;
}
get (key) {
return this.state[key];
}
setState (states: StateValues, transitionParameter?: StateTransitionParameters) {
// Do not set any state if invalid
if (!states || typeof states !== 'object') {
return this;
}
// Set states is delegated to stateTransitionManager
this.stateTransitionManager.setState(states, transitionParameter);
return this;
}
getStates () {
return this.state;
}
clearCaches (options: ClearCacheOptions = {}) {
// HaikuBase implements a general-purpose caching mechanism which we also call here
this.cacheClear();
this.needsExpand = true;
// Don't forget to repopulate the states with originals when we clear cache
if (options.clearStates) {
this.clearStates();
}
this.hydrateMutableTimelines();
this.parsedValueClusters = {};
// Our managed timeline instances may have their own privately cached properties
const timelines = this.fetchTimelines();
for (const timelineName in timelines) {
timelines[timelineName].cacheClear();
}
}
cacheNodeWithSelectorKey (node) {
if (!node || typeof node !== 'object') {
return;
}
if (node.attributes && node.attributes[HAIKU_ID_ATTRIBUTE]) {
const selector = `haiku:${node.attributes[HAIKU_ID_ATTRIBUTE]}`;
const key = this.nodesCacheKey(selector);
const collection = this.cacheGet(key) || [];
if (collection.indexOf(node) === -1) {
collection.push(node);
}
this.cacheSet(key, collection);
}
}
clearStates () {
this._states = {};
this.bindStates();
}
getClock (): IHaikuClock {
return this.context.clock;
}
getTemplate (): any {
return this.bytecode.template;
}
getHelpers (): BytecodeHelpers {
return this.bytecode.helpers;
}
getTimelines () {
return this.cacheFetch('getTimelines', () => {
return this.fetchTimelines();
});
}
fetchTimelines () {
const names = Object.keys(this.bytecode.timelines);
for (let i = 0; i < names.length; i++) {
const name = names[i];
if (!name) {
continue;
}
const existing = HaikuTimeline.where({
name,
component: this,
})[0];
if (!existing) {
HaikuTimeline.create(
this,
name,
this.config,
);
}
}
const out = {};
const timelines = HaikuTimeline.where({component: this});
for (let j = 0; j < timelines.length; j++) {
const timeline = timelines[j];
out[timeline.getName()] = timeline;
}
return out;
}
getTimeline (name): HaikuTimeline {
return this.getTimelines()[name];
}
fetchTimeline (name, descriptor): HaikuTimeline {
const found = this.getTimeline(name);
if (found) {
return found;
}
return HaikuTimeline.create(this, name, this.config);
}
getDefaultTimeline (): HaikuTimeline {
const timelines = this.getTimelines();
return timelines[DEFAULT_TIMELINE_NAME];
}
stopAllTimelines () {
const timelines = this.getTimelines();
for (const name in timelines) {
this.stopTimeline(name);
}
}
startAllTimelines () {
const timelines = this.getTimelines();
for (const name in timelines) {
this.startTimeline(name);
}
}
startTimeline (timelineName) {
const descriptor = this.getTimelineDescriptor(timelineName);
const existing = this.fetchTimeline(timelineName, descriptor);
if (existing) {
existing.start();
}
}
stopTimeline (timelineName) {
const descriptor = this.getTimelineDescriptor(timelineName);
const existing = this.fetchTimeline(timelineName, descriptor);
if (existing) {
existing.stop();
}
}
/**
* @description Convenience alias for HaikuTimeline#gotoAndPlay
*/
gotoAndPlay (amount: number, unit: TimeUnit = TimeUnit.Frame) {
this.getDefaultTimeline().gotoAndPlay(amount, unit);
}
/**
* @description Convenience alias for HaikuTimeline#gotoAndStop
*/
gotoAndStop (amount: number, unit: TimeUnit = TimeUnit.Frame) {
this.getDefaultTimeline().gotoAndStop(amount, unit);
}
/**
* @description Convenience alias for HaikuTimeline#pause
*/
pause () {
this.getDefaultTimeline().pause();
}
/**
* @description Convenience alias for HaikuTimeline#stop
*/
stop () {
this.getDefaultTimeline().stop();
}
/**
* @description Convenience alias for HaikuTimeline#seek
*/
seek (amount: number, unit: TimeUnit = TimeUnit.Frame) {
this.getDefaultTimeline().seek(amount, unit);
}
/**
* @description Convenience alias for HaikuTimeline#start
*/
start () {
this.getDefaultTimeline().start();
}
/**
* @description Convenience alias for HaikuTimeline#play
*/
play (options: any = {}) {
this.getDefaultTimeline().play();
}
getTimelineDescriptor (timelineName: string) {
return this.bytecode.timelines[timelineName];
}
getInjectables (): any {
const injectables = {};
assign(injectables, this.getSummonablesSchema());
// Local states get precedence over global summonables, so assign them last
for (const key in this._states) {
let type = this._states[key] && this._states[key].type;
if (!type) {
type = typeof this._states[key];
}
injectables[key] = type;
}
return injectables;
}
/**
* @method _deactivate
* @description When hot-reloading a component during editing, this can be used to
* ensure that this component doesn't keep updating after its replacement is loaded.
*/
deactivate () {
this.isDeactivated = true;
}
activate () {
this.isDeactivated = false;
}
sleepOn () {
this.isSleeping = true;
}
sleepOff () {
this.isSleeping = false;
}
/**
* @method dump
* @description Dump serializable info about this object
*/
dump () {
const metadata = this.getBytecodeMetadata();
return `${metadata.relpath}:${this.getComponentId()}`;
}
getBytecodeMetadata () {
return this.bytecode.metadata;
}
getBytecodeRelpath (): string {
const metadata = this.getBytecodeMetadata();
return metadata && metadata.relpath;
}
getBytecodeProject (): string {
const metadata = this.getBytecodeMetadata();
return metadata && metadata.project;
}
getBytecodeOrganization (): string {
const metadata = this.getBytecodeMetadata();
return metadata && metadata.organization;
}
getAddressableProperties (out = {}) {
if (!this.bytecode.states) {
return out;
}
for (const name in this.bytecode.states) {
const state = this.bytecode.states[name];
out[name] = {
name,
type: 'state', // As opposed to a 'native' property like fill-rule
prefix: name, // States aren't named like rotation.x, so there is no 'prefix'
suffix: undefined, // States aren't named like rotation.x, so there is no 'suffix'
fallback: state.value, // Weird nomenclature: In Haiku.app, fallback means the default value
typedef: state.type, // Weird nomenclature: In Haiku.app, typedef just means the runtime type
mock: state.mock, // Just in case needed by someone
target: this, // Used for tracking convenience; may also be an 'element'; do not remove
value: () => { // Lazy because this may change over time and we don't want to require re-query
return this.state[name]; // The current live value of this state as seen by the app
},
};
}
return out;
}
bindStates () {
const allStates = assign({}, this.bytecode.states, this.config.states);
for (const stateSpecName in allStates) {
const stateSpec = allStates[stateSpecName];
// 'null' is the signal for an empty prop, not undefined.
if (!stateSpec || stateSpec.value === undefined) {
console.error(
'Property `' +
stateSpecName +
'` cannot be undefined; use null for empty states',
);
continue;
}
if (!this._states.hasOwnProperty(stateSpecName) || this.config.states.hasOwnProperty(stateSpecName)) {
this._states[stateSpecName] = stateSpec.value;
this.defineSettableState(stateSpec, stateSpecName);
}
}
}
defineSettableState (
stateSpec,
stateSpecName: string,
) {
// Note: We define the getter/setter on the object itself, but the storage occurs on the pass-in statesTargetObject
Object.defineProperty(this.state, stateSpecName, {
configurable: true,
enumerable: true,
get: () => {
return this._states[stateSpecName];
},
set: (inputValue) => {
if (stateSpec.setter) {
// Important: We call the setter with a binding of the component, so it can access methods on `this`
this._states[stateSpecName] = stateSpec.setter.call(
this,
inputValue,
);
} else {
this._states[stateSpecName] = inputValue;
}
if (!this.isDeactivated) {
this.emit('state:set', stateSpecName, this._states[stateSpecName]);
}
return this._states[stateSpecName];
},
});
}
allEventHandlers (): any {
return assign(
{},
this.bytecode.eventHandlers,
this.config.eventHandlers,
);
}
eachEventHandler (
iteratee: (eventSelector: string, eventName: string, descriptor: BytecodeEventHandlerDescriptor) => void,
) {
const eventHandlers = this.allEventHandlers();
for (const eventSelector in eventHandlers) {
for (const eventName in eventHandlers[eventSelector]) {
const descriptor = eventHandlers[eventSelector][eventName];
if (!descriptor || !descriptor.handler) {
continue;
}
iteratee(
eventSelector,
eventName,
descriptor,
);
}
}
}
routeEventToHandler (
eventSelectorGiven: string,
eventNameGiven: string,
eventArgs: any,
) {
if (this.isDeactivated) {
return;
}
this.eachEventHandler((eventSelector, eventName, {handler}) => {
if (eventNameGiven === eventName) {
if (
eventSelectorGiven === eventSelector ||
eventSelectorGiven === GLOBAL_LISTENER_KEY
) {
this.callEventHandler(eventSelector, eventName, handler, eventArgs);
return;
}
}
});
}
setHook (hookName: string, hookFn: Function) {
this.hooks[hookName] = hookFn;
}
callHook (hookName: string, ...args) {
if (typeof this.hooks[hookName] === 'function') {
this.hooks[hookName](...args);
}
}
callEventHandler (eventsSelector: string, eventName: string, handler: Function, eventArgs: any): any {
// Only fire the event listeners if the component is in 'live' interaction mode,
// i.e., not currently being edited inside the Haiku authoring environment
// However, some components rely on specific event hooks firing in Edit mode, too — they can
// whitelist their "edit mode" event names through `options`
if (!this.isLiveMode() &&
!(this.bytecode.options &&
this.bytecode.options.editModeEvents &&
this.bytecode.options.editModeEvents[eventName])) {
return;
}
this.callHook('action:before', this, eventName, eventsSelector, eventArgs);
try {
handler.apply(this, [this].concat(eventArgs));
} catch (exception) {
consoleErrorOnce(exception);
}
this.callHook('action:after', this, eventName, eventsSelector, eventArgs);
}
routeEventToHandlerAndEmit (
eventSelectorGiven: string,
eventNameGiven: string,
eventArgs: any,
) {
if (this.isDeactivated) {
return;
}
this.routeEventToHandler(eventSelectorGiven, eventNameGiven, eventArgs);
this.emit(eventNameGiven, ...eventArgs);
}
routeEventToHandlerAndEmitWithoutBubbling (
eventSelectorGiven: string,
eventNameGiven: string,
eventArgs: any,
) {
if (this.isDeactivated) {
return;
}
this.routeEventToHandler(eventSelectorGiven, eventNameGiven, eventArgs);
this.emitWithoutBubbling(eventNameGiven, ...eventArgs);
}
routeEventToHandlerAndEmitWithoutBubblingAndWithoutGlobalHandlers (
eventSelectorGiven: string,
eventNameGiven: string,
eventArgs: any,
) {
if (this.isDeactivated) {
return;
}
this.routeEventToHandler(eventSelectorGiven, eventNameGiven, eventArgs);
this.emitToListeners(eventNameGiven, eventArgs);
this.emitToGenericListeners(eventNameGiven, eventArgs);
}
/**
* @description A more expressive form of `emit` that allows the user to route
* events to specific collections of elements/components in the tree using labels,
* selectors, etc. This method is provided in lieu of providing an individual method
* for every possible topology.
*/
send (route: string, name: string, ...args) {
// Send to parent
if (
route === 'emit' ||
route === 'up' ||
route === 'parent' ||
route === '<' // Cute: '>' is the opposite of CSS children selector '<'
) {
this.emit(name, ...args);
return;
}
// Send to children
if (
route === 'down' ||
route === 'children' ||
route === '>' // CSS children selector
) {
this.visitGuests((guest) => {
guest.emitWithoutBubbling(name, ...args);
});
return;
}
// Send to siblings
if (
route === 'sideways' ||
route === 'siblings' ||
route === '~' // CSS sibling selector
) {
if (this.host) {
this.host.visitGuests((guest) => {
if (guest !== this) {
guest.emitWithoutBubbling(name, ...args);
}
});
}
return;
}
// Send to everyone
if (
route === '*'
) {
this.top.visitGuestHierarchy((guest) => {
if (guest !== this) {
guest.emitWithoutBubbling(name, ...args);
}
});
}
}
emitToAncestors (name: string, ...args) {
if (this.host) {
// 1. Emit to listeners on the "wrapper" div
this.host.routeEventToHandler(
`haiku:${getNodeCompositeId(this.parentNode)}`,
name,
[this].concat(args),
);
// 2. For convenience, emit to listeners on the root component of the hosts
this.host.routeEventToHandler(
`haiku:${getNodeCompositeId(this.host)}`,
name,
[this].concat(args),
);
}
}
emitWithoutBubbling (key: string, ...args) {
this.routeEventToHandler(GLOBAL_LISTENER_KEY, key, args);
this.emitToListeners(key, args);
this.emitToGenericListeners(key, args);
}
markForFullFlush () {
this.doesNeedFullFlush = true;
}
unmarkForFullFlush () {
this.doesNeedFullFlush = false;
}
shouldPerformFullFlush () {
return this.doesNeedFullFlush || this.doAlwaysFlush;
}
private expandIfNeeded () {
if (this.needsExpand) {
expandNode(
this.bytecode.template,
this.container,
);
this.needsExpand = false;
}
}
performFullFlushRenderWithRenderer (renderer, options: any = {}) {
this.context.getContainer(true); // Force recalc of container
// Since we will produce a full tree, we don't need a further full flush.
this.unmarkForFullFlush();
this.needsExpand = true;
this.render(options);
// Untyped code paths downstream depend on the output of this method
return renderer.render(
this.container,
this.bytecode.template,
this,
);
}
performPatchRenderWithRenderer (renderer, options: any = {}, skipCache: boolean) {
if (renderer.shouldCreateContainer) {
this.context.getContainer(true); // Force recalc of container
}
const patches = this.patch(options, skipCache);
renderer.patch(
this,
patches,
);
for (const $id in this.guests) {
const guest = this.guests[$id];
if (guest.shouldPerformFullFlush() && guest.target) {
guest.performFullFlushRenderWithRenderer(
renderer,
options,
);
} else {
guest.performPatchRenderWithRenderer(
renderer,
options,
skipCache,
);
}
}
}
render (options: any = {}) {
// We register ourselves with our host here because render is guaranteed to be called
// both in our constructor and in the case that we were deactivated/reactivated.
// This must run before the isDeactivated check since we may use the registry to activate later.
if (this.host) {
this.host.registerGuest(this);
}
if (this.isDeactivated) {
// If deactivated, pretend like there is nothing to render
return;
}
this.clearCaches();
HaikuElement.findOrCreateByNode(this.container);
if (!this.container.__memory.subcomponent) {
// A semantically different thing than .subcomponent/.instance
this.container.__memory.containee = this;
}
hydrateNode(
this.bytecode.template, // node
this.container, // parent
this, // instance (component)
this.context,
this.host,
'div', // scope (the default is a div)
options,
true, // doConnectInstanceToNode
);
this.applyLocalBehaviors(
false, // isPatchOperation
false, // skipCache
);
if (this.context.renderer.mount) {
this.eachEventHandler((eventSelector, eventName) => {
const registrationKey = `${eventSelector}:${eventName}`;
if (this.registeredEventHandlers[registrationKey]) {
return;
}
this.registeredEventHandlers[registrationKey] = true;
this.context.renderer.mountEventListener(this, eventSelector, eventName, (...args) => {
this.routeEventToHandlerAndEmit(eventSelector, eventName, args);
});
});
}
this.applyGlobalBehaviors(options);
// But also note we need to call subcomponent renders *after* our own behaviors,
// because we need the parent-to-child states to be set prior to this render call,
// otherwise the changes they produce won't be available for this render frame.
for (const $id in this.guests) {
this.guests[$id].render({
...this.guests[$id].config,
...Config.buildChildSafeConfig(options),
});
}
this.expandIfNeeded();
return this.bytecode.template;
}
patch (options: any = {}, skipCache = false) {
if (this.isDeactivated) {
// If deactivated, pretend like there is nothing to render
return {};
}
this.applyLocalBehaviors(
true, // isPatchOperation
skipCache,
);
this.applyGlobalBehaviors(options);
const patches = {};
this.expandIfNeeded();
for (let i = 0; i < this.patches.length; i++) {
const node = this.patches[i];
computeAndApplyLayout(node, node.__memory.parent);
patches[getNodeCompositeId(node)] = node;
}
this.patches = [];
return patches;
}
applyGlobalBehaviors (options: any = {}) {
if (!this.host && options.sizing) {
const didSizingChange = computeAndApplyPresetSizing(
this.bytecode.template,
this.container,
options.sizing,
);
if (didSizingChange) {
this.patches.push(this.bytecode.template);
}
}
}
applyLocalBehaviors (
isPatchOperation,
skipCache = false,
) {
const globalClockTime = this.context.clock.getExplicitTime();
const manaTree = this.manaTreeCached();
for (const timelineName in this.bytecode.timelines) {
const timelineInstance = this.getTimeline(timelineName);
timelineInstance.executePreUpdateHooks(globalClockTime);
const timelineTime = timelineInstance.getTime(); // Bounded time
const timelineDescriptor = this.bytecode.timelines[timelineName];
let mutableTimelineDescriptor = isPatchOperation
? this.mutableTimelines[timelineName]
: timelineDescriptor;
if (!mutableTimelineDescriptor) {
mutableTimelineDescriptor = {};
}
for (const behaviorSelector in mutableTimelineDescriptor) {
const matchingElementsForBehavior = this.findMatchingNodesByCSSSelector(manaTree, behaviorSelector);
if (!matchingElementsForBehavior || matchingElementsForBehavior.length < 1) {
continue;
}
const propertiesGroup = mutableTimelineDescriptor[behaviorSelector];
if (!propertiesGroup) {
continue;
}
// This is our opportunity to group property operations that need to be in order
const propertyOperations = collatePropertyGroup(propertiesGroup);
for (let i = 0; i < matchingElementsForBehavior.length; i++) {
const matchingElement = matchingElementsForBehavior[i];
const compositeId = getNodeCompositeId(matchingElement);
for (let j = 0; j < propertyOperations.length; j++) {
const propertyGroup = propertyOperations[j];
for (const propertyName in propertyGroup) {
const keyframeCluster = propertyGroup[propertyName];
const grabbedValue = this.grabValue(
timelineName,
compositeId,
matchingElement,
propertyName,
keyframeCluster,
timelineTime,
isPatchOperation,
skipCache,
);
const {
computedValue,
didValueChangeSinceLastRequest,
didValueOriginateFromExplicitKeyframeDefinition,
} = grabbedValue;
if (computedValue === undefined) {
continue;
}
// We always apply the property if...
if (
// - This is a full render
!isPatchOperation ||
// - The value in question has changed
didValueChangeSinceLastRequest ||
// - The value is in the whitelist of always-updated properties
ALWAYS_UPDATED_PROPERTIES[propertyName] ||
(
// - The value was explicitly defined as a keyframe and...
didValueOriginateFromExplicitKeyframeDefinition && (
// - We haven't yet reached the end
(timelineTime < timelineInstance.getMaxTime()) ||
// - The timeline is looping (we won't be hanging on the final keyframe)
timelineInstance.isLooping() ||
// - We just reached the final keyframe (but haven't already visited it)
timelineInstance.getLastFrame() !== timelineInstance.getBoundedFrame()
)
)
) {
this.applyPropertyToNode(
matchingElement,
propertyName,
computedValue,
timelineInstance,
);
if (isPatchOperation) {
this.patches.push(matchingElement);
}
}
}
}
}
}
timelineInstance.executePostUpdateHooks(globalClockTime);
}
}
getProjectRootPathWithTerminatingSlash (): string {
const metadata = this.getBytecodeMetadata();
// If root is set and is not precisely this known magic string,
// assume the root actually defines a root path somewhere on the web we can resolve to.
if (metadata && metadata.root && metadata.root !== CDN_ROOT_STR) {
return metadata.root;
}
// Try to use a locally defined folder (i.e. during editing in Haiku),
// or fallback to a local path and hope we resolve to something meaningful.
return this.config.folder || (metadata && metadata.folder) || './';
}
applyPropertyToNode (
node,
name: string,
value,
timeline: HaikuTimeline,
) {
const sender = (node.__memory.instance) ? node.__memory.instance : this; // Who sent the command
const receiver = node.__memory.subcomponent;
const type = (receiver && receiver.tagName) || node.elementName;
const addressables = receiver && receiver.getAddressableProperties();
const addressee = addressables && addressables[name] !== undefined && receiver;
if (addressee) {
// Note: Even though we apply the value to addressables of the subcomponent,
// we still proceed with application of properties directly to the wrapper.
// This is as a convenience, so that if a subcomponent wants to handle any property
// applied to its wrapper than it can do so, e.g. sizeAbsolute.x/sizeAbsolute.y.
addressee.set(name, value);
}
const vanity = getVanity(type, name);
if (vanity) {
return vanity(
name,
node,
value,
this.context,
timeline,
receiver,
sender,
);
}
const parts = name.split('.');
if (parts[0] === 'style' && parts[1]) {
return setStyle(parts[1], node, value);
}
return setAttribute(name, node, value);
}
findElementsByHaikuId (componentId) {
return this.findMatchingNodesByCSSSelector(this.manaTreeCached(), `haiku:${componentId}`);
}
nodesCacheKey (selector: string) {
return 'nodes:' + selector;
}
private manaTreeCached () {
return this.cacheFetch('flatManaTree', () => manaFlattenTree(this.bytecode.template, CSS_QUERY_MAPPING));
}
findMatchingNodesByCSSSelector (manaTree, selector: string) {
const nodes = this.cacheFetch(
this.nodesCacheKey(selector),
() => cssQueryList(manaTree, selector, CSS_QUERY_MAPPING),
);
const out = [];
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
const repeatees = findRespectiveRepeatees(node);
// If the node in question is the descendant of a repeater, we need to find all repeated
// copies of it inside the host repeater. If any repeatees are returned that means the
// element is in fact a repeater, otherwise it is not a repeater, so just use the node.
if (repeatees.length > 0) {
out.push(...repeatees);
} else {
out.push(node);
}
}
return out;
}
private hydrateMutableTimelines () {
this.mutableTimelines = {};
if (this.bytecode.timelines) {
for (const timelineName in this.bytecode.timelines) {
for (const selector in this.bytecode.timelines[timelineName]) {
for (const propertyName in this.bytecode.timelines[timelineName][selector]) {
if (isMutableProperty(this.bytecode.timelines[timelineName][selector][propertyName], propertyName)) {
if (!this.mutableTimelines[timelineName]) {
this.mutableTimelines[timelineName] = {};
}
if (!this.mutableTimelines[timelineName][selector]) {
this.mutableTimelines[timelineName][selector] = {};
}
this.mutableTimelines[timelineName][selector][propertyName] =
this.bytecode.timelines[timelineName][selector][propertyName];
}
}
}
}
}
}
addHotComponent (hotComponent: HotComponent) {
if (
!this.bytecode.timelines ||
!this.bytecode.timelines[hotComponent.timelineName] ||
!this.bytecode.timelines[hotComponent.timelineName][hotComponent.selector]
) {
return;
}
const propertyGroup = this.bytecode.timelines[hotComponent.timelineName][hotComponent.selector];
if (!this.mutableTimelines[hotComponent.timelineName]) {
this.mutableTimelines[hotComponent.timelineName] = {};
}
if (!this.mutableTimelines[hotComponent.timelineName][hotComponent.selector]) {
this.mutableTimelines[hotComponent.timelineName][hotComponent.selector] = {};
}
Object.assign(
this.mutableTimelines[hotComponent.timelineName][hotComponent.selector],
hotComponent.propertyNames.reduce(
(hotProperties, propertyName) => (hotProperties[propertyName] = propertyGroup[propertyName], hotProperties),
{},
),
);
}
controlTime (timelineName: string, timelineTime: number) {
const explicitTime = this.context.clock.getExplicitTime();
const timelineInstances = this.getTimelines();
for (const localTimelineName in timelineInstances) {
if (localTimelineName === timelineName) {
const timelineInstance = timelineInstances[timelineName];
timelineInstance.controlTime(timelineTime, explicitTime);
}
}
for (const $id in this.guests) {
this.guests[$id].controlTime(
timelineName,
0, // For now: Like Flash, freeze all guests at 0 while controlling host
);
}
}
getPropertiesGroup (timelineName: string, flexId: string) {
return (
this.bytecode &&
this.bytecode.timelines &&
this.bytecode.timelines[timelineName] &&
this.bytecode.timelines[timelineName][`haiku:${flexId}`]
);
}
/**
* Execute state transitions.
*/
tickStateTransitions (): void {
this.stateTransitionManager.tickStateTransitions();
}
/**
* Reset states to initial values by using State Transitions. Default to linear
*/
resetStatesToInitialValuesWithTransition (duration: number, curve: Curve = Curve.Linear) {
// Build initial states
const initialStates = assign({}, this.bytecode.states, this.config.states);
for (const key in initialStates) {
initialStates[key] = initialStates[key].value;
}
// Create state transition to initial state values
this.stateTransitionManager.setState(initialStates, {curve, duration});
}
/**
* @description Get the topmost component in the hierarchy.
*/
get top (): HaikuComponent {
if (this.host) {
return this.host.top;
}
return this;
}
getRootComponent () {
if (this.host) {
return this.host.getRootComponent();
}
return this;
}
emitFromRootComponent (eventName: string, attachedObject: any) {
this.getRootComponent().emit(eventName, {
...attachedObject,
componentTitle: this.title, // HaikuElement#get title
});
}
evaluate (expr: string) {
// Make all injectables available within the scope of the function we'll create below,
// so users can freely evaluate an expression like this.evaluate('$user.mouse.x');
try {
// tslint:disable-next-line:no-function-constructor-with-string-args
const fn = new Function(
'$children',
'$clock',
'$component',
'$container',
'$context',
'$core',
'$element',
'$host',
'$if',
'$index',
'$mount',
'$parent',
'$payload',
'$placeholder',
'$repeat',
'$state',
'$timeline',
'$top',
'$tree',
'$user',
'$window',
`return ${expr};\n`,
);
return fn(
this.summon('$children'),
this.summon('$clock'),
this.summon('$component'),
this.summon('$container'),
this.summon('$context'),
this.summon('$core'),
this.summon('$element'),
this.summon('$host'),
this.summon('$if'),
this.summon('$index'),
this.summon('$mount'),
this.summon('$parent'),
this.summon('$payload'),
this.summon('$placeholder'),
this.summon('$repeat'),
this.summon('$state'),
this.summon('$timeline'),
this.summon('$top'),
this.summon('$tree'),
this.summon('$user'),
this.summon('$window'),
);
} catch (exception) {
console.warn(`[haiku core] could not evaluate ${expr}`, exception);
}
}
summon (injectable: string) {
if (INJECTABLES[injectable] && INJECTABLES[injectable].summon) {
const out = {};
INJECTABLES[injectable].summon(
out, // injectees
this, // component
this.bytecode.template, // node
DEFAULT_TIMELINE_NAME, // timeline name
);
return out[injectable];
}
}
evaluateExpression (
fn,
timelineName: string,
flexId: string,
matchingElement,
propertyName: string,
keyframeMs,
keyframeCluster,
) {
enhance(fn, null);
// We'll store the result of this evaluation in this variable
// (so we can cache it in case unexpected subsequent calls)
let evaluation;
if (fn.specification === true) {
// This function is of an unknown kind, so just evaluate it normally without magic dependency injection
evaluation = safeCall(fn, this, this._states);
} else if (!Array.isArray(fn.specification.params)) {
// If for some reason we got a non-array params, just evaluate
evaluation = safeCall(fn, this, this._states);
} else if (fn.specification.params.length < 1) {
// If for some reason we got 0 params, just evaluate it
evaluation = safeCall(fn, this, this._states);
} else {
if (fn.specification.params.length < 1) {
// If the summon isn't in the destructured object format, just evaluate it
evaluation = safeCall(fn, this, this._states);
} else {
const summoneesArray = this.summonSummonables(
fn.specification.params,
timelineName,
flexId,
matchingElement,
propertyName,
keyframeMs,
keyframeCluster,
);
const previousSummoneesArray = this.getPreviousSummonees(timelineName, flexId, propertyName, keyframeMs);
if (areSummoneesDifferent(previousSummoneesArray, summoneesArray)) {
this.cacheSummonees(timelineName, flexId, propertyName, keyframeMs, summoneesArray);
evaluation = safeApply(fn, this, summoneesArray);
} else {
// Since nothing is different, return the previous evaluation
evaluation = this.getPreviousEvaluation(timelineName, flexId, propertyName, keyframeMs);
}
}
}
// If the output is literally `NaN`, that is almost certainly useless and not what the user
// intended. This can happen commonly when editing in Haiku.app and creating dynamic behavior
// based on state payloads whose fields may be missing, especially with controlFlow.repeat.
if (Number.isNaN(evaluation)) {
evaluation = 1;
}
// Same for Infinity; as it's more likely than not that this is a mistake
if (typeof evaluation === 'number' && !isFinite(evaluation)) {
evaluation = 1;
}
// Store the result so we can return it on the next run without re-eval
if (fn.specification && fn.specification !== true) {
this.cacheEvaluation(timelineName, flexId, propertyName, keyframeMs, evaluation);
}
return evaluation;
}
summonSummonables (
paramsArray,
timelineName: string,
flexId: string,
matchingElement,
propertyName: string,
keyframeMs,
keyframeCluster,
) {
const summonablesArray = [];
// Temporary storage, just creating one object here to avoid excessive allocations
const summonStorage = {};
for (let i = 0; i < paramsArray.length; i++) {
const summonsEntry = paramsArray[i];
// We'll store the output of the summons in this var, whether we're dealing with
// a complex nested summonable or a flat one
let summonsOutput;
// In case of a string, we will treat it as the key for the object to summon
if (typeof summonsEntry === 'string') {
// Treat the entry as the key to a known injectable
if (INJECTABLES[summonsEntry]) {
summonStorage[summonsEntry] = undefined; // Clear out the old value before populating with the new one
INJECTABLES[summonsEntry].summon(
summonStorage,
this,
matchingElement,
timelineName,
);
summonsOutput = summonStorage[summonsEntry];
} else {
summonsOutput = this.state[summonsEntry];
}
}
// Whatever the request format was, populate the result in here
if (summonsOutput !== undefined) {
summonablesArray[i] = summonsOutput;
}
}
return summonablesArray;
}
private fetchParsedValueCluster (
timelineName: string,
flexId: string,
matchingElement,
outputName: string,
cluster,
isPatchOperation: boolean,
skipCache: boolean,
): ParsedValueCluster {
const parseeWithKeys = this.getParseeWithKeys(timelineName, flexId, outputName, cluster);
if (!cluster) {
return parseeWithKeys;
}
const skipStableParsees = isPatchOperation && !skipCache;
if (skipStableParsees && this.clusterParseeIsStable(parseeWithKeys)) {
return parseeWithKeys;
}
for (let i = 0; i < parseeWithKeys.keys.length; i++) {
const ms = parseeWithKeys.keys[i];
const descriptor = cluster[ms];
if (
(skipStableParsees && parseeWithKeys.parsee[ms] && !parseeWithKeys.parsee[ms].expression) ||
descriptor === undefined
) {
continue;
}
if (isFunction(descriptor.value)) {
parseeWithKeys.parsee[ms] = {
expression: true,
value: this.evaluateExpression(
descriptor.value,
timelineName,
flexId,
matchingElement,
outputName,
ms,
cluster,
),
};
} else {
parseeWithKeys.parsee[ms] = {
expression: false,
value: descriptor.value,
};
}
if (descriptor.curve) {
parseeWithKeys.parsee[ms].curve = descriptor.curve;
}
}
if (parseeWithKeys.keys.length > 1) {
let parser = this.getParser(outputName);
if (
!parser &&
// tslint:disable-next-line:triple-equals
parseFloat(parseeWithKeys.parsee[parseeWithKeys.keys[0]].value) ==
parseeWithKeys.parsee[parseeWithKeys.keys[0]].value
) {
parser = parseFloat;
}
if (!parser) {
return parseeWithKeys;
}
for (let j = 0; j < parseeWithKeys.keys.length; j++) {
const ms2 = parseeWithKeys.keys[j];
parseeWithKeys.parsee[ms2].value = parser(parseeWithKeys.parsee[ms2].value);
}
if (outputName === 'd') {
synchronizePathStructure(...parseeWithKeys.keys.map((ms) => parseeWithKeys.parsee[ms].value));
}
}
return parseeWithKeys;
}
generateFinalValueFromParsedValue (
timelineName,
flexId,
matchingElement,
outputName,
computedValue,
) {
if (computedValue === undefined) {
return;
}
const generator = this.getGenerator(outputName);
if (generator) {
return generator(computedValue);
}
return computedValue;
}
grabValue (
timelineName: string,
flexId: string,
matchingElement,
propertyName: string,
keyframeCluster: any,
timelineTime: number,
isPatchOperation: boolean,
skipCache: boolean,
): IComputedValue {
// Used by $helpers to calculate scope-specific values;
this.helpers.data = {
lastTimelineName: timelineName,
lastFlexId: flexId,
lastPropertyName: propertyName,
lastTimelineTime: timelineTime,
};
const parsedValueCluster = this.fetchParsedValueCluster(
timelineName,
flexId,
matchingElement,
propertyName,
keyframeCluster,
isPatchOperation,
skipCache,
);
// If there is no property of that name, we would have gotten nothing back, so we can't forward this to Transitions
// since it expects to receive a populated cluster object
if (!parsedValueCluster) {
return {
computedValue: undefined,
didValueChangeSinceLastRequest: false,
didValueOriginateFromExplicitKeyframeDefinition: false,
};
}
let computedValueForTime;
if (!parsedValueCluster.parsee[KEYFRAME_ZERO]) {
parsedValueCluster.parsee[KEYFRAME_ZERO] = {
value: getFallback(matchingElement && matchingElement.elementName, propertyName),
};
}
computedValueForTime = calculateValue(
parsedValueCluster.parsee,
timelineTime,
parsedValueCluster.keys,
);
// When expressions and other dynamic functionality is in play, data may be missing resulting in
// properties lacking defined values; in this case we try to do the right thing and fallback
// to a known usable value for the field. Especially needed with controlFlow.repeat.
if (computedValueForTime === undefined) {
computedValueForTime = getFallback(matchingElement && matchingElement.elementName, propertyName);
}
const computedValue = this.generateFinalValueFromParsedValue(
timelineName,
flexId,
matchingElement,
propertyName,
computedValueForTime,
);
const previousValue = this.cacheGet(`values:${timelineName}|${flexId}|${propertyName}`);
this.cacheSet(`values:${timelineName}|${flexId}|${propertyName}`, computedValue);
const didValueChangeSinceLastRequest = computedValue !== previousValue;
return {
computedValue,
didValueChangeSinceLastRequest,
didValueOriginateFromExplicitKeyframeDefinition: keyframeCluster && !!keyframeCluster[Math.round(timelineTime)],
};
}
getPreviousSummonees (
timelineName,
flexId,
propertyName,
keyframeMs,
) {
return this.cacheGet(`summonees:${timelineName}|${flexId}|${propertyName}|${keyframeMs}`);
}
cacheSummonees (
timelineName,
flexId,
propertyName,
keyframeMs,
summonees,
) {
this.cacheSet(`summonees:${timelineName}|${flexId}|${propertyName}|${keyframeMs}`, summonees);
return summonees;
}
getPreviousEvaluation (
timelineName,
flexId,
propertyName,
keyframeMs,
) {
return this.cacheGet(`evaluation:${timelineName}|${flexId}|${propertyName}|${keyframeMs}`);
}
cacheEvaluation (
timelineName,
flexId,
propertyName,
keyframeMs,
evaluation,
) {
this.cacheSet(`evaluation:${timelineName}|${flexId}|${propertyName}|${keyframeMs}`, evaluation);
return evaluation;
}
private getParseeWithKeys (
timelineName,
flexId,
outputName,
cluster,
): ParsedValueCluster {
if (!this.parsedValueClusters[timelineName]) {
this.parsedValueClusters[timelineName] = {};
}
if (!this.parsedValueClusters[timelineName][flexId]) {
this.parsedValueClusters[timelineName][flexId] = {};
}
if (!this.parsedValueClusters[timelineName][flexId][outputName]) {
this.parsedValueClusters[timelineName][flexId][outputName] = {
// The parsee object is mutated in place downstream
parsee: {},
keys: cluster ? getSortedKeyframes(cluster) : [],
};
}
return this.parsedValueClusters[timelineName][flexId][outputName];
}
private clusterParseeIsStable (parsedValueCluster: ParsedValueCluster): boolean {
return parsedValueCluster.keys.every(
(ms) => parsedValueCluster.parsee[ms] && !parsedValueCluster.parsee[ms].expression,
);
}
didChangeValue (
timelineName,
flexId,
matchingElement,
outputName,
outputValue,
) {
let answer = false;
const change = this.cacheGet(`changes:${timelineName}|${flexId}|${outputName}`);
if (change === undefined || change !== outputValue) {
this.cacheSet(`changes:${timelineName}|${flexId}|${outputName}`, outputValue);
answer = true;
}
return answer;
}
getSummonablesSchema () {
const summonablesSchema = {};
for (const key in INJECTABLES) {
summonablesSchema[key] = INJECTABLES[key].schema;
}
return summonablesSchema;
}
transformContextPointToLocalPoint (
point: TwoPointFiveDimensionalLayoutProperty,
): TwoPointFiveDimensionalLayoutProperty {
if (this.layoutAncestryMatrices) {
const matrix = Layout3D.multiplyArrayOfMatrices(this.layoutAncestryMatrices.reverse());
const inverse = invert([], matrix);
if (inverse !== null) {
HaikuElement.transformPointInPlace(point, inverse);
}
}
return point;
}
getParser (outputName) {
const foundParser = HaikuComponent.PARSERS[outputName];
return foundParser && foundParser.parse;
}
getGenerator (outputName) {
const foundGenerator = HaikuComponent.PARSERS[outputName];
return foundGenerator && foundGenerator.generate;
}
static __name__ = 'HaikuComponent';
static PLAYER_VERSION = VERSION; // #LEGACY
static CORE_VERSION = VERSION;
static INJECTABLES = INJECTABLES;
// When editing a component, any of these appearing inside an expression will trigger a warning.
// This is kept in the core so it's easier to compare these to the built-in injectables and
// other special treatment for JavaScript globals. "single source of truth" etc.
static FORBIDDEN_EXPRESSION_TOKENS = {
// Keywords
new: true,
this: true,
with: true,
delete: true,
export: true,
extends: true,
super: true,
class: true,
abstract: true,
interface: true,
static: true,
label: true,
goto: true,
private: true,
import: true,
public: true,
// Future keywords
do: true,
native: true,
package: true,
transient: true,
implements: true,
protected: true,
throws: true,
synchronized: true,
final: true,
// Common globals
window: true,
document: true,
global: true,
// Danger
eval: true,
uneval: true,
Function: true,
EvalError: true,
// Module stuff to forbid
require: true,
module: true,
exports: true,
Module: true,
// Sandbox
arguments: true,
callee: true,
// Identifiers on built-in global objects
prototpye: true,
__proto__: true,
freeze: true,
setPrototypeOf: true,
constructor: true,
defineProperties: true,
defineProperty: true,
};
static PARSERS = {
'style.stroke': {parse: parseColor, generate: generateColor},
'style.fill': {parse: parseColor, generate: generateColor},
'style.backgroundColor': {parse: parseColor, generate: generateColor},
'style.borderBottomColor': {parse: parseColor, generate: generateColor},
'style.borderColor': {parse: parseColor, generate: generateColor},
'style.borderLeftColor': {parse: parseColor, generate: generateColor},
'style.borderRightColor': {parse: parseColor, generate: generateColor},
'style.borderTopColor': {parse: parseColor, generate: generateColor},
'style.floodColor': {parse: parseColor, generate: generateColor},
'style.lightingColor': {parse: parseColor, generate: generateColor},
'style.stopColor': {parse: parseColor, generate: generateColor},
stroke: {parse: parseColor, generate: generateColor},
fill: {parse: parseColor, generate: generateColor},
floodColor: {parse: parseColor, generate: generateColor},
lightingColor: {parse: parseColor, generate: generateColor},
stopColor: {parse: parseColor, generate: generateColor},
backgroundColor: {parse: parseColor, generate: generateColor},
animateColor: {parse: parseColor, generate: generateColor},
feColor: {parse: parseColor, generate: generateColor},
// Note the hyphenated duplicates, for convenience
'flood-color': {parse: parseColor, generate: generateColor},
'lighting-color': {parse: parseColor, generate: generateColor},
'stop-color': {parse: parseColor, generate: generateColor},
'background-color': {parse: parseColor, generate: generateColor},
'animate-color': {parse: parseColor, generate: generateColor},
'fe-color': {parse: parseColor, generate: generateColor},
d: {parse: parseD, generate: generateD},
points: {parse: parsePoints, generate: generatePoints},
};
static all = (): HaikuComponent[] => HaikuBase.getRegistryForClass(HaikuComponent);
}
const getNodeFlexId = (node): string => {
const domId = (
node &&
node.attributes &&
node.attributes.id
);
const haikuId = (
node &&
node.attributes &&
node.attributes[HAIKU_ID_ATTRIBUTE]
);
return haikuId || domId;
};
export const getNodeCompositeId = (node): string => {
const flexId = getNodeFlexId(node);
// Treat the 0th repeater as the original (source) element
return (node.__memory && node.__memory.repeatee && node.__memory.repeatee.index)
? `${flexId}'${node.__memory.repeatee.index}`
: flexId;
};
const collatePropertyGroup = (propertiesGroup) => {
const collation = [
{}, // presentational ops
{}, // "if" ops
{}, // "repeat" ops
{}, // "placeholder" ops
];
for (const propertyName in propertiesGroup) {
if (propertyName === 'controlFlow.if') {
collation[0][propertyName] = propertiesGroup[propertyName];
} else if (propertyName === 'controlFlow.repeat') {
collation[1][propertyName] = propertiesGroup[propertyName];
} else if (propertyName === 'controlFlow.placeholder') {
collation[2][propertyName] = propertiesGroup[propertyName];
} else {
collation[3][propertyName] = propertiesGroup[propertyName];
}
}
return collation;
};
function isBytecode (thing) {
return thing && typeof thing === OBJECT_TYPE && thing.template;
}
function assertTemplate (template) {
if (!template) {
throw new Error('Empty template not allowed');
}
if (typeof template === OBJECT_TYPE) {
if (template.attributes) {
if (!template.attributes[HAIKU_ID_ATTRIBUTE]) {
console.warn('[haiku core] bytecode template has no id');
}
} else {
console.warn('[haiku core] bytecode template has no attributes');
}
if (!template.elementName) {
console.warn('[haiku core] unexpected bytecode template format');
}
return template;
}
throw new Error('Unknown bytecode template format');
}
const needsVirtualChildren = (child: BytecodeNode): boolean => typeof child === 'object' &&
child.__memory &&
(
(child.__memory.if && !child.__memory.if.answer) ||
(child.__memory.repeater && !!child.__memory.repeater.repeatees)
);
const reduceNodeMemoryChildren = (children, out = [], doIncludeRepeatees = false) => {
for (let i = 0; i < children.length; i++) {
const child = children[i];
if (!child) {
continue;
}
if (typeof child === 'object' && child.__memory) {
// Do not include any children that have been removed due to $if-logic
if (child.__memory.if && !child.__memory.if.answer) {
continue;
}
// If the child is a repeater, use the $repeats instead of itself
if (
doIncludeRepeatees &&
child.__memory.repeater &&
child.__memory.repeater.repeatees
) {
reduceNodeMemoryChildren(child.__memory.repeater.repeatees, out, false);
continue;
}
// If we got this far, the child is structurally normal
out.push(child);
} else {
out.push(child);
}
}
return out;
};
const assembleNodeMemoryChildren = (node: BytecodeNode, subtree) => {
if (subtree) {
return [subtree];
}
if (node.__memory.placeholder) {
return [];
}
// To avoid creating garbage, only allow allocations here if we actually need virtual children.
if (!node.children || !node.children.some(needsVirtualChildren)) {
return;
}
return reduceNodeMemoryChildren(node.children, [], true);
};
const expandNode = (node: BytecodeNode|string, parent) => {
if (!node || typeof node !== 'object' || !node.__memory) {
return;
}
let children = node.children;
// Special case if our current original is the wrapper of a subcomponent.
const subtree = node.__memory.subcomponent && node.__memory.subcomponent.bytecode.template;
const assembled = assembleNodeMemoryChildren(node, subtree);
// Don't just overwrite, since node.__memory.children may've been set to vanity 'content'
if (assembled) {
node.__memory.children = assembled;
}
if (node.__memory.children) {
children = node.__memory.children;
}
/**
* When we compute layout, we have the following chicken/egg problem:
* 1. Nodes which are "auto"-sized consume their children's size to calculate their own size.
* 2. Nodes with a SIZE_PROPORTIONAL depend on parent absolute size to compute their target size. (DEPRECATED)
* 3. Nodes with an "auto"-sized parent consume their parent's bounds to calculate a translation offset.
*
* Thus, we perform the layout steps in the following order:
* 1. Compute the current node's layout.
* 1.a. If the current node is "auto"-sized, compute the size of the children. For each child,
* we compute its bounding rect using its *local* transform (not using its parent size).
* This is sufficient to obtain a bounding box in local coordinate space with respect to
* an unknown container. We then use all of the rects to determine the outermost bbox,
* which in turn is used to determine the current node's size.
* 1.b. If the current node is numerically sized, use that size.
* 2. Expand all children of the current node. By now, the parent should have a numeric size.
* 2.a. For SIZE_PROPORTIONAL nodes, compute the layout as proportion of the parent size.
* 2.b. For other nodes, compute its local size.
* 2.c. If the parent was "auto"-sized, it should have its bounds precalculated from the
* previous pass. When this is the case, use the bounds to calculate an offset value
* by which translation will be offset, aligning all children to be perfectly flush
* with their container, no matter what size it is.
*/
computeAndApplyLayout(node, parent);
if (children) {
for (let j = 0; j < children.length; j++) {
// Special case: The subtree of the subcomponent doesn't need to be re-expanded.
if (children[j] !== subtree) {
expandNode(children[j], node);
}
}
}
};
const computeAndApplyLayout = (node, parent) => {
// Don't assume the node has/needs a layout, for example, control-flow injectees
if (node.layout) {
node.layout.computed = HaikuElement.computeLayout(
node,
parent,
);
}
};
const hydrateNode = (
node,
parent,
component: HaikuComponent,
context: IHaikuContext,
host: HaikuComponent,
scope: string,
options: any = {},
doConnectInstanceToNode: boolean,
) => {
// Nothing to expand if the node happens to be text or unexpected type
if (!node || typeof node !== 'object') {
return;
}
// Hydrate a HaikuElement representation of all nodes in the tree.
// The instance is cached as node.__memory.element for performance purposes.
HaikuElement.findOrCreateByNode(node);
component.cacheNodeWithSelectorKey(node);
// Platform-specific renderers may depend on access to the parent.
node.__memory.parent = parent;
// So renderers can detect when different layout behavior is needed.
node.__memory.scope = scope || 'div';
// Give it a pointer back to the host context; used by HaikuElement
node.__memory.context = context;
Layout3D.initializeNodeAttributes(
node,
doConnectInstanceToNode, // a.k.a isRootNode
);
// Give instances a pointer to their node and vice versa
if (doConnectInstanceToNode) {
node.__memory.instance = component;
// In the case that the node represents the root of an instance, treat the instance as the element;
// connect their references and override the equivalent action in findOrCreateByNode.
HaikuElement.connectNodeWithElement(node, node.__memory.instance);
}
// If the element name is missing it should still be safe to hydrate the children
if (typeof node.elementName === STRING_TYPE || !node.elementName) {
if (node.children) {
for (let i = 0; i < node.children.length; i++) {
hydrateNode(
node.children[i], // node
node, // parent
component, // instance (component)
context,
host,
SCOPE_STRATA[node.elementName] || scope, // scope
options,
false,
);
}
}
return;
}
if (isBytecode(node.elementName)) {
// Example structure showing how nodes and instances are related:
// <div root> instance id=1
// <div>
// <div>
// <div wrap> subcomponent (instance id=2)
// <div root> instance id=2
// ...
if (!node.__memory.subcomponent) {
const config = Config.buildChildSafeConfig({
...context.config,
...options,
});
// Note: .render and thus .hydrateNode are called by the constructor,
// automatically connecting the root node to itself (see stanza above).
node.__memory.subcomponent = new HaikuComponent(
node.elementName,
context, // context
component, // host
{
loop: true, // A la Flash, subcomponents play by default
...config,
},
node, // container
);
// Very important, as the guests collection is used in rendering/patching
component.registerGuest(node.__memory.subcomponent);
} else {
// Reassigning is necessary since these objects may have changed between
// renders in the editing environment
node.__memory.subcomponent.context = context; // context
node.__memory.subcomponent.host = component; // host
node.__memory.subcomponent.container = node; // container
// Very important, as the guests collection is used in rendering/patching
component.registerGuest(node.__memory.subcomponent);
// Don't re-start any nested timelines that have been explicitly paused
if (!node.__memory.subcomponent.getDefaultTimeline().isPaused()) {
node.__memory.subcomponent.startTimeline(DEFAULT_TIMELINE_NAME);
}
}
return;
}
// In case we got a __reference node or other unknown
console.warn('[haiku core] cannot hydrate node');
};
const computeAndApplyPresetSizing = (element, container, mode): boolean => {
const elementWidth = element.layout.sizeAbsolute.x;
const elementHeight = element.layout.sizeAbsolute.y;
// Some browsers does not work correctly with matrix3d transforms on SVGs
// with resulting subpixel rendering, so let's round up the size to avoid
// browser problems
const containerWidth = Math.ceil(container.layout.computed.size.x);
const containerHeight = Math.ceil(container.layout.computed.size.y);
// I.e., the amount by which we'd have to multiply the element's scale to make it
// exactly the same size as its container (without going above it)
const scaleDiffX = containerWidth / elementWidth;
const scaleDiffY = containerHeight / elementHeight;
// This makes sure that the sizing occurs with respect to a correct and consistent origin point,
// but only if the user didn't happen to explicitly set this value (we allow their override).
if (!element.attributes.style['transform-origin']) {
element.attributes.style['transform-origin'] = '0% 0% 0px';
}
// IMPORTANT: If any value has been changed on the element, you must set this to true.
// Otherwise the changed object won't go into the deltas dictionary, and the element won't update.
let changed = false;
switch (mode) {
// Make the base element its default scale, which is just a multiplier of one. This is the default.
case 'normal':
if (element.layout.scale.x !== 1.0 || element.layout.scale.y !== 1.0) {
changed = true;
element.layout.scale.x = element.layout.scale.y = 1.0;
}
break;
// Stretch the element to fit the container on both x and y dimensions (distortion allowed)
case 'stretch':
if (scaleDiffX !== element.layout.scale.x) {
changed = true;
element.layout.scale.x = scaleDiffX;
}
if (scaleDiffY !== element.layout.scale.y) {
changed = true;
element.layout.scale.y = scaleDiffY;
}
break;
// CONTAIN algorithm
// see https://developer.mozilla.org/en-US/docs/Web/CSS/background-size?v=example
// A keyword that scales the image as large as possible and maintains image aspect ratio
// (image doesn't get squished). Image is letterboxed within the container.
// When the image and container have different dimensions, the empty areas (either top/bottom of left/right)
// are filled with the background-color.
case 'contain':
case true: // (Legacy.)
let containScaleToUse = null;
// We're looking for the larger of the two scales that still allows both dimensions to fit in the box
// The rounding is necessary to avoid precision issues, where we end up comparing e.g. 2.0000000000001 to 2
if (
~~(scaleDiffX * elementWidth) <= containerWidth &&
~~(scaleDiffX * elementHeight) <= containerHeight
) {
containScaleToUse = scaleDiffX;
}
if (
~~(scaleDiffY * elementWidth) <= containerWidth &&
~~(scaleDiffY * elementHeight) <= containerHeight
) {
if (containScaleToUse === null) {
containScaleToUse = scaleDiffY;
} else {
if (scaleDiffY >= containScaleToUse) {
containScaleToUse = scaleDiffY;
}
}
}
if (element.layout.scale.x !== containScaleToUse) {
changed = true;
element.layout.scale.x = containScaleToUse;
}
if (element.layout.scale.y !== containScaleToUse) {
changed = true;
element.layout.scale.y = containScaleToUse;
}
// Offset the translation so that the element remains centered within the letterboxing
const containTranslationOffsetX = -(containScaleToUse * elementWidth - containerWidth) / 2;
const containTranslationOffsetY = -(containScaleToUse * elementHeight - containerHeight) / 2;
if (element.layout.translation.x !== containTranslationOffsetX) {
changed = true;
element.layout.translation.x = containTranslationOffsetX;
}
if (element.layout.translation.y !== containTranslationOffsetY) {
changed = true;
element.layout.translation.y = containTranslationOffsetY;
}
break;
// COVER algorithm (inverse of CONTAIN)
// see https://developer.mozilla.org/en-US/docs/Web/CSS/background-size?v=example
// A keyword that is the inverse of contain. Scales the image as large as possible and maintains
// image aspect ratio (image doesn't get squished). The image "covers" the entire width or height
// of the container. When the image and container have different dimensions, the image is clipped
// either left/right or top/bottom.
case 'cover':
let coverScaleToUse = null;
// We're looking for the smaller of two scales that ensures the entire box is covered.
// The rounding is necessary to avoid precision issues, where we end up comparing e.g. 2.0000000000001 to 2
if (~~(scaleDiffX * elementHeight) >= containerHeight) {
coverScaleToUse = scaleDiffX;
} else if (~~(scaleDiffY * elementWidth) >= containerWidth) {
coverScaleToUse = scaleDiffY;
} else {
coverScaleToUse = Math.max(scaleDiffX, scaleDiffY);
}
if (element.layout.scale.x !== coverScaleToUse) {
changed = true;
element.layout.scale.x = coverScaleToUse;
}
if (element.layout.scale.y !== coverScaleToUse) {
changed = true;
element.layout.scale.y = coverScaleToUse;
}
// Offset the translation so that the element remains centered despite clipping
const coverTranslationOffsetX = -(coverScaleToUse * elementWidth - containerWidth) / 2;
const coverTranslationOffsetY = -(coverScaleToUse * elementHeight - containerHeight) / 2;
if (element.layout.translation.x !== coverTranslationOffsetX) {
changed = true;
element.layout.translation.x = coverTranslationOffsetX;
}
if (element.layout.translation.y !== coverTranslationOffsetY) {
changed = true;
element.layout.translation.y = coverTranslationOffsetY;
}
break;
}
return changed;
};
export interface ClonedFunction {
(...args: any[]): void;
__rfo?: RFO;
}
export const clone = (value, binding) => {
if (!value) {
return value;
}
if (typeof value === 'boolean') {
return value;
}
if (typeof value === 'number') {
return value;
}
if (typeof value === 'string') {
return value;
}
if (typeof value === 'function') {
const fn: ClonedFunction = (...args: any[]) => value.call(binding, ...args);
// Core decorates injectee functions with metadata properties
for (const key in value) {
if (value.hasOwnProperty(key)) {
fn[key] = clone(value[key], binding);
}
}
fn.__rfo = functionToRFO(value).__function;
return fn;
}
if (Array.isArray(value)) {
return value.map((el) => clone(el, binding));
}
// Don't try to clone anything other than plain objects
if (typeof value === 'object' && value.constructor === Object) {
const out = {};
for (const key in value) {
if (!value.hasOwnProperty(key) || key.slice(0, 2) === '__') {
continue;
}
// If it looks like guest bytecode, don't clone it since
// (a) we're passing down *our* function binding, which will break event handling and
// (b) each HaikuComponent#constructor calls clone() on its own anyway
if (key === 'elementName' && typeof value[key] !== 'string') {
out[key] = value[key];
} else {
out[key] = clone(value[key], binding);
}
}
return out;
}
return value;
};
const setStyle = (subkey, element, value) => {
element.attributes.style[subkey] = value;
};
const setAttribute = (key, element, value) => {
const final = ATTRS_CAMEL_TO_HYPH[key] || key;
element.attributes[final] = value;
};
const isNumeric = (n) => {
return !isNaN(parseFloat(n)) && isFinite(n);
};
const isInteger = (x) => {
return x % 1 === 0;
};
const REACT_MATCHING_OPTIONS = {
name: 'type',
attributes: 'props',
};
const HAIKU_MATCHING_OPTIONS = {
name: 'elementName',
attributes: 'attributes',
};
const querySelectSubtree = (surrogate: any, value) => {
// First try the Haiku format
if (cssMatchOne(surrogate, value, HAIKU_MATCHING_OPTIONS)) {
return surrogate;
}
// If no match yet, try the React format (TODO: Does this belong here?)
if (cssMatchOne(surrogate, value, REACT_MATCHING_OPTIONS)) {
return surrogate;
}
// Visit the descendants (if any) and see if we have a match there
const children = (
surrogate.children || // Haiku's format
(surrogate.props && surrogate.props.children) // React's format
);
// If no children, we definitely don't have a match in this subtree
if (!children) {
return null;
}
// Check for arrays first since arrays pass the typeof object check
if (Array.isArray(children)) {
for (let i = 0; i < children.length; i++) {
const found = querySelectSubtree(children[i], value);
// First time a match is found, break the loop and return it
if (found) {
return found;
}
}
}
// React may store 'children' as a single object
if (typeof children === 'object') {
return querySelectSubtree(children, value);
}
};
const querySelectSurrogates = (surrogates: any, value: string): any => {
if (Array.isArray(surrogates)) {
// Return the first match we locate in the collection
return surrogates.map((surrogate) => querySelectSurrogates(surrogate, value))[0];
}
if (surrogates && typeof surrogates === 'object') {
return querySelectSubtree(surrogates, value);
}
};
const selectSurrogate = (surrogates: any, value: any): any => {
// If the placeholder value is intended as an array index
if (Array.isArray(surrogates) && isNumeric(value) && isInteger(value)) {
if (surrogates[value]) {
return surrogates[value];
}
}
// If the placeholder value is intended as a key
if (surrogates && typeof surrogates === 'object' && typeof value === 'string') {
if (surrogates[value]) {
return surrogates[value];
}
}
return querySelectSurrogates(surrogates, value + '');
};
const getCanonicalPlaybackValue = (value) => {
if (typeof value !== 'object') {
return {
Default: value,
};
}
return value;
};
/**
* 'Vanities' are functions that provide special handling for applied properties.
* So for example, if a component wants to apply 'foo.bar'=3 to a <div> in its template,
* the renderer will look in the vanities dictionary to see if there is a
* vanity 'foo.bar' available, and if so, pass the value 3 into that function.
* The function, in turn, knows how to apply that value to the virtual element passed into
* it. In the future these will be defined by components themselves as inputs; for now,
* we are keeping a whitelist of possible vanity handlers which the renderer directly
* loads and calls.
*/
export const getVanity = (elementName: string, propertyName: string) => {
if (elementName) {
if (VANITIES[elementName] && VANITIES[elementName][propertyName]) {
return VANITIES[elementName][propertyName];
}
}
return VANITIES['*'][propertyName];
};
/**
* Ensures layout before applying a layout vanity.
*/
const ensureLayout = (node: BytecodeNode) => {
if (!node.layout) {
Layout3D.initializeNodeLayout(node);
}
};
export const LAYOUT_3D_VANITIES = {
// Layout has a couple of special values that relate to display
// but not to position:
shown: (_, element, value) => {
ensureLayout(element);
element.layout.shown = value;
},
// Opacity needs to have its opacity *layout* property set
// as opposed to its element attribute so the renderer can make a decision about
// where to put it based on the rendering medium's rules
opacity: (_, element, value) => {
ensureLayout(element);
element.layout.opacity = value;
},
// If you really want to set what we call 'position' then
// we do so on the element's attributes; this is mainly to
// enable the x/y positioning system for SVG elements.
'position.x': (name, element, value) => {
ensureLayout(element);
element.attributes.x = value;
},
'position.y': (name, element, value) => {
ensureLayout(element);
element.attributes.y = value;
},
// Everything that follows is a standard 3-coord component
// relating to the element's position in space
'rotation.x': (_, element, value) => {
ensureLayout(element);
element.layout.rotation.x = value;
},
'rotation.y': (_, element, value) => {
ensureLayout(element);
element.layout.rotation.y = value;
},
'rotation.z': (_, element, value) => {
ensureLayout(element);
element.layout.rotation.z = value;
},
'offset.x': (name, element, value) => {
ensureLayout(element);
element.layout.offset.x = value;
},
'offset.y': (name, element, value) => {
ensureLayout(element);
element.layout.offset.y = value;
},
'offset.z': (name, element, value) => {
ensureLayout(element);
element.layout.offset.z = value;
},
'origin.x': (name, element, value) => {
ensureLayout(element);
element.layout.origin.x = value;
},
'origin.y': (name, element, value) => {
ensureLayout(element);
element.layout.origin.y = value;
},
'origin.z': (name, element, value) => {
ensureLayout(element);
element.layout.origin.z = value;
},
'scale.x': (name, element, value) => {
ensureLayout(element);
element.layout.scale.x = value;
},
'scale.y': (name, element, value) => {
ensureLayout(element);
element.layout.scale.y = value;
},
'scale.z': (name, element, value) => {
ensureLayout(element);
element.layout.scale.z = value;
},
'sizeAbsolute.x': (name, element, value) => {
ensureLayout(element);
element.layout.sizeAbsolute.x = value;
},
'sizeAbsolute.y': (name, element, value) => {
ensureLayout(element);
element.layout.sizeAbsolute.y = value;
},
'sizeAbsolute.z': (name, element, value) => {
ensureLayout(element);
element.layout.sizeAbsolute.z = value;
},
'sizeDifferential.x': (name, element, value) => {
ensureLayout(element);
element.layout.sizeDifferential.x = value;
},
'sizeDifferential.y': (name, element, value) => {
ensureLayout(element);
element.layout.sizeDifferential.y = value;
},
'sizeDifferential.z': (name, element, value) => {
ensureLayout(element);
element.layout.sizeDifferential.z = value;
},
'sizeMode.x': (name, element, value) => {
ensureLayout(element);
element.layout.sizeMode.x = value;
},
'sizeMode.y': (name, element, value) => {
ensureLayout(element);
element.layout.sizeMode.y = value;
},
'sizeMode.z': (name, element, value) => {
ensureLayout(element);
element.layout.sizeMode.z = value;
},
'sizeProportional.x': (name, element, value) => {
ensureLayout(element);
element.layout.sizeProportional.x = value;
},
'sizeProportional.y': (name, element, value) => {
ensureLayout(element);
element.layout.sizeProportional.y = value;
},
'sizeProportional.z': (name, element, value) => {
ensureLayout(element);
element.layout.sizeProportional.z = value;
},
'shear.xy': (name, element, value) => {
ensureLayout(element);
element.layout.shear.xy = value;
},
'shear.xz': (name, element, value) => {
ensureLayout(element);
element.layout.shear.xz = value;
},
'shear.yz': (name, element, value) => {
ensureLayout(element);
element.layout.shear.yz = value;
},
'translation.x': (name, element, value) => {
ensureLayout(element);
element.layout.translation.x = value;
},
'translation.y': (name, element, value) => {
ensureLayout(element);
element.layout.translation.y = value;
},
'translation.z': (name, element, value) => {
ensureLayout(element);
element.layout.translation.z = value;
},
};
export const VANITIES = {
'*': {
...LAYOUT_3D_VANITIES,
// CSS style properties that need special handling
'style.WebkitTapHighlightColor': (_, element, value) => {
element.attributes.style.webkitTapHighlightColor = value;
},
// Text and other inner-content related vanities
content: (
name,
element,
value,
context,
timeline,
receiver,
sender,
) => {
element.__memory.children = [value];
// If we don't do this, then content changes resulting from setState calls
// don't have the effect of flushing the content, and the rendered text doesn't change.
// DEMO: bind-numeric-state-to-text
// TODO: What is the best way to make this less expensive (while still functional)?
sender.patches.push(element);
},
// Playback-related vanities that involve controlling timeline or clock time
playback: (
name,
element,
value: any,
context: IHaikuContext,
timeline: HaikuTimeline,
receiver: HaikuComponent,
sender: HaikuComponent,
) => {
const canonicalValue = getCanonicalPlaybackValue(value);
for (const timelineName in canonicalValue) {
const timelineInstance = receiver && receiver.getTimeline(timelineName);
if (timelineInstance) {
timelineInstance.setPlaybackStatus(canonicalValue[timelineName]);
}
}
},
// Control-flow vanities that alter the output structure of the component
'controlFlow.placeholder': (
name,
element,
value,
context,
timeline,
receiver,
sender,
) => {
// For MVP's sake, structural behaviors not rendered during hot editing.
if (sender.config.hotEditingMode) {
return;
}
if (value === null || value === undefined) {
return;
}
if (typeof value !== 'number' && typeof value !== 'string') {
return;
}
let surrogates;
// Surrogates can be passed in as:
// - React children (an array)
// - A React subtree (we'll use query selectors to match)
// - A Haiku subtree (we'll use query selectors to match)
// - Key/value pairs
if (context.config.children) {
surrogates = context.config.children;
if (!Array.isArray(surrogates)) {
surrogates = [surrogates];
}
} else if (context.config.placeholder) {
surrogates = context.config.placeholder;
}
if (!surrogates) {
return;
}
const surrogate = selectSurrogate(surrogates, value);
if (surrogate === null || surrogate === undefined) {
return;
}
if (!element.__memory.placeholder) {
element.__memory.placeholder = {};
}
element.__memory.placeholder.value = value;
// If we are running via a framework adapter, allow that framework to provide its own placeholder mechanism.
// This is necessary e.g. in React where their element format needs to be converted into our 'mana' format
if (context.config.vanities['controlFlow.placeholder']) {
context.config.vanities['controlFlow.placeholder'](
element,
surrogate,
value,
context,
timeline,
receiver,
sender,
);
} else {
element.__memory.placeholder.surrogate = surrogate;
}
},
'controlFlow.repeat': (
name: string,
element,
value,
context: IHaikuContext,
timeline: HaikuTimeline,
receiver: HaikuComponent,
sender: HaikuComponent,
) => {
let instructions;
if (Array.isArray(value)) {
instructions = value;
} else if (isNumeric(value)) {
const arr = [];
for (let i = 0; i < value; i++) {
arr.push({}); // Empty repeat payload spec
}
instructions = arr;
} else {
return;
}
if (element.__memory.repeatee) {
// Don't repeat the repeatee of an existing repeater
if (element.__memory.repeatee.index > 0) {
return;
}
}
if (element.__memory.repeater) {
if (element.__memory.repeater.changed) {
element.__memory.repeater.changed = false;
} else {
// Save CPU by avoiding recomputing a repeat when we've already done so.
// Although upstream HaikuComponent#applyLocalBehaviors does do diff comparisons,
// it intentionally skips this comparison for complex properties i.e. arrays
// and objects due to the intractability of smartly comparing for all cases.
// We do a comparison that is fairly sensible in the repeat-exclusive case.
if (isSameRepeatBehavior(element.__memory.repeater.instructions, instructions)) {
return;
}
}
}
if (!element.__memory.repeater) {
element.__memory.repeater = {};
}
element.__memory.repeater.instructions = instructions;
// Structural behaviors are not rendered during hot editing.
if (sender.config.hotEditingMode) {
// If we got at least one instruction, render that by default into the repeater
if (instructions.length > 0) {
element.__memory.repeatee = {
instructions,
index: 0,
payload: instructions[0],
source: element,
};
applyPayloadToNode(
element,
instructions[0],
sender,
timeline,
);
sender.patches.push(element);
expandNode(element, element.__memory.parent);
}
return;
}
if (!element.__memory.repeater.repeatees) {
element.__memory.repeater.repeatees = [];
} else {
// If the instructions have decreased on this run, remove the excess repeatees
element.__memory.repeater.repeatees.splice(instructions.length);
}
instructions.forEach((payload, index) => {
const repeatee = (index === 0)
? element // The first element should be the source element
: element.__memory.repeater.repeatees[index] || clone(element, sender);
// We have to initialize the element's component instance, etc.
hydrateNode(
repeatee,
element.__memory.parent, // parent
sender, // component
sender.context, // context
sender, // host
element.__memory.scope, // scope (use same scope as source node)
sender.config, // options
false, // doConnectInstanceToNode
);
repeatee.__memory.repeatee = {
index,
instructions,
payload,
source: element,
};
applyPayloadToNode(
repeatee,
payload,
sender,
timeline,
);
element.__memory.repeater.repeatees[index] = repeatee;
});
sender.patches.push(element);
expandNode(element, element.__memory.parent);
},
'controlFlow.if': (
name: string,
element,
value,
context: IHaikuContext,
timeline: HaikuTimeline,
receiver: HaikuComponent,
sender: HaikuComponent,
) => {
// For MVP's sake, structural behaviors not rendered during hot editing.
if (sender.config.hotEditingMode) {
return;
}
// Assume our if-answer is only false if we got an explicit false value
const answer = value !== false;
if (element.__memory.if) {
// Save CPU by avoiding recomputing an if when we've already done so.
if (isSameIfBehavior(element.__memory.if.answer, answer)) {
return;
}
}
element.__memory.if = {
answer,
};
// Ensure that a change in repeat will trigger the necessary re-repeat
if (element.__memory.repeater) {
element.__memory.repeater.changed = true;
}
sender.markForFullFlush();
},
},
};
const applyPayloadToNode = (node, payload, sender, timeline) => {
// Apply the repeat payload to the element as if it were a normal timeline output
for (const propertyName in payload) {
// Control-flow occurs after presentational behaviors, meaning we are overriding
// whatever may have been set on the source element instance.
sender.applyPropertyToNode(
node, // matchingElement
propertyName,
payload[propertyName], // finalValue
timeline,
);
}
};
const isSameIfBehavior = (prev, next): boolean => {
return prev === next;
};
const isSameRepeatBehavior = (prevs, nexts): boolean => {
if (prevs === nexts) {
return true;
}
if (prevs.length !== nexts.length) {
return false;
}
let answer = true;
for (let i = 0; i < prevs.length; i++) {
if (!answer) {
break;
}
const prev = prevs[i];
const next = nexts[i];
if (prev === next) {
continue;
}
for (const key in next) {
if (next[key] !== prev[key]) {
answer = false;
break;
}
}
}
return answer;
};
const findRespectiveRepeatees = (target) => {
const repeatees = [];
// Required to fix a race condition that can occur during copy+paste in Haiku.app
if (!target.__memory) {
return repeatees;
}
// The host repeatee of the given target node, if the target is a repeater's descendant
let host;
if (target.__memory.repeatee) {
host = target;
} else {
// Note that we do not ascend beyond the nearest host component instance
ascend(target, (node) => {
if (node.__memory.repeatee) {
host = node;
}
});
}
// If we've found a host repeatee, the target is a descendant of a repeater,
// and we need to find its respective node within each repeatee.
if (host) {
const repeater = host.__memory.repeatee.source;
if (repeater.__memory.repeater.repeatees) {
repeater.__memory.repeater.repeatees.forEach((repeatee) => {
visit(repeatee, (candidate) => {
if (areNodesRespective(target, candidate)) {
repeatees.push(candidate);
}
});
});
}
}
return repeatees;
};
const areNodesRespective = (n1, n2): boolean => {
if (n1 === n2) {
return true;
}
// We assume that all nodes within the tree of a component have unique haiku-ids, and that
// these haiku-ids are not directly modified within repeater groups
if (
// If the haiku-id attribute is empty, assume the comparison isn't valid
n1.attributes[HAIKU_ID_ATTRIBUTE] &&
n1.attributes[HAIKU_ID_ATTRIBUTE] === n2.attributes[HAIKU_ID_ATTRIBUTE]
) {
return true;
}
return false;
};
export const getFallback = (elementName: string, propertyName: string) => {
if (elementName) {
if (
LAYOUT_COORDINATE_SYSTEM_FALLBACKS[elementName] &&
LAYOUT_COORDINATE_SYSTEM_FALLBACKS[elementName][propertyName] !== undefined) {
return LAYOUT_COORDINATE_SYSTEM_FALLBACKS[elementName][propertyName];
}
if (FALLBACKS[elementName] && FALLBACKS[elementName][propertyName] !== undefined) {
return FALLBACKS[elementName][propertyName];
}
}
return FALLBACKS['*'][propertyName];
};
const LAYOUT_COORDINATE_SYSTEM_FALLBACKS = {
svg: {
'origin.x': 0.5,
'origin.y': 0.5,
'origin.z': 0.5,
},
};
const LAYOUT_DEFAULTS = Layout3D.createLayoutSpec();
export const FALLBACKS = {
'*': {
shown: LAYOUT_DEFAULTS.shown,
opacity: LAYOUT_DEFAULTS.opacity,
content: '',
'offset.x': LAYOUT_DEFAULTS.offset.x,
'offset.y': LAYOUT_DEFAULTS.offset.y,
'offset.z': LAYOUT_DEFAULTS.offset.z,
'origin.x': LAYOUT_DEFAULTS.origin.x,
'origin.y': LAYOUT_DEFAULTS.origin.y,
'origin.z': LAYOUT_DEFAULTS.origin.z,
'translation.x': LAYOUT_DEFAULTS.translation.x,
'translation.y': LAYOUT_DEFAULTS.translation.y,
'translation.z': LAYOUT_DEFAULTS.translation.z,
'rotation.x': LAYOUT_DEFAULTS.rotation.x,
'rotation.y': LAYOUT_DEFAULTS.rotation.y,
'rotation.z': LAYOUT_DEFAULTS.rotation.z,
'scale.x': LAYOUT_DEFAULTS.scale.x,
'scale.y': LAYOUT_DEFAULTS.scale.y,
'scale.z': LAYOUT_DEFAULTS.scale.z,
'shear.xy': LAYOUT_DEFAULTS.shear.xy,
'shear.xz': LAYOUT_DEFAULTS.shear.xz,
'shear.yz': LAYOUT_DEFAULTS.shear.yz,
'sizeAbsolute.x': LAYOUT_DEFAULTS.sizeAbsolute.x,
'sizeAbsolute.y': LAYOUT_DEFAULTS.sizeAbsolute.y,
'sizeAbsolute.z': LAYOUT_DEFAULTS.sizeAbsolute.z,
'sizeProportional.x': LAYOUT_DEFAULTS.sizeProportional.x,
'sizeProportional.y': LAYOUT_DEFAULTS.sizeProportional.y,
'sizeProportional.z': LAYOUT_DEFAULTS.sizeProportional.z,
'sizeDifferential.x': LAYOUT_DEFAULTS.sizeDifferential.x,
'sizeDifferential.y': LAYOUT_DEFAULTS.sizeDifferential.y,
'sizeDifferential.z': LAYOUT_DEFAULTS.sizeDifferential.z,
'sizeMode.x': LAYOUT_DEFAULTS.sizeMode.x,
'sizeMode.y': LAYOUT_DEFAULTS.sizeMode.y,
'sizeMode.z': LAYOUT_DEFAULTS.sizeMode.z,
'style.overflowX': 'hidden',
'style.overflowY': 'hidden',
'style.zIndex': 1,
'style.WebkitTapHighlightColor': 'rgba(0,0,0,0)',
width: 0,
height: 0,
x: 0,
y: 0,
r: 0,
cx: 0,
cy: 0,
rx: 0,
ry: 0,
x1: 0,
y1: 0,
x2: 0,
y2: 0,
playback: PlaybackFlag.LOOP,
'controlFlow.repeat': null,
'controlFlow.placeholder': null,
},
};
export const LAYOUT_3D_SCHEMA = {
shown: 'boolean',
opacity: 'number',
'offset.x': 'number',
'offset.y': 'number',
'offset.z': 'number',
'origin.x': 'number',
'origin.y': 'number',
'origin.z': 'number',
'translation.x': 'number',
'translation.y': 'number',
'translation.z': 'number',
'rotation.x': 'number',
'rotation.y': 'number',
'rotation.z': 'number',
'scale.x': 'number',
'scale.y': 'number',
'scale.z': 'number',
'shear.xy': 'number',
'shear.xz': 'number',
'shear.yz': 'number',
'sizeAbsolute.x': 'number',
'sizeAbsolute.y': 'number',
'sizeAbsolute.z': 'number',
'sizeProportional.x': 'number',
'sizeProportional.y': 'number',
'sizeProportional.z': 'number',
'sizeDifferential.x': 'number',
'sizeDifferential.y': 'number',
'sizeDifferential.z': 'number',
'sizeMode.x': 'number',
'sizeMode.y': 'number',
'sizeMode.z': 'number',
};
export const ATTRS_CAMEL_TO_HYPH = {
accentHeight: 'accent-height',
alignmentBaseline: 'alignment-baseline',
arabicForm: 'arabic-form',
baselineShift: 'baseline-shift',
capHeight: 'cap-height',
clipPath: 'clip-path',
clipRule: 'clip-rule',
colorInterpolation: 'color-interpolation',
colorInterpolationFilters: 'color-interpolation-filters',
colorProfile: 'color-profile',
colorRendering: 'color-rendering',
dominantBaseline: 'dominant-baseline',
enableBackground: 'enable-background',
fillOpacity: 'fill-opacity',
fillRule: 'fill-rule',
floodColor: 'flood-color',
floodOpacity: 'flood-opacity',
fontFamily: 'font-family',
fontSize: 'font-size',
fontSizeAdjust: 'font-size-adjust',
fontStretch: 'font-stretch',
fontStyle: 'font-style',
fontVariant: 'font-variant',
fontWeight: 'font-weight',
glyphName: 'glyph-name',
glyphOrientationHorizontal: 'glyph-orientation-horizontal',
glyphOrientationVertical: 'glyph-orientation-vertical',
horizAdvX: 'horiz-adv-x',
horizOriginX: 'horiz-origin-x',
imageRendering: 'image-rendering',
letterSpacing: 'letter-spacing',
lightingColor: 'lighting-color',
markerEnd: 'marker-end',
markerMid: 'marker-mid',
markerStart: 'marker-start',
overlinePosition: 'overline-position',
overlineThickness: 'overline-thickness',
panose1: 'panose-1',
paintOrder: 'paint-order',
pointerEvents: 'pointer-events',
renderingIntent: 'rendering-intent',
shapeRendering: 'shape-rendering',
stopColor: 'stop-color',
stopOpacity: 'stop-opacity',
strikethroughPosition: 'strikethrough-position',
strikethroughThickness: 'strikethrough-thickness',
strokeDasharray: 'stroke-dasharray',
strokeDashoffset: 'stroke-dashoffset',
strokeLinecap: 'stroke-linecap',
strokeLinejoin: 'stroke-linejoin',
strokeMiterlimit: 'stroke-miterlimit',
strokeOpacity: 'stroke-opacity',
strokeWidth: 'stroke-width',
textAnchor: 'text-anchor',
textDecoration: 'text-decoration',
textRendering: 'text-rendering',
underlinePosition: 'underline-position',
underlineThickness: 'underline-thickness',
unicodeBidi: 'unicode-bidi',
unicodeRange: 'unicode-range',
unitsPerEm: 'units-per-em',
vAlphabetic: 'v-alphabetic',
vHanging: 'v-hanging',
vIdeographic: 'v-ideographic',
vMathematical: 'v-mathematical',
vectorEffect: 'vector-effect',
vertAdvY: 'vert-adv-y',
vertOriginX: 'vert-origin-x',
vertOriginY: 'vert-origin-y',
wordSpacing: 'word-spacing',
writingMode: 'writing-mode',
xHeight: 'x-height',
};
const PositionSchema = {
x: 'number',
y: 'number',
z: 'number',
};
export const ATTRS_HYPH_TO_CAMEL = {};
for (const camel in ATTRS_CAMEL_TO_HYPH) {
ATTRS_HYPH_TO_CAMEL[ATTRS_CAMEL_TO_HYPH[camel]] = camel;
}
INJECTABLES.$element = {
schema: {
offset: PositionSchema,
attributes: {},
tagName: 'string',
matrix: [],
opacity: 'number',
origin: PositionSchema,
rotation: PositionSchema,
scale: PositionSchema,
shown: 'boolean',
size: {x: 'number', y: 'number'},
sizeAbsolute: PositionSchema,
sizeProportional: PositionSchema,
translation: PositionSchema,
},
summon (injectees, component: HaikuComponent, node) {
injectees.$element = HaikuElement.findOrCreateByNode(node);
},
};
INJECTABLES.$window = {
schema: {},
summon (injectees) {
injectees.$window = (typeof window !== 'undefined') ? window : {};
},
};
INJECTABLES.$mount = {
schema: {},
summon (injectees, component: HaikuComponent) {
injectees.$mount = component.context.renderer.mount;
},
};
INJECTABLES.$timeline = {
schema: {},
summon (injectees, component: HaikuComponent, node, timelineName: string) {
injectees.$timeline = component.getTimeline(timelineName);
},
};
INJECTABLES.$clock = {
schema: {
destroy: 'function',
getExplicitTime: 'function',
getFrameDuration: 'function',
getTime: 'function',
setTime: 'function',
isRunning: 'function',
run: 'function',
start: 'function',
assignOptions: 'function',
},
summon (injectees, component: HaikuComponent) {
injectees.$clock = component.getClock();
},
};
INJECTABLES.$core = {
schema: {
options: DEFAULTS,
timeline: INJECTABLES.$timeline.schema,
clock: INJECTABLES.$clock.schema,
},
summon (injectees, component: HaikuComponent, node, timelineName: string) {
injectees.$core = {
component,
context: component.context,
options: component.config,
timeline: component.getTimeline(timelineName),
clock: component.getClock(),
};
},
};
INJECTABLES.$context = {
schema: {},
summon (injectees, component: HaikuComponent) {
injectees.$context = component.context;
},
};
INJECTABLES.$component = {
schema: INJECTABLES.$element.schema,
summon (injectees, component: HaikuComponent) {
injectees.$component = component;
},
};
INJECTABLES.$host = {
schema: {},
summon (injectees, component: HaikuComponent) {
injectees.$host = component.host;
},
};
INJECTABLES.$top = {
schema: {},
summon (injectees, component: HaikuComponent) {
injectees.$host = component.top;
},
};
INJECTABLES.$state = {
schema: {},
summon (injectees, component: HaikuComponent) {
injectees.$state = component.state;
},
};
INJECTABLES.$parent = {
schema: INJECTABLES.$element.schema,
summon (injectees, component: HaikuComponent, node) {
injectees.$parent = HaikuElement.findOrCreateByNode(node).parent;
},
};
INJECTABLES.$container = {
schema: INJECTABLES.$element.schema,
summon (injectees, component: HaikuComponent, node) {
const element = HaikuElement.findOrCreateByNode(node);
injectees.$container = element.owner;
},
};
INJECTABLES.$children = {
schema: INJECTABLES.$element.schema.children,
summon (injectees, component: HaikuComponent, node) {
injectees.$children = HaikuElement.findOrCreateByNode(node).children;
},
};
INJECTABLES.$tree = {
schema: {
parent: INJECTABLES.$element.schema,
chidren: INJECTABLES.$element.schema.children,
component: INJECTABLES.$element.schema,
root: INJECTABLES.$element.schema,
element: INJECTABLES.$element.schema,
},
summon (injectees, component: HaikuComponent, node) {
const element = HaikuElement.findOrCreateByNode(node);
injectees.$tree = {
element,
component,
parent: element.parent,
children: element.children,
root: element.owner,
};
},
};
INJECTABLES.$user = {
schema: {
mouse: {
x: 'number',
y: 'number',
down: 'boolean',
buttons: [],
},
mouches: [],
keys: {},
touches: [],
pan: {
x: 'number',
y: 'number',
},
},
summon (injectees, component: HaikuComponent, node) {
if (component.isLiveMode()) {
injectees.$user = component.context.getGlobalUserState();
// If we're inside another component, produce mouse coords in terms
// of our own coordinate space
if (component.host) {
Object.assign(
injectees.$user.mouse,
component.transformContextPointToLocalPoint(
Object.assign({}, injectees.$user.mouse),
),
);
}
} else {
injectees.$user = {
mouse: {
x: 1,
y: 1,
down: 0,
buttons: [0, 0, 0],
},
pan: {
x: 0,
y: 0,
},
keys: {},
touches: [],
mouches: [],
};
}
},
};
const getRepeatHostNode = (node) => {
if (!node) {
return;
}
if (node.__memory.repeatee) {
return node;
}
return getRepeatHostNode(node.__memory && node.__memory.parent);
};
const getIfHostNode = (node) => {
if (!node) {
return;
}
if (node.__memory.if) {
return node;
}
return getIfHostNode(node.__memory && node.__memory.parent);
};
INJECTABLES.$flow = {
schema: {},
summon (injectees, component: HaikuComponent, node) {
if (!injectees.$flow) {
injectees.$flow = {};
}
const repeatNode = getRepeatHostNode(node);
injectees.$flow.repeat = (repeatNode && repeatNode.__memory.repeatee) || {
instructions: [],
payload: {},
source: repeatNode,
index: 0,
};
const ifNode = getIfHostNode(node);
injectees.$flow.if = (ifNode && ifNode.__memory.if) || {
answer: null,
};
injectees.$flow.placeholder = node.__memory.placeholder || {
value: null,
surrogate: null,
};
},
};
INJECTABLES.$repeat = {
schema: {},
summon (injectees, component: HaikuComponent, node) {
if (!injectees.$repeat) {
injectees.$repeat = {};
}
const repeatNode = getRepeatHostNode(node);
injectees.$repeat = (repeatNode && repeatNode.__memory.repeatee) || {
instructions: [],
payload: {},
source: repeatNode,
index: 0,
};
},
};
INJECTABLES.$if = {
schema: {},
summon (injectees, component: HaikuComponent, node) {
if (!injectees.$if) {
injectees.$if = {};
}
const ifNode = getIfHostNode(node);
injectees.$if = (ifNode && ifNode.__memory.if) || {
answer: null,
};
},
};
INJECTABLES.$placeholder = {
schema: {},
summon (injectees, component: HaikuComponent, node) {
if (!injectees.$placeholder) {
injectees.$placeholder = {};
}
injectees.$placeholder = node.__memory.placeholder || {
value: null,
surrogate: null,
};
},
};
INJECTABLES.$index = {
schema: {},
summon (injectees, component: HaikuComponent, node) {
const repeatNode = getRepeatHostNode(node);
injectees.$index = (
repeatNode &&
repeatNode.__memory.repeatee &&
repeatNode.__memory.repeatee.index
) || 0;
},
};
INJECTABLES.$payload = {
schema: {},
summon (injectees, component: HaikuComponent, node) {
const repeatNode = getRepeatHostNode(node);
injectees.$payload = (
repeatNode &&
repeatNode.__memory.repeatee &&
repeatNode.__memory.repeatee.payload
) || {};
},
};
INJECTABLES.$helpers = {
schema: {
now: 'function',
rand: 'function',
find: 'function',
},
summon (injectees, component: HaikuComponent) {
injectees.$helpers = component.helpers;
},
};
// List of JavaScript global built-in objects that we want to provide as an injectable.
// In the future, we might end up passing in modified versions of these objects/functions.
const BUILTIN_INJECTABLES = {
Infinity,
NaN,
Object,
Boolean,
Math,
Date,
JSON,
Number,
String,
RegExp,
Array,
isFinite,
isNaN,
parseFloat,
parseInt,
decodeURI,
decodeURIComponent,
encodeURI,
encodeURIComponent,
// escape,
// unescape,
Error,
ReferenceError,
SyntaxError,
TypeError,
undefined: void (0),
// TODO: Determine which of the following to include. Need to test each for support.
// 'Int8Array': Int8Array,
// 'Uint8Array': Uint8Array,
// 'Uint8ClampedArray': Uint8ClampedArray,
// 'Int16Array': Int16Array,
// 'Uint16Array': Uint16Array,
// 'Int32Array': Int32Array,
// 'Uint32Array': Uint32Array,
// 'Float32Array': Float32Array,
// 'Float64Array': Float64Array,
// 'ArrayBuffer': ArrayBuffer,
// 'URIError': URIError
// 'RangeError': RangeError,
// 'InternalError': InternalError,
// 'Map': Map,
// 'Set': Set,
// 'WeakMap': WeakMap,
// 'WeakSet': WeakSet,
// 'SIMD ': SIMD,
// 'SharedArrayBuffer ': SharedArrayBuffer,
// 'Atomics ': Atomics ,
// 'DataView': DataView,
// 'Promise': Promise,
// 'Generator': Generator,
// 'GeneratorFunction': GeneratorFunction,
// 'AsyncFunction': AsyncFunction,
// 'Reflection': Reflection,
// 'Reflect': Reflect,
// 'Proxy': Proxy,
// 'Intl': Intl,
// 'WebAssembly': WebAssembly,
// 'Iterator ': Iterator,
// 'ParallelArray ': ParallelArray,
// 'StopIteration': StopIteration
};
for (const builtinInjectableKey in BUILTIN_INJECTABLES) {
INJECTABLES[builtinInjectableKey] = {
summon (injectees) {
injectees[builtinInjectableKey] = BUILTIN_INJECTABLES[builtinInjectableKey];
},
};
}
/**
* When evaluating expressions written by the user, don't crash everything.
* Log the error (but only once, since we're animating) and then return a
* fairly safe all-purpose value (1).
*/
const safeCall = (fn, hostInstance, hostStates) => {
try {
return fn.call(hostInstance, hostStates);
} catch (exception) {
consoleErrorOnce(exception);
return 1;
}
};
const safeApply = (fn, hostInstance, summoneesArray) => {
try {
return fn.apply(hostInstance, summoneesArray);
} catch (exception) {
consoleErrorOnce(exception);
return 1;
}
};
const areSummoneesDifferent = (previous: any, incoming: any): boolean => {
if (Array.isArray(previous) && Array.isArray(incoming)) {
if (previous.length !== incoming.length) {
return true;
}
// Do a shallow comparison of elements. We don't go deep because:
// - It easily becomes too expensive to do this while rendering
// - We can avoid needing to check for recursion
for (let i = 0; i < previous.length; i++) {
// Assume that objects are different since we don't want to do a deep comparison
if (previous[i] && typeof previous[i] === 'object') {
return true;
}
if (previous[i] !== incoming[i]) {
return true;
}
}
for (let j = 0; j < previous.length; j++) {
// Assume that objects are different since we don't want to do a deep comparison
if (incoming[j] && typeof incoming[j] === 'object') {
return true;
}
if (incoming[j] !== previous[j]) {
return true;
}
}
return false;
}
if (typeof previous === OBJECT && typeof incoming === OBJECT) {
if (previous === null && incoming === null) {
return false;
}
if (previous === null) {
return true;
}
if (incoming === null) {
return true;
}
// Do a shallow comparison of properties. We don't go deep because:
// - It easily becomes too expensive to do this while rendering
// - We can avoid needing to check for recursion
for (const pkey in previous) {
if (previous[pkey] !== incoming[pkey]) {
return true;
}
}
for (const ikey in incoming) {
if (incoming[ikey] !== previous[ikey]) {
return true;
}
}
return false;
}
return previous !== incoming;
};
const stringToInt = (str) => {
let hash = 5381;
let i = str.length;
while (i) {
hash = (hash * 33) ^ str.charCodeAt(--i);
}
return hash >>> 0;
}; | the_stack |
import { HandlerContext } from "@atomist/automation-client/lib/HandlerContext";
import { Project } from "@atomist/automation-client/lib/project/Project";
import { logger } from "@atomist/automation-client/lib/util/logger";
import * as k8s from "@kubernetes/client-node";
import * as dockerfileParser from "docker-file-parser";
import * as stringify from "json-stringify-safe";
import * as _ from "lodash";
import { DeepPartial } from "ts-essentials";
import { goalData } from "../../../api-helper/goal/sdmGoal";
import { GoalInvocation } from "../../../api/goal/GoalInvocation";
import { SdmGoalEvent } from "../../../api/goal/SdmGoalEvent";
import { readSdmVersion } from "../../../core/delivery/build/local/projectVersioner";
import { validName } from "../kubernetes/name";
import { KubernetesApplication } from "../kubernetes/request";
import { K8sDefaultNamespace } from "../support/namespace";
import { KubernetesDeployFulfillerGoalName } from "./fulfiller";
import {
goalEventSlug,
KubernetesDeploy,
KubernetesDeployDataSources,
KubernetesDeployRegistration,
} from "./goal";
import { loadKubernetesSpec } from "./spec";
/**
* JSON propery under the goal event data where the
* [[KubernetesDeployment]] goal [[KubernetesApplication]] data are
* stored, i.e., the value of `goal.data[sdmPackK8s]`.
*/
export const sdmPackK8s = "@atomist/sdm-pack-k8s";
/**
* Generate KubernetesApplication from goal, goal registration,
* project, and goal invocation. The priority of the various sources
* of KubernetesApplication data are, from lowest to highest:
*
* 1. Starting point is `{ ns: defaultNamespace }`
* 2. [[KubernetesDeployDataSources.SdmConfiguration]]
* 3. [[defaultKubernetesApplication]]
* 4. [[KubernetesDeployDataSources.Dockerfile]]
* 5. The various partial Kubernetes specs under `.atomist/kubernetes`
* 6. [[KubernetesDeployDataSources.GoalEvent]]
* 7. [[KubernetesDeployRegistration.applicationData]]
*
* Specific sources can be enabled/disabled via the
* [[KubernetesDeployRegistration.dataSources]].
*
* @param k8Deploy Kubernetes deployment goal
* @param registration Goal registration/configuration for `k8Deploy`
* @param goalInvocation The Kubernetes deployment goal currently triggered.
* @return The SdmGoalEvent augmented with [[KubernetesApplication]] in the data
*/
export function generateKubernetesGoalEventData(
k8Deploy: KubernetesDeploy,
registration: KubernetesDeployRegistration,
goalInvocation: GoalInvocation,
): Promise<SdmGoalEvent> {
return k8Deploy.sdm.configuration.sdm.projectLoader.doWithProject({ ...goalInvocation, readOnly: true }, async p => {
const { context, goalEvent } = goalInvocation;
const sdmConfigAppData: Partial<KubernetesApplication> = (registration.dataSources.includes(KubernetesDeployDataSources.SdmConfiguration)) ?
_.get(k8Deploy, "sdm.configuration.sdm.k8s.app", {}) : {};
const defaultAppData: Partial<KubernetesApplication> = await defaultKubernetesApplication(goalEvent, k8Deploy, context);
const dockerfileAppData: Partial<KubernetesApplication> = (registration.dataSources.includes(KubernetesDeployDataSources.Dockerfile)) ?
await dockerfileKubernetesApplication(p) : {};
const specAppData: Partial<KubernetesApplication> = await repoSpecsKubernetsApplication(p, registration);
const mergedAppData = _.merge({ ns: K8sDefaultNamespace }, sdmConfigAppData, defaultAppData, dockerfileAppData, specAppData);
const eventAppData: any = {};
eventAppData[sdmPackK8s] = mergedAppData;
if (registration.dataSources.includes(KubernetesDeployDataSources.GoalEvent)) {
const slug = goalEventSlug(goalEvent);
let eventData: any;
try {
eventData = goalData(goalEvent);
} catch (e) {
logger.warn(`Failed to parse goal event data for ${slug} as JSON: ${e.message}`);
logger.warn(`Ignoring current value of goal event data: ${goalEvent.data}`);
eventData = {};
}
_.merge(eventAppData, eventData);
}
if (registration.applicationData) {
const callbackAppData = await registration.applicationData(eventAppData[sdmPackK8s], p, k8Deploy, goalEvent, context);
eventAppData[sdmPackK8s] = callbackAppData;
}
goalEvent.data = JSON.stringify(eventAppData);
goalEvent.fulfillment = {
method: "sdm",
name: KubernetesDeployFulfillerGoalName,
registration: registration.name,
};
return goalEvent;
});
}
/**
* Fetch [[KubernetesApplication]] from goal event. If the goal event
* does not contain Kubernetes application information in its data
* property, `undefined` is returned. If the value of the goal event
* data cannot be parsed as JSON, an error is thrown.
*
* @param goalEvent SDM goal event to retrieve the Kubernetes application data from
* @return Parsed [[KubernetesApplication]] object
*/
export function getKubernetesGoalEventData(goalEvent: SdmGoalEvent): KubernetesApplication | undefined {
let data: any;
try {
data = goalData(goalEvent);
} catch (e) {
logger.error(e.message);
throw e;
}
return data[sdmPackK8s];
}
/**
* Given the goal event, [[KubernetesDeploy]] goal, and
* handler context generate a default [[KubernetesApplication]] object.
*
* This function uses [[defaultImage]] to determine the image.
*
* @param goalEvent SDM Kubernetes deployment goal event
* @param k8Deploy Kubernetes deployment goal configuration
* @param context Handler context
* @return a valid default KubernetesApplication for this SDM goal deployment event
*/
export async function defaultKubernetesApplication(
goalEvent: SdmGoalEvent,
k8Deploy: KubernetesDeploy,
context: HandlerContext,
): Promise<Partial<KubernetesApplication>> {
const workspaceId = context.workspaceId;
const name = validName(goalEvent.repo.name);
const image = await defaultImage(goalEvent, k8Deploy, context);
return {
workspaceId,
name,
image,
};
}
/**
* Parse Dockerfile and return port of first argument to the first
* EXPOSE command. it can suggessfully convert to an integer. If
* there are no EXPOSE commands or if it cannot successfully convert
* the EXPOSE arguments to an integer, `undefined` is returned.
*
* @param p Project to look for Dockerfile in
* @return port number or `undefined` if no EXPOSE commands are found
*/
export async function dockerPort(p: Project): Promise<number | undefined> {
const dockerFile = await p.getFile("Dockerfile");
if (dockerFile) {
const dockerFileContents = await dockerFile.getContent();
const commands = dockerfileParser.parse(dockerFileContents, { includeComments: false });
const exposeCommands = commands.filter(c => c.name === "EXPOSE");
for (const exposeCommand of exposeCommands) {
if (Array.isArray(exposeCommand.args)) {
for (const arg of exposeCommand.args) {
const port = parseInt(arg, 10);
if (!isNaN(port)) {
return port;
}
}
} else if (typeof exposeCommand.args === "string") {
const port = parseInt(exposeCommand.args, 10);
if (!isNaN(port)) {
return port;
}
} else {
logger.warn(`Unexpected EXPOSE argument type '${typeof exposeCommand.args}': ${stringify(exposeCommand.args)}`);
}
}
}
return undefined;
}
/** Package return of [[dockerPort]] in [[KubernetesApplication]]. */
async function dockerfileKubernetesApplication(p: Project): Promise<Partial<KubernetesApplication>> {
const port = await dockerPort(p);
return (port) ? { port } : {};
}
/**
* Read configured Kubernetes partial specs from repository.
*
* @param p Project to look for specs
* @param registration Configuration of KubernetesDeploy goal
* @return KubernetesApplication object with requested specs populated
*/
export async function repoSpecsKubernetsApplication(p: Project, r: KubernetesDeployRegistration): Promise<Partial<KubernetesApplication>> {
const deploymentSpec: DeepPartial<k8s.V1Deployment> = (r.dataSources.includes(KubernetesDeployDataSources.DeploymentSpec)) ?
await loadKubernetesSpec(p, "deployment") : undefined;
const serviceSpec: DeepPartial<k8s.V1Service> = (r.dataSources.includes(KubernetesDeployDataSources.ServiceSpec)) ?
await loadKubernetesSpec(p, "service") : undefined;
const ingressSpec: DeepPartial<k8s.NetworkingV1beta1Ingress> = (r.dataSources.includes(KubernetesDeployDataSources.IngressSpec)) ?
await loadKubernetesSpec(p, "ingress") : undefined;
const roleSpec: DeepPartial<k8s.V1Role> = (r.dataSources.includes(KubernetesDeployDataSources.RoleSpec)) ?
await loadKubernetesSpec(p, "role") : undefined;
const serviceAccountSpec: DeepPartial<k8s.V1ServiceAccount> = (r.dataSources.includes(KubernetesDeployDataSources.ServiceAccountSpec)) ?
await loadKubernetesSpec(p, "service-account") : undefined;
const roleBindingSpec: DeepPartial<k8s.V1RoleBinding> = (r.dataSources.includes(KubernetesDeployDataSources.RoleBindingSpec)) ?
await loadKubernetesSpec(p, "role-binding") : undefined;
return {
deploymentSpec,
serviceSpec,
ingressSpec,
roleSpec,
serviceAccountSpec,
roleBindingSpec,
};
}
/**
* Remove any invalid characters from Docker image name component
* `name` to make it a valid Docker image name component. If
* `hubOwner` is true, it ensures the name contains only alphanumeric
* characters.
*
* From https://docs.docker.com/engine/reference/commandline/tag/:
*
* > An image name is made up of slash-separated name components,
* > optionally prefixed by a registry hostname. The hostname must
* > comply with standard DNS rules, but may not contain
* > underscores. If a hostname is present, it may optionally be
* > followed by a port number in the format :8080. If not present,
* > the command uses Docker’s public registry located at
* > registry-1.docker.io by default. Name components may contain
* > lowercase letters, digits and separators. A separator is defined
* > as a period, one or two underscores, or one or more dashes. A
* > name component may not start or end with a separator.
* >
* > A tag name must be valid ASCII and may contain lowercase and
* > uppercase letters, digits, underscores, periods and dashes. A tag
* > name may not start with a period or a dash and may contain a
* > maximum of 128 characters.
*
* @param name Name component to clean up.
* @param hubOwner If `true` only allow characters valid for a Docker Hub user/org
* @return Valid Docker image name component.
*/
function dockerImageNameComponent(name: string, hubOwner: boolean = false): string {
const cleanName = name.toLocaleLowerCase()
.replace(/^[^a-z0-9]+/, "")
.replace(/[^a-z0-9]+$/, "")
.replace(/[^-_/.a-z0-9]+/g, "");
if (hubOwner) {
return cleanName.replace(/[^a-z0-9]+/g, "");
} else {
return cleanName;
}
}
/**
* Determine the best default value for the image property for this
* Kubernetes deployment goal event. If there is no image associated
* with the after commit of the push, it checks if a Docker registry
* is provided at `sdm.configuration.sdm.docker.registry` and uses
* that and the repo name to return an image. If neither of those
* exist, a Docker Hub-like image name generated from the repository
* owner and name. In the latter two cases, it tries to read a
* version for this commit from the graph. If it exists it uses it at
* the image tag. If it does not, it uses the tag "latest".
*
* @param goalEvent SDM Kubernetes deployment goal event
* @param k8Deploy Kubernetes deployment goal object
* @param context Handler context
* @return Docker image associated with goal push after commit, or best guess
*/
export async function defaultImage(goalEvent: SdmGoalEvent, k8Deploy: KubernetesDeploy, context: HandlerContext): Promise<string> {
if (goalEvent.push && goalEvent.push.after && goalEvent.push.after.images && goalEvent.push.after.images.length > 0) {
return goalEvent.push.after.images[0].imageName;
}
const slug = goalEventSlug(goalEvent);
let version: string;
try {
version = await readSdmVersion(goalEvent.repo.owner, goalEvent.repo.name, goalEvent.repo.providerId, goalEvent.sha,
goalEvent.branch, context);
} catch (e) {
logger.warn(`Failed to read version for goal ${slug}:${goalEvent.sha}: ${e.message}`);
}
if (!version) {
version = "latest";
}
const tag = version.replace(/^[-.]/, "").replace(/[^-.\w]+/, "").substring(0, 128);
const dockerName = dockerImageNameComponent(goalEvent.repo.name);
const registry = _.get(k8Deploy, "sdm.configuration.sdm.build.docker.registry", dockerImageNameComponent(goalEvent.repo.owner, true));
return `${registry}/${dockerName}:${tag}`;
} | the_stack |
import { Component, OnInit, OnDestroy, ViewChild, KeyValueChanges, KeyValueDiffer, KeyValueDiffers } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { MatDialog, MatDialogRef } from '@angular/material/dialog';
import { IndexeddbService } from '../indexeddb.service';
import { DialogPassComponent } from '../dialog-pass/dialog-pass.component';
import { DialogAddissueComponent } from '../dialog-addissue/dialog-addissue.component';
import { Router } from '@angular/router';
import { Subscription } from 'rxjs';
import { MessageService } from '../message.service';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { DialogImportComponent } from '../dialog-import/dialog-import.component';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { DialogEditComponent } from '../dialog-edit/dialog-edit.component';
import { DialogExportissuesComponent } from '../dialog-exportissues/dialog-exportissues.component';
import { DialogChangelogComponent } from '../dialog-changelog/dialog-changelog.component';
import { DialogChangekeyComponent } from '../dialog-changekey/dialog-changekey.component';
import { DialogRemoveitemsComponent } from '../dialog-removeitems/dialog-removeitems.component';
import { DialogCvssComponent } from '../dialog-cvss/dialog-cvss.component';
import { DialogCveComponent } from '../dialog-cve/dialog-cve.component';
import { DialogCustomcontentComponent } from '../dialog-customcontent/dialog-customcontent.component';
import { DialogApierrorComponent } from '../dialog-apierror/dialog-apierror.component';
import marked from 'marked';
import { sha256 } from 'js-sha256';
import {MatSnackBar} from '@angular/material/snack-bar';
import {MatChipInputEvent} from '@angular/material/chips';
import {COMMA, ENTER} from '@angular/cdk/keycodes';
import { HttpClient } from '@angular/common/http';
import * as Crypto from 'crypto-js';
import { v4 as uuid } from 'uuid';
export interface Tags {
name: string;
}
@Component({
selector: 'app-report',
templateUrl: './report.component.html',
styleUrls: ['./report.component.scss']
})
export class ReportComponent implements OnInit, OnDestroy {
// Pie
public pieChartLabels: string[] = ['Critical', 'High', 'Medium', 'Low', 'Info'];
public chartcolors: any[] = [{
backgroundColor: ['#FF0039', '#FF7518', '#F9EE06', '#3FB618', '#2780E3']
}];
private reportDiffer: KeyValueDiffer<string, any>;
private reportDifferlogo: KeyValueDiffer<string, any>;
private reportDiffersettings: KeyValueDiffer<string, any>;
private reportTitleDiffer: KeyValueDiffer<any, any>;
private objDiffers: Array<KeyValueDiffer<string, any>>;
private objDiffersFiles: Array<KeyValueDiffer<string, any>>;
private objDiffersResearcher: Array<KeyValueDiffer<string, any>>;
public pieChartData: number[] = [0, 0, 0, 0, 0];
public pieChartType = 'pie';
dialogRef: MatDialogRef<DialogPassComponent>;
displayedColumns: string[] = ['date', 'desc', 'settings'];
dataSource = new MatTableDataSource();
listchangelog: any[];
@ViewChild(MatSort) sort: MatSort;
@ViewChild(MatPaginator) paginator: MatPaginator;
advhtml = '';
report_css: any;
bugbountylist = [];
report_id: string;
report_info: any;
lastsavereportdata = '';
reportdesc: any;
selecteditem = false;
BBmsg = '';
selecteditems = [];
selected3 = [];
ReportProfilesList = [];
pok = 0;
timerCounter = 0;
savemsg = '';
report_decryption_in_progress: boolean;
report_encryption_in_progress: boolean;
upload_in_progress = false;
youhaveunsavedchanges = false;
decryptedReportData: any;
decryptedReportDataChanged: any;
subscription: Subscription;
displayedSeverityColumns: string[] = ['severity', 'count'];
dataSourceforseverity = [
{ severity: 'Critical', count: 0 },
{ severity: 'High', count: 0 },
{ severity: 'Medium', count: 0 },
{ severity: 'Low', count: 0 },
{ severity: 'Info', count: 0 }
];
issueStatus = [
{ status: 'Open (Waiting for review)', value: 1},
{ status: 'Fix In Progress', value: 2},
{ status: 'Fixed', value: 3},
{ status: 'Won\'t Fix', value: 4}
];
selectedtheme = 'white';
uploadlogoprev = '';
adv_html: any;
advlogo: any;
advlogo_saved: any;
visible = true;
selectable = true;
removable = true;
addOnBlur = true;
readonly separatorKeysCodes = [ENTER, COMMA] as const;
constructor(private route: ActivatedRoute,
public dialog: MatDialog,
private http: HttpClient,
private indexeddbService: IndexeddbService,
private differs: KeyValueDiffers,
public router: Router,
private messageService: MessageService,
private snackBar: MatSnackBar) {
// console.log(route);
this.subscription = this.messageService.getDecrypted().subscribe(message => {
this.decryptedReportData = message;
this.decryptedReportDataChanged = this.decryptedReportData;
this.adv_html = this.decryptedReportDataChanged.report_settings.report_html;
this.advlogo_saved = this.decryptedReportDataChanged.report_settings.report_logo.logo;
this.reportDiffer = this.differs.find(this.decryptedReportData).create();
this.reportDifferlogo = this.differs.find({report_logo: this.decryptedReportDataChanged.report_settings.report_logo.logo}).create();
this.reportDiffersettings = this.differs.find(this.decryptedReportDataChanged.report_settings).create();
this.objDiffers = new Array<KeyValueDiffer<string, any>>();
this.decryptedReportDataChanged.report_vulns.forEach((itemGroup, index) => {
this.objDiffers[index] = this.differs.find(itemGroup).create();
});
this.objDiffersFiles = new Array<KeyValueDiffer<string, any>>();
this.decryptedReportDataChanged.report_vulns.forEach((itemGroup, index) => {
this.objDiffersFiles[index] = this.differs.find(itemGroup.files).create();
});
this.objDiffersResearcher = new Array<KeyValueDiffer<string, any>>();
this.decryptedReportDataChanged.researcher.forEach((itemGroup, index) => {
this.objDiffersResearcher[index] = this.differs.find(itemGroup).create();
});
if (this.report_info) {
this.reportTitleDiffer = this.differs.find({report_name: this.report_info.report_name}).create();
}
this.doStats();
let i = 0;
do {
this.selected3.push(false);
i++;
}
while (i < this.decryptedReportDataChanged.report_vulns.length);
});
}
ngOnInit() {
this.report_id = this.route.snapshot.params['report_id'];
// check if report exist
this.indexeddbService.checkifreportexist(this.report_id).then(data => {
if (data) {
console.log('Report exist: OK');
this.report_info = data;
this.reportdesc = data;
// check if pass in sessionStorage
if (sessionStorage.getItem(data.report_id) !== null) {
this.report_decryption_in_progress = true;
const pass = sessionStorage.getItem(data.report_id);
this.indexeddbService.decrypt(pass, data.report_id).then(returned => {
if (returned) {
this.report_decryption_in_progress = false;
}
});
} else {
setTimeout(_ => this.openDialog(data)); // BUGFIX: https://github.com/angular/angular/issues/6005#issuecomment-165911194
}
} else {
console.log('Report not exist locally: YES');
this.indexeddbService.checkAPIreport(this.report_id).then(re => {
if (re) {
this.report_info = re;
this.reportdesc = re;
// check if pass in sessionStorage
if (sessionStorage.getItem(re.report_id) !== null) {
this.report_decryption_in_progress = true;
const pass = sessionStorage.getItem(re.report_id);
if (this.indexeddbService.decodeAES(re, pass)) {
this.report_decryption_in_progress = false;
}
} else {
setTimeout(_ => this.openDialog(re)); // BUGFIX: https://github.com/angular/angular/issues/6005#issuecomment-165911194
}
} else {
this.router.navigate(['/my-reports']);
}
});
}
});
// get css style
this.http.get('/assets/bootstrap.min.css', {responseType: 'text'}).subscribe(res => {
this.report_css = res;
});
// get bug bountys programs list, full credits: https://github.com/projectdiscovery/public-bugbounty-programs
this.http.get<any>('/assets/chaos-bugbounty-list.json?v=' + + new Date()).subscribe(res => {
this.bugbountylist = res.programs;
});
// get report profiles
this.indexeddbService.retrieveReportProfile().then(ret => {
if (ret) {
this.ReportProfilesList = ret;
}
});
}
dataChanged(changes: KeyValueChanges<any, any[]>) {
/* If you want to see details then use
changes.forEachRemovedItem((record) => ...);
changes.forEachAddedItem((record) => ...);
changes.forEachChangedItem((record) => ...);
*/
changes.forEachAddedItem((record) => {
// console.log('ADDED: ',record);
if (record.previousValue !== null) {
this.afterDetection();
}
});
changes.forEachChangedItem((record) => {
// console.log('CHANGED: ',record);
if (record.key !== 'report_version') {
// console.log('Detection start');
this.afterDetection();
}
});
}
callListener(e) {
e.preventDefault();
e.returnValue = '';
}
timeout(e) {
e.preventDefault();
e.returnValue = '';
}
sureYouWanttoLeave() {
window.addEventListener('beforeunload', this.callListener, true);
this.youhaveunsavedchanges = true;
}
removeSureYouWanttoLeave() {
window.removeEventListener('beforeunload', this.callListener, true);
this.youhaveunsavedchanges = false;
let id = window.setTimeout(function() {}, 0);
while (id--) {
window.clearTimeout(id); // will do nothing if no timeout with id is present
}
}
afterDetectionNow() {
console.log('fired');
this.reportDiffer = this.differs.find(this.decryptedReportData).create();
this.reportDifferlogo = this.differs.find({report_logo: this.decryptedReportDataChanged.report_settings.report_logo.logo}).create();
this.reportDiffersettings = this.differs.find({...this.decryptedReportDataChanged.report_settings}).create();
this.objDiffers = new Array<KeyValueDiffer<string, any>>();
this.decryptedReportDataChanged.report_vulns.forEach((itemGroup, index) => {
this.objDiffers[index] = this.differs.find(itemGroup).create();
});
this.objDiffersFiles = new Array<KeyValueDiffer<string, any>>();
this.decryptedReportDataChanged.report_vulns.forEach((itemGroup, index) => {
this.objDiffersFiles[index] = this.differs.find(itemGroup.files).create();
});
this.objDiffersResearcher = new Array<KeyValueDiffer<string, any>>();
this.decryptedReportDataChanged.researcher.forEach((itemGroup, index) => {
this.objDiffersResearcher[index] = this.differs.find(itemGroup).create();
});
if (this.report_info) {
this.reportTitleDiffer = this.differs.find({report_name: this.report_info.report_name}).create();
}
this.sureYouWanttoLeave();
}
afterDetection() {
if (this.timerCounter >= 60) {
setTimeout(() => { this.afterDetectionNow() }, 10000);
this.timerCounter = 0;
}
this.timerCounter++;
this.sureYouWanttoLeave();
}
ngDoCheck(): void {
if (this.decryptedReportDataChanged) {
const changes = this.reportDiffer.diff(this.decryptedReportDataChanged);
if (changes) {
this.dataChanged(changes);
}
if (this.reportDifferlogo) {
const changeslogo = this.reportDifferlogo.diff({report_logo: this.decryptedReportDataChanged.report_settings.report_logo.logo});
if (changeslogo) {
this.dataChanged(changeslogo);
}
}
if (this.reportDiffersettings) {
const changessettings = this.reportDiffersettings.diff(this.decryptedReportDataChanged.report_settings);
if (changessettings) {
this.dataChanged(changessettings);
}
}
if (this.objDiffers) {
this.decryptedReportDataChanged.report_vulns.forEach((itemGroup, index) => {
if (this.objDiffers[index]) {
const objDiffer = this.objDiffers[index];
const objChanges = objDiffer.diff(itemGroup);
if (objChanges) {
this.dataChanged(objChanges);
}
}
});
}
if (this.objDiffersFiles) {
this.decryptedReportDataChanged.report_vulns.forEach((itemGroup, index) => {
if (this.objDiffersFiles[index]) {
const objDiffer2 = this.objDiffersFiles[index];
const objChanges2 = objDiffer2.diff(itemGroup.files);
if (objChanges2) {
this.dataChanged(objChanges2);
}
}
});
}
if (this.objDiffersResearcher) {
this.decryptedReportDataChanged.researcher.forEach((itemGroup, index) => {
if (this.objDiffersResearcher[index]) {
const objDiffer3 = this.objDiffersResearcher[index];
const objChanges3 = objDiffer3.diff(itemGroup);
if (objChanges3) {
this.dataChanged(objChanges3);
}
}
});
}
}
if (this.reportTitleDiffer && this.report_info) {
const changesName = this.reportTitleDiffer.diff({report_name: this.report_info.report_name});
if (changesName) {
this.dataChanged(changesName);
}
}
}
// events
public chartClicked(e: any): void {
// console.log(e);
}
public chartHovered(e: any): void {
// console.log(e);
}
toggle() {
if (this.selected3.indexOf(true) !== -1) {
this.pok = 1;
} else {
this.pok = 0;
}
}
selectall() {
this.selecteditems = [];
this.selected3 = [];
let i = 0;
do {
this.selected3.push(true);
i++;
}
while (i < this.decryptedReportDataChanged.report_vulns.length);
}
deselectall() {
this.selecteditems = [];
this.selected3 = [];
this.pok = 0;
let i = 0;
do {
this.selected3.push(false);
i++;
}
while (i < this.decryptedReportDataChanged.report_vulns.length);
}
removeSelecteditems(array) {
const dialogRef = this.dialog.open(DialogRemoveitemsComponent, {
width: '400px',
data: { sel: array, orig: this.decryptedReportDataChanged.report_vulns }
});
dialogRef.afterClosed().subscribe(result => {
if (result) {
result.forEach(eachObj => {
const index: number = this.decryptedReportDataChanged.report_vulns.indexOf(eachObj);
if (index !== -1) {
this.decryptedReportDataChanged.report_vulns.splice(index, 1);
this.addtochangelog('Remove issue: ' + eachObj.title);
this.afterDetectionNow();
}
});
this.deselectall();
this.doStats();
}
});
}
openDialogCVSS(data: any): void {
const dialogRef = this.dialog.open(DialogCvssComponent, {
width: '800px',
disableClose: false,
data: data
});
dialogRef.afterClosed().subscribe(result => {
console.log('The CVSS dialog was closed');
this.doStats();
});
}
openDialogCVE(data: any): void {
const dialogRef = this.dialog.open(DialogCveComponent, {
width: '600px',
disableClose: false,
data: data
});
dialogRef.afterClosed().subscribe(result => {
console.log('The CVE dialog was closed');
});
}
openDialog(data: any): void {
const dialogRef = this.dialog.open(DialogPassComponent, {
width: '400px',
disableClose: true,
data: data
});
dialogRef.afterClosed().subscribe(result => {
console.log('The security key dialog was closed');
});
}
addtablescope(): void {
this.decryptedReportDataChanged.report_scope = this.decryptedReportDataChanged.report_scope + ' \
\n\
IP | hostname | role | comments\n\
------|--------------|-------|---------------\n\
127.0.0.1 | localhost.localdomain | PROD | client asked to test this one with care\n\
255.255.255.255 | N/A | DMZ | test you can go do whatever you want on it\n\
';
}
addcodescope(): void {
this.decryptedReportDataChanged.report_scope = this.decryptedReportDataChanged.report_scope + ' \
\n\
```\n\
Sample code here\n\
```\n\
';
}
doStats() {
const critical = this.decryptedReportDataChanged.report_vulns.filter(function (el) {
return (el.severity === 'Critical');
});
const high = this.decryptedReportDataChanged.report_vulns.filter(function (el) {
return (el.severity === 'High');
});
const medium = this.decryptedReportDataChanged.report_vulns.filter(function (el) {
return (el.severity === 'Medium');
});
const low = this.decryptedReportDataChanged.report_vulns.filter(function (el) {
return (el.severity === 'Low');
});
const info = this.decryptedReportDataChanged.report_vulns.filter(function (el) {
return (el.severity === 'Info');
});
this.dataSourceforseverity = [
{ severity: 'Critical', count: critical.length },
{ severity: 'High', count: high.length },
{ severity: 'Medium', count: medium.length },
{ severity: 'Low', count: low.length },
{ severity: 'Info', count: info.length }
];
this.pieChartData = [critical.length, high.length, medium.length, low.length, info.length];
this.listchangelog = this.decryptedReportData.report_changelog;
this.dataSource = new MatTableDataSource(this.decryptedReportData.report_changelog);
setTimeout(() => this.dataSource.sort = this.sort);
setTimeout(() => this.dataSource.paginator = this.paginator);
// this.reportdesc.report_lastupdate = this.decryptedReportDataChanged.report_lastupdate;
}
addissue() {
console.log('Add issue');
const dialogRef = this.dialog.open(DialogAddissueComponent, {
width: '600px'
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
if (result !== undefined) {
if (result.title !== '') {
this.decryptedReportDataChanged.report_vulns.push(result);
this.addtochangelog('Create issue: ' + result.title);
this.afterDetectionNow();
this.doStats();
}
}
});
}
import_issues() {
console.log('Import issues');
const dialogRef = this.dialog.open(DialogImportComponent, {
width: '500px'
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
if (result !== undefined) {
result.forEach(eachObj => {
if (eachObj.title !== '' && eachObj.title !== undefined && eachObj.cvss !== 'Active') {
this.decryptedReportDataChanged.report_vulns.push(eachObj);
this.addtochangelog('Create issue: ' + eachObj.title);
this.afterDetectionNow();
}
});
this.doStats();
}
});
}
export_by_severity(exportitem, severity) {
const bySeverity = exportitem.filter(item => item.severity === severity);
if (bySeverity.length > 0) {
console.log('Export issues');
const dialogRef = this.dialog.open(DialogExportissuesComponent, {
width: '500px',
data: bySeverity
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
});
}
}
export_issues(selected, original) {
console.log('Export issues');
const selecteditems = selected.find(i => i === true);
if (selecteditems) {
const dialogRef = this.dialog.open(DialogExportissuesComponent, {
width: '500px',
data: { sel: selected, orig: original }
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
});
} else {
const dialogRef = this.dialog.open(DialogExportissuesComponent, {
width: '500px',
data: original
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
});
}
}
drop(event: CdkDragDrop<string[]>) {
moveItemInArray(this.decryptedReportDataChanged.report_vulns, event.previousIndex, event.currentIndex);
moveItemInArray(this.selecteditems, event.previousIndex, event.currentIndex);
moveItemInArray(this.selected3, event.previousIndex, event.currentIndex);
}
saveReportChanges(report_id: any) {
this.report_encryption_in_progress = true;
this.savemsg = 'Please wait, report is encrypted...';
const pass = sessionStorage.getItem(report_id);
let useAPI = false;
this.indexeddbService.getkeybyReportID(report_id).then(data => {
if (data) {
if (data.NotFound === 'NOOK') {
console.log('no locally report');
useAPI = true;
} else {
// update report
this.decryptedReportDataChanged.report_version = this.decryptedReportDataChanged.report_version + 1;
this.addtochangelog('Save report v.' + this.decryptedReportDataChanged.report_version);
// tslint:disable-next-line:max-line-length
this.indexeddbService.prepareupdatereport(this.decryptedReportDataChanged, pass, this.report_info.report_id, this.report_info.report_name, this.report_info.report_createdate, data.key).then(retu => {
if (retu) {
this.reportdesc.report_lastupdate = retu;
this.report_encryption_in_progress = false;
this.savemsg = 'All changes saved successfully!';
this.lastsavereportdata = retu;
this.doStats();
this.removeSureYouWanttoLeave();
this.snackBar.open('All changes saved successfully!', 'OK', {
duration: 3000,
panelClass: ['notify-snackbar-success']
});
}
});
}
}
}).then(() => {
if (useAPI === true) {
this.indexeddbService.searchAPIreport(this.report_info.report_id).then(ret => {
if (ret === 'API_ERROR') {
console.log('api problems');
const dialogRef = this.dialog.open(DialogApierrorComponent, {
width: '400px',
disableClose: true
});
dialogRef.afterClosed().subscribe(result => {
if (result === 'tryagain') {
console.log('User select: try again');
this.saveReportChanges(this.report_info.report_id);
}
if (result === 'savelocally') {
console.log('User select: save locally');
try {
this.decryptedReportDataChanged.report_version = this.decryptedReportDataChanged.report_version + 1;
this.addtochangelog('Save report v.' + this.decryptedReportDataChanged.report_version);
// Encrypt
const ciphertext = Crypto.AES.encrypt(JSON.stringify(this.decryptedReportDataChanged), pass);
const now: number = Date.now();
const to_update = {
report_id: uuid(),
report_name: this.report_info.report_name,
report_createdate: this.report_info.report_createdate,
report_lastupdate: now,
encrypted_data: ciphertext.toString()
};
this.indexeddbService.cloneReportadd(to_update).then(data => {
if (data) {
this.removeSureYouWanttoLeave();
this.router.navigate(['/my-reports']);
}
});
} catch (except) {
console.log(except);
}
}
});
} else {
this.decryptedReportDataChanged.report_version = this.decryptedReportDataChanged.report_version + 1;
this.addtochangelog('Save report v.' + this.decryptedReportDataChanged.report_version);
// tslint:disable-next-line:max-line-length
this.indexeddbService.prepareupdateAPIreport(ret.api, ret.apikey, this.decryptedReportDataChanged, pass, this.report_info.report_id, this.report_info.report_name, this.report_info.report_createdate).then(retu => {
if (retu === 'NOSPACE') {
this.savemsg = '';
this.report_encryption_in_progress = false;
} else {
this.report_encryption_in_progress = false;
this.reportdesc.report_lastupdate = retu;
this.savemsg = 'All changes saved on remote API successfully!';
this.lastsavereportdata = retu;
this.doStats();
this.removeSureYouWanttoLeave();
this.snackBar.open('All changes saved on remote API successfully!', 'OK', {
duration: 3000,
panelClass: ['notify-snackbar-success']
});
}
});
}
});
}
});
}
sortbycvss() {
this.deselectall();
this.decryptedReportDataChanged.report_vulns = this.decryptedReportDataChanged.report_vulns.sort((a, b) => b.cvss - a.cvss);
}
sortbyseverity() {
this.deselectall();
const critical = this.decryptedReportDataChanged.report_vulns.filter(function (el) {
return (el.severity === 'Critical');
});
const high = this.decryptedReportDataChanged.report_vulns.filter(function (el) {
return (el.severity === 'High');
});
const medium = this.decryptedReportDataChanged.report_vulns.filter(function (el) {
return (el.severity === 'Medium');
});
const low = this.decryptedReportDataChanged.report_vulns.filter(function (el) {
return (el.severity === 'Low');
});
const info = this.decryptedReportDataChanged.report_vulns.filter(function (el) {
return (el.severity === 'Info');
});
const merge = [...critical, ...high, ...medium, ...low, ...info];
this.decryptedReportDataChanged.report_vulns = merge;
}
addCustomcontent(item) {
const dialogRef = this.dialog.open(DialogCustomcontentComponent, {
width: '550px',
height: '450px',
data: item
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
});
}
editreporttitle(item) {
const dialogRef = this.dialog.open(DialogEditComponent, {
width: '350px',
data: item
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
if (result) {
if (result !== 'nochanges') {
this.report_info.report_name = result;
}
}
});
}
changesecuritykey(report_id: string) {
const dialogRef = this.dialog.open(DialogChangekeyComponent, {
width: '450px'
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
if (result) {
this.updateSecKey(report_id, result);
}
});
}
updateSecKey(report_id, pass) {
this.savemsg = 'Please wait, report is encrypted...';
sessionStorage.setItem(report_id, pass);
// update report
this.addtochangelog('Change report security key');
this.decryptedReportDataChanged.report_version = this.decryptedReportDataChanged.report_version + 1;
this.addtochangelog('Save report v.' + this.decryptedReportDataChanged.report_version);
this.indexeddbService.getkeybyReportID(report_id).then(data => {
if (data) {
if (data.NotFound === 'NOOK') {
console.log('no locally report');
} else {
// tslint:disable-next-line:max-line-length
this.indexeddbService.prepareupdatereport(this.decryptedReportDataChanged, pass, this.report_info.report_id, this.report_info.report_name, this.report_info.report_createdate, data.key).then(retu => {
if (retu) {
this.savemsg = 'All changes saved successfully!';
this.lastsavereportdata = retu;
this.doStats();
}
});
}
}
});
}
editissuetitle(item) {
const dialogRef = this.dialog.open(DialogEditComponent, {
width: '350px',
data: item
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
if (result) {
if (result !== 'nochanges') {
const index: number = this.decryptedReportDataChanged.report_vulns.indexOf(result);
if (index !== -1) {
this.decryptedReportDataChanged.report_vulns[index].title = result.title;
this.afterDetectionNow();
}
}
}
});
}
ngOnDestroy() {
// unsubscribe to ensure no memory leaks
this.subscription.unsubscribe();
}
addresearcher() {
const add = {
reportername: '',
reportersocial: '',
reporterwww: '',
reporteremail: ''
};
this.decryptedReportDataChanged.researcher.push(add);
this.afterDetectionNow();
}
removeresearcher(item) {
const index: number = this.decryptedReportDataChanged.researcher.indexOf(item);
if (index !== -1) {
this.decryptedReportDataChanged.researcher.splice(index, 1);
this.afterDetectionNow();
}
}
addchangelog() {
const dialogRef = this.dialog.open(DialogChangelogComponent, {
width: '500px'
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
if (result !== undefined) {
this.decryptedReportDataChanged.report_changelog.push(result);
this.doStats();
}
});
}
editchangelog(item) {
const dialogRef = this.dialog.open(DialogChangelogComponent, {
width: '500px',
data: item
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
if (result) {
const index: number = this.decryptedReportDataChanged.report_changelog.indexOf(result.origi);
if (index !== -1) {
this.decryptedReportDataChanged.report_changelog[index] = { date: result.date, desc: result.desc };
this.doStats();
}
}
});
}
addtochangelog(item) {
const today: number = Date.now();
const add_changelog = {
date: today,
desc: item
};
this.decryptedReportDataChanged.report_changelog.push(add_changelog);
this.doStats();
}
removefromchangelog(item) {
const remo = 'changelog';
const dialogRef = this.dialog.open(DialogEditComponent, {
width: '350px',
data: [{ remo }, { item }],
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
const index: number = this.decryptedReportDataChanged.report_changelog.indexOf(result);
if (index !== -1) {
this.decryptedReportDataChanged.report_changelog.splice(index, 1);
this.doStats();
}
});
}
removeIssiue(item) {
const remo = 'remove';
const dialogRef = this.dialog.open(DialogEditComponent, {
width: '350px',
data: [{ remo }, { item }],
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
const index: number = this.decryptedReportDataChanged.report_vulns.indexOf(result);
if (index !== -1) {
this.decryptedReportDataChanged.report_vulns.splice(index, 1);
this.addtochangelog('Remove issue: ' + result.title);
this.afterDetectionNow();
this.doStats();
}
});
}
shareReport(report_id) {
this.indexeddbService.downloadEncryptedReport(report_id);
}
downloadASCII(report_details, metadata) {
function addNewlines(str) {
return stringDivider(str, 100, '\n');
}
function stringDivider(str, width, spaceReplacer) {
if (str.length > width) {
let p = width;
for (; p > 0 && str[p] !== ' '; p--) { }
if (p > 0) {
const left = str.substring(0, p);
const right = str.substring(p + 1);
return left + spaceReplacer + stringDivider(right, width, spaceReplacer);
}
}
return str;
}
let report_ascii_head = '######################################################\n\
# Report Title: ' + metadata.report_name + '\n\
# Report ID: ' + metadata.report_id + '\n\
# Create Date: ' + new Date(metadata.report_createdate).toLocaleString() + '\n\
# Last Update: ' + new Date(metadata.report_lastupdate).toLocaleString() + '\n';
if (report_details.researcher.length > 0) {
report_ascii_head = report_ascii_head + '#####\n# Author: \n';
report_details.researcher.forEach(function (value, key) {
if (value.reportername !== '') {
report_ascii_head = report_ascii_head + '# ' + value.reportername + '';
}
if (value.reporteremail !== '') {
report_ascii_head = report_ascii_head + ' - E-mail: ' + value.reporteremail + '';
}
if (value.reportersocial !== '') {
report_ascii_head = report_ascii_head + ' - Social: ' + value.reportersocial + '';
}
if (value.reporterwww !== '') {
report_ascii_head = report_ascii_head + ' - WWW: ' + value.reporterwww + '';
}
report_ascii_head = report_ascii_head + '\n';
}, this);
}
if (report_details.report_scope !== '') {
report_ascii_head = report_ascii_head + '# Report scope: \n' + addNewlines(report_details.report_scope);
}
report_ascii_head = report_ascii_head + '######################################################\n\
# Vulnerabilities:\n\n';
let report_ascii_vulns = '';
report_details.report_vulns.forEach(function (value, key) {
report_ascii_vulns += report_ascii_vulns = '\n-> ' + Number(key + 1) + '. ' + value.title;
if (value.severity !== '') {
report_ascii_vulns = report_ascii_vulns + '\n# Severity: ' + value.severity + '\n';
}
if (value.date !== '') {
report_ascii_vulns = report_ascii_vulns + '# Find Date: ' + value.date + '\n';
}
if (value.cvss !== '') {
report_ascii_vulns = report_ascii_vulns + '# CVSS: ' + value.cvss + '\n';
}
if (value.cve !== '') {
report_ascii_vulns = report_ascii_vulns + '# CVE: ' + addNewlines(value.cve) + '\n';
}
report_ascii_vulns = report_ascii_vulns + '# Description: \n' + addNewlines(value.desc) + '\n';
if (value.poc !== '') {
report_ascii_vulns = report_ascii_vulns + '# PoC: \n' + addNewlines(value.poc) + '\n';
}
if (value.ref !== '') {
report_ascii_vulns = report_ascii_vulns + '# References: \n' + value.ref + '\n\n';
}
}, this);
const report_ascii_end = '\n# Report generated by vulnrepo.com \n######################################################\n';
const report_ascii = report_ascii_head + report_ascii_vulns + report_ascii_end;
// download ascii report
const element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(report_ascii));
element.setAttribute('download', metadata.report_name + ' ' + metadata.report_id + ' ASCII (vulnrepo.com).txt');
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
themechange(event) {
let theme = '';
if (event.value === 'dark') {
theme = '_dark';
} else {
theme = '';
}
this.http.get('/assets/bootstrap' + theme + '.min.css', {responseType: 'text'}).subscribe(res3 => {
this.report_css = res3;
});
}
embedVideo(event) {
if (event.checked === false) {
this.decryptedReportDataChanged.report_settings.report_video_embed = false;
}
if (event.checked === true) {
this.decryptedReportDataChanged.report_settings.report_video_embed = true;
}
}
removeGeninfo(event) {
if (event.checked === false) {
this.decryptedReportDataChanged.report_settings.report_remove_lastpage = false;
}
if (event.checked === true) {
this.decryptedReportDataChanged.report_settings.report_remove_lastpage = true;
}
}
removechangelogpage(event) {
if (event.checked === false) {
this.decryptedReportDataChanged.report_settings.report_changelog_page = false;
}
if (event.checked === true) {
this.decryptedReportDataChanged.report_settings.report_changelog_page = true;
}
}
parsingdescnewline(event) {
if (event.checked === false) {
this.decryptedReportDataChanged.report_settings.report_parsing_desc = false;
}
if (event.checked === true) {
this.decryptedReportDataChanged.report_settings.report_parsing_desc = true;
}
}
removeResearchers(event) {
if (event.checked === false) {
this.decryptedReportDataChanged.report_settings.report_remove_researchers = false;
}
if (event.checked === true) {
this.decryptedReportDataChanged.report_settings.report_remove_researchers = true;
}
}
removeIssuestatus(event) {
if (event.checked === false) {
this.decryptedReportDataChanged.report_settings.report_remove_issuestatus = false;
}
if (event.checked === true) {
this.decryptedReportDataChanged.report_settings.report_remove_issuestatus = true;
}
}
removetagsfromreport(event) {
if (event.checked === false) {
this.decryptedReportDataChanged.report_settings.report_remove_issuetags = false;
}
if (event.checked === true) {
this.decryptedReportDataChanged.report_settings.report_remove_issuetags = true;
}
}
DownloadHTML(report_data, report_metadata, issueStatus) {
function escapeHtml(unsafe) {
return unsafe.toString()
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function parse_newline(text) {
return text.toString().replace(/(?:\r\n|\r|\n)/g, '<br>');
}
function statusDesc(status) {
const ret = issueStatus.filter(function (el) {
return (el.value === status);
});
return ret[0].status;
}
function parse_links(text) {
const urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
// tslint:disable-next-line:no-shadowed-variable
return text.replace(urlRegex, function (url) {
return '<a target="_blank" href="' + url + '">' + url + '</a>';
});
}
let report_html = `
<html>
<head>
<meta charset="utf-8"/>
<style>
` + this.report_css + `
@import "compass/css3";
* {
padding: 0;
margin: 0;
}
body {
margin: 20 10 20 10;
}
.pagebreak { page-break-before: always; }
.label {
color: white;
display: inline-block;
font-family: verdana, sans-serif;
padding: 4px;
}
/*critical*/
.critical {
border-color: #FF0039;
background-color: #FF0039;
}
/*high*/
.high {
border-color: #FF7518;
background-color: #FF7518;
}
/*medium*/
.medium {
color: #000;
border-color: #F9EE06;
background-color: #F9EE06;
}
/*low*/
.low {
border-color: #3FB618;
background-color: #3FB618;
}
/*information*/
.info {
border-color: #2780E3;
background-color: #2780E3;
}
.strbreak {
word-break: break-word;
}
ul {
list-style-position: inside;
}
.row {
margin-left: 0px;
}
</style>
</head>
<body class="container">
<br><br>`;
// report settings
const advlogo = report_data.report_settings.report_logo.logo;
if (advlogo !== '') {
const er = '<center><img src="' + escapeHtml(advlogo) + '" width="' + escapeHtml(report_data.report_settings.report_logo.width) + '" height="' + escapeHtml(report_data.report_settings.report_logo.height) + '"></center><br><br>';
report_html = report_html + er;
}
const advhtml = report_data.report_settings.report_html;
if (advhtml !== '') {
this.advhtml = advhtml;
}
let intro = ' \
<div id="row"> \
<center> \
<div class="card border-light mb-3" style="max-width: 30rem;"> \
<div class="card-header">Security Report</div> \
<div class="card-body"> \
<h4 class="card-title">' + escapeHtml(report_metadata.report_name) + '</h4> \
<p class="card-text">Report Version: ' + escapeHtml(report_data.report_version) + '</p> \
<p class="card-text">Report ID: ' + escapeHtml(report_metadata.report_id) + '</p>';
if (report_data.report_metadata.starttest !== '' && report_data.report_metadata.endtest !== '') {
const stringToSplit = new Date(report_data.report_metadata.starttest).toLocaleString();
const x = stringToSplit.split(',');
const stringToSplit2 = new Date(report_data.report_metadata.endtest).toLocaleString();
const y = stringToSplit2.split(',');
// tslint:disable-next-line:max-line-length
const cond0 = '<p class="card-text">Date: ' + escapeHtml(x[0]) + ' - ' + escapeHtml(y[0]) + '</p>';
intro = intro + cond0;
}
const cond5 = ' \
</div> \
</div> \
</center> \
</div> \
<br> \
<br> \
<br> \
<div class="d-flex justify-content-center"><div style="width: 500px; text-align: center;" class="label Critical"><h2>CONFIDENTIAL</h2></div></div> \
<div class="pagebreak"></div> \
<br>';
intro = intro + cond5;
const tableofcontent_one = ' \
<div id="row"> \
<h2>Table of contents</h2> \
<ul class="list-group">';
let tableofcontentlist = '<li class="list-group-item d-flex justify-content-between align-items-center"> \
<a href="#Scope">Scope</a> \
</li> \
<li class="list-group-item d-flex justify-content-between align-items-center"> \
<a href="#Statistics and Risk">Statistics and Risk</a> \
</li> \
<li class="list-group-item d-flex justify-content-between align-items-center"> \
<a href="#Results">Results (' + report_data.report_vulns.length + ')</a> \
</li>';
report_data.report_vulns.forEach((item, index) => {
let tags = '';
if (report_data.report_settings.report_remove_issuetags === false) {
if (item.tags.length > 0) {
item.tags.forEach((ite, ind) => {
tags = tags + '<span style="color: #fff" class="badge rounded-pill bg-dark">' + escapeHtml(ite.name) + '</span> ';
});
}
}
tableofcontentlist = tableofcontentlist + ' \
<li class="list-group-item d-flex justify-content-between align-items-center"> \
<a href="#' + index + '"> \
<span class="label ' + escapeHtml(item.severity) + '">' + escapeHtml(item.severity) + '</span> ' + escapeHtml(item.title) + ' \
</a> \
<span>' + tags + '</span> \
</li>';
});
let summarycomment = '';
if (report_data.report_summary !== '') {
summarycomment = '<li class="list-group-item d-flex justify-content-between align-items-center"> \
<a href="#Report summary comment">Report summary comment</a> \
</li>';
}
let authors = '';
if (report_data.report_settings.report_remove_researchers === false) {
if (report_data.researcher.length > 0 && report_data.researcher[0].reportername !== '') {
authors = '<li class="list-group-item d-flex justify-content-between align-items-center"> \
<a href="#Report authors">Report authors</a> \
</li>';
}
}
let tableofcontent_1 = '';
if (report_data.report_settings.report_changelog_page === false) {
tableofcontent_1 = '<li class="list-group-item d-flex justify-content-between align-items-center"> \
<a href="#Changelog">Changelog</a> \
</li>';
}
const endtable = ' \
</ul> \
</div> \
<br> \
<div class="pagebreak"></div> \
<br><br>';
const tableofcontent = tableofcontent_one + tableofcontentlist + summarycomment + authors + tableofcontent_1 + endtable;
const critical = report_data.report_vulns.filter(function (el) {
return (el.severity === 'Critical');
});
const high = report_data.report_vulns.filter(function (el) {
return (el.severity === 'High');
});
const medium = report_data.report_vulns.filter(function (el) {
return (el.severity === 'Medium');
});
const low = report_data.report_vulns.filter(function (el) {
return (el.severity === 'Low');
});
const info = report_data.report_vulns.filter(function (el) {
return (el.severity === 'Info');
});
const stats = '<table class="table table-hover"> \
<thead> \
<tr> \
<th>Severity</th> \
<th>Number</th> \
</tr> \
</thead> \
<tbody> \
<tr> \
<td><span class="label Critical">Critical</span></td> \
<td>' + critical.length + '</td> \
</tr> \
<tr> \
<td><span class="label High">High</span></td> \
<td>' + high.length + '</td> \
</tr> \
<tr> \
<td><span class="label Medium">Medium</span></td> \
<td>' + medium.length + '</td> \
</tr> \
<tr> \
<td><span class="label Low">Low</span></td> \
<td>' + low.length + '</td> \
</tr> \
<tr> \
<td><span class="label Info">Info</span></td> \
<td>' + info.length + '</td> \
</tr> \
</tbody> \
</table>';
const risktable = '<table class="table table-hover"> \
<thead> \
<tr> \
<th colspan="5" class="text-center">Overall Risk Severity</th> \
</tr> \
</thead> \
<tbody> \
<tr> \
<td rowspan="4" class="text-center"><b>Impact</b></td> \
<td class="text-center" style="color: #EB7F30;"><b>HIGH</b></td> \
<td class="text-center"><span style="width: 100%;" class="label Medium">Medium</span></td> \
<td class="text-center"><span style="width: 100%;" class="label High">High</span></td> \
<td class="text-center"><span style="width: 100%;" class="label Critical">Critical</span></td> \
</tr> \
<tr> \
<td class="text-center" style="color: #FFFB01;"><b>MEDIUM</b></td> \
<td class="text-center"><span style="width: 100%;" class="label Low">Low</span></td> \
<td class="text-center"><span style="width: 100%;" class="label Medium">Medium</span></td> \
<td class="text-center"><span style="width: 100%;" class="label High">High</span></td> \
</tr> \
<tr> \
<td class="text-center" style="color: #91D054;"><b>LOW</b></td> \
<td class="text-center"><span style="width: 100%;" class="label Info">Info</span></td> \
<td class="text-center"><span style="width: 100%;" class="label Low">Low</span></td> \
<td class="text-center"><span style="width: 100%;" class="label Medium">Medium</span></td> \
</tr> \
<tr> \
<td> </td> \
<td class="text-center" style="color: #91D054;"><b>LOW</b></td> \
<td class="text-center" style="color: #FFFB01;"><b>MEDIUM</b></td> \
<td class="text-center" style="color: #EB7F30;"><b>HIGH</b></td> \
</tr> \
</tbody> \
<tfoot> \
<tr> \
<td> </td> \
<td colspan="4" class="text-center"><b>Likelihood</b></td> \
</tr> \
</tfoot> \
</table>';
// add Markdown rendering
const renderer = new marked.Renderer();
renderer.table = function (header, body) {
const table = `
<table class="table">
<thead>${header}</thead>
<tbody>${body}</tbody>
</table>
`;
return table;
};
const scopemarked = marked(report_data.report_scope, { renderer: renderer });
// advanced text
let projscope = '<h2 id="Scope">Scope</h2><p>' + scopemarked + '</p>';
if (this.advhtml !== '') {
const reportHTMLmarked = marked(this.advhtml, { renderer: renderer });
projscope = projscope + '<br>' + reportHTMLmarked + '<br>';
}
const statsandrisk = '<h2 id="Statistics and Risk">Statistics and Risk</h2> \
<p>' + stats + '</p><br> \
<p>The risk of application security vulnerabilities discovered during an assessment will be rated according to a custom-tailored version the <a target="_blank" href="https://www.owasp.org/index.php/OWASP_Risk_Rating_Methodology">OWASP Risk Rating Methodology</a>. \
Risk severity is determined based on the estimated technical and business impact of the vulnerability, and on the estimated likelihood of the vulnerability being exploited:<br><br> \
' + risktable + '<br>Our Risk rating is based on this calculation: <b>Risk = Likelihood * Impact</b>.</p><div class="pagebreak"></div><br>';
const advtext = projscope + statsandrisk;
let issues = '<div class="card border-light mb-3"><div class="card-header"><center><h3 id="Results">Results (' + report_data.report_vulns.length + ')</h3></center></div><div class="card-body">';
report_data.report_vulns.forEach((item, index) => {
let issstatus = '';
if (report_data.report_settings.report_remove_issuestatus === false) {
if (item.status) {
issstatus = '<dt>Status:</dt> \
<dd>' + statusDesc(item.status) + '</dd><br>';
}
}
let issuetags = '';
if (report_data.report_settings.report_remove_issuetags === false) {
if (item.tags.length > 0) {
let tags = '';
item.tags.forEach((ite, ind) => {
tags = tags + '<span style="color: #fff" class="badge rounded-pill bg-dark">' + escapeHtml(ite.name) + '</span> ';
});
issuetags = '<dt>TAGs:</dt> \
<dd>' + tags + '</dd><br>';
}
}
let desc = '';
if (report_data.report_settings.report_parsing_desc === false) {
desc = '<dt>Description:</dt> \
<dd class="strbreak">' + escapeHtml(item.desc) + '</dd><br>';
} else {
desc = '<dt>Description:</dt> \
<dd class="strbreak">' + parse_newline(escapeHtml(item.desc)) + '</dd><br>';
}
issues = issues + ' \
<div class="row"> \
<h4 id="' + index + '"> \
<span class="label ' + escapeHtml(item.severity) + '">' + escapeHtml(item.severity) + '</span> \
' + escapeHtml(item.title) + '</h4> \
<dl>' + issstatus + desc;
if (item.poc !== '' || item.files.length !== 0) {
const ewe = ' \
<dt>Proof of Concept:</dt> \
<dd class="strbreak"> \
<div style="white-space: pre-wrap;">' + escapeHtml(item.poc) + '</div>';
let fil = '';
item.files.forEach((ite, ind) => {
let shac = '';
if (ite.sha256checksum) {
shac = '<br><small>(SHA256 File Checksum: ' + escapeHtml(ite.sha256checksum) + ')</small>';
}
let fsize = '';
if (ite.size) {
fsize = ' <small>(Size: ' + escapeHtml(ite.size) + ' bytes)</small>';
}
if (ite.type.includes('image')) {
// tslint:disable-next-line:max-line-length
fil = fil + '<b>Attachment: <i>' + escapeHtml(ite.title) + '</i></b>' + fsize + shac + '<br><img src="' + escapeHtml(ite.data) + '" title="' + escapeHtml(ite.title) + '" class="img-fluid"><br><br>';
} else if (ite.type === 'video/mp4' || ite.type === 'video/ogg' || ite.type === 'video/webm') {
if (report_data.report_settings.report_video_embed === true) {
// tslint:disable-next-line:max-line-length
fil = fil + '<b>Attachment: <i>' + escapeHtml(ite.title) + '</i></b>' + fsize + shac + '<br><video width="100%" height="600" controls><source src="' + escapeHtml(ite.data) + '" type="' + escapeHtml(ite.type) + '">Your browser does not support the video tag.</video><br><br>';
}
if (report_data.report_settings.report_video_embed === false) {
fil = fil + '<b>Attachment: <a href="' + escapeHtml(ite.data) + '" download="' + escapeHtml(ite.title) + '"><i>' + escapeHtml(ite.title) + '</i></a></b>' + fsize + shac + '<br><br>';
}
} else if (ite.type === 'text/plain') {
const byteString = atob(ite.data.split(',')[1]);
// tslint:disable-next-line:max-line-length
fil = fil + '<b>Attachment: <i>' + escapeHtml(ite.title) + '</i></b>' + fsize + shac + '<br><b>[file content]:</b><pre style="white-space: pre-wrap;">' + escapeHtml(byteString) + '</pre><br><br>';
} else {
fil = fil + '<b>Attachment: <a href="' + escapeHtml(ite.data) + '" download="' + escapeHtml(ite.title) + '"><i>' + escapeHtml(ite.title) + '</i></a></b>' + fsize + shac + '<br><br>';
}
});
const ewe2 = '</dd><br>';
issues = issues + ewe + fil + ewe2;
}
if (item.ref !== '') {
const reference_item = ' \
<dt>References:</dt> \
<dd class="strbreak">' + parse_links(parse_newline(escapeHtml(item.ref))) + '</dd><br>';
issues = issues + issuetags + reference_item;
}
const end_issues = '</dl></div>';
issues = issues + end_issues;
});
issues = issues + '</div></div><div class="pagebreak"></div>';
let summarycomment_value = '';
if (report_data.report_summary !== '') {
// tslint:disable-next-line:max-line-length
summarycomment_value = '<h2 id="Report summary comment">Report summary comment</h2><p>' + parse_newline(escapeHtml(report_data.report_summary)) + '</p><br>';
}
let authors_value = '';
if (report_data.researcher.length > 0 && report_data.researcher[0].reportername !== '') {
if (report_data.report_settings.report_remove_researchers === false) {
let aut = '';
report_data.researcher.forEach((ite, ind) => {
if (ite.reportername !== '') {
aut = aut + '<i class="bi bi-alarm"></i><div class="col-lg-4"> \
<figure>\
<blockquote class="blockquote">' + (ite.reportername !== '' ? '<p class="mb-0">' + escapeHtml(ite.reportername) + '</p>' : '') + '</blockquote>\
' + (ite.reporteremail !== '' ? '<figcaption class="blockquote-footer">E-Mail: <cite>' + escapeHtml(ite.reporteremail) + '</cite></figcaption>' : '') + '\
' + (ite.reportersocial !== '' ? '<figcaption class="blockquote-footer">Social: <cite>' + parse_links(escapeHtml(ite.reportersocial)) + '</cite></figcaption>' : '') + '\
' + (ite.reporterwww !== '' ? '<figcaption class="blockquote-footer">WWW: <cite>' + parse_links(escapeHtml(ite.reporterwww)) + '</cite></figcaption>' : '') + '\
</figure>\
</div>';
}
});
// tslint:disable-next-line:max-line-length
authors_value = '<h2 id="Report authors">Report authors</h2><p><div class="row">' + aut + '</div></p><br>';
}
}
let changeloghtml = '';
if (report_data.report_settings.report_changelog_page === false) {
changeloghtml = summarycomment_value + '<h2 id="Changelog">Changelog</h2> \
<p><table class="table table-hover"> \
<thead> \
<tr> \
<th>Date</th> \
<th>Description</th> \
</tr> \
</thead> \
<tbody>';
report_data.report_changelog.forEach((item, index) => {
changeloghtml = changeloghtml + '<tr> \
<td>' + escapeHtml(new Date(item.date).toLocaleString()) + '</td> \
<td>' + escapeHtml(item.desc) + '</td> \
</tr>';
});
changeloghtml = changeloghtml + '</tbody></table></p>';
}
let report_gen_info = '';
if (report_data.report_settings.report_remove_lastpage === false) {
report_gen_info = `<div class="pagebreak"></div>
<p>Generated by <a href="https://vulnrepo.com/">VULNRΞPO</a></p>
`;
}
const report_close = '</body></html>';
// tslint:disable-next-line:max-line-length
const download_report_complete = report_html + intro + tableofcontent + advtext + issues + authors_value + changeloghtml + report_gen_info + report_close;
// download HTML report
const blob = new Blob([download_report_complete], { type: 'text/html' });
const link = document.createElement('a');
const url = window.URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', report_metadata.report_name + ' ' + report_metadata.report_id + ' HTML (vulnrepo.com).html');
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
checksumfile(dataurl, files, dec_data) {
let file_sha2 = '';
// sha256 file checksum
const reader = new FileReader();
reader.onloadend = (e) => {
file_sha2 = sha256(reader.result);
this.proccessUpload(dataurl, files[0].name, files[0].type, files[0].size, file_sha2, dec_data);
};
reader.readAsArrayBuffer(files[0]);
}
proccessUpload(data, name, type, size, sha256check, dec_data) {
const index: number = this.decryptedReportDataChanged.report_vulns.indexOf(dec_data);
const today: number = Date.now();
function escapeHtml(unsafe) {
return unsafe.toString()
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
this.upload_in_progress = false;
const linkprev = data;
// tslint:disable-next-line:max-line-length
this.decryptedReportDataChanged.report_vulns[index].files.push({ 'data': linkprev, 'title': escapeHtml(name), 'type': escapeHtml(type), 'size': size, 'sha256checksum': sha256check, 'date': today });
this.afterDetectionNow();
}
uploadAttach(input: HTMLInputElement, dec_data) {
const files = input.files;
if (files && files.length) {
this.upload_in_progress = true;
const fileToRead = files[0];
const fileReader = new FileReader();
fileReader.onload = (e) => {
this.checksumfile(fileReader.result, files, dec_data);
};
fileReader.readAsDataURL(fileToRead);
}
}
downloadAttach(data, name) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
const byteString = atob(data.split(',')[1]);
// separate out the mime component
const mimeString = data.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to an ArrayBuffer
const ab = new ArrayBuffer(byteString.length);
// create a view into the buffer
const ia = new Uint8Array(ab);
// set the bytes of the buffer to the correct values
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
const blob = new Blob([ab], { type: mimeString });
const fileName = name;
const link = document.createElement('a');
const url = window.URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', fileName);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
removeAttach(data, dec_data) {
const index: number = this.decryptedReportDataChanged.report_vulns.indexOf(dec_data);
const ind: number = this.decryptedReportDataChanged.report_vulns[index].files.indexOf(data);
if (ind !== -1) {
this.decryptedReportDataChanged.report_vulns[index].files.splice(ind, 1);
this.afterDetectionNow();
}
}
parselogo(data) {
const linkprev = 'data:image/png;base64,' + btoa(data);
this.uploadlogoprev = '<img src="' + linkprev + '" width="100px">';
this.advlogo = linkprev;
this.decryptedReportDataChanged.report_settings.report_logo.logo = this.advlogo;
}
clearlogo() {
this.decryptedReportDataChanged.report_settings.report_logo.logo = '';
this.uploadlogoprev = '';
this.advlogo = '';
this.advlogo_saved = '';
console.log('Logo cleared!');
}
importlogo(input: HTMLInputElement) {
const files = input.files;
if (files && files.length) {
/*
console.log("Filename: " + files[0].name);
console.log("Type: " + files[0].type);
console.log("Size: " + files[0].size + " bytes");
*/
const fileToRead = files[0];
const fileReader = new FileReader();
fileReader.onload = (e) => {
this.parselogo(fileReader.result);
};
fileReader.readAsBinaryString(fileToRead);
}
}
TAGadd(event: MatChipInputEvent, dec_data): void {
const value = (event.value || '').trim();
if (value) {
const index: number = this.decryptedReportDataChanged.report_vulns.indexOf(dec_data);
this.decryptedReportDataChanged.report_vulns[index].tags.push({name: value});
}
// Reset the input value
if (event.input) {
event.input.value = '';
}
}
TAGremove(tag: Tags, dec_data): void {
const index: number = this.decryptedReportDataChanged.report_vulns.indexOf(dec_data);
const ind: number = this.decryptedReportDataChanged.report_vulns[index].tags.indexOf(tag);
if (ind !== -1) {
this.decryptedReportDataChanged.report_vulns[index].tags.splice(ind, 1);
}
}
setReportProfile(profile: any) {
this.uploadlogoprev = '<img src="' + profile.logo + '" width="100px">';
this.advlogo = profile.logo;
this.advlogo_saved = '';
this.selectedtheme = profile.theme;
// make changes
this.decryptedReportDataChanged.researcher = [{reportername: profile.ResName, reportersocial: profile.ResSocial, reporterwww: profile.ResWeb, reporteremail: profile.ResEmail}];
this.decryptedReportDataChanged.report_settings.report_logo.logo = profile.logo;
this.decryptedReportDataChanged.report_settings.report_logo.width = profile.logow;
this.decryptedReportDataChanged.report_settings.report_logo.height = profile.logoh;
this.decryptedReportDataChanged.report_settings.report_theme = profile.theme;
this.decryptedReportDataChanged.report_settings.report_video_embed = profile.video_embed;
this.decryptedReportDataChanged.report_settings.report_remove_lastpage = profile.remove_lastpage;
this.decryptedReportDataChanged.report_settings.report_remove_issuestatus = profile.remove_issueStatus;
this.decryptedReportDataChanged.report_settings.report_remove_researchers = profile.remove_researcher;
this.decryptedReportDataChanged.report_settings.report_changelog_page = profile.remove_changelog;
this.decryptedReportDataChanged.report_settings.report_remove_issuetags = profile.remove_tags;
this.decryptedReportDataChanged.report_settings.report_parsing_desc = profile.report_parsing_desc;
}
searchBounty(poc) {
this.fastsearchBB(poc, true);
}
fastsearchBB(poc, showsnack) {
this.BBmsg = 'Please wait, searching...';
let scope = [];
this.bugbountylist.forEach(function(item){
scope = scope.concat(item.domains);
});
const regex = /(?:[\w-]+\.)+[\w-]+/g;
let m;
const arr = [];
while ((m = regex.exec(poc.poc)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
m.forEach((match) => {
// get only scope & search
const findedbounty = scope.find(x => x == match);
if (findedbounty) {
this.bugbountylist.forEach(function(item){
const findedbounty2 = item.domains.find(x => x == findedbounty);
if (findedbounty2) {
arr.push(item);
}
});
}
});
}
if (showsnack !== false) {
if (arr.length == 0) {
this.snackBar.open('No bug-bounty program found :-( !', 'OK', {
duration: 2000,
panelClass: ['notify-snackbar-fail']
});
} else {
this.snackBar.open('Found bug-bounty program !!! :-)', 'OK', {
duration: 2000,
panelClass: ['notify-snackbar-success']
});
}
}
const uniqueArray = arr.filter(function(item, pos) {
return arr.indexOf(item) == pos;
});
const index: number = this.decryptedReportDataChanged.report_vulns.indexOf(poc);
this.decryptedReportDataChanged.report_vulns[index].bounty = [];
this.decryptedReportDataChanged.report_vulns[index].bounty = this.decryptedReportDataChanged.report_vulns[index].bounty.concat(uniqueArray);
this.decryptedReportDataChanged.report_vulns[index].bounty = arr.filter(function(item, pos) {
return arr.indexOf(item) == pos;
});
this.BBmsg = '';
}
redirectBounty(url){
window.open(url, "_blank");
}
changePoC(poc){
this.fastsearchBB(poc, false);
}
} | the_stack |
declare module "web3-eea" {
import type Web3 from "web3";
import type { TransactionConfig, TransactionReceipt } from "web3-eth";
import type BN from "bn.js";
export default function EEAClient(web3: IWeb3Instance, chainId: number): IWeb3InstanceExtended;
export interface IWeb3Instance {
currentProvider: any;
extend: (...args: any[]) => any;
}
export interface IEeaWeb3Extension {
/**
* Send the Raw transaction to the Besu node
*/
sendRawTransaction: (options: ISendRawTransactionOptions) => Promise<string>;
}
export interface IWeb3InstanceExtended extends Web3 {
eea: IEeaWeb3Extension;
priv: IPrivWeb3Extension;
privx: IPrivxWeb3Extension;
}
export interface IPrivxWeb3Extension {
/**
* Creates an on chain privacy group
*/
createPrivacyGroup(options: ICreatePrivacyGroupOptions): Promise<IPrivateTransactionReceipt>;
/**
* @deprecated
*/
findOnChainPrivacyGroup(options: IFindOnChainPrivacyGroupOptions): Promise<unknown>;
/**
* Remove a member from an on-chain privacy group
*/
removeFromPrivacyGroup(options: IRemoveFromPrivacyGroupOptions): Promise<IPrivateTransactionReceipt>;
/**
* Add to an existing on-chain privacy group
*/
addToPrivacyGroup(options: IAddToPrivacyGroupOptions): Promise<IPrivateTransactionReceipt>;
/**
* Either lock or unlock the privacy group for member adding
*/
setPrivacyGroupLockState(options: ISetPrivacyGroupLockState): Promise<IPrivateTransactionReceipt>;
}
export interface IPrivWeb3Extension {
/**
* Generate a privacyGroupId
* @param options Options passed into `eea_sendRawTransaction`
* @returns String The base64 encoded keccak256 hash of the participants.
*/
generatePrivacyGroup(options: IGeneratePrivacyGroupOptions): string;
/**
* Returns with the deleted group's ID (same one that was passed in).
*/
deletePrivacyGroup(options: IDeletePrivacyGroupOptions): Promise<string>;
/**
* Returns a list of privacy groups containing only the listed members.
* For example, if the listed members are A and B, a privacy group
* containing A, B, and C is not returned.
*/
findPrivacyGroup(options: IFindPrivacyGroupOptions): Promise<Array<IPrivacyGroup>>;
distributeRawTransaction(options: IPrivateTransactionConfig, method: string): Promise<unknown>;
getTransactionCount(options: IGetTransactionCountNoPrivacyGroupIdOptions | IGetTransactionCountWithPrivacyGroupIdOptions): Promise<number>;
/**
* Get the private transaction Receipt.
* @param txHash Transaction Hash of the marker transaction
* @param enclavePublicKey Public key used to start - up the Enclave
* @param retries Number of retries to be made to get the private marker transaction receipt. Default: 300
* @param delay The delay between the retries. Default: 1000
* @see https://besu.hyperledger.org/en/stable/Reference/API-Objects/#private-transaction-receipt-object
*/
getTransactionReceipt(
txHash: string,
enclavePublicKey: string,
retries?: number,
delay?: number,
): Promise<IPrivateTransactionReceipt | null>;
call(options: ICallOptions): Promise<string>;
/**
* Subscribe to new logs matching a filter
*
* If the provider supports subscriptions, it uses `priv_subscribe`, otherwise
* it uses polling and `priv_getFilterChanges` to get new logs. Returns an
* error to the callback if there is a problem subscribing or creating the filter.
* @param {string} privacyGroupId
* @param {*} filter
* @param {function} callback returns the filter/subscription ID, or an error
* @return {PrivateSubscription} a subscription object that manages the
* lifecycle of the filter or subscription
*/
subscribe(privacyGroupId: string, filter: unknown, callback: (err: Error | undefined, filterId: string) => void): Promise<unknown>;
}
/**
* Controls the lifecycle of a private subscription
*/
export interface IPrivateSubscription {
/**
* Returns with a `Promise` of a filter ID.
*/
subscribe(): Promise<string>;
on(eventName: string, callback: (...args: unknown[]) => void): this;
reset(): void;
unsubscribe(): Promise<unknown>;
}
export interface ISendGenericTransactionOptions {
readonly privateKey: string;
readonly privateFrom: string;
readonly privacyGroupId?: string;
readonly privateFor: string[];
/**
* getTransactionCount is used to calculate nonce if omitted.
*/
readonly nonce?: number;
/**
* default value 0
*/
gasPrice?: number | string | BN;
/**
* default value 3000000
*/
readonly gasLimit?: number;
readonly to?: string;
readonly data: string;
/**
* Defaults to `"restricted"`
*
* Hyperledger Besu only implements `"restricted"` mode of operation.
*/
readonly restriction?: "restricted" |"unrestricted";
}
export interface ISendRawTransactionOptions extends ISendGenericTransactionOptions, TransactionConfig {
/**
* Private Key used to sign transaction with
*/
readonly privateKey: string;
/**
* Enclave public key
*/
readonly privateFrom: string;
/**
* Enclave keys to send the transaction to
*/
readonly privateFor: string[];
/**
* Enclave id representing the receivers of the transaction
*/
readonly privacyGroupId?: string;
/**
* (Optional) : If not provided, will be calculated using`eea_getTransctionCount`
*/
readonly nonce?: number;
/**
* The address to send the transaction
*/
readonly to?: string;
/**
* Data to be sent in the transaction
*/
readonly data: string;
}
export interface ISetPrivacyGroupLockState {
/**
* Privacy group ID to lock / unlock
*/
readonly privacyGroupId: string;
/**
* Private Key used to sign transaction with
*/
readonly privateKey: string;
/**
* Orion public key
*/
readonly enclaveKey: string;
/**
* boolean indicating whether to lock or unlock
*/
readonly lock: boolean;
}
export interface IAddToPrivacyGroupOptions {
/**
* Privacy group ID to add to
*/
readonly privacyGroupId: string;
/**
* Private Key used to sign transaction with
*/
readonly privateKey: string;
/**
* Orion public key
*/
readonly enclaveKey: string;
/**
* list of enclaveKey to pass to the contract to add to the group
*/
readonly participants: string[];
}
export interface IRemoveFromPrivacyGroupOptions {
/**
* Privacy group ID to add to
*/
readonly privacyGroupId: string;
/**
* Private Key used to sign transaction with
*/
readonly privateKey: string;
/**
* Orion public key
*/
readonly enclaveKey: string;
/**
* single enclaveKey to pass to the contract to add to the group
*/
readonly participant: string;
}
export interface ICreatePrivacyGroupOptions {
/**
* Privacy group ID to add to
*/
readonly privacyGroupId: string;
/**
* Private Key used to sign transaction with
*/
readonly privateKey: string;
/**
* Orion public key
*/
readonly enclaveKey: string;
/**
* list of enclaveKey to pass to the contract to add to the group
* Expected to be Base64 encoded array of strings.
*/
readonly participants: string[];
}
export interface IFindOnChainPrivacyGroupOptions {
readonly addresses: string[];
}
export interface IGeneratePrivacyGroupOptions {
readonly privateFor: string[];
readonly privateFrom: string;
}
export interface IDeletePrivacyGroupOptions {
readonly privacyGroupId: string;
}
export interface IFindPrivacyGroupOptions {
readonly addresses: string[];
}
export interface IGetTransactionCountNoPrivacyGroupIdOptions {
readonly from: string;
readonly privateFrom: string;
readonly privateFor: string[];
readonly privacyGroupId?: string;
}
export interface IGetTransactionCountWithPrivacyGroupIdOptions {
readonly from: string;
readonly privateFrom?: string;
readonly privateFor?: string[];
readonly privacyGroupId: string;
}
export interface ICallOptions {
/**
* Enclave id representing the receivers of the transaction
*/
readonly privacyGroupId: string;
/**
* Contract address,
*/
readonly to: string;
readonly from: string;
/**
* Encoded function call(signature + data)
*/
readonly data: string;
/**
* Blocknumber defaults to "latest"
*/
readonly blockNumber?: IBlockParameter;
}
export type IBlockParameter = string | number | "latest" | "earliest" | "pending";
export interface IPrivateTransactionReceipt extends TransactionReceipt {
/**
* Data, 32 bytes Hash of block containing this transaction.
*/
readonly blockHash: string;
/**
* Quantity Block number of block containing this transaction.
*/
readonly blockNumber: number;
/**
* Data, 20 bytes Contract address created if a contract creation transaction, otherwise, null.
*/
readonly contractAddress: string;
/**
* Data, 20 bytes Address of the sender.
*/
readonly from: string;
/**
* Array Array of log objects generated by this private transaction.
*/
readonly logs: Array<IEeaLogObject>;
/**
* Data, 20 bytes Address of the receiver, if sending ether, otherwise, null.
*/
readonly to: string;
/**
* Data, 32 bytes Hash of the private transaction.
*/
readonly transactionHash: string;
/**
* Quantity, Integer Index position of transaction in the block.
*/
readonly transactionIndex: number;
/**
* String ABI - encoded string that displays the reason for reverting the transaction.Only available if revert reason is enabled.
*/
readonly revertReason: string;
/**
* Data RLP - encoded return value of a contract call if a value returns, otherwise, null.
*/
readonly output: string;
/**
* Data, 32 bytes Hash of the privacy marker transaction.
*/
readonly commitmentHash: string;
/**
* Quantity Either `0x1` (success) or `0x0` (failure).
*/
readonly status: boolean;
/**
* Data, 32 bytes Tessera public key of the sender.
*/
readonly privateFrom: string;
/**
* or privacyGroupId Array or Data, 32 bytes Tessera public keys or privacy group ID of the recipients.
*/
readonly privateFor: string | string[];
/**
* Data, 256 bytes Bloom filter for light clients to quickly retrieve related logs.
*/
readonly logsBloom: string;
}
/**
* @see https://besu.hyperledger.org/en/stable/Reference/API-Objects/#log-object
*/
export interface IEeaLogObject {
/**
* Tag true if log removed because of a chain reorganization.false if a valid log.
*/
readonly removed: string;
/**
* Quantity, Integer Log index position in the block.null when log is pending.
*/
readonly logIndex: number;
/**
* Quantity, Integer Index position of the starting transaction for the log.null when log is pending.
*/
readonly transactionIndex: number;
/**
* Data, 32 bytes Hash of the starting transaction for the log.null when log is pending.
*/
readonly transactionHash: string;
/**
* Data, 32 bytes Hash of the block that includes the log.null when log is pending.
*/
readonly blockHash: string;
/**
* Quantity Number of block that includes the log.null when log is pending.
*/
readonly blockNumber: number;
/**
* Data, 20 bytes Address the log originated from.
*/
readonly address: string;
/**
* Data Non - indexed arguments of the log.
*/
readonly data: string;
/**
* Array of Data, 32 bytes each Event signature hash and 0 to 3 indexed log arguments.
*/
readonly topics: string[];
}
export interface IPrivateTransactionConfig {
readonly privateKey: string;
readonly privateFrom: string;
readonly privacyGroupId: string;
readonly privateFor: string[];
readonly nonce: string;
/**
* Default value: 0
*/
readonly gasPrice?: number;
/**
* Default value 3000000
*/
readonly gasLimit?: number;
readonly to: string;
readonly data: string;
}
export interface IPrivacyGroup {
readonly privacyGroupId: string;
readonly type: PrivacyGroupType;
readonly name: string;
readonly description: string;
readonly members: string[];
}
// FIXME - this should be a const enum with the values matching what the
// Besu API returns (JVM enum)
export enum PrivacyGroupType {
LEGACY,
ONCHAIN,
PANTHEON
}
} | the_stack |
import typescript = require('typescript');
import path = require('path');
import fs = require('fs');
import os = require('os');
import loaderUtils = require('loader-utils');
import objectAssign = require('object-assign');
import makeResolver = require('./resolver');
import 'colors'
import {hasOwnProperty, pushArray, arrify} from './src/util'
import {
TSInstances,
TSInstance,
WebpackError,
LoaderOptions,
TSFiles,
ResolvedModule,
TSFile
} from './src/interfaces'
var Console = require('console').Console;
var semver = require('semver')
const console = new Console(process.stderr);
var instances = <TSInstances>{};
var webpackInstances = [];
const scriptRegex = /\.tsx?$/i;
// Take TypeScript errors, parse them and format to webpack errors
// Optionally adds a file name
function formatErrors(diagnostics: typescript.Diagnostic[], instance: TSInstance, merge?: any): WebpackError[] {
return diagnostics
.filter(diagnostic => instance.loaderOptions.ignoreDiagnostics.indexOf(diagnostic.code) == -1)
.map<WebpackError>(diagnostic => {
var errorCategory = instance.compiler.DiagnosticCategory[diagnostic.category].toLowerCase();
var errorCategoryAndCode = errorCategory + ' TS' + diagnostic.code + ': ';
var messageText = errorCategoryAndCode + instance.compiler.flattenDiagnosticMessageText(diagnostic.messageText, os.EOL);
if (diagnostic.file) {
var lineChar = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
return {
message: `${'('.white}${(lineChar.line+1).toString().cyan},${(lineChar.character+1).toString().cyan}): ${messageText.red}`,
rawMessage: messageText,
location: {line: lineChar.line+1, character: lineChar.character+1},
loaderSource: 'ts-loader'
};
}
else {
return {
message:`${messageText.red}`,
rawMessage: messageText,
loaderSource: 'ts-loader'
};
}
})
.map(error => <WebpackError>objectAssign(error, merge));
}
// The tsconfig.json is found using the same method as `tsc`, starting in the current directory
// and continuing up the parent directory chain.
function findConfigFile(compiler: typeof typescript, searchPath: string, configFileName: string): string {
while (true) {
var fileName = path.join(searchPath, configFileName);
if (compiler.sys.fileExists(fileName)) {
return fileName;
}
var parentPath = path.dirname(searchPath);
if (parentPath === searchPath) {
break;
}
searchPath = parentPath;
}
return undefined;
}
function appendSuffixToVue(fileName: string) {
if (/\.vue$/.test(fileName)) {
return fileName + '.ts';
}
return fileName;
}
// The loader is executed once for each file seen by webpack. However, we need to keep
// a persistent instance of TypeScript that contains all of the files in the program
// along with definition files and options. This function either creates an instance
// or returns the existing one. Multiple instances are possible by using the
// `instance` property.
function ensureTypeScriptInstance(loaderOptions: LoaderOptions, loader: any): { instance?: TSInstance, error?: WebpackError } {
function log(...messages: string[]): void {
if (!loaderOptions.silent) {
console.log.apply(console, messages);
}
}
if (hasOwnProperty(instances, loaderOptions.instance)) {
return { instance: instances[loaderOptions.instance] };
}
try {
var compiler: typeof typescript = require(loaderOptions.compiler);
}
catch (e) {
let message = loaderOptions.compiler == 'typescript'
? 'Could not load TypeScript. Try installing with `npm install typescript`. If TypeScript is installed globally, try using `npm link typescript`.'
: `Could not load TypeScript compiler with NPM package name \`${loaderOptions.compiler}\`. Are you sure it is correctly installed?`
return { error: {
message: message.red,
rawMessage: message,
loaderSource: 'ts-loader'
} };
}
var motd = `ts-loader: Using ${loaderOptions.compiler}@${compiler.version}`,
compilerCompatible = false;
if (loaderOptions.compiler == 'typescript') {
if (compiler.version && semver.gte(compiler.version, '2.0.0')) {
// don't log yet in this case, if a tsconfig.json exists we want to combine the message
compilerCompatible = true;
}
else {
log(`${motd}. This version is incompatible with ts-loader. Please upgrade to the latest version of TypeScript.`.red);
}
}
else {
log(`${motd}. This version may or may not be compatible with ts-loader.`.yellow);
}
var files = <TSFiles>{};
var instance: TSInstance = instances[loaderOptions.instance] = {
compiler,
compilerOptions: null,
loaderOptions,
files,
languageService: null,
version: 0,
dependencyGraph: {}
};
var compilerOptions: typescript.CompilerOptions = {
};
// Load any available tsconfig.json file
var filesToLoad = [];
var configFilePath = findConfigFile(compiler, path.dirname(loader.resourcePath), loaderOptions.configFileName);
var configFile: {
config?: {compilerOptions: {isolatedModules?: {}}, files: string[]};
error?: typescript.Diagnostic;
};
if (configFilePath) {
if (compilerCompatible) log(`${motd} and ${configFilePath}`.green)
else log(`ts-loader: Using config file at ${configFilePath}`.green)
// HACK: relies on the fact that passing an extra argument won't break
// the old API that has a single parameter
configFile = compiler.readConfigFile(
configFilePath,
compiler.sys.readFile
);
if (configFile.error) {
var configFileError = formatErrors([configFile.error], instance, {file: configFilePath })[0];
return { error: configFileError }
}
}
else {
if (compilerCompatible) log(motd.green)
configFile = {
config: {
compilerOptions: {},
files: []
}
}
}
configFile.config.compilerOptions = objectAssign({},
configFile.config.compilerOptions,
loaderOptions.compilerOptions);
// do any necessary config massaging
if (loaderOptions.transpileOnly) {
configFile.config.compilerOptions.isolatedModules = true;
}
var configParseResult;
configParseResult = compiler.parseJsonConfigFileContent(
configFile.config,
compiler.sys,
path.dirname(configFilePath || '')
);
if (configParseResult.errors.length) {
pushArray(
loader._module.errors,
formatErrors(configParseResult.errors, instance, { file: configFilePath }));
return { error: {
file: configFilePath,
message: 'error while parsing tsconfig.json'.red,
rawMessage: 'error while parsing tsconfig.json',
loaderSource: 'ts-loader'
}};
}
instance.compilerOptions = objectAssign(compilerOptions, configParseResult.options);
filesToLoad = configParseResult.fileNames;
// if `module` is not specified and not using ES6 target, default to CJS module output
if (compilerOptions.module == null && compilerOptions.target !== 2 /* ES6 */) {
compilerOptions.module = 1 /* CommonJS */
}
if (loaderOptions.transpileOnly) {
// quick return for transpiling
// we do need to check for any issues with TS options though
var program = compiler.createProgram([], compilerOptions),
diagnostics = program.getOptionsDiagnostics();
pushArray(
loader._module.errors,
formatErrors(diagnostics, instance, {file: configFilePath || 'tsconfig.json'}));
return { instance: instances[loaderOptions.instance] = { compiler, compilerOptions, loaderOptions, files, dependencyGraph: {} }};
}
// Load initial files (core lib files, any files specified in tsconfig.json)
let filePath: string;
try {
filesToLoad.forEach(fp => {
filePath = path.normalize(fp);
files[filePath] = {
text: fs.readFileSync(filePath, 'utf-8'),
version: 0
};
});
}
catch (exc) {
let filePathError = `A file specified in tsconfig.json could not be found: ${ filePath }`;
return { error: {
message: filePathError.red,
rawMessage: filePathError,
loaderSource: 'ts-loader'
}};
}
let newLine =
compilerOptions.newLine === 0 /* CarriageReturnLineFeed */ ? '\r\n' :
compilerOptions.newLine === 1 /* LineFeed */ ? '\n' :
os.EOL;
// make a (sync) resolver that follows webpack's rules
let resolver = makeResolver(loader.options);
var readFile = function(fileName) {
fileName = path.normalize(fileName);
try {
return fs.readFileSync(fileName, {encoding: 'utf8'})
}
catch (e) {
return;
}
}
var moduleResolutionHost = {
fileExists: (fileName: string) => readFile(fileName) !== undefined,
readFile: (fileName: string) => readFile(fileName)
};
// Create the TypeScript language service
var servicesHost: typescript.LanguageServiceHost = {
getProjectVersion: () => instance.version+'',
getScriptFileNames: () => Object.keys(files).filter(filePath => scriptRegex.test(filePath)),
getScriptVersion: fileName => {
fileName = path.normalize(fileName);
return files[fileName] && files[fileName].version.toString();
},
getScriptSnapshot: fileName => {
// This is called any time TypeScript needs a file's text
// We either load from memory or from disk
fileName = path.normalize(fileName);
var file = files[fileName];
if (!file) {
let text = readFile(fileName);
if (text == null) return;
file = files[fileName] = { version: 0, text }
}
return compiler.ScriptSnapshot.fromString(file.text);
},
getCurrentDirectory: () => process.cwd(),
getDirectories: typescript.sys.getDirectories,
directoryExists: typescript.sys.directoryExists,
getCompilationSettings: () => compilerOptions,
getDefaultLibFileName: options => compiler.getDefaultLibFilePath(options),
getNewLine: () => newLine,
log: log,
resolveModuleNames: (moduleNames: string[], containingFile: string) => {
let resolvedModules: any[] = [];
for (let moduleName of moduleNames) {
let resolvedFileName: string;
let resolutionResult: any;
try {
resolvedFileName = resolver.resolveSync(path.normalize(path.dirname(containingFile)), moduleName)
resolvedFileName = appendSuffixToVue(resolvedFileName)
if (!resolvedFileName.match(/\.tsx?$/)) resolvedFileName = null;
else resolutionResult = { resolvedFileName };
}
catch (e) { resolvedFileName = null }
let tsResolution: ResolvedModule = compiler.resolveModuleName(moduleName, containingFile, compilerOptions, moduleResolutionHost);
if (tsResolution.resolvedModule) {
if (resolvedFileName) {
if (resolvedFileName == tsResolution.resolvedModule.resolvedFileName) {
resolutionResult.isExternalLibraryImport = tsResolution.resolvedModule.isExternalLibraryImport;
}
}
else resolutionResult = tsResolution.resolvedModule;
}
resolvedModules.push(resolutionResult);
}
instance.dependencyGraph[containingFile] = resolvedModules.filter(m => m != null).map(m => m.resolvedFileName);
return resolvedModules;
}
};
var languageService = instance.languageService = compiler.createLanguageService(servicesHost, compiler.createDocumentRegistry());
var getCompilerOptionDiagnostics = true;
loader._compiler.plugin("after-compile", (compilation, callback) => {
// Don't add errors for child compilations
if (compilation.compiler.isChild()) {
callback();
return;
}
let stats = compilation.stats;
// handle all other errors. The basic approach here to get accurate error
// reporting is to start with a "blank slate" each compilation and gather
// all errors from all files. Since webpack tracks errors in a module from
// compilation-to-compilation, and since not every module always runs through
// the loader, we need to detect and remove any pre-existing errors.
function removeTSLoaderErrors(errors: WebpackError[]) {
let index = -1, length = errors.length;
while (++index < length) {
if (errors[index].loaderSource == 'ts-loader') {
errors.splice(index--, 1);
length--;
}
}
}
removeTSLoaderErrors(compilation.errors);
// handle compiler option errors after the first compile
if (getCompilerOptionDiagnostics) {
getCompilerOptionDiagnostics = false;
pushArray(
compilation.errors,
formatErrors(languageService.getCompilerOptionsDiagnostics(), instance, {file: configFilePath || 'tsconfig.json'}));
}
// build map of all modules based on normalized filename
// this is used for quick-lookup when trying to find modules
// based on filepath
let modules = {};
compilation.modules.forEach(module => {
if (module.resource) {
let modulePath = path.normalize(module.resource);
if (hasOwnProperty(modules, modulePath)) {
let existingModules = modules[modulePath];
if (existingModules.indexOf(module) == -1) {
existingModules.push(module);
}
}
else {
modules[modulePath] = [module];
}
}
})
// gather all errors from TypeScript and output them to webpack
Object.keys(instance.files)
.filter(filePath => !!filePath.match(/(\.d)?\.ts(x?)$/))
.forEach(filePath => {
let errors = languageService.getSyntacticDiagnostics(filePath).concat(languageService.getSemanticDiagnostics(filePath));
// if we have access to a webpack module, use that
if (hasOwnProperty(modules, filePath)) {
let associatedModules = modules[filePath];
associatedModules.forEach(module => {
// remove any existing errors
removeTSLoaderErrors(module.errors);
// append errors
let formattedErrors = formatErrors(errors, instance, { module });
pushArray(module.errors, formattedErrors);
pushArray(compilation.errors, formattedErrors);
})
}
// otherwise it's a more generic error
else {
pushArray(compilation.errors, formatErrors(errors, instance, {file: filePath}));
}
});
// gather all declaration files from TypeScript and output them to webpack
Object.keys(instance.files)
.filter(filePath => !!filePath.match(/\.ts(x?)$/))
.forEach(filePath => {
let output = languageService.getEmitOutput(filePath);
let declarationFile = output.outputFiles.filter(filePath => !!filePath.name.match(/\.d.ts$/)).pop();
if (declarationFile) {
let context = compilation.options.context
let assetsPath = path.normalize(path.relative(context, declarationFile.name))
compilation.assets[assetsPath] = {
source: () => declarationFile.text,
size: () => declarationFile.text.length
};
}
});
callback();
});
// manually update changed files
loader._compiler.plugin("watch-run", (watching, cb) => {
var mtimes = watching.compiler.fileTimestamps ||
watching.compiler.watchFileSystem.watcher.mtimes;
Object.keys(mtimes)
.filter(filePath => !!filePath.match(/\.tsx?$|\.jsx?$/))
.forEach(filePath => {
filePath = path.normalize(filePath);
var file = instance.files[filePath];
if (file) {
file.text = fs.readFileSync(filePath, {encoding: 'utf8'});
file.version++;
instance.version++;
}
});
cb()
})
return { instance };
}
function loader(contents) {
this.cacheable && this.cacheable();
var callback = this.async();
var filePath = path.normalize(this.resourcePath);
filePath = appendSuffixToVue(filePath);
var queryOptions = loaderUtils.parseQuery<LoaderOptions>(this.query);
var configFileOptions = this.options.ts || {};
var options = objectAssign({}, {
silent: false,
instance: 'default',
compiler: 'typescript',
configFileName: 'tsconfig.json',
transpileOnly: false,
compilerOptions: {}
}, configFileOptions, queryOptions);
options.ignoreDiagnostics = arrify(options.ignoreDiagnostics).map(Number);
// differentiate the TypeScript instance based on the webpack instance
var webpackIndex = webpackInstances.indexOf(this._compiler);
if (webpackIndex == -1) {
webpackIndex = webpackInstances.push(this._compiler)-1;
}
options.instance = webpackIndex + '_' + options.instance;
var { instance, error } = ensureTypeScriptInstance(options, this);
if (error) {
callback(error)
return;
}
// Update file contents
var file = instance.files[filePath]
if (!file) {
file = instance.files[filePath] = <TSFile>{ version: 0 };
}
if (file.text !== contents) {
file.version++;
file.text = contents;
instance.version++;
}
var outputText: string, sourceMapText: string, diagnostics: typescript.Diagnostic[] = [];
if (options.transpileOnly) {
var fileName = path.basename(filePath);
var transpileResult = instance.compiler.transpileModule(contents, {
compilerOptions: instance.compilerOptions,
reportDiagnostics: true,
fileName
});
({ outputText, sourceMapText, diagnostics } = transpileResult);
pushArray(this._module.errors, formatErrors(diagnostics, instance, {module: this._module}));
}
else {
let langService = instance.languageService;
// Emit Javascript
var output = langService.getEmitOutput(filePath);
// Make this file dependent on *all* definition files in the program
this.clearDependencies();
this.addDependency(filePath);
let allDefinitionFiles = Object.keys(instance.files).filter(filePath => /\.d\.ts$/.test(filePath));
allDefinitionFiles.forEach(this.addDependency.bind(this));
// Additionally make this file dependent on all imported files
let additionalDependencies = instance.dependencyGraph[filePath];
if (additionalDependencies) {
additionalDependencies.forEach(this.addDependency.bind(this))
}
this._module.meta.tsLoaderDefinitionFileVersions = allDefinitionFiles
.concat(additionalDependencies)
.map(filePath => filePath+'@'+(instance.files[filePath] || {version: '?'}).version);
var outputFile = output.outputFiles.filter(file => !!file.name.match(/\.js(x?)$/)).pop();
if (outputFile) { outputText = outputFile.text }
var sourceMapFile = output.outputFiles.filter(file => !!file.name.match(/\.js(x?)\.map$/)).pop();
if (sourceMapFile) { sourceMapText = sourceMapFile.text }
}
if (outputText == null) throw new Error(`Typescript emitted no output for ${filePath}`);
if (sourceMapText) {
var sourceMap = JSON.parse(sourceMapText);
sourceMap.sources = [loaderUtils.getRemainingRequest(this)];
sourceMap.file = filePath;
sourceMap.sourcesContent = [contents];
outputText = outputText.replace(/^\/\/# sourceMappingURL=[^\r\n]*/gm, '');
}
// Make sure webpack is aware that even though the emitted JavaScript may be the same as
// a previously cached version the TypeScript may be different and therefore should be
// treated as new
this._module.meta.tsLoaderFileVersion = file.version;
callback(null, outputText, sourceMap)
}
function cleanup() {
for (let key in instances) {
let instance = instances[key]
instance.dependencyGraph = null
instance.compiler = null
instance.files = null
}
instances = {}
webpackInstances = []
}
namespace loader {
export var _cleanup = cleanup
}
export = loader; | the_stack |
import { validateSimpleSwapApp, generateValidationMiddleware } from "@connext/apps";
import {
AppInstanceJson,
MethodParams,
SimpleTwoPartySwapAppName,
WithdrawAppName,
WithdrawAppState,
Opcode,
UninstallMiddlewareContext,
ProtocolName,
MiddlewareContext,
ProtocolNames,
DepositAppState,
ProtocolRoles,
ProposeMiddlewareContext,
ConditionalTransferAppNames,
DepositAppName,
GenericConditionalTransferAppState,
DefaultApp,
ConditionalTransferTypes,
ProtocolParams,
AppAction,
PriceOracleTypes,
InstallMiddlewareContext,
RequireOnlineApps,
} from "@connext/types";
import { getAddressFromAssetId, toBN, stringify } from "@connext/utils";
import { Injectable, OnModuleInit } from "@nestjs/common";
import { BigNumber } from "ethers";
import { AppType } from "../appInstance/appInstance.entity";
import { CFCoreService } from "../cfCore/cfCore.service";
import { Channel } from "../channel/channel.entity";
import { ChannelRepository } from "../channel/channel.repository";
import { ChannelService } from "../channel/channel.service";
import { ConfigService } from "../config/config.service";
import { DepositService } from "../deposit/deposit.service";
import { LoggerService } from "../logger/logger.service";
import { SwapRateService } from "../swapRate/swapRate.service";
import { WithdrawService } from "../withdraw/withdraw.service";
import { TransferService } from "../transfer/transfer.service";
import { TransferRepository } from "../transfer/transfer.repository";
@Injectable()
export class AppRegistryService implements OnModuleInit {
constructor(
private readonly cfCoreService: CFCoreService,
private readonly channelService: ChannelService,
private readonly configService: ConfigService,
private readonly log: LoggerService,
private readonly transferService: TransferService,
private readonly swapRateService: SwapRateService,
private readonly withdrawService: WithdrawService,
private readonly depositService: DepositService,
private readonly channelRepository: ChannelRepository,
private readonly transferRepository: TransferRepository,
) {
this.log.setContext("AppRegistryService");
}
async installOrReject(
appIdentityHash: string,
proposeInstallParams: MethodParams.ProposeInstall,
from: string,
): Promise<void> {
this.log.info(
`installOrReject for app ${appIdentityHash} with params ${JSON.stringify(
proposeInstallParams,
)} from ${from} started`,
);
let registryAppInfo: DefaultApp;
// if error, reject install
let installerChannel: Channel | undefined;
try {
installerChannel = await this.channelRepository.findByAppIdentityHashOrThrow(appIdentityHash);
registryAppInfo = this.cfCoreService.getAppInfoByAppDefinitionAddress(
proposeInstallParams.appDefinition,
)!;
if (!registryAppInfo.allowNodeInstall) {
throw new Error(`App ${registryAppInfo.name} is not allowed to be installed on the node`);
}
// begin transfer flow in middleware. if the transfer type requires that a
// recipient is online, it will error here. Otherwise, it will return
// without erroring and wait for the recipient to come online and reclaim
// TODO: break into flows for deposit, withdraw, swap, and transfers
if (
Object.values(ConditionalTransferAppNames).includes(
registryAppInfo.name as ConditionalTransferTypes,
)
) {
await this.transferService.transferAppInstallFlow(
appIdentityHash,
proposeInstallParams,
from,
installerChannel,
registryAppInfo.name as ConditionalTransferTypes,
);
return;
}
// TODO: break into flows for deposit, withdraw, swap, and transfers
// check if we need to collateralize, only for swap app
if (registryAppInfo.name === SimpleTwoPartySwapAppName) {
const freeBal = await this.cfCoreService.getFreeBalance(
from,
installerChannel.multisigAddress,
proposeInstallParams.responderDepositAssetId,
);
const responderDepositBigNumber = BigNumber.from(proposeInstallParams.responderDeposit);
if (freeBal[this.cfCoreService.cfCore.signerAddress].lt(responderDepositBigNumber)) {
const amount = await this.channelService.getCollateralAmountToCoverPaymentAndRebalance(
from,
installerChannel.chainId,
proposeInstallParams.responderDepositAssetId,
responderDepositBigNumber,
freeBal[this.cfCoreService.cfCore.signerAddress],
);
this.log.info(
`Calculated collateral amount to cover payment and rebalance: ${amount.toString()}`,
);
// request collateral and wait for deposit to come through\
let depositError: Error | undefined = undefined;
try {
const depositResponse = await this.depositService.deposit(
installerChannel,
amount,
proposeInstallParams.responderDepositAssetId,
);
if (!depositResponse) {
throw new Error(`Node failed to install deposit app`);
}
this.log.info(
`Installed deposit app in channel ${installerChannel.multisigAddress}, waiting for completion`,
);
await depositResponse.completed();
} catch (e) {
depositError = e;
}
if (depositError) {
throw new Error(
`Could not deposit sufficient collateral to install app for channel ${installerChannel.multisigAddress}. ${depositError.message}`,
);
}
}
}
await this.cfCoreService.installApp(appIdentityHash, installerChannel);
// any tasks that need to happen after install, i.e. DB writes
} catch (e) {
// reject if error
this.log.warn(`App install failed: ${e.message || e}`);
await this.cfCoreService.rejectInstallApp(appIdentityHash, installerChannel!, e.message);
return;
}
try {
await this.runPostInstallTasks(registryAppInfo, appIdentityHash, proposeInstallParams);
} catch (e) {
this.log.warn(
`Run post install tasks failed: ${e.message || e}, uninstalling app ${appIdentityHash}`,
);
await this.cfCoreService.uninstallApp(appIdentityHash, installerChannel);
}
}
private async runPostInstallTasks(
registryAppInfo: DefaultApp,
appIdentityHash: string,
proposeInstallParams: MethodParams.ProposeInstall,
): Promise<void> {
this.log.info(
`runPostInstallTasks for app name ${registryAppInfo.name} ${appIdentityHash} started`,
);
switch (registryAppInfo.name) {
case WithdrawAppName: {
this.log.debug(`Doing withdrawal post-install tasks`);
const appInstance = await this.cfCoreService.getAppInstance(appIdentityHash);
const initialState = proposeInstallParams.initialState as WithdrawAppState;
this.log.debug(`AppRegistry sending withdrawal to db at ${appInstance.multisigAddress}`);
await this.withdrawService.saveWithdrawal(
appIdentityHash,
BigNumber.from(proposeInstallParams.initiatorDeposit),
proposeInstallParams.initiatorDepositAssetId,
initialState.transfers[0].to,
initialState.data,
initialState.signatures[0],
initialState.signatures[1],
appInstance.multisigAddress,
);
await this.withdrawService.handleUserWithdraw(appInstance);
break;
}
default:
this.log.debug(`No post-install actions configured for app name ${registryAppInfo.name}.`);
}
this.log.info(
`runPostInstallTasks for app ${registryAppInfo.name} ${appIdentityHash} completed`,
);
}
// APP SPECIFIC MIDDLEWARE
public generateMiddleware = async (): Promise<
(protocol: ProtocolName, cxt: MiddlewareContext) => Promise<void>
> => {
const networkContexts = this.configService.getNetworkContexts();
const defaultValidation = await generateValidationMiddleware(
networkContexts,
this.configService.getSupportedTokens(),
() => Promise.resolve("1"), // incoming proposals to the node should always have a swap rate of 1, will need to address for multihop
);
return async (protocol: ProtocolName, cxt: MiddlewareContext): Promise<void> => {
await defaultValidation(protocol, cxt);
switch (protocol) {
case ProtocolNames.setup:
case ProtocolNames.takeAction:
case ProtocolNames.sync: {
return;
}
case ProtocolNames.propose: {
return this.proposeMiddleware(cxt as ProposeMiddlewareContext);
}
case ProtocolNames.install: {
return this.installMiddleware(cxt as InstallMiddlewareContext);
}
case ProtocolNames.uninstall: {
return this.uninstallMiddleware(cxt as UninstallMiddlewareContext);
}
default: {
const unexpected: never = protocol;
throw new Error(`Unexpected case: ${unexpected}`);
}
}
};
};
private proposeMiddleware = async (cxt: ProposeMiddlewareContext) => {
const { proposal, params, stateChannel } = cxt;
const contractAddresses = this.configService.getContractAddresses(stateChannel.chainId);
switch (proposal.appDefinition) {
case contractAddresses.SimpleTwoPartySwapApp: {
const responderDecimals = await this.configService.getTokenDecimals(
stateChannel.chainId,
params.responderDepositAssetId,
);
const allowedSwaps = this.configService.getAllowedSwaps(stateChannel.chainId);
const swap = allowedSwaps.find(
(swap) =>
getAddressFromAssetId(swap.from) ===
getAddressFromAssetId(params.initiatorDepositAssetId) &&
getAddressFromAssetId(swap.to) ===
getAddressFromAssetId(params.responderDepositAssetId) &&
swap.fromChainId === stateChannel.chainId &&
swap.toChainId === stateChannel.chainId,
);
if (swap?.priceOracleType === PriceOracleTypes.ACCEPT_CLIENT_RATE) {
this.log.warn(
`Swap is configured to dangerously use client input rate! ${stringify(swap, true, 0)}`,
);
return;
}
return validateSimpleSwapApp(
params as any,
allowedSwaps,
await this.swapRateService.getOrFetchRate(
getAddressFromAssetId(params.initiatorDepositAssetId),
getAddressFromAssetId(params.responderDepositAssetId),
stateChannel.chainId,
stateChannel.chainId, // swap within a channel is only on a single chain
),
responderDecimals,
);
}
}
};
private installOfflineTransferMiddleware = async (
appInstance: AppInstanceJson,
role: ProtocolRoles,
params: ProtocolParams.Install,
) => {
const match = await this.transferRepository.findByPaymentId(appInstance.meta.paymentId);
this.log.info(`installOfflineTransferMiddleware - match: ${stringify(match)}`);
if (match?.receiverApp) {
throw new Error(
`Node has already installed or completed linked transfer for this paymentId: ${stringify(
match,
true,
0,
)}`,
);
}
};
/**
* https://github.com/connext/indra/issues/863
* The node must not allow a sender's transfer app to be uninstalled before the receiver.
* If the sender app is installed, the node will try to uninstall the receiver app. If the
* receiver app is uninstalled, it must be checked for the following case:
* if !senderApp.latestState.finalized && receiverApp.latestState.finalized, then ERROR
*/
private uninstallTransferMiddleware = async (
appInstance: AppInstanceJson,
role: ProtocolRoles,
params: ProtocolParams.Uninstall,
) => {
// if we initiated the protocol, we dont need to have this check
if (role === ProtocolRoles.initiator) {
return;
}
const nodeSignerAddress = await this.configService.getSignerAddress();
const senderAppLatestState = appInstance.latestState as GenericConditionalTransferAppState;
const paymentId = appInstance.meta.paymentId;
// only run validation against sender app uninstall
if (senderAppLatestState.coinTransfers[1].to !== nodeSignerAddress) {
// add secret for receiver app uninstalls
this.log.info(
`Found action for receiver: ${stringify(
params.action,
true,
0,
)}, adding to transfer tracker`,
);
await this.transferRepository.addTransferAction(
paymentId,
params.action as AppAction,
appInstance.identityHash,
);
return;
}
let receiverApp = await this.transferService.findReceiverAppByPaymentId(paymentId);
// TODO: VERIFY THIS
// okay to allow uninstall if receiver app was not installed ever
if (!receiverApp) {
return;
}
this.log.info(`Starting uninstallTransferMiddleware for ${appInstance.identityHash}`);
if (receiverApp.type !== AppType.UNINSTALLED) {
this.log.info(
`Found receiver app ${receiverApp.identityHash} with type ${receiverApp.type}, attempting uninstall`,
);
try {
await this.cfCoreService.uninstallApp(
receiverApp.identityHash,
receiverApp.channel,
params.action as any,
);
this.log.info(`Receiver app ${receiverApp.identityHash} uninstalled`);
} catch (e) {
this.log.error(
`Caught error uninstalling receiver app ${receiverApp.identityHash}: ${e.message}`,
);
}
// TODO: can we optimize?
// get new instance from store
receiverApp = await this.transferService.findReceiverAppByPaymentId(
appInstance.meta.paymentId,
);
}
// double check that receiver app state has not been finalized
// only allow sender uninstall prior to receiver uninstall IFF the hub
// has not paid receiver. Receiver app will be uninstalled again on event
if (
toBN(senderAppLatestState.coinTransfers[1].amount).isZero() && // not reclaimed
toBN(receiverApp!.latestState.coinTransfers[0].amount).isZero() // finalized
) {
throw new Error(
`Cannot uninstall unfinalized sender app, receiver app has payment has been completed`,
);
}
this.log.info(`Finished uninstallTransferMiddleware for ${appInstance.identityHash}`);
};
private uninstallDepositMiddleware = async (
appInstance: AppInstanceJson,
role: ProtocolRoles,
): Promise<void> => {
const nodeSignerAddress = await this.configService.getSignerAddress();
// do not respond to user requests to uninstall deposit
// apps if node is depositor and there is an active collateralization
const latestState = appInstance.latestState as DepositAppState;
if (latestState.transfers[0].to !== nodeSignerAddress || role === ProtocolRoles.initiator) {
return;
}
const channel = await this.channelRepository.findByMultisigAddressOrThrow(
appInstance.multisigAddress,
);
const depositApps = await this.cfCoreService.getAppInstancesByAppDefinition(
channel.multisigAddress,
this.cfCoreService.getAppInfoByNameAndChain(DepositAppName, channel.chainId)!
.appDefinitionAddress,
);
const signerAddr = await this.configService.getSignerAddress();
const ours = depositApps.find((app) => {
const installedState = app.latestState as DepositAppState;
return (
installedState.assetId === latestState.assetId &&
installedState.transfers[0].to === signerAddr
);
});
if (ours) {
throw new Error(
`Cannot uninstall deposit app with active collateralization. App: ${ours.identityHash}`,
);
}
return;
};
private installMiddleware = async (cxt: InstallMiddlewareContext): Promise<void> => {
const { appInstance, role, params } = cxt;
const appDef = appInstance.appDefinition;
const appRegistryInfo = this.cfCoreService.getAppInfoByAppDefinitionAddress(appDef);
const appName = appRegistryInfo!.name;
const isTransfer = Object.keys(ConditionalTransferAppNames).includes(appName);
if (isTransfer) {
// Save the transfer
const paymentId = appInstance.meta.paymentId;
const match = await this.transferRepository.findByPaymentId(paymentId);
if (match?.receiverApp) {
// Add the receiver app to the transfer if it exists (which it should
// as soon as it is proposed)
await this.transferRepository.addTransferReceiver(paymentId, match.receiverApp);
}
const requireOnline =
RequireOnlineApps.includes(appName) || params.proposal?.meta?.requireOnline;
if (!requireOnline) {
return this.installOfflineTransferMiddleware(appInstance, role, params);
}
}
};
private uninstallMiddleware = async (cxt: UninstallMiddlewareContext): Promise<void> => {
const { appInstance, role, params } = cxt;
const appDef = appInstance.appDefinition;
const appRegistryInfo = this.cfCoreService.getAppInfoByAppDefinitionAddress(appDef);
if (Object.keys(ConditionalTransferAppNames).includes(appRegistryInfo!.name)) {
return this.uninstallTransferMiddleware(appInstance, role, params);
}
if (appRegistryInfo!.name === DepositAppName) {
return this.uninstallDepositMiddleware(appInstance, role);
}
};
async onModuleInit() {
this.log.info(`Injecting CF Core middleware`);
this.cfCoreService.cfCore.injectMiddleware(Opcode.OP_VALIDATE, await this.generateMiddleware());
this.log.info(`Injected CF Core middleware`);
}
} | the_stack |
import * as RIVAProto from "./RIVAProto";
import * as BaseTypes from "./BaseTypes";
import * as ImgCache from "./ImgCache";
import * as GraphDraw from "./GraphDraw";
//
// Our app is always one of these states:
//
// Connecting - Waiting to get the web socket connected. In this case we put up a
// transparent div that covers the whole screen and shows that we are trying to
// connect. We use a web worker to manage the socket which posts us status messages.
// When we see a connect we go to:
//
// -----------
// Init - Once we have connected, then we move to Init state. Here we basically
// wait for a login result message. It will either indicate an error in which case we
// display that error to the user and stop. Or it will indicate success and provide
// us some info. Any errors at this point are fatal so we just give up and move to
// failed state.
//
// If successful, we move to WaitTmpl state.
//
// -----------
// WaitTmpl = Nowe need to wait for the initial template to be loaded. It will be the
// default one configured for the user we logged in under. We need this to set up our
// drawing surface. We will get one even if the template failed to load. The server
// will send us a dummy one, so that we can be satisfied, and then it send us a msg
// to show to the user. The template will be empty so it won't do anything. This tells
// us how big the base template is, so we can size our canvas accordingly.
//
// Once we get this, we move to Ready state and we get rid of the 'connecting' DIV.
// And we should start seeing graphics commands for the new template.
//
// ----------
// Ready - At this point, we are in normal state where the user can interact with us.
// The server will start sending us graphics commands, we'll start sending him user
// input commands and periodic pings.
//
//
//
// It is retardedly complicated to do what we need to do because of the totally async
// nature of javascript. Even decoding an image that we already have is done async.
// And we don't want to process graphics commands until we have the images required.
//
// When we get a StartDraw, we start caching graphics commands until we get an end
// draw and/or all sent images have been added to the image cache.
//
// If we get any image data, because we don't have a required image in our image cache
// or it's been changed since what we have, we will continue to save up graphics
// commands, but we will start processing that image. Since the loading of even the
// image data is async, while doing that more graphics commands and even more image
// msgs can come in. We will queue them all up.
//
// When we get the completion event of the current image, we see if we have another
// image to load. If so, we start that one loading.
//
// We will start drawing either when:
//
// 1. We get the last EndDraw and there are no images left to load
// 2. We get the completion event on the last image in the queue and we have
// already seen the EndDraw for the last StartDraw.
//
// At that point, we start processing graphics commands in a loop. Since that is
// synchronous we can finally just drain the graphics cache and not worry about having
// to deal with anything else.
//
// It is possible that another StartDraw begins while we are processing images, and we
// don't want to assume that they will never be nested. So we have a startDraw counter.
// If that counter is zero when we see an EndDraw, then we have seen a final one and
// we know that we can start processing the graphics cache (as soon as any images
// complete.) If it's not zero, we just bump up the counter and keep going. Eventually
// we hit one of the two conditions above and start drawing.
//
//
// We only have one persistent visual component, well two. We have a DIV that fills the
// body, and in which we center the canvas on which we draw. The other two are transient,
// the connecting DIV and our options menu. These are placed absolute at 0,0 and overlap
// our content DIV while they are present. We use HTML templates to create them and then
// destroy them when we are done. So most of the time just the canvas and its containing
// DIV are present.
//
//
// We handle both mouse and touch input. We funnel both to a common handlers which
// sends messages to the server as appropriate. The server only cares about single
// point press, release, and move. But we also need to be able to invoke a menu, so
// the mouse and touch specific handlers will watch for those scenarios and invoke
// the menu DIV. Sometimes we don't know it's a menu operation until after we have had
// to send a press to the server, so we may have to send the server a cancel gesture
// message if it later turns out to be something else, such as the menu invocation, or
// just some random thing we don't handle.
//
enum EAppStates {
Connecting,
Init,
WaitTmpl,
Ready,
Failed
}
//
// A simple class we use to track download info for images. We have to queue up
// images to download and process them until we have them all. Once each one is
// fully received (it may take multiple msgs), we can add it to the image cache
// and set the image data on it. That is also async, so the image cache sends us
// an event to let us know its done. At which point we start another if it is
// available.
//
class ImgQItem {
// The image data may only be the initial chunk
constructor(public path : string,
public serNum : number,
public imgRes : BaseTypes.RIVASize,
public imgData : string,
public isPNG : boolean) {
this.isPNG = isPNG;
this.path = path;
this.serNum = serNum;
this.imgRes = imgRes;
this.imgData = imgData
}
}
// A simple class to track touch input points
class TouchPoint {
constructor(xPos : number,
yPos : number,
id : number) {
this.completed = false;
this.id = id;
this.startAt = new BaseTypes.RIVAPoint(null);
this.startAt.set(xPos, yPos);
}
// Returns true if complete and the start and end points are within a few pixels
withinMoveLimit() : boolean {
// If not completed say no
if (this.completed === false)
return false;
return (Math.abs(this.startAt.x - this.endAt.x) < 5) &&
(Math.abs(this.startAt.y - this.endAt.y) < 5)
}
update(xPos : number, yPos : number, end : boolean) {
this.endAt = new BaseTypes.RIVAPoint(null);
this.endAt.set(xPos, yPos);
this.completed = end;
}
completed : boolean;
endAt : BaseTypes.RIVAPoint;
startAt : BaseTypes.RIVAPoint;
id : number;
}
//
// We have some external scripts for supporting user extensions. So we have
// to declare these. If not used, they will be default, do-nothing implementations.
//
declare function rivaWebCamCreate
(
wdgId : string,
x : number,
y : number,
cx : number,
cy : number,
parms : string[],
extType : string
);
declare function rivaSetWebCamURL
(
tarURL : string, wdgId : string, params : string[], extType : string
);
declare function rivaWebCamDestroy(wdgId : string, extType : string);
declare function rivaWebCamSetup(wdgId : string, params : string[], extType : string);
declare function rivaDoRIVACmd(pathCmd : string, p1 : string, p2 : string, p3 : string);
//
// This is our main application which does the bulk of the work. It's fairly hefty though
// we offload a good bit of it to the image cache and web socket classes.
//
export class WebRIVAApp {
//
// Being in the background can cause us issues. CPU is heavy throttled on some
// systems when in the bacgkround. So, we try to sense when this happens. This
// flag is set, and we send a msg to the web worker. When in this state we will
// not get drawing commands. We just will exchange pings to keep the connection
// alive.
//
// So when we sense background, we send a msg to the server to tell him we are
// in the bgn and we tell the websocket web worker to go into background mode.
//
// When we sense back to the front, we tell the server about that, and we tell
// the websocket web worker to go back to normal mode. The server will force
// a full redraw to get us up to date.
//
// We set a flag to remember our bgn/fgn state so that, worst case, if we don't
// get notified of coming back to the foreground, our user input handler can
// watch this flag and force us out. Obviously if the user is interacting we are
// not in the bgn.
//
// Defaults to false in case we don't have visibility support, so we don't end
// up permanently throttled.
//
private inBgnTab : boolean = false;
// Some settable flags that affect us locally
private logGraphCmds : boolean = false;
private logImgProc : boolean = false;
private logMisc : boolean = false;
private logTouch : boolean = false;
private logWebSock : boolean = false;
private fullScreenMode : boolean = false;
private reconnSpread : number = 0;
//
// This one is just for debugging and let's us account for differences between the
// development setup and the deployed setup. It's set via &debugmode=1
//
private debugMode : boolean = false;
//
// And some that affect the server, so these must be sent to the server
// when they are changed from the default.
//
private logSrvMsgs : boolean = false;
private noCache : boolean = false;
private logGUIEvents : boolean = false;
//
// They can indicate on the URL that they want us to log to the server. WE don't do
// the graphics commands because there are a lot of messages, but the other stuff
// we do.
//
private logToServer : boolean = false;
//
// This is our current application state. It's the fundamental driver of what we do
// and how we react to messages. See the enum comments at the top of this file. We
// start in connecting mode.
//
private curState : EAppStates;
//
// The URL we will use to connect to the server. It's a well known URL,
// we just need to get the host:port part of the invocation URL and build
// it up.
//
private tarWSURL : string;
//
// Our web worker that keeps the socket going even if we are not the active
// tab.
//
private ourSock : Worker;
// The port we will invoke the websocket connection on
private wssPort : number;
// The ping message we send is always the same, so we pre-build it
private pingMsg : string;
//
// We store the user name and password for when we need to reconnect. These come
// from the original URL.
//
private userName : string;
private password : string;
//
// We don't process graphics commands until we get the EndDraw to indicate
// we have all the commands for a current redraw, and after we have processed
// any image loading operations that are pending.
//
private graphQ : Array<Object>;
//
// This is our image cache object. It contains a list of image cache items, each
// of which represents an image we got from the server.
//
private imgCache : ImgCache.ImgCache;
//
// We also queue up image messages, so that we can load them up into images
// in our image cache. We also need to keep a ref to the one we are currently
// loading, and the one we are currently storing away if it's a multi-block
// image msg.
//
// Note that we also push images into the queue if they are found in the
// persistent cache. They still need to be loaded up into images just as though
// they were downloaded.
//
private imgQ : Array<ImgQItem>;
private curImageDownloading : ImgQItem = null;
private curImageLoading : ImgQItem = null;
//
// We have an issue that we build up our 'connecting' screen from a template. It
// contains an image element that shows our logo. But, if we lose connection, and
// put the connecting screen again, it will try to load the logo from the server
// again, but it won't because we lost the server. So, the first time we connect,
// we will grab the image data and on subsequent connections we'll manually set
// the image data.
//
private logoImgData : string = "";
//
// A counter that we use to track how many StartDraw messages we have backed up.
// We can get another start while images are still downloading from the one
// before. So we don't want to start processing graphics commands upon completion
// of the last image if we have not seen the final end draw.
//
private startDrawCnt : number = 0;
// An instance of our class that wraps the canvas and handles drawing commands
private tarDraw : GraphDraw.GraphDraw = null;
// We still need to access the canvas ourself for non-drawing type things
private ourCanvas : HTMLCanvasElement = null;
// The DIV that contains the canvas and any remote widgets
private tmplDIV : HTMLDivElement = null;
// The main DIV that stuff goes into
private mainDIV : HTMLDivElement = null;
//
// This is initialized to 1.0, and is the initial viewport scaling that we set in the
// HTML. It can be set via URL to something else, and we'll update the viewport meta
// tag to reflect that.
//
private viewportScale : number;
//
// We remember if we are in a press state, so that we can discard bogus releases,
// and so we can only send move events when the user is actually tracking something,
// which is a huge efficiency win.
//
private inPressedState : Boolean;
// When doing mouse input, we remember when/where we were pressed. If they hold it
// for over three seconds and release without moving, we treat that as a menu
// invocation.
//
private mousePressedAt : BaseTypes.RIVAPoint;
private mousePressedTime : number;
//
// We can only send move/drag movements so quickly or we'll just overwhelm the
// server. So we both use the lastMousePos value to limit movement to every X
// pixels, and we use pendingMousePos and a timer to send them out no quicker
// than a certain rate.
//
// Press/release we do immediately, but moves we throttle. So we update
// lastMousePos every time we send one, or on each press/release. When we get
// a move, we store that in pendingMousePos. When the timer kicks in, if
// they are not the same, it sends the pending and sets it as the last.
//
// We only do anything if we are in ready state.
//
private lastMousePos : BaseTypes.RIVAPoint;
private pendingMousePos : BaseTypes.RIVAPoint;
private inputTimer : number;
//
// When touch input is being used, we have to deal with multiple touches. We
// have two scenarios.
//
// 1. One touch only, we send the usual press, drag, and release stuff. If another
// touch shows up, we tell the server to cancel the gesture.
// 2. Two touches where are pressed and released without moving. This is used to
// invoke the menu in touch mode. If either moves more than a few pixels,
// we don't do anything. That includes if the first one has moved by the time
// the second one shows up.
//
// So we may see a situation where we see the first touch, we send a press to the
// server, then we see a second and we just have to cancel it.
//
private touchPnts : Array<TouchPoint>;
//
// This is passed through to the extension files to allow for support of multiple
// extension schemes. It's set via &exttype=xxx. The xxx part we store here, it
// will be empty if not specificied.
//
private extType : string = "";
// ------------------------------------------------------------
// Our constructor, which does all of the setup, to get the incoming user
// provided values and set up the target websocket URL and to get the socket
// object created and then kick off the process by trying a connect.
// ------------------------------------------------------------
constructor() {
// If we were invoked via HTTPS default to WSS (and vice versa)
var doSecure : boolean = (window.location.protocol === "https:");
// But they can override
var secureParm : string = this.getURLQPByName("dosecure", window.location.search);
if (secureParm === "Yes")
doSecure = true;
//
// Set a default port. We will start with the port that they used to
// invoke the initial HTTP request. That's almost always going to
// be fight. Then we see if there is an override. The info about
// the port might not be available, so we start with the default
// port for the protocol.
//
this.wssPort = doSecure ? 443 : 80;
if (window.location.port)
this.wssPort = Number(window.location.port);
var portOver : string = this.getURLQPByName("tarport", window.location.search);
if (portOver)
this.wssPort = parseInt(portOver);
// Store the incoming name and password
this.userName = this.getURLQPByName("user", window.location.search);
this.password = this.getURLQPByName("pw", window.location.search);
//
// See if they want to enable debugging via the URL. If so, set those flags.
//
if (this.getURLQPByName("debugMode", window.location.search))
this.debugMode = true;
if (this.getURLQPByName("logimgproc", window.location.search))
this.logImgProc = true;
if (this.getURLQPByName("loggraphcmds", window.location.search))
this.logGraphCmds = true;
if (this.getURLQPByName("logmisc", window.location.search))
this.logMisc = true;
if (this.getURLQPByName("logtouch", window.location.search))
this.logTouch = true;
if (this.getURLQPByName("logwebsock", window.location.search))
this.logWebSock = true;
var spreadVal : string = this.getURLQPByName("reconnspread", window.location.search);
if (spreadVal)
this.reconnSpread = parseInt(spreadVal);
// They can also ask us to log to the server
if (this.getURLQPByName("logtosrv", window.location.search))
this.logToServer = true;
// Store the extension type if any
var extTypeCheck = this.getURLQPByName("exttype", window.location.search);
if (extTypeCheck !== null)
this.extType = extTypeCheck;
// OK now set up the URL that we'll use to make the Websocket connection
this.tarWSURL = (doSecure ? "wss://" : "ws://")
+ window.location.host.split(":")[0]
+ ":"
+ this.wssPort
+ "/Websock/CQSL/WebRIVA.html?";
// Add the user name and password to it
this.tarWSURL += "user=" + this.userName + "&pw=" + this.password;
// They can provide a session name, which we'll pass on to the server
var sessName : string = this.getURLQPByName("sessname", window.location.search);
if (sessName)
this.tarWSURL += "&sessname=" + sessName;
// They can provide environmental variables for this session as well
for (var envNum : number = 1; envNum <= 9; envNum++) {
var envVal : string = this.getURLQPByName("env" + envNum, window.location.search);
if (envVal)
this.tarWSURL += "&env" + envNum + "=" + envVal;
}
// They can override our default viewport scaling
this.viewportScale = 1.0;
var vpScale = this.getURLQPByName("vpscale", window.location.search);
if (vpScale)
this.viewportScale = Number(vpScale) || 1.0;
// Create our graphics command queue
this.graphQ = new Array<Object>();
// And our image loading queue
this.imgQ = new Array<ImgQItem>();
this.curImageDownloading = null;
this.curImageLoading = null;
//
// Create our image cache, and load up any images that we currently have
// in the cache.
//
this.imgCache = new ImgCache.ImgCache();
//
// Create our web worker that manages the web socket connection. We don't
// start it doing anything yet, we just laod it.
//
this.ourSock = new Worker("./src/Websocket.js");
// Make sure we have initial state set to the correct initial state
this.curState = EAppStates.Connecting;
// Register our handler for image load complete events
window.addEventListener(ImgCache.ImgCacheItem.CompleteEvName, this.imgLoadComplete);
// Set our unload event handler
// window.onload = this.loadHandler;
window.onunload = this.unloadHandler;
// Look up some elements we access a lot
this.ourCanvas = <HTMLCanvasElement>document.getElementById("TemplateCont");
this.tmplDIV = <HTMLDivElement>document.getElementById("TemplateDIV");
this.mainDIV = <HTMLDivElement>document.getElementById("MainDIV");
//
// Create some values we use to throttle input move/drag events sent to the server.
// Then set up our mouse and touch handlers. We handle both, assuming only one will
// be used at any given instant.
//
// We have to catch mouse release events at the window level, because there's
// pretty much no way for an element to know if a click inside him is ever released
// if the user moves the mouse outside of the element. It just calls our own mouse
// handler same as for the canvas ones.
//
// The server will ignore any ups that aren't matched to a down, so a click outside
// the canvas won't hurt anything.
//
this.lastMousePos = new BaseTypes.RIVAPoint(null);
this.pendingMousePos = new BaseTypes.RIVAPoint(null);
this.touchPnts = new Array<TouchPoint>();
this.mousePressedAt = new BaseTypes.RIVAPoint(null);
this.ourCanvas.onmousedown = this.canvasMouseHandler;
this.ourCanvas.onmousemove = this.canvasMouseHandler;
window.onmouseup = this.canvasMouseHandler;
this.ourCanvas.ontouchcancel = this.canvasTouchHandler;
this.ourCanvas.ontouchend = this.canvasTouchHandler;
this.ourCanvas.ontouchstart = this.canvasTouchHandler;
this.ourCanvas.ontouchmove = this.canvasTouchHandler;
// Start a timer that we use to send deferred user input move/drag events
this.inputTimer = setInterval(this.dragTimerHandler, 100);
// Set these to defaults that will get overridden below if needed
this.noCache = false;
this.logSrvMsgs = false;
this.logGUIEvents = false;
//
// They can force them via URL values if they want. Any that aren't set to
// the known defaults will be sent to the server upon connection.
//
this.logGUIEvents = this.getURLQPByName("logguievents", window.location.search) !== null;
this.logSrvMsgs = this.getURLQPByName("logsrvmsgs", window.location.search) !== null;
this.noCache = this.getURLQPByName("nocache", window.location.search) !== null;
// Set us up a handler for messages from the web worker
this.ourSock.addEventListener("message", this.workerMsgHandler);
// The ping message we send is always the same, so pre-build it
this.pingMsg = "{ \"" + RIVAProto.kAttr_OpCode + "\" : \"" +
RIVAProto.OpCodes.Ping.toString() + "\" }";
this.forceVPScale();
// Let's initially show our login popup
this.showLoginPopup();
//
// And now start up the web worker that manages the socket. He'll start connecting
// now and send us messages to keep us aware of the connection status. We also
// give it our initial debug state.
//
this.ourSock.postMessage({ type : "setdebug", data : this.logWebSock }, []);
this.ourSock.postMessage
(
{
type : "connect" , data : { url : this.tarWSURL, spread : this.reconnSpread }
}, []
);
// On a screen resize (mostly rotation) update our viewport scaling
window.onresize = (evt) => {
this.forceVPScale();
}
// See the comments for inBgnTab above
this.setVisHandler();
}
// Handle our loading by setting up the viewport initially
private loadHandler = () => {
this.forceVPScale();
}
// Handle our unloading by shutting down the web socket
private unloadHandler = () => {
if (this.ourSock)
this.ourSock.terminate();
}
// ------------------------------------------------------------
// This is our handler for the web worker that manages our socket connection,
// so all notifications related to our web socket come here, and some helpers
// that we call.
// ------------------------------------------------------------
workerMsgHandler = (msg : MessageEvent) => {
switch(msg.data.type) {
case "connected" :
this.wsConnect();
break;
case "disconnected" :
this.wsClose();
break;
case "msg" :
// Pass it the text of the message
this.wsMsg(msg.data.data);
break;
case "ping" :
this.sendPing();
break;
default :
break;
}
}
wsConnect() {
if (this.logWebSock)
console.log("Connected to server");
// Go to init state to wait for a login result
this.curState = EAppStates.Init;
// Reset everything else that is per-connection
this.startDrawCnt = 0;
this.inPressedState = false;
this.tarDraw = new GraphDraw.GraphDraw(this.logGraphCmds);
this.graphQ.length = 0;
this.imgQ.length = 0;
this.curImageDownloading = null;
this.curImageLoading = null;
//
// Build and send an image map message, which lets the server know what
// images, at what resolutions and with what serial numbers we already
// have. This will be empty on an initial connection, but after that, it can
// significantly reduce reconnect time since we'll already have all of
// the images.
//
// The server won't start sending drawing commands until he get this
// msg. And we send our background tab status with this msg, so if we are
// in the bgn tab upon connection, we won't get any drawing until they
// bring us forward.
//
// We also pass in the initial server flags so that they get there in time
// before content starts loading. We piggy back the current background tab
// state into the flags as well, to avoid another parameter.
//
var stateMsg : Object = new Object();
stateMsg[RIVAProto.kAttr_OpCode] = RIVAProto.OpCodes.SessionState;
this.imgCache.buildImgMapMsg(stateMsg);
var srvFlags : number = 0;
if (this.logGUIEvents)
srvFlags |= RIVAProto.kSrvFlag_LogGUIEvents;
if (this.logSrvMsgs)
srvFlags |= RIVAProto.kSrvFlag_LogSrvMsgs;
if (this.noCache)
srvFlags |= RIVAProto.kSrvFlag_NoCache;
if (this.inBgnTab)
srvFlags |= RIVAProto.kSrvFlag_InBgnTab;
stateMsg[RIVAProto.kAttr_ToSet] = srvFlags;
stateMsg[RIVAProto.kAttr_Mask] = RIVAProto.kSrvFlags_AllBits;
this.sendMsg(JSON.stringify(stateMsg));
// Let the socket worker know our current bgn/fgn state
this.ourSock.postMessage({ type : "setbgntab", data : this.inBgnTab }, []);
}
wsClose() {
//
// If we lost connection, we may have web camera or web widget elements
// that will now be orphaned. So we need to delete all children of the
// template DIV object that aren't our canvas.
//
var childElems : HTMLCollection = this.tmplDIV.children;
for (var index = 0; index < childElems.length; index++) {
if (childElems[index].nodeName.toLowerCase() == "video") {
try {
rivaWebCamDestroy(childElems[index].id, this.extType);
}
catch(e) {
this.logErr(e.toString());
}
}
}
// Go into connecting mode if not already
if (this.curState !== EAppStates.Connecting) {
this.curState = EAppStates.Connecting;
if (this.logWebSock)
console.log("Lost connection to server. Trying to reconnect...");
// Show the connecting popup
this.showLoginPopup();
}
}
//
// This is called when we get a msg from the server. We look at the msg type and
// figure out how to process it. It's just a JSON object flattened to a string.
//
// We either process the message or we get an error because the message is invalid
// or it isn't correct for our current state or it can't be processed for some
// state specific reason. Depending on the error, we may recycle the connection.
//
wsMsg(msgText : string) {
// Parse the message
var jsonData : Object = JSON.parse(msgText);
// Get the opcode number out and convert to the enum value
var opOrdinal : number = jsonData[RIVAProto.kAttr_OpCode];
var opCode : RIVAProto.OpCodes = <RIVAProto.OpCodes>opOrdinal;
//
// Check for graphics commands first, which are all below a specific value,
// then we can check for other specific msgs we handle.
//
if (opCode < RIVAProto.OpCodes.LastGraphics) {
//
// It's a graphics command. We have to be in ready state or something
// is wrong. We just queue them up.
//
if (this.curState === EAppStates.Ready) {
this.graphQ.push(jsonData);
} else {
// Log this? Could be a lot of them if something went wrong
}
} else if (opCode === RIVAProto.OpCodes.CreateRemWidget) {
this.createRemWidget(jsonData);
} else if (opCode === RIVAProto.OpCodes.DestroyRemWidget) {
this.destroyRemWidget(jsonData);
} else if (opCode === RIVAProto.OpCodes.ExitViewer) {
// Doesn't appear to be any way to do this anymore
} else if (opCode === RIVAProto.OpCodes.SetRemWidgetURL) {
this.setRemWidgetURL(jsonData);
} else if (opCode === RIVAProto.OpCodes.StartDraw) {
// Bump the start draw counter
this.startDrawCnt++;
// We add these to the queue as well
this.graphQ.push(jsonData);
if (this.logImgProc)
this.logMsg("Got start draw");
if (this.logImgProc) {
if ((this.curImageDownloading !== null) ||
(this.curImageLoading !== null) ||
(this.imgQ.length != 0)) {
this.logMsg("Still have images loading from previous cycle");
}
}
} else if (opCode === RIVAProto.OpCodes.EndDraw) {
// We add these to the queue as well
this.graphQ.push(jsonData);
// Decrement the start draw counter. Check for any underflow
this.startDrawCnt--;
if (this.startDrawCnt < 0) {
this.startDrawCnt = 0;
alert("Start Draw counter underflow");
}
// There should not be any image currently being downloaded now
if ((this.curImageDownloading !== null) && (this.startDrawCnt === 0)) {
this.logErr("No image should be downloading at end of final EndDraw");
}
//
// If there are any images that have not loaded, then do nothing, the
// finish of loading of the last outstanding image will start the
// processing.
//
if ((this.imgQ.length === 0) && (this.curImageLoading === null)) {
if (this.logImgProc)
this.logMsg("Final end draw, no images, processing msgs");
this.processGraphQ();
} else {
if (this.logImgProc)
this.logMsg("Got end draw but images outstanding");
}
} else if (opCode === RIVAProto.OpCodes.ImgDataFirst) {
// We have to be in ready state
if (this.curState === EAppStates.Ready) {
this.startImgDownload(jsonData);
} else {
if (this.logImgProc)
this.logErr("Got image start when not in ready state");
}
} else if (opCode === RIVAProto.OpCodes.ImgDataNext) {
// We have to be in ready state of this couldn't be valid
if (this.curState === EAppStates.Ready) {
this.nextImgBlock(jsonData);
} else {
if (this.logImgProc)
this.logErr("Got image next when not in ready state");
}
} else if (opCode === RIVAProto.OpCodes.LoginRes) {
//
// We should be in Init state. If so, we move to WaitTmpl state.
//
if (this.curState === EAppStates.Init) {
//
// If successful, move to wait template state. Else show the error
// and move to failed state. There are no recoverable errors at this
// point.
//
if (jsonData[RIVAProto.kAttr_Status]) {
this.curState = EAppStates.WaitTmpl;
} else {
this.curState = EAppStates.Failed;
alert(jsonData[RIVAProto.kAttr_MsgText]);
}
} else {
this.logErr("Got login results msg when not in login results mode");
}
} else if (opCode === RIVAProto.OpCodes.NewTemplate) {
//
// This one we can see either in waittmpl state or ready state. In init
// state we are getting the initial default template for the user
// who we logged in as.
//
if ((this.curState === EAppStates.WaitTmpl) ||
(this.curState === EAppStates.Ready)) {
//
// If in init mode, we can move to ready mode now and show the canvas and
// hide the login layer. After thus th
//
if (this.curState === EAppStates.WaitTmpl) {
this.curState = EAppStates.Ready;
// Hide the connecting popup
this.destroyLoginPopup();
}
// And call our method that handles updating for a new base template
this.handleNewTemplate(jsonData);
} else {
}
} else if (opCode === RIVAProto.OpCodes.RIVACmd) {
//
// If the path starts with our built in command prefix, we handle it. Else we
// pass it to the extension command.
//
var cmdPath : string = jsonData[RIVAProto.kAttr_Path];
try {
if (cmdPath.substring(0, RIVAProto.kIntRIVACmdPref.length) == RIVAProto.kIntRIVACmdPref) {
this.doRIVACmd
(
cmdPath,
jsonData[RIVAProto.kAttr_P1],
jsonData[RIVAProto.kAttr_P2],
jsonData[RIVAProto.kAttr_P3]
);
} else {
rivaDoRIVACmd
(
cmdPath,
jsonData[RIVAProto.kAttr_P1],
jsonData[RIVAProto.kAttr_P2],
jsonData[RIVAProto.kAttr_P3]
);
}
}
catch(e) {
this.logErr(e.toString());
}
} else if (opCode === RIVAProto.OpCodes.SetTmplBorderClr) {
// Set the color as the background on the DIV that contains our canvas
this.mainDIV.style.backgroundColor = jsonData[RIVAProto.kAttr_ToSet];
//
// The canvas has to be updated to make sure the upper/left boundary gets
// set to the same color as the background.
//
this.tarDraw.setLRBoundaryColor(jsonData[RIVAProto.kAttr_ToSet]);
} else if (opCode === RIVAProto.OpCodes.ShowErrorMsg) {
//
// Display the error message to the user. This doesn't necessarily
// mean we are doomed. It may be some action error. If it is a
// deadly error, we'll just get a subsequent close.
//
} else if (opCode === RIVAProto.OpCodes.ShowException) {
//
// Display the exception info to the user.
//
} else {
//
// It's one of the more general purpose messages, so handle them
// appropriately.
//
switch(opCode)
{
case RIVAProto.OpCodes.ShowMsg :
break;
default :
break;
};
}
}
// ------------------------------------------------------------
// Private helpers
// ------------------------------------------------------------
//
// We force the viewport scaling since the user can override it.
//
forceVPScale() {
if (this.viewportScale === 1.0)
return;
if (this.logMisc)
this.logMsg("viewportScale=" + this.viewportScale);
// See if we have added this yet, if not create it, else update it
// width=device-width,
var newVPContent = "initial-scale="
+ this.viewportScale + ", minimal-ui, maximum-scale=4, minimum-scale=0.1";
var viewportTag = document.querySelector('meta[name=viewport]');
if (!viewportTag) {
var newTag = document.createElement('meta');
newTag.id = "viewport";
newTag.name = "viewport";
newTag.content = newVPContent;
document.getElementsByTagName('head')[0].appendChild(newTag);
} else {
viewportTag.setAttribute('content', newVPContent);
}
}
// Get a parameter from the passed search part of a URL
private getURLQPByName(parmName : string, toSearch : string) : string {
var match = RegExp('[?&]' + parmName + '=([^&]*)').exec(toSearch);
if (match)
return match[1];
return null;
}
//
// When we get a message indicating a new base template is loading, we need to
// reset ourself in terms of graphics state, and update our drawing surface to
// the size required by the new template.
//
// The canvas is set up to stay sized to our template DIV, so resizing it will
// cause the canvas to resize, though the view it contains still needs to be
// resized as well.
//
private handleNewTemplate(msgData : Object) {
// Resize our template DIV to the size of the template
var newSize : BaseTypes.RIVASize = new BaseTypes.RIVASize(msgData[RIVAProto.kAttr_Size]);
this.tmplDIV.style.width = newSize.width + "px";
this.tmplDIV.style.height = newSize.height + "px";
// Let the canvas know about it
this.tarDraw.newTemplate(msgData);
}
//
// A helper to send a server flag setting messages to the server. The caller
// sends us the flag bit. We pass that as the mask, and then either zero or
// that value as the value to set.
//
sendServerFlag(srvFlag : number, newState : boolean) {
var toSend : Object = { };
toSend[RIVAProto.kAttr_OpCode] = RIVAProto.OpCodes.SetServerFlags;
toSend[RIVAProto.kAttr_Mask] = srvFlag;
if (newState)
toSend[RIVAProto.kAttr_ToSet] = srvFlag;
else
toSend[RIVAProto.kAttr_ToSet] = 0;
var msgText = JSON.stringify(toSend);
if (this.logMisc)
this.logMsg(msgText);
this.sendMsg(msgText);
}
// Set a handler for the visibility API if available
setVisState(newState : boolean) {
//
// Tell the server about this change. He will stop sending drawing commands until
// we go back to the foreground. Note the reversed meaning. He wants to know if
// we are visible. Our flag is whether we are in a bgn tab (not visible) or not.
// So we flip it when we send.
//
var toSend : string = "{ \"" + RIVAProto.kAttr_OpCode + "\" : \"" +
RIVAProto.OpCodes.SetVisState.toString() + "\", \"" + RIVAProto.kAttr_State +
"\" : " + (this.inBgnTab ? "false" : "true") + "}";
this.sendMsg(toSend);
if (this.logMisc) {
if (newState)
this.logMsg("Going into background tab mode");
else
this.logMsg("Coming back to foreground tab mode");
}
// Let the socket worker know about this change
this.ourSock.postMessage({ type : "setbgntab", data : this.inBgnTab }, []);
}
visChangeHandler = () => {
var visState = null;
if (typeof document["hidden"] != null)
visState = "hidden";
else if (typeof document["msHidden"] != null)
visState = "msHidden";
else if (typeof document["webkitHidden"] != null)
visState = "webkitHidden";
if ((visState !== null) && document[visState]) {
this.inBgnTab = true;
} else {
this.inBgnTab = false;
}
this.setVisState(this.inBgnTab);
}
setVisHandler() {
var visChangeEvId = null;
if (typeof document["visibilitychange"] !== null)
visChangeEvId = "visibilitychange";
else if (typeof document["msvisibilitychange"] !== null)
visChangeEvId = "msvisibilitychange";
else if (typeof document["webkitvisibilitychange"] !== null)
visChangeEvId = "webkitvisibilitychange";
if (visChangeEvId !== null)
document.addEventListener(visChangeEvId, this.visChangeHandler, false);
}
//
// To get around any inconsistent implementations, we provide our own tree dup method.
// This is used for importing HTML templates.
//
importChildNodes(srcNode) : any {
var retNode = null;
switch(srcNode.nodeType) {
case document.DOCUMENT_NODE :
case document.ELEMENT_NODE :
case document.DOCUMENT_FRAGMENT_NODE :
var name = srcNode.nodeName;
if ((name.length > 0) && (name[0] === '#')) {
name = name.slice(1);
}
var newNode = document.createElement(name);
if (srcNode.attributes && (srcNode.attributes.length > 0)) {
for (var attrInd = 0; attrInd < srcNode.attributes.length; attrInd++) {
newNode.setAttribute
(
srcNode.attributes[attrInd].nodeName
, srcNode.getAttribute(srcNode.attributes[attrInd].nodeName)
);
}
}
// Recurse on children
if (srcNode.childNodes && (srcNode.childNodes.length > 0)) {
for (var childInd = 0; childInd < srcNode.childNodes.length; childInd++) {
var newChild = this.importChildNodes(srcNode.childNodes[childInd]);
if (newChild != null)
newNode.appendChild(newChild);
}
}
retNode = newNode;
break;
case document.TEXT_NODE :
case document.CDATA_SECTION_NODE :
retNode = document.createTextNode(srcNode.nodeValue);
break;
}
return retNode;
}
// ----------------------------------------------------
// Image handling
// ----------------------------------------------------
//
// We got an image data start message. It may be a whole image, or it may be the
// chunk of a multi-chunk image transfer. If multi-we create our temp image cache
// item that we use to accumualte the data. One way or the other, when we've got
// the image data, we call processImg() below to get it into the image cache.
//
// The data is the base64 encoded PNG image.
//
private startImgDownload(msgData : Object) {
// Init our temp info to store the data till we can store it
var imgPath : string = msgData[RIVAProto.kAttr_Path];
var imgData : string = msgData[RIVAProto.kAttr_DataBytes];
var imgRes : BaseTypes.RIVASize = new BaseTypes.RIVASize(msgData[RIVAProto.kAttr_Size]);
var serialNum : number = msgData[RIVAProto.kAttr_SerialNum];
if (this.logImgProc)
this.logMsg("Start image download (SN=" + serialNum + ") : " + imgPath);
// If there's only one, then we have it, so add it to the queue
if (msgData[RIVAProto.kAttr_Last]) {
if (this.logImgProc)
this.logMsg("Single block image, so download complete");
this.imgQ.push
(
new ImgQItem
(
imgPath,
serialNum,
imgRes,
imgData,
msgData[RIVAProto.kAttr_Flag]
)
);
// If there is no image currently loading, then start one loading.
if (this.curImageLoading === null) {
if (this.logImgProc)
this.logMsg("No images currently loading, starting a new one");
this.processImg(this.imgQ.pop());
}
} else {
if (this.logImgProc)
this.logMsg("Multi block image, queuing for completion");
//
// Store this one as the current downloading image. We can't put it on the
// queue until it's done.
//
this.curImageDownloading = new ImgQItem
(
imgPath,
msgData[RIVAProto.kAttr_SerialNum],
imgRes,
imgData,
msgData[RIVAProto.kAttr_Flag]
);
}
}
private nextImgBlock(msgData : Object) {
// Make sure it's for the image we should be seeing
if (this.curImageDownloading.path !== msgData[RIVAProto.kAttr_Path]) {
alert
(
"Expected img data for '" +
this.curImageDownloading.path +
"' but got '" +
msgData[RIVAProto.kAttr_Path] +
"'"
);
}
// Add the data to our accumulator
this.curImageDownloading.imgData += msgData[RIVAProto.kAttr_DataBytes];
//
// If this is the last block, then push our guy onto the image queue to
// be processed and null out the downloading member.
//
if (msgData[RIVAProto.kAttr_Last] ) {
if (this.logImgProc)
this.logMsg("Got last image block: " + this.curImageDownloading.path);
this.imgQ.push(this.curImageDownloading);
this.curImageDownloading = null;
// If there is no image currently loading, then start one loading.
if (this.curImageLoading !== null) {
if (this.logImgProc)
this.logMsg("No images currently loading, starting a new one");
this.processImg(this.imgQ.pop());
}
}
}
//
// This is called when we get a completed image. Either because it fit in a single
// block or we got the last block. We get it into the cache or find it's existing
// entry. Then we do a set on it, which will cause it to start loading up from the
// base64 format to the actual image object.
//
// When it completes, our imgLoadComplete event handler will be called.
//
private processImg(toProc : ImgQItem) {
if (this.logImgProc)
this.logMsg("Processing image: " + toProc.path);
// Store this one as the one we are processing
this.curImageLoading = toProc;
// if it's in the cache, use that one, else a new one
var newItem : ImgCache.ImgCacheItem = this.imgCache.findItem(toProc.path);
if (newItem === null) {
newItem = new ImgCache.ImgCacheItem(toProc.path, toProc.serNum, toProc.imgRes);
this.imgCache.addImage(newItem);
}
//
// And set the new data on it. This will continue async and post us an event
// when it is done. We'll point those events to imgLoadComplete below.
//
newItem.setImageData(toProc.imgData, toProc.serNum, toProc.isPNG);
}
//
// Our handler for the custom event we register for image load completes. If there
// are more images to process, we start the next one processing.
//
// We also get this one updated in the persistent image cache. We need to do this
// wile we still have the base64 data.
//
private imgLoadComplete = (state) => {
if (this.logImgProc)
this.logMsg("Image load complete: " + this.curImageLoading.path);
// Null out the loading pointer
this.curImageLoading = null;
//
// See if there is another image available to start loading. If so, start
// it up. If there are not, and there's not one currently downloading, and
// we have seen the last EndDraw, then let's start processing graphics
// commands.
//
var nextImg : ImgQItem = this.imgQ.pop();
if (nextImg) {
if (this.logImgProc)
this.logMsg("More images to download, starting next one");
this.processImg(nextImg);
} else if ((this.startDrawCnt === 0) && !this.curImageDownloading) {
if (this.logImgProc)
this.logMsg("No more images to process, processing msgs");
this.processGraphQ();
}
}
// ----------------------------------------------------
// Drawing command processing
// ----------------------------------------------------
//
// This is called when we have all of the graphics commands and images for
// the current update cycle from the server. We just loop through the queued
// commands and process them.
//
processGraphQ() {
if (this.logGraphCmds)
console.log("Processing queued graphics cmds");
var opCode : RIVAProto.OpCodes;
while (this.graphQ.length) {
try{
var curMsg : Object = this.graphQ.shift();
opCode = <RIVAProto.OpCodes>curMsg[RIVAProto.kAttr_OpCode];
if (this.logGraphCmds)
this.logGraphicsCmd(curMsg);
if (!this.tarDraw.handleGraphicsCmd(opCode, curMsg, this.imgCache)) {
if (this.logGraphCmds)
console.log("Unhandled opcode: " + opCode);
}
}
catch(e) {
if (this.logGraphCmds)
console.error("Got an exception in graphics command: " + opCode);
}
}
}
// ----------------------------------------------------
// User input handling
// ----------------------------------------------------
// A timer we use to send deferred move/drag messages
dragTimerHandler = () => {
// If the pending and last mouse move points aren't the same send one
if (!this.pendingMousePos.samePoint(this.lastMousePos)) {
// Store the pending as the last
this.lastMousePos.setFrom(this.pendingMousePos);
// We only actually need to send it if in ready state
if (this.curState === EAppStates.Ready) {
var toSend : string = "{ \"" + RIVAProto.kAttr_OpCode + "\" : \"" +
RIVAProto.OpCodes.Move.toString() + "\", \"" + RIVAProto.kAttr_At +
"\" : \"" + this.lastMousePos.x + "," + this.lastMousePos.y + "\""
+ "}";
this.sendMsg(toSend);
}
}
}
//
// A common method to process incoming mouse and touch events. We have separate event
// handlers for those, which massage the values as needed and pass them on to this
// method for generic handling. They give us the raw positions so that they don't
// have to redundandtly translate them, and so that we can log msgs that match the
// original touch positions.
//
processInput(opCode : RIVAProto.OpCodes, xRaw : number, yRaw : number, minMove : number) {
//
// Absolute worse case, if we missed the fact that we came back to the foreground,
// we catch it here and force us back to foreground mode.
//
if (this.inBgnTab) {
this.inBgnTab = false;
this.setVisState(this.inBgnTab);
if (this.logMisc)
this.logMsg("User input forcing us back to foreground mode");
}
// Adjust the raw positions to account for window scrolling
var canvasRect : ClientRect = this.ourCanvas.getBoundingClientRect();
var xPos = Math.floor(xRaw - (canvasRect.left + window.scrollX));
var yPos = Math.floor(yRaw - (canvasRect.top + window.scrollY));
//
// If we aren't up and going, don't do anything. But we do keep the two mouse
// positions updated.
//
if (this.curState !== EAppStates.Ready)
{
// Make absolutely sure we get back to unpressed state
this.inPressedState = false;
this.lastMousePos.set(xPos, yPos);
this.pendingMousePos.set(xPos, yPos);
if (this.logTouch)
this.logMsg("Ignoring input, not in ready state");
return false;
}
// We need to do it, so let's get set up
if (opCode === RIVAProto.OpCodes.Press) {
// Set the last and pending mouse positions to this
this.lastMousePos.set(xPos, yPos);
this.pendingMousePos.set(xPos, yPos);
if (this.logTouch)
this.logMsg("Got press at " + xRaw + "," + yRaw);
} else if (opCode === RIVAProto.OpCodes.Release) {
// Set the last and pending mouse positions to this
this.lastMousePos.set(xPos, yPos);
this.pendingMousePos.set(xPos, yPos);
if (this.logTouch)
this.logMsg("Got release at " + xRaw + "," + yRaw);
} else if (opCode === RIVAProto.OpCodes.Move) {
//
// If we aren't in press state, then just update both values. If we
// are, then queue it up as a pending move if it has changed more than
// the minimum move amount passed.
//
if (this.inPressedState === false) {
this.lastMousePos.set(xPos, yPos);
this.pendingMousePos.set(xPos, yPos);
} else {
//
// If we've moved more than the indicated minimum change in either
// direction, queue it up. This cuts down on lots of small events
// when moving slowly.
//
if ((Math.abs(xPos - this.lastMousePos.x) > minMove)
|| (Math.abs(yPos - this.lastMousePos.y) > minMove))
{
// Store a pending mouse move
this.pendingMousePos.set(xPos, yPos);
}
}
return false;
}
//
// If we are not current in pressed state, ignore any release. Do this after
// updating the mouse position above, since it is still obviously a legitimate
// mouse event.
//
if (opCode === RIVAProto.OpCodes.Release) {
if (this.inPressedState === false) {
if (this.logTouch)
this.logMsg("Ignoring release, not in pressed state");
return false;
}
if (this.logTouch)
this.logMsg("Exiting pressed state");
this.inPressedState = false;
} else if (opCode === RIVAProto.OpCodes.Press) {
this.inPressedState = true;
if (this.logTouch)
this.logMsg("Entering pressed state");
}
// Format a message and send it
var toSend : string = "{ \"" + RIVAProto.kAttr_OpCode + "\" : \"" +
opCode.toString() + "\", \"" + RIVAProto.kAttr_At +
"\" : \"" + xPos + "," + yPos + "\""
+ "}\n";
if (this.logTouch) {
this.logMsg
(
"Sending " +
RIVAProto.OpCodes[opCode] +
" msg, pos=" +
xRaw + "/" +
yRaw
);
}
this.sendMsg(toSend);
}
//
// Handle mouse and touch input. We do the mouse or touch event specific stuff then
// pass the results on to the common input processing method above. He passes it
// on to the server if appropriate.
//
canvasMouseHandler = (e : MouseEvent) => {
// Prevent default browser response
e.preventDefault();
// If the main button, then we process it as user input. Others we ignore
if (e.button === 0) {
// Convert the event into a RIVA opcode
var opCode : RIVAProto.OpCodes = RIVAProto.OpCodes.OpCode_None;
if (e.type === "mousedown") {
opCode = RIVAProto.OpCodes.Press;
// Remember where and when
this.mousePressedAt.set(e.pageX, e.pageY);
this.mousePressedTime = Date.now();
} else if (e.type === "mouseup") {
//
// If held over three seconds and not moved more than a few pixels,
// then cancel the gesture and treat it as a menu invocation.
//
var Test : number = Date.now() - this.mousePressedTime;
if (this.inPressedState
&& (((Date.now() - this.mousePressedTime) / 1000) >= 2.5)
&& (Math.abs(this.mousePressedAt.x - e.pageX) < 3)
&& (Math.abs(this.mousePressedAt.y - e.pageY) < 3)) {
this.cancelTouch(true);
this.showMenuPopup();
} else {
// Else process it as a release
opCode = RIVAProto.OpCodes.Release;
}
} else if (e.type === "mousemove") {
opCode = RIVAProto.OpCodes.Move;
}
// Call the common handler, passing the raw coordinates if not eaten
if (opCode !== RIVAProto.OpCodes.OpCode_None)
this.processInput(opCode, e.pageX, e.pageY, 1);
}
return false;
}
//
// A helper to cancel an input operation. This is only used really for
// touch screen input. Mouse input never cancels, though they may ultimately
// move outside the initial widget and cause the release to be ignored.
//
cancelTouch(clearPntList : boolean) {
//
// Clear any tracking related stuff, but not touch points since we still
// may be tracking a menu invocation gesture.
//
this.inPressedState = false;
if (clearPntList)
this.touchPnts.length = 0;
var toSend : string = "{ \"" + RIVAProto.kAttr_OpCode + "\" : \"" +
RIVAProto.OpCodes.CancelInput.toString() + "\"}";
if (this.logTouch)
this.logMsg("Cancelling touch input");
this.sendMsg(toSend);
return false;
}
canvasTouchHandler = (e : TouchEvent) => {
// Prevent it from propagating
e.preventDefault();
if (this.logTouch) {
this.logMsg("Touch event. Type=" + e.type + ", Count=" + e.changedTouches.length);
for (var ind = 0; ind < e.changedTouches.length; ind++) {
var curPnt : Touch = e.changedTouches[ind];
this.logMsg(" Id=" + curPnt.identifier + ", At=" + curPnt.pageX + "/" + curPnt.pageY);
}
}
var opCode : RIVAProto.OpCodes = RIVAProto.OpCodes.OpCode_None;
var xPos : number;
var yPos : number;
if (e.type === "touchstart") {
//
// If there is only one touch point down and it's a start, then this has to
// be an initial touch, so clear our list.
//
if (e.touches.length === 1) {
this.touchPnts.length = 0;
if (this.logTouch)
this.logMsg("Saw initial touch, starting gesture");
}
//
// We know that, if the incoming new points plus the count we have is
// more than 2, it cannot be valid no matter what and this simplifies
// the rest of the logic.
//
// It doesn't matter if some have come and gone. All we care about is
// how many have happened. We can only have one or two, total.
//
var combinedPnts : number = this.touchPnts.length + e.changedTouches.length;
if (combinedPnts > 2) {
if (this.logTouch)
this.logMsg("More than 2 touch points, cancelling");
// Clear our touch list as well
this.cancelTouch(true);
return false;
}
// Add them to our list with id and start pos
for (var ind = 0; ind < e.changedTouches.length; ind++) {
var curPnt : Touch = e.changedTouches[ind];
this.touchPnts.push(new TouchPoint(curPnt.pageX, curPnt.pageY, curPnt.identifier));
}
//
// If it's now a single touch, then a provisional gesture so send the press
// event. If we now have more than one, then cancel the gesture, though we
// may still see a menu invocation later.
//
if (combinedPnts == 1) {
opCode = RIVAProto.OpCodes.Press;
xPos = e.changedTouches[0].pageX;
yPos = e.changedTouches[0].pageY;
} else {
if (this.logTouch)
this.logMsg("More than one touch point, cancelling gesture");
// But don't clear touch points
this.cancelTouch(false);
return false;
}
} else if (e.type === "touchend") {
// End these touch points in our list.
for (var ind = 0; ind < e.changedTouches.length; ind++) {
var curPnt : Touch = e.changedTouches[ind];
this.updateTouchPnt(curPnt.pageX, curPnt.pageY, curPnt.identifier, true);
}
// If there are no more active touch points we need to deal with it.
if (e.touches.length === 0) {
// If we only ever saw a single point, then this has to be the one
// that is ending, so this is a completed gesture and we need to send
// a release if we are still tracking.
//
// If there are two, we see if they have not moved too much. If not,
// then we invoke the menu.
//
if (this.touchPnts.length == 1) {
if (this.logTouch && (e.changedTouches[0].identifier !== this.touchPnts[0].id))
this.logErr("Released touch point is not the one we remembered");
if (this.inPressedState) {
opCode = RIVAProto.OpCodes.Release;
xPos = e.changedTouches[0].pageX;
yPos = e.changedTouches[0].pageY;
}
} else if (this.touchPnts.length === 2) {
if (this.touchPnts[0].withinMoveLimit() &&
this.touchPnts[1].withinMoveLimit())
{
this.touchPnts.length = 0;
if (this.logTouch)
this.logMsg("Got valid touch menu invocation gesture");
this.showMenuPopup();
}
}
// We can clear our list now
this.touchPnts.length = 0;
}
} else if (e.type === "touchmove") {
// Update these touch points if in our list
for (var ind = 0; ind < e.changedTouches.length; ind++) {
var curPnt : Touch = e.changedTouches[ind];
this.updateTouchPnt(curPnt.pageX, curPnt.pageY, curPnt.identifier, false);
}
// If we still only have only seen one touch point, it's a move
if (this.touchPnts.length === 1) {
opCode = RIVAProto.OpCodes.Move;
xPos = e.changedTouches[0].pageX;
yPos = e.changedTouches[0].pageY
}
} else if (e.type === "touchcancel") {
// Doesn't matter what point it is, we give up.
this.touchPnts.length = 0;
opCode = RIVAProto.OpCodes.CancelInput;
xPos = e.changedTouches[0].pageX;
yPos = e.changedTouches[0].pageY;
}
if (opCode !== RIVAProto.OpCodes.OpCode_None)
this.processInput(opCode, xPos, yPos, 2);
return false;
}
//
// We find the passed touch point in our list and mark it complete and store its
// final position.
//
updateTouchPnt(xPos : number, yPos : number, id : number, end : boolean) {
for (var ind = 0; ind < this.touchPnts.length; ind++) {
var curPnt : TouchPoint = this.touchPnts[ind];
if (curPnt.id == id) {
curPnt.update(xPos, yPos, end);
return;
}
}
// We never found it
if (this.logTouch)
this.logMsg("Changed touch point was not in our list");
}
// ----------------------------------------------------
// Login popup menu stuff
// ----------------------------------------------------
//
// These methods show and destroy the login 'popup'. It is created on the fly
// from an HTML template. We add it to the main body, which puts it on top of
// the canvas.
//
showLoginPopup() {
// Load our login popup template and get a copy of the nodes
var toLoad : HTMLTemplateElement = <HTMLTemplateElement>document.getElementById("LoginPopupTmpl");
var tmplCopy = this.importChildNodes(toLoad.content);
// Get main DIV and load the imported nodes into it
var mainDIV : HTMLDivElement = this.mainDIV;
mainDIV.appendChild(tmplCopy);
//
// If we have stored the logo image data, set it directly. Else set the path on
// it so it will load it.
//
var logoImg : HTMLImageElement = <HTMLImageElement>document.getElementById("CQSLLogo");
if (this.logoImgData)
logoImg.src = this.logoImgData;
else
logoImg.src = "/CQCImg/System/Logos/CQS_Small";
}
destroyLoginPopup() {
//
// Before we destroy it, if we have not already, grab the image data from the logo
// image.
//
if (!this.logoImgData) {
var logoImg : HTMLImageElement = <HTMLImageElement>document.getElementById("CQSLLogo");
// We need to create a temp canvas and draw the image into it
var tmpCanvas : HTMLCanvasElement = document.createElement("canvas");
tmpCanvas.height = logoImg.height;
tmpCanvas.width = logoImg.width;
tmpCanvas.style.height = logoImg.height.toString();
tmpCanvas.style.width = logoImg.width.toString();
var tmpCtx : CanvasRenderingContext2D = tmpCanvas.getContext("2d");
try {
tmpCtx.drawImage(logoImg, 0, 0);
// Now we can get it to give us the base64 image URL
this.logoImgData = tmpCanvas.toDataURL();
}
catch(e)
{
}
}
document.getElementById("LoginPopup").remove();
}
// ----------------------------------------------------
// Options menu stuff
// ----------------------------------------------------
//
// These methods show and destroy the options menu 'popup'. It is created on
// the fly from an HTML template. We add it to the main div which puts it on top
// of the canvas.
//
showMenuPopup() {
// Load our login popup template and get a copy of the nodes
var toLoad : HTMLTemplateElement = <HTMLTemplateElement>document.getElementById("PopupMenuTmpl");
var tmplCopy = this.importChildNodes(toLoad.content);
// Get main DIV and load the imported nodes into it
var mainDIV : HTMLDivElement = this.mainDIV;
mainDIV.appendChild(tmplCopy);
// Set up the click handlers now
document.getElementById("FullScreen").onclick = this.menuClickHandler;
document.getElementById("LogGraphCmds").onclick = this.menuClickHandler;
document.getElementById("LogImgProc").onclick = this.menuClickHandler;
document.getElementById("LogMisc").onclick = this.menuClickHandler;
document.getElementById("LogTouch").onclick = this.menuClickHandler;
document.getElementById("LogWebSock").onclick = this.menuClickHandler;
document.getElementById("LogGUIEvents").onclick = this.menuClickHandler;
document.getElementById("LogSrvMsgs").onclick = this.menuClickHandler;
document.getElementById("NoCache").onclick = this.menuClickHandler;
// Update the menu to make sure it reflects current settings
this.updateMenuItem("LogGraphCmds", this.logGraphCmds);
this.updateMenuItem("LogImgProc", this.logImgProc);
this.updateMenuItem("LogMisc", this.logMisc);
this.updateMenuItem("LogTouch", this.logTouch);
this.updateMenuItem("LogWebSock", this.logWebSock);
this.updateMenuItem("LogGUIEvents", this.logGUIEvents);
this.updateMenuItem("LogSrvMsgs", this.logSrvMsgs);
this.updateMenuItem("NoCache", this.noCache);
this.updateMenuItem("FullScreen", this.fullScreenMode);
document.getElementById("MenuClose").onclick = this.menuClickHandler;
}
destroyMenuPopup() {
document.getElementById("PopupMenu").remove();
}
//
// A helper to update a context menu item. We hide/show the check mark image based
// the state of the item.
//
updateMenuItem(itemId : string, state : boolean) {
var tarImg : HTMLImageElement = (<HTMLImageElement>document.getElementById(itemId + "Check"));
if (state)
tarImg.style.visibility = "visible";
else
tarImg.style.visibility = "hidden";
}
// A click handler for our menu items and the menu close button
menuClickHandler = (srcevent : Event) => {
var event = srcevent.srcElement as HTMLElement;
srcevent.preventDefault();
// Handle the special case of closing the menu. This simplifies the stuff below
if (srcevent.srcElement.id === "MenuClose") {
this.destroyMenuPopup();
// This can mess up our input stuff, so be extra careful
this.inPressedState = false;
this.touchPnts.length = 0;
return false;
}
// Has to be one of the checked options
var newState : boolean = null;
var srvFlag : number = RIVAProto.kSrvFlag_None;
// Local stuff, where we just toggle our local flag
if (event.id === "LogGraphCmds") {
this.logGraphCmds = !this.logGraphCmds;
newState = this.logGraphCmds;
} else if (event.id === "LogImgProc") {
this.logImgProc = !this.logImgProc;
newState = this.logImgProc;
} else if (event.id === "LogMisc") {
this.logMisc = !this.logMisc;
newState = this.logMisc;
} else if (event.id === "LogTouch") {
this.logTouch = !this.logTouch;
newState = this.logTouch;
} if (event.id === "LogWebSock") {
this.logWebSock = !this.logWebSock;
newState = this.logWebSock;
// Update our web worker
this.ourSock.postMessage({ type : "setdebug", data : newState }, []);
// Server related flags. We toggle a local flag but need to tell the server also
} else if (event.id === "LogGUIEvents") {
this.logGUIEvents = !this.logGUIEvents;
srvFlag = RIVAProto.kSrvFlag_LogGUIEvents;
newState = this.logGUIEvents;
} else if (event.id === "LogSrvMsgs") {
this.logSrvMsgs = !this.logSrvMsgs;
srvFlag = RIVAProto.kSrvFlag_LogSrvMsgs
newState = this.logSrvMsgs;
} else if (event.id === "NoCache") {
this.noCache = !this.noCache;
srvFlag = RIVAProto.kSrvFlag_NoCache
newState = this.noCache;
// Enter or exit full screen
} else if (event.id === "FullScreen") {
if (this.fullScreenMode) {
this.fullScreenMode = false;
this.exitFullScreen();
} else {
this.fullScreenMode = true;
this.enterFullScreen();
}
}
// Update the menu item's check mark
this.updateMenuItem(event.id, newState);
// If it's one of the ones related to the server, we need to pass it on
if (srvFlag !== RIVAProto.kSrvFlag_None)
this.sendServerFlag(srvFlag, newState);
return false;
}
// ----------------------------------------------------
// We use a web worker to manage the socket, so we provide this helper to hide
// the details of how messages get sent.
// ----------------------------------------------------
sendMsg(toSend : string) {
//
// We just post the message to our worker, with the approriate info to tell him
// it's a message to send.
//
this.ourSock.postMessage( { type : "send", data : toSend } );
}
// Sends out a ping message, which we do from a couple places
sendPing() {
// Just log this to the local console
if (this.logMisc)
console.log("Sending ping");
this.sendMsg(this.pingMsg);
}
// ----------------------------------------------------
// Internally handled RIVACmd operations are passed here for processing. Others are passed
// to the extension file.
// ----------------------------------------------------
doRIVACmd(pathCmd : string, p1 : string, p2 : string, p3 : string) {
if (pathCmd === RIVAProto.kIntRIVACmd_LoadURLTab) {
//
// Just invoke a tab. p1 is the URL, and p2 is the tab name
//
var newTab = window.open(p1, p2);
newTab.focus();
} else {
if (this.logMisc)
console.log("Unknown internal RIVA cmd: " + pathCmd);
}
}
// ----------------------------------------------------
// Methods related to the special 'remote widgets' where we have to
// create a visual element ourself.
// ----------------------------------------------------
createRemWidget(msgData : Object) {
// Figure out which type
var ordVal : number = msgData[RIVAProto.kAttr_Type];
var wdgType : RIVAProto.WdgTypes = <RIVAProto.WdgTypes>(ordVal);
// And now create the appropriate thing
if (wdgType === RIVAProto.WdgTypes.WebBrowser) {
// Not dealt with yet
} else if (wdgType === RIVAProto.WdgTypes.WebCamera) {
// Get the parameters. This is just the raw JSON
var params = msgData[RIVAProto.kAttr_Params];
//
// This is the position relative to the overall template, which means
// the canvas in our case, and therefore the template DIV. So we set
// it absolute relative to the template DIV>
//
var atPos : BaseTypes.RIVAArea = new BaseTypes.RIVAArea(msgData[RIVAProto.kAttr_At]);
// Create the unique id for this widget
var wdgId : string = RIVAProto.WdgTypes[wdgType] + msgData[RIVAProto.kAttr_Id];
//
// Create a new element at the indicated area. We let them do it if they
// want. If they don't, then we will create a standard video element.
//
var newCam : HTMLVideoElement;
newCam = rivaWebCamCreate
(
wdgId, atPos.x, atPos.y, atPos.width, atPos.height, params, this.extType
);
if (newCam === null) {
newCam = document.createElement('video');
if (newCam) {
newCam.id = wdgId;
newCam.style.left = atPos.x.toString() + "px";
newCam.style.top = atPos.y.toString() + "px";
newCam.style.width = atPos.width.toString() + "px";
newCam.style.height = atPos.height.toString() + "px";
newCam.style.visibility = "visible";
newCam.style.position = "absolute";
newCam.style.zIndex = "1000";
// Typescript is incorrect on this one so we have to do it this way
newCam["autoplay"] = true;
// Since we created it, let them do post setup
rivaWebCamSetup(wdgId, params, this.extType);
}
}
else {
this.logMsg("Cam widget created via extension");
// Just to be sure, make sure the widget id is set
newCam.id = wdgId;
}
// If it got created, then add it to the DOM
if (newCam !== null)
this.tmplDIV.appendChild(newCam);
}
}
destroyRemWidget(msgData : Object) {
// Figure out which type
var ordVal : number = msgData[RIVAProto.kAttr_Type];
var wdgType : RIVAProto.WdgTypes = <RIVAProto.WdgTypes>(ordVal);
// Build the unique id and try to remove this element
var wdgId : string = RIVAProto.WdgTypes[wdgType] + msgData[RIVAProto.kAttr_Id];
// Find the video widget and destroy it
var toDestroy : HTMLElement = document.getElementById(wdgId);
if (toDestroy) {
// Let the client's code do any required cleanup first
try {
if (wdgType === RIVAProto.WdgTypes.WebCamera) {
this.logMsg("Destroying web cam widget: " + wdgId);
rivaWebCamDestroy(wdgId, this.extType);
}
}
catch(e) {
this.logErr(e.toString());
}
} else {
this.logMsg("Video widget to destroy was not found");
}
}
//
// This is called to update the URL of a remote widget.
//
setRemWidgetURL(msgData : Object) {
// Figure out which type
var ordVal : number = msgData[RIVAProto.kAttr_Type];
var wdgType : RIVAProto.WdgTypes = <RIVAProto.WdgTypes>(ordVal);
// Build up the unique widget id and use that to look up the element
var wdgId : string = RIVAProto.WdgTypes[wdgType] + msgData[RIVAProto.kAttr_Id];
var tarElem : HTMLElement = document.getElementById(wdgId);
if (tarElem) {
var tarURL = msgData[RIVAProto.kAttr_ToLoad];
var optParms = msgData[RIVAProto.kAttr_Params];
// Let the client's code do any required cleanup first
try {
if (wdgType === RIVAProto.WdgTypes.WebCamera) {
this.logMsg("Setting web cam URL: " + wdgId);
rivaSetWebCamURL(wdgId, tarURL, optParms, this.extType);
}
}
catch(e) {
this.logErr(e.toString());
}
}
}
// ----------------------------------------------------
// Helpers for full screen API support
// ----------------------------------------------------
fullScreenPossible() : boolean {
var retVal : boolean = false;
if (document.fullscreenEnabled) {
retVal = document.fullscreenEnabled;
} else if (document['msFullscreenEnabled']) {
retVal = document['msFullscreenEnabled'];
} else if (document['webkitFullscreenEnabled']) {
retVal = document['webkitFullscreenEnabled'];
} else if (document['mozFullscreenEnabled']) {
retVal = document['mozFullscreenEnabled'];
}
return retVal;
}
enterFullScreen() {
if (this.fullScreenPossible()) {
var tarElem : HTMLElement = document.documentElement;
if (tarElem.requestFullscreen) {
tarElem.requestFullscreen();
} else if (tarElem['msRequestFullscreen']) {
tarElem['msRequestFullscreen']();
} else if (tarElem['webkitRequestFullscreen']) {
tarElem['webkitRequestFullscreen']();
} else if (tarElem['mozRequestFullscreen']) {
tarElem['mozRequestFullscreen']();
}
} else {
alert("Full screen access is not available on this browser");
}
}
exitFullScreen() {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document['msExitFullscreen']) {
document['msExitFullscreen']();
} else if (document['webkitExitFullscreen']) {
document['webkitExitFullscreen']();
} else if (document['mozExitFullscreen']) {
document['mozExitFullscreen']();
}
}
// ----------------------------------------------------
// A helper to log graphics commands to the console, in a readable way, since
// they are heavily compressed by using numeric ids for lots of stuff.
// ----------------------------------------------------
logGraphicsCmd(toLog : Object) {
var msgText : string = "GMSG: ";
// Get the opcode out and to a string
var opNum : number = toLog[RIVAProto.kAttr_OpCode];
msgText += RIVAProto.OpCodes[opNum];
// And now loop through all the values
var valInd : number = 0;
Object.keys(toLog).forEach((key : string) => {
// Eat this one. We did it explicitly above to make sure it's first
if (key !== RIVAProto.kAttr_OpCode) {
if (valInd === 0)
msgText + " - ";
msgText += ", ";
// Translate some of them
switch(key) {
case RIVAProto.kAttr_ClipMode :
msgText += "ClipMode=";
var mode : RIVAProto.ClipModes = <RIVAProto.ClipModes>Number(toLog[key]);
msgText += RIVAProto.ClipModes[mode];
break;
case RIVAProto.kAttr_ClipArea :
msgText += "ClipArea=" + toLog[key];
break;
case RIVAProto.kAttr_SrcArea :
msgText += "SrcArea=" + toLog[key];
break;
case RIVAProto.kAttr_TarArea :
msgText += "TarArea=" + toLog[key];
break;
case RIVAProto.kAttr_ToDraw :
msgText += "ToDraw=" + toLog[key];
break;
default :
msgText += key + "=" + toLog[key];
break;
}
valInd++;
}
});
// These we always log to the console, even if server logging is enabled
console.log(msgText);
}
// ----------------------------------------------------
// This is our single message logging method. Everyone (except the graphics cmds
// logging) has to call this so that we can redirect to the web server if asked
// to do so. For mobile devices this is a very useful option. Else we log to the
// local console, which is best used where available.
// ----------------------------------------------------
private logErr(toLog : string) {
if (this.logToServer) {
var toSend : string = "{ \"" + RIVAProto.kAttr_OpCode + "\" : " +
"\"" + RIVAProto.OpCodes.LogMsg.toString() + "\", " +
"\"" + RIVAProto.kAttr_MsgText + "\" : \"" + toLog + "\", " +
"\"" + RIVAProto.kAttr_Flag + "\" : true" +
"}";
this.sendMsg(toSend);
} else {
console.log(toLog);
}
}
private logMsg(toLog : string) {
if (this.logToServer) {
var toSend : string = "{ \"" + RIVAProto.kAttr_OpCode + "\" : " +
"\"" + RIVAProto.OpCodes.LogMsg.toString() + "\", " +
"\"" + RIVAProto.kAttr_MsgText + "\" : \"" + toLog + "\", " +
"\"" + RIVAProto.kAttr_Flag + "\" : false" +
"}";
this.sendMsg(toSend);
} else {
console.log(toLog);
}
}
}
// Create our one global object
var ourApp : WebRIVAApp = new WebRIVAApp(); | the_stack |
import { List, Map as IMMap } from 'immutable';
import * as BackUtils from '../backend/backUtils';
import { Context, ContextSet } from '../backend/context';
import { ShEnv } from '../backend/sharpEnvironments';
import {
CodeSource,
ShValue,
SVAddr,
SVFunc,
SVInt,
SVNone,
SVObject,
SVString,
SVType,
SVUndef,
} from '../backend/sharpValues';
import { SymExp } from '../backend/symExpressions';
import { TorchBackend } from '../backend/torchBackend';
import { LibCallType, TEConst, TEObject, TSLet, TSReturn } from '../frontend/torchStatements';
import { PyteaService } from '../service/pyteaService';
import * as PyteaUtils from '../service/pyteaUtils';
import { LCImpl } from '.';
export namespace LCBase {
export type BaseParamType =
| ImportParams
| SetDefaultParams
| CallKVParams
| ExportGlobalParams
| RaiseParams
| ExplicitParams;
export interface ExplicitParams {
params: ShValue[];
}
export function explicit(ctx: Context<ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> {
// placeholder. explicit call is evaluated in evalLibCall.
return ctx.warnWithMsg('unimplemented libcall', source).toSet();
}
// return new class object of `object`
export function objectClass(ctx: Context<ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> {
const { heap } = ctx;
const [tempClass, objectAddr, newHeap] = SVObject.create(heap, source);
let objectClass = tempClass;
const objInit = SVFunc.create(
'__init__',
List(['self']),
TSReturn.create(TEConst.genNone()),
new ShEnv(),
source
);
const objNew = SVFunc.create('__new__', List(['cls']), TSReturn.create(TEObject.create()), new ShEnv(), source);
objectClass = objectClass.setAttr('__init__', objInit);
objectClass = objectClass.setAttr('__new__', objNew);
return ctx.setHeap(newHeap.setVal(objectAddr, objectClass)).toSetWith(objectAddr);
}
// return module object.
export interface ImportParams {
qualPath: string;
assignTo?: string;
}
// import is JS reserved keyword.
export function thImport(ctx: Context<ImportParams>, source: CodeSource | undefined): ContextSet<ShValue> {
const service = PyteaService.getGlobalService();
if (!service) {
return ctx.failWithMsg('PyTea service uninitialized.', source).toSet();
}
const assignTo = ctx.retVal.assignTo;
const qualPath = ctx.retVal.qualPath;
const currPath = ctx.relPath;
const paths = PyteaUtils.scanQualPath(qualPath, currPath);
let baseEnv = ctx.env;
const basePath = ctx.relPath;
const lastPath = paths[paths.length - 1];
const hasWild = lastPath.endsWith('*');
const wildId = paths.length - 1;
let ctxSet: ContextSet<any> = ctx.toSet();
paths.forEach((libRelPath, index) => {
// import wildcard
if (hasWild && libRelPath.endsWith('*')) {
return;
}
// do not import twice
ctxSet = ctxSet.flatMap((ctx) => {
const currEnv = ctx.env;
let imported = ctx.imported;
if (imported.addrMap.has(libRelPath)) {
return ctx.toSet();
}
const [stmt, isInit] = service.getImportModuleStmt(libRelPath);
if (!stmt) return ctx.toSet();
const newPath = isInit ? `${libRelPath}.__init__` : libRelPath;
const [moduleAddr, moduleHeap0] = ctx.heap.allocNew(SVUndef.create(source), source);
const [nameAddr, moduleHeap] = moduleHeap0.allocNew(SVString.create(libRelPath, source), source);
imported = imported.setId(libRelPath, moduleAddr);
const defaultEnv = currEnv.set(
'addrMap',
currEnv.addrMap.filter((v) => v.addr < 0).set('__name__', nameAddr)
);
const newCtx = ctx.setEnv(defaultEnv).setHeap(moduleHeap).setImported(imported).setRelPath(newPath);
const ctxSet = TorchBackend.runModule(stmt as TSLet, newPath, newCtx);
return ctxSet.map((ctx) => {
const env = ctx.env;
let heap = ctx.heap;
let imported = ctx.imported;
env.addrMap.forEach((addr, id) => {
if (addr.addr >= 0) {
imported = imported.setId(`${libRelPath}.${id}`, addr);
}
});
heap = heap.setVal(moduleAddr, ctx.retVal);
if (hasWild && index === wildId - 1) {
baseEnv = baseEnv.mergeAddr(env);
const moduleBase = baseEnv.getId('$module');
const moduleAddr = BackUtils.sanitizeAddr(moduleBase, heap);
// assign imported variables to $module.
// (wildcard import does not controlled by frontend)
if (moduleAddr && moduleAddr.type === SVType.Addr) {
const moduleObj = heap.getVal(moduleAddr);
if (moduleObj && moduleObj.type === SVType.Object) {
let obj: SVObject = moduleObj;
env.addrMap.forEach((addr, id) => {
if (addr.addr >= 0) {
obj = obj.setAttr(id, addr);
}
});
heap = heap.setVal(moduleAddr, obj);
}
}
}
return ctx.setImported(imported).setEnv(currEnv).setHeap(heap);
});
});
});
// TODO: Garbage collection
return ctxSet.map((ctx) => {
let newCtx = ctx.setEnv(baseEnv).setRelPath(basePath);
const retVal = ctx.imported.getId(lastPath);
if (assignTo) {
let to = baseEnv.getId(assignTo);
const val = BackUtils.sanitizeAddr(retVal, newCtx.heap);
if (!to) {
const [addr, newHeap] = newCtx.heap.malloc(source);
const newEnv = newCtx.env.setId(assignTo, addr);
to = addr;
newCtx = ctx.setEnv(newEnv).setHeap(newHeap);
}
if (to) {
if (val && val.type !== SVType.Undef) {
newCtx = newCtx.setHeap(newCtx.heap.setVal(to, val));
} else if (retVal) {
newCtx = newCtx.setHeap(newCtx.heap.setVal(to, retVal));
}
}
}
if (retVal) {
return newCtx.setRetVal(retVal);
} else if (hasWild) {
return newCtx.setRetVal(SVNone.create());
} else {
return newCtx.warnWithMsg(`import ${qualPath}(${lastPath}) failed `, source) as Context<ShValue>;
}
});
}
export function genList(ctx: Context<ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> {
const { heap } = ctx;
const params = ctx.retVal.params;
// TODO: flattening varargs
const [tempObj, objAddr, newHeap] = SVObject.create(heap, source);
let obj = tempObj;
params.forEach((v, i) => {
obj = obj.setIndice(i, v);
});
obj = obj.setAttr('$length', SVInt.create(params.length, source));
let listType = BackUtils.fetchAddr(ctx.env.getId('list'), ctx.heap);
if (listType?.type === SVType.Object) {
// class _Primitives defines self.mro = (self, object)
listType = BackUtils.fetchAddr(listType.getAttr('__mro__'), ctx.heap);
}
if (listType?.type === SVType.Object) {
obj = obj.setAttr('__mro__', listType);
}
return ctx.setHeap(newHeap.setVal(objAddr, obj)).toSetWith(objAddr);
}
export function genDict(ctx: Context<ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> {
// TODO: genDict
const { heap } = ctx;
const params = ctx.retVal.params;
// const [listLoc, heap1] = heap.malloc();
const [tempObj, objAddr, newHeap] = SVObject.create(heap, source);
let obj = tempObj;
for (const i in params) {
const kvTuple = BackUtils.fetchAddr(params[i], heap);
if (kvTuple?.type !== SVType.Object) {
return ctx.warnWithMsg(`from 'LibCall.genDict: parameter must be key-value tuple`, source).toSet();
}
const key = BackUtils.fetchAddr(kvTuple.getIndice(0), heap);
const value = kvTuple.getIndice(1);
if (!key || !value) {
return ctx.warnWithMsg(`from 'LibCall.genDict: parameter must be key-value tuple`, source).toSet();
}
// TODO: hash object + symbolic something
if (key.type === SVType.Int) {
const keyRng = ctx.getCachedRange(key.value);
if (keyRng?.toIntRange()?.isConst()) obj = obj.setIndice(keyRng.start, value);
} else if (key.type === SVType.String && typeof key.value === 'string') {
obj = obj.setKeyVal(key.value, value);
}
}
obj = obj.setAttr('$length', SVInt.create(params.length, source));
let dictType = BackUtils.fetchAddr(ctx.env.getId('dict'), ctx.heap);
if (dictType?.type === SVType.Object) {
// class _Primitives defines self.mro = (self, object)
dictType = BackUtils.fetchAddr(dictType.getAttr('__mro__'), ctx.heap);
}
if (dictType?.type === SVType.Object) {
obj = obj.setAttr('__mro__', dictType);
}
return ctx.setHeap(newHeap.setVal(objAddr, obj)).toSetWith(objAddr);
}
export interface SetDefaultParams {
$func: SVFunc;
defaults: { [paramName: string]: ShValue };
$varargsName?: string;
$kwargsName?: string;
$keyOnlyNum?: number;
}
export function setDefault(ctx: Context<SetDefaultParams>, source: CodeSource | undefined): ContextSet<ShValue> {
const { $func, defaults, $varargsName, $kwargsName, $keyOnlyNum } = ctx.retVal;
let newFunc = $func;
newFunc = newFunc.setDefaults(IMMap(defaults));
newFunc = newFunc.setVKParam($varargsName, $kwargsName, $keyOnlyNum);
return ctx.toSetWith(newFunc);
}
export interface CallKVParams {
$func: SVFunc;
$args: ShValue[];
$kwargs: { [paramName: string]: ShValue };
}
export function callKV(ctx: Context<CallKVParams>, source: CodeSource | undefined): ContextSet<ShValue> {
const { $func, $args, $kwargs } = ctx.retVal;
return TorchBackend.functionCall(ctx, $func, $args, source, $kwargs);
}
export function DEBUG(ctx: Context<ExplicitParams>, source: CodeSource | undefined): ContextSet<ShValue> {
const heap = ctx.heap;
const params = ctx.retVal.params;
const value: ShValue | undefined = BackUtils.fetchAddr(params[0], heap);
let newCtx: Context<ExplicitParams>;
PyteaService.log(value?.toString());
if (value) {
newCtx = ctx.addLogValue(value);
} else {
newCtx = ctx.addLogValue(params[0] ? params[0] : SVNone.create());
}
return newCtx.toSetWith(SVNone.create());
}
// export set $module[globalVar] = address of globalVar
export interface ExportGlobalParams {
$module: SVAddr; // points SVObject
globalVar: string;
}
export function exportGlobal(
ctx: Context<ExportGlobalParams>,
source: CodeSource | undefined
): ContextSet<ShValue> {
const addr = ctx.retVal.$module;
const obj = ctx.heap.getVal(addr) as SVObject;
const global = ctx.env.getId(ctx.retVal.globalVar) as SVAddr;
return ctx.setHeap(ctx.heap.setVal(addr, obj.setAttr(ctx.retVal.globalVar, global))).toSetWith(global);
}
export interface GetAttrParams {
name: string;
self: ShValue;
baseClass: SVObject;
bind: boolean;
selfAddr?: SVAddr;
}
export function getAttr(ctx: Context<GetAttrParams>, source: CodeSource | undefined): ContextSet<ShValue> {
const { bind, selfAddr, name, self, baseClass } = ctx.retVal;
const selfAttr = self.type === SVType.Object ? self.attrs.get(name) : undefined;
if (selfAttr) {
return ctx.setRetVal(selfAttr).toSet();
}
return TorchBackend.getAttrDeep(ctx, baseClass, name, source).map((ctx) => {
let newHeap = ctx.heap;
const superAttr = ctx.retVal;
if (bind && superAttr.type === SVType.Func) {
if (self.type !== SVType.Object) {
return ctx.warnWithMsg(`value is not an object. (not bindable)`, source);
}
let addr = selfAddr;
if (!addr) {
[addr, newHeap] = newHeap.malloc(source);
}
const boundFunc = superAttr.bound(addr);
if (!boundFunc) {
return ctx.warnWithMsg(`Function ${superAttr.name} is not bindable. (no parameters)`, source);
}
return ctx.setRetVal(boundFunc);
} else {
return ctx.setRetVal(superAttr);
}
});
}
export interface RaiseParams {
value: ShValue;
}
export function raise(ctx: Context<RaiseParams>, source: CodeSource | undefined): ContextSet<ShValue> {
const raisedVal = BackUtils.fetchAddr(ctx.retVal.value, ctx.heap);
if (raisedVal?.type === SVType.Object) {
return ctx.getAttrDeep(raisedVal, '__name__', source).flatMap((ctx) => {
if (ctx.retVal?.type === SVType.String) {
const errType = ctx.retVal.value;
return ctx.getAttrDeep(raisedVal, 'args', source).flatMap((ctx) => {
let errMsg = '';
const args = BackUtils.fetchAddr(ctx.retVal, ctx.heap);
if (args?.type === SVType.Object) {
const msg = BackUtils.fetchAddr(args.getIndice(0), ctx.heap);
if (msg?.type === SVType.String) {
errMsg = `: ${SymExp.toString(msg.value)}`;
}
}
return ctx.failWithMsg(`${errType}${errMsg}`, source).toSet();
});
}
return ctx.failWithMsg('TypeError: exceptions must derive from BaseException', source).toSet();
});
}
return ctx.failWithMsg('TypeError: exceptions must derive from BaseException', source).toSet();
}
export const libCallImpls: { [key in keyof typeof LibCallType]: LCImpl } = {
import: thImport,
genList,
genDict,
DEBUG,
setDefault,
callKV,
explicit,
exportGlobal,
raise,
objectClass,
};
}
export const libCallMap = new Map([...Object.entries(LCBase.libCallImpls)]); | the_stack |
import * as React from "react";
import * as utils from "../utils/utils";
import * as strings from "spfxReactGridStrings";
import {connect} from "react-redux";
import * as _ from "lodash";
import { SharePointLookupCellFormatter } from "../components/SharePointFormatters";
import WebSelector from "../components/WebSelector";
import ListEditor from "../components/ListEditor";
import { addList, removeList, saveList, removeAllLists } from "../actions/listActions";
import { getWebsAction, getListsForWebAction, getFieldsForListAction } from "../actions/SiteActions";
import { Button, ButtonType, Dropdown, IDropdownOption, TextField, CommandBar } from "office-ui-fabric-react";
import ListDefinition from "../model/ListDefinition";
import { FieldDefinition } from "../model/ListDefinition";
import { ColumnReference } from "../model/ListDefinition";
import { Site, Web, WebList, WebListField } from "../model/Site";
import ColumnDefinition from "../model/ColumnDefinition";
import Container from "../components/container";
import { Guid, Log } from "@microsoft/sp-core-library";
import { PageContext } from "@microsoft/sp-page-context";
export class GridColumn {
constructor(
public id: string,
public name: string,
public title: string,
public editable: boolean,
public width: number,
public type: string,
public formatter: string = "",
public editor?: string) { }
}
export interface IListViewPageProps extends React.Props<any> {
lists: Array<ListDefinition>;
columnRefs: Array<ColumnDefinition>;
sites: Array<Site>;
addList: (siteUrl: string) => void;
removeList: (List) => void;
removeAllLists: () => void;
saveList: (List) => void;
getWebs: (siteUrl) => Promise<any>;
getListsForWeb: (webUrl) => Promise<any>;
getFieldsForList: (webUrl, listId) => Promise<any>;
save: () => void;
pageContext: PageContext;
}
function mapStateToProps(state) {
return {
lists: state.lists,
sites: state.sites,
columnRefs: state.columns,
pageContext: state.pageContext
};
}
function mapDispatchToProps(dispatch) {
return {
addList: (siteUrl: string): void => {
const id = Guid.newGuid();
const list: ListDefinition = new ListDefinition(id.toString(), null, null, siteUrl, null, null);
dispatch(addList(list));
},
removeList: (list: ListDefinition): void => {
dispatch(removeList(list));
},
removeAllLists: (): void => {
dispatch(removeAllLists());
},
getWebs: (siteUrl): Promise<any> => {
return dispatch(getWebsAction(dispatch, siteUrl));
},
getListsForWeb(webUrl): Promise<any> {
return dispatch(getListsForWebAction(dispatch, webUrl));
},
getFieldsForList(webUrl, listId): Promise<any> {
return dispatch(getFieldsForListAction(dispatch, webUrl, listId));
},
saveList: (list): void => {
const action = saveList(list);
dispatch(action);
},
};
}
export interface IGridProps {
editing: {
entityid: string;
columnid: string;
};
}
export class ListDefinitionContainerNative extends React.Component<IListViewPageProps, IGridProps> {
public defaultColumns: Array<GridColumn> = [
{
id: "rowGuid",
name: "guid",
title: "List Definition ID",
editable: false,
width: 250,
formatter: "",
type: "Text"
},
{
id: "SiteUrl",
name: "siteUrl", // the url to the site
title: "SiteUrl",
editable: true,
width: 359,
formatter: "",
type: "Text"
},
{
id: "listDefTitle",
name: "listDefTitle",
title: "List Definition Title",
editable: true,
width: 100,
formatter: "",
type: "Text"
},
{
id: "WebLookup",
name: "webLookup", // the name of the field in the model
title: "Web Containing List",
editable: true,
width: 300,
editor: "WebEditor",
formatter: "SharePointLookupCellFormatter",
type: "Lookup"
},
{
id: "listlookup",
width: 300,
name: "listLookup",
title: "List",
editable: true,
editor: "ListEditor",
formatter: "SharePointLookupCellFormatter",
type: "Lookup"
}];
public extendedColumns: Array<GridColumn> = [];
public constructor() {
super();
this.getWebsForSite = this.getWebsForSite.bind(this);
this.getListsForWeb = this.getListsForWeb.bind(this);
this.getFieldsForlist = this.getFieldsForlist.bind(this);
this.getFieldDefinition = this.getFieldDefinition.bind(this);
this.CellContentsEditable = this.CellContentsEditable.bind(this);
this.CellContents = this.CellContents.bind(this);
this.TableDetail = this.TableDetail.bind(this);
this.TableRow = this.TableRow.bind(this);
this.TableRows = this.TableRows.bind(this);
this.toggleEditing = this.toggleEditing.bind(this);
this.handleCellUpdated = this.handleCellUpdated.bind(this);
this.handleCellUpdatedEvent = this.handleCellUpdatedEvent.bind(this);
this.deleteList = this.deleteList.bind(this);
this.addList = this.addList.bind(this);
}
public componentWillMount(): void {
if (this.props.sites.length === 0) {
// prload current site, assuming user wants lists from current site
// this.props.getWebs(this.props.pageContext.site.absoluteUrl);
}
this.extendedColumns = _.clone(this.defaultColumns);
for (const columnRef of this.props.columnRefs) {
const newCol = new GridColumn(columnRef.guid, columnRef.name, columnRef.name, columnRef.editable, columnRef.width, columnRef.type, "FieldFormatter", "FieldEditor");
this.extendedColumns.push(newCol);
}
}
private isdeafaultColumn(columnid): boolean {
for (const col of this.defaultColumns) {
if (col.id === columnid) return true;
}
return false;
}
private updateExtendedColumn(entity: ListDefinition, columnid: string, value: any) {
const internalName = utils.ParseSPField(value).id;
const fieldDefinition: FieldDefinition = this.getFieldDefinition(entity, internalName); // values is the fueld just selected.... get the definition for it
for (const col of entity.columnReferences) {
if (col.columnDefinitionId === columnid) {
col.name = value;
col.fieldDefinition = fieldDefinition;
return;
}
}
const x = new ColumnReference(columnid, value, fieldDefinition);
entity.columnReferences.push(x);
}
public getFieldDefinition(listdef: ListDefinition, internalName: string): FieldDefinition {
const field = this.getFieldInList(listdef, internalName);
return field.fieldDefinition;
}
private handleCellUpdatedEvent(event) { //native react uses a Synthetic event
this.handleCellUpdated(event.target.value);
}
private handleCellUpdated(value) { // Office UI Fabric does not use events. It just calls this method with the new value
const {entityid, columnid} = this.state.editing;
const entity: ListDefinition = _.find(this.props.lists,(temp) => temp.guid === entityid);
const column = _.find(this.extendedColumns,temp => temp.id === columnid);
// if it is a default column, just set its value , otheriwse update it in the list of extended columns (i.e. sharepoint columns)
if (this.isdeafaultColumn(columnid)) {
/** need to save the web url if the web column was updated
* Sharepoint rest wont let me go from an SPSite to an SPWeb using just the id. Need tis
* I need the url to the Web.
* hmmmm... can i construct it (dont store the Id of the we, store the path instead?)
* need this for lookup columns.. they only stote a weid and list id...ohhhh noooo
*/
entity[column.name] = value;
}
else {
this.updateExtendedColumn(entity, columnid, value);
}
// this.props.saveList(entity);
}
public addList(event): any {
this.props.addList(this.props.pageContext.site.absoluteUrl);
return;
}
public deleteList(event) {
Log.verbose("list-Page", "Row changed-fired when row changed or leaving cell ");
const target = this.getParent(event.target, "TD");
const attributes: NamedNodeMap = target.attributes;
const entity = attributes.getNamedItem("data-entityid").value;
const list: ListDefinition = _.find(this.props.lists,temp => temp.guid === entity);
this.props.removeList(list);
return;
}
public getParent(node: Node, type: string): Node {
while (node.nodeName !== "TD") {
node = node.parentNode;
}
return node;
}
public getWebsForSite(listDef: ListDefinition): Array<Web> {
for (const site of this.props.sites) {
if (site.url === listDef.siteUrl) {
return site.webs;
}
}
// not in our cache/ go get it
this.props.getWebs(listDef.siteUrl);
return [];
}
public getListsForWeb(listDef: ListDefinition): Array<WebList> {
const webs = this.getWebsForSite(listDef);
for (const web of webs) {
if (web.url === utils.ParseSPField(listDef.webLookup).id) {
if (web.listsFetched) {
return web.lists;
}
else {
this.props.getListsForWeb(utils.ParseSPField(listDef.webLookup).id);
return [];
}
}
}
this.props.getListsForWeb(utils.ParseSPField(listDef.webLookup).id);
return []; // havent fetched parent yet,
}
public getFieldsForlist(listDef: ListDefinition, colType?: string): Array<WebListField> {
const lists = this.getListsForWeb(listDef);
for (const list of lists) {
if (list.id === utils.ParseSPField(listDef.listLookup).id) {
if (list.fieldsFetched) {
if (colType === undefined || colType === null) {
return list.fields;
} else {
return _.filter(list.fields, (f) => f.fieldDefinition.TypeAsString === colType);
}
}
else {
this.props.getFieldsForList(utils.ParseSPField(listDef.webLookup).id, utils.ParseSPField(listDef.listLookup).id);
return [];
}
}
}
return [];// havent fetched parent yet,
}
/** This method is called just before we ara going to save a field in our listdef. It gets the Field Deefinition from sharepoint. */
public getFieldInList(listDef: ListDefinition, internalName): WebListField {
const fields = this.getFieldsForlist(listDef);
for (const field of fields) {
if (utils.ParseSPField(field.name).id === internalName) {
return field;
}
}
}
public GetColumnReferenence(listDefinition: ListDefinition, columnDefinitionId: string): ColumnReference {
for (const columnref of listDefinition.columnReferences) {
if (columnref.columnDefinitionId === columnDefinitionId) {
return columnref;
}
}
}
public toggleEditing(event) {
Log.verbose("list-Page", "focus event fired editing when entering cell");
const target = this.getParent(event.target, "TD"); // walk up the Dom to the TD, thats where the IDs are stored
const attributes: NamedNodeMap = target.attributes;
const entityid = attributes.getNamedItem("data-entityid").value;
const columnid = attributes.getNamedItem("data-columnid").value;
this.setState({ "editing": { entityid: entityid, columnid: columnid } });
}
public CellContentsEditable(props: { entity: ListDefinition, column: GridColumn, cellUpdated: (newValue) => void, cellUpdatedEvent: (event: React.SyntheticEvent<any>) => void; }): JSX.Element {
const {entity, column, cellUpdated, cellUpdatedEvent} = props;
let columnValue;
if (this.isdeafaultColumn(column.id)) {
columnValue = entity[column.name];
}
else {
const colRef: ColumnReference = this.GetColumnReferenence(entity, column.id);
if (colRef) {
columnValue = this.GetColumnReferenence(entity, column.id).name;
}
}
switch (column.editor) {
case "WebEditor":
return (
<WebSelector
selectedWeb={columnValue}
onChange={cellUpdated}
PageContext={this.props.pageContext}
siteUrl={entity.siteUrl}
headerText={strings.WebSelectorHeaderText}
/>
);
case "ListEditor":
let lists = this.getListsForWeb(entity);// the Id portion of the WebLookup is the URL
return (<ListEditor selectedValue={columnValue} onChange={cellUpdated} lists={lists} />);
case "FieldEditor":
const colType = column.type;
let fields: Array<IDropdownOption> = this.getFieldsForlist(entity, colType).map(fld => {
return { key: fld.name, text: utils.ParseSPField(fld.name).value };
});
fields.unshift({ key: null, text: "(Select one)" });
return (<Dropdown options={fields} label="" selectedKey={columnValue} onChanged={(selection: IDropdownOption) => cellUpdated(selection.key)} />);
default:
return (
<TextField autoFocus width={column.width}
value={entity[column.name]}
onChanged={cellUpdated} />);
}
}
public CellContents(props: { entity: ListDefinition, column: GridColumn }): JSX.Element {
const {entity, column} = props;
switch (column.formatter) {
case "SharePointLookupCellFormatter":
return (<SharePointLookupCellFormatter value={entity[column.name]} onFocus={this.toggleEditing} />);
default:
if (this.isdeafaultColumn(column.id)) {
return (<a href="#" onFocus={this.toggleEditing} style={{ textDecoration: "none" }}>
{entity[column.name]}
</a>
);
}
else {
const colref = _.find(entity.columnReferences,cr => cr.columnDefinitionId === column.id);
let displaytext = "";
if (colref != null) {
displaytext = utils.ParseSPField(colref.name).value;
}
return (<a href="#" onFocus={this.toggleEditing} style={{ textDecoration: "none" }}>
{displaytext}
</a>
);
}
}
}
public TableDetail(props: { entity: ListDefinition, column: GridColumn, cellUpdated: (newValue) => void, cellUpdatedEvent: (event: React.SyntheticEvent<any>) => void; }): JSX.Element {
const {entity, column, cellUpdated, cellUpdatedEvent} = props;
if (this.state && this.state.editing && this.state.editing.entityid === entity.guid && this.state.editing.columnid === column.id) {
return (<td data-entityid={entity.guid} data-columnid={column.id} style={{ width: column.width, border: "1px solid red", padding: "0px" }}>
<this.CellContentsEditable entity={entity} column={column} cellUpdated={this.handleCellUpdated} cellUpdatedEvent={this.handleCellUpdatedEvent} />
</td>
);
} else {
return (<td data-entityid={entity.guid} data-columnid={column.id} style={{ width: column.width, border: "1px solid black", padding: "0px" }} onClick={this.toggleEditing} >
<this.CellContents entity={entity} column={column} />
</td>
);
}
}
public TableRow(props: { entity: ListDefinition, columns: Array<GridColumn>, cellUpdated: (newValue) => void, cellUpdatedEvent: (event: React.SyntheticEvent<any>) => void; }): JSX.Element {
const {entity, columns, cellUpdated, cellUpdatedEvent} = props;
return (
<tr>
{
columns.filter(c => c.type !== "__LISTDEFINITIONTITLE__").map(function (column) {
return (
<this.TableDetail key={column.id} entity={entity} column={column} cellUpdated={this.handleCellUpdated} cellUpdatedEvent={this.handleCellUpdatedEvent} />
);
}, this)
}
<td data-entityid={entity.guid} data-columnid={""}>
<Button
onClick={this.deleteList}
buttonType={ButtonType.icon}
icon="Delete" />
</td>
</tr>);
};
public TableRows(props: { entities: Array<ListDefinition>, columns: Array<GridColumn>, cellUpdated: (newValue) => void, cellUpdatedEvent: (event: React.SyntheticEvent<any>) => void; }): JSX.Element {
const {entities, columns, cellUpdated, cellUpdatedEvent} = props;
return (
<tbody>
{
entities.map(function (list) {
return (
<this.TableRow key={list.guid} entity={list} columns={columns} cellUpdated={this.handleCellUpdated} cellUpdatedEvent={this.handleCellUpdatedEvent} />
);
}, this)
}
</tbody>
);
}
public render() {
return (
<Container testid="columns" size={2} center>
<CommandBar items={[{
key: "Add LIST",
name: "Add a List",
icon: "Add",
onClick: this.addList
},
{
key: "Clear All Lists",
name: "Remove All Lists",
icon: "Delete",
onClick: this.props.removeAllLists
},
{
key: "Allow All Types ",
name: "Allow All Types ",
canCheck: true,
isChecked: true,
icon: "ClearFilter"
},
{
key: "save",
name: "save",
canCheck: true,
icon: "Save",
onClick: this.props.save
}]} />
<table >
<thead>
<tr>
{this.extendedColumns.filter(c => c.type !== "__LISTDEFINITIONTITLE__").map((column) => {
return <th key={column.name}>{column.title}</th>;
})}
</tr>
</thead>
{
<this.TableRows entities={this.props.lists} columns={this.extendedColumns} cellUpdated={this.handleCellUpdated} cellUpdatedEvent={this.handleCellUpdatedEvent} />
})}
</table>
</Container>
);
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(ListDefinitionContainerNative); | the_stack |
import { TFunction } from "i18next";
import { computed, runInAction, when } from "mobx";
import PropTypes from "prop-types";
import React from "react";
import { WithTranslation, withTranslation } from "react-i18next";
import styled, { DefaultTheme, withTheme } from "styled-components";
import Cartesian2 from "terriajs-cesium/Source/Core/Cartesian2";
import Cartesian3 from "terriajs-cesium/Source/Core/Cartesian3";
import Ellipsoid from "terriajs-cesium/Source/Core/Ellipsoid";
import CesiumEvent from "terriajs-cesium/Source/Core/Event";
import getTimestamp from "terriajs-cesium/Source/Core/getTimestamp";
import CesiumMath from "terriajs-cesium/Source/Core/Math";
import Matrix4 from "terriajs-cesium/Source/Core/Matrix4";
import Ray from "terriajs-cesium/Source/Core/Ray";
import Transforms from "terriajs-cesium/Source/Core/Transforms";
import isDefined from "../../../../Core/isDefined";
import Terria from "../../../../Models/Terria";
import ViewState from "../../../../ReactViewModels/ViewState";
import Box from "../../../../Styled/Box";
import Icon, { StyledIcon } from "../../../../Styled/Icon";
import GyroscopeGuidance from "../../../GyroscopeGuidance/GyroscopeGuidance";
import { withTerriaRef } from "../../../HOCs/withTerriaRef";
import FadeIn from "../../../Transitions/FadeIn/FadeIn";
const CameraFlightPath = require("terriajs-cesium/Source/Scene/CameraFlightPath")
.default;
export const COMPASS_LOCAL_PROPERTY_KEY = "CompassHelpPrompted";
// Map Compass
//
// Markup:
// <StyledCompass>
// (<GyroscopeGuidance /> if hovered/active/focused)
// <StyledCompassOuterRing /> (base, turns into white circle when active)
// <StyledCompassOuterRing /> (clone to be used for animation)
// <StyledCompassInnerRing title="Click and drag to rotate the camera" />
// <StyledCompassRotationMarker />
// </StyledCompass>
interface StyledCompassProps {
active: boolean;
theme: DefaultTheme;
}
const StyledCompass = styled.div<StyledCompassProps>`
display: none;
position: relative;
width: ${props => props.theme.compassWidth}px;
height: ${props => props.theme.compassWidth}px;
@media (min-width: ${props => props.theme.sm}px) {
display: block;
}
`;
/**
* Take a compass width and scale it up 10px, instead of hardcoding values like:
* // const compassScaleRatio = 66 / 56;
*/
const getCompassScaleRatio = (compassWidth: string) =>
(Number(compassWidth) + 10) / Number(compassWidth);
/**
* You think 0.9999 is a joke but I kid you not, it's the root of all evil in
* bandaging these related issues:
* https://github.com/TerriaJS/terriajs/issues/4261
* https://github.com/TerriaJS/terriajs/pull/4262
* https://github.com/TerriaJS/terriajs/pull/4213
*
* It seems the rendering in Chrome means that in certain conditions
* - chrome (not even another webkit browser)
* - "default browser zoom" (doesn't happen when you are even at 110%, but will
* when shrunk down enough)
* - the way our compass is composed
*
* The action of triggering the 'active' state (scaled up to
* `getCompassScaleRatio()`) & back down means that the "InnerRing" will look
* off-center by 0.5-1px until you switch windows/tabs away and back, then
* chrome will decide to render it in the correct position.
*
* I haven't dug further to the root cause as doing it like this means wew now
* have a beautiful animating compass.
*
* So please leave scale(0.9999) alone unless you can fix the rendering issue in
* chrome, or if you want to develop a burning hatred for the compass 🙏🔥
*
**/
const StyledCompassOuterRing = styled.div<StyledCompassProps>`
${props => props.theme.centerWithoutFlex()}
// override the transform provided in centerWithoutFlex()
transform: translate(-50%,-50%) scale(0.9999);
z-index: ${props => (props.active ? "2" : "1")};
width: 100%;
${props =>
props.active &&
`transform: translate(-50%,-50%) scale(${getCompassScaleRatio(
props.theme.compassWidth
)});`};
transition: transform 0.3s;
`;
const StyledCompassInnerRing = styled.div`
${props => props.theme.verticalAlign()}
width: ${props =>
Number(props.theme.compassWidth) - Number(props.theme.ringWidth) - 10}px;
height: ${props =>
Number(props.theme.compassWidth) - Number(props.theme.ringWidth) - 10}px;
margin: 0 auto;
padding: 4px;
box-sizing: border-box;
`;
const StyledCompassRotationMarker = styled.div`
${props => props.theme.centerWithoutFlex()}
z-index: 3;
cursor: pointer;
width: ${props =>
Number(props.theme.compassWidth) + Number(props.theme.ringWidth) - 4}px;
height: ${props =>
Number(props.theme.compassWidth) + Number(props.theme.ringWidth) - 4}px;
border-radius: 50%;
background-repeat: no-repeat;
background-size: contain;
`;
type PropTypes = WithTranslation & {
terria: Terria;
viewState: ViewState;
refFromHOC?: React.Ref<HTMLDivElement>;
theme: DefaultTheme;
t: TFunction;
};
type IStateTypes = {
orbitCursorAngle: number;
heading: number;
orbitCursorOpacity: number;
active: boolean;
activeForTransition: boolean;
};
// the compass on map
class Compass extends React.Component<PropTypes, IStateTypes> {
_unsubscribeFromPostRender: any;
_unsubscribeFromAnimationFrame: any;
private _unsubscribeFromViewerChange?: CesiumEvent.RemoveCallback;
orbitMouseMoveFunction?: (this: Document, ev: MouseEvent) => any;
orbitMouseUpFunction?: (this: Document, ev: MouseEvent) => any;
rotateMouseMoveFunction?: (this: Document, ev: MouseEvent) => any;
rotateMouseUpFunction?: (this: Document, ev: MouseEvent) => any;
isRotating: boolean = false;
rotateInitialCursorAngle: number = 0;
rotateFrame?: Matrix4;
rotateIsLook: boolean = false;
rotateInitialCameraAngle: number = 0;
rotateInitialCameraDistance: number = 0;
orbitFrame?: Matrix4;
orbitIsLook: boolean = false;
orbitLastTimestamp: number = 0;
isOrbiting: boolean = false;
orbitAnimationFrameFunction?: any;
showCompass?: boolean;
/**
* @param {Props} props
*/
constructor(props: PropTypes) {
super(props);
this.state = {
orbitCursorAngle: 0,
heading: 0.0,
orbitCursorOpacity: 0,
active: false,
activeForTransition: false
};
when(
() => isDefined(this.cesiumViewer),
() => this.cesiumLoaded()
);
}
@computed
get cesiumViewer() {
return this.props.terria.cesium;
}
cesiumLoaded() {
this._unsubscribeFromViewerChange = this.props.terria.mainViewer.afterViewerChanged.addEventListener(
() => viewerChange(this)
);
viewerChange(this);
}
componentWillUnmount() {
if (this.orbitMouseMoveFunction) {
document.removeEventListener(
"mousemove",
this.orbitMouseMoveFunction,
false
);
}
if (this.orbitMouseUpFunction) {
document.removeEventListener("mouseup", this.orbitMouseUpFunction, false);
}
this._unsubscribeFromAnimationFrame &&
this._unsubscribeFromAnimationFrame();
this._unsubscribeFromPostRender && this._unsubscribeFromPostRender();
this._unsubscribeFromViewerChange && this._unsubscribeFromViewerChange();
}
handleMouseDown(e: any) {
if (e.stopPropagation) e.stopPropagation();
if (e.preventDefault) e.preventDefault();
const compassElement = e.currentTarget;
const compassRectangle = e.currentTarget.getBoundingClientRect();
const maxDistance = compassRectangle.width / 2.0;
const center = new Cartesian2(
(compassRectangle.right - compassRectangle.left) / 2.0,
(compassRectangle.bottom - compassRectangle.top) / 2.0
);
const clickLocation = new Cartesian2(
e.clientX - compassRectangle.left,
e.clientY - compassRectangle.top
);
const vector = Cartesian2.subtract(clickLocation, center, vectorScratch);
const distanceFromCenter = Cartesian2.magnitude(vector);
const distanceFraction = distanceFromCenter / maxDistance;
const nominalTotalRadius = 145;
const nominalGyroRadius = 50;
if (distanceFraction < nominalGyroRadius / nominalTotalRadius) {
orbit(this, compassElement, vector);
} else if (distanceFraction < 1.0) {
rotate(this, compassElement, vector);
} else {
return true;
}
}
handleDoubleClick(e: any) {
const scene = this.props.terria.cesium!.scene;
const camera = scene.camera;
const windowPosition = windowPositionScratch;
windowPosition.x = scene.canvas.clientWidth / 2;
windowPosition.y = scene.canvas.clientHeight / 2;
const ray = camera.getPickRay(windowPosition, pickRayScratch);
const center = scene.globe.pick(ray, scene, centerScratch);
if (!isDefined(center)) {
// Globe is barely visible, so reset to home view.
this.props.terria.currentViewer.zoomTo(
this.props.terria.mainViewer.homeCamera,
1.5
);
return;
}
const rotateFrame = Transforms.eastNorthUpToFixedFrame(
center,
Ellipsoid.WGS84
);
const lookVector = Cartesian3.subtract(
center,
camera.position,
new Cartesian3()
);
const flight = CameraFlightPath.createTween(scene, {
destination: Matrix4.multiplyByPoint(
rotateFrame,
new Cartesian3(0.0, 0.0, Cartesian3.magnitude(lookVector)),
new Cartesian3()
),
direction: Matrix4.multiplyByPointAsVector(
rotateFrame,
new Cartesian3(0.0, 0.0, -1.0),
new Cartesian3()
),
up: Matrix4.multiplyByPointAsVector(
rotateFrame,
new Cartesian3(0.0, 1.0, 0.0),
new Cartesian3()
),
duration: 1.5
});
scene.tweens.add(flight);
}
resetRotater() {
this.setState({
orbitCursorOpacity: 0,
orbitCursorAngle: 0
});
}
render() {
const rotationMarkerStyle = {
transform: "rotate(-" + this.state.orbitCursorAngle + "rad)",
WebkitTransform: "rotate(-" + this.state.orbitCursorAngle + "rad)",
opacity: this.state.orbitCursorOpacity
};
const outerCircleStyle = {
transform: "rotate(-" + this.state.heading + "rad)",
WebkitTransform: "rotate(-" + this.state.heading + "rad)",
opacity: ""
};
const { t } = this.props;
const active = this.state.active;
const description = t("compass.description");
const showGuidance = !this.props.viewState.terria.getLocalProperty(
COMPASS_LOCAL_PROPERTY_KEY
);
return (
<StyledCompass
onMouseDown={this.handleMouseDown.bind(this)}
onDoubleClick={this.handleDoubleClick.bind(this)}
onMouseUp={this.resetRotater.bind(this)}
active={active}
>
{/* Bottom "turns into white circle when active" layer */}
<StyledCompassOuterRing active={false}>
<div style={outerCircleStyle}>
<StyledIcon
fillColor={this.props.theme.darkWithOverlay}
// if it's active, show a white circle only, as we need the base layer
glyph={
active
? Icon.GLYPHS.compassOuterSkeleton
: Icon.GLYPHS.compassOuter
}
/>
</div>
</StyledCompassOuterRing>
{/* "Top" animated layer */}
<StyledCompassOuterRing
active={active}
title={description}
aria-hidden="true"
role="presentation"
>
<div ref={this.props.refFromHOC} style={outerCircleStyle}>
<StyledIcon
fillColor={this.props.theme.darkWithOverlay}
glyph={Icon.GLYPHS.compassOuter}
/>
</div>
</StyledCompassOuterRing>
{/* "Center circle icon" */}
<StyledCompassInnerRing title={t("compass.title")}>
<StyledIcon
fillColor={this.props.theme.darkWithOverlay}
glyph={
active ? Icon.GLYPHS.compassInnerArrows : Icon.GLYPHS.compassInner
}
/>
</StyledCompassInnerRing>
{/* Rotation marker when dragging */}
<StyledCompassRotationMarker
title={description}
style={{
backgroundImage: require("../../../../../wwwroot/images/compass-rotation-marker.svg")
}}
onMouseOver={() => this.setState({ active: true })}
onMouseOut={() => {
if (showGuidance) {
this.setState({ active: true });
} else {
this.setState({ active: false });
}
}}
// do we give focus to this? given it's purely a mouse tool
// focus it anyway..
tabIndex={0}
onFocus={() => this.setState({ active: true })}
// Gotta keep menu open if blurred, and close it with the close button
// instead. otherwise it'll never focus on the help buttons
// onBlur={() => this.setState({ active: false })}
>
<div style={rotationMarkerStyle}>
<StyledIcon
fillColor={this.props.theme.darkWithOverlay}
glyph={Icon.GLYPHS.compassRotationMarker}
/>
</div>
</StyledCompassRotationMarker>
{/* Gyroscope guidance menu */}
{showGuidance && (
<FadeIn isVisible={active}>
<Box
css={`
${(p: any) => p.theme.verticalAlign("absolute")}
direction: rtl;
right: 55px;
`}
>
<GyroscopeGuidance
//@ts-ignore
rightOffset="72px"
viewState={this.props.viewState}
// handleHelp={() => {
// this.props.viewState.showHelpPanel();
// this.props.viewState.selectHelpMenuItem("navigation");
// }}
onClose={() => this.setState({ active: false })}
/>
</Box>
</FadeIn>
)}
</StyledCompass>
);
}
}
const vectorScratch = new Cartesian2();
const oldTransformScratch = new Matrix4();
const newTransformScratch = new Matrix4();
const centerScratch = new Cartesian3();
const windowPositionScratch = new Cartesian2();
const pickRayScratch = new Ray();
function rotate(
viewModel: Compass,
compassElement: Element,
cursorVector: Cartesian2
) {
// Remove existing event handlers, if any.
if (viewModel.rotateMouseMoveFunction) {
document.removeEventListener(
"mousemove",
viewModel.rotateMouseMoveFunction,
false
);
}
if (viewModel.rotateMouseUpFunction) {
document.removeEventListener(
"mouseup",
viewModel.rotateMouseUpFunction,
false
);
}
viewModel.rotateMouseMoveFunction = undefined;
viewModel.rotateMouseUpFunction = undefined;
viewModel.isRotating = true;
viewModel.rotateInitialCursorAngle = Math.atan2(
-cursorVector.y,
cursorVector.x
);
const scene = viewModel.props.terria.cesium!.scene;
let camera = scene.camera;
const windowPosition = windowPositionScratch;
windowPosition.x = scene.canvas.clientWidth / 2;
windowPosition.y = scene.canvas.clientHeight / 2;
const ray = camera.getPickRay(windowPosition, pickRayScratch);
const viewCenter = scene.globe.pick(ray, scene, centerScratch);
if (!isDefined(viewCenter)) {
viewModel.rotateFrame = Transforms.eastNorthUpToFixedFrame(
camera.positionWC,
Ellipsoid.WGS84,
newTransformScratch
);
viewModel.rotateIsLook = true;
} else {
viewModel.rotateFrame = Transforms.eastNorthUpToFixedFrame(
viewCenter,
Ellipsoid.WGS84,
newTransformScratch
);
viewModel.rotateIsLook = false;
}
let oldTransform = Matrix4.clone(camera.transform, oldTransformScratch);
camera.lookAtTransform(viewModel.rotateFrame);
viewModel.rotateInitialCameraAngle = Math.atan2(
camera.position.y,
camera.position.x
);
viewModel.rotateInitialCameraDistance = Cartesian3.magnitude(
new Cartesian3(camera.position.x, camera.position.y, 0.0)
);
camera.lookAtTransform(oldTransform);
viewModel.rotateMouseMoveFunction = function(e) {
const compassRectangle = compassElement.getBoundingClientRect();
const center = new Cartesian2(
(compassRectangle.right - compassRectangle.left) / 2.0,
(compassRectangle.bottom - compassRectangle.top) / 2.0
);
const clickLocation = new Cartesian2(
e.clientX - compassRectangle.left,
e.clientY - compassRectangle.top
);
const vector = Cartesian2.subtract(clickLocation, center, vectorScratch);
const angle = Math.atan2(-vector.y, vector.x);
const angleDifference = angle - viewModel.rotateInitialCursorAngle;
const newCameraAngle = CesiumMath.zeroToTwoPi(
viewModel.rotateInitialCameraAngle - angleDifference
);
camera = viewModel.props.terria.cesium!.scene.camera;
oldTransform = Matrix4.clone(camera.transform, oldTransformScratch);
camera.lookAtTransform(viewModel.rotateFrame!);
const currentCameraAngle = Math.atan2(camera.position.y, camera.position.x);
camera.rotateRight(newCameraAngle - currentCameraAngle);
camera.lookAtTransform(oldTransform);
// viewModel.props.terria.cesium.notifyRepaintRequired();
};
viewModel.rotateMouseUpFunction = function(e) {
viewModel.isRotating = false;
if (viewModel.rotateMouseMoveFunction) {
document.removeEventListener(
"mousemove",
viewModel.rotateMouseMoveFunction,
false
);
}
if (viewModel.rotateMouseUpFunction) {
document.removeEventListener(
"mouseup",
viewModel.rotateMouseUpFunction,
false
);
}
viewModel.rotateMouseMoveFunction = undefined;
viewModel.rotateMouseUpFunction = undefined;
};
document.addEventListener(
"mousemove",
viewModel.rotateMouseMoveFunction,
false
);
document.addEventListener("mouseup", viewModel.rotateMouseUpFunction, false);
}
function orbit(
viewModel: Compass,
compassElement: Element,
cursorVector: Cartesian2
) {
// Remove existing event handlers, if any.
if (viewModel.orbitMouseMoveFunction) {
document.removeEventListener(
"mousemove",
viewModel.orbitMouseMoveFunction,
false
);
}
if (viewModel.orbitMouseUpFunction) {
document.removeEventListener(
"mouseup",
viewModel.orbitMouseUpFunction,
false
);
}
viewModel._unsubscribeFromAnimationFrame &&
viewModel._unsubscribeFromAnimationFrame();
viewModel._unsubscribeFromAnimationFrame = undefined;
viewModel.orbitMouseMoveFunction = undefined;
viewModel.orbitMouseUpFunction = undefined;
viewModel.orbitAnimationFrameFunction = undefined;
viewModel.isOrbiting = true;
viewModel.orbitLastTimestamp = getTimestamp();
const scene = viewModel.props.terria.cesium!.scene;
const camera = scene.camera;
const windowPosition = windowPositionScratch;
windowPosition.x = scene.canvas.clientWidth / 2;
windowPosition.y = scene.canvas.clientHeight / 2;
const ray = camera.getPickRay(windowPosition, pickRayScratch);
const center = scene.globe.pick(ray, scene, centerScratch);
if (!isDefined(center)) {
viewModel.orbitFrame = Transforms.eastNorthUpToFixedFrame(
camera.positionWC,
Ellipsoid.WGS84,
newTransformScratch
);
viewModel.orbitIsLook = true;
} else {
viewModel.orbitFrame = Transforms.eastNorthUpToFixedFrame(
center,
Ellipsoid.WGS84,
newTransformScratch
);
viewModel.orbitIsLook = false;
}
viewModel.orbitAnimationFrameFunction = function(e: any) {
const timestamp = getTimestamp();
const deltaT = timestamp - viewModel.orbitLastTimestamp;
const rate = ((viewModel.state.orbitCursorOpacity - 0.5) * 2.5) / 1000;
const distance = deltaT * rate;
const angle = viewModel.state.orbitCursorAngle + CesiumMath.PI_OVER_TWO;
const x = Math.cos(angle) * distance;
const y = Math.sin(angle) * distance;
const scene = viewModel.props.terria.cesium!.scene;
const camera = scene.camera;
const oldTransform = Matrix4.clone(camera.transform, oldTransformScratch);
camera.lookAtTransform(viewModel.orbitFrame!);
if (viewModel.orbitIsLook) {
camera.look(Cartesian3.UNIT_Z, -x);
camera.look(camera.right, -y);
} else {
camera.rotateLeft(x);
camera.rotateUp(y);
}
camera.lookAtTransform(oldTransform);
// viewModel.props.terria.cesium.notifyRepaintRequired();
viewModel.orbitLastTimestamp = timestamp;
};
function updateAngleAndOpacity(vector: Cartesian2, compassWidth: number) {
const angle = Math.atan2(-vector.y, vector.x);
viewModel.setState({
orbitCursorAngle: CesiumMath.zeroToTwoPi(angle - CesiumMath.PI_OVER_TWO)
});
const distance = Cartesian2.magnitude(vector);
const maxDistance = compassWidth / 2.0;
const distanceFraction = Math.min(distance / maxDistance, 1.0);
const easedOpacity = 0.5 * distanceFraction * distanceFraction + 0.5;
viewModel.setState({
orbitCursorOpacity: easedOpacity
});
// viewModel.props.terria.cesium.notifyRepaintRequired();
}
viewModel.orbitMouseMoveFunction = function(e) {
const compassRectangle = compassElement.getBoundingClientRect();
const center = new Cartesian2(
(compassRectangle.right - compassRectangle.left) / 2.0,
(compassRectangle.bottom - compassRectangle.top) / 2.0
);
const clickLocation = new Cartesian2(
e.clientX - compassRectangle.left,
e.clientY - compassRectangle.top
);
const vector = Cartesian2.subtract(clickLocation, center, vectorScratch);
updateAngleAndOpacity(vector, compassRectangle.width);
};
viewModel.orbitMouseUpFunction = function(e: any) {
// TODO: if mouse didn't move, reset view to looking down, north is up?
viewModel.isOrbiting = false;
if (viewModel.orbitMouseMoveFunction) {
document.removeEventListener(
"mousemove",
viewModel.orbitMouseMoveFunction,
false
);
}
if (viewModel.orbitMouseUpFunction) {
document.removeEventListener(
"mouseup",
viewModel.orbitMouseUpFunction,
false
);
}
viewModel._unsubscribeFromAnimationFrame &&
viewModel._unsubscribeFromAnimationFrame();
viewModel._unsubscribeFromAnimationFrame = undefined;
viewModel.orbitMouseMoveFunction = undefined;
viewModel.orbitMouseUpFunction = undefined;
viewModel.orbitAnimationFrameFunction = undefined;
};
document.addEventListener(
"mousemove",
viewModel.orbitMouseMoveFunction,
false
);
document.addEventListener("mouseup", viewModel.orbitMouseUpFunction, false);
subscribeToAnimationFrame(viewModel);
updateAngleAndOpacity(
cursorVector,
compassElement.getBoundingClientRect().width
);
}
function subscribeToAnimationFrame(viewModel: Compass) {
viewModel._unsubscribeFromAnimationFrame = (id => () =>
cancelAnimationFrame(id))(
requestAnimationFrame(() => {
if (isDefined(viewModel.orbitAnimationFrameFunction)) {
viewModel.orbitAnimationFrameFunction();
}
subscribeToAnimationFrame(viewModel);
})
);
}
function viewerChange(viewModel: Compass) {
runInAction(() => {
if (isDefined(viewModel.props.terria.cesium)) {
if (viewModel._unsubscribeFromPostRender) {
viewModel._unsubscribeFromPostRender();
viewModel._unsubscribeFromPostRender = undefined;
}
viewModel._unsubscribeFromPostRender = viewModel.props.terria.cesium.scene.postRender.addEventListener(
function() {
runInAction(() => {
viewModel.setState({
heading: viewModel.props.terria.cesium!.scene.camera.heading
});
});
}
);
} else {
if (viewModel._unsubscribeFromPostRender) {
viewModel._unsubscribeFromPostRender();
viewModel._unsubscribeFromPostRender = undefined;
}
viewModel.showCompass = false;
}
});
}
export const COMPASS_NAME = "MapNavigationCompassOuterRing";
export const COMPASS_TOOL_ID = "compass";
export default withTranslation()(
withTheme(withTerriaRef(Compass, COMPASS_NAME))
); | the_stack |
import {IGameState, init, setDifficulty, refresh, guess, clampDifficulty,
createLevels} from './index';
import * as I from 'immutable';
import {spy} from 'sinon';
import {assert} from 'chai';
// tslint:disable:max-line-length
describe('Game', () => {
// Set up the types for a test game record.
const levels = I.Range(1, 3);
const stepCounts = I.Map<number, number>([[1, 10], [2, 20], [3, 30]]);
type TestGuess = number;
interface ITestState extends IGameState<TestGuess> {}
type TestState = I.Record.IRecord<ITestState>;
const TestStateRecord = I.Record<ITestState>({
name: 'piano-game', // has nothing to do with piano game, is just to satisfy the type
levelCount: 3,
levels,
stepCounts,
level: undefined,
step: undefined,
choices: undefined,
correctChoice: undefined,
lastGuess: undefined,
wasLastGuessCorrect: undefined,
presentCount: undefined,
guessCount: undefined,
guessCountForCurrentCorrectChoice: undefined,
shouldRefreshChoices: undefined,
shouldRefreshCorrectChoice: undefined,
refreshChoicesCount: undefined,
refreshCorrectChoiceCount: undefined,
});
// Helper to create a fresh. Isn't needed for every test so is not used in a `beforeEach`.
function createAndInitGame(): TestState {
return init(
new TestStateRecord(),
(g: TestState) => g.set('choices', I.List([3, 4, 5])) as TestState,
(g: TestState) => g.set('correctChoice', 4) as TestState
);
}
describe('init', () => {
it('should initialize a game state record with default values', () => {
const choices = I.List([3, 4, 5]);
const correctChoice = 4;
const refreshChoices = spy(
(game: TestState) => game.set('choices', choices)
);
const refreshCorrectChoice = spy(
(game: TestState) => game.set('correctChoice', correctChoice)
);
const game = init(new TestStateRecord(), refreshChoices, refreshCorrectChoice);
assert.strictEqual(refreshChoices.callCount, 1);
assert.strictEqual(refreshCorrectChoice.callCount, 1);
assert.strictEqual(game.level, 1);
assert.strictEqual(game.step, 0);
assert(I.is(game.choices, choices));
assert.strictEqual(game.correctChoice, correctChoice);
assert.strictEqual(game.lastGuess, null);
assert.strictEqual(game.wasLastGuessCorrect, null);
assert.strictEqual(game.presentCount, 0);
assert.strictEqual(game.guessCount, 0);
assert.strictEqual(game.guessCountForCurrentCorrectChoice, 0);
assert.strictEqual(game.shouldRefreshChoices, false);
assert.strictEqual(game.shouldRefreshCorrectChoice, false);
assert.strictEqual(game.refreshChoicesCount, 1);
assert.strictEqual(game.refreshCorrectChoiceCount, 1);
});
});
describe('setDifficulty', () => {
it('should set the level and step for a game', () => {
const game = createAndInitGame();
const newLevel = 2;
const newStep = 2;
assert.notStrictEqual(game.level, newLevel);
assert.notStrictEqual(game.step, newStep);
const updatedGame = setDifficulty(game, newLevel, newStep);
assert.strictEqual(updatedGame.level, newLevel);
assert.strictEqual(updatedGame.step, newStep);
assert.strictEqual(updatedGame.shouldRefreshChoices, true);
});
});
describe('refresh', () => {
it('should refresh a game when forced', () => {
const game = createAndInitGame();
const newChoices = I.List([7, 8, 9]);
const newCorrectChoice = 8;
assert(!I.is(game.choices, newChoices));
assert.notStrictEqual(game.correctChoice, newCorrectChoice);
const updatedGame = refresh(
game,
(g: TestState) => g.set('choices', newChoices) as TestState,
(g: TestState) => g.set('correctChoice', newCorrectChoice) as TestState,
true
);
assert(I.is(updatedGame.choices, newChoices));
assert.strictEqual(updatedGame.correctChoice, newCorrectChoice);
assert.strictEqual(updatedGame.guessCountForCurrentCorrectChoice, 0);
assert.strictEqual(game.refreshChoicesCount, updatedGame.refreshChoicesCount - 1);
assert.strictEqual(game.refreshCorrectChoiceCount, updatedGame.refreshCorrectChoiceCount - 1);
});
it('should not refresh a new game when not forced', () => {
const game = createAndInitGame();
const newChoices = I.List([7, 8, 9]);
const newCorrectChoice = 8;
assert(!I.is(game.choices, newChoices));
assert.notStrictEqual(game.correctChoice, newCorrectChoice);
const updatedGame = refresh(
game,
(g: TestState) => g.set('choices', newChoices) as TestState,
(g: TestState) => g.set('correctChoice', newCorrectChoice) as TestState,
false
);
assert(!I.is(updatedGame.choices, newChoices));
assert.notStrictEqual(updatedGame.correctChoice, newCorrectChoice);
assert.strictEqual(updatedGame.guessCountForCurrentCorrectChoice, 0);
assert.strictEqual(game.refreshChoicesCount, updatedGame.refreshChoicesCount);
assert.strictEqual(game.refreshCorrectChoiceCount, updatedGame.refreshCorrectChoiceCount);
});
it('should refresh a game when not forced if the refresh flags are true', () => {
const game = createAndInitGame()
.set('shouldRefreshChoices', true)
.set('shouldRefreshCorrectChoice', true) as TestState;
const newChoices = I.List([7, 8, 9]);
const newCorrectChoice = 8;
assert(!I.is(game.choices, newChoices));
assert.notStrictEqual(game.correctChoice, newCorrectChoice);
const updatedGame = refresh(
game,
(g: TestState) => g.set('choices', newChoices) as TestState,
(g: TestState) => g.set('correctChoice', newCorrectChoice) as TestState,
false
);
assert(I.is(updatedGame.choices, newChoices));
assert.strictEqual(updatedGame.correctChoice, newCorrectChoice);
assert.strictEqual(updatedGame.guessCountForCurrentCorrectChoice, 0);
assert.strictEqual(game.refreshChoicesCount, updatedGame.refreshChoicesCount - 1);
assert.strictEqual(game.refreshCorrectChoiceCount, updatedGame.refreshCorrectChoiceCount - 1);
});
});
describe('guess', () => {
it('should perform an incorrect guess on a game that does not change its level', () => {
const game = setDifficulty(createAndInitGame(), 1, 2);
const incorrectChoice = game.choices.last();
assert.notStrictEqual(game.correctChoice, incorrectChoice);
const updatedGame = guess(game, incorrectChoice);
assert.strictEqual(updatedGame.level, game.level);
assert.strictEqual(updatedGame.step, game.step - 1);
assert.strictEqual(updatedGame.lastGuess, incorrectChoice);
assert.strictEqual(updatedGame.wasLastGuessCorrect, false);
assert.strictEqual(updatedGame.guessCount, game.guessCount + 1);
assert.strictEqual(updatedGame.guessCountForCurrentCorrectChoice, game.guessCountForCurrentCorrectChoice + 1);
assert.strictEqual(updatedGame.shouldRefreshChoices, false);
assert.strictEqual(updatedGame.shouldRefreshCorrectChoice, false);
});
it('should perform an incorrect guess on a game that changes its level', () => {
const game = setDifficulty(createAndInitGame(), 2, 1);
const incorrectChoice = game.choices.last();
assert.notStrictEqual(game.correctChoice, incorrectChoice);
const updatedGame = guess(game, incorrectChoice);
assert.strictEqual(updatedGame.level, game.level - 1);
assert.strictEqual(updatedGame.step, updatedGame.stepCounts.get(updatedGame.level));
assert.strictEqual(updatedGame.lastGuess, incorrectChoice);
assert.strictEqual(updatedGame.wasLastGuessCorrect, false);
assert.strictEqual(updatedGame.guessCount, game.guessCount + 1);
assert.strictEqual(updatedGame.guessCountForCurrentCorrectChoice, game.guessCountForCurrentCorrectChoice + 1);
assert.strictEqual(updatedGame.shouldRefreshChoices, true);
assert.strictEqual(updatedGame.shouldRefreshCorrectChoice, false);
});
it('should perform a correct guess on a game that does not change its level', () => {
const game = setDifficulty(createAndInitGame(), 1, 2);
assert.strictEqual(game.correctChoice, game.correctChoice);
const updatedGame = guess(game, game.correctChoice);
assert.strictEqual(updatedGame.level, game.level);
assert.strictEqual(updatedGame.step, game.step + 1);
assert.strictEqual(updatedGame.lastGuess, game.correctChoice);
assert.strictEqual(updatedGame.wasLastGuessCorrect, true);
assert.strictEqual(updatedGame.guessCount, game.guessCount + 1);
assert.strictEqual(updatedGame.guessCountForCurrentCorrectChoice, game.guessCountForCurrentCorrectChoice + 1);
assert.strictEqual(updatedGame.shouldRefreshChoices, false);
assert.strictEqual(updatedGame.shouldRefreshCorrectChoice, true);
});
it('should perform a correct guess on a game that changes its level', () => {
const originalGame = createAndInitGame();
const game = setDifficulty(originalGame, 1, originalGame.stepCounts.get(1));
assert.strictEqual(game.correctChoice, game.correctChoice);
const updatedGame = guess(game, game.correctChoice);
assert.strictEqual(updatedGame.level, game.level + 1);
assert.strictEqual(updatedGame.step, 1);
assert.strictEqual(updatedGame.lastGuess, game.correctChoice);
assert.strictEqual(updatedGame.wasLastGuessCorrect, true);
assert.strictEqual(updatedGame.guessCount, game.guessCount + 1);
assert.strictEqual(updatedGame.guessCountForCurrentCorrectChoice, game.guessCountForCurrentCorrectChoice + 1);
assert.strictEqual(updatedGame.shouldRefreshChoices, true);
assert.strictEqual(updatedGame.shouldRefreshCorrectChoice, true);
});
});
describe('clampDifficulty', () => {
it('should enforce that the level does not go below its minimum', () => {
assert.deepEqual(
clampDifficulty(levels, stepCounts, 0, 1),
[1, 0]
);
});
it('should enforce that the step does not go below its minimum', () => {
assert.deepEqual(
clampDifficulty(levels, stepCounts, 1, -1),
[1, 0]
);
});
it('should enforce that the level does not go above its maximum', () => {
assert.deepEqual(
clampDifficulty(levels, stepCounts, levels.last() + 1, 1),
[levels.last(), stepCounts.get(levels.last())]
);
});
it('should enforce that the step does not go above its maximum', () => {
assert.deepEqual(
clampDifficulty(levels, stepCounts, levels.last(), stepCounts.get(levels.last()) + 1),
[levels.last(), stepCounts.get(levels.last())]
);
});
it('should increment the level and reset the step when the step exceeds the maximum for the level', () => {
assert.deepEqual(
clampDifficulty(levels, stepCounts, levels.first(), stepCounts.get(levels.first()) + 1),
[levels.first() + 1, 1]
);
});
it('should decrement the level and set the step to the new maximum when the step is lower than the minimum for the level', () => {
assert.deepEqual(
clampDifficulty(levels, stepCounts, 2, 0),
[1, stepCounts.get(1)]
);
});
});
describe('createLevels', () => {
it('should create an iterable sequence of levels for a game', () => {
const levelCount = 12;
const levels = createLevels(levelCount); // tslint:disable-line:no-shadowed-variable
assert.equal(levels.first(), 1, 'levels should start counting at 1');
assert.equal(levels.last(), levelCount);
});
});
}); | the_stack |
import {
Feature,
FeatureCollection,
Geometry,
Polygon,
MultiLineString,
MultiPolygon,
Position,
PolygonCoordinates,
} from '../geojson-types';
export class ImmutableFeatureCollection {
featureCollection: FeatureCollection;
constructor(featureCollection: FeatureCollection) {
this.featureCollection = featureCollection;
}
getObject() {
return this.featureCollection;
}
/**
* Replaces the position deeply nested withing the given feature's geometry.
* Works with Point, MultiPoint, LineString, MultiLineString, Polygon, and MultiPolygon.
*
* @param featureIndex The index of the feature to update
* @param positionIndexes An array containing the indexes of the position to replace
* @param updatedPosition The updated position to place in the result (i.e. [lng, lat])
*
* @returns A new `ImmutableFeatureCollection` with the given position replaced. Does not modify this `ImmutableFeatureCollection`.
*/
replacePosition(
featureIndex: number,
positionIndexes: number[] | null | undefined,
updatedPosition: Position
): ImmutableFeatureCollection {
const geometry = this.featureCollection.features[featureIndex].geometry;
const isPolygonal = geometry.type === 'Polygon' || geometry.type === 'MultiPolygon';
const updatedGeometry: any = {
...geometry,
coordinates: immutablyReplacePosition(
geometry.coordinates,
positionIndexes,
updatedPosition,
isPolygonal
),
};
return this.replaceGeometry(featureIndex, updatedGeometry);
}
/**
* Removes a position deeply nested in a GeoJSON geometry coordinates array.
* Works with MultiPoint, LineString, MultiLineString, Polygon, and MultiPolygon.
*
* @param featureIndex The index of the feature to update
* @param positionIndexes An array containing the indexes of the postion to remove
*
* @returns A new `ImmutableFeatureCollection` with the given coordinate removed. Does not modify this `ImmutableFeatureCollection`.
*/
removePosition(
featureIndex: number,
positionIndexes: number[] | null | undefined
): ImmutableFeatureCollection {
const geometry = this.featureCollection.features[featureIndex].geometry;
if (geometry.type === 'Point') {
throw Error(`Can't remove a position from a Point or there'd be nothing left`);
}
if (
geometry.type === 'MultiPoint' && // only 1 point left
geometry.coordinates.length < 2
) {
throw Error(`Can't remove the last point of a MultiPoint or there'd be nothing left`);
}
if (
geometry.type === 'LineString' && // only 2 positions
geometry.coordinates.length < 3
) {
throw Error(`Can't remove position. LineString must have at least two positions`);
}
if (
geometry.type === 'Polygon' && // outer ring is a triangle
geometry.coordinates[0].length < 5 &&
Array.isArray(positionIndexes) && // trying to remove from outer ring
positionIndexes[0] === 0
) {
throw Error(`Can't remove position. Polygon's outer ring must have at least four positions`);
}
if (
geometry.type === 'MultiLineString' && // only 1 LineString left
geometry.coordinates.length === 1 && // only 2 positions
geometry.coordinates[0].length < 3
) {
throw Error(`Can't remove position. MultiLineString must have at least two positions`);
}
if (
geometry.type === 'MultiPolygon' && // only 1 polygon left
geometry.coordinates.length === 1 && // outer ring is a triangle
geometry.coordinates[0][0].length < 5 &&
Array.isArray(positionIndexes) && // trying to remove from first polygon
positionIndexes[0] === 0 && // trying to remove from outer ring
positionIndexes[1] === 0
) {
throw Error(
`Can't remove position. MultiPolygon's outer ring must have at least four positions`
);
}
const isPolygonal = geometry.type === 'Polygon' || geometry.type === 'MultiPolygon';
const updatedGeometry: any = {
...geometry,
coordinates: immutablyRemovePosition(geometry.coordinates, positionIndexes, isPolygonal),
};
// Handle cases where incomplete geometries need pruned (e.g. holes that were triangles)
pruneGeometryIfNecessary(updatedGeometry);
return this.replaceGeometry(featureIndex, updatedGeometry);
}
/**
* Adds a position deeply nested in a GeoJSON geometry coordinates array.
* Works with MultiPoint, LineString, MultiLineString, Polygon, and MultiPolygon.
*
* @param featureIndex The index of the feature to update
* @param positionIndexes An array containing the indexes of the position that will proceed the new position
* @param positionToAdd The new position to place in the result (i.e. [lng, lat])
*
* @returns A new `ImmutableFeatureCollection` with the given coordinate removed. Does not modify this `ImmutableFeatureCollection`.
*/
addPosition(
featureIndex: number,
positionIndexes: number[] | null | undefined,
positionToAdd: Position
): ImmutableFeatureCollection {
const geometry = this.featureCollection.features[featureIndex].geometry;
if (geometry.type === 'Point') {
throw new Error('Unable to add a position to a Point feature');
}
const isPolygonal = geometry.type === 'Polygon' || geometry.type === 'MultiPolygon';
const updatedGeometry: any = {
...geometry,
coordinates: immutablyAddPosition(
geometry.coordinates,
positionIndexes,
positionToAdd,
isPolygonal
),
};
return this.replaceGeometry(featureIndex, updatedGeometry);
}
replaceGeometry(featureIndex: number, geometry: Geometry): ImmutableFeatureCollection {
const updatedFeature: any = {
...this.featureCollection.features[featureIndex],
geometry,
};
const updatedFeatureCollection = {
...this.featureCollection,
features: [
...this.featureCollection.features.slice(0, featureIndex),
updatedFeature,
...this.featureCollection.features.slice(featureIndex + 1),
],
};
return new ImmutableFeatureCollection(updatedFeatureCollection);
}
addFeature(feature: Feature): ImmutableFeatureCollection {
return this.addFeatures([feature]);
}
addFeatures(features: Feature[]): ImmutableFeatureCollection {
const updatedFeatureCollection = {
...this.featureCollection,
features: [...this.featureCollection.features, ...features],
};
return new ImmutableFeatureCollection(updatedFeatureCollection);
}
deleteFeature(featureIndex: number) {
return this.deleteFeatures([featureIndex]);
}
deleteFeatures(featureIndexes: number[]) {
const features = [...this.featureCollection.features];
featureIndexes.sort();
for (let i = featureIndexes.length - 1; i >= 0; i--) {
const featureIndex = featureIndexes[i];
if (featureIndex >= 0 && featureIndex < features.length) {
features.splice(featureIndex, 1);
}
}
const updatedFeatureCollection = {
...this.featureCollection,
features,
};
return new ImmutableFeatureCollection(updatedFeatureCollection);
}
}
function getUpdatedPosition(updatedPosition: Position, previousPosition: Position): Position {
// This function checks if the updatedPosition is missing elevation
// and copies it from previousPosition
if (updatedPosition.length === 2 && previousPosition.length === 3) {
const elevation = (previousPosition as any)[2];
return [updatedPosition[0], updatedPosition[1], elevation];
}
return updatedPosition;
}
function immutablyReplacePosition(
coordinates: any,
positionIndexes: number[] | null | undefined,
updatedPosition: Position,
isPolygonal: boolean
): any {
if (!positionIndexes) {
return coordinates;
}
if (positionIndexes.length === 0) {
return getUpdatedPosition(updatedPosition, coordinates);
}
if (positionIndexes.length === 1) {
const updated = [
...coordinates.slice(0, positionIndexes[0]),
getUpdatedPosition(updatedPosition, coordinates[positionIndexes[0]]),
...coordinates.slice(positionIndexes[0] + 1),
];
if (
isPolygonal &&
(positionIndexes[0] === 0 || positionIndexes[0] === coordinates.length - 1)
) {
// for polygons, the first point is repeated at the end of the array
// so, update it on both ends of the array
updated[0] = getUpdatedPosition(updatedPosition, coordinates[0]);
updated[coordinates.length - 1] = getUpdatedPosition(updatedPosition, coordinates[0]);
}
return updated;
}
// recursively update inner array
return [
...coordinates.slice(0, positionIndexes[0]),
immutablyReplacePosition(
coordinates[positionIndexes[0]],
positionIndexes.slice(1, positionIndexes.length),
updatedPosition,
isPolygonal
),
...coordinates.slice(positionIndexes[0] + 1),
];
}
function immutablyRemovePosition(
coordinates: any,
positionIndexes: number[] | null | undefined,
isPolygonal: boolean
): any {
if (!positionIndexes) {
return coordinates;
}
if (positionIndexes.length === 0) {
throw Error('Must specify the index of the position to remove');
}
if (positionIndexes.length === 1) {
const updated = [
...coordinates.slice(0, positionIndexes[0]),
...coordinates.slice(positionIndexes[0] + 1),
];
if (
isPolygonal &&
(positionIndexes[0] === 0 || positionIndexes[0] === coordinates.length - 1)
) {
// for polygons, the first point is repeated at the end of the array
// so, if the first/last coordinate is to be removed, coordinates[1] will be the new first/last coordinate
if (positionIndexes[0] === 0) {
// change the last to be the same as the first
updated[updated.length - 1] = updated[0];
} else if (positionIndexes[0] === coordinates.length - 1) {
// change the first to be the same as the last
updated[0] = updated[updated.length - 1];
}
}
return updated;
}
// recursively update inner array
return [
...coordinates.slice(0, positionIndexes[0]),
immutablyRemovePosition(
coordinates[positionIndexes[0]],
positionIndexes.slice(1, positionIndexes.length),
isPolygonal
),
...coordinates.slice(positionIndexes[0] + 1),
];
}
function immutablyAddPosition(
coordinates: any,
positionIndexes: number[] | null | undefined,
positionToAdd: Position,
isPolygonal: boolean
): any {
if (!positionIndexes) {
return coordinates;
}
if (positionIndexes.length === 0) {
throw Error('Must specify the index of the position to remove');
}
if (positionIndexes.length === 1) {
const updated = [
...coordinates.slice(0, positionIndexes[0]),
positionToAdd,
...coordinates.slice(positionIndexes[0]),
];
return updated;
}
// recursively update inner array
return [
...coordinates.slice(0, positionIndexes[0]),
immutablyAddPosition(
coordinates[positionIndexes[0]],
positionIndexes.slice(1, positionIndexes.length),
positionToAdd,
isPolygonal
),
...coordinates.slice(positionIndexes[0] + 1),
];
}
function pruneGeometryIfNecessary(geometry: Geometry) {
switch (geometry.type) {
case 'Polygon':
prunePolygonIfNecessary(geometry);
break;
case 'MultiLineString':
pruneMultiLineStringIfNecessary(geometry);
break;
case 'MultiPolygon':
pruneMultiPolygonIfNecessary(geometry);
break;
default:
// Not downgradable
break;
}
}
function prunePolygonIfNecessary(geometry: Polygon) {
const polygon = geometry.coordinates;
// If any hole is no longer a polygon, remove the hole entirely
for (let holeIndex = 1; holeIndex < polygon.length; holeIndex++) {
if (removeHoleIfNecessary(polygon, holeIndex)) {
// It was removed, so keep the index the same
holeIndex--;
}
}
}
function pruneMultiLineStringIfNecessary(geometry: MultiLineString) {
for (let lineStringIndex = 0; lineStringIndex < geometry.coordinates.length; lineStringIndex++) {
const lineString = geometry.coordinates[lineStringIndex];
if (lineString.length === 1) {
// Only a single position left on this LineString, so remove it (can't have Point in MultiLineString)
geometry.coordinates.splice(lineStringIndex, 1);
// Keep the index the same
lineStringIndex--;
}
}
}
function pruneMultiPolygonIfNecessary(geometry: MultiPolygon) {
for (let polygonIndex = 0; polygonIndex < geometry.coordinates.length; polygonIndex++) {
const polygon = geometry.coordinates[polygonIndex];
const outerRing = polygon[0];
// If the outer ring is no longer a polygon, remove the whole polygon
if (outerRing.length <= 3) {
geometry.coordinates.splice(polygonIndex, 1);
// It was removed, so keep the index the same
polygonIndex--;
}
for (let holeIndex = 1; holeIndex < polygon.length; holeIndex++) {
if (removeHoleIfNecessary(polygon, holeIndex)) {
// It was removed, so keep the index the same
holeIndex--;
}
}
}
}
function removeHoleIfNecessary(polygon: PolygonCoordinates, holeIndex: number) {
const hole = polygon[holeIndex];
if (hole.length <= 3) {
polygon.splice(holeIndex, 1);
return true;
}
return false;
} | the_stack |
import {
callIfFunction,
getDeepClone,
getFullPath,
getMergedObject,
getValueAtPath,
getNewEmptyObject,
isCloneable,
isEmptyPath,
isSameValueZero,
splice,
throwInvalidFnError,
} from './utils';
const { isArray } = Array;
const slice = Function.prototype.bind.call(Function.prototype.call, Array.prototype.slice);
/**
* @function createCall
*
* @description
* create handlers for call / callWith
*
* @param isWithHandler is the method using a with handler
* @returns call / callWith
*/
export function createCall<IsWith extends true | false>(
isWithHandler: IsWith,
): IsWith extends true ? unchanged.CallWith : unchanged.Call;
export function createCall<IsWith extends true | false>(
isWithHandler: IsWith,
): unchanged.CallWith | unchanged.Call {
if (isWithHandler) {
return function callWith(
fn: unchanged.WithHandler,
path: unchanged.Path,
parameters: any[],
object: unchanged.Unchangeable | unchanged.Fn,
context: any = object,
) {
if (typeof fn !== 'function') {
throwInvalidFnError();
}
const extraArgs: any[] = slice(arguments, 5);
if (isEmptyPath(path)) {
return callIfFunction(fn(object, ...extraArgs), context, parameters);
}
const value = getValueAtPath(path, object);
if (value === void 0) {
return;
}
const result = fn(value, ...extraArgs);
return callIfFunction(result, context, parameters);
};
}
return function call(
path: unchanged.Path,
parameters: any[],
object: unchanged.Unchangeable | Function,
context: any = object,
) {
const callable = isEmptyPath(path) ? object : getValueAtPath(path, object);
return callIfFunction(callable, context, parameters);
};
}
/**
* @function createGet
*
* @description
* create handlers for get / getWith
*
* @param isWithHandler is the method using a with handler
* @returns get / getWith
*/
export function createGet<IsWith extends true | false>(
isWithHandler: IsWith,
): IsWith extends true ? unchanged.GetWith : unchanged.Get;
export function createGet<IsWith extends true | false>(
isWithHandler: IsWith,
): unchanged.GetWith | unchanged.Get {
if (isWithHandler) {
return function getWith(
fn: unchanged.WithHandler,
path: unchanged.Path,
object: unchanged.Unchangeable,
) {
if (typeof fn !== 'function') {
throwInvalidFnError();
}
const extraArgs: any[] = slice(arguments, 4);
if (isEmptyPath(path)) {
return fn(object, ...extraArgs);
}
const value = getValueAtPath(path, object);
return value === void 0 ? value : fn(value, ...extraArgs);
};
}
return function get(path: unchanged.Path, object: unchanged.Unchangeable) {
return isEmptyPath(path) ? object : getValueAtPath(path, object);
};
}
/**
* @function createGetOr
*
* @description
* create handlers for getOr / getWithOr
*
* @param isWithHandler is the method using a with handler
* @returns getOr / getWithOr
*/
export function createGetOr<IsWith extends true | false>(
isWithHandler: IsWith,
): IsWith extends true ? unchanged.GetWithOr : unchanged.GetOr;
export function createGetOr<IsWith extends true | false>(
isWithHandler: IsWith,
): unchanged.GetWithOr | unchanged.GetOr {
if (isWithHandler) {
return function getWithOr(
fn: unchanged.WithHandler,
noMatchValue: any,
path: unchanged.Path,
object: unchanged.Unchangeable,
) {
if (typeof fn !== 'function') {
throwInvalidFnError();
}
const extraArgs: any[] = slice(arguments, 4);
if (isEmptyPath(path)) {
return fn(object, ...extraArgs);
}
const value = getValueAtPath(path, object);
return value === void 0 ? noMatchValue : fn(value, ...extraArgs);
};
}
return function getOr(noMatchValue: any, path: unchanged.Path, object: unchanged.Unchangeable) {
return isEmptyPath(path) ? object : getValueAtPath(path, object, noMatchValue);
};
}
/**
* @function createHas
*
* @description
* create handlers for has / hasWith
*
* @param isWithHandler is the method using a with handler
* @returns has / hasWith
*/
export function createHas<IsWith extends true | false>(
isWithHandler: IsWith,
): IsWith extends true ? unchanged.HasWith : unchanged.Has;
export function createHas<IsWith extends true | false>(
isWithHandler: IsWith,
): unchanged.HasWith | unchanged.Has {
if (isWithHandler) {
return function hasWith(
fn: unchanged.WithHandler,
path: unchanged.Path,
object: unchanged.Unchangeable,
) {
if (typeof fn !== 'function') {
throwInvalidFnError();
}
const extraArgs: any[] = slice(arguments, 3);
if (isEmptyPath(path)) {
return !!fn(object, ...extraArgs);
}
const value: any = getValueAtPath(path, object);
return value !== void 0 && !!fn(value, ...extraArgs);
};
}
return function has(path: unchanged.Path, object: unchanged.Unchangeable) {
return isEmptyPath(path) ? object != null : getValueAtPath(path, object) !== void 0;
};
}
/**
* @function createIs
*
* @description
* create handlers for is / isWith
*
* @param isWithHandler is the method using a with handler
* @returns is / isWith
*/
export function createIs<IsWith extends true | false>(
isWithHandler: IsWith,
): IsWith extends true ? unchanged.IsWith : unchanged.Is;
export function createIs<IsWith extends true | false>(
isWithHandler: IsWith,
): unchanged.IsWith | unchanged.Is {
if (isWithHandler) {
return function isWith(
fn: unchanged.WithHandler,
path: unchanged.Path,
value: any,
object: unchanged.Unchangeable,
) {
if (typeof fn !== 'function') {
throwInvalidFnError();
}
const extraArgs: any[] = slice(arguments, 4);
if (isEmptyPath(path)) {
return isSameValueZero(fn(object, ...extraArgs), value);
}
return isSameValueZero(fn(getValueAtPath(path, object), ...extraArgs), value);
};
}
return function is(path: unchanged.Path, value: any, object: unchanged.Unchangeable) {
const _path = isEmptyPath(path) ? object : getValueAtPath(path, object);
return isSameValueZero(_path, value);
};
}
/**
* @function createMerge
*
* @description
* create handlers for merge / mergeWith
*
* @param isWithHandler is the method using a with handler
* @param isDeep is the handler for a deep merge or shallow
* @returns merge / mergeWith
*/
export function createMerge<IsWith extends true | false>(
isWithHandler: IsWith,
isDeep: boolean,
): IsWith extends true ? unchanged.MergeWith : unchanged.Merge;
export function createMerge<IsWith extends true | false>(
isWithHandler: IsWith,
isDeep: boolean,
): unchanged.MergeWith | unchanged.Merge {
if (isWithHandler) {
return function mergeWith(
fn: unchanged.WithHandler,
path: unchanged.Path,
object: unchanged.Unchangeable,
): unchanged.Unchangeable {
if (typeof fn !== 'function') {
throwInvalidFnError();
}
const extraArgs: any[] = slice(arguments, 3);
if (!isCloneable(object)) {
return fn(object, ...extraArgs);
}
if (isEmptyPath(path)) {
const objectToMerge: any = fn(object, ...extraArgs);
return objectToMerge ? getMergedObject(object, objectToMerge, isDeep) : object;
}
let hasChanged: boolean = false;
const result: unchanged.Unchangeable = getDeepClone(
path,
object,
(ref: unchanged.Unchangeable, key: unchanged.PathItem): void => {
const objectToMerge: any = fn(ref[key], ...extraArgs);
if (objectToMerge) {
ref[key] = getMergedObject(ref[key], objectToMerge, isDeep);
hasChanged = true;
}
},
);
return hasChanged ? result : object;
};
}
return function merge(
path: unchanged.Path,
objectToMerge: unchanged.Unchangeable,
object: unchanged.Unchangeable,
): unchanged.Unchangeable {
if (!isCloneable(object)) {
return objectToMerge;
}
return isEmptyPath(path)
? getMergedObject(object, objectToMerge, true)
: getDeepClone(path, object, (ref: unchanged.Unchangeable, key: unchanged.PathItem): void => {
ref[key] = getMergedObject(ref[key], objectToMerge, isDeep);
});
};
}
/**
* @function createNot
*
* @description
* create handlers for not / notWith
*
* @param isWithHandler not the method using a with handler
* @returns not / notWithHandler
*/
export function createNot<IsWith extends true | false>(
isWithHandler: IsWith,
): IsWith extends true ? unchanged.NotWith : unchanged.Not;
export function createNot<IsWith extends true | false>(
isWithHandler: IsWith,
): unchanged.NotWith | unchanged.Not {
const is: Function = createIs(isWithHandler);
return function not(this: any) {
return !is.apply(this, arguments);
};
}
/**
* @function createRemove
*
* @description
* create handlers for remove / removeWith
*
* @param isWithHandler is the method using a with handler
* @returns remove / removeWith
*/
export function createRemove<IsWith extends true | false>(
isWithHandler: IsWith,
): IsWith extends true ? unchanged.RemoveWith : unchanged.Remove;
export function createRemove<IsWith extends true | false>(
isWithHandler: IsWith,
): unchanged.RemoveWith | unchanged.Remove {
if (isWithHandler) {
return function removeWith(
fn: unchanged.WithHandler,
path: unchanged.Path,
object: unchanged.Unchangeable,
): unchanged.Unchangeable {
if (typeof fn !== 'function') {
throwInvalidFnError();
}
const extraArgs: any[] = slice(arguments, 3);
if (isEmptyPath(path)) {
const emptyObject: unchanged.Unchangeable = getNewEmptyObject(object);
return fn(emptyObject, ...extraArgs) ? emptyObject : object;
}
const value: any = getValueAtPath(path, object);
return value !== void 0 && fn(value, ...extraArgs)
? getDeepClone(path, object, (ref: unchanged.Unchangeable, key: number | string): void => {
if (isArray(ref)) {
splice(ref, key as number);
} else {
delete ref[key];
}
})
: object;
};
}
return function remove(
path: unchanged.Path,
object: unchanged.Unchangeable,
): unchanged.Unchangeable {
if (isEmptyPath(path)) {
return getNewEmptyObject(object);
}
return getValueAtPath(path, object) !== void 0
? getDeepClone(path, object, (ref: unchanged.Unchangeable, key: number | string): void => {
if (isArray(ref)) {
splice(ref, key as number);
} else {
delete ref[key];
}
})
: object;
};
}
/**
* @function createSet
*
* @description
* create handlers for set / setWith
*
* @param isWithHandler is the method using a with handler
* @returns set / setWith
*/
export function createSet<IsWith extends true | false>(
isWithHandler: IsWith,
): IsWith extends true ? unchanged.SetWith : unchanged.Set;
export function createSet<IsWith extends true | false>(
isWithHandler: IsWith,
): unchanged.SetWith | unchanged.Set {
if (isWithHandler) {
return function setWith(
fn: unchanged.WithHandler,
path: unchanged.Path,
object: unchanged.Unchangeable,
): unchanged.Unchangeable {
if (typeof fn !== 'function') {
throwInvalidFnError();
}
const extraArgs: any[] = slice(arguments, 3);
return isEmptyPath(path)
? fn(object, ...extraArgs)
: getDeepClone(
path,
object,
(ref: unchanged.Unchangeable, key: unchanged.PathItem): void => {
ref[key] = fn(ref[key], ...extraArgs);
},
);
};
}
return function set(
path: unchanged.Path,
value: any,
object: unchanged.Unchangeable,
): unchanged.Unchangeable {
return isEmptyPath(path)
? value
: getDeepClone(path, object, (ref: unchanged.Unchangeable, key: unchanged.PathItem): void => {
ref[key] = value;
});
};
}
/**
* @function createAdd
*
* @description
* create handlers for add / addWith
*
* @param isWithHandler is the method using a with handler
* @returns add / addWith
*/
export function createAdd<IsWith extends true | false>(
isWithHandler: IsWith,
): IsWith extends true ? unchanged.AddWith : unchanged.Add;
export function createAdd<IsWith extends true | false>(
isWithHandler: IsWith,
): unchanged.AddWith | unchanged.Add {
const _add: Function = createSet(isWithHandler);
if (isWithHandler) {
return function addWith(
this: any,
fn: unchanged.WithHandler,
path: unchanged.Path,
object: unchanged.Unchangeable,
): unchanged.Unchangeable {
return _add.apply(
this,
[fn, getFullPath(path, object, fn), object].concat(slice(arguments, 3)),
);
};
}
return function add(
path: unchanged.Path,
value: any,
object: unchanged.Unchangeable,
): unchanged.Unchangeable {
return _add(getFullPath(path, object), value, object);
};
} | the_stack |
'use strict';
import { workspace, window, ExtensionContext, languages, commands } from 'vscode';
import { Planning } from './planning/planning';
import { PddlWorkspace } from 'pddl-workspace';
import { PDDL, PLAN, HAPPENINGS } from 'pddl-workspace';
import { PddlConfiguration, PDDL_CONFIGURE_COMMAND } from './configuration/configuration';
import { SAuthentication } from './util/Authentication';
import { AutoCompletion } from './completion/AutoCompletion';
import { SymbolRenameProvider } from './symbols/SymbolRenameProvider';
import { SymbolInfoProvider } from './symbols/SymbolInfoProvider';
import { Diagnostics } from './diagnostics/Diagnostics';
import { StartUp } from './init/StartUp';
import { PTestExplorer } from './ptest/PTestExplorer';
import { PlanValidator } from './diagnostics/PlanValidator';
import { Debugging } from './debugger/debugging';
import { ExtensionInfo, ExtensionPackage } from './configuration/ExtensionInfo';
import { HappeningsValidator } from './diagnostics/HappeningsValidator';
import { PlanComparer } from './comparison/PlanComparer';
import { Catalog } from './catalog/Catalog';
import { initialize, instrumentOperation, instrumentOperationAsVsCodeCommand } from "vscode-extension-telemetry-wrapper";
import { SearchDebugger } from './searchDebugger/SearchDebugger';
import { PlanningDomainsSessions } from './session/PlanningDomainsSessions';
import { PddlFormatProvider } from './formatting/PddlFormatProvider';
import { ValDownloader } from './validation/ValDownloader';
import { createPddlExtensionContext, showError, toPddlFileSystem } from './utils';
import { AssociationProvider } from './workspace/AssociationProvider';
import { SuggestionProvider } from './symbols/SuggestionProvider';
import { CodePddlWorkspace } from './workspace/CodePddlWorkspace';
import { DomainDiagnostics } from './diagnostics/DomainDiagnostics';
import { PddlOnTypeFormatter } from './formatting/PddlOnTypeFormatter';
import { PddlCompletionItemProvider } from './completion/PddlCompletionItemProvider';
import { ProblemInitView } from './modelView/ProblemInitView';
import { ProblemObjectsView } from './modelView/ProblemObjectsView';
import { DomainTypesView } from './modelView/DomainTypesView';
import { ProblemConstraintsView } from './modelView/ProblemConstraintsView';
import { ModelHierarchyProvider } from './symbols/ModelHierarchyProvider';
import { PlannersConfiguration } from './configuration/PlannersConfiguration';
import { registerPlanReport } from './planReport/planReport';
import { PlannerExecutableFactory } from './planning/PlannerExecutable';
const PDDL_CONFIGURE_PARSER = 'pddl.configureParser';
const PDDL_LOGIN_PARSER_SERVICE = 'pddl.loginParserService';
const PDDL_UPDATE_TOKENS_PARSER_SERVICE = 'pddl.updateTokensParserService';
const PDDL_LOGIN_PLANNER_SERVICE = 'pddl.loginPlannerService';
const PDDL_UPDATE_TOKENS_PLANNER_SERVICE = 'pddl.updateTokensPlannerService';
const PDDL_CONFIGURE_VALIDATOR = 'pddl.configureValidate';
let formattingProvider: PddlFormatProvider;
let pddlConfiguration: PddlConfiguration;
export let plannersConfiguration: PlannersConfiguration;
/** the workspace instance that integration tests may use */
export let codePddlWorkspaceForTests: CodePddlWorkspace | undefined;
export let planning: Planning | undefined;
export let ptestExplorer: PTestExplorer | undefined;
export let packageJson: ExtensionPackage | undefined;
/** API this extension exposes to other extensions. */
interface PddlExtensionApi {
pddlWorkspace: PddlWorkspace;
plannerExecutableFactory: PlannerExecutableFactory;
}
export async function activate(context: ExtensionContext): Promise<PddlExtensionApi | undefined> {
const extensionInfo = new ExtensionInfo();
// initialize the instrumentation wrapper
const telemetryKey = process.env.VSCODE_PDDL_TELEMETRY_TOKEN;
if (telemetryKey) {
initialize(extensionInfo.getId(), extensionInfo.getVersion(), telemetryKey);
}
try {
// activate the extension, but send instrumentation data
return await instrumentOperation("activation", activateWithTelemetry)(context);
}
catch (ex: unknown) {
// sadly, the next line never gets triggered, even if the activateWithTelemetry fails
const error = ex as Error;
console.error("Error during PDDL extension activation: " + (error.message ?? ex));
window.showErrorMessage("There was an error starting the PDDL extension: " + (error.message ?? ex));
return undefined;
}
}
async function activateWithTelemetry(_operationId: string, context: ExtensionContext): Promise<PddlExtensionApi> {
pddlConfiguration = new PddlConfiguration(context);
const valDownloader = new ValDownloader(context).registerCommands();
const pddlContext = createPddlExtensionContext(context);
const pddlWorkspace = new PddlWorkspace(pddlConfiguration.getEpsilonTimeStep(), pddlContext, toPddlFileSystem(workspace.fs));
plannersConfiguration = new PlannersConfiguration(context, pddlWorkspace);
// run start-up actions
new StartUp(context, pddlConfiguration, plannersConfiguration, valDownloader).atStartUp();
const codePddlWorkspace = CodePddlWorkspace.getInstance(pddlWorkspace, context, pddlConfiguration);
codePddlWorkspaceForTests = codePddlWorkspace;
planning = new Planning(codePddlWorkspace, pddlConfiguration, plannersConfiguration, context);
registerPlanReport(context);
const planValidator = new PlanValidator(planning.output, codePddlWorkspace, pddlConfiguration, context);
const happeningsValidator = new HappeningsValidator(planning.output, codePddlWorkspace, pddlConfiguration, context);
const configureParserCommand = instrumentOperationAsVsCodeCommand(PDDL_CONFIGURE_PARSER, () => {
pddlConfiguration.askNewParserPath();
});
const searchDebugger = new SearchDebugger(context, pddlConfiguration);
planning.addOptionsProvider(searchDebugger);
const loginParserServiceCommand = instrumentOperationAsVsCodeCommand(PDDL_LOGIN_PARSER_SERVICE, () => {
const scopePromise = pddlConfiguration.askConfigurationScope();
scopePromise.then((scope) => {
if (scope === undefined) { return; } // canceled
const configuration = pddlConfiguration.getConfigurationForScope(scope);
if (configuration === undefined) { return; }
const authentication = createAuthentication(pddlConfiguration);
authentication.login(
(refreshtoken: string, accesstoken: string, stoken: string) => {
pddlConfiguration.savePddlParserAuthenticationTokens(configuration, refreshtoken, accesstoken, stoken, scope.target);
window.showInformationMessage("Login successful.");
},
(message: string) => { window.showErrorMessage('Login failure: ' + message); });
});
});
const updateTokensParserServiceCommand = instrumentOperationAsVsCodeCommand(PDDL_UPDATE_TOKENS_PARSER_SERVICE, () => {
const scopePromise = pddlConfiguration.askConfigurationScope();
scopePromise.then((scope) => {
if (scope === undefined) { return; } // canceled
const configuration = pddlConfiguration.getConfigurationForScope(scope);
if (configuration === undefined) { return; }
const authentication = createAuthentication(pddlConfiguration);
authentication.login(
(refreshtoken: string, accesstoken: string, stoken: string) => {
pddlConfiguration.savePddlParserAuthenticationTokens(configuration, refreshtoken, accesstoken, stoken, scope.target);
window.showInformationMessage("Tokens refreshed and saved.");
},
(message: string) => { window.showErrorMessage('Couldn\'t refresh the tokens, try to login: ' + message); });
});
});
const loginPlannerServiceCommand = instrumentOperationAsVsCodeCommand(PDDL_LOGIN_PLANNER_SERVICE, () => {
const scopePromise = pddlConfiguration.askConfigurationScope();
scopePromise.then((scope) => {
if (scope === undefined) { return; } // canceled
const configuration = pddlConfiguration.getConfigurationForScope(scope);
if (configuration === undefined) { return; }
const authentication = createAuthentication(pddlConfiguration);
authentication.login(
(refreshtoken: string, accesstoken: string, stoken: string) => {
pddlConfiguration.savePddlPlannerAuthenticationTokens(configuration, refreshtoken, accesstoken, stoken, scope.target);
window.showInformationMessage("Login successful.");
},
(message: string) => { window.showErrorMessage('Login failure: ' + message); });
});
});
const updateTokensPlannerServiceCommand = instrumentOperationAsVsCodeCommand(PDDL_UPDATE_TOKENS_PLANNER_SERVICE, () => {
const scopePromise = pddlConfiguration.askConfigurationScope();
scopePromise.then((scope) => {
if (scope === undefined) { return; } // canceled
const configuration = pddlConfiguration.getConfigurationForScope(scope);
if (configuration === undefined) { return; }
const authentication = createAuthentication(pddlConfiguration);
authentication.login(
(refreshtoken: string, accesstoken: string, stoken: string) => {
pddlConfiguration.savePddlPlannerAuthenticationTokens(configuration, refreshtoken, accesstoken, stoken, scope.target);
window.showInformationMessage("Tokens refreshed and saved.");
},
(message: string) => { window.showErrorMessage('Couldn\'t refresh the tokens, try to login: ' + message); });
});
});
context.subscriptions.push(instrumentOperationAsVsCodeCommand(PDDL_CONFIGURE_VALIDATOR, () => {
pddlConfiguration.askNewValidatorPath();
}));
const completionItemProvider = languages.registerCompletionItemProvider(PDDL, new AutoCompletion(codePddlWorkspace), '(', ':', '-');
const completionItemProvider2 = languages.registerCompletionItemProvider(PDDL, new PddlCompletionItemProvider(codePddlWorkspace), '(', ':', '-', '?');
const suggestionProvider = languages.registerCodeActionsProvider(PDDL, new SuggestionProvider(codePddlWorkspace), {
providedCodeActionKinds: SuggestionProvider.providedCodeActionKinds
});
const domainTypesView = new DomainTypesView(context, codePddlWorkspace);
context.subscriptions.push(languages.registerCodeLensProvider(PDDL, domainTypesView));
const problemInitView = new ProblemInitView(context, codePddlWorkspace);
context.subscriptions.push(languages.registerCodeLensProvider(PDDL, problemInitView));
const problemObjectsView = new ProblemObjectsView(context, codePddlWorkspace);
context.subscriptions.push(languages.registerCodeLensProvider(PDDL, problemObjectsView));
const problemConstraintsView = new ProblemConstraintsView(context, codePddlWorkspace);
context.subscriptions.push(languages.registerCodeLensProvider(PDDL, problemConstraintsView));
registerDocumentFormattingProvider(context, codePddlWorkspace);
const renameProvider = languages.registerRenameProvider(PDDL, new SymbolRenameProvider(codePddlWorkspace));
if (workspace.getConfiguration("pddl").get<boolean>("modelHierarchy")) {
const modelHierarchyProvider = new ModelHierarchyProvider(context, codePddlWorkspace);
context.subscriptions.push(languages.registerHoverProvider(PDDL, modelHierarchyProvider));
}
const symbolInfoProvider = new SymbolInfoProvider(codePddlWorkspace);
const documentSymbolProvider = languages.registerDocumentSymbolProvider(PDDL, symbolInfoProvider);
const definitionProvider = languages.registerDefinitionProvider(PDDL, symbolInfoProvider);
const referencesProvider = languages.registerReferenceProvider(PDDL, symbolInfoProvider);
const hoverProvider = languages.registerHoverProvider(PDDL, symbolInfoProvider);
const diagnosticCollection = languages.createDiagnosticCollection(PDDL);
const diagnostics = new Diagnostics(codePddlWorkspace, diagnosticCollection, pddlConfiguration,
planValidator, happeningsValidator);
// tslint:disable-next-line:no-unused-expression
new DomainDiagnostics(codePddlWorkspace);
// tslint:disable-next-line: no-unused-expression
new AssociationProvider(context, codePddlWorkspace);
const planDefinitionProvider = languages.registerDefinitionProvider(PLAN, symbolInfoProvider);
const planHoverProvider = languages.registerHoverProvider(PLAN, symbolInfoProvider);
const happeningsDefinitionProvider = languages.registerDefinitionProvider(HAPPENINGS, symbolInfoProvider);
const happeningsHoverProvider = languages.registerHoverProvider(HAPPENINGS, symbolInfoProvider);
// tslint:disable-next-line:no-unused-expression
ptestExplorer = new PTestExplorer(context, pddlContext, codePddlWorkspace, planning);
// tslint:disable-next-line:no-unused-expression
new Catalog(context);
// tslint:disable-next-line:no-unused-expression
new PlanningDomainsSessions(context);
// tslint:disable-next-line:no-unused-expression
new Debugging(context, codePddlWorkspace, pddlConfiguration);
const localPackageJson = packageJson = context.extension.packageJSON;
context.subscriptions.push(instrumentOperationAsVsCodeCommand('pddl.settings', (): void => {
commands.executeCommand(
'workbench.action.openSettings',
`@ext:${localPackageJson.publisher}.${localPackageJson.name}`
);
}));
context.subscriptions.push(new PlanComparer(pddlWorkspace, pddlConfiguration));
workspace.onDidChangeConfiguration(() => {
plannersConfiguration.refreshStatusBar();
if (registerDocumentFormattingProvider(context, codePddlWorkspace)) {
window.showInformationMessage("PDDL formatter is now available. Right-click on a PDDL file...");
console.log('PDDL Formatter enabled.');
}
});
const configureCommand = instrumentOperationAsVsCodeCommand(PDDL_CONFIGURE_COMMAND, (configurationName: string) => {
pddlConfiguration.askConfiguration(configurationName).catch(showError);
});
plannersConfiguration.registerBuiltInPlannerProviders();
console.log('PDDL Extension initialized.');
// Push the disposables to the context's subscriptions so that the
// client can be deactivated on extension deactivation
context.subscriptions.push(diagnostics,
configureParserCommand, loginParserServiceCommand, updateTokensParserServiceCommand,
loginPlannerServiceCommand, updateTokensPlannerServiceCommand, completionItemProvider, completionItemProvider2,
renameProvider, suggestionProvider, documentSymbolProvider, definitionProvider, referencesProvider, hoverProvider,
planHoverProvider, planDefinitionProvider, happeningsHoverProvider, happeningsDefinitionProvider,
problemInitView, problemObjectsView, problemConstraintsView, configureCommand);
return {
pddlWorkspace: pddlWorkspace,
plannerExecutableFactory: new PlannerExecutableFactory()
};
}
export function deactivate(): void {
// nothing to do
}
function createAuthentication(pddlConfiguration: PddlConfiguration): SAuthentication {
const configuration = pddlConfiguration.getPddlParserServiceAuthenticationConfiguration();
return new SAuthentication(configuration.url!, configuration.requestEncoded!, configuration.clientId!, configuration.callbackPort!, configuration.timeoutInMs!,
configuration.tokensvcUrl!, configuration.tokensvcApiKey!, configuration.tokensvcAccessPath!, configuration.tokensvcValidatePath!,
configuration.tokensvcCodePath!, configuration.tokensvcRefreshPath!, configuration.tokensvcSvctkPath!,
configuration.refreshToken!, configuration.accessToken!, configuration.sToken!);
}
function registerDocumentFormattingProvider(context: ExtensionContext, pddlWorkspace: CodePddlWorkspace): boolean {
if (workspace.getConfiguration("pddl").get<boolean>("formatter") && !formattingProvider) {
formattingProvider = new PddlFormatProvider(pddlWorkspace);
const formattingProviderDisposable = languages.registerDocumentFormattingEditProvider(PDDL, formattingProvider);
context.subscriptions.push(formattingProviderDisposable);
const rangeFormattingProviderDisposable = languages.registerDocumentRangeFormattingEditProvider(PDDL, formattingProvider);
context.subscriptions.push(rangeFormattingProviderDisposable);
const onTypeFormattingProviderDisposable = languages.registerOnTypeFormattingEditProvider(PDDL, new PddlOnTypeFormatter(pddlWorkspace), '\n');
context.subscriptions.push(onTypeFormattingProviderDisposable);
return true;
}
else {
return false;
}
} | the_stack |
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js";
import * as msRest from "@azure/ms-rest-js";
export { BaseResource, CloudError };
/**
* Reference to another subresource.
*/
export interface SubResource extends BaseResource {
/**
* Resource ID.
*/
id?: string;
}
/**
* IP configuration for virtual network gateway
*/
export interface VirtualNetworkGatewayIPConfiguration extends SubResource {
/**
* The private IP allocation method. Possible values are: 'Static' and 'Dynamic'. Possible values
* include: 'Static', 'Dynamic'
*/
privateIPAllocationMethod?: IPAllocationMethod;
/**
* The reference of the subnet resource.
*/
subnet?: SubResource;
/**
* The reference of the public IP resource.
*/
publicIPAddress?: SubResource;
/**
* The provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting',
* and 'Failed'.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: string;
/**
* The name of the resource that is unique within a resource group. This name can be used to
* access the resource.
*/
name?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* VirtualNetworkGatewaySku details
*/
export interface VirtualNetworkGatewaySku {
/**
* Gateway SKU name. Possible values include: 'Basic', 'HighPerformance', 'Standard',
* 'UltraPerformance', 'VpnGw1', 'VpnGw2', 'VpnGw3', 'VpnGw1AZ', 'VpnGw2AZ', 'VpnGw3AZ',
* 'ErGw1AZ', 'ErGw2AZ', 'ErGw3AZ'
*/
name?: VirtualNetworkGatewaySkuName;
/**
* Gateway SKU tier. Possible values include: 'Basic', 'HighPerformance', 'Standard',
* 'UltraPerformance', 'VpnGw1', 'VpnGw2', 'VpnGw3', 'VpnGw1AZ', 'VpnGw2AZ', 'VpnGw3AZ',
* 'ErGw1AZ', 'ErGw2AZ', 'ErGw3AZ'
*/
tier?: VirtualNetworkGatewaySkuTier;
/**
* The capacity.
*/
capacity?: number;
}
/**
* AddressSpace contains an array of IP address ranges that can be used by subnets of the virtual
* network.
*/
export interface AddressSpace {
/**
* A list of address blocks reserved for this virtual network in CIDR notation.
*/
addressPrefixes?: string[];
}
/**
* VPN client root certificate of virtual network gateway
*/
export interface VpnClientRootCertificate extends SubResource {
/**
* The certificate public data.
*/
publicCertData: string;
/**
* The provisioning state of the VPN client root certificate resource. Possible values are:
* 'Updating', 'Deleting', and 'Failed'.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: string;
/**
* The name of the resource that is unique within a resource group. This name can be used to
* access the resource.
*/
name?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* VPN client revoked certificate of virtual network gateway.
*/
export interface VpnClientRevokedCertificate extends SubResource {
/**
* The revoked VPN client certificate thumbprint.
*/
thumbprint?: string;
/**
* The provisioning state of the VPN client revoked certificate resource. Possible values are:
* 'Updating', 'Deleting', and 'Failed'.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: string;
/**
* The name of the resource that is unique within a resource group. This name can be used to
* access the resource.
*/
name?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* An IPSec Policy configuration for a virtual network gateway connection
*/
export interface IpsecPolicy {
/**
* The IPSec Security Association (also called Quick Mode or Phase 2 SA) lifetime in seconds for
* a site to site VPN tunnel.
*/
saLifeTimeSeconds: number;
/**
* The IPSec Security Association (also called Quick Mode or Phase 2 SA) payload size in KB for a
* site to site VPN tunnel.
*/
saDataSizeKilobytes: number;
/**
* The IPSec encryption algorithm (IKE phase 1). Possible values include: 'None', 'DES', 'DES3',
* 'AES128', 'AES192', 'AES256', 'GCMAES128', 'GCMAES192', 'GCMAES256'
*/
ipsecEncryption: IpsecEncryption;
/**
* The IPSec integrity algorithm (IKE phase 1). Possible values include: 'MD5', 'SHA1', 'SHA256',
* 'GCMAES128', 'GCMAES192', 'GCMAES256'
*/
ipsecIntegrity: IpsecIntegrity;
/**
* The IKE encryption algorithm (IKE phase 2). Possible values include: 'DES', 'DES3', 'AES128',
* 'AES192', 'AES256', 'GCMAES256', 'GCMAES128'
*/
ikeEncryption: IkeEncryption;
/**
* The IKE integrity algorithm (IKE phase 2). Possible values include: 'MD5', 'SHA1', 'SHA256',
* 'SHA384', 'GCMAES256', 'GCMAES128'
*/
ikeIntegrity: IkeIntegrity;
/**
* The DH Groups used in IKE Phase 1 for initial SA. Possible values include: 'None', 'DHGroup1',
* 'DHGroup2', 'DHGroup14', 'DHGroup2048', 'ECP256', 'ECP384', 'DHGroup24'
*/
dhGroup: DhGroup;
/**
* The Pfs Groups used in IKE Phase 2 for new child SA. Possible values include: 'None', 'PFS1',
* 'PFS2', 'PFS2048', 'ECP256', 'ECP384', 'PFS24', 'PFS14', 'PFSMM'
*/
pfsGroup: PfsGroup;
}
/**
* VpnClientConfiguration for P2S client.
*/
export interface VpnClientConfiguration {
/**
* The reference of the address space resource which represents Address space for P2S VpnClient.
*/
vpnClientAddressPool?: AddressSpace;
/**
* VpnClientRootCertificate for virtual network gateway.
*/
vpnClientRootCertificates?: VpnClientRootCertificate[];
/**
* VpnClientRevokedCertificate for Virtual network gateway.
*/
vpnClientRevokedCertificates?: VpnClientRevokedCertificate[];
/**
* VpnClientProtocols for Virtual network gateway.
*/
vpnClientProtocols?: VpnClientProtocol[];
/**
* VpnClientIpsecPolicies for virtual network gateway P2S client.
*/
vpnClientIpsecPolicies?: IpsecPolicy[];
/**
* The radius server address property of the VirtualNetworkGateway resource for vpn client
* connection.
*/
radiusServerAddress?: string;
/**
* The radius secret property of the VirtualNetworkGateway resource for vpn client connection.
*/
radiusServerSecret?: string;
}
/**
* BGP settings details
*/
export interface BgpSettings {
/**
* The BGP speaker's ASN.
*/
asn?: number;
/**
* The BGP peering address and BGP identifier of this BGP speaker.
*/
bgpPeeringAddress?: string;
/**
* The weight added to routes learned from this BGP speaker.
*/
peerWeight?: number;
}
/**
* BGP peer status details
*/
export interface BgpPeerStatus {
/**
* The virtual network gateway's local address
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly localAddress?: string;
/**
* The remote BGP peer
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly neighbor?: string;
/**
* The autonomous system number of the remote BGP peer
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly asn?: number;
/**
* The BGP peer state. Possible values include: 'Unknown', 'Stopped', 'Idle', 'Connecting',
* 'Connected'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly state?: BgpPeerState;
/**
* For how long the peering has been up
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly connectedDuration?: string;
/**
* The number of routes learned from this peer
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly routesReceived?: number;
/**
* The number of BGP messages sent
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly messagesSent?: number;
/**
* The number of BGP messages received
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly messagesReceived?: number;
}
/**
* Gateway routing details
*/
export interface GatewayRoute {
/**
* The gateway's local address
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly localAddress?: string;
/**
* The route's network prefix
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly network?: string;
/**
* The route's next hop
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nextHop?: string;
/**
* The peer this route was learned from
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly sourcePeer?: string;
/**
* The source this route was learned from
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly origin?: string;
/**
* The route's AS path sequence
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly asPath?: string;
/**
* The route's weight
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly weight?: number;
}
/**
* Common resource representation.
*/
export interface Resource extends BaseResource {
/**
* Resource ID.
*/
id?: string;
/**
* Resource name.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* Resource type.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
/**
* Resource location.
*/
location?: string;
/**
* Resource tags.
*/
tags?: { [propertyName: string]: string };
}
/**
* A common class for general resource information
*/
export interface VirtualNetworkGateway extends Resource {
/**
* IP configurations for virtual network gateway.
*/
ipConfigurations?: VirtualNetworkGatewayIPConfiguration[];
/**
* The type of this virtual network gateway. Possible values are: 'Vpn' and 'ExpressRoute'.
* Possible values include: 'Vpn', 'ExpressRoute'
*/
gatewayType?: VirtualNetworkGatewayType;
/**
* The type of this virtual network gateway. Possible values are: 'PolicyBased' and 'RouteBased'.
* Possible values include: 'PolicyBased', 'RouteBased'
*/
vpnType?: VpnType;
/**
* Whether BGP is enabled for this virtual network gateway or not.
*/
enableBgp?: boolean;
/**
* ActiveActive flag
*/
activeActive?: boolean;
/**
* The reference of the LocalNetworkGateway resource which represents local network site having
* default routes. Assign Null value in case of removing existing default site setting.
*/
gatewayDefaultSite?: SubResource;
/**
* The reference of the VirtualNetworkGatewaySku resource which represents the SKU selected for
* Virtual network gateway.
*/
sku?: VirtualNetworkGatewaySku;
/**
* The reference of the VpnClientConfiguration resource which represents the P2S VpnClient
* configurations.
*/
vpnClientConfiguration?: VpnClientConfiguration;
/**
* Virtual network gateway's BGP speaker settings.
*/
bgpSettings?: BgpSettings;
/**
* The resource GUID property of the VirtualNetworkGateway resource.
*/
resourceGuid?: string;
/**
* The provisioning state of the VirtualNetworkGateway resource. Possible values are: 'Updating',
* 'Deleting', and 'Failed'.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: string;
/**
* Gets a unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* Vpn Client Parameters for package generation
*/
export interface VpnClientParameters {
/**
* VPN client Processor Architecture. Possible values are: 'AMD64' and 'X86'. Possible values
* include: 'Amd64', 'X86'
*/
processorArchitecture?: ProcessorArchitecture;
/**
* VPN client Authentication Method. Possible values are: 'EAPTLS' and 'EAPMSCHAPv2'. Possible
* values include: 'EAPTLS', 'EAPMSCHAPv2'
*/
authenticationMethod?: AuthenticationMethod;
/**
* The public certificate data for the radius server authentication certificate as a Base-64
* encoded string. Required only if external radius authentication has been configured with
* EAPTLS authentication.
*/
radiusServerAuthCertificate?: string;
/**
* A list of client root certificates public certificate data encoded as Base-64 strings.
* Optional parameter for external radius based authentication with EAPTLS.
*/
clientRootCertificates?: string[];
}
/**
* Response for list BGP peer status API service call
*/
export interface BgpPeerStatusListResult {
/**
* List of BGP peers
*/
value?: BgpPeerStatus[];
}
/**
* List of virtual network gateway routes
*/
export interface GatewayRouteListResult {
/**
* List of gateway routes
*/
value?: GatewayRoute[];
}
/**
* VirtualNetworkGatewayConnection properties
*/
export interface TunnelConnectionHealth {
/**
* Tunnel name.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly tunnel?: string;
/**
* Virtual network Gateway connection status. Possible values include: 'Unknown', 'Connecting',
* 'Connected', 'NotConnected'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly connectionStatus?: VirtualNetworkGatewayConnectionStatus;
/**
* The Ingress Bytes Transferred in this connection
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly ingressBytesTransferred?: number;
/**
* The Egress Bytes Transferred in this connection
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly egressBytesTransferred?: number;
/**
* The time at which connection was established in Utc format.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly lastConnectionEstablishedUtcTime?: string;
}
/**
* A common class for general resource information
*/
export interface LocalNetworkGateway extends Resource {
/**
* Local network site address space.
*/
localNetworkAddressSpace?: AddressSpace;
/**
* IP address of local network gateway.
*/
gatewayIpAddress?: string;
/**
* Local network gateway's BGP speaker settings.
*/
bgpSettings?: BgpSettings;
/**
* The resource GUID property of the LocalNetworkGateway resource.
*/
resourceGuid?: string;
/**
* The provisioning state of the LocalNetworkGateway resource. Possible values are: 'Updating',
* 'Deleting', and 'Failed'.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* A common class for general resource information
*/
export interface VirtualNetworkGatewayConnection extends Resource {
/**
* The authorizationKey.
*/
authorizationKey?: string;
/**
* The reference to virtual network gateway resource.
*/
virtualNetworkGateway1: VirtualNetworkGateway;
/**
* The reference to virtual network gateway resource.
*/
virtualNetworkGateway2?: VirtualNetworkGateway;
/**
* The reference to local network gateway resource.
*/
localNetworkGateway2?: LocalNetworkGateway;
/**
* Gateway connection type. Possible values are: 'Ipsec','Vnet2Vnet','ExpressRoute', and
* 'VPNClient. Possible values include: 'IPsec', 'Vnet2Vnet', 'ExpressRoute', 'VPNClient'
*/
connectionType: VirtualNetworkGatewayConnectionType;
/**
* Connection protocol used for this connection. Possible values include: 'IKEv2', 'IKEv1'
*/
connectionProtocol?: VirtualNetworkGatewayConnectionProtocol;
/**
* The routing weight.
*/
routingWeight?: number;
/**
* The IPSec shared key.
*/
sharedKey?: string;
/**
* Virtual network Gateway connection status. Possible values are 'Unknown', 'Connecting',
* 'Connected' and 'NotConnected'. Possible values include: 'Unknown', 'Connecting', 'Connected',
* 'NotConnected'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly connectionStatus?: VirtualNetworkGatewayConnectionStatus;
/**
* Collection of all tunnels' connection health status.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly tunnelConnectionStatus?: TunnelConnectionHealth[];
/**
* The egress bytes transferred in this connection.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly egressBytesTransferred?: number;
/**
* The ingress bytes transferred in this connection.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly ingressBytesTransferred?: number;
/**
* The reference to peerings resource.
*/
peer?: SubResource;
/**
* EnableBgp flag
*/
enableBgp?: boolean;
/**
* Enable policy-based traffic selectors.
*/
usePolicyBasedTrafficSelectors?: boolean;
/**
* The IPSec Policies to be considered by this connection.
*/
ipsecPolicies?: IpsecPolicy[];
/**
* The resource GUID property of the VirtualNetworkGatewayConnection resource.
*/
resourceGuid?: string;
/**
* The provisioning state of the VirtualNetworkGatewayConnection resource. Possible values are:
* 'Updating', 'Deleting', and 'Failed'.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: string;
/**
* Bypass ExpressRoute Gateway for data forwarding
*/
expressRouteGatewayBypass?: boolean;
/**
* Gets a unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* The virtual network connection reset shared key
*/
export interface ConnectionResetSharedKey {
/**
* The virtual network connection reset shared key length, should between 1 and 128.
*/
keyLength: number;
}
/**
* Response for GetConnectionSharedKey API service call
*/
export interface ConnectionSharedKey extends SubResource {
/**
* The virtual network connection shared key value.
*/
value: string;
}
/**
* An IPSec parameters for a virtual network gateway P2S connection.
*/
export interface VpnClientIPsecParameters {
/**
* The IPSec Security Association (also called Quick Mode or Phase 2 SA) lifetime in seconds for
* P2S client.
*/
saLifeTimeSeconds: number;
/**
* The IPSec Security Association (also called Quick Mode or Phase 2 SA) payload size in KB for
* P2S client..
*/
saDataSizeKilobytes: number;
/**
* The IPSec encryption algorithm (IKE phase 1). Possible values include: 'None', 'DES', 'DES3',
* 'AES128', 'AES192', 'AES256', 'GCMAES128', 'GCMAES192', 'GCMAES256'
*/
ipsecEncryption: IpsecEncryption;
/**
* The IPSec integrity algorithm (IKE phase 1). Possible values include: 'MD5', 'SHA1', 'SHA256',
* 'GCMAES128', 'GCMAES192', 'GCMAES256'
*/
ipsecIntegrity: IpsecIntegrity;
/**
* The IKE encryption algorithm (IKE phase 2). Possible values include: 'DES', 'DES3', 'AES128',
* 'AES192', 'AES256', 'GCMAES256', 'GCMAES128'
*/
ikeEncryption: IkeEncryption;
/**
* The IKE integrity algorithm (IKE phase 2). Possible values include: 'MD5', 'SHA1', 'SHA256',
* 'SHA384', 'GCMAES256', 'GCMAES128'
*/
ikeIntegrity: IkeIntegrity;
/**
* The DH Groups used in IKE Phase 1 for initial SA. Possible values include: 'None', 'DHGroup1',
* 'DHGroup2', 'DHGroup14', 'DHGroup2048', 'ECP256', 'ECP384', 'DHGroup24'
*/
dhGroup: DhGroup;
/**
* The Pfs Groups used in IKE Phase 2 for new child SA. Possible values include: 'None', 'PFS1',
* 'PFS2', 'PFS2048', 'ECP256', 'ECP384', 'PFS24', 'PFS14', 'PFSMM'
*/
pfsGroup: PfsGroup;
}
/**
* A reference to VirtualNetworkGateway or LocalNetworkGateway resource.
*/
export interface VirtualNetworkConnectionGatewayReference {
/**
* The ID of VirtualNetworkGateway or LocalNetworkGateway resource.
*/
id: string;
}
/**
* A common class for general resource information
*/
export interface VirtualNetworkGatewayConnectionListEntity extends Resource {
/**
* The authorizationKey.
*/
authorizationKey?: string;
/**
* The reference to virtual network gateway resource.
*/
virtualNetworkGateway1: VirtualNetworkConnectionGatewayReference;
/**
* The reference to virtual network gateway resource.
*/
virtualNetworkGateway2?: VirtualNetworkConnectionGatewayReference;
/**
* The reference to local network gateway resource.
*/
localNetworkGateway2?: VirtualNetworkConnectionGatewayReference;
/**
* Gateway connection type. Possible values are: 'Ipsec','Vnet2Vnet','ExpressRoute', and
* 'VPNClient. Possible values include: 'IPsec', 'Vnet2Vnet', 'ExpressRoute', 'VPNClient'
*/
connectionType: VirtualNetworkGatewayConnectionType;
/**
* Connection protocol used for this connection. Possible values include: 'IKEv2', 'IKEv1'
*/
connectionProtocol?: VirtualNetworkGatewayConnectionProtocol;
/**
* The routing weight.
*/
routingWeight?: number;
/**
* The IPSec shared key.
*/
sharedKey?: string;
/**
* Virtual network Gateway connection status. Possible values are 'Unknown', 'Connecting',
* 'Connected' and 'NotConnected'. Possible values include: 'Unknown', 'Connecting', 'Connected',
* 'NotConnected'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly connectionStatus?: VirtualNetworkGatewayConnectionStatus;
/**
* Collection of all tunnels' connection health status.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly tunnelConnectionStatus?: TunnelConnectionHealth[];
/**
* The egress bytes transferred in this connection.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly egressBytesTransferred?: number;
/**
* The ingress bytes transferred in this connection.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly ingressBytesTransferred?: number;
/**
* The reference to peerings resource.
*/
peer?: SubResource;
/**
* EnableBgp flag
*/
enableBgp?: boolean;
/**
* Enable policy-based traffic selectors.
*/
usePolicyBasedTrafficSelectors?: boolean;
/**
* The IPSec Policies to be considered by this connection.
*/
ipsecPolicies?: IpsecPolicy[];
/**
* The resource GUID property of the VirtualNetworkGatewayConnection resource.
*/
resourceGuid?: string;
/**
* The provisioning state of the VirtualNetworkGatewayConnection resource. Possible values are:
* 'Updating', 'Deleting', and 'Failed'.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: string;
/**
* Bypass ExpressRoute Gateway for data forwarding
*/
expressRouteGatewayBypass?: boolean;
/**
* Gets a unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* Vpn device configuration script generation parameters
*/
export interface VpnDeviceScriptParameters {
/**
* The vendor for the vpn device.
*/
vendor?: string;
/**
* The device family for the vpn device.
*/
deviceFamily?: string;
/**
* The firmware version for the vpn device.
*/
firmwareVersion?: string;
}
/**
* Tags object for patch operations.
*/
export interface TagsObject {
/**
* Resource tags.
*/
tags?: { [propertyName: string]: string };
}
/**
* SKU of a load balancer
*/
export interface LoadBalancerSku {
/**
* Name of a load balancer SKU. Possible values include: 'Basic', 'Standard'
*/
name?: LoadBalancerSkuName;
}
/**
* An application security group in a resource group.
*/
export interface ApplicationSecurityGroup extends Resource {
/**
* The resource GUID property of the application security group resource. It uniquely identifies
* a resource, even if the user changes its name or migrate the resource across subscriptions or
* resource groups.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly resourceGuid?: string;
/**
* The provisioning state of the application security group resource. Possible values are:
* 'Succeeded', 'Updating', 'Deleting', and 'Failed'.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly etag?: string;
}
/**
* Network security rule.
*/
export interface SecurityRule extends SubResource {
/**
* A description for this rule. Restricted to 140 chars.
*/
description?: string;
/**
* Network protocol this rule applies to. Possible values are 'Tcp', 'Udp', and '*'. Possible
* values include: 'Tcp', 'Udp', '*'
*/
protocol: SecurityRuleProtocol;
/**
* The source port or range. Integer or range between 0 and 65535. Asterisks '*' can also be used
* to match all ports.
*/
sourcePortRange?: string;
/**
* The destination port or range. Integer or range between 0 and 65535. Asterisks '*' can also be
* used to match all ports.
*/
destinationPortRange?: string;
/**
* The CIDR or source IP range. Asterisks '*' can also be used to match all source IPs. Default
* tags such as 'VirtualNetwork', 'AzureLoadBalancer' and 'Internet' can also be used. If this is
* an ingress rule, specifies where network traffic originates from.
*/
sourceAddressPrefix?: string;
/**
* The CIDR or source IP ranges.
*/
sourceAddressPrefixes?: string[];
/**
* The application security group specified as source.
*/
sourceApplicationSecurityGroups?: ApplicationSecurityGroup[];
/**
* The destination address prefix. CIDR or destination IP range. Asterisks '*' can also be used
* to match all source IPs. Default tags such as 'VirtualNetwork', 'AzureLoadBalancer' and
* 'Internet' can also be used.
*/
destinationAddressPrefix?: string;
/**
* The destination address prefixes. CIDR or destination IP ranges.
*/
destinationAddressPrefixes?: string[];
/**
* The application security group specified as destination.
*/
destinationApplicationSecurityGroups?: ApplicationSecurityGroup[];
/**
* The source port ranges.
*/
sourcePortRanges?: string[];
/**
* The destination port ranges.
*/
destinationPortRanges?: string[];
/**
* The network traffic is allowed or denied. Possible values are: 'Allow' and 'Deny'. Possible
* values include: 'Allow', 'Deny'
*/
access: SecurityRuleAccess;
/**
* The priority of the rule. The value can be between 100 and 4096. The priority number must be
* unique for each rule in the collection. The lower the priority number, the higher the priority
* of the rule.
*/
priority?: number;
/**
* The direction of the rule. The direction specifies if rule will be evaluated on incoming or
* outgoing traffic. Possible values are: 'Inbound' and 'Outbound'. Possible values include:
* 'Inbound', 'Outbound'
*/
direction: SecurityRuleDirection;
/**
* The provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting',
* and 'Failed'.
*/
provisioningState?: string;
/**
* The name of the resource that is unique within a resource group. This name can be used to
* access the resource.
*/
name?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* Identifies the service being brought into the virtual network.
*/
export interface EndpointService {
/**
* A unique identifier of the service being referenced by the interface endpoint.
*/
id?: string;
}
/**
* Interface endpoint resource.
*/
export interface InterfaceEndpoint extends Resource {
/**
* A first-party service's FQDN that is mapped to the private IP allocated via this interface
* endpoint.
*/
fqdn?: string;
/**
* A reference to the service being brought into the virtual network.
*/
endpointService?: EndpointService;
/**
* The ID of the subnet from which the private IP will be allocated.
*/
subnet?: Subnet;
/**
* Gets an array of references to the network interfaces created for this interface endpoint.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly networkInterfaces?: NetworkInterface[];
/**
* A read-only property that identifies who created this interface endpoint.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly owner?: string;
/**
* The provisioning state of the interface endpoint. Possible values are: 'Updating', 'Deleting',
* and 'Failed'.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: string;
/**
* Gets a unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* Tap configuration in a Network Interface
*/
export interface NetworkInterfaceTapConfiguration extends SubResource {
/**
* The reference of the Virtual Network Tap resource.
*/
virtualNetworkTap?: VirtualNetworkTap;
/**
* The provisioning state of the network interface tap configuration. Possible values are:
* 'Updating', 'Deleting', and 'Failed'.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: string;
/**
* The name of the resource that is unique within a resource group. This name can be used to
* access the resource.
*/
name?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
/**
* Sub Resource type.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
}
/**
* Frontend IP address of the load balancer.
*/
export interface FrontendIPConfiguration extends SubResource {
/**
* Read only. Inbound rules URIs that use this frontend IP.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly inboundNatRules?: SubResource[];
/**
* Read only. Inbound pools URIs that use this frontend IP.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly inboundNatPools?: SubResource[];
/**
* Read only. Outbound rules URIs that use this frontend IP.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly outboundRules?: SubResource[];
/**
* Gets load balancing rules URIs that use this frontend IP.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly loadBalancingRules?: SubResource[];
/**
* The private IP address of the IP configuration.
*/
privateIPAddress?: string;
/**
* The Private IP allocation method. Possible values are: 'Static' and 'Dynamic'. Possible values
* include: 'Static', 'Dynamic'
*/
privateIPAllocationMethod?: IPAllocationMethod;
/**
* The reference of the subnet resource.
*/
subnet?: Subnet;
/**
* The reference of the Public IP resource.
*/
publicIPAddress?: PublicIPAddress;
/**
* The reference of the Public IP Prefix resource.
*/
publicIPPrefix?: SubResource;
/**
* Gets the provisioning state of the public IP resource. Possible values are: 'Updating',
* 'Deleting', and 'Failed'.
*/
provisioningState?: string;
/**
* The name of the resource that is unique within a resource group. This name can be used to
* access the resource.
*/
name?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
/**
* A list of availability zones denoting the IP allocated for the resource needs to come from.
*/
zones?: string[];
}
/**
* Virtual Network Tap resource
*/
export interface VirtualNetworkTap extends Resource {
/**
* Specifies the list of resource IDs for the network interface IP configuration that needs to be
* tapped.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly networkInterfaceTapConfigurations?: NetworkInterfaceTapConfiguration[];
/**
* The resourceGuid property of the virtual network tap.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly resourceGuid?: string;
/**
* The provisioning state of the virtual network tap. Possible values are: 'Updating',
* 'Deleting', and 'Failed'.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: string;
/**
* The reference to the private IP Address of the collector nic that will receive the tap
*/
destinationNetworkInterfaceIPConfiguration?: NetworkInterfaceIPConfiguration;
/**
* The reference to the private IP address on the internal Load Balancer that will receive the
* tap
*/
destinationLoadBalancerFrontEndIPConfiguration?: FrontendIPConfiguration;
/**
* The VXLAN destination port that will receive the tapped traffic.
*/
destinationPort?: number;
/**
* Gets a unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* Backend address of an application gateway.
*/
export interface ApplicationGatewayBackendAddress {
/**
* Fully qualified domain name (FQDN).
*/
fqdn?: string;
/**
* IP address
*/
ipAddress?: string;
}
/**
* Backend Address Pool of an application gateway.
*/
export interface ApplicationGatewayBackendAddressPool extends SubResource {
/**
* Collection of references to IPs defined in network interfaces.
*/
backendIPConfigurations?: NetworkInterfaceIPConfiguration[];
/**
* Backend addresses
*/
backendAddresses?: ApplicationGatewayBackendAddress[];
/**
* Provisioning state of the backend address pool resource. Possible values are: 'Updating',
* 'Deleting', and 'Failed'.
*/
provisioningState?: string;
/**
* Name of the backend address pool that is unique within an Application Gateway.
*/
name?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
/**
* Type of the resource.
*/
type?: string;
}
/**
* Pool of backend IP addresses.
*/
export interface BackendAddressPool extends SubResource {
/**
* Gets collection of references to IP addresses defined in network interfaces.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly backendIPConfigurations?: NetworkInterfaceIPConfiguration[];
/**
* Gets load balancing rules that use this backend address pool.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly loadBalancingRules?: SubResource[];
/**
* Gets outbound rules that use this backend address pool.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly outboundRule?: SubResource;
/**
* Gets outbound rules that use this backend address pool.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly outboundRules?: SubResource[];
/**
* Get provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting',
* and 'Failed'.
*/
provisioningState?: string;
/**
* Gets name of the resource that is unique within a resource group. This name can be used to
* access the resource.
*/
name?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* Inbound NAT rule of the load balancer.
*/
export interface InboundNatRule extends SubResource {
/**
* A reference to frontend IP addresses.
*/
frontendIPConfiguration?: SubResource;
/**
* A reference to a private IP address defined on a network interface of a VM. Traffic sent to
* the frontend port of each of the frontend IP configurations is forwarded to the backend IP.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly backendIPConfiguration?: NetworkInterfaceIPConfiguration;
/**
* Possible values include: 'Udp', 'Tcp', 'All'
*/
protocol?: TransportProtocol;
/**
* The port for the external endpoint. Port numbers for each rule must be unique within the Load
* Balancer. Acceptable values range from 1 to 65534.
*/
frontendPort?: number;
/**
* The port used for the internal endpoint. Acceptable values range from 1 to 65535.
*/
backendPort?: number;
/**
* The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The
* default value is 4 minutes. This element is only used when the protocol is set to TCP.
*/
idleTimeoutInMinutes?: number;
/**
* Configures a virtual machine's endpoint for the floating IP capability required to configure a
* SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn
* Availability Groups in SQL server. This setting can't be changed after you create the
* endpoint.
*/
enableFloatingIP?: boolean;
/**
* Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected connection termination.
* This element is only used when the protocol is set to TCP.
*/
enableTcpReset?: boolean;
/**
* Gets the provisioning state of the public IP resource. Possible values are: 'Updating',
* 'Deleting', and 'Failed'.
*/
provisioningState?: string;
/**
* Gets name of the resource that is unique within a resource group. This name can be used to
* access the resource.
*/
name?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* SKU of a public IP address
*/
export interface PublicIPAddressSku {
/**
* Name of a public IP address SKU. Possible values include: 'Basic', 'Standard'
*/
name?: PublicIPAddressSkuName;
}
/**
* IP configuration
*/
export interface IPConfiguration extends SubResource {
/**
* The private IP address of the IP configuration.
*/
privateIPAddress?: string;
/**
* The private IP allocation method. Possible values are 'Static' and 'Dynamic'. Possible values
* include: 'Static', 'Dynamic'
*/
privateIPAllocationMethod?: IPAllocationMethod;
/**
* The reference of the subnet resource.
*/
subnet?: Subnet;
/**
* The reference of the public IP resource.
*/
publicIPAddress?: PublicIPAddress;
/**
* Gets the provisioning state of the public IP resource. Possible values are: 'Updating',
* 'Deleting', and 'Failed'.
*/
provisioningState?: string;
/**
* The name of the resource that is unique within a resource group. This name can be used to
* access the resource.
*/
name?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* Contains FQDN of the DNS record associated with the public IP address
*/
export interface PublicIPAddressDnsSettings {
/**
* Gets or sets the Domain name label.The concatenation of the domain name label and the
* regionalized DNS zone make up the fully qualified domain name associated with the public IP
* address. If a domain name label is specified, an A DNS record is created for the public IP in
* the Microsoft Azure DNS system.
*/
domainNameLabel?: string;
/**
* Gets the FQDN, Fully qualified domain name of the A DNS record associated with the public IP.
* This is the concatenation of the domainNameLabel and the regionalized DNS zone.
*/
fqdn?: string;
/**
* Gets or Sets the Reverse FQDN. A user-visible, fully qualified domain name that resolves to
* this public IP address. If the reverseFqdn is specified, then a PTR DNS record is created
* pointing from the IP address in the in-addr.arpa domain to the reverse FQDN.
*/
reverseFqdn?: string;
}
/**
* Contains the DDoS protection settings of the public IP.
*/
export interface DdosSettings {
/**
* The DDoS custom policy associated with the public IP.
*/
ddosCustomPolicy?: SubResource;
/**
* The DDoS protection policy customizability of the public IP. Only standard coverage will have
* the ability to be customized. Possible values include: 'Basic', 'Standard'
*/
protectionCoverage?: ProtectionCoverage;
}
/**
* Contains the IpTag associated with the object
*/
export interface IpTag {
/**
* Gets or sets the ipTag type: Example FirstPartyUsage.
*/
ipTagType?: string;
/**
* Gets or sets value of the IpTag associated with the public IP. Example SQL, Storage etc
*/
tag?: string;
}
/**
* Public IP address resource.
*/
export interface PublicIPAddress extends Resource {
/**
* The public IP address SKU.
*/
sku?: PublicIPAddressSku;
/**
* The public IP allocation method. Possible values are: 'Static' and 'Dynamic'. Possible values
* include: 'Static', 'Dynamic'
*/
publicIPAllocationMethod?: IPAllocationMethod;
/**
* The public IP address version. Possible values are: 'IPv4' and 'IPv6'. Possible values
* include: 'IPv4', 'IPv6'
*/
publicIPAddressVersion?: IPVersion;
/**
* The IP configuration associated with the public IP address.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly ipConfiguration?: IPConfiguration;
/**
* The FQDN of the DNS record associated with the public IP address.
*/
dnsSettings?: PublicIPAddressDnsSettings;
/**
* The DDoS protection custom policy associated with the public IP address.
*/
ddosSettings?: DdosSettings;
/**
* The list of tags associated with the public IP address.
*/
ipTags?: IpTag[];
/**
* The IP address associated with the public IP address resource.
*/
ipAddress?: string;
/**
* The Public IP Prefix this Public IP Address should be allocated from.
*/
publicIPPrefix?: SubResource;
/**
* The idle timeout of the public IP address.
*/
idleTimeoutInMinutes?: number;
/**
* The resource GUID property of the public IP resource.
*/
resourceGuid?: string;
/**
* The provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting',
* and 'Failed'.
*/
provisioningState?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
/**
* A list of availability zones denoting the IP allocated for the resource needs to come from.
*/
zones?: string[];
}
/**
* IPConfiguration in a network interface.
*/
export interface NetworkInterfaceIPConfiguration extends SubResource {
/**
* The reference to Virtual Network Taps.
*/
virtualNetworkTaps?: VirtualNetworkTap[];
/**
* The reference of ApplicationGatewayBackendAddressPool resource.
*/
applicationGatewayBackendAddressPools?: ApplicationGatewayBackendAddressPool[];
/**
* The reference of LoadBalancerBackendAddressPool resource.
*/
loadBalancerBackendAddressPools?: BackendAddressPool[];
/**
* A list of references of LoadBalancerInboundNatRules.
*/
loadBalancerInboundNatRules?: InboundNatRule[];
/**
* Private IP address of the IP configuration.
*/
privateIPAddress?: string;
/**
* Defines how a private IP address is assigned. Possible values are: 'Static' and 'Dynamic'.
* Possible values include: 'Static', 'Dynamic'
*/
privateIPAllocationMethod?: IPAllocationMethod;
/**
* Available from Api-Version 2016-03-30 onwards, it represents whether the specific
* ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. Possible values are: 'IPv4' and
* 'IPv6'. Possible values include: 'IPv4', 'IPv6'
*/
privateIPAddressVersion?: IPVersion;
/**
* Subnet bound to the IP configuration.
*/
subnet?: Subnet;
/**
* Gets whether this is a primary customer address on the network interface.
*/
primary?: boolean;
/**
* Public IP address bound to the IP configuration.
*/
publicIPAddress?: PublicIPAddress;
/**
* Application security groups in which the IP configuration is included.
*/
applicationSecurityGroups?: ApplicationSecurityGroup[];
/**
* The provisioning state of the network interface IP configuration. Possible values are:
* 'Updating', 'Deleting', and 'Failed'.
*/
provisioningState?: string;
/**
* The name of the resource that is unique within a resource group. This name can be used to
* access the resource.
*/
name?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* DNS settings of a network interface.
*/
export interface NetworkInterfaceDnsSettings {
/**
* List of DNS servers IP addresses. Use 'AzureProvidedDNS' to switch to azure provided DNS
* resolution. 'AzureProvidedDNS' value cannot be combined with other IPs, it must be the only
* value in dnsServers collection.
*/
dnsServers?: string[];
/**
* If the VM that uses this NIC is part of an Availability Set, then this list will have the
* union of all DNS servers from all NICs that are part of the Availability Set. This property is
* what is configured on each of those VMs.
*/
appliedDnsServers?: string[];
/**
* Relative DNS name for this NIC used for internal communications between VMs in the same
* virtual network.
*/
internalDnsNameLabel?: string;
/**
* Fully qualified DNS name supporting internal communications between VMs in the same virtual
* network.
*/
internalFqdn?: string;
/**
* Even if internalDnsNameLabel is not specified, a DNS entry is created for the primary NIC of
* the VM. This DNS name can be constructed by concatenating the VM name with the value of
* internalDomainNameSuffix.
*/
internalDomainNameSuffix?: string;
}
/**
* A network interface in a resource group.
*/
export interface NetworkInterface extends Resource {
/**
* The reference of a virtual machine.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly virtualMachine?: SubResource;
/**
* The reference of the NetworkSecurityGroup resource.
*/
networkSecurityGroup?: NetworkSecurityGroup;
/**
* A reference to the interface endpoint to which the network interface is linked.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly interfaceEndpoint?: InterfaceEndpoint;
/**
* A list of IPConfigurations of the network interface.
*/
ipConfigurations?: NetworkInterfaceIPConfiguration[];
/**
* A list of TapConfigurations of the network interface.
*/
tapConfigurations?: NetworkInterfaceTapConfiguration[];
/**
* The DNS settings in network interface.
*/
dnsSettings?: NetworkInterfaceDnsSettings;
/**
* The MAC address of the network interface.
*/
macAddress?: string;
/**
* Gets whether this is a primary network interface on a virtual machine.
*/
primary?: boolean;
/**
* If the network interface is accelerated networking enabled.
*/
enableAcceleratedNetworking?: boolean;
/**
* Indicates whether IP forwarding is enabled on this network interface.
*/
enableIPForwarding?: boolean;
/**
* A list of references to linked BareMetal resources
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly hostedWorkloads?: string[];
/**
* The resource GUID property of the network interface resource.
*/
resourceGuid?: string;
/**
* The provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting',
* and 'Failed'.
*/
provisioningState?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* NetworkSecurityGroup resource.
*/
export interface NetworkSecurityGroup extends Resource {
/**
* A collection of security rules of the network security group.
*/
securityRules?: SecurityRule[];
/**
* The default security rules of network security group.
*/
defaultSecurityRules?: SecurityRule[];
/**
* A collection of references to network interfaces.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly networkInterfaces?: NetworkInterface[];
/**
* A collection of references to subnets.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly subnets?: Subnet[];
/**
* The resource GUID property of the network security group resource.
*/
resourceGuid?: string;
/**
* The provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting',
* and 'Failed'.
*/
provisioningState?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* Route resource
*/
export interface Route extends SubResource {
/**
* The destination CIDR to which the route applies.
*/
addressPrefix?: string;
/**
* The type of Azure hop the packet should be sent to. Possible values are:
* 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', and 'None'. Possible
* values include: 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', 'None'
*/
nextHopType: RouteNextHopType;
/**
* The IP address packets should be forwarded to. Next hop values are only allowed in routes
* where the next hop type is VirtualAppliance.
*/
nextHopIpAddress?: string;
/**
* The provisioning state of the resource. Possible values are: 'Updating', 'Deleting', and
* 'Failed'.
*/
provisioningState?: string;
/**
* The name of the resource that is unique within a resource group. This name can be used to
* access the resource.
*/
name?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* Route table resource.
*/
export interface RouteTable extends Resource {
/**
* Collection of routes contained within a route table.
*/
routes?: Route[];
/**
* A collection of references to subnets.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly subnets?: Subnet[];
/**
* Gets or sets whether to disable the routes learned by BGP on that route table. True means
* disable.
*/
disableBgpRoutePropagation?: boolean;
/**
* The provisioning state of the resource. Possible values are: 'Updating', 'Deleting', and
* 'Failed'.
*/
provisioningState?: string;
/**
* Gets a unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* The service endpoint properties.
*/
export interface ServiceEndpointPropertiesFormat {
/**
* The type of the endpoint service.
*/
service?: string;
/**
* A list of locations.
*/
locations?: string[];
/**
* The provisioning state of the resource.
*/
provisioningState?: string;
}
/**
* Service Endpoint policy definitions.
*/
export interface ServiceEndpointPolicyDefinition extends SubResource {
/**
* A description for this rule. Restricted to 140 chars.
*/
description?: string;
/**
* service endpoint name.
*/
service?: string;
/**
* A list of service resources.
*/
serviceResources?: string[];
/**
* The provisioning state of the service end point policy definition. Possible values are:
* 'Updating', 'Deleting', and 'Failed'.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: string;
/**
* The name of the resource that is unique within a resource group. This name can be used to
* access the resource.
*/
name?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* Service End point policy resource.
*/
export interface ServiceEndpointPolicy extends Resource {
/**
* A collection of service endpoint policy definitions of the service endpoint policy.
*/
serviceEndpointPolicyDefinitions?: ServiceEndpointPolicyDefinition[];
/**
* A collection of references to subnets.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly subnets?: Subnet[];
/**
* The resource GUID property of the service endpoint policy resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly resourceGuid?: string;
/**
* The provisioning state of the service endpoint policy. Possible values are: 'Updating',
* 'Deleting', and 'Failed'.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* IP configuration profile child resource.
*/
export interface IPConfigurationProfile extends SubResource {
/**
* The reference of the subnet resource to create a container network interface ip configuration.
*/
subnet?: Subnet;
/**
* The provisioning state of the resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: string;
/**
* The name of the resource. This name can be used to access the resource.
*/
name?: string;
/**
* Sub Resource type.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* ResourceNavigationLink resource.
*/
export interface ResourceNavigationLink extends SubResource {
/**
* Resource type of the linked resource.
*/
linkedResourceType?: string;
/**
* Link to the external resource
*/
link?: string;
/**
* Provisioning state of the ResourceNavigationLink resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: string;
/**
* Name of the resource that is unique within a resource group. This name can be used to access
* the resource.
*/
name?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly etag?: string;
}
/**
* ServiceAssociationLink resource.
*/
export interface ServiceAssociationLink extends SubResource {
/**
* Resource type of the linked resource.
*/
linkedResourceType?: string;
/**
* Link to the external resource.
*/
link?: string;
/**
* Provisioning state of the ServiceAssociationLink resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: string;
/**
* Name of the resource that is unique within a resource group. This name can be used to access
* the resource.
*/
name?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly etag?: string;
}
/**
* Details the service to which the subnet is delegated.
*/
export interface Delegation extends SubResource {
/**
* The name of the service to whom the subnet should be delegated (e.g. Microsoft.Sql/servers)
*/
serviceName?: string;
/**
* Describes the actions permitted to the service upon delegation
*/
actions?: string[];
/**
* The provisioning state of the resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: string;
/**
* The name of the resource that is unique within a subnet. This name can be used to access the
* resource.
*/
name?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* Subnet in a virtual network resource.
*/
export interface Subnet extends SubResource {
/**
* The address prefix for the subnet.
*/
addressPrefix?: string;
/**
* List of address prefixes for the subnet.
*/
addressPrefixes?: string[];
/**
* The reference of the NetworkSecurityGroup resource.
*/
networkSecurityGroup?: NetworkSecurityGroup;
/**
* The reference of the RouteTable resource.
*/
routeTable?: RouteTable;
/**
* An array of service endpoints.
*/
serviceEndpoints?: ServiceEndpointPropertiesFormat[];
/**
* An array of service endpoint policies.
*/
serviceEndpointPolicies?: ServiceEndpointPolicy[];
/**
* An array of references to interface endpoints
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly interfaceEndpoints?: InterfaceEndpoint[];
/**
* Gets an array of references to the network interface IP configurations using subnet.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly ipConfigurations?: IPConfiguration[];
/**
* Array of IP configuration profiles which reference this subnet.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly ipConfigurationProfiles?: IPConfigurationProfile[];
/**
* Gets an array of references to the external resources using subnet.
*/
resourceNavigationLinks?: ResourceNavigationLink[];
/**
* Gets an array of references to services injecting into this subnet.
*/
serviceAssociationLinks?: ServiceAssociationLink[];
/**
* Gets an array of references to the delegations on the subnet.
*/
delegations?: Delegation[];
/**
* A read-only string identifying the intention of use for this subnet based on delegations and
* other user-defined properties.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly purpose?: string;
/**
* The provisioning state of the resource.
*/
provisioningState?: string;
/**
* The name of the resource that is unique within a resource group. This name can be used to
* access the resource.
*/
name?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* A load balancing rule for a load balancer.
*/
export interface LoadBalancingRule extends SubResource {
/**
* A reference to frontend IP addresses.
*/
frontendIPConfiguration?: SubResource;
/**
* A reference to a pool of DIPs. Inbound traffic is randomly load balanced across IPs in the
* backend IPs.
*/
backendAddressPool?: SubResource;
/**
* The reference of the load balancer probe used by the load balancing rule.
*/
probe?: SubResource;
/**
* Possible values include: 'Udp', 'Tcp', 'All'
*/
protocol: TransportProtocol;
/**
* The load distribution policy for this rule. Possible values are 'Default', 'SourceIP', and
* 'SourceIPProtocol'. Possible values include: 'Default', 'SourceIP', 'SourceIPProtocol'
*/
loadDistribution?: LoadDistribution;
/**
* The port for the external endpoint. Port numbers for each rule must be unique within the Load
* Balancer. Acceptable values are between 0 and 65534. Note that value 0 enables "Any Port"
*/
frontendPort: number;
/**
* The port used for internal connections on the endpoint. Acceptable values are between 0 and
* 65535. Note that value 0 enables "Any Port"
*/
backendPort?: number;
/**
* The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The
* default value is 4 minutes. This element is only used when the protocol is set to TCP.
*/
idleTimeoutInMinutes?: number;
/**
* Configures a virtual machine's endpoint for the floating IP capability required to configure a
* SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn
* Availability Groups in SQL server. This setting can't be changed after you create the
* endpoint.
*/
enableFloatingIP?: boolean;
/**
* Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected connection termination.
* This element is only used when the protocol is set to TCP.
*/
enableTcpReset?: boolean;
/**
* Configures SNAT for the VMs in the backend pool to use the publicIP address specified in the
* frontend of the load balancing rule.
*/
disableOutboundSnat?: boolean;
/**
* Gets the provisioning state of the PublicIP resource. Possible values are: 'Updating',
* 'Deleting', and 'Failed'.
*/
provisioningState?: string;
/**
* The name of the resource that is unique within a resource group. This name can be used to
* access the resource.
*/
name?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* A load balancer probe.
*/
export interface Probe extends SubResource {
/**
* The load balancer rules that use this probe.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly loadBalancingRules?: SubResource[];
/**
* The protocol of the end point. Possible values are: 'Http', 'Tcp', or 'Https'. If 'Tcp' is
* specified, a received ACK is required for the probe to be successful. If 'Http' or 'Https' is
* specified, a 200 OK response from the specifies URI is required for the probe to be
* successful. Possible values include: 'Http', 'Tcp', 'Https'
*/
protocol: ProbeProtocol;
/**
* The port for communicating the probe. Possible values range from 1 to 65535, inclusive.
*/
port: number;
/**
* The interval, in seconds, for how frequently to probe the endpoint for health status.
* Typically, the interval is slightly less than half the allocated timeout period (in seconds)
* which allows two full probes before taking the instance out of rotation. The default value is
* 15, the minimum value is 5.
*/
intervalInSeconds?: number;
/**
* The number of probes where if no response, will result in stopping further traffic from being
* delivered to the endpoint. This values allows endpoints to be taken out of rotation faster or
* slower than the typical times used in Azure.
*/
numberOfProbes?: number;
/**
* The URI used for requesting health status from the VM. Path is required if a protocol is set
* to http. Otherwise, it is not allowed. There is no default value.
*/
requestPath?: string;
/**
* Gets the provisioning state of the public IP resource. Possible values are: 'Updating',
* 'Deleting', and 'Failed'.
*/
provisioningState?: string;
/**
* Gets name of the resource that is unique within a resource group. This name can be used to
* access the resource.
*/
name?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* Inbound NAT pool of the load balancer.
*/
export interface InboundNatPool extends SubResource {
/**
* A reference to frontend IP addresses.
*/
frontendIPConfiguration?: SubResource;
/**
* Possible values include: 'Udp', 'Tcp', 'All'
*/
protocol: TransportProtocol;
/**
* The first port number in the range of external ports that will be used to provide Inbound Nat
* to NICs associated with a load balancer. Acceptable values range between 1 and 65534.
*/
frontendPortRangeStart: number;
/**
* The last port number in the range of external ports that will be used to provide Inbound Nat
* to NICs associated with a load balancer. Acceptable values range between 1 and 65535.
*/
frontendPortRangeEnd: number;
/**
* The port used for internal connections on the endpoint. Acceptable values are between 1 and
* 65535.
*/
backendPort: number;
/**
* The timeout for the TCP idle connection. The value can be set between 4 and 30 minutes. The
* default value is 4 minutes. This element is only used when the protocol is set to TCP.
*/
idleTimeoutInMinutes?: number;
/**
* Configures a virtual machine's endpoint for the floating IP capability required to configure a
* SQL AlwaysOn Availability Group. This setting is required when using the SQL AlwaysOn
* Availability Groups in SQL server. This setting can't be changed after you create the
* endpoint.
*/
enableFloatingIP?: boolean;
/**
* Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected connection termination.
* This element is only used when the protocol is set to TCP.
*/
enableTcpReset?: boolean;
/**
* Gets the provisioning state of the PublicIP resource. Possible values are: 'Updating',
* 'Deleting', and 'Failed'.
*/
provisioningState?: string;
/**
* The name of the resource that is unique within a resource group. This name can be used to
* access the resource.
*/
name?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* Outbound rule of the load balancer.
*/
export interface OutboundRule extends SubResource {
/**
* The number of outbound ports to be used for NAT.
*/
allocatedOutboundPorts?: number;
/**
* The Frontend IP addresses of the load balancer.
*/
frontendIPConfigurations: SubResource[];
/**
* A reference to a pool of DIPs. Outbound traffic is randomly load balanced across IPs in the
* backend IPs.
*/
backendAddressPool: SubResource;
/**
* Gets the provisioning state of the PublicIP resource. Possible values are: 'Updating',
* 'Deleting', and 'Failed'.
*/
provisioningState?: string;
/**
* Protocol - TCP, UDP or All. Possible values include: 'Tcp', 'Udp', 'All'
*/
protocol: Protocol;
/**
* Receive bidirectional TCP Reset on TCP flow idle timeout or unexpected connection termination.
* This element is only used when the protocol is set to TCP.
*/
enableTcpReset?: boolean;
/**
* The timeout for the TCP idle connection
*/
idleTimeoutInMinutes?: number;
/**
* The name of the resource that is unique within a resource group. This name can be used to
* access the resource.
*/
name?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* LoadBalancer resource
*/
export interface LoadBalancer extends Resource {
/**
* The load balancer SKU.
*/
sku?: LoadBalancerSku;
/**
* Object representing the frontend IPs to be used for the load balancer
*/
frontendIPConfigurations?: FrontendIPConfiguration[];
/**
* Collection of backend address pools used by a load balancer
*/
backendAddressPools?: BackendAddressPool[];
/**
* Object collection representing the load balancing rules Gets the provisioning
*/
loadBalancingRules?: LoadBalancingRule[];
/**
* Collection of probe objects used in the load balancer
*/
probes?: Probe[];
/**
* Collection of inbound NAT Rules used by a load balancer. Defining inbound NAT rules on your
* load balancer is mutually exclusive with defining an inbound NAT pool. Inbound NAT pools are
* referenced from virtual machine scale sets. NICs that are associated with individual virtual
* machines cannot reference an Inbound NAT pool. They have to reference individual inbound NAT
* rules.
*/
inboundNatRules?: InboundNatRule[];
/**
* Defines an external port range for inbound NAT to a single backend port on NICs associated
* with a load balancer. Inbound NAT rules are created automatically for each NIC associated with
* the Load Balancer using an external port from this range. Defining an Inbound NAT pool on your
* Load Balancer is mutually exclusive with defining inbound Nat rules. Inbound NAT pools are
* referenced from virtual machine scale sets. NICs that are associated with individual virtual
* machines cannot reference an inbound NAT pool. They have to reference individual inbound NAT
* rules.
*/
inboundNatPools?: InboundNatPool[];
/**
* The outbound rules.
*/
outboundRules?: OutboundRule[];
/**
* The resource GUID property of the load balancer resource.
*/
resourceGuid?: string;
/**
* Gets the provisioning state of the PublicIP resource. Possible values are: 'Updating',
* 'Deleting', and 'Failed'.
*/
provisioningState?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* An interface representing ErrorDetails.
*/
export interface ErrorDetails {
code?: string;
target?: string;
message?: string;
}
/**
* An interface representing ErrorModel.
*/
export interface ErrorModel {
code?: string;
message?: string;
target?: string;
details?: ErrorDetails[];
innerError?: string;
}
/**
* The response body contains the status of the specified asynchronous operation, indicating
* whether it has succeeded, is in progress, or has failed. Note that this status is distinct from
* the HTTP status code returned for the Get Operation Status operation itself. If the asynchronous
* operation succeeded, the response body includes the HTTP status code for the successful request.
* If the asynchronous operation failed, the response body includes the HTTP status code for the
* failed request and error information regarding the failure.
*/
export interface AzureAsyncOperationResult {
/**
* Status of the Azure async operation. Possible values are: 'InProgress', 'Succeeded', and
* 'Failed'. Possible values include: 'InProgress', 'Succeeded', 'Failed'
*/
status?: NetworkOperationStatus;
error?: ErrorModel;
}
/**
* An interface representing ManagedServiceIdentityUserAssignedIdentitiesValue.
*/
export interface ManagedServiceIdentityUserAssignedIdentitiesValue {
/**
* The principal id of user assigned identity.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly principalId?: string;
/**
* The client id of user assigned identity.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly clientId?: string;
}
/**
* Identity for the resource.
*/
export interface ManagedServiceIdentity {
/**
* The principal id of the system assigned identity. This property will only be provided for a
* system assigned identity.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly principalId?: string;
/**
* The tenant id of the system assigned identity. This property will only be provided for a
* system assigned identity.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly tenantId?: string;
/**
* The type of identity used for the resource. The type 'SystemAssigned, UserAssigned' includes
* both an implicitly created identity and a set of user assigned identities. The type 'None'
* will remove any identities from the virtual machine. Possible values include:
* 'SystemAssigned', 'UserAssigned', 'SystemAssigned, UserAssigned', 'None'
*/
type?: ResourceIdentityType;
/**
* The list of user identities associated with resource. The user identity dictionary key
* references will be ARM resource ids in the form:
* '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.
*/
userAssignedIdentities?: { [propertyName: string]: ManagedServiceIdentityUserAssignedIdentitiesValue };
}
/**
* The effective network security group association.
*/
export interface EffectiveNetworkSecurityGroupAssociation {
/**
* The ID of the subnet if assigned.
*/
subnet?: SubResource;
/**
* The ID of the network interface if assigned.
*/
networkInterface?: SubResource;
}
/**
* Effective network security rules.
*/
export interface EffectiveNetworkSecurityRule {
/**
* The name of the security rule specified by the user (if created by the user).
*/
name?: string;
/**
* The network protocol this rule applies to. Possible values are: 'Tcp', 'Udp', and 'All'.
* Possible values include: 'Tcp', 'Udp', 'All'
*/
protocol?: EffectiveSecurityRuleProtocol;
/**
* The source port or range.
*/
sourcePortRange?: string;
/**
* The destination port or range.
*/
destinationPortRange?: string;
/**
* The source port ranges. Expected values include a single integer between 0 and 65535, a range
* using '-' as separator (e.g. 100-400), or an asterisk (*)
*/
sourcePortRanges?: string[];
/**
* The destination port ranges. Expected values include a single integer between 0 and 65535, a
* range using '-' as separator (e.g. 100-400), or an asterisk (*)
*/
destinationPortRanges?: string[];
/**
* The source address prefix.
*/
sourceAddressPrefix?: string;
/**
* The destination address prefix.
*/
destinationAddressPrefix?: string;
/**
* The source address prefixes. Expected values include CIDR IP ranges, Default Tags
* (VirtualNetwork, AzureLoadBalancer, Internet), System Tags, and the asterisk (*).
*/
sourceAddressPrefixes?: string[];
/**
* The destination address prefixes. Expected values include CIDR IP ranges, Default Tags
* (VirtualNetwork, AzureLoadBalancer, Internet), System Tags, and the asterisk (*).
*/
destinationAddressPrefixes?: string[];
/**
* The expanded source address prefix.
*/
expandedSourceAddressPrefix?: string[];
/**
* Expanded destination address prefix.
*/
expandedDestinationAddressPrefix?: string[];
/**
* Whether network traffic is allowed or denied. Possible values are: 'Allow' and 'Deny'.
* Possible values include: 'Allow', 'Deny'
*/
access?: SecurityRuleAccess;
/**
* The priority of the rule.
*/
priority?: number;
/**
* The direction of the rule. Possible values are: 'Inbound and Outbound'. Possible values
* include: 'Inbound', 'Outbound'
*/
direction?: SecurityRuleDirection;
}
/**
* Effective network security group.
*/
export interface EffectiveNetworkSecurityGroup {
/**
* The ID of network security group that is applied.
*/
networkSecurityGroup?: SubResource;
/**
* Associated resources.
*/
association?: EffectiveNetworkSecurityGroupAssociation;
/**
* A collection of effective security rules.
*/
effectiveSecurityRules?: EffectiveNetworkSecurityRule[];
/**
* Mapping of tags to list of IP Addresses included within the tag.
*/
tagMap?: { [propertyName: string]: string[] };
}
/**
* Response for list effective network security groups API service call.
*/
export interface EffectiveNetworkSecurityGroupListResult {
/**
* A list of effective network security groups.
*/
value?: EffectiveNetworkSecurityGroup[];
/**
* The URL to get the next set of results.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nextLink?: string;
}
/**
* Effective Route
*/
export interface EffectiveRoute {
/**
* The name of the user defined route. This is optional.
*/
name?: string;
/**
* Who created the route. Possible values are: 'Unknown', 'User', 'VirtualNetworkGateway', and
* 'Default'. Possible values include: 'Unknown', 'User', 'VirtualNetworkGateway', 'Default'
*/
source?: EffectiveRouteSource;
/**
* The value of effective route. Possible values are: 'Active' and 'Invalid'. Possible values
* include: 'Active', 'Invalid'
*/
state?: EffectiveRouteState;
/**
* The address prefixes of the effective routes in CIDR notation.
*/
addressPrefix?: string[];
/**
* The IP address of the next hop of the effective route.
*/
nextHopIpAddress?: string[];
/**
* The type of Azure hop the packet should be sent to. Possible values are:
* 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', and 'None'. Possible
* values include: 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance', 'None'
*/
nextHopType?: RouteNextHopType;
}
/**
* Response for list effective route API service call.
*/
export interface EffectiveRouteListResult {
/**
* A list of effective routes.
*/
value?: EffectiveRoute[];
/**
* The URL to get the next set of results.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nextLink?: string;
}
/**
* Display metadata associated with the operation.
*/
export interface OperationDisplay {
/**
* Service provider: Microsoft Network.
*/
provider?: string;
/**
* Resource on which the operation is performed.
*/
resource?: string;
/**
* Type of the operation: get, read, delete, etc.
*/
operation?: string;
/**
* Description of the operation.
*/
description?: string;
}
/**
* Availability of the metric.
*/
export interface Availability {
/**
* The time grain of the availability.
*/
timeGrain?: string;
/**
* The retention of the availability.
*/
retention?: string;
/**
* Duration of the availability blob.
*/
blobDuration?: string;
}
/**
* Dimension of the metric.
*/
export interface Dimension {
/**
* The name of the dimension.
*/
name?: string;
/**
* The display name of the dimension.
*/
displayName?: string;
/**
* The internal name of the dimension.
*/
internalName?: string;
}
/**
* Description of metrics specification.
*/
export interface MetricSpecification {
/**
* The name of the metric.
*/
name?: string;
/**
* The display name of the metric.
*/
displayName?: string;
/**
* The description of the metric.
*/
displayDescription?: string;
/**
* Units the metric to be displayed in.
*/
unit?: string;
/**
* The aggregation type.
*/
aggregationType?: string;
/**
* List of availability.
*/
availabilities?: Availability[];
/**
* Whether regional MDM account enabled.
*/
enableRegionalMdmAccount?: boolean;
/**
* Whether gaps would be filled with zeros.
*/
fillGapWithZero?: boolean;
/**
* Pattern for the filter of the metric.
*/
metricFilterPattern?: string;
/**
* List of dimensions.
*/
dimensions?: Dimension[];
/**
* Whether the metric is internal.
*/
isInternal?: boolean;
/**
* The source MDM account.
*/
sourceMdmAccount?: string;
/**
* The source MDM namespace.
*/
sourceMdmNamespace?: string;
/**
* The resource Id dimension name override.
*/
resourceIdDimensionNameOverride?: string;
}
/**
* Description of logging specification.
*/
export interface LogSpecification {
/**
* The name of the specification.
*/
name?: string;
/**
* The display name of the specification.
*/
displayName?: string;
/**
* Duration of the blob.
*/
blobDuration?: string;
}
/**
* Specification of the service.
*/
export interface OperationPropertiesFormatServiceSpecification {
/**
* Operation service specification.
*/
metricSpecifications?: MetricSpecification[];
/**
* Operation log specification.
*/
logSpecifications?: LogSpecification[];
}
/**
* Network REST API operation definition.
*/
export interface Operation {
/**
* Operation name: {provider}/{resource}/{operation}
*/
name?: string;
/**
* Display metadata associated with the operation.
*/
display?: OperationDisplay;
/**
* Origin of the operation.
*/
origin?: string;
/**
* Specification of the service.
*/
serviceSpecification?: OperationPropertiesFormatServiceSpecification;
}
/**
* Peerings in a virtual network resource.
*/
export interface VirtualNetworkPeering extends SubResource {
/**
* Whether the VMs in the linked virtual network space would be able to access all the VMs in
* local Virtual network space.
*/
allowVirtualNetworkAccess?: boolean;
/**
* Whether the forwarded traffic from the VMs in the remote virtual network will be
* allowed/disallowed.
*/
allowForwardedTraffic?: boolean;
/**
* If gateway links can be used in remote virtual networking to link to this virtual network.
*/
allowGatewayTransit?: boolean;
/**
* If remote gateways can be used on this virtual network. If the flag is set to true, and
* allowGatewayTransit on remote peering is also true, virtual network will use gateways of
* remote virtual network for transit. Only one peering can have this flag set to true. This flag
* cannot be set if virtual network already has a gateway.
*/
useRemoteGateways?: boolean;
/**
* The reference of the remote virtual network. The remote virtual network can be in the same or
* different region (preview). See here to register for the preview and learn more
* (https://docs.microsoft.com/en-us/azure/virtual-network/virtual-network-create-peering).
*/
remoteVirtualNetwork?: SubResource;
/**
* The reference of the remote virtual network address space.
*/
remoteAddressSpace?: AddressSpace;
/**
* The status of the virtual network peering. Possible values are 'Initiated', 'Connected', and
* 'Disconnected'. Possible values include: 'Initiated', 'Connected', 'Disconnected'
*/
peeringState?: VirtualNetworkPeeringState;
/**
* The provisioning state of the resource.
*/
provisioningState?: string;
/**
* The name of the resource that is unique within a resource group. This name can be used to
* access the resource.
*/
name?: string;
/**
* A unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* DhcpOptions contains an array of DNS servers available to VMs deployed in the virtual network.
* Standard DHCP option for a subnet overrides VNET DHCP options.
*/
export interface DhcpOptions {
/**
* The list of DNS servers IP addresses.
*/
dnsServers?: string[];
}
/**
* Virtual Network resource.
*/
export interface VirtualNetwork extends Resource {
/**
* The AddressSpace that contains an array of IP address ranges that can be used by subnets.
*/
addressSpace?: AddressSpace;
/**
* The dhcpOptions that contains an array of DNS servers available to VMs deployed in the virtual
* network.
*/
dhcpOptions?: DhcpOptions;
/**
* A list of subnets in a Virtual Network.
*/
subnets?: Subnet[];
/**
* A list of peerings in a Virtual Network.
*/
virtualNetworkPeerings?: VirtualNetworkPeering[];
/**
* The resourceGuid property of the Virtual Network resource.
*/
resourceGuid?: string;
/**
* The provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting',
* and 'Failed'.
*/
provisioningState?: string;
/**
* Indicates if DDoS protection is enabled for all the protected resources in the virtual
* network. It requires a DDoS protection plan associated with the resource. Default value:
* false.
*/
enableDdosProtection?: boolean;
/**
* Indicates if VM protection is enabled for all the subnets in the virtual network. Default
* value: false.
*/
enableVmProtection?: boolean;
/**
* The DDoS protection plan associated with the virtual network.
*/
ddosProtectionPlan?: SubResource;
/**
* Gets a unique read-only string that changes whenever the resource is updated.
*/
etag?: string;
}
/**
* Response for CheckIPAddressAvailability API service call
*/
export interface IPAddressAvailabilityResult {
/**
* Private IP address availability.
*/
available?: boolean;
/**
* Contains other available private IP addresses if the asked for address is taken.
*/
availableIPAddresses?: string[];
}
/**
* Usage strings container.
*/
export interface VirtualNetworkUsageName {
/**
* Localized subnet size and usage string.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly localizedValue?: string;
/**
* Subnet size and usage string.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly value?: string;
}
/**
* Usage details for subnet.
*/
export interface VirtualNetworkUsage {
/**
* Indicates number of IPs used from the Subnet.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly currentValue?: number;
/**
* Subnet identifier.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* Indicates the size of the subnet.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly limit?: number;
/**
* The name containing common and localized value for usage.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: VirtualNetworkUsageName;
/**
* Usage units. Returns 'Count'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly unit?: string;
}
/**
* Optional Parameters.
*/
export interface VirtualNetworkGatewaysResetOptionalParams extends msRest.RequestOptionsBase {
/**
* Virtual network gateway vip address supplied to the begin reset of the active-active feature
* enabled gateway.
*/
gatewayVip?: string;
}
/**
* Optional Parameters.
*/
export interface VirtualNetworkGatewaysGetBgpPeerStatusOptionalParams extends msRest.RequestOptionsBase {
/**
* The IP address of the peer to retrieve the status of.
*/
peer?: string;
}
/**
* Optional Parameters.
*/
export interface VirtualNetworkGatewaysBeginResetOptionalParams extends msRest.RequestOptionsBase {
/**
* Virtual network gateway vip address supplied to the begin reset of the active-active feature
* enabled gateway.
*/
gatewayVip?: string;
}
/**
* Optional Parameters.
*/
export interface VirtualNetworkGatewaysBeginGetBgpPeerStatusOptionalParams extends msRest.RequestOptionsBase {
/**
* The IP address of the peer to retrieve the status of.
*/
peer?: string;
}
/**
* Optional Parameters.
*/
export interface LoadBalancersGetOptionalParams extends msRest.RequestOptionsBase {
/**
* Expands referenced resources.
*/
expand?: string;
}
/**
* Optional Parameters.
*/
export interface InboundNatRulesGetOptionalParams extends msRest.RequestOptionsBase {
/**
* Expands referenced resources.
*/
expand?: string;
}
/**
* Optional Parameters.
*/
export interface NetworkInterfacesGetOptionalParams extends msRest.RequestOptionsBase {
/**
* Expands referenced resources.
*/
expand?: string;
}
/**
* Optional Parameters.
*/
export interface NetworkSecurityGroupsGetOptionalParams extends msRest.RequestOptionsBase {
/**
* Expands referenced resources.
*/
expand?: string;
}
/**
* Optional Parameters.
*/
export interface PublicIPAddressesGetOptionalParams extends msRest.RequestOptionsBase {
/**
* Expands referenced resources.
*/
expand?: string;
}
/**
* Optional Parameters.
*/
export interface RouteTablesGetOptionalParams extends msRest.RequestOptionsBase {
/**
* Expands referenced resources.
*/
expand?: string;
}
/**
* Optional Parameters.
*/
export interface VirtualNetworksGetOptionalParams extends msRest.RequestOptionsBase {
/**
* Expands referenced resources.
*/
expand?: string;
}
/**
* Optional Parameters.
*/
export interface SubnetsGetOptionalParams extends msRest.RequestOptionsBase {
/**
* Expands referenced resources.
*/
expand?: string;
}
/**
* An interface representing NetworkManagementClientOptions.
*/
export interface NetworkManagementClientOptions extends AzureServiceClientOptions {
baseUri?: string;
}
/**
* @interface
* Response for the ListVirtualNetworkGateways API service call.
* @extends Array<VirtualNetworkGateway>
*/
export interface VirtualNetworkGatewayListResult extends Array<VirtualNetworkGateway> {
/**
* The URL to get the next set of results.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nextLink?: string;
}
/**
* @interface
* Response for the VirtualNetworkGatewayListConnections API service call
* @extends Array<VirtualNetworkGatewayConnectionListEntity>
*/
export interface VirtualNetworkGatewayListConnectionsResult extends Array<VirtualNetworkGatewayConnectionListEntity> {
/**
* The URL to get the next set of results.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nextLink?: string;
}
/**
* @interface
* Response for the ListVirtualNetworkGatewayConnections API service call
* @extends Array<VirtualNetworkGatewayConnection>
*/
export interface VirtualNetworkGatewayConnectionListResult extends Array<VirtualNetworkGatewayConnection> {
/**
* The URL to get the next set of results.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nextLink?: string;
}
/**
* @interface
* Response for ListLocalNetworkGateways API service call.
* @extends Array<LocalNetworkGateway>
*/
export interface LocalNetworkGatewayListResult extends Array<LocalNetworkGateway> {
/**
* The URL to get the next set of results.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nextLink?: string;
}
/**
* @interface
* Response for ListLoadBalancers API service call.
* @extends Array<LoadBalancer>
*/
export interface LoadBalancerListResult extends Array<LoadBalancer> {
/**
* The URL to get the next set of results.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nextLink?: string;
}
/**
* @interface
* Response for ListBackendAddressPool API service call.
* @extends Array<BackendAddressPool>
*/
export interface LoadBalancerBackendAddressPoolListResult extends Array<BackendAddressPool> {
/**
* The URL to get the next set of results.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nextLink?: string;
}
/**
* @interface
* Response for ListFrontendIPConfiguration API service call.
* @extends Array<FrontendIPConfiguration>
*/
export interface LoadBalancerFrontendIPConfigurationListResult extends Array<FrontendIPConfiguration> {
/**
* The URL to get the next set of results.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nextLink?: string;
}
/**
* @interface
* Response for ListInboundNatRule API service call.
* @extends Array<InboundNatRule>
*/
export interface InboundNatRuleListResult extends Array<InboundNatRule> {
/**
* The URL to get the next set of results.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nextLink?: string;
}
/**
* @interface
* Response for ListLoadBalancingRule API service call.
* @extends Array<LoadBalancingRule>
*/
export interface LoadBalancerLoadBalancingRuleListResult extends Array<LoadBalancingRule> {
/**
* The URL to get the next set of results.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nextLink?: string;
}
/**
* @interface
* Response for ListOutboundRule API service call.
* @extends Array<OutboundRule>
*/
export interface LoadBalancerOutboundRuleListResult extends Array<OutboundRule> {
/**
* The URL to get the next set of results.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nextLink?: string;
}
/**
* @interface
* Response for the ListNetworkInterface API service call.
* @extends Array<NetworkInterface>
*/
export interface NetworkInterfaceListResult extends Array<NetworkInterface> {
/**
* The URL to get the next set of results.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nextLink?: string;
}
/**
* @interface
* Response for ListProbe API service call.
* @extends Array<Probe>
*/
export interface LoadBalancerProbeListResult extends Array<Probe> {
/**
* The URL to get the next set of results.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nextLink?: string;
}
/**
* @interface
* Response for list ip configurations API service call.
* @extends Array<NetworkInterfaceIPConfiguration>
*/
export interface NetworkInterfaceIPConfigurationListResult extends Array<NetworkInterfaceIPConfiguration> {
/**
* The URL to get the next set of results.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nextLink?: string;
}
/**
* @interface
* Response for list ip configurations API service call.
* @extends Array<LoadBalancer>
*/
export interface NetworkInterfaceLoadBalancerListResult extends Array<LoadBalancer> {
/**
* The URL to get the next set of results.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nextLink?: string;
}
/**
* @interface
* Response for list tap configurations API service call.
* @extends Array<NetworkInterfaceTapConfiguration>
*/
export interface NetworkInterfaceTapConfigurationListResult extends Array<NetworkInterfaceTapConfiguration> {
/**
* The URL to get the next set of results.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nextLink?: string;
}
/**
* @interface
* Response for ListNetworkSecurityGroups API service call.
* @extends Array<NetworkSecurityGroup>
*/
export interface NetworkSecurityGroupListResult extends Array<NetworkSecurityGroup> {
/**
* The URL to get the next set of results.
*/
nextLink?: string;
}
/**
* @interface
* Response for ListSecurityRule API service call. Retrieves all security rules that belongs to a
* network security group.
* @extends Array<SecurityRule>
*/
export interface SecurityRuleListResult extends Array<SecurityRule> {
/**
* The URL to get the next set of results.
*/
nextLink?: string;
}
/**
* @interface
* Result of the request to list Network operations. It contains a list of operations and a URL
* link to get the next set of results.
* @extends Array<Operation>
*/
export interface OperationListResult extends Array<Operation> {
/**
* URL to get the next set of operation list results if there are any.
*/
nextLink?: string;
}
/**
* @interface
* Response for ListPublicIpAddresses API service call.
* @extends Array<PublicIPAddress>
*/
export interface PublicIPAddressListResult extends Array<PublicIPAddress> {
/**
* The URL to get the next set of results.
*/
nextLink?: string;
}
/**
* @interface
* Response for the ListRouteTable API service call.
* @extends Array<RouteTable>
*/
export interface RouteTableListResult extends Array<RouteTable> {
/**
* The URL to get the next set of results.
*/
nextLink?: string;
}
/**
* @interface
* Response for the ListRoute API service call
* @extends Array<Route>
*/
export interface RouteListResult extends Array<Route> {
/**
* The URL to get the next set of results.
*/
nextLink?: string;
}
/**
* @interface
* Response for the ListVirtualNetworks API service call.
* @extends Array<VirtualNetwork>
*/
export interface VirtualNetworkListResult extends Array<VirtualNetwork> {
/**
* The URL to get the next set of results.
*/
nextLink?: string;
}
/**
* @interface
* Response for the virtual networks GetUsage API service call.
* @extends Array<VirtualNetworkUsage>
*/
export interface VirtualNetworkListUsageResult extends Array<VirtualNetworkUsage> {
/**
* The URL to get the next set of results.
*/
nextLink?: string;
}
/**
* @interface
* Response for ListSubnets API service callRetrieves all subnet that belongs to a virtual network
* @extends Array<Subnet>
*/
export interface SubnetListResult extends Array<Subnet> {
/**
* The URL to get the next set of results.
*/
nextLink?: string;
}
/**
* @interface
* Response for ListSubnets API service call. Retrieves all subnets that belong to a virtual
* network.
* @extends Array<VirtualNetworkPeering>
*/
export interface VirtualNetworkPeeringListResult extends Array<VirtualNetworkPeering> {
/**
* The URL to get the next set of results.
*/
nextLink?: string;
}
/**
* Defines values for IPAllocationMethod.
* Possible values include: 'Static', 'Dynamic'
* @readonly
* @enum {string}
*/
export type IPAllocationMethod = 'Static' | 'Dynamic';
/**
* Defines values for VirtualNetworkGatewayType.
* Possible values include: 'Vpn', 'ExpressRoute'
* @readonly
* @enum {string}
*/
export type VirtualNetworkGatewayType = 'Vpn' | 'ExpressRoute';
/**
* Defines values for VpnType.
* Possible values include: 'PolicyBased', 'RouteBased'
* @readonly
* @enum {string}
*/
export type VpnType = 'PolicyBased' | 'RouteBased';
/**
* Defines values for VirtualNetworkGatewaySkuName.
* Possible values include: 'Basic', 'HighPerformance', 'Standard', 'UltraPerformance', 'VpnGw1',
* 'VpnGw2', 'VpnGw3', 'VpnGw1AZ', 'VpnGw2AZ', 'VpnGw3AZ', 'ErGw1AZ', 'ErGw2AZ', 'ErGw3AZ'
* @readonly
* @enum {string}
*/
export type VirtualNetworkGatewaySkuName = 'Basic' | 'HighPerformance' | 'Standard' | 'UltraPerformance' | 'VpnGw1' | 'VpnGw2' | 'VpnGw3' | 'VpnGw1AZ' | 'VpnGw2AZ' | 'VpnGw3AZ' | 'ErGw1AZ' | 'ErGw2AZ' | 'ErGw3AZ';
/**
* Defines values for VirtualNetworkGatewaySkuTier.
* Possible values include: 'Basic', 'HighPerformance', 'Standard', 'UltraPerformance', 'VpnGw1',
* 'VpnGw2', 'VpnGw3', 'VpnGw1AZ', 'VpnGw2AZ', 'VpnGw3AZ', 'ErGw1AZ', 'ErGw2AZ', 'ErGw3AZ'
* @readonly
* @enum {string}
*/
export type VirtualNetworkGatewaySkuTier = 'Basic' | 'HighPerformance' | 'Standard' | 'UltraPerformance' | 'VpnGw1' | 'VpnGw2' | 'VpnGw3' | 'VpnGw1AZ' | 'VpnGw2AZ' | 'VpnGw3AZ' | 'ErGw1AZ' | 'ErGw2AZ' | 'ErGw3AZ';
/**
* Defines values for VpnClientProtocol.
* Possible values include: 'IkeV2', 'SSTP', 'OpenVPN'
* @readonly
* @enum {string}
*/
export type VpnClientProtocol = 'IkeV2' | 'SSTP' | 'OpenVPN';
/**
* Defines values for IpsecEncryption.
* Possible values include: 'None', 'DES', 'DES3', 'AES128', 'AES192', 'AES256', 'GCMAES128',
* 'GCMAES192', 'GCMAES256'
* @readonly
* @enum {string}
*/
export type IpsecEncryption = 'None' | 'DES' | 'DES3' | 'AES128' | 'AES192' | 'AES256' | 'GCMAES128' | 'GCMAES192' | 'GCMAES256';
/**
* Defines values for IpsecIntegrity.
* Possible values include: 'MD5', 'SHA1', 'SHA256', 'GCMAES128', 'GCMAES192', 'GCMAES256'
* @readonly
* @enum {string}
*/
export type IpsecIntegrity = 'MD5' | 'SHA1' | 'SHA256' | 'GCMAES128' | 'GCMAES192' | 'GCMAES256';
/**
* Defines values for IkeEncryption.
* Possible values include: 'DES', 'DES3', 'AES128', 'AES192', 'AES256', 'GCMAES256', 'GCMAES128'
* @readonly
* @enum {string}
*/
export type IkeEncryption = 'DES' | 'DES3' | 'AES128' | 'AES192' | 'AES256' | 'GCMAES256' | 'GCMAES128';
/**
* Defines values for IkeIntegrity.
* Possible values include: 'MD5', 'SHA1', 'SHA256', 'SHA384', 'GCMAES256', 'GCMAES128'
* @readonly
* @enum {string}
*/
export type IkeIntegrity = 'MD5' | 'SHA1' | 'SHA256' | 'SHA384' | 'GCMAES256' | 'GCMAES128';
/**
* Defines values for DhGroup.
* Possible values include: 'None', 'DHGroup1', 'DHGroup2', 'DHGroup14', 'DHGroup2048', 'ECP256',
* 'ECP384', 'DHGroup24'
* @readonly
* @enum {string}
*/
export type DhGroup = 'None' | 'DHGroup1' | 'DHGroup2' | 'DHGroup14' | 'DHGroup2048' | 'ECP256' | 'ECP384' | 'DHGroup24';
/**
* Defines values for PfsGroup.
* Possible values include: 'None', 'PFS1', 'PFS2', 'PFS2048', 'ECP256', 'ECP384', 'PFS24',
* 'PFS14', 'PFSMM'
* @readonly
* @enum {string}
*/
export type PfsGroup = 'None' | 'PFS1' | 'PFS2' | 'PFS2048' | 'ECP256' | 'ECP384' | 'PFS24' | 'PFS14' | 'PFSMM';
/**
* Defines values for BgpPeerState.
* Possible values include: 'Unknown', 'Stopped', 'Idle', 'Connecting', 'Connected'
* @readonly
* @enum {string}
*/
export type BgpPeerState = 'Unknown' | 'Stopped' | 'Idle' | 'Connecting' | 'Connected';
/**
* Defines values for ProcessorArchitecture.
* Possible values include: 'Amd64', 'X86'
* @readonly
* @enum {string}
*/
export type ProcessorArchitecture = 'Amd64' | 'X86';
/**
* Defines values for AuthenticationMethod.
* Possible values include: 'EAPTLS', 'EAPMSCHAPv2'
* @readonly
* @enum {string}
*/
export type AuthenticationMethod = 'EAPTLS' | 'EAPMSCHAPv2';
/**
* Defines values for VirtualNetworkGatewayConnectionStatus.
* Possible values include: 'Unknown', 'Connecting', 'Connected', 'NotConnected'
* @readonly
* @enum {string}
*/
export type VirtualNetworkGatewayConnectionStatus = 'Unknown' | 'Connecting' | 'Connected' | 'NotConnected';
/**
* Defines values for VirtualNetworkGatewayConnectionType.
* Possible values include: 'IPsec', 'Vnet2Vnet', 'ExpressRoute', 'VPNClient'
* @readonly
* @enum {string}
*/
export type VirtualNetworkGatewayConnectionType = 'IPsec' | 'Vnet2Vnet' | 'ExpressRoute' | 'VPNClient';
/**
* Defines values for VirtualNetworkGatewayConnectionProtocol.
* Possible values include: 'IKEv2', 'IKEv1'
* @readonly
* @enum {string}
*/
export type VirtualNetworkGatewayConnectionProtocol = 'IKEv2' | 'IKEv1';
/**
* Defines values for LoadBalancerSkuName.
* Possible values include: 'Basic', 'Standard'
* @readonly
* @enum {string}
*/
export type LoadBalancerSkuName = 'Basic' | 'Standard';
/**
* Defines values for SecurityRuleProtocol.
* Possible values include: 'Tcp', 'Udp', '*'
* @readonly
* @enum {string}
*/
export type SecurityRuleProtocol = 'Tcp' | 'Udp' | '*';
/**
* Defines values for SecurityRuleAccess.
* Possible values include: 'Allow', 'Deny'
* @readonly
* @enum {string}
*/
export type SecurityRuleAccess = 'Allow' | 'Deny';
/**
* Defines values for SecurityRuleDirection.
* Possible values include: 'Inbound', 'Outbound'
* @readonly
* @enum {string}
*/
export type SecurityRuleDirection = 'Inbound' | 'Outbound';
/**
* Defines values for TransportProtocol.
* Possible values include: 'Udp', 'Tcp', 'All'
* @readonly
* @enum {string}
*/
export type TransportProtocol = 'Udp' | 'Tcp' | 'All';
/**
* Defines values for IPVersion.
* Possible values include: 'IPv4', 'IPv6'
* @readonly
* @enum {string}
*/
export type IPVersion = 'IPv4' | 'IPv6';
/**
* Defines values for PublicIPAddressSkuName.
* Possible values include: 'Basic', 'Standard'
* @readonly
* @enum {string}
*/
export type PublicIPAddressSkuName = 'Basic' | 'Standard';
/**
* Defines values for RouteNextHopType.
* Possible values include: 'VirtualNetworkGateway', 'VnetLocal', 'Internet', 'VirtualAppliance',
* 'None'
* @readonly
* @enum {string}
*/
export type RouteNextHopType = 'VirtualNetworkGateway' | 'VnetLocal' | 'Internet' | 'VirtualAppliance' | 'None';
/**
* Defines values for LoadDistribution.
* Possible values include: 'Default', 'SourceIP', 'SourceIPProtocol'
* @readonly
* @enum {string}
*/
export type LoadDistribution = 'Default' | 'SourceIP' | 'SourceIPProtocol';
/**
* Defines values for ProbeProtocol.
* Possible values include: 'Http', 'Tcp', 'Https'
* @readonly
* @enum {string}
*/
export type ProbeProtocol = 'Http' | 'Tcp' | 'Https';
/**
* Defines values for NetworkOperationStatus.
* Possible values include: 'InProgress', 'Succeeded', 'Failed'
* @readonly
* @enum {string}
*/
export type NetworkOperationStatus = 'InProgress' | 'Succeeded' | 'Failed';
/**
* Defines values for ResourceIdentityType.
* Possible values include: 'SystemAssigned', 'UserAssigned', 'SystemAssigned, UserAssigned',
* 'None'
* @readonly
* @enum {string}
*/
export type ResourceIdentityType = 'SystemAssigned' | 'UserAssigned' | 'SystemAssigned, UserAssigned' | 'None';
/**
* Defines values for EffectiveSecurityRuleProtocol.
* Possible values include: 'Tcp', 'Udp', 'All'
* @readonly
* @enum {string}
*/
export type EffectiveSecurityRuleProtocol = 'Tcp' | 'Udp' | 'All';
/**
* Defines values for EffectiveRouteSource.
* Possible values include: 'Unknown', 'User', 'VirtualNetworkGateway', 'Default'
* @readonly
* @enum {string}
*/
export type EffectiveRouteSource = 'Unknown' | 'User' | 'VirtualNetworkGateway' | 'Default';
/**
* Defines values for EffectiveRouteState.
* Possible values include: 'Active', 'Invalid'
* @readonly
* @enum {string}
*/
export type EffectiveRouteState = 'Active' | 'Invalid';
/**
* Defines values for VirtualNetworkPeeringState.
* Possible values include: 'Initiated', 'Connected', 'Disconnected'
* @readonly
* @enum {string}
*/
export type VirtualNetworkPeeringState = 'Initiated' | 'Connected' | 'Disconnected';
/**
* Defines values for ProtectionCoverage.
* Possible values include: 'Basic', 'Standard'
* @readonly
* @enum {string}
*/
export type ProtectionCoverage = 'Basic' | 'Standard';
/**
* Defines values for Protocol.
* Possible values include: 'Tcp', 'Udp', 'All'
* @readonly
* @enum {string}
*/
export type Protocol = 'Tcp' | 'Udp' | 'All';
/**
* Contains response data for the createOrUpdate operation.
*/
export type VirtualNetworkGatewaysCreateOrUpdateResponse = VirtualNetworkGateway & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkGateway;
};
};
/**
* Contains response data for the get operation.
*/
export type VirtualNetworkGatewaysGetResponse = VirtualNetworkGateway & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkGateway;
};
};
/**
* Contains response data for the updateTags operation.
*/
export type VirtualNetworkGatewaysUpdateTagsResponse = VirtualNetworkGateway & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkGateway;
};
};
/**
* Contains response data for the list operation.
*/
export type VirtualNetworkGatewaysListResponse = VirtualNetworkGatewayListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkGatewayListResult;
};
};
/**
* Contains response data for the listConnections operation.
*/
export type VirtualNetworkGatewaysListConnectionsResponse = VirtualNetworkGatewayListConnectionsResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkGatewayListConnectionsResult;
};
};
/**
* Contains response data for the reset operation.
*/
export type VirtualNetworkGatewaysResetResponse = VirtualNetworkGateway & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkGateway;
};
};
/**
* Contains response data for the generatevpnclientpackage operation.
*/
export type VirtualNetworkGatewaysGeneratevpnclientpackageResponse = {
/**
* The parsed response body.
*/
body: string;
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: string;
};
};
/**
* Contains response data for the generateVpnProfile operation.
*/
export type VirtualNetworkGatewaysGenerateVpnProfileResponse = {
/**
* The parsed response body.
*/
body: string;
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: string;
};
};
/**
* Contains response data for the getVpnProfilePackageUrl operation.
*/
export type VirtualNetworkGatewaysGetVpnProfilePackageUrlResponse = {
/**
* The parsed response body.
*/
body: string;
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: string;
};
};
/**
* Contains response data for the getBgpPeerStatus operation.
*/
export type VirtualNetworkGatewaysGetBgpPeerStatusResponse = BgpPeerStatusListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: BgpPeerStatusListResult;
};
};
/**
* Contains response data for the supportedVpnDevices operation.
*/
export type VirtualNetworkGatewaysSupportedVpnDevicesResponse = {
/**
* The parsed response body.
*/
body: string;
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: string;
};
};
/**
* Contains response data for the getLearnedRoutes operation.
*/
export type VirtualNetworkGatewaysGetLearnedRoutesResponse = GatewayRouteListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: GatewayRouteListResult;
};
};
/**
* Contains response data for the getAdvertisedRoutes operation.
*/
export type VirtualNetworkGatewaysGetAdvertisedRoutesResponse = GatewayRouteListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: GatewayRouteListResult;
};
};
/**
* Contains response data for the setVpnclientIpsecParameters operation.
*/
export type VirtualNetworkGatewaysSetVpnclientIpsecParametersResponse = VpnClientIPsecParameters & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VpnClientIPsecParameters;
};
};
/**
* Contains response data for the getVpnclientIpsecParameters operation.
*/
export type VirtualNetworkGatewaysGetVpnclientIpsecParametersResponse = VpnClientIPsecParameters & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VpnClientIPsecParameters;
};
};
/**
* Contains response data for the vpnDeviceConfigurationScript operation.
*/
export type VirtualNetworkGatewaysVpnDeviceConfigurationScriptResponse = {
/**
* The parsed response body.
*/
body: string;
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: string;
};
};
/**
* Contains response data for the beginCreateOrUpdate operation.
*/
export type VirtualNetworkGatewaysBeginCreateOrUpdateResponse = VirtualNetworkGateway & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkGateway;
};
};
/**
* Contains response data for the beginUpdateTags operation.
*/
export type VirtualNetworkGatewaysBeginUpdateTagsResponse = VirtualNetworkGateway & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkGateway;
};
};
/**
* Contains response data for the beginReset operation.
*/
export type VirtualNetworkGatewaysBeginResetResponse = VirtualNetworkGateway & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkGateway;
};
};
/**
* Contains response data for the beginGeneratevpnclientpackage operation.
*/
export type VirtualNetworkGatewaysBeginGeneratevpnclientpackageResponse = {
/**
* The parsed response body.
*/
body: string;
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: string;
};
};
/**
* Contains response data for the beginGenerateVpnProfile operation.
*/
export type VirtualNetworkGatewaysBeginGenerateVpnProfileResponse = {
/**
* The parsed response body.
*/
body: string;
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: string;
};
};
/**
* Contains response data for the beginGetVpnProfilePackageUrl operation.
*/
export type VirtualNetworkGatewaysBeginGetVpnProfilePackageUrlResponse = {
/**
* The parsed response body.
*/
body: string;
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: string;
};
};
/**
* Contains response data for the beginGetBgpPeerStatus operation.
*/
export type VirtualNetworkGatewaysBeginGetBgpPeerStatusResponse = BgpPeerStatusListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: BgpPeerStatusListResult;
};
};
/**
* Contains response data for the beginGetLearnedRoutes operation.
*/
export type VirtualNetworkGatewaysBeginGetLearnedRoutesResponse = GatewayRouteListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: GatewayRouteListResult;
};
};
/**
* Contains response data for the beginGetAdvertisedRoutes operation.
*/
export type VirtualNetworkGatewaysBeginGetAdvertisedRoutesResponse = GatewayRouteListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: GatewayRouteListResult;
};
};
/**
* Contains response data for the beginSetVpnclientIpsecParameters operation.
*/
export type VirtualNetworkGatewaysBeginSetVpnclientIpsecParametersResponse = VpnClientIPsecParameters & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VpnClientIPsecParameters;
};
};
/**
* Contains response data for the beginGetVpnclientIpsecParameters operation.
*/
export type VirtualNetworkGatewaysBeginGetVpnclientIpsecParametersResponse = VpnClientIPsecParameters & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VpnClientIPsecParameters;
};
};
/**
* Contains response data for the listNext operation.
*/
export type VirtualNetworkGatewaysListNextResponse = VirtualNetworkGatewayListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkGatewayListResult;
};
};
/**
* Contains response data for the listConnectionsNext operation.
*/
export type VirtualNetworkGatewaysListConnectionsNextResponse = VirtualNetworkGatewayListConnectionsResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkGatewayListConnectionsResult;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type VirtualNetworkGatewayConnectionsCreateOrUpdateResponse = VirtualNetworkGatewayConnection & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkGatewayConnection;
};
};
/**
* Contains response data for the get operation.
*/
export type VirtualNetworkGatewayConnectionsGetResponse = VirtualNetworkGatewayConnection & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkGatewayConnection;
};
};
/**
* Contains response data for the updateTags operation.
*/
export type VirtualNetworkGatewayConnectionsUpdateTagsResponse = VirtualNetworkGatewayConnection & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkGatewayConnection;
};
};
/**
* Contains response data for the setSharedKey operation.
*/
export type VirtualNetworkGatewayConnectionsSetSharedKeyResponse = ConnectionSharedKey & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ConnectionSharedKey;
};
};
/**
* Contains response data for the getSharedKey operation.
*/
export type VirtualNetworkGatewayConnectionsGetSharedKeyResponse = ConnectionSharedKey & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ConnectionSharedKey;
};
};
/**
* Contains response data for the list operation.
*/
export type VirtualNetworkGatewayConnectionsListResponse = VirtualNetworkGatewayConnectionListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkGatewayConnectionListResult;
};
};
/**
* Contains response data for the resetSharedKey operation.
*/
export type VirtualNetworkGatewayConnectionsResetSharedKeyResponse = ConnectionResetSharedKey & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ConnectionResetSharedKey;
};
};
/**
* Contains response data for the beginCreateOrUpdate operation.
*/
export type VirtualNetworkGatewayConnectionsBeginCreateOrUpdateResponse = VirtualNetworkGatewayConnection & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkGatewayConnection;
};
};
/**
* Contains response data for the beginUpdateTags operation.
*/
export type VirtualNetworkGatewayConnectionsBeginUpdateTagsResponse = VirtualNetworkGatewayConnection & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkGatewayConnection;
};
};
/**
* Contains response data for the beginSetSharedKey operation.
*/
export type VirtualNetworkGatewayConnectionsBeginSetSharedKeyResponse = ConnectionSharedKey & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ConnectionSharedKey;
};
};
/**
* Contains response data for the beginResetSharedKey operation.
*/
export type VirtualNetworkGatewayConnectionsBeginResetSharedKeyResponse = ConnectionResetSharedKey & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ConnectionResetSharedKey;
};
};
/**
* Contains response data for the listNext operation.
*/
export type VirtualNetworkGatewayConnectionsListNextResponse = VirtualNetworkGatewayConnectionListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkGatewayConnectionListResult;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type LocalNetworkGatewaysCreateOrUpdateResponse = LocalNetworkGateway & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: LocalNetworkGateway;
};
};
/**
* Contains response data for the get operation.
*/
export type LocalNetworkGatewaysGetResponse = LocalNetworkGateway & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: LocalNetworkGateway;
};
};
/**
* Contains response data for the updateTags operation.
*/
export type LocalNetworkGatewaysUpdateTagsResponse = LocalNetworkGateway & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: LocalNetworkGateway;
};
};
/**
* Contains response data for the list operation.
*/
export type LocalNetworkGatewaysListResponse = LocalNetworkGatewayListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: LocalNetworkGatewayListResult;
};
};
/**
* Contains response data for the beginCreateOrUpdate operation.
*/
export type LocalNetworkGatewaysBeginCreateOrUpdateResponse = LocalNetworkGateway & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: LocalNetworkGateway;
};
};
/**
* Contains response data for the beginUpdateTags operation.
*/
export type LocalNetworkGatewaysBeginUpdateTagsResponse = LocalNetworkGateway & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: LocalNetworkGateway;
};
};
/**
* Contains response data for the listNext operation.
*/
export type LocalNetworkGatewaysListNextResponse = LocalNetworkGatewayListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: LocalNetworkGatewayListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type LoadBalancersGetResponse = LoadBalancer & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: LoadBalancer;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type LoadBalancersCreateOrUpdateResponse = LoadBalancer & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: LoadBalancer;
};
};
/**
* Contains response data for the updateTags operation.
*/
export type LoadBalancersUpdateTagsResponse = LoadBalancer & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: LoadBalancer;
};
};
/**
* Contains response data for the listAll operation.
*/
export type LoadBalancersListAllResponse = LoadBalancerListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: LoadBalancerListResult;
};
};
/**
* Contains response data for the list operation.
*/
export type LoadBalancersListResponse = LoadBalancerListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: LoadBalancerListResult;
};
};
/**
* Contains response data for the beginCreateOrUpdate operation.
*/
export type LoadBalancersBeginCreateOrUpdateResponse = LoadBalancer & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: LoadBalancer;
};
};
/**
* Contains response data for the beginUpdateTags operation.
*/
export type LoadBalancersBeginUpdateTagsResponse = LoadBalancer & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: LoadBalancer;
};
};
/**
* Contains response data for the listAllNext operation.
*/
export type LoadBalancersListAllNextResponse = LoadBalancerListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: LoadBalancerListResult;
};
};
/**
* Contains response data for the listNext operation.
*/
export type LoadBalancersListNextResponse = LoadBalancerListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: LoadBalancerListResult;
};
};
/**
* Contains response data for the list operation.
*/
export type LoadBalancerBackendAddressPoolsListResponse = LoadBalancerBackendAddressPoolListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: LoadBalancerBackendAddressPoolListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type LoadBalancerBackendAddressPoolsGetResponse = BackendAddressPool & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: BackendAddressPool;
};
};
/**
* Contains response data for the listNext operation.
*/
export type LoadBalancerBackendAddressPoolsListNextResponse = LoadBalancerBackendAddressPoolListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: LoadBalancerBackendAddressPoolListResult;
};
};
/**
* Contains response data for the list operation.
*/
export type LoadBalancerFrontendIPConfigurationsListResponse = LoadBalancerFrontendIPConfigurationListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: LoadBalancerFrontendIPConfigurationListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type LoadBalancerFrontendIPConfigurationsGetResponse = FrontendIPConfiguration & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: FrontendIPConfiguration;
};
};
/**
* Contains response data for the listNext operation.
*/
export type LoadBalancerFrontendIPConfigurationsListNextResponse = LoadBalancerFrontendIPConfigurationListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: LoadBalancerFrontendIPConfigurationListResult;
};
};
/**
* Contains response data for the list operation.
*/
export type InboundNatRulesListResponse = InboundNatRuleListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: InboundNatRuleListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type InboundNatRulesGetResponse = InboundNatRule & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: InboundNatRule;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type InboundNatRulesCreateOrUpdateResponse = InboundNatRule & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: InboundNatRule;
};
};
/**
* Contains response data for the beginCreateOrUpdate operation.
*/
export type InboundNatRulesBeginCreateOrUpdateResponse = InboundNatRule & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: InboundNatRule;
};
};
/**
* Contains response data for the listNext operation.
*/
export type InboundNatRulesListNextResponse = InboundNatRuleListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: InboundNatRuleListResult;
};
};
/**
* Contains response data for the list operation.
*/
export type LoadBalancerLoadBalancingRulesListResponse = LoadBalancerLoadBalancingRuleListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: LoadBalancerLoadBalancingRuleListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type LoadBalancerLoadBalancingRulesGetResponse = LoadBalancingRule & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: LoadBalancingRule;
};
};
/**
* Contains response data for the listNext operation.
*/
export type LoadBalancerLoadBalancingRulesListNextResponse = LoadBalancerLoadBalancingRuleListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: LoadBalancerLoadBalancingRuleListResult;
};
};
/**
* Contains response data for the list operation.
*/
export type LoadBalancerOutboundRulesListResponse = LoadBalancerOutboundRuleListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: LoadBalancerOutboundRuleListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type LoadBalancerOutboundRulesGetResponse = OutboundRule & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: OutboundRule;
};
};
/**
* Contains response data for the listNext operation.
*/
export type LoadBalancerOutboundRulesListNextResponse = LoadBalancerOutboundRuleListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: LoadBalancerOutboundRuleListResult;
};
};
/**
* Contains response data for the list operation.
*/
export type LoadBalancerNetworkInterfacesListResponse = NetworkInterfaceListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkInterfaceListResult;
};
};
/**
* Contains response data for the listNext operation.
*/
export type LoadBalancerNetworkInterfacesListNextResponse = NetworkInterfaceListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkInterfaceListResult;
};
};
/**
* Contains response data for the list operation.
*/
export type LoadBalancerProbesListResponse = LoadBalancerProbeListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: LoadBalancerProbeListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type LoadBalancerProbesGetResponse = Probe & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Probe;
};
};
/**
* Contains response data for the listNext operation.
*/
export type LoadBalancerProbesListNextResponse = LoadBalancerProbeListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: LoadBalancerProbeListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type NetworkInterfacesGetResponse = NetworkInterface & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkInterface;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type NetworkInterfacesCreateOrUpdateResponse = NetworkInterface & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkInterface;
};
};
/**
* Contains response data for the updateTags operation.
*/
export type NetworkInterfacesUpdateTagsResponse = NetworkInterface & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkInterface;
};
};
/**
* Contains response data for the listAll operation.
*/
export type NetworkInterfacesListAllResponse = NetworkInterfaceListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkInterfaceListResult;
};
};
/**
* Contains response data for the list operation.
*/
export type NetworkInterfacesListResponse = NetworkInterfaceListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkInterfaceListResult;
};
};
/**
* Contains response data for the getEffectiveRouteTable operation.
*/
export type NetworkInterfacesGetEffectiveRouteTableResponse = EffectiveRouteListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EffectiveRouteListResult;
};
};
/**
* Contains response data for the listEffectiveNetworkSecurityGroups operation.
*/
export type NetworkInterfacesListEffectiveNetworkSecurityGroupsResponse = EffectiveNetworkSecurityGroupListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EffectiveNetworkSecurityGroupListResult;
};
};
/**
* Contains response data for the beginCreateOrUpdate operation.
*/
export type NetworkInterfacesBeginCreateOrUpdateResponse = NetworkInterface & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkInterface;
};
};
/**
* Contains response data for the beginUpdateTags operation.
*/
export type NetworkInterfacesBeginUpdateTagsResponse = NetworkInterface & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkInterface;
};
};
/**
* Contains response data for the beginGetEffectiveRouteTable operation.
*/
export type NetworkInterfacesBeginGetEffectiveRouteTableResponse = EffectiveRouteListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EffectiveRouteListResult;
};
};
/**
* Contains response data for the beginListEffectiveNetworkSecurityGroups operation.
*/
export type NetworkInterfacesBeginListEffectiveNetworkSecurityGroupsResponse = EffectiveNetworkSecurityGroupListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: EffectiveNetworkSecurityGroupListResult;
};
};
/**
* Contains response data for the listAllNext operation.
*/
export type NetworkInterfacesListAllNextResponse = NetworkInterfaceListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkInterfaceListResult;
};
};
/**
* Contains response data for the listNext operation.
*/
export type NetworkInterfacesListNextResponse = NetworkInterfaceListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkInterfaceListResult;
};
};
/**
* Contains response data for the list operation.
*/
export type NetworkInterfaceIPConfigurationsListResponse = NetworkInterfaceIPConfigurationListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkInterfaceIPConfigurationListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type NetworkInterfaceIPConfigurationsGetResponse = NetworkInterfaceIPConfiguration & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkInterfaceIPConfiguration;
};
};
/**
* Contains response data for the listNext operation.
*/
export type NetworkInterfaceIPConfigurationsListNextResponse = NetworkInterfaceIPConfigurationListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkInterfaceIPConfigurationListResult;
};
};
/**
* Contains response data for the list operation.
*/
export type NetworkInterfaceLoadBalancersListResponse = NetworkInterfaceLoadBalancerListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkInterfaceLoadBalancerListResult;
};
};
/**
* Contains response data for the listNext operation.
*/
export type NetworkInterfaceLoadBalancersListNextResponse = NetworkInterfaceLoadBalancerListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkInterfaceLoadBalancerListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type NetworkInterfaceTapConfigurationsGetResponse = NetworkInterfaceTapConfiguration & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkInterfaceTapConfiguration;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type NetworkInterfaceTapConfigurationsCreateOrUpdateResponse = NetworkInterfaceTapConfiguration & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkInterfaceTapConfiguration;
};
};
/**
* Contains response data for the list operation.
*/
export type NetworkInterfaceTapConfigurationsListResponse = NetworkInterfaceTapConfigurationListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkInterfaceTapConfigurationListResult;
};
};
/**
* Contains response data for the beginCreateOrUpdate operation.
*/
export type NetworkInterfaceTapConfigurationsBeginCreateOrUpdateResponse = NetworkInterfaceTapConfiguration & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkInterfaceTapConfiguration;
};
};
/**
* Contains response data for the listNext operation.
*/
export type NetworkInterfaceTapConfigurationsListNextResponse = NetworkInterfaceTapConfigurationListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkInterfaceTapConfigurationListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type NetworkSecurityGroupsGetResponse = NetworkSecurityGroup & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkSecurityGroup;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type NetworkSecurityGroupsCreateOrUpdateResponse = NetworkSecurityGroup & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkSecurityGroup;
};
};
/**
* Contains response data for the updateTags operation.
*/
export type NetworkSecurityGroupsUpdateTagsResponse = NetworkSecurityGroup & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkSecurityGroup;
};
};
/**
* Contains response data for the listAll operation.
*/
export type NetworkSecurityGroupsListAllResponse = NetworkSecurityGroupListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkSecurityGroupListResult;
};
};
/**
* Contains response data for the list operation.
*/
export type NetworkSecurityGroupsListResponse = NetworkSecurityGroupListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkSecurityGroupListResult;
};
};
/**
* Contains response data for the beginCreateOrUpdate operation.
*/
export type NetworkSecurityGroupsBeginCreateOrUpdateResponse = NetworkSecurityGroup & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkSecurityGroup;
};
};
/**
* Contains response data for the beginUpdateTags operation.
*/
export type NetworkSecurityGroupsBeginUpdateTagsResponse = NetworkSecurityGroup & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkSecurityGroup;
};
};
/**
* Contains response data for the listAllNext operation.
*/
export type NetworkSecurityGroupsListAllNextResponse = NetworkSecurityGroupListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkSecurityGroupListResult;
};
};
/**
* Contains response data for the listNext operation.
*/
export type NetworkSecurityGroupsListNextResponse = NetworkSecurityGroupListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: NetworkSecurityGroupListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type SecurityRulesGetResponse = SecurityRule & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: SecurityRule;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type SecurityRulesCreateOrUpdateResponse = SecurityRule & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: SecurityRule;
};
};
/**
* Contains response data for the list operation.
*/
export type SecurityRulesListResponse = SecurityRuleListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: SecurityRuleListResult;
};
};
/**
* Contains response data for the beginCreateOrUpdate operation.
*/
export type SecurityRulesBeginCreateOrUpdateResponse = SecurityRule & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: SecurityRule;
};
};
/**
* Contains response data for the listNext operation.
*/
export type SecurityRulesListNextResponse = SecurityRuleListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: SecurityRuleListResult;
};
};
/**
* Contains response data for the list operation.
*/
export type DefaultSecurityRulesListResponse = SecurityRuleListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: SecurityRuleListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type DefaultSecurityRulesGetResponse = SecurityRule & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: SecurityRule;
};
};
/**
* Contains response data for the listNext operation.
*/
export type DefaultSecurityRulesListNextResponse = SecurityRuleListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: SecurityRuleListResult;
};
};
/**
* Contains response data for the list operation.
*/
export type OperationsListResponse = OperationListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: OperationListResult;
};
};
/**
* Contains response data for the listNext operation.
*/
export type OperationsListNextResponse = OperationListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: OperationListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type PublicIPAddressesGetResponse = PublicIPAddress & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: PublicIPAddress;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type PublicIPAddressesCreateOrUpdateResponse = PublicIPAddress & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: PublicIPAddress;
};
};
/**
* Contains response data for the updateTags operation.
*/
export type PublicIPAddressesUpdateTagsResponse = PublicIPAddress & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: PublicIPAddress;
};
};
/**
* Contains response data for the listAll operation.
*/
export type PublicIPAddressesListAllResponse = PublicIPAddressListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: PublicIPAddressListResult;
};
};
/**
* Contains response data for the list operation.
*/
export type PublicIPAddressesListResponse = PublicIPAddressListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: PublicIPAddressListResult;
};
};
/**
* Contains response data for the beginCreateOrUpdate operation.
*/
export type PublicIPAddressesBeginCreateOrUpdateResponse = PublicIPAddress & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: PublicIPAddress;
};
};
/**
* Contains response data for the beginUpdateTags operation.
*/
export type PublicIPAddressesBeginUpdateTagsResponse = PublicIPAddress & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: PublicIPAddress;
};
};
/**
* Contains response data for the listAllNext operation.
*/
export type PublicIPAddressesListAllNextResponse = PublicIPAddressListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: PublicIPAddressListResult;
};
};
/**
* Contains response data for the listNext operation.
*/
export type PublicIPAddressesListNextResponse = PublicIPAddressListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: PublicIPAddressListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type RouteTablesGetResponse = RouteTable & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: RouteTable;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type RouteTablesCreateOrUpdateResponse = RouteTable & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: RouteTable;
};
};
/**
* Contains response data for the updateTags operation.
*/
export type RouteTablesUpdateTagsResponse = RouteTable & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: RouteTable;
};
};
/**
* Contains response data for the list operation.
*/
export type RouteTablesListResponse = RouteTableListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: RouteTableListResult;
};
};
/**
* Contains response data for the listAll operation.
*/
export type RouteTablesListAllResponse = RouteTableListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: RouteTableListResult;
};
};
/**
* Contains response data for the beginCreateOrUpdate operation.
*/
export type RouteTablesBeginCreateOrUpdateResponse = RouteTable & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: RouteTable;
};
};
/**
* Contains response data for the beginUpdateTags operation.
*/
export type RouteTablesBeginUpdateTagsResponse = RouteTable & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: RouteTable;
};
};
/**
* Contains response data for the listNext operation.
*/
export type RouteTablesListNextResponse = RouteTableListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: RouteTableListResult;
};
};
/**
* Contains response data for the listAllNext operation.
*/
export type RouteTablesListAllNextResponse = RouteTableListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: RouteTableListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type RoutesGetResponse = Route & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Route;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type RoutesCreateOrUpdateResponse = Route & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Route;
};
};
/**
* Contains response data for the list operation.
*/
export type RoutesListResponse = RouteListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: RouteListResult;
};
};
/**
* Contains response data for the beginCreateOrUpdate operation.
*/
export type RoutesBeginCreateOrUpdateResponse = Route & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Route;
};
};
/**
* Contains response data for the listNext operation.
*/
export type RoutesListNextResponse = RouteListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: RouteListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type VirtualNetworksGetResponse = VirtualNetwork & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetwork;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type VirtualNetworksCreateOrUpdateResponse = VirtualNetwork & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetwork;
};
};
/**
* Contains response data for the updateTags operation.
*/
export type VirtualNetworksUpdateTagsResponse = VirtualNetwork & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetwork;
};
};
/**
* Contains response data for the listAll operation.
*/
export type VirtualNetworksListAllResponse = VirtualNetworkListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkListResult;
};
};
/**
* Contains response data for the list operation.
*/
export type VirtualNetworksListResponse = VirtualNetworkListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkListResult;
};
};
/**
* Contains response data for the checkIPAddressAvailability operation.
*/
export type VirtualNetworksCheckIPAddressAvailabilityResponse = IPAddressAvailabilityResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: IPAddressAvailabilityResult;
};
};
/**
* Contains response data for the listUsage operation.
*/
export type VirtualNetworksListUsageResponse = VirtualNetworkListUsageResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkListUsageResult;
};
};
/**
* Contains response data for the beginCreateOrUpdate operation.
*/
export type VirtualNetworksBeginCreateOrUpdateResponse = VirtualNetwork & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetwork;
};
};
/**
* Contains response data for the beginUpdateTags operation.
*/
export type VirtualNetworksBeginUpdateTagsResponse = VirtualNetwork & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetwork;
};
};
/**
* Contains response data for the listAllNext operation.
*/
export type VirtualNetworksListAllNextResponse = VirtualNetworkListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkListResult;
};
};
/**
* Contains response data for the listNext operation.
*/
export type VirtualNetworksListNextResponse = VirtualNetworkListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkListResult;
};
};
/**
* Contains response data for the listUsageNext operation.
*/
export type VirtualNetworksListUsageNextResponse = VirtualNetworkListUsageResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkListUsageResult;
};
};
/**
* Contains response data for the get operation.
*/
export type SubnetsGetResponse = Subnet & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Subnet;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type SubnetsCreateOrUpdateResponse = Subnet & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Subnet;
};
};
/**
* Contains response data for the list operation.
*/
export type SubnetsListResponse = SubnetListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: SubnetListResult;
};
};
/**
* Contains response data for the beginCreateOrUpdate operation.
*/
export type SubnetsBeginCreateOrUpdateResponse = Subnet & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: Subnet;
};
};
/**
* Contains response data for the listNext operation.
*/
export type SubnetsListNextResponse = SubnetListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: SubnetListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type VirtualNetworkPeeringsGetResponse = VirtualNetworkPeering & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkPeering;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type VirtualNetworkPeeringsCreateOrUpdateResponse = VirtualNetworkPeering & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkPeering;
};
};
/**
* Contains response data for the list operation.
*/
export type VirtualNetworkPeeringsListResponse = VirtualNetworkPeeringListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkPeeringListResult;
};
};
/**
* Contains response data for the beginCreateOrUpdate operation.
*/
export type VirtualNetworkPeeringsBeginCreateOrUpdateResponse = VirtualNetworkPeering & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkPeering;
};
};
/**
* Contains response data for the listNext operation.
*/
export type VirtualNetworkPeeringsListNextResponse = VirtualNetworkPeeringListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: VirtualNetworkPeeringListResult;
};
}; | the_stack |
import { FieldType } from '@terascope/types';
import { isArrayLike } from './arrays';
import { getTypeOf } from './deps';
let supportsBigInt = true;
try {
if (typeof globalThis.BigInt === 'undefined') {
supportsBigInt = false;
}
} catch (err) {
supportsBigInt = false;
}
/** A native implementation of lodash random */
export function random(min: number, max: number): number {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/** Check if an input is a number */
export function isNumber(input: unknown): input is number {
return typeof input === 'number' && !Number.isNaN(input);
}
/** Convert any input to a number, return Number.NaN if unable to convert input */
export function toNumber(input: unknown): number {
if (typeof input === 'number') return input;
return Number(input);
}
/** Will throw if converted number is NaN */
export function toNumberOrThrow(input: unknown): number {
const num = toNumber(input);
if (!isNumber(num)) {
throw new Error(`Could not convert ${input} to a number`);
}
return num;
}
/** Check if value is a bigint */
export function isBigInt(input: unknown): input is bigint {
return typeof input === 'bigint';
}
/** Convert any input to a bigint */
export function toBigInt(input: unknown): bigint|false {
if (!supportsBigInt) {
throw new Error('BigInt isn\'t supported in this environment');
}
try {
return toBigIntOrThrow(input);
} catch {
return false;
}
}
const _maxBigInt: bigint = supportsBigInt
? BigInt(Number.MAX_SAFE_INTEGER)
: (Number.MAX_SAFE_INTEGER as any);
/** Convert any input to a bigint */
export function toBigIntOrThrow(input: unknown): bigint {
if (typeof input === 'object') {
throw new TypeError(`Expected ${input} (${getTypeOf(input)}) to be parsable to a float`);
}
if (isBigInt(input)) return input;
if (!supportsBigInt) {
throw new Error('BigInt isn\'t supported in this environment');
}
if (
typeof input === 'number' && input < Number.MAX_SAFE_INTEGER
) {
return BigInt(Math.trunc(input));
}
if (!isNumberLike(input)) {
throw new TypeError(`Expected ${input} (${getTypeOf(input)}) to be parsable to a BigInt`);
}
let big: bigint;
if (typeof input === 'string' && input.includes('.')) {
big = BigInt(Number.parseInt(input, 10));
} else {
big = BigInt(input as string | number | bigint);
}
// for some reason the number
// is incorrect when given a number
// greater than the max safe integer
if (big > _maxBigInt) {
return big + BigInt(1);
}
return big;
}
/**
* Convert a BigInt to either a number or a string
*/
export function bigIntToJSON(int: bigint): string|number {
if (typeof int === 'number') return int;
if (int <= _maxBigInt) {
return Number.parseInt(int.toString(10), 10);
}
// for some reason bigints ending being +1
return (int - BigInt(1)).toString(10);
}
/**
* A stricter check for verifying a number string
* @todo this needs to be smarter
*/
export function isNumberLike(input: unknown): boolean {
if (typeof input === 'number') return true;
if (typeof input === 'object') return false;
if (typeof input === 'boolean') return false;
// https://regexr.com/5cljt
return /^\s*[+-]{0,1}[\d,]+(\.[\d]+){0,1}\s*$/.test(String(input));
}
/** A simplified implementation of lodash isInteger */
export function isInteger(val: unknown): val is number {
if (typeof val !== 'number') return false;
return Number.isSafeInteger(val);
}
/** Convert an input to a integer, return false if unable to convert input */
export function toInteger(input: unknown): number | false {
try {
return toIntegerOrThrow(input);
} catch (err) {
return false;
}
}
/** Convert an input to a integer or throw */
export function toIntegerOrThrow(input: unknown): number {
if (typeof input === 'object') {
throw new TypeError(`Expected ${input} (${getTypeOf(input)}) to be parsable to a integer`);
}
if (isBigInt(input)) {
const val = bigIntToJSON(input);
if (typeof val === 'string') {
throw new TypeError(`Expected ${val} (${getTypeOf(input)}) to be parsable to a integer`);
}
return val;
}
if (isInteger(input) || isFloat(input)) return Math.trunc(input);
if (!isNumberLike(input)) {
throw new TypeError(`Expected ${input} (${getTypeOf(input)}) to be parsable to a integer`);
}
const val = Number.parseInt(input as any, 10);
if (isInteger(val)) return val;
throw new TypeError(`Expected ${val} (${getTypeOf(input)}) to be parsable to a integer`);
}
/** Verify the input is a finite number (and float like) */
export function isFloat(val: unknown): val is number {
if (!isNumber(val)) return false;
if (val === Number.POSITIVE_INFINITY) return false;
if (val === Number.NEGATIVE_INFINITY) return false;
return true;
}
/** Convert an input to a float, return false if unable to convert input */
export function toFloat(input: unknown): number | false {
try {
return toFloatOrThrow(input);
} catch (err) {
return false;
}
}
/** Convert an input to a float or throw */
export function toFloatOrThrow(input: unknown): number {
if (typeof input === 'object') {
throw new TypeError(`Expected ${input} (${getTypeOf(input)}) to be parsable to a float`);
}
if (isFloat(input)) return input;
if (isBigInt(input)) {
const val = bigIntToJSON(input);
if (typeof val === 'string') {
throw new TypeError(`Expected ${val} (${getTypeOf(input)}) to be parsable to a float`);
}
return val;
}
if (!isNumberLike(input)) {
throw new TypeError(`Expected ${input} (${getTypeOf(input)}) to be parsable to a float`);
}
const val = Number.parseFloat(input as any);
if (isFloat(val)) return val;
throw new TypeError(`Expected ${val} (${getTypeOf(input)}) to be parsable to a float`);
}
/**
* Like parseList, except it returns numbers
*/
export function parseNumberList(input: unknown): number[] {
let items: (number | string)[];
if (typeof input === 'string') {
items = input.split(',');
} else if (Array.isArray(input)) {
items = input;
} else if (isArrayLike(input)) {
items = Array.from(input);
} else if (isNumber(input)) {
return [input];
} else {
return [];
}
return items
// filter out any empty string
.filter(isConvertibleToNumber)
.map(toNumber)
.filter(isNumber);
}
function isConvertibleToNumber(item: unknown): boolean {
if (item == null) return false;
if (typeof item === 'string' && !item.trim().length) return false;
return true;
}
export interface InNumberRangeArg {
min?: number;
max?: number;
inclusive?: boolean
}
/**
* Returns true if number is between min or max value provided
*
* @example
* inNumberRange(42, { min: 0, max: 100}); // true
* inNumberRange(-42, { min:0 , max: 100 }); // false
* inNumberRange(42, { min: 0, max: 42 }); // false
* inNumberRange(42, { min: 0, max: 42, inclusive: true }) // true
*/
export function inNumberRange(input: unknown, args: InNumberRangeArg): input is number {
if (!isNumber(input) && !isBigInt(input)) return false;
const min = args.min == null ? Number.NEGATIVE_INFINITY : args.min;
const max = args.max == null ? Number.POSITIVE_INFINITY : args.max;
if (args.inclusive) {
return (input >= min && input <= max);
}
return (input > min && input < max);
}
export function inNumberRangeFP(args: InNumberRangeArg) {
return function _inNumberRangeFP(input: unknown): input is number {
return inNumberRange(input, args);
};
}
/**
* Returns a truncated number to nth decimal places.
*
* @param fractionDigits The number of decimal points to round to.
* @param truncate If this is true the number will not be rounded
*/
export function setPrecision(
input: unknown,
fractionDigits: number,
truncate = false
): number {
if (Number.isNaN(input)
|| input === Number.POSITIVE_INFINITY
|| input === Number.NEGATIVE_INFINITY) {
return input as number;
}
const num = toFloatOrThrow(input);
if (!truncate) {
return parseFloat(num.toFixed(fractionDigits));
}
return parseFloat(
setPrecisionFromString(num.toString(), fractionDigits)
);
}
/**
* A functional programming version of setPrecision
*
* @param fractionDigits The number of decimal points to round to.
* @param truncate If this is true the number will not be rounded
*/
export function setPrecisionFP(
fractionDigits: number,
truncate = false
): (input: unknown) => number {
return function _setPrecision(input) {
return setPrecision(input, fractionDigits, truncate);
};
}
/**
* this will always truncate (not round)
*/
function setPrecisionFromString(
input: string,
fractionDigits: number,
): string {
const [int, points] = input.toString().split('.');
if (!points) return int || '0';
const remainingPoints = points.slice(0, fractionDigits);
if (!remainingPoints) return int || '0';
return `${int || '0'}.${remainingPoints}`;
}
/**
* Convert a fahrenheit value to celsius, this will return a precision of
* 2 decimal points
*/
export function toCelsius(input: unknown): number {
const num = toFloatOrThrow(input);
const cNum = (num - 32) * (5 / 9);
return parseFloat(cNum.toFixed(2));
}
/**
* Convert a celsius value to fahrenheit, this will return a precision of
* 2 decimal points
*/
export function toFahrenheit(input: unknown): number {
const num = toFloatOrThrow(input);
const fNum = ((9 / 5) * num) + 32;
return parseFloat(fNum.toFixed(2));
}
const INT_SIZES = {
[FieldType.Byte]: { min: -128, max: 127 },
[FieldType.Short]: { min: -32_768, max: 32_767 },
[FieldType.Integer]: { min: -(2 ** 31), max: (2 ** 31) - 1 },
} as const;
function _validateNumberFieldType(input: unknown, type: FieldType): number {
const int = toIntegerOrThrow(input);
if (INT_SIZES[type]) {
const { max, min } = INT_SIZES[type];
if (int >= max) {
throw new TypeError(`Invalid byte, value of ${int} is greater than maximum size of ${max}`);
}
if (int <= min) {
throw new TypeError(`Invalid byte, value of ${int} is less than minimum size of ${min}`);
}
}
return int;
}
export function validateByteNumber(input: unknown): number {
return _validateNumberFieldType(input, FieldType.Byte);
}
export function validateShortNumber(input: unknown): number {
return _validateNumberFieldType(input, FieldType.Short);
}
export function validateIntegerNumber(input: unknown): number {
return _validateNumberFieldType(input, FieldType.Integer);
}
export function validateNumberType(type: FieldType) {
return function _validateNumberType(input: unknown): number {
return _validateNumberFieldType(input, type);
};
}
export function isValidateNumberType(type: FieldType): (input: unknown) => boolean {
const fn = validateNumberType(type);
return function _isValidateNumberType(input: unknown): boolean {
try {
return fn(input) != null;
} catch (_err) {
return false;
}
};
} | the_stack |
import type { b64string } from '@tanker/crypto';
import { generichash, tcrypto, utils } from '@tanker/crypto';
import { InternalError, InvalidArgument, PreconditionFailed } from '@tanker/errors';
import type { SecretProvisionalIdentity, PublicProvisionalIdentity, PublicProvisionalUser } from '../Identity';
import type { Client } from '../Network/Client';
import type { TankerProvisionalIdentityResponse } from '../Network/types';
import type { PrivateProvisionalKeys, LocalUserManager } from '../LocalUser/Manager';
import type KeyStore from '../LocalUser/KeyStore';
import { formatProvisionalKeysRequest, formatVerificationRequest } from '../LocalUser/requests';
import type {
EmailVerification,
EmailVerificationMethod,
OIDCVerification, PhoneNumberVerification, PhoneNumberVerificationMethod, ProvisionalVerification,
ProvisionalVerificationMethod,
} from '../LocalUser/types';
import { Status } from '../Session/status';
import type UserManager from '../Users/Manager';
import { provisionalIdentityClaimFromBlock, makeProvisionalIdentityClaim } from './Serialize';
import { verifyProvisionalIdentityClaim } from './Verify';
import type { AttachResult } from './types';
import {
identityTargetToVerificationMethodType,
isProvisionalIdentity,
} from '../Identity';
type TankerProvisionalKeys = { tankerSignatureKeyPair: tcrypto.SodiumKeyPair; tankerEncryptionKeyPair: tcrypto.SodiumKeyPair; };
const toTankerProvisionalKeys = (serverResult: TankerProvisionalIdentityResponse) => ({
tankerSignatureKeyPair: {
privateKey: utils.fromBase64(serverResult.private_signature_key),
publicKey: utils.fromBase64(serverResult.public_signature_key),
},
tankerEncryptionKeyPair: {
privateKey: utils.fromBase64(serverResult.private_encryption_key),
publicKey: utils.fromBase64(serverResult.public_encryption_key),
},
});
export default class ProvisionalIdentityManager {
_client: Client;
_keyStore: KeyStore;
_localUserManager: LocalUserManager;
_userManager: UserManager;
_provisionalIdentity?: SecretProvisionalIdentity;
constructor(
client: Client,
keyStore: KeyStore,
localUserManager: LocalUserManager,
userManager: UserManager,
) {
this._client = client;
this._localUserManager = localUserManager;
this._userManager = userManager;
this._keyStore = keyStore;
}
async attachProvisionalIdentity(provisionalIdentity: SecretProvisionalIdentity): Promise<AttachResult> {
let hasClaimed = this._localUserManager.hasProvisionalUserKey(utils.fromBase64(provisionalIdentity.public_encryption_key));
if (!hasClaimed) {
await this.refreshProvisionalPrivateKeys();
hasClaimed = this._localUserManager.hasProvisionalUserKey(utils.fromBase64(provisionalIdentity.public_encryption_key));
}
if (hasClaimed) {
return { status: Status.READY };
}
if (!isProvisionalIdentity(provisionalIdentity)) {
// @ts-expect-error Target is already checked when deserializing the provisional identity
throw new InternalError(`Assertion error: unsupported provisional identity target: ${provisionalIdentity.target}`);
}
const verificationMethod = await this._getVerificationMethodForProvisional(provisionalIdentity);
if (verificationMethod) {
const attachSuccess = await this._attachProvisionalWithVerifMethod(provisionalIdentity, verificationMethod);
if (attachSuccess) {
return { status: Status.READY };
}
}
this._provisionalIdentity = provisionalIdentity;
return {
status: Status.IDENTITY_VERIFICATION_NEEDED,
verificationMethod: this._verificationMethodFromIdentity(provisionalIdentity),
};
}
async _getVerificationMethodForProvisional(provisionalIdentity: SecretProvisionalIdentity): Promise<ProvisionalVerificationMethod | null> {
const methodType = identityTargetToVerificationMethodType(provisionalIdentity.target);
const verificationMethods = await this._localUserManager.getVerificationMethods();
// @ts-expect-error We select the verificationMethod using the provisional target
return verificationMethods.find(method => method.type === methodType);
}
async _attachProvisionalWithVerifMethod(provisionalIdentity: SecretProvisionalIdentity, verificationMethod: ProvisionalVerificationMethod): Promise<boolean> {
const expected = {
email: (verificationMethod as EmailVerificationMethod).email || null,
phone_number: (verificationMethod as PhoneNumberVerificationMethod).phoneNumber || null,
};
// When the target is also registered as a verification method:
// - we can directly claim if keys found
// - we know that there's nothing to claim if keys not found
if (expected[provisionalIdentity.target] === provisionalIdentity.value) {
const tankerKeys = await this._getProvisionalIdentityKeys(provisionalIdentity);
if (tankerKeys) {
await this._claimProvisionalIdentity(provisionalIdentity, tankerKeys);
}
return true;
}
return false;
}
_verificationMethodFromIdentity(provisionalIdentity: SecretProvisionalIdentity): ProvisionalVerificationMethod {
if (provisionalIdentity.target === 'email') {
return {
type: 'email',
email: provisionalIdentity.value,
};
}
if (provisionalIdentity.target === 'phone_number') {
return {
type: 'phoneNumber',
phoneNumber: provisionalIdentity.value,
};
}
// Target is already checked when deserializing the provisional identity
throw new InternalError(`Assertion error: unsupported provisional identity target: ${provisionalIdentity.target}`);
}
async verifyProvisionalIdentity(verification: ProvisionalVerification | OIDCVerification) {
if (!('email' in verification) && !('phoneNumber' in verification) && !('oidcIdToken' in verification))
throw new InternalError(`Assertion error: unsupported verification method for provisional identity: ${JSON.stringify(verification)}`);
if (!this._provisionalIdentity)
throw new PreconditionFailed('Cannot call verifyProvisionalIdentity() without having called attachProvisionalIdentity() before');
const provisionalIdentity = this._provisionalIdentity;
if ('oidcIdToken' in verification) {
let jwtPayload;
try {
jwtPayload = JSON.parse(utils.toString(utils.fromSafeBase64(verification.oidcIdToken.split('.')[1]!)));
} catch (e) {
throw new InvalidArgument('Failed to parse "verification.oidcIdToken"');
}
if (jwtPayload.email !== provisionalIdentity.value)
throw new InvalidArgument('"verification.oidcIdToken" does not match provisional identity');
} else if (provisionalIdentity.target === 'email' && (verification as EmailVerification).email !== provisionalIdentity.value) {
throw new InvalidArgument('"verification.email" does not match provisional identity');
} else if (provisionalIdentity.target === 'phone_number' && (verification as PhoneNumberVerification).phoneNumber !== provisionalIdentity.value) {
throw new InvalidArgument('"verification.phoneNumber" does not match provisional identity');
}
const tankerKeys = await this._getProvisionalIdentityKeys(provisionalIdentity, verification);
await this._claimProvisionalIdentity(provisionalIdentity, tankerKeys);
delete this._provisionalIdentity;
}
findPrivateProvisionalKeys(appPublicSignatureKey: Uint8Array, tankerPublicSignatureKey: Uint8Array): PrivateProvisionalKeys | null {
return this._localUserManager.findProvisionalUserKey(appPublicSignatureKey, tankerPublicSignatureKey);
}
async getPrivateProvisionalKeys(appPublicSignatureKey: Uint8Array, tankerPublicSignatureKey: Uint8Array): Promise<PrivateProvisionalKeys | null> {
let provisionalEncryptionKeyPairs = this.findPrivateProvisionalKeys(appPublicSignatureKey, tankerPublicSignatureKey);
if (!provisionalEncryptionKeyPairs) {
await this.refreshProvisionalPrivateKeys();
provisionalEncryptionKeyPairs = this.findPrivateProvisionalKeys(appPublicSignatureKey, tankerPublicSignatureKey);
}
return provisionalEncryptionKeyPairs;
}
async getProvisionalUsers(provisionalIdentitiesWithDup: Array<PublicProvisionalIdentity>): Promise<Array<PublicProvisionalUser>> {
if (provisionalIdentitiesWithDup.length === 0)
return [];
const appKeys: Set<b64string> = new Set();
const provisionalIdentities: Array<PublicProvisionalIdentity> = [];
for (const id of provisionalIdentitiesWithDup) {
if (!appKeys.has(id.public_signature_key)) {
appKeys.add(id.public_signature_key);
provisionalIdentities.push(id);
}
}
const emailHashedValues = [];
const phoneNumberHashedValues = [];
for (const provisionalIdentity of provisionalIdentities) {
switch (provisionalIdentity.target) {
case 'email':
emailHashedValues.push(generichash(utils.fromString(provisionalIdentity.value)));
break;
case 'hashed_email':
emailHashedValues.push(utils.fromBase64(provisionalIdentity.value));
break;
case 'hashed_phone_number':
phoneNumberHashedValues.push(utils.fromBase64(provisionalIdentity.value));
break;
default:
throw new InvalidArgument(`Unsupported provisional identity target: ${provisionalIdentity.target}`);
}
}
const tankerPublicKeysByHashedValues = await this._client.getPublicProvisionalIdentities(emailHashedValues, phoneNumberHashedValues);
const tankerPublicKeysByEmailHash = tankerPublicKeysByHashedValues.hashedEmails;
const tankerPublicKeysByPhoneNumberHash = tankerPublicKeysByHashedValues.hashedPhoneNumbers;
return provisionalIdentities.map(provisionalIdentity => {
let tankerPublicKeys;
if (provisionalIdentity.target === 'email') {
const emailHash = utils.toBase64(generichash(utils.fromString(provisionalIdentity.value)));
tankerPublicKeys = tankerPublicKeysByEmailHash[emailHash];
} else if (provisionalIdentity.target === 'hashed_email') {
tankerPublicKeys = tankerPublicKeysByEmailHash[provisionalIdentity.value];
} else if (provisionalIdentity.target === 'hashed_phone_number') {
tankerPublicKeys = tankerPublicKeysByPhoneNumberHash[provisionalIdentity.value];
} else {
throw new InternalError(`Assertion error: Unreachable if targets have been validated before doing the request (target ${provisionalIdentity.target})`);
}
if (!tankerPublicKeys) {
throw new InternalError(`Assertion error: couldn't find or generate tanker public keys for provisional identity: ${provisionalIdentity.value}`);
}
return {
trustchainId: utils.fromBase64(provisionalIdentity.trustchain_id),
target: provisionalIdentity.target,
value: provisionalIdentity.value,
appEncryptionPublicKey: utils.fromBase64(provisionalIdentity.public_encryption_key),
appSignaturePublicKey: utils.fromBase64(provisionalIdentity.public_signature_key),
tankerEncryptionPublicKey: utils.fromBase64(tankerPublicKeys.public_encryption_key),
tankerSignaturePublicKey: utils.fromBase64(tankerPublicKeys.public_signature_key),
};
});
}
async _getProvisionalIdentityKeys(provIdentity: SecretProvisionalIdentity, verification?: ProvisionalVerification | OIDCVerification): Promise<TankerProvisionalKeys> {
let tankerProvisionalKeysReply: TankerProvisionalIdentityResponse;
const localUser = this._localUserManager.localUser;
if (verification) {
tankerProvisionalKeysReply = await this._client.getTankerProvisionalKeysWithVerif({
verification: formatVerificationRequest(verification, localUser, provIdentity),
});
} else {
tankerProvisionalKeysReply = await this._client.getTankerProvisionalKeysFromSession(
formatProvisionalKeysRequest(provIdentity, localUser),
);
}
return toTankerProvisionalKeys(tankerProvisionalKeysReply);
}
async refreshProvisionalPrivateKeys() {
const claimBlocks: Array<string> = await this._client.getProvisionalIdentityClaims();
const claimEntries = claimBlocks.map(block => provisionalIdentityClaimFromBlock(block));
const authorDevices = claimEntries.map(entry => entry.author);
const authorDeviceKeysMap = await this._userManager.getDeviceKeysByDevicesIds(authorDevices, { isLight: true });
for (let i = 0, length = claimEntries.length; i < length; i++) {
const claimEntry = claimEntries[i]!;
const authorDevicePublicSignatureKey = authorDeviceKeysMap.get(utils.toBase64(authorDevices[i]!));
if (!authorDevicePublicSignatureKey) {
throw new InternalError('refreshProvisionalPrivateKeys: author device should have a public signature key');
}
verifyProvisionalIdentityClaim(claimEntry, authorDevicePublicSignatureKey, this._localUserManager.localUser.userId);
const privateProvisionalKeys = await this._decryptPrivateProvisionalKeys(claimEntry.recipient_user_public_key, claimEntry.encrypted_provisional_identity_private_keys);
await this._localUserManager.addProvisionalUserKey(
claimEntry.app_provisional_identity_signature_public_key,
claimEntry.tanker_provisional_identity_signature_public_key,
privateProvisionalKeys,
);
}
}
async _decryptPrivateProvisionalKeys(recipientUserPublicKey: Uint8Array, encryptedPrivateProvisionalKeys: Uint8Array): Promise<PrivateProvisionalKeys> {
const userKeyPair = (await this._localUserManager.findUserKey(recipientUserPublicKey))!;
const provisionalUserPrivateKeys = tcrypto.sealDecrypt(encryptedPrivateProvisionalKeys, userKeyPair);
const appEncryptionKeyPair = tcrypto.getEncryptionKeyPairFromPrivateKey(new Uint8Array(provisionalUserPrivateKeys.subarray(0, tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE)));
const tankerEncryptionKeyPair = tcrypto.getEncryptionKeyPairFromPrivateKey(new Uint8Array(provisionalUserPrivateKeys.subarray(tcrypto.ENCRYPTION_PUBLIC_KEY_SIZE)));
return {
appEncryptionKeyPair,
tankerEncryptionKeyPair,
};
}
async _claimProvisionalIdentity(provisionalIdentity: SecretProvisionalIdentity, tankerKeys: TankerProvisionalKeys): Promise<void> {
await this._localUserManager.updateLocalUser({ isLight: true });
const appProvisionalUserPrivateSignatureKey = utils.fromBase64(provisionalIdentity.private_signature_key);
const appProvisionalUserPrivateEncryptionKey = utils.fromBase64(provisionalIdentity.private_encryption_key);
const provisionalUserKeys = {
...tankerKeys,
appEncryptionKeyPair: tcrypto.getEncryptionKeyPairFromPrivateKey(appProvisionalUserPrivateEncryptionKey),
appSignatureKeyPair: tcrypto.getSignatureKeyPairFromPrivateKey(appProvisionalUserPrivateSignatureKey),
};
const {
userId,
deviceId,
currentUserKey,
} = this._localUserManager.localUser;
const {
payload,
nature,
} = makeProvisionalIdentityClaim(userId, deviceId, currentUserKey.publicKey, provisionalUserKeys);
const block = this._localUserManager.localUser.makeBlock(payload, nature);
await this._client.claimProvisionalIdentity({ provisional_identity_claim: block });
}
} | the_stack |
import { ComponentOptions } from '../Base/ComponentOptions';
import { IQueryResult } from '../../rest/QueryResult';
import { HighlightUtils, StringAndHoles } from '../../utils/HighlightUtils';
import { Initialization } from '../Base/Initialization';
import { Utils } from '../../utils/Utils';
import { $$ } from '../../utils/Dom';
import { exportGlobally } from '../../GlobalExports';
import 'styling/_PrintableUri';
import { ResultLink } from '../ResultLink/ResultLink';
import { IResultLinkOptions } from '../ResultLink/ResultLinkOptions';
import { IResultsComponentBindings } from '../Base/ResultsComponentBindings';
import { getRestHighlightsForAllTerms, DefaultStreamHighlightOptions } from '../../utils/StreamHighlightUtils';
import * as _ from 'underscore';
import { ComponentOptionsModel } from '../../models/ComponentOptionsModel';
import { Component } from '../Base/Component';
import { IHighlight } from '../../rest/Highlight';
import { AccessibleButton } from '../../utils/AccessibleButton';
import { DeviceUtils } from '../../utils/DeviceUtils';
import { l } from '../../strings/Strings';
export interface IPrintableUriOptions extends IResultLinkOptions {}
interface IPrintableUriRenderOptions {
parents: Element[];
firstIndexToRender: number;
maxNumOfParts: number;
}
/**
* The `PrintableUri` component inherits from the [ `ResultLink` ]{@link ResultLink} component and supports all of its options.
*
* This component displays the URI, or path, to access a result.
*
* This component is a result template component (see [Result Templates](https://docs.coveo.com/en/413/)).
*/
export class PrintableUri extends Component {
static ID = 'PrintableUri';
static options: IPrintableUriOptions = {};
static doExport = () => {
exportGlobally({
PrintableUri: PrintableUri
});
};
private links: ResultLink[] = [];
/**
* Creates a new PrintableUri.
* @param element The HTMLElement on which to instantiate the component.
* @param options The options for the PrintableUri component.
* @param bindings The bindings that the component requires to function normally. If not set, these will be
* automatically resolved (with a slower execution time).
* @param result The result to associate the component with.
*/
constructor(
public element: HTMLElement,
public options: IPrintableUriOptions,
public bindings?: IResultsComponentBindings,
public result?: IQueryResult
) {
super(element, PrintableUri.ID, bindings);
this.options = ComponentOptions.initComponentOptions(element, PrintableUri, options);
this.options = _.extend({}, this.options, this.componentOptionsModel.get(ComponentOptionsModel.attributesEnum.resultLink));
this.renderUri(this.result);
this.addAccessibilityAttributes();
}
/**
* Opens the result in the same window, no matter how the actual component is configured for the end user.
* @param logAnalytics Specifies whether the method should log an analytics event.
*/
public openLink(logAnalytics = true) {
_.last(this.links).openLink(logAnalytics);
}
/**
* Opens the result in a new window, no matter how the actual component is configured for the end user.
* @param logAnalytics Specifies whether the method should log an analytics event.
*/
public openLinkInNewWindow(logAnalytics = true) {
_.last(this.links).openLinkInNewWindow(logAnalytics);
}
/**
* Opens the link in the same manner the end user would.
*
* This essentially simulates a click on the result link.
*
* @param logAnalytics Specifies whether the method should log an analytics event.
*/
public openLinkAsConfigured(logAnalytics = true) {
_.last(this.links).openLinkAsConfigured(logAnalytics);
}
private renderUri(result: IQueryResult) {
const parentsXml = Utils.getFieldValue(result, 'parents');
if (parentsXml) {
this.renderParents({
parents: this.parseXmlParents(parentsXml),
firstIndexToRender: 0,
maxNumOfParts: DeviceUtils.isMobileDevice() ? 3 : 5
});
} else if (this.options.titleTemplate) {
const link = new ResultLink(this.buildElementForResultLink(result.printableUri), this.options, this.bindings, this.result);
this.links.push(link);
this.element.appendChild(this.makeLinkAccessible(link.element));
} else {
this.renderShortenedUri();
}
}
private buildSeparator(): HTMLElement {
const separator = $$('span', { className: 'coveo-printable-uri-separator', role: 'separator' }, ' > ');
return separator.el;
}
private buildHtmlToken(name: string, uri: string): HTMLElement {
let modifiedName = name.charAt(0).toUpperCase() + name.slice(1);
const resultPart: IQueryResult = _.extend({}, this.result, {
clickUri: uri,
title: modifiedName,
titleHighlights: this.getModifiedHighlightsForModifiedResultTitle(modifiedName)
});
const link = new ResultLink(this.buildElementForResultLink(modifiedName), this.options, this.bindings, resultPart);
this.links.push(link);
return link.element;
}
private parseXmlParents(parentsXml: string): Element[] {
const elements = Utils.parseXml(parentsXml).getElementsByTagName('parent');
const parents: Element[] = [];
for (let i = 0; i < elements.length; i++) {
parents.push(elements.item(i));
}
return parents;
}
private renderParents(renderOptions: IPrintableUriRenderOptions) {
$$(this.element).empty();
const lastIndex = renderOptions.parents.length - 1;
const beforeLastIndex = lastIndex - 1;
const maxMiddleParts = renderOptions.maxNumOfParts - 1;
const lastMiddlePartIndex = Math.min(beforeLastIndex, renderOptions.firstIndexToRender + maxMiddleParts - 1);
const partsBetweenMiddlePartsAndLastPart = beforeLastIndex - lastMiddlePartIndex;
this.optionallyRenderFirstEllipsis(renderOptions);
this.renderMiddleParts(renderOptions, lastMiddlePartIndex);
if (partsBetweenMiddlePartsAndLastPart > 0) {
this.renderLastEllipsis({
...renderOptions,
firstIndexToRender: Math.min(Math.max(lastMiddlePartIndex + 1, 0), renderOptions.parents.length - renderOptions.maxNumOfParts)
});
}
this.renderLastPart(renderOptions);
}
private optionallyRenderFirstEllipsis(nextRenderOptions: IPrintableUriRenderOptions) {
if (nextRenderOptions.firstIndexToRender > 0) {
this.appendEllipsis({
...nextRenderOptions,
firstIndexToRender: Math.max(0, nextRenderOptions.firstIndexToRender - nextRenderOptions.maxNumOfParts + 1)
});
this.appendSeparator();
}
}
private renderMiddleParts(renderOptions: IPrintableUriRenderOptions, lastIndexToRender: number) {
for (let i = renderOptions.firstIndexToRender; i <= lastIndexToRender; i++) {
if (i > renderOptions.firstIndexToRender) {
this.appendSeparator();
}
this.appendToken(renderOptions.parents[i]);
}
}
private renderLastEllipsis(nextRenderOptions: IPrintableUriRenderOptions) {
this.appendSeparator();
this.appendEllipsis(nextRenderOptions);
}
private renderLastPart(renderOptions: IPrintableUriRenderOptions) {
this.appendSeparator();
this.appendToken(renderOptions.parents[renderOptions.parents.length - 1]);
}
private appendSeparator() {
this.element.appendChild(this.buildSeparator());
}
private appendEllipsis(nextRenderOptions: IPrintableUriRenderOptions) {
this.element.appendChild(
this.buildEllipsis(() => {
this.renderParents(nextRenderOptions);
(this.element.firstChild.firstChild as HTMLElement).focus();
})
);
}
private appendToken(part: Element) {
this.element.appendChild(this.makeLinkAccessible(this.buildHtmlToken(part.getAttribute('name'), part.getAttribute('uri'))));
}
private renderShortenedUri() {
let stringAndHoles: StringAndHoles;
if (this.result.printableUri.indexOf('\\') == -1) {
stringAndHoles = StringAndHoles.shortenUri(this.result.printableUri, $$(this.element).width());
} else {
stringAndHoles = StringAndHoles.shortenPath(this.result.printableUri, $$(this.element).width());
}
const shortenedUri = HighlightUtils.highlightString(
stringAndHoles.value,
this.result.printableUriHighlights,
stringAndHoles.holes,
'coveo-highlight'
);
const resultPart: IQueryResult = _.extend({}, this.result, {
title: shortenedUri,
titleHighlights: this.getModifiedHighlightsForModifiedResultTitle(shortenedUri)
});
const link = new ResultLink(this.buildElementForResultLink(this.result.printableUri), this.options, this.bindings, resultPart);
this.links.push(link);
this.element.appendChild(this.makeLinkAccessible(link.element));
}
private makeLinkAccessible(link: HTMLElement) {
return $$(
'span',
{
className: 'coveo-printable-uri-part',
role: 'listitem'
},
link
).el;
}
private buildEllipsis(action: (e: Event) => void) {
const button = $$('button', { type: 'button' }, '...');
const element = $$(
'span',
{
className: 'coveo-printable-uri-ellipsis',
role: 'listitem'
},
button
).el;
new AccessibleButton().withElement(button).withLabel(l('CollapsedUriParts')).withSelectAction(action).build();
return element;
}
private buildElementForResultLink(title: string): HTMLElement {
return $$('a', {
className: 'CoveoResultLink',
title
}).el;
}
private getModifiedHighlightsForModifiedResultTitle(newTitle: string): IHighlight[] {
return getRestHighlightsForAllTerms(
newTitle,
this.result.termsToHighlight,
this.result.phrasesToHighlight,
new DefaultStreamHighlightOptions()
);
}
private addAccessibilityAttributes() {
this.element.setAttribute('role', 'list');
}
}
PrintableUri.options = _.extend({}, PrintableUri.options, ResultLink.options);
Initialization.registerAutoCreateComponent(PrintableUri); | the_stack |
import getModuleInfos from './parse-graphql/get-module-infos';
import * as fs from 'fs';
import * as path from 'path';
// @ts-ignore
import * as shelljs from 'shelljs';
import configureDebug from 'debug';
import { Source, buildSchema } from 'graphql';
import { pascalCase } from 'pascal-case';
import getModuleNames from './parse-graphql/getModuleNames';
import getFederatedEntities from './parse-graphql/getFederatedEntities';
import getInterfaces from './parse-graphql/getInterfaces';
import getScalars from './parse-graphql/getScalars';
// import checkIfGitStateClean from './helpers/checkIfGitStateClean';
import { saveRenderedTemplate } from './helpers/saveRenderedTemplate';
import { findProjectMainPath } from './helpers/findProjectMainPath';
import { execQuietly } from './helpers/execQuietly';
const debug = configureDebug('generate-module');
const generateSchema = async (projectMainPath: string) => {
await execQuietly(`ts-node -r tsconfig-paths/register ./generated/graphql/printSchema.ts > ./schema.graphql`, {
cwd: projectMainPath,
});
};
export const executeGeneration = async (appPrefix = '~app', generatedPrefix = '~generated', modulesPath = 'src/') => {
const capitalize = (string: string) => string.charAt(0).toUpperCase() + string.slice(1);
const projectMainPath = findProjectMainPath();
shelljs.mkdir('-p', `${projectMainPath}/generated/graphql/helpers`);
// "Framework" "generated" files - initial generation
const createCombineSchemas = () => {
const templateName = './templates/combineSchemas.ts';
const filePath = `${projectMainPath}/generated/graphql/`;
const fileName = 'combineSchemas.ts';
saveRenderedTemplate(templateName, {}, filePath, fileName);
};
debug('createCombineSchemas');
createCombineSchemas();
const createPrintSchema = () => {
const templateName = './templates/printSchema.ts';
const filePath = `${projectMainPath}/generated/graphql/`;
const fileName = 'printSchema.ts';
saveRenderedTemplate(templateName, {}, filePath, fileName);
};
debug('createPrintSchema');
createPrintSchema();
const createGenericDataModelSchema = () => {
const templateName = './templates/genericDataModelSchema.graphql';
const filePath = `${projectMainPath}/generated/graphql/`;
const fileName = 'genericDataModelSchema.graphql';
saveRenderedTemplate(templateName, {}, filePath, fileName);
};
debug('createGenericDataModelSchema');
createGenericDataModelSchema();
const createFrameworkSchema = () => {
const templateName = './templates/frameworkSchema.graphql';
const filePath = `${projectMainPath}/generated/graphql/`;
const fileName = 'frameworkSchema.graphql';
saveRenderedTemplate(templateName, {}, filePath, fileName);
};
debug('createFrameworkSchema');
createFrameworkSchema();
const createGetCodegenConfig = () => {
const templateName = './templates/getCodegenConfig.js';
const filePath = `${projectMainPath}/generated/graphql/`;
const fileName = 'getCodegenConfig.js';
saveRenderedTemplate(templateName, { appPrefix }, filePath, fileName);
};
debug('createGetCodegenConfig');
createGetCodegenConfig();
const modulesResolvedPath = path.join(projectMainPath, modulesPath);
const graphqlPaths = shelljs.ls(path.join(modulesResolvedPath, '**/*.graphql'));
const moduleNames = getModuleNames(graphqlPaths, projectMainPath);
const modules = getModuleInfos(moduleNames);
const createGlobalResolvers = () => {
const templateName = './templates/resolvers.handlebars';
const context = { modules };
const filePath = `${projectMainPath}/generated/graphql/`;
const fileName = 'resolvers.ts';
saveRenderedTemplate(templateName, context, filePath, fileName);
};
debug('createGlobalResolvers');
createGlobalResolvers();
// End of "Framework" "generated" files
// Initial App Setup files
debug('generateSchema');
await generateSchema(projectMainPath);
const globalSchemaString = fs.readFileSync(path.join(projectMainPath, 'schema.graphql')); // read file
const createGlobalSchema = () => {
const templateName = './templates/schema.ts';
const context = { modules, schemaString: globalSchemaString.toString().replace(/`/g, '\\`'), generatedPrefix };
const filePath = `${projectMainPath}/generated/graphql/`;
const fileName = 'schema.ts';
saveRenderedTemplate(templateName, context, filePath, fileName);
};
debug('createGlobalSchema');
createGlobalSchema();
modules.forEach((module) => {
const moduleName = module.name;
const { graphqlFileRootPath } = module;
const createQuery = (queryName: string, hasArguments: boolean) => {
const templateName = './templates/query.handlebars';
const context = {
queryName,
moduleName,
hasArguments,
generatedPrefix,
};
const filePath = `${projectMainPath}/src/${graphqlFileRootPath}/queries/`;
const fileName = `${queryName}Query.ts`;
const keepIfExists = true;
saveRenderedTemplate(templateName, context, filePath, fileName, keepIfExists);
};
const createQuerySpec = (queryName: string, hasArguments: boolean) => {
const templateName = './templates/query.spec.handlebars';
const context = {
queryName,
moduleName,
hasArguments,
generatedPrefix,
pascalCasedArgName: `Query${pascalCase(queryName)}Args`,
};
const filePath = `${projectMainPath}/src/${graphqlFileRootPath}/queries/`;
const fileName = `${queryName}Query.spec.ts`;
const keepIfExists = true;
saveRenderedTemplate(templateName, context, filePath, fileName, keepIfExists);
};
const createQuerySpecWrapper = (queryName: string, hasArguments: boolean) => {
const templateName = './templates/querySpecWrapper.handlebars';
const context = {
queryName,
moduleName,
hasArguments,
generatedPrefix,
appPrefix,
graphqlFileRootPath,
pascalCasedArgName: `Query${pascalCase(queryName)}Args`,
};
const filePath = `${projectMainPath}/generated/graphql/helpers/`;
const fileName = `${queryName}QuerySpecWrapper.ts`;
const keepIfExists = false;
saveRenderedTemplate(templateName, context, filePath, fileName, keepIfExists);
};
if (module.queries && module.queries.length > 0) {
shelljs.mkdir('-p', `${projectMainPath}/src/${graphqlFileRootPath}/queries`);
module.queries.forEach(({ name, hasArguments }: { name: string; hasArguments: boolean }) => {
createQuery(name, hasArguments);
createQuerySpec(name, hasArguments);
createQuerySpecWrapper(name, hasArguments);
});
}
const createMutation = (mutationName: string, hasArguments: boolean) => {
const templateName = './templates/mutation.handlebars';
const context = {
mutationName,
moduleName,
hasArguments,
generatedPrefix,
};
const filePath = `${projectMainPath}/src/${graphqlFileRootPath}/mutations/`;
const fileName = `${mutationName}Mutation.ts`;
const keepIfExists = true;
saveRenderedTemplate(templateName, context, filePath, fileName, keepIfExists);
};
const createMutationSpec = (mutationName: string, hasArguments: boolean) => {
const templateName = './templates/mutation.spec.handlebars';
const context = {
mutationName,
moduleName,
hasArguments,
generatedPrefix,
appPrefix,
graphqlFileRootPath,
pascalCasedArgName: `Mutation${pascalCase(mutationName)}Args`,
};
const filePath = `${projectMainPath}/src/${graphqlFileRootPath}/mutations/`;
const fileName = `${mutationName}Mutation.spec.ts`;
const keepIfExists = true;
saveRenderedTemplate(templateName, context, filePath, fileName, keepIfExists);
};
const createMutationSpecWrapper = (mutationName: string, hasArguments: boolean) => {
const templateName = './templates/mutationSpecWrapper.handlebars';
const context = {
mutationName,
moduleName,
hasArguments,
generatedPrefix,
appPrefix,
graphqlFileRootPath,
pascalCasedArgName: `Mutation${pascalCase(mutationName)}Args`,
};
const filePath = `${projectMainPath}/generated/graphql/helpers/`;
const fileName = `${mutationName}MutationSpecWrapper.ts`;
const keepIfExists = false;
saveRenderedTemplate(templateName, context, filePath, fileName, keepIfExists);
};
if (module.mutations && module.mutations.length > 0) {
shelljs.mkdir('-p', `${projectMainPath}/src/${graphqlFileRootPath}/mutations`);
module.mutations.forEach(({ name, hasArguments }) => {
createMutation(name, hasArguments);
createMutationSpec(name, hasArguments);
createMutationSpecWrapper(name, hasArguments);
});
}
});
const createTypeResolvers = () => {
modules.forEach(({ name, typeDefinitions, types, schemaString, queries, mutations, graphqlFileRootPath }) => {
const typeResolvers: { typeName: string; fieldName: { name: string; capitalizedName: string }[] }[] = [];
if (types) {
debug(`create type resolvers for module ${name}`);
const federatedEntities = getFederatedEntities(schemaString);
const interfaces = getInterfaces(schemaString);
// Leaving this for now
// eslint-disable-next-line no-param-reassign
schemaString = schemaString.replace(/extend type/g, 'type');
const source = new Source(schemaString);
const schema = buildSchema(source, { assumeValidSDL: true });
shelljs.mkdir('-p', `${projectMainPath}/src/${graphqlFileRootPath}/types/`);
const createInterfaceType = (interfaceName: string) => {
const templateName = './templates/typeTypeResolvers.handlebars';
const capitalizedFieldName = capitalize('__resolveType');
const context = {
typeName: interfaceName,
fieldName: '__resolveType',
moduleName: name,
resolveReferenceType: true,
capitalizedFieldName,
generatedPrefix,
};
const filePath = `${projectMainPath}/src/${graphqlFileRootPath}/types/`;
const fileName = `${interfaceName}${capitalizedFieldName}.ts`;
const keepIfExists = true;
saveRenderedTemplate(templateName, context, filePath, fileName, keepIfExists);
};
const createInterfaceSpec = (interfaceName: string) => {
const templateName = './templates/typeTypeResolvers.spec.handlebars';
const capitalizedFieldName = capitalize('__resolveType');
const context = {
typeName: interfaceName,
fieldName: '__resolveType',
moduleName: name,
hasArguments: false,
resolveReferenceType: true,
capitalizedFieldName,
generatedPrefix,
};
const filePath = `${projectMainPath}/src/${graphqlFileRootPath}/types/`;
const fileName = `${interfaceName}${capitalizedFieldName}.spec.ts`;
const keepIfExists = true;
saveRenderedTemplate(templateName, context, filePath, fileName, keepIfExists);
};
const createInterfaceSpecWrapper = (interfaceName: string) => {
const templateName = './templates/typeTypeResolversSpecWrapper.handlebars';
const capitalizedFieldName = capitalize('__resolveType');
const context = {
typeName: interfaceName,
fieldName: '__resolveType',
moduleName: name,
hasArguments: false,
resolveReferenceType: true,
capitalizedFieldName,
generatedPrefix,
appPrefix,
graphqlFileRootPath,
};
const filePath = `${projectMainPath}/generated/graphql/helpers/`;
const fileName = `${interfaceName}${capitalizedFieldName}SpecWrapper.ts`;
const keepIfExists = false;
saveRenderedTemplate(templateName, context, filePath, fileName, keepIfExists);
};
interfaces.forEach((interfaceName) => {
createInterfaceType(interfaceName);
createInterfaceSpec(interfaceName);
createInterfaceSpecWrapper(interfaceName);
typeResolvers.push({
typeName: interfaceName,
fieldName: [{ name: '__resolveType', capitalizedName: capitalize('__resolveType') }],
});
});
type FilteredType = { name: { value: string }; resolveReferenceType: boolean; arguments?: string[] };
typeDefinitions.forEach((typeDef) => {
let filtered: FilteredType[] = [];
let type = schema.getType(typeDef.name);
if (!type) {
const newSchemaString = schemaString.replace(`extend type ${typeDef.name}`, `type ${typeDef.name}`);
type = buildSchema(new Source(newSchemaString)).getType(typeDef.name);
}
if (type?.astNode) {
// @ts-ignore
filtered = type.astNode.fields.filter((field) =>
field.directives.find(
(d: { name: { value: string } }) =>
d.name.value === 'computed' ||
d.name.value === 'link' ||
d.name.value === 'requires' ||
d.name.value === 'map',
),
);
}
let isFederatedAndExternal = false;
if (federatedEntities.find((e) => e === typeDef.name)) {
isFederatedAndExternal =
Boolean(type!.astNode) &&
Boolean(
// @ts-ignore
type?.astNode.fields.find((field) => field.directives.find((d) => d.name.value === 'external')),
);
const foundComputed = type?.astNode?.directives?.find((d) => d.name.value === 'computed');
const notComputed = Boolean(!foundComputed);
// If it's a federated and external but NOT marked with a computed directive, we do not want to
// create the resolveReference files for it.
if (!(isFederatedAndExternal && notComputed)) {
filtered.push({ name: { value: '__resolveReference' }, resolveReferenceType: true });
}
}
filtered.forEach(({ name: { value }, resolveReferenceType }) => {
const templateName = './templates/typeTypeResolvers.handlebars';
const capitalizedFieldName = capitalize(value);
const context = {
typeName: typeDef.name,
fieldName: value,
moduleName: name,
resolveReferenceType,
capitalizedFieldName,
generatedPrefix,
};
const filePath = `${projectMainPath}/src/${graphqlFileRootPath}/types/`;
const fileName = `${typeDef.name}${capitalizedFieldName}.ts`;
const keepIfExists = true;
saveRenderedTemplate(templateName, context, filePath, fileName, keepIfExists);
});
const createTypeFieldResolverSpec = (
value: string,
resolveReferenceType: boolean,
resolverArguments?: string[],
) => {
const templateName = './templates/typeTypeResolvers.spec.handlebars';
const capitalizedFieldName = capitalize(value);
const context = {
typeName: typeDef.name,
fieldName: value,
moduleName: name,
hasArguments: resolverArguments && resolverArguments.length,
resolveReferenceType,
capitalizedFieldName,
generatedPrefix,
pascalCasedArgName: `${typeDef.name}${pascalCase(capitalizedFieldName)}Args`,
};
const filePath = `${projectMainPath}/src/${graphqlFileRootPath}/types/`;
const fileName = `${typeDef.name}${capitalizedFieldName}.spec.ts`;
const keepIfExists = true;
saveRenderedTemplate(templateName, context, filePath, fileName, keepIfExists);
};
const createTypeFieldResolverSpecWrapper = (
value: string,
resolveReferenceType: boolean,
resolverArguments?: string[],
) => {
const templateName = './templates/typeTypeResolversSpecWrapper.handlebars';
const capitalizedFieldName = capitalize(value);
const context = {
typeName: typeDef.name,
fieldName: value,
moduleName: name,
hasArguments: resolverArguments && resolverArguments.length,
resolveReferenceType,
capitalizedFieldName,
generatedPrefix,
appPrefix,
graphqlFileRootPath,
isFederatedAndExternal,
pascalCasedArgName: `${typeDef.name}${pascalCase(capitalizedFieldName)}Args`,
};
const filePath = `${projectMainPath}/generated/graphql/helpers/`;
const fileName = `${typeDef.name}${capitalizedFieldName}SpecWrapper.ts`;
const keepIfExists = true;
saveRenderedTemplate(templateName, context, filePath, fileName, keepIfExists);
};
filtered.forEach(({ name: { value }, arguments: resolverArguments, resolveReferenceType }) => {
createTypeFieldResolverSpec(value, resolveReferenceType, resolverArguments);
createTypeFieldResolverSpecWrapper(value, resolveReferenceType, resolverArguments);
});
if (filtered.length > 0) {
typeResolvers.push({
typeName: typeDef.name,
fieldName: filtered.map(({ name: { value } }) => ({ name: value, capitalizedName: capitalize(value) })),
});
}
});
}
const scalars = getScalars(schemaString);
const createScalarResolvers = () => {
if (scalars && scalars.length > 0) {
shelljs.mkdir('-p', `${projectMainPath}/src/${graphqlFileRootPath}/scalars/`);
}
scalars.forEach((scalarName) => {
const templateName = './templates/scalarResolver.handlebars';
const context = {
scalarName,
moduleName: name,
generatedPrefix,
};
const filePath = `${projectMainPath}/src/${graphqlFileRootPath}/scalars/`;
const fileName = `${scalarName}.ts`;
const keepIfExists = true;
saveRenderedTemplate(templateName, context, filePath, fileName, keepIfExists);
});
};
createScalarResolvers();
const moduleName = name;
const createModuleResolvers = () => {
const templateName = './templates/moduleResolvers.handlebars';
const context = {
moduleName,
queries,
mutations,
typeResolvers,
graphqlFileRootPath,
appPrefix,
scalars,
};
const filePath = `${projectMainPath}/generated/graphql/`;
const fileName = `${moduleName}Resolvers.ts`;
saveRenderedTemplate(templateName, context, filePath, fileName);
};
createModuleResolvers();
});
};
debug('createTypeResolvers');
createTypeResolvers();
}; | the_stack |
import chalk from 'chalk'
import ora from 'ora'
import { find, cloneDeep } from 'lodash'
import { prompt } from 'inquirer'
import { table, getBorderCharacters } from 'table'
import untildify from 'untildify'
import { existsSync } from 'fs-extra'
import { createManifest } from './helpers'
import { ServerClient } from 'postmark'
import {
TemplateManifest,
TemplatePushResults,
TemplatePushReview,
TemplatePushArguments,
Templates,
ProcessTemplates,
} from '../../types'
import { pluralize, log, validateToken } from '../../utils'
let pushManifest: TemplateManifest[] = []
export const command = 'push <templates directory> [options]'
export const desc =
'Push templates from <templates directory> to a Postmark server'
export const builder = {
'server-token': {
type: 'string',
hidden: true,
},
'request-host': {
type: 'string',
hidden: true,
},
force: {
type: 'boolean',
describe: 'Disable confirmation before pushing templates',
alias: 'f',
},
all: {
type: 'boolean',
describe:
'Push all local templates up to Postmark regardless of whether they changed',
alias: 'a',
},
}
export const handler = (args: TemplatePushArguments) => exec(args)
/**
* Execute the command
*/
const exec = (args: TemplatePushArguments) => {
const { serverToken } = args
return validateToken(serverToken).then(token => {
validateDirectory(token, args)
})
}
/**
* Check if directory exists before pushing
*/
const validateDirectory = (
serverToken: string,
args: TemplatePushArguments
) => {
const rootPath: string = untildify(args.templatesdirectory)
// Check if path exists
if (!existsSync(rootPath)) {
log('The provided path does not exist', { error: true })
return process.exit(1)
}
return push(serverToken, args)
}
/**
* Begin pushing the templates
*/
const push = (serverToken: string, args: TemplatePushArguments) => {
const { templatesdirectory, force, requestHost, all } = args
const spinner = ora('Fetching templates...').start()
const manifest = createManifest(templatesdirectory)
const client = new ServerClient(serverToken)
if (requestHost !== undefined && requestHost !== '') {
client.clientOptions.requestHost = requestHost
}
// Make sure manifest isn't empty
if (manifest.length > 0) {
// Get template list from Postmark
client
.getTemplates({ count: 300 })
.then(response => {
// Check if there are templates on the server
if (response.TotalCount === 0) {
processTemplates({
newList: [],
manifest: manifest,
all: all,
force: force,
spinner: spinner,
client: client,
})
} else {
// Gather template content before processing templates
getTemplateContent(client, response).then(newList => {
processTemplates({
newList: newList,
manifest: manifest,
all: all,
force: force,
spinner: spinner,
client: client,
})
})
}
})
.catch((error: any) => {
spinner.stop()
log(error, { error: true })
process.exit(1)
})
} else {
spinner.stop()
log('No templates or layouts were found.', { error: true })
process.exit(1)
}
}
/**
* Compare templates and CLI flow
*/
const processTemplates = (config: ProcessTemplates) => {
const { newList, manifest, all, force, spinner, client } = config
compareTemplates(newList, manifest, all)
spinner.stop()
if (pushManifest.length === 0) return log('There are no changes to push.')
// Show which templates are changing
printReview(review)
// Push templates if force arg is present
if (force) {
spinner.text = 'Pushing templates to Postmark...'
spinner.start()
return pushTemplates(spinner, client, pushManifest)
}
// Ask for user confirmation
confirmation().then(answer => {
if (answer.confirm) {
spinner.text = 'Pushing templates to Postmark...'
spinner.start()
pushTemplates(spinner, client, pushManifest)
} else {
log('Canceling push. Have a good day!')
}
})
}
/**
* Gather template content from server to compare against local versions
*/
const getTemplateContent = (
client: any,
templateList: Templates
): Promise<any> =>
new Promise<TemplateManifest[]>(resolve => {
let newList: any[] = cloneDeep(templateList.Templates)
let progress = 0
newList.forEach((template, index) => {
client
.getTemplate(template.TemplateId)
.then((result: TemplateManifest) => {
newList[index] = {
...newList[index],
HtmlBody: result.HtmlBody,
TextBody: result.TextBody,
Subject: result.Subject,
TemplateType: result.TemplateType,
LayoutTemplate: result.LayoutTemplate,
}
progress++
if (progress === newList.length) {
return resolve(newList)
}
})
})
})
/**
* Ask user to confirm the push
*/
const confirmation = (): Promise<any> =>
new Promise<string>((resolve, reject) => {
prompt([
{
type: 'confirm',
name: 'confirm',
default: false,
message: `Would you like to continue?`,
},
])
.then((answer: any) => resolve(answer))
.catch((err: any) => reject(err))
})
/**
* Compare templates on server against local
*/
const compareTemplates = (
response: TemplateManifest[],
manifest: TemplateManifest[],
pushAll: boolean
): void => {
// Iterate through manifest
manifest.forEach(template => {
// See if this local template exists on the server
const match = find(response, { Alias: template.Alias })
template.New = !match
// New template
if (!match) {
template.Status = chalk.green('Added')
return pushTemplatePreview(match, template)
}
// Set modification status
const modified = wasModified(match, template)
template.Status = modified
? chalk.yellow('Modified')
: chalk.gray('Unmodified')
// Push all templates if --all argument is present,
// regardless of whether templates were modified
if (pushAll) {
return pushTemplatePreview(match, template)
}
// Only push modified templates
if (modified) {
return pushTemplatePreview(match, template)
}
})
}
/**
* Check if local template is different than server
*/
const wasModified = (
server: TemplateManifest,
local: TemplateManifest
): boolean => {
const htmlModified = server.HtmlBody !== local.HtmlBody
const textModified = server.TextBody !== local.TextBody
const subjectModified =
local.TemplateType === 'Standard' ? server.Subject !== local.Subject : false
const nameModified = server.Name !== local.Name
const layoutModified =
local.TemplateType === 'Standard'
? server.LayoutTemplate !== local.LayoutTemplate
: false
return (
htmlModified ||
textModified ||
subjectModified ||
nameModified ||
layoutModified
)
}
/**
* Push template details to review table
*/
const pushTemplatePreview = (
match: any,
template: TemplateManifest
): number => {
pushManifest.push(template)
let reviewData = [template.Status, template.Name, template.Alias]
// Push layout to review table
if (template.TemplateType === 'Layout') return review.layouts.push(reviewData)
// Push template to review table
// Add layout used column
reviewData.push(
layoutUsedLabel(
template.LayoutTemplate,
match ? match.LayoutTemplate : template.LayoutTemplate
)
)
return review.templates.push(reviewData)
}
/**
* Render the "Layout used" column for Standard templates
*/
const layoutUsedLabel = (
localLayout: string | null | undefined,
serverLayout: string | null | undefined
): string => {
let label: string = localLayout ? localLayout : chalk.gray('None')
// If layout template on server doesn't match local template
if (localLayout !== serverLayout) {
serverLayout = serverLayout ? serverLayout : 'None'
// Append old server layout to label
label += chalk.red(` ✘ ${serverLayout}`)
}
return label
}
/**
* Show which templates will change after the publish
*/
const printReview = (review: TemplatePushReview) => {
const { templates, layouts } = review
// Table headers
const header = [chalk.gray('Status'), chalk.gray('Name'), chalk.gray('Alias')]
const templatesHeader = [...header, chalk.gray('Layout used')]
// Labels
const templatesLabel =
templates.length > 0
? `${templates.length} ${pluralize(
templates.length,
'template',
'templates'
)}`
: ''
const layoutsLabel =
layouts.length > 0
? `${layouts.length} ${pluralize(layouts.length, 'layout', 'layouts')}`
: ''
// Log template and layout files
if (templates.length > 0) {
log(`\n${templatesLabel}`)
log(
table([templatesHeader, ...templates], {
border: getBorderCharacters('norc'),
})
)
}
if (layouts.length > 0) {
log(`\n${layoutsLabel}`)
log(table([header, ...layouts], { border: getBorderCharacters('norc') }))
}
// Log summary
log(
chalk.yellow(
`${templatesLabel}${
templates.length > 0 && layouts.length > 0 ? ' and ' : ''
}${layoutsLabel} will be pushed to Postmark.`
)
)
}
/**
* Push all local templates
*/
const pushTemplates = (
spinner: any,
client: any,
templates: TemplateManifest[]
) => {
templates.forEach(template =>
pushTemplate(spinner, client, template, templates.length)
)
}
/**
* Determine whether to create a new template or edit an existing
*/
const pushTemplate = (
spinner: any,
client: any,
template: TemplateManifest,
total: number
): void => {
if (template.New) {
return client
.createTemplate(template)
.then((response: object) =>
pushComplete(true, response, template, spinner, total)
)
.catch((response: object) =>
pushComplete(false, response, template, spinner, total)
)
}
return client
.editTemplate(template.Alias, template)
.then((response: object) =>
pushComplete(true, response, template, spinner, total)
)
.catch((response: object) =>
pushComplete(false, response, template, spinner, total)
)
}
/**
* Run each time a push has been completed
*/
const pushComplete = (
success: boolean,
response: object,
template: TemplateManifest,
spinner: any,
total: number
) => {
// Update counters
results[success ? 'success' : 'failed']++
const completed = results.success + results.failed
// Log any errors to the console
if (!success) {
spinner.stop()
log(`\n${template.Alias}: ${response.toString()}`, { error: true })
spinner.start()
}
if (completed === total) {
spinner.stop()
log('✅ All finished!', { color: 'green' })
// Show failures
if (results.failed) {
log(
`⚠️ Failed to push ${results.failed} ${pluralize(
results.failed,
'template',
'templates'
)}. Please see the output above for more details.`,
{ error: true }
)
}
}
}
let results: TemplatePushResults = {
success: 0,
failed: 0,
}
let review: TemplatePushReview = {
layouts: [],
templates: [],
} | the_stack |
import { promises as fs } from 'fs'
import ora from 'ora'
import path from 'path'
import { flattenAllApexs } from '../blobs/apex'
import { generateBuild, VendorDirectories, writeBuildFiles } from '../blobs/build'
import { BlobEntry } from '../blobs/entry'
import { combinedPartPathToEntry, diffLists, listPart, serializeBlobList } from '../blobs/file-list'
import { diffPartOverlays, parsePartOverlayApks, serializePartOverlays } from '../blobs/overlays'
import { parsePresignedRecursive, updatePresignedBlobs } from '../blobs/presigned'
import { diffPartitionProps, loadPartitionProps, PartitionProps } from '../blobs/props'
import { diffPartVintfManifests, loadPartVintfInfo, writePartVintfManifests } from '../blobs/vintf'
import { findOverrideModules } from '../build/overrides'
import { removeSelfModules } from '../build/soong-info'
import { DeviceConfig } from '../config/device'
import { filterKeys, Filters, filterValue, filterValues } from '../config/filters'
import { collectSystemState, parseSystemState, SystemState } from '../config/system-state'
import { ANDROID_INFO, extractFactoryFirmware, generateAndroidInfo, writeFirmwareImages } from '../images/firmware'
import {
diffPartContexts,
parseContextsRecursive,
parsePartContexts,
resolvePartContextDiffs,
SelinuxContexts,
SelinuxPartResolutions,
} from '../selinux/contexts'
import { generateFileContexts } from '../selinux/labels'
import { exists, readFile, TempState } from '../util/fs'
import { ALL_SYS_PARTITIONS } from '../util/partitions'
export interface PropResults {
stockProps: PartitionProps
missingProps?: PartitionProps
fingerprint?: string
missingOtaParts: Array<string>
}
export async function loadCustomState(config: DeviceConfig, aapt2Path: string, customSrc: string) {
if ((await fs.stat(customSrc)).isFile()) {
return parseSystemState(await readFile(customSrc))
}
// Try <device>.json
let deviceSrc = `${customSrc}/${config.device.name}.json`
if (await exists(deviceSrc)) {
return parseSystemState(await readFile(deviceSrc))
}
// Otherwise, assume it's AOSP build output
return await collectSystemState(config.device.name, customSrc, aapt2Path)
}
export async function enumerateFiles(
spinner: ora.Ora,
filters: Filters,
forceIncludeFilters: Filters | null,
namedEntries: Map<string, BlobEntry>,
customState: SystemState | null,
stockSrc: string,
) {
for (let partition of ALL_SYS_PARTITIONS) {
let filesRef = await listPart(partition, stockSrc, filters)
if (filesRef == null) continue
let filesNew = customState?.partitionFiles[partition] ?? []
if (filesNew == undefined) continue
let missingFiles = diffLists(filesNew, filesRef)
// Evaluate force-include filters and merge forced files from ref
if (forceIncludeFilters != null) {
let forcedFiles = filterValues(forceIncludeFilters, filesRef)
missingFiles.push(...forcedFiles)
// Re-sort
missingFiles.sort((a, b) => a.localeCompare(b))
}
for (let combinedPartPath of missingFiles) {
let entry = combinedPartPathToEntry(partition, combinedPartPath)
namedEntries.set(combinedPartPath, entry)
}
spinner.text = partition
}
}
export async function resolveOverrides(
config: DeviceConfig,
customState: SystemState,
dirs: VendorDirectories,
namedEntries: Map<string, BlobEntry>,
) {
let targetPrefix = `out/target/product/${config.device.name}/`
let targetPaths = Array.from(namedEntries.keys())
// Never use existing modules for dep files (e.g. generated in prep) to avoid feedback loop
.filter(p => !filterValue(config.filters.dep_files, p))
// Convert to installed paths
.map(cPartPath => `${targetPrefix}${cPartPath}`)
let modulesMap = customState.moduleInfo
removeSelfModules(modulesMap, dirs.proprietary)
let { modules: builtModules, builtPaths } = findOverrideModules(targetPaths, modulesMap)
// Remove new modules from entries
for (let path of builtPaths) {
namedEntries.delete(path.replace(targetPrefix, ''))
}
return builtModules
}
export async function updatePresigned(
spinner: ora.Ora,
config: DeviceConfig,
entries: BlobEntry[],
aapt2Path: string,
stockSrc: string,
) {
let presignedPkgs = await parsePresignedRecursive(config.platform.sepolicy_dirs)
await updatePresignedBlobs(
aapt2Path,
stockSrc,
presignedPkgs,
entries,
entry => {
spinner.text = entry.srcPath
},
config.filters.presigned,
)
}
export async function flattenApexs(
spinner: ora.Ora,
entries: BlobEntry[],
dirs: VendorDirectories,
tmp: TempState,
stockSrc: string,
) {
let apex = await flattenAllApexs(entries, stockSrc, tmp, progress => {
spinner.text = progress
})
// Write context labels
let fileContexts = `${dirs.sepolicy}/file_contexts`
await fs.writeFile(fileContexts, generateFileContexts(apex.labels))
return apex.entries
}
export async function extractProps(config: DeviceConfig, customState: SystemState | null, stockSrc: string) {
let stockProps = await loadPartitionProps(stockSrc)
let customProps = customState?.partitionProps ?? new Map<string, Map<string, string>>()
// Filters
for (let props of stockProps.values()) {
filterKeys(config.filters.props, props)
}
for (let props of customProps.values()) {
filterKeys(config.filters.props, props)
}
// Fingerprint for SafetyNet
let fingerprint = stockProps.get('system')!.get('ro.system.build.fingerprint')!
// Diff
let missingProps: PartitionProps | undefined
if (customProps != null) {
let propChanges = diffPartitionProps(stockProps, customProps)
missingProps = new Map(Array.from(propChanges.entries()).map(([part, props]) => [part, props.removed]))
}
// A/B OTA partitions
let stockOtaParts = stockProps.get('product')!.get('ro.product.ab_ota_partitions')!.split(',')
let customOtaParts = new Set(customProps.get('product')?.get('ro.product.ab_ota_partitions')?.split(',') ?? [])
let missingOtaParts = stockOtaParts.filter(p => !customOtaParts.has(p) && filterValue(config.filters.partitions, p))
return {
stockProps,
missingProps,
fingerprint,
missingOtaParts,
} as PropResults
}
export async function resolveSepolicyDirs(
config: DeviceConfig,
customState: SystemState,
dirs: VendorDirectories,
stockSrc: string,
) {
// Built contexts
let stockContexts = await parsePartContexts(stockSrc)
let customContexts = customState.partitionSecontexts
// Contexts from AOSP
let sourceContexts: SelinuxContexts = new Map<string, string>()
for (let dir of config.platform.sepolicy_dirs) {
// TODO: support alternate ROM root
let contexts = await parseContextsRecursive(dir, '.')
for (let [ctx, source] of contexts.entries()) {
sourceContexts.set(ctx, source)
}
}
// Diff; reversed custom->stock order to get *missing* contexts
let ctxDiffs = diffPartContexts(customContexts, stockContexts)
let ctxResolutions = resolvePartContextDiffs(ctxDiffs, sourceContexts, config.filters.sepolicy_dirs)
// Add APEX labels
if (ctxResolutions.has('vendor')) {
ctxResolutions.get('vendor')!.sepolicyDirs.push(dirs.sepolicy)
}
return ctxResolutions
}
export async function extractOverlays(
spinner: ora.Ora,
config: DeviceConfig,
customState: SystemState,
dirs: VendorDirectories,
aapt2Path: string,
stockSrc: string,
) {
let stockOverlays = await parsePartOverlayApks(
aapt2Path,
stockSrc,
path => {
spinner.text = path
},
config.filters.overlay_files,
)
let customOverlays = customState.partitionOverlays
let missingOverlays = diffPartOverlays(
stockOverlays,
customOverlays,
config.filters.overlay_keys,
config.filters.overlay_values,
)
// Generate RROs and get a list of modules to build
let buildPkgs = await serializePartOverlays(missingOverlays, dirs.overlays)
// Dump overlay key and value lists
if (buildPkgs.length > 0) {
for (let [part, overlays] of Object.entries(missingOverlays)) {
let overlayList = Array.from(overlays.entries())
.map(([k, v]) => `${k} = ${v}`)
.join('\n')
await fs.writeFile(`${dirs.overlays}/${part}.txt`, `${overlayList}\n`)
}
}
return buildPkgs
}
export async function extractVintfManifests(customState: SystemState, dirs: VendorDirectories, stockSrc: string) {
let customVintf = customState.partitionVintfInfo
let stockVintf = await loadPartVintfInfo(stockSrc)
let missingHals = diffPartVintfManifests(customVintf, stockVintf)
return await writePartVintfManifests(missingHals, dirs.vintf)
}
export async function extractFirmware(
config: DeviceConfig,
dirs: VendorDirectories,
stockProps: PartitionProps,
factoryPath: string,
) {
let fwImages = await extractFactoryFirmware(factoryPath)
let fwPaths = await writeFirmwareImages(fwImages, dirs.firmware)
// Generate android-info.txt from device and versions
let androidInfo = generateAndroidInfo(
config.device.name,
stockProps.get('vendor')!.get('ro.build.expect.bootloader')!,
stockProps.get('vendor')!.get('ro.build.expect.baseband')!,
)
await fs.writeFile(`${dirs.firmware}/${ANDROID_INFO}`, androidInfo)
return fwPaths
}
export async function generateBuildFiles(
config: DeviceConfig,
dirs: VendorDirectories,
entries: BlobEntry[],
buildPkgs: string[],
propResults: PropResults | null,
fwPaths: string[] | null,
vintfManifestPaths: Map<string, string> | null,
sepolicyResolutions: SelinuxPartResolutions | null,
stockSrc: string,
addAbOtaParts = true,
enforceAllRros = false,
) {
let build = await generateBuild(entries, config.device.name, config.device.vendor, stockSrc, dirs)
// Add rules to build overridden modules and overlays, then re-sort
build.deviceMakefile!.packages!.push(...buildPkgs)
build.deviceMakefile!.packages!.sort((a, b) => a.localeCompare(b))
// Add device parts
build.deviceMakefile = {
props: propResults?.missingProps,
fingerprint: propResults?.fingerprint,
...(vintfManifestPaths != null && { vintfManifestPaths }),
...build.deviceMakefile,
}
// Add board parts
build.boardMakefile = {
...(sepolicyResolutions != null && { sepolicyResolutions }),
...(propResults != null &&
propResults.missingOtaParts.length > 0 && {
buildPartitions: propResults.missingOtaParts,
...(addAbOtaParts && { abOtaPartitions: propResults.missingOtaParts }),
}),
...(fwPaths != null && { boardInfo: `${dirs.firmware}/${ANDROID_INFO}` }),
}
// Add firmware
if (fwPaths != null) {
build.modulesMakefile!.radioFiles = fwPaths.map(p => path.relative(dirs.out, p))
}
// Create device
if (config.generate.products) {
if (propResults == null) {
throw new Error('Product generation depends on properties')
}
let productProps = propResults.stockProps.get('product')!
let productName = productProps.get('ro.product.product.name')!
build.productMakefile = {
baseProductPath: config.platform.product_makefile,
name: productName,
model: productProps.get('ro.product.product.model')!,
brand: productProps.get('ro.product.product.brand')!,
manufacturer: productProps.get('ro.product.product.manufacturer')!,
}
build.productsMakefile = {
products: [productName],
}
}
// Enforce RROs?
if (enforceAllRros) {
build.deviceMakefile.enforceRros = '*'
if (build.productMakefile != undefined) {
build.productMakefile.enforceRros = '*'
}
}
// Dump blob list
if (entries.length > 0) {
let fileList = serializeBlobList(entries)
await fs.writeFile(`${dirs.out}/proprietary-files.txt`, `${fileList}\n`)
}
await writeBuildFiles(build, dirs)
} | the_stack |
import * as path from "path";
import {expect} from "chai";
import * as fs from "fs";
import Ast, {ts, ScriptTarget, ModuleResolutionKind} from "ts-morph";
import {TsToCSharpGenerator} from "./TStoCSharpGenerator";
import {GenOptions} from "./GenerateOptions";
import {Context} from "./Context";
console.log("");
console.log("TypeScript version: " + ts.version);
console.log("Working Directory: " + __dirname);
const definitionsPath = "./test/definitions";
const casesPath = "./test/cases";
class TestGenOptions extends GenOptions {
constructor ()
{
super();
this.isPrefixInterface = false;
this.isCaseChange = false;
this.interfaceAccessModifier = "";
}
}
function CreateAST() : Ast
{
const ast = new Ast({
compilerOptions: {
target: ScriptTarget.ESNext,
module: ts.ModuleKind.CommonJS,
moduleResolution: ModuleResolutionKind.NodeJs,
noLib: true
}
});
return ast;
}
const interfaceCases = [
{should: "should generate simple interface", file: "Interface"},
{should: "should generate simple interface with closing brackets on separate lines", file: "Interface2"},
{should: "should generate simple interface with leading and trailing comments", file: "Comments"},
{should: "should generate simple interface with leading and trailing comments on separate line", file: "Comments2"},
{should: "should generate interface extending one interface", file: "Extends"},
{should: "should generate interface with method that returns void", file: "MethodReturnVoid"},
{should: "should generate interface with method that returns never", file: "MethodReturnNever"},
{should: "should generate interface with method that returns bool", file: "MethodReturnBool"},
{should: "should generate interface with method that returns bool or null", file: "MethodReturnBoolOrNull"},
{should: "should generate interface with method that returns string", file: "MethodReturnString"},
{should: "should generate interface with method that returns string or null", file: "MethodReturnStringOrNull"},
{should: "should generate interface with method that returns any", file: "MethodReturnAny"},
{should: "should generate interface with method that returns any or null", file: "MethodReturnAnyOrNull"},
{should: "should generate interface with method that returns number", file: "MethodReturnNumber"},
{should: "should generate interface with method that returns number or null", file: "MethodReturnNumberOrNull"},
{should: "should generate interface with method that returns type reference", file: "MethodReturnRefType1"},
{should: "should generate interface with 2 methods that returns type reference", file: "MethodReturnRefType2"},
{should: "should generate interface with method that returns type reference or null", file: "MethodReturnRefTypeOrNull"},
{should: "should generate interface with method with string parm that returns bool", file: "MethodWithStringParmReturnBool"},
{should: "should generate interface with method with string parms", file: "MethodWithStringParms"},
{should: "should generate interface with method with string array parms", file: "MethodWithStringArrayParms"},
{should: "should generate interface with method with string array or null parms", file: "MethodWithStringArrayOrNullParms"},
{should: "should generate interface with method with string or null parms", file: "MethodWithStringOrNullParms"},
{should: "should generate interface with method with boolean parms", file: "MethodWithBooleanParms"},
{should: "should generate interface with method with boolean or null parms", file: "MethodWithBooleanOrNullParms"},
{should: "should generate interface with method with boolean array parms", file: "MethodWithBooleanArrayParms"},
{should: "should generate interface with method with number parms", file: "MethodWithNumberParms"},
{should: "should generate interface with method with number or null parms", file: "MethodWithNumberOrNullParms"},
{should: "should generate interface with method with number array parms", file: "MethodWithNumberArrayParms"},
{should: "should generate interface with method with number array or null parms", file: "MethodWithNumberArrayOrNullParms"},
{should: "should generate interface with method with type reference or null parms", file: "MethodWithTypeRefOrNullParms"},
{should: "should generate interface with method with type reference array parms", file: "MethodWithTypeRefArrayParms"},
{should: "should generate interface with method with type reference array or null parms", file: "MethodWithTypeRefArrayOrNullParms"},
{should: "should generate interface with method with rest any parms", file: "MethodWithRestAnyParms"},
{should: "should generate interface with method with rest type ref parms", file: "MethodWithRestTypeRefParms"},
{should: "should generate interface with method with rest string parms", file: "MethodWithRestStringParms"},
{should: "should generate interface with method with literal type parms", file: "MethodWithLiteralTypeParm"},
{should: "should generate interface with method leading and trailing comments", file: "MethodComments"},
{should: "should generate interface with method that returns number array", file: "MethodReturnNumberArray"},
{should: "should generate interface with method that returns number array or null", file: "MethodReturnNumberArrayOrNull"},
{should: "should generate interface with method that returns string array", file: "MethodReturnStringArray"},
{should: "should generate interface with method that returns string array or null", file: "MethodReturnStringArrayOrNull"},
{should: "should generate interface with method that returns any array", file: "MethodReturnAnyArray"},
{should: "should generate interface with method that returns any array or null", file: "MethodReturnAnyArrayOrNull"},
{should: "should generate interface with method that returns type reference array", file: "MethodReturnRefTypeArray"},
{should: "should generate interface with method that returns type reference array or null", file: "MethodReturnRefTypeArrayOrNull"},
{should: "should generate interface with string property", file: "StringProperty"},
{should: "should generate interface with readonly object property", file: "ReadOnlyObjectProperty"},
{should: "should generate interface with string or null property", file: "StringOrNullProperty"},
{should: "should generate interface with number property", file: "NumberProperty"},
{should: "should generate interface with number or null property", file: "NumberOrNullProperty"},
{should: "should generate interface with boolean property", file: "BooleanProperty"},
{should: "should generate interface with boolean or null property", file: "BooleanOrNullProperty"},
{should: "should generate interface with type reference or null property", file: "ObjOrNullProperty"},
{should: "should generate interface with indexer property", file: "IndexerProperty"},
{should: "should generate interface with readonly indexer property", file: "ReadOnlyIndexerProperty"},
{should: "should generate interface with string indexer property", file: "StringIndexerProperty"},
{should: "should generate interface with indexer property with leading and trailing comments", file: "IndexerPropertyComments"},
{should: "should generate interface with string array property", file: "ArrayProperty"},
{should: "should generate interface with number and object array property", file: "ArrayProperty2"},
{should: "should generate interface with number array property", file: "NumberArrayProperty"},
{should: "should generate interface with nullable number array property", file: "NumberArrayOrNullProperty"},
{should: "should generate interface with boolean array property", file: "BooleanArrayProperty"},
{should: "should generate interface with nullable boolean array property", file: "BooleanArrayOrNullProperty"},
{should: "should generate interface with type reference array property", file: "TypeRefArrayProperty"},
{should: "should generate interface with nullable type reference array property", file: "TypeRefArrayOrNullProperty"},
{should: "should generate interface with string array property", file: "StringArrayProperty"},
{should: "should generate interface with nullable string array property", file: "StringArrayOrNullProperty"},
{should: "should generate interface with type query property", file: "TypeQueryProperty"},
{should: "should generate interfaces extending one interface", file: "Extends2"},
{should: "should generate multiple interfaces extending multiple interfaces", file: "Extends3"},
{should: "should generate multiple interfaces extending multiple interfaces", file: "Extends4"},
{should: "should generate interface with generic and extends generic", file: "ExtendsGeneric"},
{should: "should generate generic interface with constraints", file: "GenericInterfaceWithConstraint"},
{should: "should generate generic interface generic constraints #2", file: "GenericInterfaceWithConstraint2"},
{should: "should generate generic interface with non supported type default", file: "GenericInterfaceWithTypeDefault"},
{should: "should generate interface with event handlers", file: "EventHandlers"},
{should: "should generate interface with with method with DOM event handler", file: "MethodWithDOMEventHandlerParms"},
]
describe("TsToCSharpGenerator", () => {
describe("interfaces", () => {
const testPath = "interfaces";
interfaceCases.forEach(testCase =>
{
const testFile = testCase.file;
it(testCase.should, () => {
const ast = CreateAST();
//console.log("Adding Source File: " + path.resolve(path.join(definitionsPath,testPath,testFile + ".d.ts")));
ast.addExistingSourceFileIfExists(path.resolve(path.join(definitionsPath,testPath,testFile + ".d.ts")));
const sourceFiles = ast.getSourceFiles();
const context = new Context(new TestGenOptions());
const sourceCode = TsToCSharpGenerator(sourceFiles[0], context)
//fs.writeFileSync(path.join(casesPath,testPath,testFile + ".cs"), sourceCode);
const genCase = fs.readFileSync(path.join(casesPath,testPath,testFile + ".cs")).toString();
expect(sourceCode).to.equal(genCase);
});
}
)
});
});
class TestClassGenOptions extends GenOptions {
constructor ()
{
super();
this.isCaseChangeParameters = false;
}
}
class TestClassNoEmitComments extends GenOptions {
constructor ()
{
super();
this.emitComments = false;
this.isCaseChangeParameters = false;
}
}
class TestClassNSGenOptions extends GenOptions {
constructor ()
{
super();
this.isCaseChangeParameters = false;
this.defaultNameSpace = "Hello.World";
}
}
class TestClassNSAndUsingGenOptions extends GenOptions {
constructor ()
{
super();
this.isCaseChangeParameters = false;
this.defaultNameSpace = "Hello.World";
this.isEmitUsings = true;
}
}
const classCases = [
{should: "should generate simple class from declaraion of interface", file: "InterfaceDeclaration", genOptions: new TestClassGenOptions() },
{should: "should generate simple class from declaraion of interface with comments", file: "InterfaceDeclarationWithComments", genOptions: new TestClassGenOptions()},
{should: "should generate simple class from declaraion of interface without comments", file: "InterfaceDeclarationNoEmitComments", genOptions: new TestClassNoEmitComments()},
{should: "should generate simple class from declaraion of interface with constructor arguments", file: "InterfaceDeclarationWithConstructorArgs", genOptions: new TestClassGenOptions()},
{should: "should generate class from declaraion of interface with properties", file: "InterfaceDeclarationWithProperties", genOptions: new TestClassGenOptions()},
{should: "should generate class from declaraion of interface with methods", file: "InterfaceDeclarationWithMethods", genOptions: new TestClassGenOptions()},
{should: "should generate class from declaraion of interface with inherited properties", file: "InterfaceDeclarationWithInheritedProperties", genOptions: new TestClassGenOptions()},
{should: "should generate class from declaraion of interface with inherited methods", file: "InterfaceDeclarationWithInheritedMethods", genOptions: new TestClassGenOptions()},
{should: "should generate class from declaraion of interface with inherited indexer", file: "InterfaceDeclarationPropertyIndexer", genOptions: new TestClassGenOptions()},
{should: "should generate class from declaraion of interface with inherited methods and properties", file: "InterfaceDeclaration1", genOptions: new TestClassGenOptions()},
{should: "should generate class from declaraion of interface with type query properties", file: "InterfaceDeclarationWithTypeQuery", genOptions: new TestClassGenOptions()},
{should: "should generate class from declaraion of interface with extended interfaces", file: "InterfaceDeclaration2", genOptions: new TestClassGenOptions()},
{should: "should generate class from declaraion of interface with event handlers", file: "InterfaceDeclarationWithEventHandlers", genOptions: new TestClassGenOptions()},
{should: "should generate simple class with default namespace", file: "InterfaceDeclaration4", genOptions: new TestClassNSGenOptions() },
{should: "should generate simple class with default namespace and Usings", file: "InterfaceDeclaration5", genOptions: new TestClassNSAndUsingGenOptions() },
]
describe("TsToCSharpGenerator", function () {
describe("classes", function () {
const testPath = "classes";
classCases.forEach(testCase =>
{
const testFile = testCase.file;
const genOptions = testCase.genOptions;//testCase.genOptions ? testCase.genOptions : new TestClassGenOptions();
it(testCase.should, function () {
const ast = CreateAST();
//console.log("Adding Source File: " + path.resolve(path.join(definitionsPath,testPath,testFile + ".d.ts")));
ast.addExistingSourceFileIfExists(path.resolve(path.join(definitionsPath,testPath,testFile + ".d.ts")));
const sourceFiles = ast.getSourceFiles();
const context = new Context(genOptions);
const sourceCode = TsToCSharpGenerator(sourceFiles[0], context)
//fs.writeFileSync(path.join(casesPath,testPath,testFile + ".cs"), sourceCode);
const genCase = fs.readFileSync(path.join(casesPath,testPath,testFile + ".cs")).toString();
expect(sourceCode).to.equal(genCase);
});
}
)
});
});
const diagnosticCases = [
{should: "should generate warning non supported type default", file: "GenericInterfaceWithTypeDefault"},
{should: "should generate warning non supported declaration", file: "DeclarationOfNonInterface"},
]
describe("TsToCSharpGenerator", () => {
describe("diagnostics", () => {
const testPath = "diagnostics";
let testCase = diagnosticCases[0];
let testFile = diagnosticCases[0].file;
it(testCase.should, () => {
const ast = CreateAST();
ast.addExistingSourceFileIfExists(path.resolve(path.join(definitionsPath,testPath,testFile + ".d.ts")));
const sourceFiles = ast.getSourceFiles();
const context = new Context(new TestGenOptions());
TsToCSharpGenerator(sourceFiles[0], context)
expect(context.diagnostics.warnings.length).to.equal(1);
});
testCase = diagnosticCases[1];
testFile = diagnosticCases[1].file;
it(testCase.should, () => {
const ast = CreateAST();
ast.addExistingSourceFileIfExists(path.resolve(path.join(definitionsPath,testPath,testFile + ".d.ts")));
const sourceFiles = ast.getSourceFiles();
const context = new Context(new TestClassGenOptions());
TsToCSharpGenerator(sourceFiles[0], context)
expect(context.diagnostics.warnings.length).to.equal(1);
});
});
}); | the_stack |
import {
expect
} from 'chai';
import {
each, every
} from '@phosphor/algorithm';
import {
IMessageHandler, IMessageHook, Message, MessageLoop
} from '@phosphor/messaging';
import {
PanelLayout, Widget
} from '@phosphor/widgets';
class LogHook implements IMessageHook {
messages: string[] = [];
messageHook(target: IMessageHandler, msg: Message): boolean {
this.messages.push(msg.type);
return true;
}
}
class LogPanelLayout extends PanelLayout {
methods: string[] = [];
protected init(): void {
super.init();
this.methods.push('init');
}
protected attachWidget(index: number, widget: Widget): void {
super.attachWidget(index, widget);
this.methods.push('attachWidget');
}
protected moveWidget(fromIndex: number, toIndex: number, widget: Widget): void {
super.moveWidget(fromIndex, toIndex, widget);
this.methods.push('moveWidget');
}
protected detachWidget(index: number, widget: Widget): void {
super.detachWidget(index, widget);
this.methods.push('detachWidget');
}
protected onChildRemoved(msg: Widget.ChildMessage): void {
super.onChildRemoved(msg);
this.methods.push('onChildRemoved');
}
}
describe('@phosphor/widgets', () => {
describe('PanelLayout', () => {
describe('#dispose()', () => {
it('should dispose of the resources held by the widget', () => {
let layout = new PanelLayout();
let widgets = [new Widget(), new Widget()];
each(widgets, w => { layout.addWidget(w); });
layout.dispose();
expect(every(widgets, w => w.isDisposed)).to.equal(true);
});
});
describe('#widgets', () => {
it('should be a read-only sequence of widgets in the layout', () => {
let layout = new PanelLayout();
let widget = new Widget();
layout.addWidget(widget);
let widgets = layout.widgets;
expect(widgets.length).to.equal(1);
expect(widgets[0]).to.equal(widget);
});
});
describe('#iter()', () => {
it('should create an iterator over the widgets in the layout', () => {
let layout = new PanelLayout();
let widgets = [new Widget(), new Widget()];
each(widgets, w => { layout.addWidget(w); });
each(widgets, w => { w.title.label = 'foo'; });
let iter = layout.iter();
expect(every(iter, w => w.title.label === 'foo')).to.equal(true);
expect(layout.iter()).to.not.equal(iter);
});
});
describe('#addWidget()', () => {
it('should add a widget to the end of the layout', () => {
let layout = new PanelLayout();
layout.addWidget(new Widget());
let widget = new Widget();
layout.addWidget(widget);
expect(layout.widgets[1]).to.equal(widget);
});
it('should move an existing widget to the end', () => {
let layout = new PanelLayout();
let widget = new Widget();
layout.addWidget(widget);
layout.addWidget(new Widget());
layout.addWidget(widget);
expect(layout.widgets[1]).to.equal(widget);
});
});
describe('#insertWidget()', () => {
it('should insert a widget at the specified index', () => {
let layout = new PanelLayout();
layout.addWidget(new Widget());
let widget = new Widget();
layout.insertWidget(0, widget);
expect(layout.widgets[0]).to.equal(widget);
});
it('should move an existing widget to the specified index', () => {
let layout = new PanelLayout();
layout.addWidget(new Widget());
let widget = new Widget();
layout.addWidget(widget);
layout.insertWidget(0, widget);
expect(layout.widgets[0]).to.equal(widget);
});
it('should clamp the index to the bounds of the widgets', () => {
let layout = new PanelLayout();
layout.addWidget(new Widget());
let widget = new Widget();
layout.insertWidget(-2, widget);
expect(layout.widgets[0]).to.equal(widget);
layout.insertWidget(10, widget);
expect(layout.widgets[1]).to.equal(widget);
});
it('should be a no-op if the index does not change', () => {
let layout = new PanelLayout();
let widget = new Widget();
layout.addWidget(widget);
layout.addWidget(new Widget());
layout.insertWidget(0, widget);
expect(layout.widgets[0]).to.equal(widget);
});
});
describe('#removeWidget()', () => {
it('should remove a widget by value', () => {
let layout = new PanelLayout();
let widget = new Widget();
layout.addWidget(widget);
layout.addWidget(new Widget());
layout.removeWidget(widget);
expect(layout.widgets.length).to.equal(1);
expect(layout.widgets[0]).to.not.equal(widget);
});
});
describe('#removeWidgetAt()', () => {
it('should remove a widget at a given index', () => {
let layout = new PanelLayout();
let widget = new Widget();
layout.addWidget(widget);
layout.addWidget(new Widget());
layout.removeWidgetAt(0);
expect(layout.widgets.length).to.equal(1);
expect(layout.widgets[0]).to.not.equal(widget);
});
});
describe('#init()', () => {
it('should be invoked when the layout is installed on its parent', () => {
let widget = new Widget();
let layout = new LogPanelLayout();
widget.layout = layout;
expect(layout.methods).to.contain('init');
});
it('should attach all widgets to the DOM', () => {
let parent = new Widget();
Widget.attach(parent, document.body);
let layout = new LogPanelLayout();
let widgets = [new Widget(), new Widget(), new Widget()];
each(widgets, w => { layout.addWidget(w); });
parent.layout = layout;
expect(every(widgets, w => w.parent === parent)).to.equal(true);
expect(every(widgets, w => w.isAttached)).to.equal(true);
parent.dispose();
});
});
describe('#attachWidget()', () => {
it("should attach a widget to the parent's DOM node", () => {
let panel = new Widget();
let layout = new LogPanelLayout();
let widget = new Widget();
panel.layout = layout;
layout.insertWidget(0, widget);
expect(layout.methods).to.contain('attachWidget');
expect(panel.node.children[0]).to.equal(widget.node);
panel.dispose();
});
it("should send before/after attach messages if the parent is attached", () => {
let panel = new Widget();
let layout = new LogPanelLayout();
let widget = new Widget();
let hook = new LogHook();
panel.layout = layout;
MessageLoop.installMessageHook(widget, hook);
Widget.attach(panel, document.body);
layout.insertWidget(0, widget);
expect(layout.methods).to.contain('attachWidget');
expect(hook.messages).to.contain('before-attach');
expect(hook.messages).to.contain('after-attach');
panel.dispose();
});
});
describe('#moveWidget()', () => {
it("should move a widget in the parent's DOM node", () => {
let panel = new Widget();
let layout = new LogPanelLayout();
let widget = new Widget();
panel.layout = layout;
layout.addWidget(widget);
layout.addWidget(new Widget());
layout.insertWidget(1, widget);
expect(layout.methods).to.contain('moveWidget');
expect(panel.node.children[1]).to.equal(widget.node);
panel.dispose();
});
it("should send before/after detach/attach messages if the parent is attached", () => {
let panel = new Widget();
let layout = new LogPanelLayout();
let widget = new Widget();
let hook = new LogHook();
MessageLoop.installMessageHook(widget, hook);
panel.layout = layout;
Widget.attach(panel, document.body);
layout.addWidget(widget);
layout.addWidget(new Widget());
layout.insertWidget(1, widget);
expect(layout.methods).to.contain('moveWidget');
expect(hook.messages).to.contain('before-detach');
expect(hook.messages).to.contain('after-detach');
expect(hook.messages).to.contain('before-attach');
expect(hook.messages).to.contain('after-attach');
panel.dispose();
});
});
describe('#detachWidget()', () => {
it("should detach a widget from the parent's DOM node", () => {
let panel = new Widget();
let layout = new LogPanelLayout();
let widget = new Widget();
panel.layout = layout;
layout.insertWidget(0, widget);
expect(panel.node.children[0]).to.equal(widget.node);
layout.removeWidget(widget);
expect(layout.methods).to.contain('detachWidget');
panel.dispose();
});
it("should send before/after detach message if the parent is attached", () => {
let panel = new Widget();
let layout = new LogPanelLayout();
let widget = new Widget();
let hook = new LogHook();
MessageLoop.installMessageHook(widget, hook);
panel.layout = layout;
Widget.attach(panel, document.body);
layout.insertWidget(0, widget);
expect(panel.node.children[0]).to.equal(widget.node);
layout.removeWidget(widget);
expect(layout.methods).to.contain('detachWidget');
expect(hook.messages).to.contain('before-detach');
expect(hook.messages).to.contain('after-detach');
panel.dispose();
});
});
describe('#onChildRemoved()', () => {
it('should be called when a widget is removed from its parent', () => {
let panel = new Widget();
let layout = new LogPanelLayout();
let widget = new Widget();
panel.layout = layout;
layout.addWidget(widget);
widget.parent = null;
expect(layout.methods).to.contain('onChildRemoved');
});
it('should remove the widget from the layout', () => {
let panel = new Widget();
let layout = new LogPanelLayout();
let widget = new Widget();
panel.layout = layout;
layout.addWidget(widget);
widget.parent = null;
expect(layout.widgets.length).to.equal(0);
});
});
});
}); | the_stack |
import {Manifest} from '../../manifest.js';
import {assert} from '../../../platform/chai-web.js';
import {PolicyRetentionMedium, PolicyAllowedUsageType} from '../policy.js';
import {assertThrowsAsync} from '../../../testing/test-util.js';
import {mapToDictionary} from '../../../utils/lib-utils.js';
import {TtlUnits, Persistence, Encryption, Capabilities, Ttl} from '../../capabilities.js';
import {IngressValidation} from '../ingress-validation.js';
import {deleteFieldRecursively} from '../../../utils/lib-utils.js';
import {EntityType, SingletonType, CollectionType, ReferenceType, TupleType, TypeVariable} from '../../../types/lib-types.js';
const customAnnotation = `
annotation custom
targets: [Policy, PolicyTarget, PolicyField]
retention: Source
doc: 'custom annotation for testing'
`;
const personSchema = `
schema Person
name: Text
age: Number
friends: [&Friend {name: Text, age: Number}]
`;
async function parsePolicy(str: string) {
const manifest = await Manifest.parse(customAnnotation + personSchema + str);
assert.lengthOf(manifest.policies, 1);
return manifest.policies[0];
}
describe('policy', () => {
it('can round-trip to string', async () => {
const manifestString = `
${customAnnotation.trim()}
${personSchema.trim()}
@intendedPurpose(description: 'test')
@egressType(type: 'Logging')
@custom
policy MyPolicy {
@maxAge(age: '2d')
@allowedRetention(medium: 'Ram', encryption: false)
@allowedRetention(medium: 'Disk', encryption: true)
@custom
from Person access {
@allowedUsage(label: 'raw', usageType: 'join')
@allowedUsage(label: 'truncated', usageType: 'egress')
friends {
@allowedUsage(label: 'redacted', usageType: '*')
@custom
age,
},
@custom
name,
}
config SomeConfig {
abc: '123'
def: '456'
}
}`.trim();
const manifest = await Manifest.parse(manifestString);
assert.strictEqual(manifest.toString(), manifestString);
});
it('rejects duplicate policy names', async () => {
await assertThrowsAsync(async () => parsePolicy(`
policy MyPolicy {}
policy MyPolicy {}
`), 'A policy named MyPolicy already exists.');
});
it('policy annotations work', async () => {
const policy = await parsePolicy(`
@intendedPurpose('test')
@egressType('Logging')
@custom
policy MyPolicy {}
`);
assert.strictEqual(policy.name, 'MyPolicy');
assert.strictEqual(policy.description, 'test');
assert.strictEqual(policy.egressType, 'Logging');
assert.lengthOf(policy.customAnnotations, 1);
assert.strictEqual(policy.customAnnotations[0].name, 'custom');
});
it('handles missing policy annotations', async () => {
const policy = await parsePolicy(`
policy MyPolicy {}
`);
assert.isNull(policy.description);
assert.isNull(policy.egressType);
});
it('allows arbitrary egress types', async () => {
const policy = await parsePolicy(`
@egressType('SomeInventedEgressType')
policy MyPolicy {}
`);
assert.strictEqual(policy.egressType, 'SomeInventedEgressType');
});
it('policy target annotations work', async () => {
const policy = await parsePolicy(`
policy MyPolicy {
@allowedRetention(medium: 'Disk', encryption: true)
@allowedRetention(medium: 'Ram', encryption: false)
@maxAge('2d')
@custom
from Person access {}
}`);
assert.lengthOf(policy.targets, 1);
const target = policy.targets[0];
assert.strictEqual(target.schemaName, 'Person');
assert.deepStrictEqual(target.retentions, [
{
medium: PolicyRetentionMedium.Disk,
encryptionRequired: true,
},
{
medium: PolicyRetentionMedium.Ram,
encryptionRequired: false,
},
]);
assert.strictEqual(target.maxAge.count, 2);
assert.strictEqual(target.maxAge.units, TtlUnits.Days);
assert.lengthOf(target.customAnnotations, 1);
assert.strictEqual(target.customAnnotations[0].name, 'custom');
});
it('handles missing target annotations', async () => {
const policy = await parsePolicy(`
policy MyPolicy {
from Person access {}
}
`);
const target = policy.targets[0];
assert.strictEqual(target.maxAge.millis, 0);
assert.isEmpty(target.fields);
assert.isEmpty(target.customAnnotations);
});
it('rejects unknown target types', async () => {
await assertThrowsAsync(async () => parsePolicy(`
policy MyPolicy {
from UnknownType access {}
}`), `Unknown type name: UnknownType.`);
});
it('rejects duplicate targets', async () => {
await assertThrowsAsync(async () => parsePolicy(`
policy MyPolicy {
from Person access {}
from Person access {}
}`), `A definition for 'Person' already exists.`);
});
it('rejects duplicate retentions', async () => {
await assertThrowsAsync(async () => parsePolicy(`
policy MyPolicy {
@allowedRetention(medium: 'Ram', encryption: true)
@allowedRetention(medium: 'Ram', encryption: true)
from Person access {}
}`), '@allowedRetention has already been defined for Ram.');
});
it('rejects unknown retention mediums', async () => {
await assertThrowsAsync(async () => parsePolicy(`
policy MyPolicy {
@allowedRetention(medium: 'SomethingElse', encryption: false)
from Person access {}
}`), 'Expected one of: Ram, Disk. Found: SomethingElse.');
});
it('rejects invalid maxAge', async () => {
await assertThrowsAsync(async () => parsePolicy(`
policy MyPolicy {
@maxAge('4x')
from Person access {}
}`), 'Invalid ttl: 4x');
});
it('policy field annotations work', async () => {
const policy = await parsePolicy(`
policy MyPolicy {
from Person access {
@allowedUsage(label: 'redacted', usageType: 'egress')
@allowedUsage(label: 'redacted', usageType: 'join')
@custom
friends {
@allowedUsage(label: 'truncated', usageType: 'join')
@custom
name,
@allowedUsage(label: 'raw', usageType: '*')
age,
}
}
}`);
const fields = policy.targets[0].fields;
assert.lengthOf(fields, 1);
const friends = fields[0];
assert.strictEqual(friends.name, 'friends');
assert.deepStrictEqual(friends.allowedUsages, [
{
usage: PolicyAllowedUsageType.Egress,
label: 'redacted',
},
{
usage: PolicyAllowedUsageType.Join,
label: 'redacted',
},
]);
assert.lengthOf(friends.customAnnotations, 1);
assert.strictEqual(friends.customAnnotations[0].name, 'custom');
const subfields = friends.subfields;
assert.lengthOf(subfields, 2);
const [name, age] = subfields;
assert.strictEqual(name.name, 'name');
assert.deepStrictEqual(name.allowedUsages, [{
usage: PolicyAllowedUsageType.Join,
label: 'truncated',
}]);
assert.lengthOf(name.customAnnotations, 1);
assert.strictEqual(name.customAnnotations[0].name, 'custom');
assert.strictEqual(age.name, 'age');
assert.deepStrictEqual(age.allowedUsages, [{
usage: PolicyAllowedUsageType.Any,
label: '',
}]);
assert.lengthOf(age.customAnnotations, 0);
});
it('rejects unknown fields and subfields', async () => {
await assertThrowsAsync(async () => parsePolicy(`
policy MyPolicy {
from Person access {
unknownField,
}
}`), /Schema 'Person \{.*\}' does not contain field 'unknownField'/);
await assertThrowsAsync(async () => parsePolicy(`
policy MyPolicy {
from Person access {
friends {
unknownField,
}
}
}`), /Schema 'Friend \{.*\}' does not contain field 'unknownField'/);
});
it('rejects unknown usage types', async () => {
await assertThrowsAsync(async () => parsePolicy(`
policy MyPolicy {
from Person access {
@allowedUsage(label: 'redacted', usageType: 'SomethingElse')
age,
}
}`), 'Expected one of: *, egress, join. Found: SomethingElse.');
});
it('rejects duplicate usage types', async () => {
await assertThrowsAsync(async () => parsePolicy(`
policy MyPolicy {
from Person access {
@allowedUsage(label: 'redacted', usageType: 'egress')
@allowedUsage(label: 'redacted', usageType: 'egress')
age,
}
}`), `Usage of label 'redacted' for usage type 'egress' has already been allowed.`);
});
it('rejects duplicate fields', async () => {
await assertThrowsAsync(async () => parsePolicy(`
policy MyPolicy {
from Person access {
abc,
abc,
}
}`), `A definition for 'abc' already exists.`);
});
it('rejects duplicate subfields', async () => {
await assertThrowsAsync(async () => parsePolicy(`
policy MyPolicy {
from Person access {
friends,
friends {
name
}
}
}`), `A definition for 'friends' already exists.`);
});
it('allowed usages defaults to any', async () => {
const policyStr = `
policy MyPolicy {
from Person access {
age,
}
}`.trim();
const policy = await parsePolicy(policyStr);
assert.deepStrictEqual(policy.targets[0].fields[0].allowedUsages, [{
label: '',
usage: PolicyAllowedUsageType.Any,
}]);
assert.strictEqual(policy.toManifestString(), policyStr);
});
it('policy configs work', async () => {
const policy = await parsePolicy(`
policy MyPolicy {
config MyConfig {
abc: '123'
def: '456'
}
}`);
assert.lengthOf(policy.configs, 1);
const config = policy.configs[0];
assert.strictEqual(config.name, 'MyConfig');
assert.deepStrictEqual(mapToDictionary(config.metadata), {
abc: '123',
def: '456',
});
});
it('rejects duplicate configs', async () => {
await assertThrowsAsync(async () => parsePolicy(`
policy MyPolicy {
config Abc {}
config Abc {}
}`), `A definition for 'Abc' already exists.`);
});
it('converts to capabilities', async () => {
const target = (await parsePolicy(`
policy MyPolicy {
@allowedRetention(medium: 'Disk', encryption: true)
@allowedRetention(medium: 'Ram', encryption: false)
@maxAge('2d')
@custom
from Person access {}
}`)).targets[0];
const capabilities = target.toCapabilities();
assert.lengthOf(capabilities, 2);
assert.isTrue(capabilities[0].isEquivalent(Capabilities.create([
Persistence.onDisk(), new Encryption(true), Ttl.days(2)])),
`Unexpected capabilities: ${capabilities[0].toDebugString()}`);
assert.isTrue(capabilities[1].isEquivalent(
Capabilities.create([Persistence.inMemory(), new Encryption(false), Ttl.days(2)])),
`Unexpected capabilities: ${capabilities[1].toDebugString()}`);
});
it('restricts types according to policy', async () => {
const manifest = await Manifest.parse(`
schema Address
number: Number
street: Text
city: Text
country: Text
schema Person
name: Text
phone: Text
address: &Address
otherAddresses: [&Address {street, city, country}]
policy MyPolicy {
from Person access {
name,
address {
number
street,
city
},
otherAddresses {city, country}
}
}`);
const policy = manifest.policies[0];
const schema = policy.targets[0].getMaxReadSchema();
const expectedSchemas = (await Manifest.parse(`
schema Address
number: Number
street: Text
city: Text
country: Text
schema Person
name: Text
address: &Address {number, street, city}
otherAddresses: [&Address {city, country}]
`)).schemas;
deleteFieldRecursively(schema, 'location');
deleteFieldRecursively(expectedSchemas, 'location');
assert.deepEqual(schema, expectedSchemas['Person']);
});
it('restricts inline types according to policy', async () => {
const manifest = await Manifest.parse(`
schema Address
number: Number
street: Text
city: Text
country: Text
schema Name
first: Text
last: Text
schema Person
name: inline Name
phone: Text
addresses: List<inline Address>
policy MyPolicy {
from Person access {
name {
last
},
addresses {
number
street,
city
},
}
}`);
const policy = manifest.policies[0];
const schema = policy.targets[0].getMaxReadSchema();
const expectedSchemas = (await Manifest.parse(`
schema Person
name: inline Name {last: Text}
addresses: List<inline Address {number: Number, street: Text, city: Text}>
`)).schemas;
deleteFieldRecursively(schema, 'location');
deleteFieldRecursively(expectedSchemas['Person'], 'location');
assert.deepEqual(schema, expectedSchemas['Person']);
});
it('restricts deeply nested schemas according to policy', async () => {
const manifest = await Manifest.parse(`
schema Name
first: Text
last: Text
schema Address
number: Number
street: Text
city: Text
state: Text
schema Person
name: inline Name
address: &Address
schema Group
persons: List<inline Person>
policy MyPolicy {
from Group access {
persons {
name {
last
},
address {
city
}
}
}
}`);
const ingressValidation = new IngressValidation(manifest.policies);
const maxReadSchemas = ingressValidation.maxReadSchemas;
const expectedSchemas = (await Manifest.parse(`
schema Name
last: Text
schema Address
city: Text
schema Person
name: inline Name
address: &Address
schema Group
persons: List<inline Person>
`)).schemas;
deleteFieldRecursively(maxReadSchemas['Group'], 'location', {replaceWithNulls: true});
deleteFieldRecursively(expectedSchemas['Group'], 'location', {replaceWithNulls: true});
assert.deepEqual(maxReadSchemas['Group'], expectedSchemas['Group']);
// `Person` and `Name` are only referred to as an inline entities.
// Therefore, they can only be written via `Group`. So, it is not
// included in the max read schemas.
//
// On the other hand `Address` is a reference, and therefore, the
// data might be written into a different store directly.
// Therefore, we need to make sure that fields made accessible through
// this policy are preserved by ingress restricting.
assert.isFalse('Person' in maxReadSchemas);
assert.isFalse('Name' in maxReadSchemas);
assert.deepEqual(maxReadSchemas['Address'], expectedSchemas['Address']);
});
const manifestWithMultiplePolicies = `
schema Address
number: Number
street: Text
city: Text
zip: Number
state: Text
country: Text
schema Person
name: Text
phone: Text
address: &Address
otherAddresses: [&Address {street, city, country}]
schema SensitiveInfo
name: Text
ssn: Text
policy PolicyOne {
from Person access {
name,
address {
number,
street
}
}
}
policy PolicyTwo {
from Person access {
address {
street,
city
},
otherAddresses {city}
}
}
policy PolicyThree {
from Person access {
name,
otherAddresses {country}
}
}
policy PolicyFour {
from Address access {
state
}
}`;
const maxReadSchemasForMultiplePolicies = `
schema Address
number: Number
street: Text
city: Text
state: Text
country: Text
schema Person
name: Text
address: &Address {number, street, city}
otherAddresses: [&Address {city, country}]
`;
it('restricts types according to multiple policies', async () => {
const policies =
(await Manifest.parse(manifestWithMultiplePolicies)).policies;
const ingressValidation = new IngressValidation(policies);
const maxReadSchemas = ingressValidation.maxReadSchemas;
const expectedSchemas =
(await Manifest.parse(maxReadSchemasForMultiplePolicies)).schemas;
deleteFieldRecursively(maxReadSchemas['Person'], 'location', {replaceWithNulls: true});
deleteFieldRecursively(expectedSchemas['Person'], 'location', {replaceWithNulls: true});
deleteFieldRecursively(maxReadSchemas['Address'], 'location', {replaceWithNulls: true});
deleteFieldRecursively(expectedSchemas['Address'], 'location', {replaceWithNulls: true});
assert.deepEqual(maxReadSchemas['Person'], expectedSchemas['Person']);
assert.deepEqual(maxReadSchemas['Address'], expectedSchemas['Address']);
});
it('does not add nested inline entities to max read schemas', async () => {
const manifest = await Manifest.parse(`
schema Address
number: Number
street: Text
city: Text
country: Text
schema Name
first: Text
last: Text
schema Person
name: inline Name
phone: Text
addresses: List<inline Address>
policy MyPolicy {
from Person access {
name {
last
},
addresses {
number
street,
city
},
}
}
policy AddressPolicy {
from Address access {
city,
country
}
}`);
const ingressValidation = new IngressValidation(manifest.policies);
const maxReadSchemas = ingressValidation.maxReadSchemas;
const expectedSchemas = (await Manifest.parse(`
schema Address
city: Text
country: Text
schema Person
name: inline Name {last: Text}
addresses: List<inline Address {number: Number, street: Text, city: Text}>
`)).schemas;
deleteFieldRecursively(maxReadSchemas['Person'], 'location', {replaceWithNulls: true});
deleteFieldRecursively(expectedSchemas['Person'], 'location', {replaceWithNulls: true});
deleteFieldRecursively(maxReadSchemas['Address'], 'location', {replaceWithNulls: true});
deleteFieldRecursively(expectedSchemas['Address'], 'location', {replaceWithNulls: true});
assert.deepEqual(maxReadSchemas['Person'], expectedSchemas['Person']);
assert.deepEqual(maxReadSchemas['Address'], expectedSchemas['Address']);
// 'Name' is not in `maxReadSchemas` because it only appears as
// an inline entity.
assert.isFalse('Name' in maxReadSchemas);
});
it('adds references in inline entities to max read schema', async () => {
const manifest = await Manifest.parse(`
schema Name
first: Text
last: Text
schema Person
name: &Name
phone: Text
schema Group
persons: List<inline Person>
policy MyPolicy {
from Group access {
persons {
name {
last
}
}
}
}`);
const ingressValidation = new IngressValidation(manifest.policies);
const maxReadSchemas = ingressValidation.maxReadSchemas;
const expectedSchemas = (await Manifest.parse(`
schema Name
last: Text
schema Person
name: &Name
schema Group
persons: List<inline Person>
`)).schemas;
deleteFieldRecursively(maxReadSchemas['Group'], 'location', {replaceWithNulls: true});
deleteFieldRecursively(expectedSchemas['Group'], 'location', {replaceWithNulls: true});
assert.deepEqual(maxReadSchemas['Group'], expectedSchemas['Group']);
// `Person` is only referred to as an inline entity. Therefore, it
// can only be written via `Group`. So, it is not included in the
// max read schemas.
//
// On the other hand `Name` is a reference, and therefore, the
// data might be written into a different store directly.
// Therefore, we need to make sure that fields made accessible through
// this policy are preserved by ingress restricting.
assert.isFalse('Person' in maxReadSchemas);
assert.deepEqual(maxReadSchemas['Name'], expectedSchemas['Name']);
});
it('returns max read type according to multiple policies', async () => {
const manifest = await Manifest.parse(manifestWithMultiplePolicies);
const expectedSchemas =
(await Manifest.parse(maxReadSchemasForMultiplePolicies)).schemas;
const ingressValidation = new IngressValidation(manifest.policies);
deleteFieldRecursively(expectedSchemas['Person'], 'location', {replaceWithNulls: true});
deleteFieldRecursively(expectedSchemas['Address'], 'location', {replaceWithNulls: true});
deleteFieldRecursively(manifest.schemas['Person'], 'location', {replaceWithNulls: true});
deleteFieldRecursively(manifest.schemas['Address'], 'location', {replaceWithNulls: true});
const manifestPerson = new EntityType(manifest.schemas['Person']);
const manifestAddress = new EntityType(manifest.schemas['Address']);
const maxReadPerson = new EntityType(expectedSchemas['Person']);
const maxReadAddress = new EntityType(expectedSchemas['Address']);
// Entity type.
assert.deepEqual(
ingressValidation.getMaxReadType(manifestPerson),
maxReadPerson);
// Singleton type.
assert.deepEqual(
ingressValidation.getMaxReadType(new SingletonType(manifestPerson)),
new SingletonType(maxReadPerson));
// Reference type.
assert.deepEqual(
ingressValidation.getMaxReadType(new ReferenceType(manifestPerson)),
new ReferenceType(maxReadPerson));
// Tuple type.
const manifestTuple = new TupleType([manifestPerson, manifestAddress]);
const maxReadTuple = new TupleType([maxReadPerson, maxReadAddress]);
assert.deepEqual(
ingressValidation.getMaxReadType(manifestTuple),
maxReadTuple);
// Collection type.
const manifestCollection = new CollectionType(manifestPerson);
const maxReadCollection = new CollectionType(maxReadPerson);
assert.deepEqual(
ingressValidation.getMaxReadType(manifestCollection),
maxReadCollection);
});
it('updates the write constraint of a type variable to get max read type',
async () => {
const manifest = await Manifest.parse(manifestWithMultiplePolicies);
const expectedSchemas =
(await Manifest.parse(maxReadSchemasForMultiplePolicies)).schemas;
const ingressValidation = new IngressValidation(manifest.policies);
deleteFieldRecursively(expectedSchemas['Person'], 'location', {replaceWithNulls: true});
deleteFieldRecursively(manifest.schemas['Person'], 'location', {replaceWithNulls: true});
const manifestPerson = new EntityType(manifest.schemas['Person']);
const maxReadPerson = new EntityType(expectedSchemas['Person']);
const manifestCollection = new CollectionType(manifestPerson);
const maxReadCollection = new CollectionType(maxReadPerson);
// Type variable.
// Only the canWriteSuperset will be replaced with the max read type.
const typeVar = TypeVariable.make(
'',
/* canWriteSuperset = */manifestCollection,
/* canReadSubset = */manifestCollection);
const maxReadTypeVar = TypeVariable.make(
'',
/* canWriteSuperset = */maxReadCollection,
/* canReadsubset = */manifestCollection);
assert.deepEqual(ingressValidation.getMaxReadType(typeVar), maxReadTypeVar);
const noWriteTypeVar = TypeVariable.make(
'',
/* canWriteSuperset = */manifestCollection,
/* canReadSubset = */null);
assert.deepEqual(ingressValidation.getMaxReadType(noWriteTypeVar), noWriteTypeVar);
});
it('returns correct type variable when write constraint is <= max read type',
async () => {
const manifest = await Manifest.parse(manifestWithMultiplePolicies);
const expectedSchemas =
(await Manifest.parse(maxReadSchemasForMultiplePolicies)).schemas;
const manifestPerson = new EntityType(manifest.schemas['Person']);
const ingressValidation = new IngressValidation(manifest.policies);
// This represents a type that is a subset of the maxReadPerson.
const personSubsetSchema = (await Manifest.parse(`
schema Address
number: Number
street: Text
city: Text
state: Text
country: Text
schema Person
address: &Address {number, city}
otherAddresses: [&Address {city}]
`)).schemas['Person'];
// Sanity checks to ensure `personSubsetSchema` is subset of maxPersonSchema.
deleteFieldRecursively(personSubsetSchema, 'location', {replaceWithNulls: true});
assert.isTrue(
expectedSchemas['Person'].isAtLeastAsSpecificAs(personSubsetSchema));
assert.isFalse(
personSubsetSchema.isAtLeastAsSpecificAs(expectedSchemas['Person']));
const personSubset = new EntityType(personSubsetSchema);
const subsetTypeVar = TypeVariable.make(
'',
/* canWriteSuperset = */manifestPerson,
/* canReadSubset = */personSubset);
const expectedTypeVar = TypeVariable.make(
'',
/* canWriteSuperset = */personSubset,
/* canReadSubset = */personSubset);
assert.deepEqual(
ingressValidation.getMaxReadType(subsetTypeVar), expectedTypeVar);
});
const createTypeVarForSchema = async (
name: string,
writeSupersetFields: string|null,
readSubsetFields: string|null
) => {
// Create a type variable with the given strings as the write and
// read fields of a schema `A`.
const parseSchema = async (fields: string | null) => {
if (fields == null) return null;
const schema = (await Manifest.parse(`schema ${name} { ${fields} }`)).schemas['A'];
deleteFieldRecursively(schema, 'location', {replaceWithNulls: true});
return new EntityType(schema);
};
const canWriteSuperset = await parseSchema(writeSupersetFields);
const canReadSubset = await parseSchema(readSubsetFields);
return TypeVariable.make('', canWriteSuperset, canReadSubset);
};
it('updates write w/ max read type that is consistent with read', async () => {
const manifest = await Manifest.parse(`
schema A {a: Text, b:Text, c: Text, d: Text}
policy P {
from A access {a, b}
}
`);
const ingressValidation = new IngressValidation(manifest.policies);
const typeVar = await createTypeVarForSchema('A', null, 'a: Text, d: Text');
const expected = await createTypeVarForSchema('A', 'a: Text', 'a: Text, d: Text');
assert.deepEqual(
ingressValidation.getMaxReadType(typeVar), expected);
});
it('updates write w/ max read type that is consistent with read (inline)', async () => {
const manifest = await Manifest.parse(`
schema A
foo: inline Foo {a: Text, b: Text, c: Text, d: Text}
policy P {
from A access {
foo {a, b}
}
}
`);
const ingressValidation = new IngressValidation(manifest.policies);
const typeVar = await createTypeVarForSchema(
'A', null, 'foo: inline Foo {a: Text, d: Text}');
// The expected max read type variable should have `A { foo {a} }` for writeSuperset.
const expected = await createTypeVarForSchema(
'A',
'foo: inline Foo {a: Text}',
'foo: inline Foo {a: Text, d: Text}');
// See getMaxReadType() implementation and `maxReadA` above.
assert.deepEqual(
ingressValidation.getMaxReadType(typeVar), expected);
});
it('uses resolved type of a typevar to get max read type', async () => {
const manifest = await Manifest.parse(`
schema A
foo: inline Foo {a: Text, b: Text, c: Text, d: Text}
policy P {
from A access {
foo {a, b}
}
}
`);
const ingressValidation = new IngressValidation(manifest.policies);
const typeVar = await createTypeVarForSchema(
'A',
'foo: inline Foo {a: Text, d: Text}',
'foo: inline Foo {a: Text, d: Text}');
assert(typeVar.maybeResolve());
const expected = await createTypeVarForSchema(
'A',
'foo: inline Foo {a: Text, b: Text}',
null);
assert.deepEqual(
ingressValidation.getMaxReadType(typeVar), expected);
});
it('returns null for max read type if type has inaccessible schemas', async () => {
const manifest = await Manifest.parse(manifestWithMultiplePolicies);
const ingressValidation = new IngressValidation(manifest.policies);
const manifestPerson = new EntityType(manifest.schemas['Person']);
const manifestSensitiveInfo =
new EntityType(manifest.schemas['SensitiveInfo']);
// Entity type.
assert.isNull(
ingressValidation.getMaxReadType(manifestSensitiveInfo));
// Singleton type.
assert.isNull(
ingressValidation.getMaxReadType(
new SingletonType(manifestSensitiveInfo)));
// Reference type.
assert.isNull(
ingressValidation.getMaxReadType(
new ReferenceType(manifestSensitiveInfo)));
// Tuple type.
assert.isNull(
ingressValidation.getMaxReadType(
new TupleType([manifestPerson, manifestSensitiveInfo])));
// Collection type.
assert.isNull(
ingressValidation.getMaxReadType(
new CollectionType(manifestSensitiveInfo)));
// Type variable.
const typeVar = TypeVariable.make(
'',
/* canWriteSuperset = */manifestSensitiveInfo,
/* canReadSubset = */manifestSensitiveInfo);
// Unresolved type variable
assert(!typeVar.isResolved());
assert.isNull(ingressValidation.getMaxReadType(typeVar));
// Resolved Type variable.
assert(typeVar.maybeResolve());
assert.isNull(ingressValidation.getMaxReadType(typeVar));
});
it('returns error details if type has inaccessible schemas', async () => {
const manifest = await Manifest.parse(manifestWithMultiplePolicies);
const ingressValidation = new IngressValidation(manifest.policies);
const manifestPerson = new EntityType(manifest.schemas['Person']);
const manifestSensitiveInfo =
new EntityType(manifest.schemas['SensitiveInfo']);
const errors = [];
assert.isNull(
ingressValidation.getMaxReadType(manifestSensitiveInfo, errors));
assert.isTrue(errors.length === 1);
assert.deepEqual(errors[0], `Schema 'SensitiveInfo' is not mentioned in policy`);
});
}); | the_stack |
import type { Color } from "../../core/util/Color";
import type { ColorSet } from "../../core/util/ColorSet";
import type { Bullet } from "../../core/render/Bullet";
import type { Root } from "../../core/Root";
import type { Easing } from "../../core/util/Ease";
import { HierarchyDefaultTheme } from "./HierarchyDefaultTheme";
import { Series, ISeriesSettings, ISeriesDataItem, ISeriesPrivate, ISeriesEvents } from "../../core/render/Series";
import { DataItem } from "../../core/render/Component";
import { HierarchyNode } from "./HierarchyNode";
import { Container } from "../../core/render/Container";
import { Label } from "../../core/render/Label";
import { Template } from "../../core/util/Template";
import { ListTemplate } from "../../core/util/List";
import * as $array from "../../core/util/Array";
import * as $type from "../../core/util/Type";
import * as $utils from "../../core/util/Utils";
import * as d3hierarchy from "d3-hierarchy";
/**
* @ignore
*/
export interface IHierarchyDataObject {
name?: string,
value?: number,
children?: IHierarchyDataObject[],
dataItem?: DataItem<IHierarchyDataItem>
customValue?: boolean;
};
export interface IHierarchyDataItem extends ISeriesDataItem {
value: number;
/**
* @ignore
*/
valueWorking: number;
valuePercentTotal: number;
sum: number;
category: string;
children: Array<DataItem<IHierarchyDataItem>>;
childData: Array<any>
parent: DataItem<IHierarchyDataItem>;
depth: number;
node: HierarchyNode;
label: Label;
fill: Color;
disabled: boolean;
/**
* @ignore
*/
d3HierarchyNode: d3hierarchy.HierarchyNode<IHierarchyDataObject>;
}
export interface IHierarchySettings extends ISeriesSettings {
/**
* How to sort nodes by their value.
*
* @default "none"
*/
sort?: "ascending" | "descending" | "none"
/**
* A field in data that holds numeric value for the node.
*/
valueField?: string;
/**
* A field in data that holds string-based identificator for node.
*/
categoryField?: string;
/**
* A field in data that holds an array of child node data.
*/
childDataField?: string;
/**
* A field in data that holds boolean value indicating if node is
* disabled (collapsed).
*/
disabledField?: string;
/**
* A field in data that holds color used for fills for various elements, such
* as nodes.
*/
fillField?: string;
/**
* A [[ColorSet]] to use when asigning colors for nodes.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/hierarchy/#Node_colors} for more info
*/
colors?: ColorSet;
/**
* Number of child levels to open when clicking on a node.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/hierarchy/#Drill_down} for more info
*/
downDepth?: number;
/**
* Number of levels parent levels to show from currently selected node.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/hierarchy/#Drill_down} for more info
*/
upDepth?: number;
/**
* Number of levels to show on chart's first load.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/hierarchy/#Tree_depth} for more info
*/
initialDepth?: number;
/**
* If set, will show nodes starting from set level.
*
* It could be used to eliminate top level branches, that do not need to be
* shown.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/hierarchy/#Tree_depth} for more info
*/
topDepth?: number;
/**
* If set to `true` will make all other branches collapse when some branch is
* expanded.
*/
singleBranchOnly?: boolean;
/**
* A data item for currently selected node.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/hierarchy/#Pre_selected_branch} for more info
*/
selectedDataItem?: DataItem<IHierarchyDataItem>;
/**
* Duration for all drill animations in milliseconds.
*/
animationDuration?: number;
/**
* An easing function to use for drill animations.
*/
animationEasing?: Easing;
}
export interface IHierarchyPrivate extends ISeriesPrivate {
/**
* Level count in series.
*/
maxDepth: number;
}
export interface IHierarchyEvents extends ISeriesEvents {
dataitemselected: {
dataItem?: DataItem<IHierarchyDataItem>
};
}
/**
* A base class for all hierarchy charts.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/hierarchy/} for more info
*/
export abstract class Hierarchy extends Series {
public static className: string = "Hierarchy";
public static classNames: Array<string> = Series.classNames.concat([Hierarchy.className]);
declare public _settings: IHierarchySettings;
declare public _privateSettings: IHierarchyPrivate;
declare public _dataItemSettings: IHierarchyDataItem;
declare public _events: IHierarchyEvents;
/**
* A [[Container]] that nodes are placed in.
*
* @default Container.new()
*/
public readonly nodesContainer = this.children.push(Container.new(this._root, { isMeasured: false }));
public _rootNode: d3hierarchy.HierarchyNode<IHierarchyDataObject> | undefined;
public _treeData: IHierarchyDataObject | undefined;
protected _index: number = 0;
protected _tag: string = "hierarchy";
/**
* A list of nodes in a [[Hierarchy]] chart.
*
* @default new ListTemplate<HierarchyNode>
*/
public readonly nodes: ListTemplate<HierarchyNode> = new ListTemplate(
Template.new({}),
() => HierarchyNode.new(this._root, {
themeTags: $utils.mergeTags(this.nodes.template.get("themeTags", []), [this._tag, "hierarchy", "node"])
}, this.nodes.template)
);
/**
* @ignore
*/
public makeNode(dataItem: DataItem<this["_dataItemSettings"]>): HierarchyNode {
const childData = dataItem.get("childData");
const node = this.nodes.make();
node.series = this;
node._setDataItem(dataItem);
this.nodes.push(node);
dataItem.setRaw("node", node);
const label = this.labels.make();
label._setDataItem(dataItem);
dataItem.setRaw("label", label);
this.labels.push(label);
if (!childData || childData.length == 0) {
node.addTag("last");
}
const depth = dataItem.get("depth");
node.addTag("depth" + depth);
this.nodesContainer.children.push(node);
node.children.push(label);
return node;
}
/**
* A list of label elements in a [[Hierarchy]] chart.
*
* @default new ListTemplate<Label>
*/
public readonly labels: ListTemplate<Label> = new ListTemplate(
Template.new({}),
() => Label.new(this._root, {
themeTags: $utils.mergeTags(this.labels.template.get("themeTags", []), [this._tag])
}, this.labels.template)
);
public _currentDownDepth: number | undefined;
protected _afterNew() {
this._defaultThemes.push(HierarchyDefaultTheme.new(this._root));
this.fields.push("category", "childData", "disabled", "fill");
this.children.push(this.bulletsContainer);
super._afterNew();
}
public _prepareChildren() {
super._prepareChildren();
if (this._valuesDirty) {
this._treeData = {};
const first = this.dataItems[0];
if (first) {
this._makeHierarchyData(this._treeData, first);
this._index = 0;
this._rootNode = (d3hierarchy.hierarchy(this._treeData) as any);
if (this._rootNode) {
this._rootNode.sum((d) => {
return d.value as any;
});
const sort = this.get("sort")
if (sort == "descending") {
this._rootNode.sort((a, b) => (b.value as any) - (a.value as any));
}
else if (sort == "ascending") {
this._rootNode.sort((a, b) => (a.value as any) - (b.value as any));
}
this.setPrivateRaw("valueLow", Infinity);
this.setPrivateRaw("valueHigh", -Infinity);
this.setPrivateRaw("maxDepth", 0);
this._updateValues(this._rootNode);
}
}
}
if (this._valuesDirty || this._sizeDirty) {
this._updateVisuals();
}
if (this._sizeDirty) {
this._selectDataItem(this.get("selectedDataItem"), this._currentDownDepth);
}
}
public _changed() {
super._changed();
if (this.isDirty("selectedDataItem")) {
this._selectDataItem(this.get("selectedDataItem"));
}
}
protected _updateVisuals() {
if (this._rootNode) {
this._updateNodes(this._rootNode);
}
}
protected _updateNodes(hierarchyNode: d3hierarchy.HierarchyNode<IHierarchyDataObject>) {
const dataItem = hierarchyNode.data.dataItem;
if (dataItem) {
this._updateNode(dataItem);
if (this.bullets.length > 0 && !dataItem.bullets) {
this._makeBullets(dataItem);
}
const hierarchyChildren = hierarchyNode.children;
if (hierarchyChildren) {
$array.each(hierarchyChildren, (hierarchyChild) => {
this._updateNodes(hierarchyChild)
})
}
}
}
protected _updateNode(_dataItem: DataItem<this["_dataItemSettings"]>) {
}
public _getDataItemById(dataItems: Array<DataItem<this["_dataItemSettings"]>>, id: string): DataItem<this["_dataItemSettings"]> | undefined {
let di: DataItem<this["_dataItemSettings"]> | undefined;
$array.each(dataItems, (dataItem: any) => {
if (dataItem.get("id") == id) {
di = dataItem;
}
const children = dataItem.get("children");
if (children) {
let childDataItem = this._getDataItemById(children, id);
if (childDataItem) {
di = childDataItem
}
}
})
return di;
}
protected _handleBullets(dataItems: Array<DataItem<this["_dataItemSettings"]>>) {
$array.each(dataItems, (dataItem) => {
const bullets = dataItem.bullets;
if (bullets) {
$array.each(bullets, (bullet) => {
bullet.dispose();
})
dataItem.bullets = undefined;
}
const children = dataItem.get("children");
if (children) {
this._handleBullets(children);
}
})
this._updateVisuals();
}
protected _onDataClear() {
super._onDataClear();
const colors = this.get("colors");
if (colors) {
colors.reset();
}
}
protected processDataItem(dataItem: DataItem<this["_dataItemSettings"]>) {
super.processDataItem(dataItem);
const childData = dataItem.get("childData");
const colors = this.get("colors");
const topDepth = this.get("topDepth", 0);
if (!dataItem.get("parent")) {
dataItem.setRaw("depth", 0);
if (colors && topDepth == 0 && dataItem.get("fill") == null) {
dataItem.setRaw("fill", colors.next());
}
}
let depth = dataItem.get("depth");
const initialDepth = this.get("initialDepth", 1);
this.makeNode(dataItem);
this._processDataItem(dataItem);
if (childData) {
const children: Array<DataItem<this["_dataItemSettings"]>> = [];
dataItem.setRaw("children", children);
$array.each(childData, (child) => {
const childDataItem = new DataItem(this, child, this._makeDataItem(child));
children.push(childDataItem);
childDataItem.setRaw("parent", dataItem);
childDataItem.setRaw("depth", depth + 1);
if (this.dataItems.length == 1 && depth == 0) {
if (colors && childDataItem.get("fill") == null) {
childDataItem.setRaw("fill", colors.next());
}
}
else {
childDataItem.setRaw("fill", dataItem.get("fill"));
}
this.processDataItem(childDataItem);
})
}
const children = dataItem.get("children");
if (!children || children.length == 0) {
const node = dataItem.get("node");
node.setAll({ toggleKey: undefined });
}
if (dataItem.get("disabled") == null) {
if (depth >= topDepth + initialDepth) {
this.disableDataItem(dataItem, 0);
}
}
}
protected _processDataItem(_dataItem: DataItem<this["_dataItemSettings"]>) {
}
protected _updateValues(d3HierarchyNode: d3hierarchy.HierarchyNode<IHierarchyDataObject>) {
const dataItem = d3HierarchyNode.data.dataItem;
if (d3HierarchyNode.depth > this.getPrivate("maxDepth")) {
this.setPrivateRaw("maxDepth", d3HierarchyNode.depth);
}
if (dataItem) {
dataItem.setRaw("d3HierarchyNode", d3HierarchyNode);
(d3HierarchyNode as any).index = this._index;
this._index++;
dataItem.get("node").set("disabled", dataItem.get("disabled"));
let dataValue = d3HierarchyNode.data.value;
let value = d3HierarchyNode.value
if (dataValue != null) {
value = dataValue;
(d3HierarchyNode as any)["value"] = value;
}
if ($type.isNumber(value)) {
dataItem.setRaw("sum", value);
if (this.getPrivate("valueLow") > value) {
this.setPrivateRaw("valueLow", value);
}
if (this.getPrivate("valueHigh") < value) {
this.setPrivateRaw("valueHigh", value);
}
}
this.updateLegendValue(dataItem);
}
const hierarchyChildren = d3HierarchyNode.children;
if (hierarchyChildren) {
$array.each(hierarchyChildren, (d3HierarchyChild) => {
this._updateValues(d3HierarchyChild);
})
}
}
protected _makeHierarchyData(data: IHierarchyDataObject, dataItem: DataItem<IHierarchyDataItem>) {
data.dataItem = dataItem;
const children = dataItem.get("children");
if (children) {
const childrenDataArray: Array<IHierarchyDataObject> = [];
data.children = childrenDataArray;
$array.each(children, (childDataItem) => {
const childData = {};
childrenDataArray.push(childData);
this._makeHierarchyData(childData, childDataItem);
})
const value = dataItem.get("valueWorking");
if ($type.isNumber(value)) {
data.value = value;
}
}
else {
const value = dataItem.get("valueWorking");
if ($type.isNumber(value)) {
data.value = value;
}
}
}
/**
* @ignore
*/
public disposeDataItem(dataItem: DataItem<this["_dataItemSettings"]>) {
super.disposeDataItem(dataItem);
const node = dataItem.get("node");
if (node) {
this.nodes.removeValue(node);
node.dispose();
}
const label = dataItem.get("label");
if (label) {
this.labels.removeValue(label);
label.dispose();
}
const children = dataItem.get("children");
if (children) {
$array.each(children, (child) => {
this.disposeDataItem(child);
})
}
}
/**
* Hides hierarchy's data item.
*
* @param dataItem Data item
* @param duration Animation duration in milliseconds
* @return Promise
*/
public async hideDataItem(dataItem: DataItem<this["_dataItemSettings"]>, duration?: number): Promise<void> {
const promises = [super.hideDataItem(dataItem, duration)];
const hiddenState = this.states.create("hidden", {})
if (!$type.isNumber(duration)) {
const stateAnimationDuration = "stateAnimationDuration"
duration = hiddenState.get(stateAnimationDuration, this.get(stateAnimationDuration, 0));
}
const stateAnimationEasing = "stateAnimationEasing";
const easing = hiddenState.get(stateAnimationEasing, this.get(stateAnimationEasing));
const children = dataItem.get("children");
if ((!children || children.length == 0) && $type.isNumber(dataItem.get("value"))) {
promises.push(dataItem.animate({ key: "valueWorking" as any, to: 0, duration: duration, easing: easing }).waitForStop());
}
const node = dataItem.get("node");
node.hide();
node.hideTooltip();
if (children) {
$array.each(children, (childDataItem) => {
promises.push(this.hideDataItem(childDataItem));
})
}
await Promise.all(promises);
}
/**
* Shows hierarchy's data item.
*
* @param dataItem Data item
* @param duration Animation duration in milliseconds
* @return Promise
*/
public async showDataItem(dataItem: DataItem<this["_dataItemSettings"]>, duration?: number): Promise<void> {
const promises = [super.showDataItem(dataItem, duration)];
if (!$type.isNumber(duration)) {
duration = this.get("stateAnimationDuration", 0);
}
const easing = this.get("stateAnimationEasing");
const children = dataItem.get("children");
if ((!children || children.length == 0) && $type.isNumber(dataItem.get("value"))) {
promises.push(dataItem.animate({ key: "valueWorking" as any, to: dataItem.get("value"), duration: duration, easing: easing }).waitForStop());
}
const node = dataItem.get("node");
node.show();
if (children) {
$array.each(children, (childDataItem) => {
promises.push(this.showDataItem(childDataItem));
})
}
await Promise.all(promises);
}
/**
* Enables a disabled data item.
*
* @param dataItem Target data item
* @param duration Animation duration in milliseconds
*/
public enableDataItem(dataItem: DataItem<this["_dataItemSettings"]>, maxDepth?: number, depth?: number, duration?: number) {
if (depth == null) {
depth = 0;
}
if (maxDepth == null) {
maxDepth = 1;
}
dataItem.set("disabled", false);
dataItem.get("node").set("disabled", false);
if (!dataItem.isHidden()) {
dataItem.get("node").show(duration);
}
if (depth == 0) {
const upDepth = this.get("upDepth", Infinity);
let parent = dataItem;
let count = 0;
while (parent !== undefined) {
if (count > upDepth) {
parent.get("node").hide();
}
parent = parent.get("parent");
count++;
}
}
let children = dataItem.get("children");
if (children) {
if (depth < maxDepth - 1) {
$array.each(children, (child) => {
this.enableDataItem(child, maxDepth, depth as number + 1, duration);
})
}
else {
$array.each(children, (child) => {
if (!child.isHidden()) {
child.get("node").show(duration);
child.get("node").states.applyAnimate("disabled");
child.set("disabled", true);
this.disableDataItem(child);
}
})
}
}
}
/**
* Disables a data item.
*
* @param dataItem Target data item
* @param duration Animation duration in milliseconds
*/
public disableDataItem(dataItem: DataItem<this["_dataItemSettings"]>, duration?: number) {
dataItem.set("disabled", true);
let children = dataItem.get("children");
if (children) {
$array.each(children, (child) => {
this.disableDataItem(child, duration);
child.get("node").hide(duration);
})
}
}
protected _selectDataItem(dataItem?: DataItem<this["_dataItemSettings"]>, downDepth?: number) {
if (dataItem) {
const type = "dataitemselected";
this.events.dispatch(type, { type: type, target: this, dataItem: dataItem });
let maxDepth = this.getPrivate("maxDepth", 1);
const topDepth = this.get("topDepth", 0);
if (downDepth == null) {
downDepth = Math.min(this.get("downDepth", 1), maxDepth - dataItem.get("depth"));
}
if (!this.inited) {
downDepth = Math.min(this.get("initialDepth", 1), maxDepth - topDepth);
}
this._currentDownDepth = downDepth;
const hierarchyNode = dataItem.get("d3HierarchyNode");
let currentDepth = hierarchyNode.depth;
if (currentDepth + downDepth > maxDepth) {
downDepth = maxDepth - currentDepth;
}
if (currentDepth < topDepth) {
downDepth += topDepth - currentDepth;
currentDepth = topDepth;
}
const children = dataItem.get("children");
if (children && children.length > 0) {
if (downDepth > 0) {
this.enableDataItem(dataItem, downDepth);
}
else {
dataItem.get("node").show();
$array.each(children, (child) => {
child.get("node").hide();
})
}
if (hierarchyNode.depth < topDepth) {
dataItem.get("node").hide(0);
}
if (this.get("singleBranchOnly")) {
this._handleSingle(dataItem);
}
}
else {
this.enableDataItem(this.dataItems[0], downDepth, 0);
}
this._zoom(dataItem);
}
}
protected _zoom(_dataItem: DataItem<this["_dataItemSettings"]>) {
}
protected _handleSingle(dataItem: DataItem<this["_dataItemSettings"]>) {
const parent = dataItem.get("parent");
if (parent) {
const children = parent.get("children");
if (children) {
$array.each(children, (child) => {
if (child != dataItem) {
this.disableDataItem(child);
}
})
}
}
}
/**
* Selects specific data item.
*
* @param dataItem Target data item
*/
public selectDataItem(dataItem: DataItem<this["_dataItemSettings"]>) {
const parent = dataItem.get("parent");
const maxDepth = this.getPrivate("maxDepth", 1);
if (this.get("selectedDataItem") == dataItem) {
if (parent) {
this.set("selectedDataItem", parent);
}
else {
let depth = Math.min(this.get("downDepth", 1), maxDepth - dataItem.get("depth"));
if (this._currentDownDepth == depth) {
depth = Math.min(this.get("initialDepth", 1), maxDepth - this.get("topDepth", 0));
}
this._selectDataItem(dataItem, depth);
}
}
else {
this.set("selectedDataItem", dataItem);
}
}
protected _makeBullet(dataItem: DataItem<this["_dataItemSettings"]>, bulletFunction: (root: Root, series: Series, dataItem: DataItem<this["_dataItemSettings"]>) => Bullet | undefined, index?: number) {
const bullet = super._makeBullet(dataItem, bulletFunction, index);
if (bullet) {
const sprite = bullet.get("sprite");
const node = dataItem.get("node");
if (sprite) {
node.children.push(sprite);
node.on("width", () => {
this._positionBullet(bullet);
})
node.on("height", () => {
this._positionBullet(bullet);
})
}
}
return bullet;
}
public _positionBullet(bullet: Bullet) {
const sprite = bullet.get("sprite");
if (sprite) {
const dataItem = sprite.dataItem as DataItem<this["_dataItemSettings"]>;
const locationX = bullet.get("locationX", 0.5);
const locationY = bullet.get("locationY", 0.5);
const node = dataItem.get("node");
sprite.set("x", node.width() * locationX);
sprite.set("y", node.height() * locationY);
}
}
/**
* Triggers hover on a series data item.
*
* @since 5.0.7
* @param dataItem Target data item
*/
public hoverDataItem(dataItem: DataItem<this["_dataItemSettings"]>) {
const node = dataItem.get("node");
if (node && !node.isHidden()) {
node.hover();
}
}
/**
* Triggers un-hover on a series data item.
*
* @since 5.0.7
* @param dataItem Target data item
*/
public unhoverDataItem(dataItem: DataItem<this["_dataItemSettings"]>) {
const node = dataItem.get("node");
if (node) {
node.unhover();
}
}
} | the_stack |
import * as vscode from 'vscode';
import * as myExtension from '../extension/extension';
import * as chai from 'chai';
import * as chaiAsPromised from 'chai-as-promised';
import * as sinon from 'sinon';
import * as sinonChai from 'sinon-chai';
import * as path from 'path';
import { version as currentExtensionVersion } from '../package.json';
import { ExtensionUtil } from '../extension/util/ExtensionUtil';
import { DependencyManager } from '../extension/dependencies/DependencyManager';
import { VSCodeBlockchainOutputAdapter } from '../extension/logging/VSCodeBlockchainOutputAdapter';
import { TemporaryCommandRegistry } from '../extension/dependencies/TemporaryCommandRegistry';
import { TestUtil } from './TestUtil';
import { Reporter } from '../extension/util/Reporter';
import { ExtensionCommands } from '../ExtensionCommands';
import { LogType, FabricGatewayRegistry, FabricGatewayRegistryEntry, FabricEnvironmentRegistry, FabricEnvironmentRegistryEntry, EnvironmentType, EnvironmentFlags, FabricRuntimeUtil } from 'ibm-blockchain-platform-common';
import { SettingConfigurations } from '../extension/configurations';
import { UserInputUtil } from '../extension/commands/UserInputUtil';
import { dependencies } from '../package.json';
import { GlobalState, DEFAULT_EXTENSION_DATA, ExtensionData } from '../extension/util/GlobalState';
import { BlockchainGatewayExplorerProvider } from '../extension/explorer/gatewayExplorer';
import { BlockchainEnvironmentExplorerProvider } from '../extension/explorer/environmentExplorer';
import { BlockchainWalletExplorerProvider } from '../extension/explorer/walletExplorer';
import { LocalMicroEnvironmentManager } from '../extension/fabric/environments/LocalMicroEnvironmentManager';
chai.use(sinonChai);
chai.use(chaiAsPromised);
// tslint:disable no-unused-expression
describe('Extension Tests', () => {
const mySandBox: sinon.SinonSandbox = sinon.createSandbox();
let sendTelemetryStub: sinon.SinonStub;
let getPackageJSONStub: sinon.SinonStub;
let reporterDisposeStub: sinon.SinonStub;
let logSpy: sinon.SinonSpy;
let setupCommandsStub: sinon.SinonStub;
let completeActivationStub: sinon.SinonStub;
let setExtensionContextStub: sinon.SinonStub;
let hasPreReqsInstalledStub: sinon.SinonStub;
let registerPreActivationCommandsStub: sinon.SinonStub;
let createTempCommandsStub: sinon.SinonStub;
let showConfirmationWarningMessageStub: sinon.SinonStub;
before(async () => {
// We need this else TestUtil.setupTests() will fail when it tries to activate
await TestUtil.setupTests(mySandBox);
await vscode.workspace.getConfiguration().update(SettingConfigurations.EXTENSION_BYPASS_PREREQS, true, vscode.ConfigurationTarget.Global);
await vscode.workspace.getConfiguration().update(SettingConfigurations.HOME_SHOW_ON_STARTUP, false, vscode.ConfigurationTarget.Global);
await vscode.workspace.getConfiguration().update(SettingConfigurations.HOME_SHOW_ON_NEXT_ACTIVATION, false, vscode.ConfigurationTarget.Global);
});
beforeEach(async () => {
mySandBox.restore();
const extensionData: ExtensionData = DEFAULT_EXTENSION_DATA;
extensionData.dockerForWindows = true;
await GlobalState.update(extensionData);
await vscode.workspace.getConfiguration().update(SettingConfigurations.FABRIC_RUNTIME, {}, vscode.ConfigurationTarget.Global);
sendTelemetryStub = mySandBox.stub(Reporter.instance(), 'sendTelemetryEvent').resolves();
await vscode.workspace.getConfiguration().update(SettingConfigurations.EXTENSION_BYPASS_PREREQS, false, vscode.ConfigurationTarget.Global);
reporterDisposeStub = mySandBox.stub(Reporter.instance(), 'dispose');
getPackageJSONStub = mySandBox.stub(ExtensionUtil, 'getPackageJSON').returns({ production: true });
logSpy = mySandBox.spy(VSCodeBlockchainOutputAdapter.instance(), 'log');
setupCommandsStub = mySandBox.stub(ExtensionUtil, 'setupCommands');
completeActivationStub = mySandBox.stub(ExtensionUtil, 'completeActivation');
setExtensionContextStub = mySandBox.stub(GlobalState, 'setExtensionContext');
hasPreReqsInstalledStub = mySandBox.stub(DependencyManager.instance(), 'hasPreReqsInstalled');
registerPreActivationCommandsStub = mySandBox.stub(ExtensionUtil, 'registerPreActivationCommands');
createTempCommandsStub = mySandBox.stub(TemporaryCommandRegistry.instance(), 'createTempCommands');
showConfirmationWarningMessageStub = mySandBox.stub(UserInputUtil, 'showConfirmationWarningMessage').withArgs(`Detected old local environments which can not be used with this upgrade. Would you like to teardown these environments?`).resolves(false);
});
afterEach(async () => {
await GlobalState.reset();
mySandBox.restore();
});
describe('activate', () => {
it('should refresh the tree when a gateway connection is added', async () => {
await FabricGatewayRegistry.instance().clear();
const treeDataProvider: BlockchainGatewayExplorerProvider = ExtensionUtil.getBlockchainGatewayExplorerProvider();
const treeSpy: sinon.SinonSpy = mySandBox.spy(treeDataProvider['_onDidChangeTreeData'], 'fire');
const gateway: FabricGatewayRegistryEntry = new FabricGatewayRegistryEntry({
name: 'myGateway',
associatedWallet: '',
connectionProfilePath: path.join('blockchain', 'extension', 'directory', 'gatewayOne', 'connection.json')
});
await FabricGatewayRegistry.instance().add(gateway);
treeSpy.should.have.been.called;
});
it('should refresh all the trees when a environment connection is added', async () => {
await FabricEnvironmentRegistry.instance().clear();
const gatewayTreeDataProvider: BlockchainGatewayExplorerProvider = ExtensionUtil.getBlockchainGatewayExplorerProvider();
const gatewayTreeSpy: sinon.SinonSpy = mySandBox.spy(gatewayTreeDataProvider['_onDidChangeTreeData'], 'fire');
const environmentTreeDataProvider: BlockchainEnvironmentExplorerProvider = ExtensionUtil.getBlockchainEnvironmentExplorerProvider();
const environmentTreeSpy: sinon.SinonSpy = mySandBox.spy(environmentTreeDataProvider['_onDidChangeTreeData'], 'fire');
const walletTreeDataProvider: BlockchainWalletExplorerProvider = ExtensionUtil.getBlockchainWalletExplorerProvider();
const walletTreeSpy: sinon.SinonSpy = mySandBox.spy(walletTreeDataProvider['_onDidChangeTreeData'], 'fire');
const environment: FabricEnvironmentRegistryEntry = new FabricEnvironmentRegistryEntry({
name: 'myEnvironment',
environmentType: EnvironmentType.ENVIRONMENT
});
await FabricEnvironmentRegistry.instance().add(environment);
environmentTreeSpy.should.have.been.called;
gatewayTreeSpy.should.have.been.called;
walletTreeSpy.should.have.been.called;
});
it('should activate if required dependencies are installed and prereq page has been shown before', async () => {
setupCommandsStub.resolves();
completeActivationStub.resolves();
const context: vscode.ExtensionContext = GlobalState.getExtensionContext();
setExtensionContextStub.returns(undefined);
hasPreReqsInstalledStub.resolves(true);
const executeCommandSpy: sinon.SinonSpy = mySandBox.spy(vscode.commands, 'executeCommand');
registerPreActivationCommandsStub.resolves(context);
createTempCommandsStub.returns(undefined);
const extensionData: ExtensionData = DEFAULT_EXTENSION_DATA;
extensionData.preReqPageShown = true;
extensionData.dockerForWindows = true;
extensionData.version = currentExtensionVersion;
extensionData.generatorVersion = dependencies['generator-fabric'];
extensionData.createOneOrgLocalFabric = true;
extensionData.deletedOneOrgLocalFabric = false;
await GlobalState.update(extensionData);
await myExtension.activate(context);
logSpy.should.have.been.calledWith(LogType.IMPORTANT, undefined, 'Log files can be found by running the `Developer: Open Logs Folder` command from the palette', undefined, true);
logSpy.should.have.been.calledWith(LogType.INFO, undefined, 'Starting IBM Blockchain Platform Extension');
setExtensionContextStub.should.have.been.calledTwice;
createTempCommandsStub.should.have.been.calledOnceWith(true);
setupCommandsStub.should.have.been.calledOnce;
hasPreReqsInstalledStub.should.have.been.calledOnce;
registerPreActivationCommandsStub.should.have.been.calledOnce;
executeCommandSpy.should.not.have.been.calledWith(ExtensionCommands.OPEN_PRE_REQ_PAGE);
completeActivationStub.should.have.been.called;
});
it('should dispose of the reporter instance production flag is false on extension activiation', async () => {
getPackageJSONStub.returns({ production: false });
reporterDisposeStub.resolves();
setupCommandsStub.resolves();
completeActivationStub.resolves();
const context: vscode.ExtensionContext = GlobalState.getExtensionContext();
setExtensionContextStub.returns(undefined);
hasPreReqsInstalledStub.resolves(true);
const executeCommandSpy: sinon.SinonSpy = mySandBox.spy(vscode.commands, 'executeCommand');
registerPreActivationCommandsStub.resolves(context);
createTempCommandsStub.returns(undefined);
const extensionData: ExtensionData = DEFAULT_EXTENSION_DATA;
extensionData.preReqPageShown = true;
extensionData.dockerForWindows = true;
extensionData.migrationCheck = 2;
extensionData.version = currentExtensionVersion;
extensionData.generatorVersion = dependencies['generator-fabric'];
extensionData.createOneOrgLocalFabric = true;
extensionData.deletedOneOrgLocalFabric = false;
await GlobalState.update(extensionData);
await myExtension.activate(context);
logSpy.should.have.been.calledWith(LogType.IMPORTANT, undefined, 'Log files can be found by running the `Developer: Open Logs Folder` command from the palette', undefined, true);
logSpy.should.have.been.calledWith(LogType.INFO, undefined, 'Starting IBM Blockchain Platform Extension');
setExtensionContextStub.should.have.been.calledTwice;
createTempCommandsStub.should.have.been.calledOnceWith(true);
setupCommandsStub.should.have.been.calledOnce;
hasPreReqsInstalledStub.should.have.been.calledOnce;
registerPreActivationCommandsStub.should.have.been.calledOnce;
executeCommandSpy.should.not.have.been.calledWith(ExtensionCommands.OPEN_PRE_REQ_PAGE);
completeActivationStub.should.have.been.called;
reporterDisposeStub.should.have.been.called;
});
it('should open prereq page if not shown before', async () => {
setupCommandsStub.resolves();
completeActivationStub.resolves();
const context: vscode.ExtensionContext = GlobalState.getExtensionContext();
setExtensionContextStub.returns(undefined);
const executeCommandStub: sinon.SinonStub = mySandBox.stub(vscode.commands, 'executeCommand');
executeCommandStub.callThrough();
executeCommandStub.withArgs(ExtensionCommands.OPEN_PRE_REQ_PAGE).resolves();
hasPreReqsInstalledStub.resolves(true);
registerPreActivationCommandsStub.resolves(context);
createTempCommandsStub.returns(undefined);
const updateGlobalStateSpy: sinon.SinonSpy = mySandBox.spy(GlobalState, 'update');
const extensionData: ExtensionData = DEFAULT_EXTENSION_DATA;
extensionData.preReqPageShown = false;
extensionData.dockerForWindows = true;
extensionData.version = currentExtensionVersion;
extensionData.generatorVersion = dependencies['generator-fabric'];
extensionData.migrationCheck = 2;
extensionData.createOneOrgLocalFabric = true;
extensionData.deletedOneOrgLocalFabric = false;
await GlobalState.update(extensionData);
await myExtension.activate(context);
logSpy.should.have.been.calledWith(LogType.IMPORTANT, undefined, 'Log files can be found by running the `Developer: Open Logs Folder` command from the palette', undefined, true);
logSpy.should.have.been.calledWith(LogType.INFO, undefined, 'Starting IBM Blockchain Platform Extension');
setExtensionContextStub.should.have.been.calledTwice;
createTempCommandsStub.should.have.been.calledOnceWith(true);
setupCommandsStub.should.have.been.calledOnce;
hasPreReqsInstalledStub.should.have.been.calledOnce;
registerPreActivationCommandsStub.should.have.been.calledOnce;
executeCommandStub.should.have.been.calledWith(ExtensionCommands.OPEN_PRE_REQ_PAGE);
const preReqPageShown: boolean = updateGlobalStateSpy.getCalls()[1].args[0].preReqPageShown;
preReqPageShown.should.equal(true); // Should have updated the global state to say the PreReq page has now been shown
completeActivationStub.should.have.been.calledOnce;
});
it('should open prereq page if required dependencies aren\'t installed', async () => {
setupCommandsStub.resolves();
completeActivationStub.resolves();
const context: vscode.ExtensionContext = GlobalState.getExtensionContext();
setExtensionContextStub.returns(undefined);
const executeCommandStub: sinon.SinonStub = mySandBox.stub(vscode.commands, 'executeCommand');
executeCommandStub.callThrough();
executeCommandStub.withArgs(ExtensionCommands.OPEN_PRE_REQ_PAGE).resolves();
hasPreReqsInstalledStub.resolves(false);
registerPreActivationCommandsStub.resolves(context);
createTempCommandsStub.returns(undefined);
const extensionData: ExtensionData = DEFAULT_EXTENSION_DATA;
extensionData.preReqPageShown = true;
extensionData.dockerForWindows = true;
extensionData.version = currentExtensionVersion;
extensionData.generatorVersion = dependencies['generator-fabric'];
extensionData.migrationCheck = 2;
extensionData.createOneOrgLocalFabric = true;
extensionData.deletedOneOrgLocalFabric = false;
await GlobalState.update(extensionData);
await myExtension.activate(context);
logSpy.should.have.been.calledWith(LogType.IMPORTANT, undefined, 'Log files can be found by running the `Developer: Open Logs Folder` command from the palette', undefined, true);
logSpy.should.have.been.calledWith(LogType.INFO, undefined, 'Starting IBM Blockchain Platform Extension');
setExtensionContextStub.should.have.been.calledTwice;
hasPreReqsInstalledStub.should.have.been.calledOnce;
createTempCommandsStub.should.have.been.calledOnceWith(false, ExtensionCommands.OPEN_PRE_REQ_PAGE);
setupCommandsStub.should.not.have.been.called;
registerPreActivationCommandsStub.should.have.been.calledOnce;
executeCommandStub.should.have.been.calledWith(ExtensionCommands.OPEN_PRE_REQ_PAGE);
completeActivationStub.should.not.have.been.called;
});
it('should activate if the extension has been updated', async () => {
const releaseNotesPath: string = path.join(ExtensionUtil.getExtensionPath(), 'RELEASE-NOTES.md');
const releaseNotesUri: vscode.Uri = vscode.Uri.file(releaseNotesPath);
setupCommandsStub.resolves();
completeActivationStub.resolves();
const context: vscode.ExtensionContext = GlobalState.getExtensionContext();
setExtensionContextStub.returns(undefined);
const executeCommandStub: sinon.SinonStub = mySandBox.stub(vscode.commands, 'executeCommand');
executeCommandStub.callThrough();
executeCommandStub.withArgs('markdown.showPreview', releaseNotesUri).resolves();
hasPreReqsInstalledStub.resolves(true);
registerPreActivationCommandsStub.resolves(context);
createTempCommandsStub.returns(undefined);
const extensionData: ExtensionData = DEFAULT_EXTENSION_DATA;
extensionData.preReqPageShown = true;
extensionData.dockerForWindows = true;
extensionData.version = '2.0.0-beta.9';
extensionData.generatorVersion = dependencies['generator-fabric'];
extensionData.migrationCheck = 2;
extensionData.createOneOrgLocalFabric = true;
extensionData.deletedOneOrgLocalFabric = false;
await GlobalState.update(extensionData);
await myExtension.activate(context);
sendTelemetryStub.should.have.been.calledWith('updatedInstall', { IBM: sinon.match.string });
logSpy.should.have.been.calledWith(LogType.IMPORTANT, undefined, 'Log files can be found by running the `Developer: Open Logs Folder` command from the palette', undefined, true);
logSpy.should.have.been.calledWith(LogType.INFO, undefined, 'Starting IBM Blockchain Platform Extension');
setExtensionContextStub.should.have.been.calledTwice;
hasPreReqsInstalledStub.should.have.been.calledOnce;
createTempCommandsStub.should.have.been.calledOnceWith(true);
setupCommandsStub.should.have.been.calledOnce;
hasPreReqsInstalledStub.should.have.been.calledOnce;
registerPreActivationCommandsStub.should.have.been.calledOnce;
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.OPEN_PRE_REQ_PAGE);
executeCommandStub.should.have.been.calledWith('markdown.showPreview', releaseNotesUri);
completeActivationStub.should.have.been.calledOnce;
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.DELETE_ENVIRONMENT);
});
it(`should delete any local environments or ansible environments`, async () => {
const releaseNotesPath: string = path.join(ExtensionUtil.getExtensionPath(), 'RELEASE-NOTES.md');
const releaseNotesUri: vscode.Uri = vscode.Uri.file(releaseNotesPath);
setupCommandsStub.resolves();
completeActivationStub.resolves();
const context: vscode.ExtensionContext = GlobalState.getExtensionContext();
setExtensionContextStub.returns(undefined);
const executeCommandStub: sinon.SinonStub = mySandBox.stub(vscode.commands, 'executeCommand');
executeCommandStub.callThrough();
executeCommandStub.withArgs('markdown.showPreview', releaseNotesUri).resolves();
executeCommandStub.withArgs(ExtensionCommands.DELETE_ENVIRONMENT).resolves();
hasPreReqsInstalledStub.resolves(true);
registerPreActivationCommandsStub.resolves(context);
createTempCommandsStub.returns(undefined);
const extensionData: ExtensionData = DEFAULT_EXTENSION_DATA;
extensionData.preReqPageShown = true;
extensionData.dockerForWindows = true;
extensionData.version = '2.0.0-beta.9';
extensionData.generatorVersion = dependencies['generator-fabric'];
extensionData.migrationCheck = 2;
extensionData.createOneOrgLocalFabric = true;
extensionData.deletedOneOrgLocalFabric = false;
await GlobalState.update(extensionData);
const oldOtherEntry: FabricEnvironmentRegistryEntry = new FabricEnvironmentRegistryEntry({name: 'oldlocal', environmentType: EnvironmentType.LOCAL_ENVIRONMENT, numberOfOrgs: 1});
const ansibleEntry: FabricEnvironmentRegistryEntry = new FabricEnvironmentRegistryEntry({name: 'oldAnsible', environmentType: EnvironmentType.ANSIBLE_ENVIRONMENT, environmentDirectory: '/some/path'});
const getAllEnvironmentsStub: sinon.SinonStub = mySandBox.stub(FabricEnvironmentRegistry.instance(), 'getAll');
getAllEnvironmentsStub.resolves([oldOtherEntry, ansibleEntry]);
const initializeStub: sinon.SinonStub = mySandBox.stub(LocalMicroEnvironmentManager.instance(), 'initialize').resolves();
await myExtension.activate(context);
getAllEnvironmentsStub.should.have.been.calledOnceWithExactly([EnvironmentFlags.ANSIBLE]);
executeCommandStub.should.have.been.calledWith(ExtensionCommands.DELETE_ENVIRONMENT, oldOtherEntry, true);
executeCommandStub.should.have.been.calledWith(ExtensionCommands.DELETE_ENVIRONMENT, ansibleEntry, true);
sendTelemetryStub.should.have.been.calledWith('updatedInstall', { IBM: sinon.match.string });
initializeStub.should.not.have.been.called;
logSpy.should.have.been.calledWith(LogType.IMPORTANT, undefined, 'Log files can be found by running the `Developer: Open Logs Folder` command from the palette', undefined, true);
logSpy.should.have.been.calledWith(LogType.INFO, undefined, 'Starting IBM Blockchain Platform Extension');
setExtensionContextStub.should.have.been.calledTwice;
hasPreReqsInstalledStub.should.have.been.calledOnce;
createTempCommandsStub.should.have.been.calledOnceWith(true);
setupCommandsStub.should.have.been.calledOnce;
hasPreReqsInstalledStub.should.have.been.calledOnce;
registerPreActivationCommandsStub.should.have.been.calledOnce;
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.OPEN_PRE_REQ_PAGE);
executeCommandStub.should.have.been.calledWith('markdown.showPreview', releaseNotesUri);
completeActivationStub.should.have.been.calledOnce;
});
it(`should delete any local environments and start a new ${FabricRuntimeUtil.LOCAL_FABRIC} if an older version existed`, async () => {
const releaseNotesPath: string = path.join(ExtensionUtil.getExtensionPath(), 'RELEASE-NOTES.md');
const releaseNotesUri: vscode.Uri = vscode.Uri.file(releaseNotesPath);
setupCommandsStub.resolves();
completeActivationStub.resolves();
const context: vscode.ExtensionContext = GlobalState.getExtensionContext();
setExtensionContextStub.returns(undefined);
const executeCommandStub: sinon.SinonStub = mySandBox.stub(vscode.commands, 'executeCommand');
executeCommandStub.callThrough();
executeCommandStub.withArgs('markdown.showPreview', releaseNotesUri).resolves();
executeCommandStub.withArgs(ExtensionCommands.DELETE_ENVIRONMENT).resolves();
hasPreReqsInstalledStub.resolves(true);
registerPreActivationCommandsStub.resolves(context);
createTempCommandsStub.returns(undefined);
const extensionData: ExtensionData = DEFAULT_EXTENSION_DATA;
extensionData.preReqPageShown = true;
extensionData.dockerForWindows = true;
extensionData.version = '2.0.0-beta.9';
extensionData.generatorVersion = dependencies['generator-fabric'];
extensionData.migrationCheck = 2;
extensionData.createOneOrgLocalFabric = true;
extensionData.deletedOneOrgLocalFabric = false;
await GlobalState.update(extensionData);
const oldOneOrgEntry: FabricEnvironmentRegistryEntry = new FabricEnvironmentRegistryEntry({name: FabricRuntimeUtil.LOCAL_FABRIC, environmentType: EnvironmentType.LOCAL_ENVIRONMENT, numberOfOrgs: 1});
const oldOtherEntry: FabricEnvironmentRegistryEntry = new FabricEnvironmentRegistryEntry({name: 'oldlocal', environmentType: EnvironmentType.LOCAL_ENVIRONMENT, numberOfOrgs: 1});
const getAllEnvironmentsStub: sinon.SinonStub = mySandBox.stub(FabricEnvironmentRegistry.instance(), 'getAll');
getAllEnvironmentsStub.resolves([oldOneOrgEntry, oldOtherEntry]);
const initializeStub: sinon.SinonStub = mySandBox.stub(LocalMicroEnvironmentManager.instance(), 'initialize').resolves();
await myExtension.activate(context);
getAllEnvironmentsStub.should.have.been.calledOnceWithExactly([EnvironmentFlags.ANSIBLE]);
executeCommandStub.should.have.been.calledWith(ExtensionCommands.DELETE_ENVIRONMENT, oldOneOrgEntry, true);
executeCommandStub.should.have.been.calledWith(ExtensionCommands.DELETE_ENVIRONMENT, oldOtherEntry, true);
sendTelemetryStub.should.have.been.calledWith('updatedInstall', { IBM: sinon.match.string });
initializeStub.should.have.been.calledOnceWithExactly(FabricRuntimeUtil.LOCAL_FABRIC, 1);
logSpy.should.have.been.calledWith(LogType.IMPORTANT, undefined, 'Log files can be found by running the `Developer: Open Logs Folder` command from the palette', undefined, true);
logSpy.should.have.been.calledWith(LogType.INFO, undefined, 'Starting IBM Blockchain Platform Extension');
setExtensionContextStub.should.have.been.calledTwice;
hasPreReqsInstalledStub.should.have.been.calledOnce;
createTempCommandsStub.should.have.been.calledOnceWith(true);
setupCommandsStub.should.have.been.calledOnce;
hasPreReqsInstalledStub.should.have.been.calledOnce;
registerPreActivationCommandsStub.should.have.been.calledOnce;
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.OPEN_PRE_REQ_PAGE);
executeCommandStub.should.have.been.calledWith('markdown.showPreview', releaseNotesUri);
completeActivationStub.should.have.been.calledOnce;
});
it('should remove any old settings', async () => {
const releaseNotesPath: string = path.join(ExtensionUtil.getExtensionPath(), 'RELEASE-NOTES.md');
const releaseNotesUri: vscode.Uri = vscode.Uri.file(releaseNotesPath);
setupCommandsStub.resolves();
completeActivationStub.resolves();
const context: vscode.ExtensionContext = GlobalState.getExtensionContext();
setExtensionContextStub.returns(undefined);
const executeCommandStub: sinon.SinonStub = mySandBox.stub(vscode.commands, 'executeCommand');
executeCommandStub.callThrough();
executeCommandStub.withArgs('markdown.showPreview', releaseNotesUri).resolves();
executeCommandStub.withArgs(ExtensionCommands.DELETE_ENVIRONMENT).resolves();
hasPreReqsInstalledStub.resolves(true);
registerPreActivationCommandsStub.resolves(context);
createTempCommandsStub.returns(undefined);
const extensionData: ExtensionData = DEFAULT_EXTENSION_DATA;
extensionData.preReqPageShown = true;
extensionData.dockerForWindows = true;
extensionData.version = '2.0.0-beta.9';
extensionData.generatorVersion = dependencies['generator-fabric'];
extensionData.migrationCheck = 2;
extensionData.createOneOrgLocalFabric = true;
extensionData.deletedOneOrgLocalFabric = false;
await GlobalState.update(extensionData);
const oldOneOrgEntry: FabricEnvironmentRegistryEntry = new FabricEnvironmentRegistryEntry({name: FabricRuntimeUtil.LOCAL_FABRIC, environmentType: EnvironmentType.LOCAL_ENVIRONMENT, numberOfOrgs: 1});
const oldOtherEntry: FabricEnvironmentRegistryEntry = new FabricEnvironmentRegistryEntry({name: 'oldlocal', environmentType: EnvironmentType.LOCAL_ENVIRONMENT, numberOfOrgs: 1});
const getAllEnvironmentsStub: sinon.SinonStub = mySandBox.stub(FabricEnvironmentRegistry.instance(), 'getAll');
getAllEnvironmentsStub.resolves([oldOneOrgEntry, oldOtherEntry]);
const initializeStub: sinon.SinonStub = mySandBox.stub(LocalMicroEnvironmentManager.instance(), 'initialize').resolves();
const originalSettings: any = vscode.workspace.getConfiguration().get(SettingConfigurations.FABRIC_RUNTIME, vscode.ConfigurationTarget.Global);
const newSettings: any = Object.assign({otherLocal: {startPort: 1000, endPort: 2000}, anotherLocal: {startPort: 3000, endPort: 4000}, microfabLocal: 9001}, originalSettings);
await vscode.workspace.getConfiguration().update(SettingConfigurations.FABRIC_RUNTIME, newSettings, vscode.ConfigurationTarget.Global);
await myExtension.activate(context);
const finalSettings: any = vscode.workspace.getConfiguration().get(SettingConfigurations.FABRIC_RUNTIME, vscode.ConfigurationTarget.Global);
finalSettings.should.deep.equal({
microfabLocal: 9001
});
getAllEnvironmentsStub.should.have.been.calledOnceWithExactly([EnvironmentFlags.ANSIBLE]);
executeCommandStub.should.have.been.calledWith(ExtensionCommands.DELETE_ENVIRONMENT, oldOneOrgEntry, true);
executeCommandStub.should.have.been.calledWith(ExtensionCommands.DELETE_ENVIRONMENT, oldOtherEntry, true);
sendTelemetryStub.should.have.been.calledWith('updatedInstall', { IBM: sinon.match.string });
initializeStub.should.have.been.calledOnceWithExactly(FabricRuntimeUtil.LOCAL_FABRIC, 1);
logSpy.should.have.been.calledWith(LogType.IMPORTANT, undefined, 'Log files can be found by running the `Developer: Open Logs Folder` command from the palette', undefined, true);
logSpy.should.have.been.calledWith(LogType.INFO, undefined, 'Starting IBM Blockchain Platform Extension');
setExtensionContextStub.should.have.been.calledTwice;
hasPreReqsInstalledStub.should.have.been.calledOnce;
createTempCommandsStub.should.have.been.calledOnceWith(true);
setupCommandsStub.should.have.been.calledOnce;
hasPreReqsInstalledStub.should.have.been.calledOnce;
registerPreActivationCommandsStub.should.have.been.calledOnce;
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.OPEN_PRE_REQ_PAGE);
executeCommandStub.should.have.been.calledWith('markdown.showPreview', releaseNotesUri);
completeActivationStub.should.have.been.calledOnce;
});
it('should set global state properties if a previous version has been used', async () => {
const releaseNotesPath: string = path.join(ExtensionUtil.getExtensionPath(), 'RELEASE-NOTES.md');
const releaseNotesUri: vscode.Uri = vscode.Uri.file(releaseNotesPath);
setupCommandsStub.resolves();
completeActivationStub.resolves();
const context: vscode.ExtensionContext = GlobalState.getExtensionContext();
setExtensionContextStub.returns(undefined);
const executeCommandStub: sinon.SinonStub = mySandBox.stub(vscode.commands, 'executeCommand');
executeCommandStub.callThrough();
executeCommandStub.withArgs('markdown.showPreview', releaseNotesUri).resolves();
hasPreReqsInstalledStub.resolves(true);
registerPreActivationCommandsStub.resolves(context);
createTempCommandsStub.returns(undefined);
const extensionData: ExtensionData = DEFAULT_EXTENSION_DATA;
extensionData.preReqPageShown = true;
extensionData.dockerForWindows = true;
extensionData.version = '1.0.6';
extensionData.generatorVersion = dependencies['generator-fabric'];
extensionData.migrationCheck = 2;
extensionData.createOneOrgLocalFabric = undefined;
extensionData.deletedOneOrgLocalFabric = undefined;
await GlobalState.update(extensionData);
const showInformationMessageStub: sinon.SinonStub = mySandBox.stub(vscode.window, 'showInformationMessage').resolves(undefined);
await myExtension.activate(context);
const newExtData: ExtensionData = GlobalState.get();
newExtData.createOneOrgLocalFabric.should.equal(true);
newExtData.deletedOneOrgLocalFabric.should.equal(false);
sendTelemetryStub.should.have.been.calledWith('updatedInstall', { IBM: sinon.match.string });
logSpy.should.have.been.calledWith(LogType.IMPORTANT, undefined, 'Log files can be found by running the `Developer: Open Logs Folder` command from the palette', undefined, true);
logSpy.should.have.been.calledWith(LogType.INFO, undefined, 'Starting IBM Blockchain Platform Extension');
setExtensionContextStub.should.have.been.calledTwice;
hasPreReqsInstalledStub.should.have.been.calledOnce;
createTempCommandsStub.should.have.been.calledOnceWith(true);
setupCommandsStub.should.have.been.calledOnce;
hasPreReqsInstalledStub.should.have.been.calledOnce;
registerPreActivationCommandsStub.should.have.been.calledOnce;
showInformationMessageStub.should.have.been.calledOnce;
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.OPEN_PRE_REQ_PAGE);
executeCommandStub.should.have.been.calledWith('markdown.showPreview', releaseNotesUri);
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.DELETE_ENVIRONMENT);
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.OPEN_FABRIC_2_PAGE);
completeActivationStub.should.have.been.calledOnce;
});
it('should not open release notes on first ever install', async () => {
setupCommandsStub.resolves();
completeActivationStub.resolves();
const context: vscode.ExtensionContext = GlobalState.getExtensionContext();
setExtensionContextStub.returns(undefined);
const executeCommandSpy: sinon.SinonSpy = mySandBox.spy(vscode.commands, 'executeCommand');
hasPreReqsInstalledStub.resolves(true);
registerPreActivationCommandsStub.resolves(context);
createTempCommandsStub.returns(undefined);
const extensionData: ExtensionData = DEFAULT_EXTENSION_DATA;
extensionData.preReqPageShown = true;
extensionData.dockerForWindows = true;
extensionData.version = null;
extensionData.generatorVersion = null;
extensionData.migrationCheck = 2;
extensionData.createOneOrgLocalFabric = true;
extensionData.deletedOneOrgLocalFabric = false;
await GlobalState.update(extensionData);
await myExtension.activate(context);
sendTelemetryStub.should.have.been.calledWith('newInstall', { IBM: sinon.match.string });
logSpy.should.have.been.calledWith(LogType.IMPORTANT, undefined, 'Log files can be found by running the `Developer: Open Logs Folder` command from the palette', undefined, true);
logSpy.should.have.been.calledWith(LogType.INFO, undefined, 'Starting IBM Blockchain Platform Extension');
setExtensionContextStub.should.have.been.calledTwice;
hasPreReqsInstalledStub.should.have.been.calledOnce;
createTempCommandsStub.should.have.been.calledOnceWith(true);
setupCommandsStub.should.have.been.calledOnce;
hasPreReqsInstalledStub.should.have.been.calledOnce;
registerPreActivationCommandsStub.should.have.been.calledOnce;
executeCommandSpy.should.not.have.been.calledWith(ExtensionCommands.OPEN_PRE_REQ_PAGE);
executeCommandSpy.should.not.have.been.calledWith('markdown.showPreview');
completeActivationStub.should.have.been.calledOnce;
});
it(`should report that the release notes can't be opened`, async () => {
const releaseNotesPath: string = path.join(ExtensionUtil.getExtensionPath(), 'RELEASE-NOTES.md');
const releaseNotesUri: vscode.Uri = vscode.Uri.file(releaseNotesPath);
const executeCommandStub: sinon.SinonStub = mySandBox.stub(vscode.commands, 'executeCommand');
executeCommandStub.callThrough();
const error: Error = new Error('unable to preview markdown');
executeCommandStub.withArgs('markdown.showPreview', releaseNotesUri).throws(error);
setupCommandsStub.resolves();
completeActivationStub.resolves();
const context: vscode.ExtensionContext = GlobalState.getExtensionContext();
setExtensionContextStub.returns(undefined);
hasPreReqsInstalledStub.resolves(true);
registerPreActivationCommandsStub.resolves(context);
createTempCommandsStub.returns(undefined);
const extensionData: ExtensionData = DEFAULT_EXTENSION_DATA;
extensionData.preReqPageShown = true;
extensionData.dockerForWindows = true;
extensionData.version = '1.0.6';
extensionData.generatorVersion = dependencies['generator-fabric'];
extensionData.migrationCheck = 2;
extensionData.createOneOrgLocalFabric = true;
extensionData.deletedOneOrgLocalFabric = false;
const showInformationMessageStub: sinon.SinonStub = mySandBox.stub(vscode.window, 'showInformationMessage').resolves(undefined);
await GlobalState.update(extensionData);
await myExtension.activate(context);
sendTelemetryStub.should.have.been.calledWith('updatedInstall', { IBM: sinon.match.string });
logSpy.should.have.been.calledWith(LogType.IMPORTANT, undefined, 'Log files can be found by running the `Developer: Open Logs Folder` command from the palette', undefined, true);
logSpy.should.have.been.calledWith(LogType.INFO, undefined, 'Starting IBM Blockchain Platform Extension');
logSpy.should.have.been.calledWith(LogType.ERROR, `Unable to open release notes: ${error.toString()}`);
setExtensionContextStub.should.have.been.calledTwice;
hasPreReqsInstalledStub.should.have.been.calledOnce;
createTempCommandsStub.should.have.been.calledOnceWith(true);
setupCommandsStub.should.have.been.calledOnce;
hasPreReqsInstalledStub.should.have.been.calledOnce;
registerPreActivationCommandsStub.should.have.been.calledOnce;
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.OPEN_PRE_REQ_PAGE);
executeCommandStub.should.have.been.calledWith('markdown.showPreview', releaseNotesUri);
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.DELETE_ENVIRONMENT);
completeActivationStub.should.have.been.calledOnce;
showInformationMessageStub.should.have.been.calledOnce;
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.OPEN_FABRIC_2_PAGE);
});
it('should activate extension and bypass prereqs', async () => {
const releaseNotesPath: string = path.join(ExtensionUtil.getExtensionPath(), 'RELEASE-NOTES.md');
const releaseNotesUri: vscode.Uri = vscode.Uri.file(releaseNotesPath);
await vscode.workspace.getConfiguration().update(SettingConfigurations.EXTENSION_BYPASS_PREREQS, true, vscode.ConfigurationTarget.Global);
setupCommandsStub.resolves();
completeActivationStub.resolves();
const context: vscode.ExtensionContext = GlobalState.getExtensionContext();
setExtensionContextStub.returns(undefined);
const executeCommandStub: sinon.SinonStub = mySandBox.stub(vscode.commands, 'executeCommand');
executeCommandStub.callThrough();
executeCommandStub.withArgs('markdown.showPreview', releaseNotesUri).resolves();
hasPreReqsInstalledStub.resolves(true);
registerPreActivationCommandsStub.resolves(context);
createTempCommandsStub.returns(undefined);
const extensionData: ExtensionData = DEFAULT_EXTENSION_DATA;
extensionData.preReqPageShown = true;
extensionData.dockerForWindows = true;
extensionData.version = '1.0.6';
extensionData.generatorVersion = dependencies['generator-fabric'];
extensionData.migrationCheck = 2;
extensionData.createOneOrgLocalFabric = true;
extensionData.deletedOneOrgLocalFabric = false;
const showInformationMessageStub: sinon.SinonStub = mySandBox.stub(vscode.window, 'showInformationMessage').resolves(undefined);
await GlobalState.update(extensionData);
await myExtension.activate(context);
sendTelemetryStub.should.have.been.calledWith('updatedInstall', { IBM: sinon.match.string });
logSpy.should.have.been.calledWith(LogType.IMPORTANT, undefined, 'Log files can be found by running the `Developer: Open Logs Folder` command from the palette', undefined, true);
logSpy.should.have.been.calledWith(LogType.INFO, undefined, 'Starting IBM Blockchain Platform Extension');
setExtensionContextStub.should.have.been.calledTwice;
hasPreReqsInstalledStub.should.not.have.been.called;
createTempCommandsStub.should.have.been.calledOnceWith(true);
setupCommandsStub.should.have.been.calledOnce;
registerPreActivationCommandsStub.should.have.been.calledOnce;
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.OPEN_PRE_REQ_PAGE);
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.DELETE_ENVIRONMENT);
completeActivationStub.should.have.been.calledOnce;
showInformationMessageStub.should.have.been.calledOnce;
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.OPEN_FABRIC_2_PAGE);
});
it(`should open 'whats new page' when major extension version has been updated and user selects 'Read more'`, async () => {
const releaseNotesPath: string = path.join(ExtensionUtil.getExtensionPath(), 'RELEASE-NOTES.md');
const releaseNotesUri: vscode.Uri = vscode.Uri.file(releaseNotesPath);
await vscode.workspace.getConfiguration().update(SettingConfigurations.EXTENSION_BYPASS_PREREQS, true, vscode.ConfigurationTarget.Global);
setupCommandsStub.resolves();
completeActivationStub.resolves();
const context: vscode.ExtensionContext = GlobalState.getExtensionContext();
setExtensionContextStub.returns(undefined);
const executeCommandStub: sinon.SinonStub = mySandBox.stub(vscode.commands, 'executeCommand');
executeCommandStub.callThrough();
executeCommandStub.withArgs('markdown.showPreview', releaseNotesUri).resolves();
executeCommandStub.withArgs(ExtensionCommands.OPEN_FABRIC_2_PAGE).resolves();
hasPreReqsInstalledStub.resolves(true);
registerPreActivationCommandsStub.resolves(context);
createTempCommandsStub.returns(undefined);
const extensionData: ExtensionData = DEFAULT_EXTENSION_DATA;
extensionData.preReqPageShown = true;
extensionData.dockerForWindows = true;
extensionData.version = '1.0.6';
extensionData.generatorVersion = dependencies['generator-fabric'];
extensionData.migrationCheck = 2;
extensionData.createOneOrgLocalFabric = true;
extensionData.deletedOneOrgLocalFabric = false;
const showInformationMessageStub: sinon.SinonStub = mySandBox.stub(vscode.window, 'showInformationMessage').resolves('Learn more');
await GlobalState.update(extensionData);
await myExtension.activate(context);
sendTelemetryStub.should.have.been.calledWith('updatedInstall', { IBM: sinon.match.string });
logSpy.should.have.been.calledWith(LogType.IMPORTANT, undefined, 'Log files can be found by running the `Developer: Open Logs Folder` command from the palette', undefined, true);
logSpy.should.have.been.calledWith(LogType.INFO, undefined, 'Starting IBM Blockchain Platform Extension');
setExtensionContextStub.should.have.been.calledTwice;
hasPreReqsInstalledStub.should.not.have.been.called;
createTempCommandsStub.should.have.been.calledOnceWith(true);
setupCommandsStub.should.have.been.calledOnce;
registerPreActivationCommandsStub.should.have.been.calledOnce;
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.OPEN_PRE_REQ_PAGE);
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.DELETE_ENVIRONMENT);
completeActivationStub.should.have.been.calledOnce;
showInformationMessageStub.should.have.been.calledOnce;
executeCommandStub.should.have.been.calledWith(ExtensionCommands.OPEN_FABRIC_2_PAGE);
});
it('should report if a new user has installed the extension', async () => {
setupCommandsStub.resolves();
completeActivationStub.resolves();
const context: vscode.ExtensionContext = GlobalState.getExtensionContext();
setExtensionContextStub.returns(undefined);
const executeCommandStub: sinon.SinonStub = mySandBox.stub(vscode.commands, 'executeCommand');
executeCommandStub.callThrough();
hasPreReqsInstalledStub.resolves(true);
registerPreActivationCommandsStub.resolves(context);
createTempCommandsStub.returns(undefined);
const extensionData: ExtensionData = DEFAULT_EXTENSION_DATA;
extensionData.preReqPageShown = true;
extensionData.dockerForWindows = true;
extensionData.version = null;
extensionData.generatorVersion = null;
extensionData.migrationCheck = 2;
extensionData.createOneOrgLocalFabric = true;
extensionData.deletedOneOrgLocalFabric = false;
await GlobalState.update(extensionData);
await myExtension.activate(context);
sendTelemetryStub.should.have.been.calledWith('newInstall', { IBM: sinon.match.string });
logSpy.should.have.been.calledWith(LogType.IMPORTANT, undefined, 'Log files can be found by running the `Developer: Open Logs Folder` command from the palette', undefined, true);
logSpy.should.have.been.calledWith(LogType.INFO, undefined, 'Starting IBM Blockchain Platform Extension');
setExtensionContextStub.should.have.been.calledTwice;
createTempCommandsStub.should.have.been.calledOnceWith(true);
hasPreReqsInstalledStub.should.have.been.calledOnce;
setupCommandsStub.should.have.been.calledOnce;
registerPreActivationCommandsStub.should.have.been.calledOnce;
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.OPEN_PRE_REQ_PAGE);
completeActivationStub.should.have.been.calledOnce;
});
it('should handle any errors when the extension fails to activate', async () => {
const context: vscode.ExtensionContext = GlobalState.getExtensionContext();
setExtensionContextStub.returns(undefined);
const releaseNotesPath: string = path.join(ExtensionUtil.getExtensionPath(), 'RELEASE-NOTES.md');
const releaseNotesUri: vscode.Uri = vscode.Uri.file(releaseNotesPath);
const extensionData: ExtensionData = DEFAULT_EXTENSION_DATA;
extensionData.preReqPageShown = true;
extensionData.dockerForWindows = true;
extensionData.version = currentExtensionVersion;
extensionData.generatorVersion = '1.0.6';
extensionData.migrationCheck = 2;
extensionData.createOneOrgLocalFabric = true;
extensionData.deletedOneOrgLocalFabric = false;
const showInformationMessageStub: sinon.SinonStub = mySandBox.stub(vscode.window, 'showInformationMessage').resolves(undefined);
await GlobalState.update(extensionData);
const error: Error = new Error('some error');
hasPreReqsInstalledStub.rejects(error);
const executeCommandStub: sinon.SinonStub = mySandBox.stub(vscode.commands, 'executeCommand');
executeCommandStub.callThrough();
executeCommandStub.withArgs('markdown.showPreview', releaseNotesUri).resolves();
const failedActivationWindowStub: sinon.SinonStub = mySandBox.stub(UserInputUtil, 'failedActivationWindow').resolves();
await myExtension.activate(context);
setExtensionContextStub.should.have.been.calledOnce;
hasPreReqsInstalledStub.should.have.been.called;
failedActivationWindowStub.should.have.been.calledOnceWithExactly('some error');
sendTelemetryStub.should.have.been.calledWith('activationFailed', { activationError: 'some error' });
logSpy.should.have.been.calledWith(LogType.ERROR, undefined, `Failed to activate extension: ${error.toString()}`, error.stack);
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.DELETE_ENVIRONMENT);
showInformationMessageStub.should.not.have.been.called;
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.OPEN_FABRIC_2_PAGE);
});
it('should add home page button to the status bar', async () => {
const releaseNotesPath: string = path.join(ExtensionUtil.getExtensionPath(), 'RELEASE-NOTES.md');
const releaseNotesUri: vscode.Uri = vscode.Uri.file(releaseNotesPath);
setupCommandsStub.resolves();
completeActivationStub.resolves();
const context: vscode.ExtensionContext = GlobalState.getExtensionContext();
setExtensionContextStub.returns(undefined);
hasPreReqsInstalledStub.resolves(true);
registerPreActivationCommandsStub.resolves(context);
createTempCommandsStub.returns(undefined);
const extensionData: ExtensionData = DEFAULT_EXTENSION_DATA;
extensionData.preReqPageShown = true;
extensionData.dockerForWindows = true;
extensionData.version = '1.0.6';
extensionData.generatorVersion = dependencies['generator-fabric'];
extensionData.migrationCheck = 2;
await GlobalState.update(extensionData);
const executeCommandStub: sinon.SinonStub = mySandBox.stub(vscode.commands, 'executeCommand');
executeCommandStub.callThrough();
executeCommandStub.withArgs('markdown.showPreview', releaseNotesUri).resolves();
const showInformationMessageStub: sinon.SinonStub = mySandBox.stub(vscode.window, 'showInformationMessage').resolves(undefined);
await myExtension.activate(context);
sendTelemetryStub.should.have.been.calledWith('updatedInstall', { IBM: sinon.match.string });
logSpy.should.have.been.calledWith(LogType.IMPORTANT, undefined, 'Log files can be found by running the `Developer: Open Logs Folder` command from the palette', undefined, true);
logSpy.should.have.been.calledWith(LogType.INFO, undefined, 'Starting IBM Blockchain Platform Extension');
setExtensionContextStub.should.have.been.calledTwice;
createTempCommandsStub.should.have.been.calledOnceWith(true);
setupCommandsStub.should.have.been.calledOnce;
registerPreActivationCommandsStub.should.have.been.calledOnce;
completeActivationStub.should.have.been.calledOnce;
const newContext: vscode.ExtensionContext = GlobalState.getExtensionContext();
const homePageButton: any = newContext.subscriptions.find((subscription: any) => {
return subscription.text === 'Blockchain Home';
});
homePageButton.tooltip.should.equal('View Homepage');
homePageButton.command.should.equal(ExtensionCommands.OPEN_HOME_PAGE);
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.DELETE_ENVIRONMENT);
showInformationMessageStub.should.have.been.calledOnce;
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.OPEN_FABRIC_2_PAGE);
});
it(`should ask user if they want to teardown old (v1 extension) local ansible environments if present when major extension version has been updated`, async () => {
const releaseNotesPath: string = path.join(ExtensionUtil.getExtensionPath(), 'RELEASE-NOTES.md');
const releaseNotesUri: vscode.Uri = vscode.Uri.file(releaseNotesPath);
const v1AnsibleLocal: FabricEnvironmentRegistryEntry = new FabricEnvironmentRegistryEntry({name: 'v1Ansible', environmentType: EnvironmentType.MANAGED, environmentDirectory: '/some/path'});
const getAllEnvironmentsStub: sinon.SinonStub = mySandBox.stub(FabricEnvironmentRegistry.instance(), 'getAll');
getAllEnvironmentsStub.onFirstCall().resolves([v1AnsibleLocal]);
getAllEnvironmentsStub.onSecondCall().resolves([]);
await vscode.workspace.getConfiguration().update(SettingConfigurations.EXTENSION_BYPASS_PREREQS, true, vscode.ConfigurationTarget.Global);
setupCommandsStub.resolves();
completeActivationStub.resolves();
const context: vscode.ExtensionContext = GlobalState.getExtensionContext();
setExtensionContextStub.returns(undefined);
const executeCommandStub: sinon.SinonStub = mySandBox.stub(vscode.commands, 'executeCommand');
executeCommandStub.callThrough();
executeCommandStub.withArgs('markdown.showPreview', releaseNotesUri).resolves();
executeCommandStub.withArgs(ExtensionCommands.OPEN_FABRIC_2_PAGE).resolves();
executeCommandStub.withArgs(ExtensionCommands.TEARDOWN_FABRIC, undefined, true, v1AnsibleLocal.name, true).resolves();
hasPreReqsInstalledStub.resolves(true);
registerPreActivationCommandsStub.resolves(context);
createTempCommandsStub.returns(undefined);
const extensionData: ExtensionData = DEFAULT_EXTENSION_DATA;
extensionData.preReqPageShown = true;
extensionData.dockerForWindows = true;
extensionData.version = '1.0.6';
extensionData.generatorVersion = dependencies['generator-fabric'];
extensionData.migrationCheck = 2;
extensionData.createOneOrgLocalFabric = true;
extensionData.deletedOneOrgLocalFabric = false;
const showInformationMessageStub: sinon.SinonStub = mySandBox.stub(vscode.window, 'showInformationMessage').resolves('Learn more');
await GlobalState.update(extensionData);
await myExtension.activate(context);
sendTelemetryStub.should.have.been.calledWith('updatedInstall', { IBM: sinon.match.string });
logSpy.should.have.been.calledWith(LogType.IMPORTANT, undefined, 'Log files can be found by running the `Developer: Open Logs Folder` command from the palette', undefined, true);
logSpy.should.have.been.calledWith(LogType.INFO, undefined, 'Starting IBM Blockchain Platform Extension');
showConfirmationWarningMessageStub.should.have.been.calledOnce;
setExtensionContextStub.should.have.been.calledTwice;
hasPreReqsInstalledStub.should.not.have.been.called;
createTempCommandsStub.should.have.been.calledOnceWith(true);
setupCommandsStub.should.have.been.calledOnce;
registerPreActivationCommandsStub.should.have.been.calledOnce;
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.TEARDOWN_FABRIC, undefined, true, v1AnsibleLocal.name, true);
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.OPEN_PRE_REQ_PAGE);
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.DELETE_ENVIRONMENT);
completeActivationStub.should.have.been.calledOnce;
showInformationMessageStub.should.have.been.calledOnce;
executeCommandStub.should.have.been.calledWith(ExtensionCommands.OPEN_FABRIC_2_PAGE);
});
it(`should teardown old v1 ansible local environments if present and user agrees when major extension version has been updated`, async () => {
const releaseNotesPath: string = path.join(ExtensionUtil.getExtensionPath(), 'RELEASE-NOTES.md');
const releaseNotesUri: vscode.Uri = vscode.Uri.file(releaseNotesPath);
const v1AnsibleLocal: FabricEnvironmentRegistryEntry = new FabricEnvironmentRegistryEntry({name: 'v1Ansible', environmentType: EnvironmentType.MANAGED, environmentDirectory: '/some/path'});
const getAllEnvironmentsStub: sinon.SinonStub = mySandBox.stub(FabricEnvironmentRegistry.instance(), 'getAll');
getAllEnvironmentsStub.onFirstCall().resolves([v1AnsibleLocal]);
getAllEnvironmentsStub.onSecondCall().resolves([]);
showConfirmationWarningMessageStub.resolves(true);
await vscode.workspace.getConfiguration().update(SettingConfigurations.EXTENSION_BYPASS_PREREQS, true, vscode.ConfigurationTarget.Global);
setupCommandsStub.resolves();
completeActivationStub.resolves();
const context: vscode.ExtensionContext = GlobalState.getExtensionContext();
setExtensionContextStub.returns(undefined);
const executeCommandStub: sinon.SinonStub = mySandBox.stub(vscode.commands, 'executeCommand');
executeCommandStub.callThrough();
executeCommandStub.withArgs('markdown.showPreview', releaseNotesUri).resolves();
executeCommandStub.withArgs(ExtensionCommands.OPEN_FABRIC_2_PAGE).resolves();
executeCommandStub.withArgs(ExtensionCommands.TEARDOWN_FABRIC, undefined, true, v1AnsibleLocal.name, true).resolves();
hasPreReqsInstalledStub.resolves(true);
registerPreActivationCommandsStub.resolves(context);
createTempCommandsStub.returns(undefined);
const extensionData: ExtensionData = DEFAULT_EXTENSION_DATA;
extensionData.preReqPageShown = true;
extensionData.dockerForWindows = true;
extensionData.version = '1.0.6';
extensionData.generatorVersion = dependencies['generator-fabric'];
extensionData.migrationCheck = 2;
extensionData.createOneOrgLocalFabric = true;
extensionData.deletedOneOrgLocalFabric = false;
const showInformationMessageStub: sinon.SinonStub = mySandBox.stub(vscode.window, 'showInformationMessage').resolves('Learn more');
await GlobalState.update(extensionData);
await myExtension.activate(context);
sendTelemetryStub.should.have.been.calledWith('updatedInstall', { IBM: sinon.match.string });
logSpy.should.have.been.calledWith(LogType.INFO, undefined, `Successful teardown of ${v1AnsibleLocal.name} environment.`);
logSpy.should.have.been.calledWith(LogType.IMPORTANT, undefined, 'Log files can be found by running the `Developer: Open Logs Folder` command from the palette', undefined, true);
logSpy.should.have.been.calledWith(LogType.INFO, undefined, 'Starting IBM Blockchain Platform Extension');
showConfirmationWarningMessageStub.should.have.been.calledOnce;
setExtensionContextStub.should.have.been.calledTwice;
hasPreReqsInstalledStub.should.not.have.been.called;
createTempCommandsStub.should.have.been.calledOnceWith(true);
setupCommandsStub.should.have.been.calledOnce;
registerPreActivationCommandsStub.should.have.been.calledOnce;
executeCommandStub.should.have.been.calledWith(ExtensionCommands.TEARDOWN_FABRIC, undefined, true, v1AnsibleLocal.name, true);
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.OPEN_PRE_REQ_PAGE);
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.DELETE_ENVIRONMENT);
completeActivationStub.should.have.been.calledOnce;
showInformationMessageStub.should.have.been.calledOnce;
executeCommandStub.should.have.been.calledWith(ExtensionCommands.OPEN_FABRIC_2_PAGE);
});
it(`should log error if teardown of old v1 ansible local environments fails when major extension version has been updated`, async () => {
const releaseNotesPath: string = path.join(ExtensionUtil.getExtensionPath(), 'RELEASE-NOTES.md');
const releaseNotesUri: vscode.Uri = vscode.Uri.file(releaseNotesPath);
const v1AnsibleLocal: FabricEnvironmentRegistryEntry = new FabricEnvironmentRegistryEntry({name: 'v1Ansible', environmentType: EnvironmentType.MANAGED, environmentDirectory: '/some/path'});
const getAllEnvironmentsStub: sinon.SinonStub = mySandBox.stub(FabricEnvironmentRegistry.instance(), 'getAll');
getAllEnvironmentsStub.onFirstCall().resolves([v1AnsibleLocal]);
getAllEnvironmentsStub.onSecondCall().resolves([]);
showConfirmationWarningMessageStub.resolves(true);
await vscode.workspace.getConfiguration().update(SettingConfigurations.EXTENSION_BYPASS_PREREQS, true, vscode.ConfigurationTarget.Global);
setupCommandsStub.resolves();
completeActivationStub.resolves();
const context: vscode.ExtensionContext = GlobalState.getExtensionContext();
setExtensionContextStub.returns(undefined);
const executeCommandStub: sinon.SinonStub = mySandBox.stub(vscode.commands, 'executeCommand');
executeCommandStub.callThrough();
executeCommandStub.withArgs('markdown.showPreview', releaseNotesUri).resolves();
executeCommandStub.withArgs(ExtensionCommands.OPEN_FABRIC_2_PAGE).resolves();
executeCommandStub.withArgs(ExtensionCommands.TEARDOWN_FABRIC, undefined, true, v1AnsibleLocal.name, true).rejects('some error');
hasPreReqsInstalledStub.resolves(true);
registerPreActivationCommandsStub.resolves(context);
createTempCommandsStub.returns(undefined);
const extensionData: ExtensionData = DEFAULT_EXTENSION_DATA;
extensionData.preReqPageShown = true;
extensionData.dockerForWindows = true;
extensionData.version = '1.0.6';
extensionData.generatorVersion = dependencies['generator-fabric'];
extensionData.migrationCheck = 2;
extensionData.createOneOrgLocalFabric = true;
extensionData.deletedOneOrgLocalFabric = false;
const showInformationMessageStub: sinon.SinonStub = mySandBox.stub(vscode.window, 'showInformationMessage').resolves('Learn more');
await GlobalState.update(extensionData);
await myExtension.activate(context);
sendTelemetryStub.should.have.been.calledWith('updatedInstall', { IBM: sinon.match.string });
logSpy.should.have.been.calledWith(LogType.ERROR, undefined, `Unable to teardown ${v1AnsibleLocal.name} environment: some error.`);
logSpy.should.have.been.calledWith(LogType.IMPORTANT, undefined, 'Log files can be found by running the `Developer: Open Logs Folder` command from the palette', undefined, true);
logSpy.should.have.been.calledWith(LogType.INFO, undefined, 'Starting IBM Blockchain Platform Extension');
showConfirmationWarningMessageStub.should.have.been.calledOnce;
setExtensionContextStub.should.have.been.calledTwice;
hasPreReqsInstalledStub.should.not.have.been.called;
createTempCommandsStub.should.have.been.calledOnceWith(true);
setupCommandsStub.should.have.been.calledOnce;
registerPreActivationCommandsStub.should.have.been.calledOnce;
executeCommandStub.should.have.been.calledWith(ExtensionCommands.TEARDOWN_FABRIC, undefined, true, v1AnsibleLocal.name, true);
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.OPEN_PRE_REQ_PAGE);
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.DELETE_ENVIRONMENT);
completeActivationStub.should.have.been.calledOnce;
showInformationMessageStub.should.have.been.calledOnce;
executeCommandStub.should.have.been.calledWith(ExtensionCommands.OPEN_FABRIC_2_PAGE);
});
it(`should not ask user if they want to teardown old (v1 extension) local ansible environments if none present when major extension version has been updated`, async () => {
const releaseNotesPath: string = path.join(ExtensionUtil.getExtensionPath(), 'RELEASE-NOTES.md');
const releaseNotesUri: vscode.Uri = vscode.Uri.file(releaseNotesPath);
const v1OpsTools: FabricEnvironmentRegistryEntry = new FabricEnvironmentRegistryEntry({name: 'v1Ansible', environmentType: 3 as EnvironmentType, environmentDirectory: '/some/path'});
const getAllEnvironmentsStub: sinon.SinonStub = mySandBox.stub(FabricEnvironmentRegistry.instance(), 'getAll');
getAllEnvironmentsStub.onFirstCall().resolves([v1OpsTools]);
getAllEnvironmentsStub.onSecondCall().resolves([]);
await vscode.workspace.getConfiguration().update(SettingConfigurations.EXTENSION_BYPASS_PREREQS, true, vscode.ConfigurationTarget.Global);
setupCommandsStub.resolves();
completeActivationStub.resolves();
const context: vscode.ExtensionContext = GlobalState.getExtensionContext();
setExtensionContextStub.returns(undefined);
const executeCommandStub: sinon.SinonStub = mySandBox.stub(vscode.commands, 'executeCommand');
executeCommandStub.callThrough();
executeCommandStub.withArgs('markdown.showPreview', releaseNotesUri).resolves();
executeCommandStub.withArgs(ExtensionCommands.OPEN_FABRIC_2_PAGE).resolves();
hasPreReqsInstalledStub.resolves(true);
registerPreActivationCommandsStub.resolves(context);
createTempCommandsStub.returns(undefined);
const extensionData: ExtensionData = DEFAULT_EXTENSION_DATA;
extensionData.preReqPageShown = true;
extensionData.dockerForWindows = true;
extensionData.version = '1.0.6';
extensionData.generatorVersion = dependencies['generator-fabric'];
extensionData.migrationCheck = 2;
extensionData.createOneOrgLocalFabric = true;
extensionData.deletedOneOrgLocalFabric = false;
const showInformationMessageStub: sinon.SinonStub = mySandBox.stub(vscode.window, 'showInformationMessage').resolves('Learn more');
await GlobalState.update(extensionData);
await myExtension.activate(context);
sendTelemetryStub.should.have.been.calledWith('updatedInstall', { IBM: sinon.match.string });
logSpy.should.have.been.calledWith(LogType.IMPORTANT, undefined, 'Log files can be found by running the `Developer: Open Logs Folder` command from the palette', undefined, true);
logSpy.should.have.been.calledWith(LogType.INFO, undefined, 'Starting IBM Blockchain Platform Extension');
showConfirmationWarningMessageStub.should.have.not.been.calledOnce;
setExtensionContextStub.should.have.been.calledTwice;
hasPreReqsInstalledStub.should.not.have.been.called;
createTempCommandsStub.should.have.been.calledOnceWith(true);
setupCommandsStub.should.have.been.calledOnce;
registerPreActivationCommandsStub.should.have.been.calledOnce;
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.TEARDOWN_FABRIC, undefined, true, v1OpsTools.name, true);
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.OPEN_PRE_REQ_PAGE);
executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.DELETE_ENVIRONMENT);
completeActivationStub.should.have.been.calledOnce;
showInformationMessageStub.should.have.been.calledOnce;
executeCommandStub.should.have.been.calledWith(ExtensionCommands.OPEN_FABRIC_2_PAGE);
});
});
describe('deactivate', () => {
it('should deactivate extension', async () => {
const context: vscode.ExtensionContext = GlobalState.getExtensionContext();
const getExtensionContextStub: sinon.SinonStub = mySandBox.stub(GlobalState, 'getExtensionContext').returns(context);
const disposeExtensionStub: sinon.SinonStub = mySandBox.stub(ExtensionUtil, 'disposeExtension').returns(undefined);
await myExtension.deactivate();
getExtensionContextStub.should.have.been.calledOnce;
reporterDisposeStub.should.have.been.calledOnce;
disposeExtensionStub.should.have.been.calledOnceWithExactly(context);
});
});
describe('txdata files', () => {
it('should associate .txdata files with JSON language', async () => {
getPackageJSONStub.callThrough();
const packageJSON: any = ExtensionUtil.getPackageJSON();
const languages: Array<{id: string, extensions: string[]}> = packageJSON.contributes.languages;
languages.should.deep.equal([{
id: 'json',
extensions: ['.txdata']
}]);
});
it('should associate a schema with .txdata files for validation', async () => {
getPackageJSONStub.callThrough();
const packageJSON: any = ExtensionUtil.getPackageJSON();
const jsonValidation: Array<{fileMatch: string, url: string}> = packageJSON.contributes.jsonValidation;
jsonValidation.should.deep.equal([{
fileMatch: '*.txdata',
url: './txdata.schema.json'
}]);
});
});
}); | the_stack |
import * as fs from 'fs';
import * as net from 'net';
import * as events from 'events';
import * as rpc from 'transparent-rpc';
import express from 'express';
import sockaddr from 'sockaddr';
import JsonDatagramSocket from '../util/json_datagram_socket';
import userToShardId from './shard';
import * as proto from './protocol';
import type Engine from './engine';
import type { WebSocketApi, WebhookApi } from './platform';
import type EngineManager from './enginemanager';
import EngineManagerClientK8s from './enginemanagerclient_k8s';
import * as Config from '../config';
let _instance : EngineManagerInterface;
function connectToMaster(shardId : number) {
const shard = Config.THINGENGINE_MANAGER_ADDRESS[shardId];
const socket = new net.Socket();
socket.connect(sockaddr(shard));
const jsonSocket = new JsonDatagramSocket<proto.MasterToFrontend, proto.FrontendToMaster>(socket, socket, 'utf8');
if (Config.THINGENGINE_MANAGER_AUTHENTICATION !== null)
jsonSocket.write({ control: 'auth', token: Config.THINGENGINE_MANAGER_AUTHENTICATION });
return jsonSocket;
}
type EngineProxy = rpc.Proxy<Engine> & {
websocket : rpc.Proxy<WebSocketApi>;
webhook : rpc.Proxy<WebhookApi>;
}
interface CachedEngine {
engine : Promise<EngineProxy>;
socket : rpc.Socket;
}
interface EngineManagerInterface extends events.EventEmitter {
getEngine(userId : number) : Promise<EngineProxy>;
dispatchWebhook(userId : number, req : express.Request, res : express.Response) : void;
start() : void;
stop() : void;
killAllUsers() : Promise<boolean>;
isRunning(userId : number) : Promise<boolean>;
getProcessId(userId : number) : Promise<number|string>;
startUser(userId : number) : Promise<void>;
killUser(userId : number) : Promise<void>;
deleteUser(userId : number) : Promise<void>;
clearCache(userId : number) : Promise<void>;
restartUser(userId : number) : Promise<void>;
restartUserWithoutCache(userId : number) : Promise<void>;
isK8s() : boolean;
}
class EngineManagerClientImpl extends events.EventEmitter {
private _cachedEngines : Map<number, CachedEngine>;
private _expectClose : boolean;
private _nShards : number;
private _rpcControls : Array<rpc.Proxy<EngineManager>|null>;
private _rpcSockets : Array<rpc.Socket|null>;
constructor() {
super();
this.setMaxListeners(Infinity);
this._cachedEngines = new Map;
this._expectClose = false;
_instance = this;
// one control+socket per shard
this._nShards = Config.THINGENGINE_MANAGER_ADDRESS.length;
this._rpcControls = new Array(this._nShards);
this._rpcSockets = new Array(this._nShards);
}
isK8s() {
return false;
}
getEngine(userId : number) : Promise<EngineProxy> {
if (this._cachedEngines.has(userId)) {
const cached = this._cachedEngines.get(userId)!;
return cached.engine;
}
const jsonSocket = connectToMaster(userToShardId(userId));
const rpcSocket = new rpc.Socket(jsonSocket);
let deleted = false;
rpcSocket.on('close', () => {
if (this._expectClose)
return;
console.log('Socket to user ID ' + userId + ' closed');
if (!deleted) {
this._cachedEngines.delete(userId);
this.emit('socket-closed', userId);
}
deleted = true;
});
const promise = new Promise<EngineProxy>((resolve, reject) => {
// if we still can, catch the error early and fail the request
rpcSocket.on('error', reject);
const initError = (msg : proto.MasterToFrontend) => {
if ('error' in msg) {
const err : Error & { code ?: string } = new Error(msg.error);
err.code = msg.code;
reject(err);
}
};
jsonSocket.on('data', initError);
const stub = {
ready(engine : EngineProxy, websocket : rpc.Proxy<WebSocketApi>, webhook : rpc.Proxy<WebhookApi>) {
jsonSocket.removeListener('data', initError);
engine.websocket = websocket;
engine.webhook = webhook;
resolve(engine);
},
error(message : string) {
reject(new Error(message));
},
$rpcMethods: ['ready', 'error'] as const
};
const replyId = rpcSocket.addStub(stub);
jsonSocket.write({ control:'direct', target: userId, replyId: replyId });
});
this._cachedEngines.set(userId, {
engine: promise,
socket: rpcSocket
});
return promise;
}
dispatchWebhook(userId : number, req : express.Request, res : express.Response) {
const id = req.params.id;
return this.getEngine(userId).then((engine) => {
return engine.webhook.handleCallback(id, req.method as 'GET'|'POST',
req.query as Record<string, string|string[]|undefined>, req.headers, req.body);
}).then((result) => {
if (result) {
if (result.contentType)
res.type(result.contentType);
res.status(result.code).send(result.response);
} else {
res.status(200).json({ result: 'ok' });
}
}).catch((err) => {
res.status(400).json({ error: err.message });
});
}
private _connect(shardId : number) {
if (this._rpcControls[shardId])
return;
const jsonSocket = connectToMaster(shardId);
const rpcSocket = new rpc.Socket(jsonSocket);
this._rpcSockets[shardId] = rpcSocket;
const ready = (msg : proto.MasterToFrontend) => {
if ('control' in msg && msg.control === 'ready') {
console.log(`Control channel to EngineManager[${shardId}] ready`);
this._rpcControls[shardId] = rpcSocket.getProxy(msg.rpcId) as rpc.Proxy<EngineManager>;
jsonSocket.removeListener('data', ready);
}
};
jsonSocket.on('data', ready);
jsonSocket.write({ control:'master' });
rpcSocket.on('close', () => {
this._rpcSockets[shardId] = null;
this._rpcControls[shardId] = null;
if (this._expectClose)
return;
console.log(`Control channel to EngineManager[${shardId}] severed`);
console.log('Reconnecting in 10s...');
setTimeout(() => {
this._connect(shardId);
}, 10000);
});
rpcSocket.on('error', () => {
// ignore the error, the socket will be closed soon and we'll deal with it
});
}
start() {
for (let i = 0; i < this._nShards; i++)
this._connect(i);
}
stop() {
this._expectClose = true;
for (const engine of this._cachedEngines.values())
engine.socket.end();
this._cachedEngines.clear();
for (let i = 0; i < this._nShards; i++) {
const socket = this._rpcSockets[i];
if (!socket)
continue;
socket.end();
}
}
async killAllUsers() : Promise<boolean> {
let ok = true;
for (let i = 0; i < this._nShards; i++) {
const ctrl = this._rpcControls[i];
if (!ctrl) {
ok = false;
continue;
}
if (!await ctrl.killAllUsers())
ok = false;
}
return ok;
}
async isRunning(userId : number) : Promise<boolean> {
const shardId = userToShardId(userId);
const ctrl = this._rpcControls[shardId];
if (!ctrl)
return false;
return ctrl.isRunning(userId);
}
async getProcessId(userId : number) {
const shardId = userToShardId(userId);
const ctrl = this._rpcControls[shardId];
if (!ctrl)
return -1;
return ctrl.getProcessId(userId);
}
async startUser(userId : number) {
const shardId = userToShardId(userId);
const ctrl = this._rpcControls[shardId];
if (!ctrl)
throw new Error('EngineManager died');
return ctrl.startUser(userId);
}
async killUser(userId : number) {
this._cachedEngines.delete(userId);
const shardId = userToShardId(userId);
const ctrl = this._rpcControls[shardId];
if (!ctrl)
throw new Error('EngineManager died');
return ctrl.killUser(userId);
}
async deleteUser(userId : number) {
this._cachedEngines.delete(userId);
const shardId = userToShardId(userId);
const ctrl = this._rpcControls[shardId];
if (!ctrl)
throw new Error('EngineManager died');
return ctrl.deleteUser(userId);
}
async clearCache(userId : number) {
this._cachedEngines.delete(userId);
const shardId = userToShardId(userId);
const ctrl = this._rpcControls[shardId];
if (!ctrl)
throw new Error('EngineManager died');
return ctrl.clearCache(userId);
}
async restartUser(userId : number) {
this._cachedEngines.delete(userId);
const shardId = userToShardId(userId);
const ctrl = this._rpcControls[shardId];
if (!ctrl)
throw new Error('EngineManager died');
return ctrl.restartUser(userId);
}
async restartUserWithoutCache(userId : number) {
this._cachedEngines.delete(userId);
const shardId = userToShardId(userId);
const ctrl = this._rpcControls[shardId];
if (!ctrl)
throw new Error('EngineManager died');
return ctrl.restartUserWithoutCache(userId);
}
}
export function init(useK8s : boolean) {
if (useK8s) {
const namespace = fs.readFileSync('/var/run/secrets/kubernetes.io/serviceaccount/namespace', 'utf-8');
_instance = new EngineManagerClientK8s(namespace);
} else {
_instance = new EngineManagerClientImpl();
}
}
export function get() : EngineManagerInterface {
if (!_instance)
init(false);
return _instance;
} | the_stack |
interface Bip32 {
public: number
private: number
}
export interface Network {
messagePrefix?: string
bip32: Bip32
pubKeyHash: number
scriptHash?: number
wif: number
dustSoftThreshold?: number
dustThreshold?: number
feePerKb?: number
ethereum?: boolean
}
const networks: { [key: string]: Network } = {}
networks.shadow = {
messagePrefix: '\x19ShadowCash Signed Message:\n',
bip32: {
public: 0xee80286a,
private: 0xee8031e8
},
pubKeyHash: 0x3f,
scriptHash: 0x7d,
wif: 0xbf,
dustThreshold: 0,
feePerKb: 1000
}
networks.shadowtn = {
messagePrefix: '\x19ShadowCash Signed Message:\n',
bip32: {
public: 0x76c0fdfb,
private: 0x76c1077a
},
pubKeyHash: 0x7f,
scriptHash: 0xc4,
wif: 0xff,
dustThreshold: 0,
feePerKb: 1000
}
networks.clam = {
bip32: {
public: 0xa8c26d64,
private: 0xa8c17826
},
pubKeyHash: 0x89,
wif: 0x85
}
networks.bitcoin = {
messagePrefix: '\x18Bitcoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 0x00,
scriptHash: 0x05,
wif: 0x80,
dustThreshold: 546, // https://github.com/bitcoin/bitcoin/blob/v0.9.2/src/core.h#L151-L162
feePerKb: 10000 // https://github.com/bitcoin/bitcoin/blob/v0.9.2/src/main.cpp#L53
}
networks.testnet = {
messagePrefix: '\x18Bitcoin Signed Message:\n',
bip32: {
public: 0x043587cf,
private: 0x04358394
},
pubKeyHash: 0x6f,
scriptHash: 0xc4,
wif: 0xef,
dustThreshold: 546,
feePerKb: 10000
}
networks.litecoin = {
messagePrefix: '\x19Litecoin Signed Message:\n',
bip32: {
public: 0x019da462,
private: 0x019d9cfe
},
pubKeyHash: 0x30,
scriptHash: 0x05,
wif: 0xb0,
dustThreshold: 0, // https://github.com/litecoin-project/litecoin/blob/v0.8.7.2/src/main.cpp#L360-L365
dustSoftThreshold: 100000, // https://github.com/litecoin-project/litecoin/blob/v0.8.7.2/src/main.h#L53
feePerKb: 100000 // https://github.com/litecoin-project/litecoin/blob/v0.8.7.2/src/main.cpp#L56
}
networks.dogecoin = {
messagePrefix: '\x19Dogecoin Signed Message:\n',
bip32: {
public: 0x02facafd,
private: 0x02fac398
},
pubKeyHash: 0x1e,
scriptHash: 0x16,
wif: 0x9e,
dustThreshold: 0, // https://github.com/dogecoin/dogecoin/blob/v1.7.1/src/core.h#L155-L160
dustSoftThreshold: 100000000, // https://github.com/dogecoin/dogecoin/blob/v1.7.1/src/main.h#L62
feePerKb: 100000000 // https://github.com/dogecoin/dogecoin/blob/v1.7.1/src/main.cpp#L58
}
networks.dash = {
messagePrefix: '\x19DarkCoin Signed Message:\n',
bip32: {
public: 0x02fe52f8,
private: 0x02fe52cc
},
pubKeyHash: 0x4c,
scriptHash: 0x10,
wif: 0xcc,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.viacoin = {
messagePrefix: '\x18Viacoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 0x47,
scriptHash: 0x21,
wif: 0xc7,
dustThreshold: 560,
dustSoftThreshold: 100000,
feePerKb: 100000 //
}
networks.viacointestnet = {
messagePrefix: '\x18Viacoin Signed Message:\n',
bip32: {
public: 0x043587cf,
private: 0x04358394
},
pubKeyHash: 0x7f,
scriptHash: 0xc4,
wif: 0xff,
dustThreshold: 560,
dustSoftThreshold: 100000,
feePerKb: 100000
}
networks.gamecredits = {
messagePrefix: '\x19Gamecredits Signed Message:\n',
bip32: {
public: 0x019da462,
private: 0x019d9cfe
},
pubKeyHash: 0x26,
scriptHash: 0x05,
wif: 0xa6,
dustThreshold: 0, // https://github.com/gamers-coin/gamers-coinv3/blob/master/src/main.cpp#L358-L363
dustSoftThreshold: 100000, // https://github.com/gamers-coin/gamers-coinv3/blob/master/src/main.cpp#L51
feePerKb: 100000 // https://github.com/gamers-coin/gamers-coinv3/blob/master/src/main.cpp#L54
}
networks.jumbucks = {
messagePrefix: '\x19Jumbucks Signed Message:\n',
bip32: {
public: 0x037a689a,
private: 0x037a6460
},
pubKeyHash: 0x2b,
scriptHash: 0x05,
wif: 0xab,
dustThreshold: 0,
dustSoftThreshold: 10000,
feePerKb: 10000
}
networks.zetacoin = {
messagePrefix: '\x18Zetacoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 0x50,
scriptHash: 0x09,
wif: 0xe0,
dustThreshold: 546, // https://github.com/zetacoin/zetacoin/blob/master/src/core.h#L159
feePerKb: 10000 // https://github.com/zetacoin/zetacoin/blob/master/src/main.cpp#L54
}
networks.nubits = {
messagePrefix: '\x18Nu Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 0x19,
scriptHash: 0x1a,
wif: 0x96,
dustThreshold: 100,
feePerKb: 100
}
networks.nushares = {
messagePrefix: '\x18Nu Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 0x3f,
scriptHash: 0x40,
wif: 0x95,
dustThreshold: 10000,
feePerKb: 10000
}
networks.blackcoin = {
messagePrefix: '\x18BlackCoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 0x19,
scriptHash: 0x55,
wif: 0x99,
dustThreshold: 1,
feePerKb: 10000
}
networks.potcoin = {
messagePrefix: '\x18PotCoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 55,
scriptHash: 5,
wif: 183,
dustThreshold: 1,
feePerKb: 100000
}
networks.batacoin = {
messagePrefix: '\x19Bata Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 25,
scriptHash: 5,
wif: 153,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.feathercoin = {
messagePrefix: '\x19Feathercoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 14,
scriptHash: 5,
wif: 142,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.gridcoin = {
messagePrefix: '\x19Gridcoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 62,
scriptHash: 85,
wif: 190,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.richcoin = {
messagePrefix: '\x19Richcoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 61,
scriptHash: 9,
wif: 128,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.auroracoin = {
messagePrefix: '\x19Auroracoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 23,
scriptHash: 5,
wif: 151,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.novacoin = {
messagePrefix: '\x19Novacoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 8,
scriptHash: 20,
wif: 136,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.cannacoin = {
messagePrefix: '\x19Cannacoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 28,
scriptHash: 5,
wif: 156,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.clubcoin = {
messagePrefix: '\x19Clubcoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 28,
scriptHash: 85,
wif: 153,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.digibyte = {
messagePrefix: '\x19Digibyte Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 30,
scriptHash: 5,
wif: 128,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.digitalcoin = {
messagePrefix: '\x19Digitalcoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 30,
scriptHash: 5,
wif: 158,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.edrcoin = {
messagePrefix: '\x19EDRcoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 93,
scriptHash: 28,
wif: 221,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.egulden = {
messagePrefix: '\x19e-Gulden Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 48,
scriptHash: 5,
wif: 176,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.gulden = {
messagePrefix: '\x19Gulden Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 38,
scriptHash: 5,
wif: 166,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.gcrcoin = {
messagePrefix: '\x19GCR Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 38,
scriptHash: 97,
wif: 154,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.monacoin = {
messagePrefix: '\x19Monacoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 50,
scriptHash: 5,
wif: 178,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.myriadcoin = {
messagePrefix: '\x19Myriadcoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 50,
scriptHash: 9,
wif: 178,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.neoscoin = {
messagePrefix: '\x19Neoscoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 53,
scriptHash: 5,
wif: 177,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.parkbyte = {
messagePrefix: '\x19ParkByte Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 55,
scriptHash: 28,
wif: 183,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.peercoin = {
messagePrefix: '\x19PPCoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 55,
scriptHash: 117,
wif: 183,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.pesobit = {
messagePrefix: '\x19Pesobit Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 55,
scriptHash: 85,
wif: 183,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.reddcoin = {
messagePrefix: '\x19Reddcoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 61,
scriptHash: 5,
wif: 189,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.primecoin = {
messagePrefix: '\x19Primecoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 23,
scriptHash: 83,
wif: 151,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.rubycoin = {
messagePrefix: '\x19Rubycoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 60,
scriptHash: 85,
wif: 188,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.smileycoin = {
messagePrefix: '\x19Smileycoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 25,
scriptHash: 5,
wif: 153,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.solarcoin = {
messagePrefix: '\x19SolarCoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 18,
scriptHash: 5,
wif: 146,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.syscoin = {
messagePrefix: '\x19Syscoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 63,
scriptHash: 5,
wif: 191,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.unobtanium = {
messagePrefix: '\x19Unobtanium Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 130,
scriptHash: 30,
wif: 224,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.vergecoin = {
messagePrefix: '\x19Vergecoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 30,
scriptHash: 33,
wif: 158,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.vertcoin = {
messagePrefix: '\x19Vertcoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 71,
scriptHash: 5,
wif: 199,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.vpncoin = {
messagePrefix: '\x19VpnCoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 71,
scriptHash: 5,
wif: 199,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.pivx = {
messagePrefix: '\x19PIVX Signed Message:\n',
bip32: {
public: 0x022d2533,
private: 0x0221312b
},
pubKeyHash: 30,
scriptHash: 13,
wif: 212
}
networks.eth = {
messagePrefix: '\x19Ethereum Signed Message:\n',
bip32: {
public: 0xffffffff,
private: 0xffffffff
},
scriptHash: 13,
pubKeyHash: 0xff,
wif: 0xff,
ethereum: true
}
networks.etc = {
bip32: {
public: 0xffffffff,
private: 0xffffffff
},
pubKeyHash: 0xff,
wif: 0xff,
ethereum: true
}
networks.clo = {
bip32: {
public: 0xffffffff,
private: 0xffffffff
},
pubKeyHash: 0xff,
wif: 0xff,
ethereum: true
}
networks.abncoin = {
messagePrefix: '\x19Abncoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 25,
scriptHash: 85,
wif: 153
}
networks.asiacoin = {
messagePrefix: '\x19Asiacoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 23,
scriptHash: 8,
wif: 151
}
networks.bitcoinplus = {
messagePrefix: '\x19Bitcoinplus Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 25,
scriptHash: 85,
wif: 153
}
networks.canadaecoin = {
messagePrefix: '\x19Canada eCoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 28,
scriptHash: 5,
wif: 156
}
networks.einsteinium = {
messagePrefix: '\x19Einsteinium Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 33,
scriptHash: 5,
wif: 161
}
networks.expanse = {
bip32: {
public: 0xffffffff,
private: 0xffffffff
},
pubKeyHash: 0xff,
wif: 0xff,
ethereum: true
}
networks.iop = {
messagePrefix: '\x19Internet of People Signed Message:\n',
bip32: {
public: 0x2780915f,
private: 0xae3416f6
},
pubKeyHash: 117,
scriptHash: 174,
wif: 49
}
networks.ixcoin = {
messagePrefix: '\x19Ixcoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 138,
scriptHash: 5,
wif: 128
}
networks.landcoin = {
messagePrefix: '\x19Landcoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 48,
scriptHash: 122,
wif: 176
}
networks.namecoin = {
messagePrefix: '\x19Namecoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 52,
scriptHash: 13,
wif: 180
}
networks.navcoin = {
messagePrefix: '\x19Navcoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 53,
scriptHash: 85,
wif: 150
}
networks.okcash = {
messagePrefix: '\x19Okcash Signed Message:\n',
bip32: {
public: 0x03cc23d7,
private: 0x03cc1c73
},
pubKeyHash: 55,
scriptHash: 28,
wif: 183
}
networks.posw = {
messagePrefix: '\x19POSWcoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 55,
scriptHash: 85,
wif: 183
}
networks.stratis = {
messagePrefix: '\x19Stratis Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488b2dd
},
pubKeyHash: 63,
scriptHash: 125,
wif: 191
}
networks.zcash = {
messagePrefix: '\x19Zcash Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 0x1cb8,
scriptHash: 0x1cbd,
wif: 128
}
networks.lbry = {
messagePrefix: '\x19LBRYcrd Signed Message:\n',
bip32: {
public: 0x019c354f,
private: 0x019c3118
},
pubKeyHash: 85,
scriptHash: 122,
wif: 28
}
networks.bela = {
messagePrefix: '\x19Belacoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 25,
scriptHash: 5,
wif: 153
}
networks.britcoin = {
messagePrefix: '\x19Britcoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 25,
scriptHash: 85,
wif: 153
}
networks.compcoin = {
messagePrefix: '\x19Compcoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 28,
scriptHash: 5,
wif: 156
}
networks.zcoin = {
messagePrefix: '\x19ZCoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 82,
scriptHash: 7,
wif: 210
}
networks.insane = {
messagePrefix: '\x19Insanecoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 102,
scriptHash: 57,
wif: 55
}
networks.ultimatesecurecash = {
messagePrefix: '\x19Ultimate Secure Cash Signed Message:\n',
bip32: {
public: 0xee80286a,
private: 0xee8031e8
},
pubKeyHash: 68,
scriptHash: 125,
wif: 137
}
networks.neurocoin = {
messagePrefix: '\x19PPCoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 53,
scriptHash: 117,
wif: 181
}
networks.hempcoin = {
messagePrefix: '\x19Hempcoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 40,
scriptHash: 8,
wif: 168
}
networks.linxcoin = {
messagePrefix: '\x19LinX Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 75,
scriptHash: 5,
wif: 203
}
networks.ecoin = {
messagePrefix: '\x19eCoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 92,
scriptHash: 20,
wif: 220
}
networks.denarius = {
messagePrefix: '\x19Denarius Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 30,
scriptHash: 90,
wif: 158
}
networks.pinkcoin = {
messagePrefix: '\x19Pinkcoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 3,
scriptHash: 28,
wif: 131
}
networks.flashcoin = {
messagePrefix: '\x19Flashcoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 68,
scriptHash: 130,
wif: 196
}
networks.defcoin = {
messagePrefix: '\x19defcoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 30,
scriptHash: 5,
wif: 158
}
networks.putincoin = {
messagePrefix: '\x19PutinCoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 55,
scriptHash: 20,
wif: 183
}
networks.zencash = {
messagePrefix: '\x19Zcash Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 0x2089,
scriptHash: 0x2096,
wif: 128
}
networks.smartcash = {
messagePrefix: '\x19SmartCash Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 63,
scriptHash: 18,
wif: 191
}
networks.fujicoin = {
messagePrefix: '\x19Fujicoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 36,
scriptHash: 16,
wif: 164
}
networks.mix = {
bip32: {
public: 0xffffffff,
private: 0xffffffff
},
pubKeyHash: 0xff,
wif: 0xff,
ethereum: true
}
networks.voxels = {
messagePrefix: '\x19Voxels Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 70,
scriptHash: 5,
wif: 198
}
networks.crown = {
messagePrefix: '\x19Crown Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 0,
scriptHash: 28,
wif: 128
}
networks.vcash = {
messagePrefix: '\x19Vcash Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 71,
scriptHash: 8,
wif: 199
}
networks.bridgecoin = {
messagePrefix: '\x19bridgecoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 27,
scriptHash: 50,
wif: 176
}
networks.bitsend = {
messagePrefix: '\x19Bitsend Signed Message:\n',
bip32: {
public: 0x02fe52f8,
private: 0x02fe52cc
},
pubKeyHash: 102,
scriptHash: 5,
wif: 204,
dustThreshold: 0,
dustSoftThreshold: 0,
feePerKb: 0
}
networks.bitcore = {
messagePrefix: '\x19BitCore Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 0,
scriptHash: 5,
wif: 128
}
networks.europecoin = {
messagePrefix: '\x19Bitcoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 33,
scriptHash: 5,
wif: 168
}
networks.toacoin = {
messagePrefix: '\x19TOA Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 65,
scriptHash: 23,
wif: 193
}
networks.diamond = {
messagePrefix: '\x19Diamond Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 90,
scriptHash: 8,
wif: 218
}
networks.adcoin = {
messagePrefix: '\x19AdCoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 23,
scriptHash: 5,
wif: 151
}
networks.Helleniccoin = {
messagePrefix: '\x19helleniccoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 48,
scriptHash: 5,
wif: 176
}
networks.bitcoincash = {
messagePrefix: '\x19Bitcoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 0x00,
scriptHash: 0x05,
wif: 0x80
}
networks.bitcoingold = {
messagePrefix: '\x19Bitcoin Gold Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 38,
scriptHash: 23,
wif: 128
}
networks.firstcoin = {
messagePrefix: '\x19FirstCoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 35,
scriptHash: 5,
wif: 163
}
networks.vivo = {
messagePrefix: '\x19DarkCoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 70,
scriptHash: 10,
wif: 198
}
networks.whitecoin = {
messagePrefix: '\x19Whitecoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 73,
scriptHash: 87,
wif: 201
}
networks.gobyte = {
messagePrefix: '\x19DarkCoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 38,
scriptHash: 10,
wif: 198
}
networks.groestlcoin = {
messagePrefix: '\x19GroestlCoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 36,
scriptHash: 5,
wif: 128
}
networks.newyorkcoin = {
messagePrefix: '\x19newyorkc Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 60,
scriptHash: 22,
wif: 188
}
networks.omni = {
messagePrefix: '\x19Bitcoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 0,
scriptHash: 5,
wif: 128
}
networks.bitcoinz = {
messagePrefix: '\x19BitcoinZ Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 0x1cb8,
scriptHash: 0x1cbd,
wif: 128
}
networks.poa = {
bip32: {
public: 0xffffffff,
private: 0xffffffff
},
pubKeyHash: 0xff,
wif: 0xff,
ethereum: true
}
networks.tether = {
messagePrefix: '\x19Bitcoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 0,
scriptHash: 5,
wif: 128
}
networks.bitcoinatom = {
messagePrefix: '\x19Bitcoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 23,
scriptHash: 10,
wif: 128
}
networks.crave = {
messagePrefix: '\x19DarkNet Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 70,
scriptHash: 85,
wif: 153
}
networks.exclusivecoin = {
messagePrefix: '\x19ExclusiveCoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 33,
scriptHash: 137,
wif: 161
}
networks.lynx = {
messagePrefix: '\x19Lynx Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 45,
scriptHash: 50,
wif: 173
}
networks.minexcoin = {
messagePrefix: '\x19Bitcoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 75,
scriptHash: 5,
wif: 128
}
networks.musicoin = {
bip32: {
public: 0xffffffff,
private: 0xffffffff
},
pubKeyHash: 0xff,
wif: 0xff,
ethereum: true
}
networks.wincoin = {
messagePrefix: '\x19WinCoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 73,
scriptHash: 83,
wif: 201
}
networks.zclassic = {
messagePrefix: '\x19Zcash Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 0x1cb8,
scriptHash: 0x1cbd,
wif: 128
}
networks.litecoincash = {
messagePrefix: '\x19Litecoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 28,
scriptHash: 50,
wif: 176
}
networks.bitcoinprivate = {
messagePrefix: '\x19Zcash Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 0x1325,
scriptHash: 0x13af,
wif: 128
}
networks.kobocoin = {
messagePrefix: '\x18Kobocoin Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 0x23,
scriptHash: 0x1c,
wif: 0xa3
}
networks.komodo = {
messagePrefix: '\x18Komodo Signed Message:\n',
bip32: {
public: 0x0488b21e,
private: 0x0488ade4
},
pubKeyHash: 0x3c,
scriptHash: 0x55,
wif: 0xbc
}
export { networks } | the_stack |
import { BN } from "bn.js";
import * as testUtils from "./helper/testUtils";
import { settleOrders } from "./helper/settleOrders";
import { market, TOKEN_CODES } from "./helper/testUtils";
import { BrokerVerifierContract } from "./bindings/broker_verifier";
import { DarknodeRegistryContract } from "./bindings/darknode_registry";
import { OrderbookContract } from "./bindings/orderbook";
import { PreciseTokenContract } from "./bindings/precise_token";
import { RenExBalancesContract } from "./bindings/ren_ex_balances";
import { RenExBrokerVerifierContract } from "./bindings/ren_ex_broker_verifier";
import { RenExSettlementContract } from "./bindings/ren_ex_settlement";
import { RenExTokensContract } from "./bindings/ren_ex_tokens";
import { RepublicTokenContract } from "./bindings/republic_token";
import { SettlementRegistryContract } from "./bindings/settlement_registry";
const {
DarknodeRegistry,
Orderbook,
RenExSettlement,
RenExBalances,
RenExTokens,
PreciseToken,
RepublicToken,
DGXToken,
RenExBrokerVerifier,
SettlementRegistry,
ApprovingBroker,
} = testUtils.contracts;
contract("RenEx", function (accounts: string[]) {
const buyer = accounts[0];
const seller = accounts[1];
let details: any[];
const VPT = 0x3;
const ALTBTC = 0x4;
const DGX_REN = market(TOKEN_CODES.DGX, TOKEN_CODES.REN);
const ETH_REN = market(TOKEN_CODES.ETH, TOKEN_CODES.REN);
before(async function () {
const dnr: DarknodeRegistryContract = await DarknodeRegistry.deployed();
const orderbook: OrderbookContract = await Orderbook.deployed();
const renExSettlement: RenExSettlementContract = await RenExSettlement.deployed();
const renExBalances: RenExBalancesContract = await RenExBalances.deployed();
const renExTokens: RenExTokensContract = await RenExTokens.deployed();
// PreciseToken
const preciseToken: PreciseTokenContract = await PreciseToken.new();
const ren: RepublicTokenContract = await RepublicToken.deployed();
const tokenAddresses = new Map<number, testUtils.BasicERC20>()
.set(TOKEN_CODES.BTC, testUtils.MockBTC)
.set(TOKEN_CODES.ETH, testUtils.MockETH)
.set(ALTBTC, testUtils.MockBTC)
.set(TOKEN_CODES.DGX, await DGXToken.deployed())
.set(TOKEN_CODES.REN, ren)
.set(VPT, preciseToken);
// Register ALTBTC
await renExTokens.registerToken(
ALTBTC,
tokenAddresses.get(ALTBTC).address,
new BN(await tokenAddresses.get(ALTBTC).decimals())
);
// Register VPT
await renExTokens.registerToken(
VPT, tokenAddresses.get(VPT).address,
new BN(await tokenAddresses.get(VPT).decimals())
);
// Register darknode
const darknode = accounts[2];
await ren.transfer(darknode, testUtils.minimumBond);
await ren.approve(dnr.address, testUtils.minimumBond, { from: darknode });
await dnr.register(darknode, testUtils.PUBK("1"), { from: darknode });
await testUtils.waitForEpoch(dnr);
const broker = accounts[3];
// Register broker
const renExBrokerVerifier: RenExBrokerVerifierContract =
await RenExBrokerVerifier.deployed();
await renExBrokerVerifier.registerBroker(broker);
details = [
buyer, seller, darknode, broker, renExSettlement, renExBalances,
tokenAddresses, orderbook, renExBrokerVerifier,
];
});
it("order 1", async () => {
const buy = { tokens: DGX_REN, price: 1, volume: 2 /* REN */, minimumVolume: 1 /* REN */ };
const sell = { tokens: DGX_REN, price: 0.95, volume: 1 /* REN */ };
(await settleOrders.apply(this, [buy, sell, ...details]))
.should.deep.equal([0.975 /* DGX */, 1 /* REN */]);
});
it("order 2", async () => {
const buy = { tokens: DGX_REN, price: 1, volume: 1.025641025641 /* REN */ };
const sell = { tokens: DGX_REN, price: 0.95, volume: 1.025641025641 /* REN */ };
(await settleOrders.apply(this, [buy, sell, ...details]))
.should.deep.equal([0.999999999 /* DGX */, 1.025641025641 /* REN */]);
});
it("order 3", async () => {
const buy = { tokens: DGX_REN, price: 0.5, volume: 4 /* REN */ };
const sell = { tokens: DGX_REN, price: 0.5, volume: 2 /* REN */ };
(await settleOrders.apply(this, [buy, sell, ...details]))
.should.deep.equal([1 /* DGX */, 2 /* REN */]);
});
it("order 4", async () => {
const buy = { tokens: DGX_REN, price: 1, volume: 1.9999999999 /* REN */ };
// More precise than the number of decimals DGX has
const sell = { tokens: DGX_REN, price: 0.0000000001, volume: 1.9999999999 /* REN */ };
(await settleOrders.apply(this, [buy, sell, ...details]))
.should.deep.equal([1 /* DGX */, 1.9999999999 /* REN */]);
});
it("order 5", async () => {
const buy = { tokens: DGX_REN, price: 999.5, volume: 0.002001501126 /* REN */ };
const sell = { tokens: DGX_REN, price: 999, volume: 0.002001501126 /* REN */ };
(await settleOrders.apply(this, [buy, sell, ...details]))
.should.deep.equal([2 /* DGX */, 0.002001501126 /* REN */]);
});
it("order 6", async () => {
const buy = { tokens: ETH_REN, price: 99950000, volume: "2.001e-9" /* REN */ };
const sell = { tokens: ETH_REN, price: 99950000, volume: "2.001e-9" /* REN */ };
(await settleOrders.apply(this, [buy, sell, ...details]))
.should.deep.equal([0.19999995 /* ETH */, 2.001e-9 /* REN */]);
});
it("order 7", async () => {
// Prices are at lowest precision possible, and mid-price is even more
// precise. If the mid-price is rounded, this test will fail.
const buy = { tokens: ETH_REN, price: 0.000000000002, volume: 1 /* REN */ };
const sell = { tokens: ETH_REN, price: 0.000000000001, volume: 1 /* REN */ };
(await settleOrders.apply(this, [buy, sell, ...details]))
.should.deep.equal([1.5e-12 /* ETH */, 1 /* REN */]);
});
it("atomic swap", async () => {
const tokens = market(TOKEN_CODES.BTC, TOKEN_CODES.ETH);
const buy = { settlement: 2, tokens, price: 1, volume: 2 /* DGX */, minimumVolume: 1 /* REN */ };
const sell = { settlement: 2, tokens, price: 0.95, volume: 1 /* REN */ };
(await settleOrders.apply(this, [buy, sell, ...details]))
.should.deep.equal([0.975 /* DGX */, 1 /* REN */]);
});
it("atomic fees are paid in ethereum-based token", async () => {
let tokens = market(TOKEN_CODES.ETH, ALTBTC);
let buy = { settlement: 2, tokens, price: 1, volume: 2 /* ETH */, minimumVolume: 1 /* ALTBTC */ };
let sell = { settlement: 2, tokens, price: 0.95, volume: 1 /* ALTBTC */ };
(await settleOrders.apply(this, [buy, sell, ...details]))
.should.deep.equal([0.975 /* ETH */, 1 /* ALTBTC */]);
});
context("(negative tests)", async () => {
const tokens = DGX_REN;
it("seller volume too low", async () => {
// Seller volume too low
let buy: any = { tokens, price: 1, volume: 2 /* DGX */, minimumVolume: 2 /* REN */ };
let sell: any = { tokens, price: 1, volume: 1 /* REN */ };
await settleOrders.apply(this, [buy, sell, ...details])
.should.be.rejectedWith(null, /incompatible orders/);
});
it("Buyer volume too low", async () => {
const buy = { tokens, price: 1, volume: 1 /* DGX */ };
const sell = { tokens, price: 1, volume: 2 /* REN */, minimumVolume: 2 /* REN */ };
await settleOrders.apply(this, [buy, sell, ...details])
.should.be.rejectedWith(null, /incompatible orders/);
});
it("Prices don't match", async () => {
const buy = { tokens, price: 1, volume: 1 /* DGX */ };
const sell = { tokens, price: 1.05, volume: 1 /* REN */, minimumVolume: 1 /* DGX */ };
await settleOrders.apply(this, [buy, sell, ...details])
.should.be.rejectedWith(null, /incompatible orders/);
});
it("Invalid tokens (should be DGX/REN, not REN/DGX)", async () => {
const REN_DGX = market(TOKEN_CODES.REN, TOKEN_CODES.DGX);
const buy = { tokens: REN_DGX, price: 1, volume: 2 /* DGX */, minimumVolume: 1 /* REN */ };
const sell = { tokens: REN_DGX, price: 0.95, volume: 1 /* REN */ };
await settleOrders.apply(this, [buy, sell, ...details])
.should.be.rejectedWith(null, /incompatible orders/);
});
it("Orders opened by the same trader", async () => {
const buy = { tokens, price: 1, volume: 2 /* DGX */, minimumVolume: 1 /* REN */ };
const sell = { tokens, price: 0.95, volume: 1 /* REN */, trader: buyer };
await settleOrders.apply(this, [buy, sell, ...details])
.should.be.rejectedWith(null, /orders from same trader/);
});
it("Unsupported settlement", async () => {
// Register unrelated settlement layer
const settlementRegistry: SettlementRegistryContract =
await SettlementRegistry.deployed();
const approvingBroker: BrokerVerifierContract = await ApprovingBroker.new();
await settlementRegistry.registerSettlement(3, approvingBroker.address, approvingBroker.address);
const buy = { settlement: 3, tokens, price: 1, volume: 2 /* DGX */, minimumVolume: 1 /* REN */ };
const sell = { settlement: 3, tokens, price: 0.95, volume: 1 /* REN */ };
await settleOrders.apply(this, [buy, sell, ...details])
.should.be.rejectedWith(null, /invalid settlement id/);
});
it("Token with too many decimals", async () => {
const ETH_VPT = market(TOKEN_CODES.ETH, VPT);
const buy = { tokens: ETH_VPT, price: 1e-12, volume: 1e-12 /* VPT */ };
const sell = { tokens: ETH_VPT, price: 1e-12, volume: 1e-12 /* VPT */ };
await settleOrders.apply(this, [buy, sell, ...details])
.should.be.rejectedWith(null, /invalid opcode/);
});
it("Atomic swap not involving Ether", async () => {
const BTC_ALT = market(TOKEN_CODES.BTC, ALTBTC);
const buy = { settlement: 2, tokens: BTC_ALT, price: 1, volume: 2 /* BTC */, minimumVolume: 1 /* ALT */ };
const sell = { settlement: 2, tokens: BTC_ALT, price: 0.95, volume: 1 /* ALTBTC */ };
await settleOrders.apply(this, [buy, sell, ...details])
.should.be.rejectedWith(null, /non-eth atomic swaps are not supported/);
});
});
}); | the_stack |
import { IJSONSchema } from '@opensumi/ide-core-common/lib/json-schema';
import { Color } from './color';
import { ITokenColorizationSetting } from './theme.service';
export const ISemanticTokenRegistry = Symbol('ISemanticTokenRegistry');
export const TOKEN_TYPE_WILDCARD = '*';
export const TOKEN_CLASSIFIER_LANGUAGE_SEPARATOR = ':';
export const CLASSIFIER_MODIFIER_SEPARATOR = '.';
const CHAR_LANGUAGE = TOKEN_CLASSIFIER_LANGUAGE_SEPARATOR.charCodeAt(0);
const CHAR_MODIFIER = CLASSIFIER_MODIFIER_SEPARATOR.charCodeAt(0);
// qualified string [type|*](.modifier)*(/language)!
export type TokenClassificationString = string;
export const idPattern = '\\w+[-_\\w+]*';
export const typeAndModifierIdPattern = `^${idPattern}$`;
export const selectorPattern = `^(${idPattern}|\\*)(\\${CLASSIFIER_MODIFIER_SEPARATOR}${idPattern})*(\\${TOKEN_CLASSIFIER_LANGUAGE_SEPARATOR}${idPattern})?$`;
export const fontStylePattern = '^(\\s*(italic|bold|underline))*\\s*$';
export interface TokenSelector {
match(type: string, modifiers: string[], language: string): number;
readonly id: string;
}
export interface SemanticTokenDefaultRule {
selector: TokenSelector;
defaults: TokenStyleDefaults;
}
export interface TokenTypeOrModifierContribution {
readonly num: number;
readonly id: string;
readonly superType?: string;
readonly description: string;
readonly deprecationMessage?: string;
}
export interface TokenStyleData {
foreground?: Color;
bold?: boolean;
underline?: boolean;
italic?: boolean;
}
export class TokenStyle implements Readonly<TokenStyleData> {
constructor(
public readonly foreground?: Color,
public readonly bold?: boolean,
public readonly underline?: boolean,
public readonly italic?: boolean,
) {}
}
export namespace TokenStyle {
export function toJSONObject(style: TokenStyle): any {
return {
_foreground: style.foreground === undefined ? null : Color.Format.CSS.formatHexA(style.foreground, true),
_bold: style.bold === undefined ? null : style.bold,
_underline: style.underline === undefined ? null : style.underline,
_italic: style.italic === undefined ? null : style.italic,
};
}
export function fromJSONObject(obj: any): TokenStyle | undefined {
if (obj) {
const boolOrUndef = (b: any) => (typeof b === 'boolean' ? b : undefined);
const colorOrUndef = (s: any) => (typeof s === 'string' ? Color.fromHex(s) : undefined);
return new TokenStyle(
colorOrUndef(obj._foreground),
boolOrUndef(obj._bold),
boolOrUndef(obj._underline),
boolOrUndef(obj._italic),
);
}
return undefined;
}
export function equals(s1: any, s2: any): boolean {
if (s1 === s2) {
return true;
}
return (
s1 !== undefined &&
s2 !== undefined &&
(s1.foreground instanceof Color ? s1.foreground.equals(s2.foreground) : s2.foreground === undefined) &&
s1.bold === s2.bold &&
s1.underline === s2.underline &&
s1.italic === s2.italic
);
}
export function is(s: any): s is TokenStyle {
return s instanceof TokenStyle;
}
export function fromData(data: {
foreground?: Color;
bold?: boolean;
underline?: boolean;
italic?: boolean;
}): TokenStyle {
return new TokenStyle(data.foreground, data.bold, data.underline, data.italic);
}
export function fromSettings(
foreground: string | undefined,
fontStyle: string | undefined,
bold?: boolean,
underline?: boolean,
italic?: boolean,
): TokenStyle {
let foregroundColor: Color | undefined;
if (foreground !== undefined) {
foregroundColor = Color.fromHex(foreground);
}
if (fontStyle !== undefined) {
bold = italic = underline = false;
const expression = /italic|bold|underline/g;
let match;
while ((match = expression.exec(fontStyle))) {
switch (match[0]) {
case 'bold':
bold = true;
break;
case 'italic':
italic = true;
break;
case 'underline':
underline = true;
break;
}
}
}
return new TokenStyle(foregroundColor, bold, underline, italic);
}
}
export interface SemanticTokenRule {
style: TokenStyle;
selector: TokenSelector;
}
export interface ITextMateThemingRule {
name?: string;
scope?: string | string[];
settings: ITokenColorizationSetting;
}
export type TokenStyleDefinition = SemanticTokenRule | ProbeScope[] | TokenStyleValue;
export type TokenStyleDefinitions = {
[P in keyof TokenStyleData]?: TokenStyleDefinition | undefined;
};
export type TextMateThemingRuleDefinitions = {
[P in keyof TokenStyleData]?: ITextMateThemingRule | undefined;
} & { scope?: ProbeScope };
/**
* A TokenStyle Value is either a token style literal, or a TokenClassificationString
*/
export type TokenStyleValue = TokenStyle | TokenClassificationString;
export type ProbeScope = string[];
export type Matcher<T> = (matcherInput: T) => number;
export const noMatch = (_scope: ProbeScope) => -1;
export function nameMatcher(identifers: string[], scope: ProbeScope): number {
function findInIdents(s: string, lastIndent: number): number {
for (let i = lastIndent - 1; i >= 0; i--) {
if (scopesAreMatching(s, identifers[i])) {
return i;
}
}
return -1;
}
if (scope.length < identifers.length) {
return -1;
}
let lastScopeIndex = scope.length - 1;
let lastIdentifierIndex = findInIdents(scope[lastScopeIndex--], identifers.length);
if (lastIdentifierIndex >= 0) {
const score = (lastIdentifierIndex + 1) * 0x10000 + identifers[lastIdentifierIndex].length;
while (lastScopeIndex >= 0) {
lastIdentifierIndex = findInIdents(scope[lastScopeIndex--], lastIdentifierIndex);
if (lastIdentifierIndex === -1) {
return -1;
}
}
return score;
}
return -1;
}
export interface MatcherWithPriority<T> {
matcher: Matcher<T>;
priority: -1 | 0 | 1;
}
function isIdentifier(token: string | null): token is string {
return !!token && !!token.match(/[\w.:]+/);
}
function newTokenizer(input: string): { next: () => string | null } {
const regex = /([LR]:|[\w.:][\w.:-]*|[,|\-()])/g;
let match = regex.exec(input);
return {
next: () => {
if (!match) {
return null;
}
const res = match[0];
match = regex.exec(input);
return res;
},
};
}
export function createMatchers<T>(
selector: string,
matchesName: (names: string[], matcherInput: T) => number,
results: MatcherWithPriority<T>[],
): void {
const tokenizer = newTokenizer(selector);
let token = tokenizer.next();
while (token !== null) {
let priority: -1 | 0 | 1 = 0;
if (token.length === 2 && token.charAt(1) === ':') {
switch (token.charAt(0)) {
case 'R':
priority = 1;
break;
case 'L':
priority = -1;
break;
default:
// eslint-disable-next-line no-console
console.log(`Unknown priority ${token} in scope selector`);
}
token = tokenizer.next();
}
const matcher = parseConjunction();
if (matcher) {
results.push({ matcher, priority });
}
if (token !== ',') {
break;
}
token = tokenizer.next();
}
function parseOperand(): Matcher<T> | null {
if (token === '-') {
token = tokenizer.next();
const expressionToNegate = parseOperand();
if (!expressionToNegate) {
return null;
}
return (matcherInput) => {
const score = expressionToNegate(matcherInput);
return score < 0 ? 0 : -1;
};
}
if (token === '(') {
token = tokenizer.next();
const expressionInParents = parseInnerExpression();
if (token === ')') {
token = tokenizer.next();
}
return expressionInParents;
}
if (isIdentifier(token)) {
const identifiers: string[] = [];
do {
identifiers.push(token);
token = tokenizer.next();
} while (isIdentifier(token));
return (matcherInput) => matchesName(identifiers, matcherInput);
}
return null;
}
function parseConjunction(): Matcher<T> | null {
let matcher = parseOperand();
if (!matcher) {
return null;
}
const matchers: Matcher<T>[] = [];
while (matcher) {
matchers.push(matcher);
matcher = parseOperand();
}
return (matcherInput) => {
// and
let min = matchers[0](matcherInput);
for (let i = 1; min >= 0 && i < matchers.length; i++) {
min = Math.min(min, matchers[i](matcherInput));
}
return min;
};
}
function parseInnerExpression(): Matcher<T> | null {
let matcher = parseConjunction();
if (!matcher) {
return null;
}
const matchers: Matcher<T>[] = [];
while (matcher) {
matchers.push(matcher);
if (token === '|' || token === ',') {
do {
token = tokenizer.next();
} while (token === '|' || token === ','); // ignore subsequent commas
} else {
break;
}
matcher = parseConjunction();
}
return (matcherInput) => {
// or
let max = matchers[0](matcherInput);
for (let i = 1; i < matchers.length; i++) {
max = Math.max(max, matchers[i](matcherInput));
}
return max;
};
}
}
function scopesAreMatching(thisScopeName: string, scopeName: string): boolean {
if (!thisScopeName) {
return false;
}
if (thisScopeName === scopeName) {
return true;
}
const len = scopeName.length;
return thisScopeName.length > len && thisScopeName.substr(0, len) === scopeName && thisScopeName[len] === '.';
}
export interface TokenStyleDefaults {
scopesToProbe?: ProbeScope[];
light?: TokenStyleValue;
dark?: TokenStyleValue;
hc?: TokenStyleValue;
}
export interface ISemanticTokenRegistry {
/**
* Parses a token selector from a selector string.
* @param selectorString selector string in the form (*|type)(.modifier)*
* @param language language to which the selector applies or undefined if the selector is for all language
* @returns the parsed selector
* @throws an error if the string is not a valid selector
*/
parseTokenSelector(selectorString: string, language?: string): TokenSelector;
/**
* Register a TokenStyle default to the registry.
* @param selector The rule selector
* @param defaults The default values
*/
registerTokenStyleDefault(selector: TokenSelector, defaults: TokenStyleDefaults): void;
/**
* Deregister a TokenStyle default to the registry.
* @param selector The rule selector
*/
deregisterTokenStyleDefault(selector: TokenSelector): void;
/**
* The styling rules to used when a schema does not define any styling rules.
*/
getTokenStylingDefaultRules(): SemanticTokenDefaultRule[];
/**
* Register a token type to the registry.
* @param id The TokenType id as used in theme description files
* @param description the description
*/
registerTokenType(id: string, description: string, superType?: string, deprecationMessage?: string): void;
/**
* Register a token modifier to the registry.
* @param id The TokenModifier id as used in theme description files
* @param description the description
*/
registerTokenModifier(id: string, description: string, deprecationMessage?: string): void;
}
export function parseClassifierString(
s: string,
defaultLanguage: string,
): { type: string; modifiers: string[]; language: string };
export function parseClassifierString(
s: string,
defaultLanguage?: string,
): { type: string; modifiers: string[]; language: string | undefined };
export function parseClassifierString(
s: string,
defaultLanguage: string | undefined,
): { type: string; modifiers: string[]; language: string | undefined } {
let k = s.length;
let language: string | undefined = defaultLanguage;
const modifiers: string[] = [];
for (let i = k - 1; i >= 0; i--) {
const ch = s.charCodeAt(i);
if (ch === CHAR_LANGUAGE || ch === CHAR_MODIFIER) {
const segment = s.substring(i + 1, k);
k = i;
if (ch === CHAR_LANGUAGE) {
language = segment;
} else {
modifiers.push(segment);
}
}
}
const type = s.substring(0, k);
return { type, modifiers, language };
}
export function getStylingSchemeEntry(description?: string, deprecationMessage?: string): IJSONSchema {
return {
description,
deprecationMessage,
defaultSnippets: [{ body: '${1:#ff0000}' }],
anyOf: [
{
type: 'string',
format: 'color-hex',
},
{
$ref: '#definitions/style',
},
],
};
} | the_stack |
import { throttle } from 'throttle-debounce';
export type TDraggableOptions = {
/**
* CSS selector of blocks that can be dragged
*/
draggableSelector: string;
/**
* CSS selector where draggable blocks can be placed
*/
containerSelector: string;
/**
* DOM element inside of which Draggable works. Used to insert draggable elements.
* Will use "body" tag by default if no elem specified.
*/
rootElement?: HTMLElement;
rootElementSelector?: string;
/**
* How to display element at the new place during dragging. Create a preview element
* cloning dragging one (will have impact on a layout which may lead to twitching)
* or just show an underline at the new place.
*/
dragPlacement?: 'element' | 'underline';
onBlockInserted?: (container: HTMLElement, draggedBlock: HTMLElement, nextElement?: Element | null) => void;
onTryToInsert?: (container: HTMLElement, draggedBlock: HTMLElement, shadow?: HTMLElement | null, nextElement?: Element | null) => void;
canInsertBlock?: (container: HTMLElement, draggedBlock: HTMLElement, nextElement?: Element | null) => boolean;
onBlockSelected?: (draggedBlock: HTMLElement) => void;
onBlockDeSelected?: (draggedBlock: HTMLElement) => void;
onBlockHoverStart?: (draggedBlock: HTMLElement) => void;
onBlockHoverEnd?: (draggedBlock: HTMLElement) => void;
canDeselectBlock?: (draggedBlock: HTMLElement) => boolean;
canDragBlock?: (draggedBlock: HTMLElement) => boolean;
getFrameColor?: (block: HTMLElement) => string;
ignoreDraggableClass?: string;
/**
* Disable actual DOM insert of elements into new positions? If true, will
* be used in "preview" mode and it'll create only block's shadows at new positions and remove
* them at mouseUp event, so no modification will be applied to the DOM at the end
* of a drag action.
* Use it to prevent React errors, since React must manage its elements by itself.
* In this case handle insertion manually via onBlockInserted prop.
*/
disableInsert?: boolean;
/**
* Color of frames
*/
primaryColor?: string;
/** Create a new draggable frame or find inside a block */
createFrame?: boolean;
draggableFrameClass?: string;
/** Custom document to work on (e.g. in iframe) */
document?: typeof document;
iframeSelector?: string;
disableClickAwayDeselect?: boolean;
applyZIndex?: boolean;
}
export class Draggable {
// Block on which drag started
private draggingBlock: HTMLElement | null = null;
// Copy of draggingBlock that attached to the mouse cursor
private draggingCursor: HTMLElement | null = null;
private hoveredBlock: HTMLElement | null = null;
private selectedBlock: HTMLElement | null = null;
private draggingBlockShadow: HTMLElement | null = null;
private draggableBlocks: (HTMLElement | null)[] = [];
private containers: (HTMLElement | null)[] | null = [];
private canDragBlock = false;
private isDragging = false;
private options: TDraggableOptions;
private document = document;
private onMouseDownInfo: {
clientY: number;
clientX: number;
} | null = null;
private onDragStartInfo: {
mousePosYinsideBlock: number;
mousePosXinsideBlock: number;
} | null = null;
private lastInsertionData: {
draggingBlock: HTMLElement;
container: HTMLElement;
afterElement: HTMLElement;
} | null = null;
public static draggableFrameClass: string = 'DraggableBlock__frame';
public static draggableBlockClass: string = 'DraggableBlock';
public static draggableFrameHoveredCSSclass: string = 'DraggableBlock__frame_hovered';
public static draggableFrameSelectedCSSclass: string = 'DraggableBlock__frame_selected';
public static draggingClass: string = 'DraggableBlock__dragging';
public static cursorClass: string = 'DraggableBlock__cursor';
private canInsertBlock?: TDraggableOptions['canInsertBlock'];
private onBlockInserted?: TDraggableOptions['onBlockInserted'];
constructor(options: TDraggableOptions) {
this.setupDraggableBlocks(options);
}
public setupDraggableBlocks = (options: TDraggableOptions) => {
const { draggableSelector, containerSelector } = options;
this.setOptions(options);
this.draggableBlocks = Array.from(this.document.querySelectorAll(draggableSelector)) as HTMLElement[];
this.containers = Array.from(this.document.querySelectorAll(containerSelector)) as HTMLElement[];
this.draggableBlocks.forEach(b => {
if (b) this.setupBlock(b);
});
}
public setOptions(options: TDraggableOptions) {
this.options = options;
if (!this.options.dragPlacement) this.options.dragPlacement = 'element';
this.canInsertBlock = options.canInsertBlock;
this.onBlockInserted = options.onBlockInserted;
if (options.document) this.document = options.document;
this.document.body.addEventListener('mousemove', this.onMouseMove);
this.document.body.addEventListener('mouseup', this.onDragStop);
this.document.body.addEventListener('click', this.onPageBodyClick);
if (options.iframeSelector) {
const iframe: HTMLIFrameElement = document.querySelector(options.iframeSelector)
if (iframe) {
this.document = iframe.contentDocument;
}
}
if (!options.rootElement && options.rootElementSelector) {
options.rootElement = document.querySelector(options.rootElementSelector);
}
}
private setupBlock = (block: HTMLElement) => {
if (!block || !this.options) return;
block.classList.add(Draggable.draggableBlockClass);
block.addEventListener('click', (e) => {
this.onBlockClick(block, e);
});
block.addEventListener('mousedown', (e) => {
if (this.options.ignoreDraggableClass &&
block.classList.contains(this.options.ignoreDraggableClass)) return;
this.onBlockMouseDown(e, block);
});
block.addEventListener('mouseover', (e) => {
this.onHoverStart(e, block);
});
block.addEventListener('mouseleave', (e) => {
this.onHoverEnd(e, block);
});
}
private clearBlock = (block: HTMLElement) => {
const frames = block.querySelectorAll(`.${Draggable.draggableFrameClass}`);
frames.forEach(frame => frame.remove());
block.classList.remove(Draggable.draggableBlockClass);
}
public updateBlocks = () => {
if (!this.options) {
console.error('No options provided. Call setupDraggableBlocks first');
return;
}
const { draggableSelector, containerSelector } = this.options;
const updatedBlocks = Array.from(this.document.querySelectorAll(draggableSelector)) as HTMLElement[];
// Clear old blocks that weren't found now
if (this.draggableBlocks) {
this.draggableBlocks.forEach(block => {
if (block && !updatedBlocks.includes(block)) {
this.clearBlock(block);
}
})
}
// Setup newly appeared blocks
updatedBlocks.forEach(block => {
if (this.draggableBlocks && !this.draggableBlocks.includes(block)) {
this.setupBlock(block);
}
})
this.draggableBlocks = updatedBlocks;
this.containers = Array.from(this.document.querySelectorAll(containerSelector)) as HTMLElement[];
}
public onMouseUp = () => {
this.onDragStop();
}
private onBlockMouseDown = (event: MouseEvent, block: HTMLElement) => {
if ((event as any).hitBlock) return;
(event as any).hitBlock = true;
this.draggingBlock = block;
this.onMouseDownInfo = {
clientY: event.clientY,
clientX: event.clientX,
}
setTimeout(() => {
if (this.draggingBlock) {
this.canDragBlock = true;
}
}, 100);
}
private onDragStart = (block: HTMLElement) => {
const rect = this.draggingBlock.getBoundingClientRect();
// this.deselectCurrentBlock();
this.onDragStartInfo = {
mousePosYinsideBlock: (this.onMouseDownInfo?.clientY ?? 0) - rect.top + 10,
mousePosXinsideBlock: (this.onMouseDownInfo?.clientX ?? 0) - rect.left + 10
}
this.draggingCursor = block.cloneNode(true) as HTMLElement;
this.draggingCursor.classList.add(Draggable.cursorClass);
this.draggingCursor.style.height = this.draggingBlock.offsetHeight + 'px';
this.draggingCursor.style.width = this.draggingBlock.offsetWidth + 'px';
const { rootElement } = this.options;
if (rootElement) {
rootElement.appendChild(this.draggingCursor);
} else {
this.document.body.appendChild(this.draggingCursor);
}
this.draggingBlock.classList.add(Draggable.draggingClass);
if (this.options.disableInsert) {
this.lastInsertionData = null;
if (this.draggingBlockShadow) this.draggingBlockShadow.remove();
if (this.options.dragPlacement === 'element') {
this.draggingBlockShadow = this.draggingBlock.cloneNode(true) as HTMLElement;
this.draggingBlockShadow.style.display = 'none';
} else {
// underline
this.draggingBlockShadow = document.createElement('div');
this.draggingBlockShadow.classList.add('DraggableBlock__underline_container');
const underline = document.createElement('div');
underline.classList.add('DraggableBlock__underline');
underline.style.width = this.draggingBlock.clientWidth + 'px';
this.draggingBlockShadow.appendChild(underline);
}
if (rootElement) {
rootElement.appendChild(this.draggingBlockShadow);
} else {
this.document.body.appendChild(this.draggingBlockShadow);
}
}
}
private onMouseMove = (event: MouseEvent) => {
// console.log('canDragBlock', canDragBlock, 'draggingBlock', draggingBlock);
if (this.canDragBlock && this.draggingBlock) {
if (!this.isDragging) {
let canDrag = true;
if (this.options.canDragBlock) {
canDrag = this.options.canDragBlock(this.draggingBlock)
}
if (canDrag !== false) {
this.isDragging = true;
this.onDragStart(this.draggingBlock);
}
}
if (this.draggingCursor) {
const mousePosYinsideBlock = this.onDragStartInfo?.mousePosYinsideBlock ?? 0;
const mousePosXinsideBlock = this.onDragStartInfo?.mousePosXinsideBlock ?? 0;
this.draggingCursor.style.top = (event.clientY - mousePosYinsideBlock) + 'px';
this.draggingCursor.style.left = (event.clientX - mousePosXinsideBlock) + 'px';
this.tryToInsert(event);
}
}
}
private tryToInsert = throttle(100, (event: MouseEvent) => {
if (!this.hoveredBlock || !this.draggingBlock) return;
if (this.draggingBlock.contains(this.hoveredBlock)) return;
const afterElement = this.getDragAfterElement(this.hoveredBlock, event.clientY);
const canInsert = this.canInsertBlock ?
this.canInsertBlock(this.hoveredBlock, this.draggingBlock, afterElement) : true;
if (canInsert) {
let blockToInsert: HTMLElement | null = null;
if (this.options.disableInsert) {
blockToInsert = this.draggingBlockShadow;
if (this.options.dragPlacement === 'element') {
this.draggingBlock.style.display = 'none';
}
if (this.draggingBlockShadow) this.draggingBlockShadow.style.display = '';
this.lastInsertionData = {
draggingBlock: this.draggingBlock,
container: this.hoveredBlock,
afterElement: afterElement as HTMLElement
}
} else {
blockToInsert = this.draggingBlock;
}
try {
if (blockToInsert) {
if (afterElement) {
this.hoveredBlock.insertBefore(blockToInsert, afterElement)
} else {
this.hoveredBlock.appendChild(blockToInsert);
}
}
this.options?.onTryToInsert(this.hoveredBlock, this.draggingBlock, blockToInsert, afterElement)
if (!this.options.disableInsert)
this.onBlockInserted?.(this.hoveredBlock, this.draggingBlock, afterElement);
} catch (e) {
console.error(e);
}
}
});
private getDragAfterElement(container: HTMLElement, clientY: number): Element | null {
const draggableElements = Array.from(container.children).filter(child =>
child.classList.contains(Draggable.draggableBlockClass) &&
!child.classList.contains(Draggable.draggingClass))
let closestElement: Element | null = null;
let closestOffset: number = Number.NEGATIVE_INFINITY;
draggableElements.forEach(element => {
const box = element.getBoundingClientRect();
const offset = clientY - box.top - box.height / 2;
if (offset < 0 && offset > closestOffset) {
closestElement = element;
closestOffset = offset;
}
});
return closestElement;
}
private onDragStop = () => {
this.canDragBlock = false;
this.isDragging = false;
if (this.draggingBlock) {
this.draggingBlock.classList.remove(Draggable.draggingClass);
}
if (this.options.disableInsert) {
if (this.draggingBlockShadow) this.draggingBlockShadow.remove();
if (this.draggingBlock) this.draggingBlock.style.display = '';
if (this.lastInsertionData)
this.onBlockInserted?.(this.lastInsertionData.container,
this.lastInsertionData.draggingBlock, this.lastInsertionData.afterElement);
this.draggingBlockShadow = null;
this.lastInsertionData = null;
}
this.draggingBlock = null;
if (this.draggingCursor) {
this.draggingCursor.remove();
this.draggingCursor = null;
}
}
private onHoverStart = (event: MouseEvent, block: HTMLElement) => {
if ((event as any).hitContainer) return;
if (this.containers.includes(block)) {
(event as any).hitContainer = true;
}
// When dragging, we want to highlight only containers
// But when we do not, highlight draggable blocks
if (this.isDragging && !this.containers.includes(block)) return;
if ((event as any).hitBlock) return;
(event as any).hitBlock = true;
if (this.hoveredBlock === block) return;
if (this.hoveredBlock && this.hoveredBlock !== this.selectedBlock) {
this.blockHoverEnd(event, this.hoveredBlock);
}
this.hoveredBlock = block;
this.options?.onBlockHoverStart?.(block);
if (block !== this.selectedBlock) {
this.styleHoveredBlock(block);
}
}
private onHoverEnd = (event: MouseEvent, block: HTMLElement) => {
if ((event as any).hitBlock) return;
(event as any).hitBlock = true;
this.blockHoverEnd(event, block);
}
private blockHoverEnd = (event: MouseEvent, block: HTMLElement) => {
if (block !== this.selectedBlock) {
this.styleDeselectedBlock(block);
}
this.options?.onBlockHoverEnd?.(this.hoveredBlock);
this.hoveredBlock = null;
}
private onBlockClick = (block: HTMLElement, event: MouseEvent) => {
if ((event as any).hitBlock) return;
(event as any).hitBlock = true;
if (block !== this.selectedBlock) {
const canDeselectBlock = this.deselectCurrentBlock();
if (!canDeselectBlock) return;
this.options?.onBlockSelected?.(block);
this.selectedBlock = block;
this.styleSelectedBlock(block);
}
}
private onPageBodyClick = (event: MouseEvent) => {
if ((event as any).hitBlock) return;
if (!this.options.disableClickAwayDeselect)
this.deselectCurrentBlock();
}
public deselectCurrentBlock = (): boolean => {
if (this.options.canDeselectBlock) {
const canDeselectBlock = this.options.canDeselectBlock(this.selectedBlock);
if (canDeselectBlock === false) return false;
}
if (this.selectedBlock) {
this.styleDeselectedBlock(this.selectedBlock)
this.options?.onBlockDeSelected?.(this.selectedBlock);
}
if (this.selectedBlock === this.hoveredBlock) {
this.styleHoveredBlock(this.selectedBlock);
}
this.selectedBlock = null;
return true;
}
private styleHoveredBlock = (block: HTMLElement) => {
if (block) {
if (this.options.applyZIndex) block.style.zIndex = '1005';
const styleParent = (block: HTMLElement) => {
const parent = block.parentElement;
if (parent) {
if (parent === this.options.rootElement) return;
if (this.draggableBlocks.includes(parent) && this.options.applyZIndex)
parent.style.zIndex = '1005';
styleParent(parent);
}
}
styleParent(block);
}
}
private styleSelectedBlock = (block: HTMLElement) => {
if (block) {
if (this.options.applyZIndex) block.style.zIndex = '1006';
const styleParent = (block: HTMLElement) => {
const parent = block.parentElement;
if (parent) {
if (parent === this.options.rootElement) return;
if (this.draggableBlocks.includes(parent)) parent.style.zIndex = '1006';
styleParent(parent);
}
}
styleParent(block);
}
}
private styleDeselectedBlock = (block: HTMLElement) => {
if (this.options.applyZIndex) if (block) block.style.zIndex = '1002';
}
} | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement } from "../shared";
/**
* Statement provider for service [cognito-sync](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoncognitosync.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class CognitoSync extends PolicyStatement {
public servicePrefix = 'cognito-sync';
/**
* Statement provider for service [cognito-sync](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazoncognitosync.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
constructor (sid?: string) {
super(sid);
}
/**
* Initiates a bulk publish of all existing datasets for an Identity Pool to the configured stream.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognitosync/latest/APIReference/API_BulkPublish.html
*/
public toBulkPublish() {
return this.to('BulkPublish');
}
/**
* Deletes the specific dataset.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognitosync/latest/APIReference/API_DeleteDataset.html
*/
public toDeleteDataset() {
return this.to('DeleteDataset');
}
/**
* Gets meta data about a dataset by identity and dataset name.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/cognitosync/latest/APIReference/API_DescribeDataset.html
*/
public toDescribeDataset() {
return this.to('DescribeDataset');
}
/**
* Gets usage details (for example, data storage) about a particular identity pool.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/cognitosync/latest/APIReference/API_DescribeIdentityPoolUsage.html
*/
public toDescribeIdentityPoolUsage() {
return this.to('DescribeIdentityPoolUsage');
}
/**
* Gets usage information for an identity, including number of datasets and data usage.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/cognitosync/latest/APIReference/API_DescribeIdentityUsage.html
*/
public toDescribeIdentityUsage() {
return this.to('DescribeIdentityUsage');
}
/**
* Get the status of the last BulkPublish operation for an identity pool.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/cognitosync/latest/APIReference/API_GetBulkPublishDetails.html
*/
public toGetBulkPublishDetails() {
return this.to('GetBulkPublishDetails');
}
/**
* Gets the events and the corresponding Lambda functions associated with an identity pool.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/cognitosync/latest/APIReference/API_GetCognitoEvents.html
*/
public toGetCognitoEvents() {
return this.to('GetCognitoEvents');
}
/**
* Gets the configuration settings of an identity pool.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/cognitosync/latest/APIReference/API_GetIdentityPoolConfiguration.html
*/
public toGetIdentityPoolConfiguration() {
return this.to('GetIdentityPoolConfiguration');
}
/**
* Lists datasets for an identity.
*
* Access Level: List
*
* https://docs.aws.amazon.com/cognitosync/latest/APIReference/API_ListDatasets.html
*/
public toListDatasets() {
return this.to('ListDatasets');
}
/**
* Gets a list of identity pools registered with Cognito.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/cognitosync/latest/APIReference/API_ListIdentityPoolUsage.html
*/
public toListIdentityPoolUsage() {
return this.to('ListIdentityPoolUsage');
}
/**
* Gets paginated records, optionally changed after a particular sync count for a dataset and identity.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/cognitosync/latest/APIReference/API_ListRecords.html
*/
public toListRecords() {
return this.to('ListRecords');
}
/**
* A permission that grants the ability to query records.
*
* Access Level: Read
*/
public toQueryRecords() {
return this.to('QueryRecords');
}
/**
* Registers a device to receive push sync notifications.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognitosync/latest/APIReference/API_RegisterDevice.html
*/
public toRegisterDevice() {
return this.to('RegisterDevice');
}
/**
* Sets the AWS Lambda function for a given event type for an identity pool.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognitosync/latest/APIReference/API_SetCognitoEvents.html
*/
public toSetCognitoEvents() {
return this.to('SetCognitoEvents');
}
/**
* A permission that grants ability to configure datasets.
*
* Access Level: Write
*/
public toSetDatasetConfiguration() {
return this.to('SetDatasetConfiguration');
}
/**
* Sets the necessary configuration for push sync.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognitosync/latest/APIReference/API_SetIdentityPoolConfiguration.html
*/
public toSetIdentityPoolConfiguration() {
return this.to('SetIdentityPoolConfiguration');
}
/**
* Subscribes to receive notifications when a dataset is modified by another device.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognitosync/latest/APIReference/API_SubscribeToDataset.html
*/
public toSubscribeToDataset() {
return this.to('SubscribeToDataset');
}
/**
* Unsubscribes from receiving notifications when a dataset is modified by another device.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognitosync/latest/APIReference/API_UnsubscribeFromDataset.html
*/
public toUnsubscribeFromDataset() {
return this.to('UnsubscribeFromDataset');
}
/**
* Posts updates to records and adds and deletes records for a dataset and user.
*
* Access Level: Write
*
* https://docs.aws.amazon.com/cognitosync/latest/APIReference/API_UpdateRecords.html
*/
public toUpdateRecords() {
return this.to('UpdateRecords');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"BulkPublish",
"DeleteDataset",
"RegisterDevice",
"SetCognitoEvents",
"SetDatasetConfiguration",
"SetIdentityPoolConfiguration",
"SubscribeToDataset",
"UnsubscribeFromDataset",
"UpdateRecords"
],
"Read": [
"DescribeDataset",
"DescribeIdentityPoolUsage",
"DescribeIdentityUsage",
"GetBulkPublishDetails",
"GetCognitoEvents",
"GetIdentityPoolConfiguration",
"ListIdentityPoolUsage",
"ListRecords",
"QueryRecords"
],
"List": [
"ListDatasets"
]
};
/**
* Adds a resource of type dataset to the statement
*
* https://docs.aws.amazon.com/cognito/latest/developerguide/synchronizing-data.html#understanding-datasets
*
* @param identityPoolId - Identifier for the identityPoolId.
* @param identityId - Identifier for the identityId.
* @param datasetName - Identifier for the datasetName.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onDataset(identityPoolId: string, identityId: string, datasetName: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:cognito-sync:${Region}:${Account}:identitypool/${IdentityPoolId}/identity/${IdentityId}/dataset/${DatasetName}';
arn = arn.replace('${IdentityPoolId}', identityPoolId);
arn = arn.replace('${IdentityId}', identityId);
arn = arn.replace('${DatasetName}', datasetName);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type identity to the statement
*
* https://docs.aws.amazon.com/cognito/latest/developerguide/identity-pools.html#authenticated-and-unauthenticated-identities
*
* @param identityPoolId - Identifier for the identityPoolId.
* @param identityId - Identifier for the identityId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onIdentity(identityPoolId: string, identityId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:cognito-sync:${Region}:${Account}:identitypool/${IdentityPoolId}/identity/${IdentityId}';
arn = arn.replace('${IdentityPoolId}', identityPoolId);
arn = arn.replace('${IdentityId}', identityId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type identitypool to the statement
*
* https://docs.aws.amazon.com/cognito/latest/developerguide/identity-pools.html
*
* @param identityPoolId - Identifier for the identityPoolId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onIdentitypool(identityPoolId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:cognito-sync:${Region}:${Account}:identitypool/${IdentityPoolId}';
arn = arn.replace('${IdentityPoolId}', identityPoolId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
} | the_stack |
import Votes from '../lib/collections/votes/collection';
import { Tags } from '../lib/collections/tags/collection';
import type { KarmaChangeSettingsType } from '../lib/collections/users/custom_fields';
import moment from '../lib/moment-timezone';
import htmlToText from 'html-to-text';
import sumBy from 'lodash/sumBy';
const COMMENT_DESCRIPTION_LENGTH = 500;
// Given a user and a date range, get a summary of karma changes that occurred
// during that date range.
//
// For example:
// {
// totalChange: 10,
// startDate: Date("2018-09-09"),
// endDate: Date("2018-09-10"),
// documents: [
// {
// _id: "12345",
// collectionName: "Posts",
// scoreChange: 3,
// },
// {
// _id: "12345",
// collectionName: "Comments",
// scoreChange: -1,
// },
// ]
// }
export async function getKarmaChanges({user, startDate, endDate, nextBatchDate=null, af=false, context}: {
user: DbUser,
startDate: Date,
endDate: Date,
nextBatchDate?: Date|null,
af?: boolean,
context?: ResolverContext,
})
{
if (!user) throw new Error("Missing required argument: user");
if (!startDate) throw new Error("Missing required argument: startDate");
if (!endDate) throw new Error("Missing required argument: endDate");
if (startDate > endDate)
throw new Error("getKarmaChanges: endDate must be after startDate");
const showNegativeKarmaSetting = user.karmaChangeNotifierSettings?.showNegativeKarma
function karmaChangesInCollectionPipeline(collectionName: CollectionNameString) {
return [
// Get votes cast on this user's content (including cancelled votes)
{$match: {
authorId: user._id,
votedAt: {$gte: startDate, $lte: endDate},
userId: {$ne: user._id}, //Exclude self-votes
collectionName: collectionName,
...(af && {afPower: {$exists: true}})
}},
// Group by thing-that-was-voted-on and calculate the total karma change
{$group: {
_id: "$documentId",
collectionName: { $first: "$collectionName" },
scoreChange: { $sum: af ? "$afPower" : "$power" },
}},
// Filter out things with zero or negative net change (eg where someone voted and then
// unvoted and nothing else happened)
// User setting determines whether we show negative changes
{$match: {
scoreChange: showNegativeKarmaSetting ? {$ne: 0} : {$gt: 0}
}}
];
}
let changedComments = await Votes.aggregate(
[
...karmaChangesInCollectionPipeline("Comments"),
{$lookup: {
from: "comments",
localField: "_id",
foreignField: "_id",
as: "comment"
}},
{$project: {
_id:1,
scoreChange:1,
description: {$arrayElemAt: ["$comment.contents.html",0]},
postId: {$arrayElemAt: ["$comment.postId",0]},
tagId: {$arrayElemAt: ["$comment.tagId",0]},
}},
]
).toArray()
let changedPosts = await Votes.aggregate(
[
...karmaChangesInCollectionPipeline("Posts"),
{$lookup: {
from: "posts",
localField: "_id",
foreignField: "_id",
as: "post"
}},
{$project: {
_id:1,
scoreChange:1,
title: {$arrayElemAt: ["$post.title",0]},
slug: {$arrayElemAt: ["$post.slug",0]},
}},
]
).toArray();
// Replace comment bodies with abbreviated plain-text versions (rather than
// HTML).
for (let comment of changedComments) {
comment.description = htmlToText.fromString(comment.description)
.substring(0, COMMENT_DESCRIPTION_LENGTH);
}
let changedTagRevisions = await Votes.aggregate(
[
...karmaChangesInCollectionPipeline("Revisions"),
{$lookup: {
from: "revisions",
localField: "_id",
foreignField: "_id",
as: "revision"
}},
{$project: {
_id:1,
scoreChange:1,
tagId: {$arrayElemAt: ["$revision.documentId",0]},
}},
]
).toArray();
// Fill in tag references
const tagIdsReferenced = new Set<string>();
for (let changedComment of changedComments) {
if (changedComment.tagId)
tagIdsReferenced.add(changedComment.tagId);
}
for (let changedTagRevision of changedTagRevisions) {
tagIdsReferenced.add(changedTagRevision.tagId);
}
const tagIdToMetadata = await mapTagIdsToMetadata([...tagIdsReferenced.keys()], context)
for (let changedComment of changedComments) {
if (changedComment.tagId) {
changedComment.tagSlug = tagIdToMetadata[changedComment.tagId].slug;
}
}
for (let changedRevision of changedTagRevisions) {
changedRevision.tagSlug = tagIdToMetadata[changedRevision.tagId].slug;
changedRevision.tagName = tagIdToMetadata[changedRevision.tagId].name;
}
let totalChange =
sumBy(changedPosts, (doc: any)=>doc.scoreChange)
+ sumBy(changedComments, (doc: any)=>doc.scoreChange)
+ sumBy(changedTagRevisions, (doc: any)=>doc.scoreChange);
return {
totalChange,
startDate,
nextBatchDate,
endDate,
posts: changedPosts,
comments: changedComments,
tagRevisions: changedTagRevisions,
};
}
const mapTagIdsToMetadata = async (tagIds: Array<string>, context: ResolverContext|undefined): Promise<Record<string,{slug:string, name:string}>> => {
const mapping: Record<string,{slug: string, name: string}> = {};
await Promise.all(tagIds.map(async (tagId: string) => {
const tag = context
? await context.loaders.Tags.load(tagId)
: await Tags.findOne(tagId)
if (tag?.slug) {
mapping[tagId] = {
slug: tag.slug,
name: tag.name
};
}
}));
return mapping;
}
export function getKarmaChangeDateRange({settings, now, lastOpened=null, lastBatchStart=null}: {
settings: any,
now: Date,
lastOpened?: Date|null,
lastBatchStart?: Date|null,
}): null|{start:any, end:any}
{
// Greatest date prior to lastOpened at which the time of day matches
// settings.timeOfDay.
let todaysDailyReset = moment(now).tz("GMT");
todaysDailyReset.set('hour', Math.floor(settings.timeOfDayGMT));
todaysDailyReset.set('minute', 60*(settings.timeOfDayGMT%1));
todaysDailyReset.set('second', 0);
todaysDailyReset.set('millisecond', 0);
const lastDailyReset = todaysDailyReset.isAfter(now)
? moment(todaysDailyReset).subtract(1, 'days')
: todaysDailyReset;
const previousBatchExists = !!lastBatchStart
switch(settings.updateFrequency) {
default:
case "disabled":
return null;
case "daily": {
const oneDayPrior = moment(lastDailyReset).subtract(1, 'days')
// Check whether the last time you opened the menu was in the same batch-period
const openedBeforeNextBatch = lastOpened && lastOpened >= lastDailyReset.toDate()
// If you open the notification menu again before the next batch has started, just return
// the previous batch
if (previousBatchExists && openedBeforeNextBatch) {
// Since we know that we reopened the notifications before the next batch, the last batch
// will have ended at the last daily reset time
const lastBatchEnd = lastDailyReset
// Sanity check in case lastBatchStart is invalid (eg not cleared after a settings change)
if (lastBatchStart! < lastBatchEnd.toDate()) {
return {
start: lastBatchStart,
end: lastBatchEnd.toDate()
};
}
}
// If you've never opened the menu before, then return the last daily batch, else
// create batch for all periods that happened since you last opened it
const startDate = lastOpened ? moment.min(oneDayPrior, moment(lastOpened)) : oneDayPrior
return {
start: startDate.toDate(),
end: lastDailyReset.toDate(),
};
}
case "weekly": {
// Target day of the week, as an integer 0-6
const targetDayOfWeekNum = moment().day(settings.dayOfWeekGMT).day();
const lastDailyResetDayOfWeekNum = lastDailyReset.day();
// Number of days back from today's daily reset to get to a daily reset
// of the correct day of the week
const daysOfWeekDifference = ((lastDailyResetDayOfWeekNum - targetDayOfWeekNum) + 7) % 7;
const lastWeeklyReset = moment(lastDailyReset).subtract(daysOfWeekDifference, 'days');
const oneWeekPrior = moment(lastWeeklyReset).subtract(7, 'days');
// Check whether the last time you opened the menu was in the same batch-period
const openedBeforeNextBatch = lastOpened && lastOpened >= lastWeeklyReset.toDate()
// If you open the notification menu again before the next batch has started, just return
// the previous batch
if (previousBatchExists && openedBeforeNextBatch) {
// Since we know that we reopened the notifications before the next batch, the last batch
// will have ended at the last daily reset time
const lastBatchEnd = lastWeeklyReset
// Sanity check in case lastBatchStart is invalid (eg not cleared after a settings change)
if (lastBatchStart! < lastBatchEnd.toDate()) {
return {
start: lastBatchStart,
end: lastBatchEnd.toDate()
};
}
}
// If you've never opened the menu before, then return the last daily batch, else
// create batch for all periods that happened since you last opened it
const startDate = lastOpened ? moment.min(oneWeekPrior, moment(lastOpened)) : oneWeekPrior
return {
start: startDate.toDate(),
end: lastWeeklyReset.toDate(),
};
}
case "realtime":
if (!lastOpened) {
// If set to realtime and never opened before (eg, you just changed the
// setting), default to the last 24 hours.
return {
start: moment().subtract(1, 'days').toDate(),
end: now
}
} else {
return {
start: lastOpened,
end: now
}
}
}
}
export function getKarmaChangeNextBatchDate({settings, now}: {
settings: KarmaChangeSettingsType,
now: Date,
})
{
switch(settings.updateFrequency) {
case "disabled":
case "realtime":
return null;
case "daily":
const lastDailyBatch = getKarmaChangeDateRange({settings, now});
const lastDailyReset = lastDailyBatch!.end;
const nextDailyReset = moment(lastDailyReset).add(1, 'days');
return nextDailyReset.toDate();
case "weekly":
const lastWeeklyBatch = getKarmaChangeDateRange({settings, now});
const lastWeeklyReset = lastWeeklyBatch!.end;
const nextWeeklyReset = moment(lastWeeklyReset).add(7, 'days');
return nextWeeklyReset.toDate();
}
} | the_stack |
import { flatMap } from 'lodash';
import type * as babel from '@babel/core';
import jsx from '@babel/plugin-syntax-jsx';
import {
ArrayPattern,
ArrowFunctionExpression,
BlockStatement,
Expression,
FunctionDeclaration,
FunctionExpression,
Identifier,
Node,
ObjectPattern,
SourceLocation,
} from '@babel/types';
import { addNamed } from '@babel/helper-module-imports';
import type { VisitNodeObject } from '@babel/traverse';
import {
utils,
ObservedMeta,
Loc,
ComponentMetaData,
VIRTUAL_LOC,
} from '@relyzer/shared';
import { parse as parseComment } from 'comment-parser';
import { obj2ast } from './object-ast';
export interface RelyzerBabelPluginOptions {
autoDetect?: boolean;
include?: string[];
exclude?: string[];
}
const runtimePackageName = '@relyzer/runtime';
const randomId = process.env.NODE_ENV === 'test'
? () => 'RANDOM'
: utils.randomId;
function removeNull<T>(
array: ReadonlyArray<T | null | undefined>,
) {
return array.filter((x) => x != null) as T[];
}
type FunctionExpressionOrDeclaration =
| FunctionExpression
| FunctionDeclaration
| ArrowFunctionExpression;
interface RelyzerScopeStack {
code: string;
nodePath: babel.NodePath<FunctionExpressionOrDeclaration>;
blockPath: babel.NodePath<BlockStatement>;
relyzerIdentifier: Identifier;
return: RelyzerScopeStack | null;
observedList: ObservedMeta[];
isAutoDetected: boolean;
}
interface VisitorState extends babel.PluginPass {
collectorScopeStack: RelyzerScopeStack | null;
}
const transformBabelLoc = (loc: SourceLocation): Loc => [
loc.start.line,
loc.start.column,
loc.end.line,
loc.end.column,
];
const getRelativeLoc = (offset: SourceLocation, child: SourceLocation): Loc => {
const column = (position: SourceLocation['start']) => position.column - (position.line === offset.start.line ? offset.start.column : 0);
return [
child.start.line - offset.start.line,
column(child.start),
child.end.line - offset.start.line,
column(child.end),
];
};
const buildLocStr = (loc: SourceLocation) => utils.stringifyLoc(transformBabelLoc(loc));
const isFirstCap = (str: string) => /^[A-Z]/.test(str);
/**
* detect whether a function is named capitalized
*/
const isFirstCapFunction = (
nodePath: babel.NodePath<FunctionExpressionOrDeclaration>,
b: typeof babel,
) => {
/**
* function Name() {}
*/
if (
nodePath.isFunctionDeclaration()
&& isFirstCap(nodePath.node.id?.name ?? '')
) return true;
/**
* const A = function() {}
* const A = () => {}
*/
if (
(nodePath.isFunctionExpression() || nodePath.isArrowFunctionExpression())
&& nodePath.parentPath.isVariableDeclarator()
&& b.types.isIdentifier(nodePath.parentPath.node.id)
&& isFirstCap(nodePath.parentPath.node.id.name)
) return true;
/**
* const A = memo(() => {})
* const A = memo(function() {})
*/
if (
(nodePath.isFunctionExpression() || nodePath.isArrowFunctionExpression())
&& nodePath.parentPath.isCallExpression()
&& nodePath.parentPath.parentPath.isVariableDeclarator()
&& b.types.isIdentifier(nodePath.parentPath.parentPath.node.id)
&& isFirstCap(nodePath.parentPath.parentPath.node.id.name)
) return true;
return false;
};
/**
* check whether the comments include `@component`
*/
const isComponentComments = (comments: readonly babel.types.Comment[] | null) => comments?.some((comment) => {
const parsedComment = parseComment(`/*${comment.value}*/`);
return parsedComment.some((c) => c.tags.some((tag) => tag.tag === 'component'));
});
const isBlockHasRelyzerDirective = (
node: babel.types.BlockStatement,
) => node.directives.some(
(directive) => directive.value.value === 'use relyzer',
);
const detectIsNodePathComponent = (
nodePath: babel.NodePath<FunctionExpressionOrDeclaration>,
b: typeof babel,
) => {
let p: babel.NodePath<any> = nodePath;
/**
* detect for comment `@component`
*/
while (p && p.type !== 'BlockStatement') {
if (isComponentComments(p.node.leadingComments)) {
return true;
}
p = p.parentPath;
}
/**
* detect for 'use relyzer'
*/
if (
b.types.isBlockStatement(nodePath.node.body)
&& isBlockHasRelyzerDirective(nodePath.node.body)
) {
return true;
}
return false;
};
/**
* create a observer expression for an expression
* transform from:
* ```
* expr;
* ```
*
* to:
* ```
* p(expr, loc);
* ```
* and add extra data to scope.observedList
*/
const observeExpr = (
{
t,
scope,
expr,
type,
name,
loc,
}: {
t: typeof babel.types,
scope: RelyzerScopeStack,
expr: Expression,
type: ObservedMeta['type'],
name: string,
loc?: SourceLocation | null,
},
) => {
if (loc == null) return null;
const { observedList, nodePath, relyzerIdentifier } = scope;
const locStr = utils.stringifyLoc(getRelativeLoc(nodePath.node.loc!, loc));
if (observedList.find((item) => item.loc === locStr)) return null;
const count = observedList.push({
type,
loc: locStr,
name,
});
return t.callExpression(
t.identifier(relyzerIdentifier.name),
[expr, t.numericLiteral(count - 1)],
);
};
const shouldResolveFile = (filename: string, options: RelyzerBabelPluginOptions): boolean => {
if (!filename) {
return true;
}
if ((
options.include && !options.include.some((item) => filename.includes(item))
)) {
return false;
}
const exclude = options.exclude ?? ['node_modules'];
if (exclude.some((item) => filename.includes(item))) {
return false;
}
return true;
};
export default function relyzerBabel(bb: typeof babel): babel.PluginObj<VisitorState> {
const t = bb.types;
// add `const collect = useRelyzer(code, loc)`
const functionVisit: VisitNodeObject<VisitorState, any> = {
enter(nodePath: babel.NodePath<FunctionExpressionOrDeclaration>, state) {
const options = (state.opts as RelyzerBabelPluginOptions);
if (!shouldResolveFile(state.filename, options)) {
return;
}
const isAutoDetected = !!(options.autoDetect && isFirstCapFunction(nodePath, bb));
if (
(isAutoDetected || detectIsNodePathComponent(nodePath, bb))
&& nodePath.node.loc
) {
const code = this.file.code.slice(nodePath.node.start!, nodePath.node.end!);
const blockPath = nodePath.get('body');
if (!blockPath.isBlockStatement()) return;
const perfIdentifier = blockPath.scope.generateUidIdentifier('p');
state.collectorScopeStack = {
code,
blockPath,
nodePath,
relyzerIdentifier: perfIdentifier,
return: state.collectorScopeStack,
observedList: [],
isAutoDetected,
};
}
},
exit(nodePath: babel.NodePath<FunctionExpressionOrDeclaration>, state) {
const { collectorScopeStack } = state;
const { node } = nodePath;
if (collectorScopeStack?.nodePath !== nodePath || !node.loc) {
return;
}
const importName = addNamed(nodePath, 'useRelyzer', runtimePackageName);
const {
blockPath,
code,
relyzerIdentifier: identifier,
observedList,
} = collectorScopeStack;
const param: ComponentMetaData = {
id: randomId(),
code,
loc: buildLocStr(node.loc),
observedList,
shouldDetectCallStack: collectorScopeStack.isAutoDetected,
};
const useRelyzerDeclaration = t.variableDeclaration('const', [
t.variableDeclarator(
identifier,
t.callExpression(
t.identifier(importName.name),
[obj2ast(param, bb)],
),
),
]);
const beforeInsertedNodes: Node[] = [useRelyzerDeclaration];
let [propsParam] = node.params;
const originalPropsParam = propsParam;
if (!propsParam || t.isObjectPattern(propsParam)) {
propsParam = blockPath.scope.generateUidIdentifier('props');
node.params[0] = propsParam;
}
if (t.isIdentifier(propsParam)) {
const observePropsExpr = t.callExpression(
t.identifier(identifier.name),
[t.identifier(propsParam.name), t.numericLiteral(VIRTUAL_LOC.PROPS)],
);
beforeInsertedNodes.push(t.expressionStatement(observePropsExpr));
if (t.isObjectPattern(originalPropsParam)) {
const propsPatternDeclaration = t.variableDeclaration('let', [
t.variableDeclarator(
originalPropsParam,
t.identifier(propsParam.name),
),
]);
beforeInsertedNodes.push(propsPatternDeclaration);
}
}
blockPath.unshiftContainer(
'body',
beforeInsertedNodes,
);
state.collectorScopeStack = collectorScopeStack.return;
},
};
const visitor: babel.Visitor<VisitorState> = {
FunctionDeclaration: functionVisit,
FunctionExpression: functionVisit,
ArrowFunctionExpression: functionVisit,
/**
* collect `const xxx =`
*/
VariableDeclaration(nodePath, { collectorScopeStack }) {
if (!collectorScopeStack || collectorScopeStack.nodePath !== nodePath.parentPath.parentPath) return;
// if (nodePath.node.kind !== 'const') return;
const identifiers = flatMap<babel.types.VariableDeclarator, Identifier>(nodePath.node.declarations, (declaration) => {
const extractArrayPatternIdentifiers = (arrayPattern: ArrayPattern): Identifier[] => flatMap(arrayPattern.elements, (element) => {
switch (element?.type) {
case 'Identifier':
return element;
case 'ObjectPattern':
// eslint-disable-next-line @typescript-eslint/no-use-before-define
return extractObjectPatternIdentifiers(element);
case 'ArrayPattern':
return extractArrayPatternIdentifiers(element);
case 'RestElement':
if (element.argument.type === 'Identifier') {
return [element.argument];
}
break;
case 'AssignmentPattern':
if (element.left.type === 'Identifier') {
return [element.left];
}
break;
default:
}
return [];
});
const extractObjectPatternIdentifiers = (objectPattern: ObjectPattern): Identifier[] => flatMap(objectPattern.properties, (property) => {
switch (property.type) {
case 'RestElement':
if (property.argument.type === 'Identifier') {
return [property.argument];
}
break;
case 'ObjectProperty': {
const { value } = property;
switch (value.type) {
case 'Identifier':
return [value];
case 'ArrayPattern':
return extractArrayPatternIdentifiers(value);
case 'AssignmentPattern':
if (value.left.type === 'Identifier') {
return [value.left];
}
break;
default:
}
break;
}
default:
}
return [];
});
switch (declaration.id.type) {
case 'ObjectPattern':
return extractObjectPatternIdentifiers(declaration.id);
case 'ArrayPattern':
return extractArrayPatternIdentifiers(declaration.id);
case 'Identifier':
if (!t.isLiteral(declaration.init)) {
return [declaration.id];
}
break;
default:
}
return [];
});
// add `perf(name, loc)`
const perfExps = removeNull(identifiers.map(
(identifier) => {
const expr = observeExpr({
t,
scope: collectorScopeStack,
expr: t.identifier(identifier.name),
loc: identifier.loc,
type: 'var',
name: identifier.name,
});
return expr ? t.expressionStatement(expr) : null;
},
));
if (perfExps.length) {
nodePath.insertAfter(perfExps);
}
},
/**
* collect `useCallback / useMemo` dependencies
*/
CallExpression(nodePath, { collectorScopeStack }) {
const block = nodePath.find((path) => path.type === 'BlockStatement') as babel.NodePath<BlockStatement> | null;
if (!collectorScopeStack || collectorScopeStack.nodePath !== block?.parentPath) return;
const { node } = nodePath;
const depsArg = node.arguments[1];
if (
t.isIdentifier(node.callee)
&& ['useCallback', 'useMemo'].includes(node.callee.name)
&& t.isArrayExpression(depsArg)
) {
depsArg.elements = depsArg.elements.map((dep) => {
const expr = t.isExpression(dep) && observeExpr({
t,
scope: collectorScopeStack,
expr: dep,
loc: dep.loc,
type: 'dep',
name: t.isIdentifier(dep) ? dep.name : dep.type,
});
return expr || dep;
});
}
},
/**
* collect jsx attribute for non native element
*/
JSXAttribute(nodePath, { collectorScopeStack }) {
const funcPath = nodePath.find(
(path) => (
path.type === 'FunctionExpression'
|| path.type === 'FunctionDeclaration'
|| path.type === 'ArrowFunctionExpression'
),
) as babel.NodePath<FunctionExpressionOrDeclaration> | null;
const { node, parentPath } = nodePath;
const attrName = node.name;
if (
!collectorScopeStack
|| collectorScopeStack.nodePath !== funcPath
|| !parentPath.isJSXOpeningElement()
|| (t.isJSXIdentifier(parentPath.node.name) && /^[a-z]/.test(parentPath.node.name.name)) // exclude native element like div
|| !attrName.loc
|| t.isStringLiteral(node.value)
) return;
const value = t.isJSXExpressionContainer(node.value)
? node.value.expression
: node.value;
if (!value || t.isLiteral(value) || t.isJSXEmptyExpression(value)) return;
const expr = observeExpr({
t,
scope: collectorScopeStack,
expr: value,
loc: attrName.loc,
type: 'attr',
name: t.isJSXIdentifier(attrName)
? attrName.name
: `${attrName.namespace.name}:${attrName.name.name}`,
});
if (expr) {
node.value = t.jsxExpressionContainer(expr);
}
},
};
return {
visitor: process.env.NODE_ENV === 'production' ? {} : visitor,
inherits: jsx,
};
} | the_stack |
import * as geom from "../format/geom";
import * as dbft from "../format/dragonBonesFormat";
export default function (data: dbft.DragonBones | null, textureAtlases: dbft.TextureAtlas[] | null = null): void {
if (data) {
for (const armature of data.armature) {
if (armature.canvas) {
if (armature.canvas.hasBackground) {
armature.canvas.hasBackground = false; // { color:0xxxxxxx }
}
else {
armature.canvas.color = -1; // { }
}
}
if (armature.bone.length === 0) {
armature.slot.length = 0;
armature.ik.length = 0;
armature.path.length = 0;
armature.skin.length = 0;
armature.animation.length = 0;
armature.defaultActions.length = 0;
armature.actions.length = 0;
return;
}
// if (typeof this.type === "string") { // LowerCase bug. (If fix the bug, some third-party plugins may go wrong)
// this.type = this.type.toLowerCase();
// }
armature.aabb.toFixed();
for (const bone of armature.bone) {
if (bone.parent && !armature.getBone(bone.parent)) {
bone.parent = "";
}
bone.alpha = Number(bone.alpha.toFixed(2));
if (bone instanceof dbft.Surface) {
const vertices = (bone as dbft.Surface).vertices;
for (let i = 0, l = vertices.length; i < l; ++i) {
vertices[i] = Number(vertices[i].toFixed(2));
}
}
else {
bone.transform.skX = geom.normalizeDegree(bone.transform.skX);
bone.transform.skY = geom.normalizeDegree(bone.transform.skY);
if (bone.transform.scX === 0.0) {
bone.transform.scX = 0.000001;
}
if (bone.transform.scY === 0.0) {
bone.transform.scY = 0.000001;
}
bone.transform.toFixed();
}
}
for (const slot of armature.slot) {
if (!slot.parent || !armature.getBone(slot.parent)) {
slot.parent = armature.bone[0].name;
}
slot.alpha = Number(slot.alpha.toFixed(2));
slot.color.toFixed();
}
for (const ikConstraint of armature.ik) {
if (!ikConstraint.target || !ikConstraint.bone) {
// TODO
}
// TODO check recurrence
ikConstraint.weight = Number(ikConstraint.weight.toFixed(2));
}
for (const pathConstraint of armature.path) {
if (!pathConstraint.target || !pathConstraint.bones) {
// TODO
}
// TODO check recurrence
pathConstraint.position = Number(pathConstraint.position.toFixed(2));
pathConstraint.spacing = Number(pathConstraint.spacing.toFixed(2));
pathConstraint.rotateOffset = Number(pathConstraint.rotateOffset.toFixed(2));
pathConstraint.rotateMix = Number(pathConstraint.rotateMix.toFixed(2));
pathConstraint.translateMix = Number(pathConstraint.translateMix.toFixed(2));
}
armature.sortBones();
for (const skin of armature.skin) {
for (const skinSlot of skin.slot) {
if (!armature.getSlot(skinSlot.name)) {
skinSlot.display.length = 0;
continue;
}
skinSlot.actions.length = 0; // Fix data bug.
for (const display of skinSlot.display) {
if (!display) {
continue;
}
if (
display instanceof dbft.ImageDisplay ||
display instanceof dbft.MeshDisplay ||
display instanceof dbft.SharedMeshDisplay ||
display instanceof dbft.ArmatureDisplay
) {
if (display.path === display.name) {
display.path = "";
}
}
if (display instanceof dbft.MeshDisplay) {
if (display.weights.length > 0) {
for (let i = 0, l = display.weights.length; i < l; ++i) {
display.weights[i] = Number(display.weights[i].toFixed(6));
}
for (let i = 0, l = display.bonePose.length; i < l; ++i) {
display.bonePose[i] = Number(display.bonePose[i].toFixed(6)); // TODO
}
display._matrix.copyFromArray(display.slotPose, 0);
display.transform.identity();
display.slotPose[0] = 1.0;
display.slotPose[1] = 0.0;
display.slotPose[2] = 0.0;
display.slotPose[3] = 1.0;
display.slotPose[4] = 0.0;
display.slotPose[5] = 0.0;
}
else {
display.transform.toMatrix(display._matrix);
display.transform.identity();
}
for (let i = 0, l = display.uvs.length; i < l; ++i) {
display.uvs[i] = Number(display.uvs[i].toFixed(6));
}
for (let i = 0, l = display.vertices.length; i < l; i += 2) {
display._matrix.transformPoint(display.vertices[i], display.vertices[i + 1], geom.helpPointA);
display.vertices[i] = Number(geom.helpPointA.x.toFixed(2));
display.vertices[i + 1] = Number(geom.helpPointA.y.toFixed(2));
}
}
if (display instanceof dbft.PathDisplay) {
for (let i = 0, l = display.lengths.length; i < l; ++i) {
display.lengths[i] = Number(display.lengths[i].toFixed(2));
}
for (let i = 0, l = display.vertices.length; i < l; ++i) {
display.vertices[i] = Number(display.vertices[i].toFixed(2));
}
for (let i = 0, l = display.weights.length; i < l; ++i) {
display.weights[i] = Number(display.weights[i].toFixed(6));
}
}
if (
display instanceof dbft.RectangleBoundingBoxDisplay ||
display instanceof dbft.EllipseBoundingBoxDisplay
) {
display.width = Number(display.width.toFixed(2));
display.height = Number(display.height.toFixed(2));
}
if (display instanceof dbft.PolygonBoundingBoxDisplay) {
display.transform.toMatrix(geom.helpMatrixA);
display.transform.identity();
for (let i = 0, l = display.vertices.length; i < l; i += 2) {
geom.helpMatrixA.transformPoint(display.vertices[i], display.vertices[i + 1], geom.helpPointA);
display.vertices[i] = Number(geom.helpPointA.x.toFixed(2));
display.vertices[i + 1] = Number(geom.helpPointA.y.toFixed(2));
}
}
display.transform.skX = geom.normalizeDegree(display.transform.skX);
display.transform.skY = geom.normalizeDegree(display.transform.skY);
display.transform.toFixed();
}
}
}
for (const animation of armature.animation) {
if (!(animation instanceof dbft.Animation)) {
continue;
}
if (animation.zOrder) {
for (const frame of animation.zOrder.frame as dbft.MutilpleValueFrame[]) { // Fix zOrder bug.
for (let i = 0, l = frame.zOrder.length; i < l; i += 2) {
const index = frame.zOrder[i] + frame.zOrder[i + 1];
if (index < 0) {
frame.zOrder[i + 1] = armature.slot.length + index;
}
}
}
cleanFrame(animation.zOrder.frame);
if (animation.zOrder.frame.length === 0) {
animation.zOrder = null;
}
}
for (let i = 0, l = animation.bone.length; i < l; ++i) {
const timeline = animation.bone[i];
const bone = armature.getBone(timeline.name);
if (bone) {
for (const frame of timeline.frame) {
frame.transform.skX = geom.normalizeDegree(frame.transform.skX);
frame.transform.skY = geom.normalizeDegree(frame.transform.skY);
frame.transform.toFixed();
}
for (const frame of timeline.translateFrame) {
frame.x = Number(frame.x.toFixed(2));
frame.y = Number(frame.y.toFixed(2));
}
for (const frame of timeline.rotateFrame) {
frame.rotate = Number(geom.normalizeDegree(frame.rotate).toFixed(2));
frame.skew = Number(geom.normalizeDegree(frame.skew).toFixed(2));
}
for (const frame of timeline.scaleFrame) {
frame.x = Number(frame.x.toFixed(4));
frame.y = Number(frame.y.toFixed(4));
}
cleanFrame(timeline.frame);
cleanFrame(timeline.translateFrame);
cleanFrame(timeline.rotateFrame);
cleanFrame(timeline.scaleFrame);
if (timeline.frame.length === 1) {
const frame = timeline.frame[0];
if (
frame.transform.x === 0.0 &&
frame.transform.y === 0.0 &&
frame.transform.skX === 0.0 &&
frame.transform.skY === 0.0 &&
frame.transform.scX === 0.0 &&
frame.transform.scY === 0.0
) {
timeline.frame.length = 0;
}
}
if (timeline.translateFrame.length === 1) {
const frame = timeline.translateFrame[0];
if (frame.x === 0.0 && frame.y === 0.0) {
timeline.translateFrame.length = 0;
}
}
if (timeline.rotateFrame.length === 1) {
const frame = timeline.rotateFrame[0];
if (frame.rotate === 0.0 && frame.skew === 0.0) {
timeline.rotateFrame.length = 0;
}
}
if (timeline.scaleFrame.length === 1) {
const frame = timeline.scaleFrame[0];
if (frame.x === 0.0 && frame.y === 0.0) {
timeline.scaleFrame.length = 0;
}
}
if (timeline.frame.length > 0 || timeline.translateFrame.length > 0 || timeline.rotateFrame.length > 0 || timeline.scaleFrame.length > 0) {
continue;
}
}
animation.bone.splice(i, 1);
i--;
l--;
}
for (let i = 0, l = animation.slot.length; i < l; ++i) {
const timeline = animation.slot[i];
const slot = armature.getSlot(timeline.name);
if (slot) {
for (const frame of timeline.frame) {
frame.color.toFixed();
}
for (const frame of timeline.colorFrame) {
frame.value.toFixed();
}
cleanFrame(timeline.frame);
cleanFrame(timeline.displayFrame);
cleanFrame(timeline.colorFrame);
if (timeline.frame.length === 1) {
const frame = timeline.frame[0];
if (
frame.displayIndex === slot.displayIndex &&
frame.color.equal(slot.color)
) {
timeline.frame.length = 0;
}
}
if (timeline.displayFrame.length === 1) {
const frame = timeline.displayFrame[0];
if (frame.actions.length === 0 && frame.value === slot.displayIndex) {
timeline.displayFrame.length = 0;
}
}
if (timeline.colorFrame.length === 1) {
const frame = timeline.colorFrame[0];
if (frame.value.equal(slot.color)) {
timeline.colorFrame.length = 0;
}
}
if (timeline.frame.length > 0 || timeline.displayFrame.length > 0 || timeline.colorFrame.length > 0) {
continue;
}
}
animation.slot.splice(i, 1);
i--;
l--;
}
for (let i = 0, l = animation.ffd.length; i < l; ++i) {
const timeline = animation.ffd[i];
const slot = armature.getSlot(timeline.slot);
const display = armature.getDisplay(timeline.skin, timeline.slot, timeline.name) as dbft.MeshDisplay | null;
if (slot && display) {
const vertices = display.vertices;
// display.path = display.path || display.name;
// display.name = (timeline.skin ? timeline.skin + "_" : "") + (timeline.slot ? timeline.slot + "_" : "") + display.name;
// timeline.skin = ""; TODO
// timeline.slot = ""; TODO
for (const frame of timeline.frame as dbft.MutilpleValueFrame[]) {
let inSide = 0;
let x = 0.0;
let y = 0.0;
for (let i = 0, l = vertices.length; i < l; i += 2) {
inSide = 0;
if (i < frame.offset || i - frame.offset >= frame.vertices.length) {
x = 0.0;
}
else {
inSide = 1;
x = frame.vertices[i - frame.offset];
}
if (i + 1 < frame.offset || i + 1 - frame.offset >= frame.vertices.length) {
y = 0.0;
}
else {
if (inSide === 0) {
inSide = -1;
}
y = frame.vertices[i + 1 - frame.offset];
}
if (inSide !== 0) {
display._matrix.transformPoint(x, y, geom.helpPointA, true);
if (inSide === 1) {
frame.vertices[i - frame.offset] = geom.helpPointA.x;
}
frame.vertices[i + 1 - frame.offset] = geom.helpPointA.y;
}
}
frame.offset += formatDeform(frame.vertices);
}
cleanFrame(timeline.frame);
if (timeline.frame.length === 1) {
const frame = timeline.frame[0] as dbft.MutilpleValueFrame;
if (frame.vertices.length === 0) {
timeline.frame.length = 0;
}
}
if (timeline.frame.length > 0) {
continue;
}
}
animation.ffd.splice(i, 1);
i--;
l--;
}
for (let i = 0, l = animation.timeline.length; i < l; ++i) {
const timeline = animation.timeline[i];
switch (timeline.type) {
case dbft.TimelineType.Action:
case dbft.TimelineType.ZOrder: {
cleanFrame(timeline.frame);
break;
}
case dbft.TimelineType.SlotDisplay: {
const slot = armature.getSlot(timeline.name);
if (slot) {
cleanFrame(timeline.frame);
if (timeline.frame.length === 1) {
const frame = timeline.frame[0] as dbft.SingleValueFrame0;
if (frame.value === slot.displayIndex) {
timeline.frame.length = 0;
}
}
}
else {
timeline.frame.length = 0;
}
break;
}
case dbft.TimelineType.SlotZIndex: {
const slot = armature.getSlot(timeline.name);
if (slot) {
cleanFrame(timeline.frame);
// if (timeline.frame.length === 1) {
// const frame = timeline.frame[0] as dbft.SingleValueFrame0;
// if (frame.value === slot.zIndex) {
// timeline.frame.length = 0;
// }
// }
}
else {
timeline.frame.length = 0;
}
break;
}
case dbft.TimelineType.BoneAlpha:
case dbft.TimelineType.SlotAlpha: {
const frames = timeline.frame as dbft.SingleValueFrame1[];
for (const frame of frames) {
frame.value = Number(frame.value.toFixed(2));
}
cleanFrame(frames);
// if (frames.length === 1) { // TODO
// const frame = frames[0];
// if (frame.value === 1.0) {
// frames.length = 0;
// }
// }
break;
}
case dbft.TimelineType.BoneTranslate:
case dbft.TimelineType.BoneRotate: {
const frames = timeline.frame as dbft.DoubleValueFrame0[];
for (const frame of frames) {
frame.x = Number(frame.x.toFixed(2));
frame.y = Number(frame.y.toFixed(2));
}
cleanFrame(frames);
if (frames.length === 1) {
const frame = frames[0];
if (frame.x === 0.0 && frame.y === 0.0) {
frames.length = 0;
}
}
break;
}
case dbft.TimelineType.IKConstraint:
case dbft.TimelineType.BoneScale: {
const frames = timeline.frame as dbft.DoubleValueFrame1[];
for (const frame of frames) {
frame.x = Number(frame.x.toFixed(4));
frame.y = Number(frame.y.toFixed(4));
}
cleanFrame(frames);
if (frames.length === 1) {
const frame = frames[0];
if (frame.x === 1.0 && frame.y === 1.0) {
frames.length = 0;
}
}
break;
}
case dbft.TimelineType.Surface:
case dbft.TimelineType.SlotDeform: {
const frames = timeline.frame as dbft.MutilpleValueFrame[];
for (const frame of frames) {
frame.offset += formatDeform(frame.value);
}
cleanFrame(frames);
if (frames.length === 1) {
const frame = frames[0];
if (frame.value.length === 0) {
frames.length = 0;
}
}
break;
}
case dbft.TimelineType.AnimationProgress:
case dbft.TimelineType.AnimationWeight:
case dbft.TimelineType.AnimationParameter: {
if (timeline instanceof dbft.AnimationTimeline) {
timeline.x = Number(timeline.x.toFixed(4));
timeline.y = Number(timeline.y.toFixed(4));
}
if (timeline.type === dbft.TimelineType.AnimationParameter) {
const frames = timeline.frame as dbft.DoubleValueFrame0[];
for (const frame of frames) {
frame.x = Number(frame.x.toFixed(4));
frame.y = Number(frame.y.toFixed(4));
}
cleanFrame(frames);
}
else {
const frames = timeline.frame as (dbft.SingleValueFrame0 | dbft.SingleValueFrame1)[];
for (const frame of frames) {
frame.value = Number(frame.value.toFixed(4));
}
cleanFrame(frames);
cleanFrameB(frames);
}
break;
}
case dbft.TimelineType.SlotColor: {
const slot = armature.getSlot(timeline.name);
const frames = timeline.frame as dbft.SlotColorFrame[];
if (slot) {
for (const frame of frames) {
frame.value.toFixed();
}
cleanFrame(frames);
if (frames.length === 1) {
const frame = frames[0];
if (frame.value.equal(slot.color)) {
frames.length = 0;
}
}
}
else {
frames.length = 0;
}
break;
}
}
if (timeline.frame.length > 0) {
continue;
}
animation.timeline.splice(i, 1);
i--;
l--;
}
}
}
for (const textureAtlas of data.textureAtlas) {
formatTextureAtlas(textureAtlas);
}
}
if (textureAtlases) {
for (const textureAtlas of textureAtlases) {
formatTextureAtlas(textureAtlas);
}
}
}
function formatDeform(deform: number[]) {
for (let i = 0, l = deform.length; i < l; ++i) {
deform[i] = Number(deform[i].toFixed(2));
}
let begin = 0;
while (deform[begin] === 0.0) {
begin++;
if (begin === deform.length - 1) {
break;
}
}
let end = deform.length;
while (end > begin && deform[end - 1] === 0.0) {
end--;
}
let index = 0;
for (let i = begin; i < end; ++i) {
deform[index++] = deform[i];
}
deform.length = end - begin;
return begin;
}
function formatTextureAtlas(textureAtlas: dbft.TextureAtlas) {
for (const subTexture of textureAtlas.SubTexture) {
if (textureAtlas.width > 0 && subTexture.x + subTexture.width > textureAtlas.width) {
subTexture.width = textureAtlas.width - subTexture.x;
}
if (textureAtlas.height > 0 && subTexture.y + subTexture.height > textureAtlas.height) {
subTexture.height = textureAtlas.height - subTexture.x;
}
if (subTexture.x < 0) {
subTexture.x = 0;
}
if (subTexture.y < 0) {
subTexture.y = 0;
}
if (subTexture.width < 0) {
subTexture.width = 0;
}
if (subTexture.height < 0) {
subTexture.height = 0;
}
if (
(subTexture.frameWidth === subTexture.width && subTexture.frameHeight === subTexture.height) ||
(subTexture.frameWidth === subTexture.height && subTexture.frameHeight === subTexture.width)
) {
subTexture.frameWidth = 0;
subTexture.frameHeight = 0;
}
if (subTexture.frameWidth < 0) {
subTexture.frameWidth = 0;
}
if (subTexture.frameHeight < 0) {
subTexture.frameHeight = 0;
}
}
}
function cleanFrame(frames: dbft.Frame[]) {
let prevFrame: dbft.Frame | null = null;
for (let i = 0, l = frames.length; i < l; ++i) {
const frame = frames[i];
if (
prevFrame && prevFrame.equal(frame) &&
(i === l - 1 || !(frame instanceof dbft.TweenFrame) || frame.equal(frames[i + 1] as dbft.TweenFrame))
) {
prevFrame.duration += frame.duration;
if (i === l - 1 && prevFrame instanceof dbft.TweenFrame) {
prevFrame.removeTween();
}
frames.splice(i, 1);
i--;
l--;
}
else {
prevFrame = frame;
}
}
}
function cleanFrameB(frames: dbft.SingleValueFrame0[]) {
let prevFrameA: dbft.SingleValueFrame0 | null = null;
let prevFrameB: dbft.SingleValueFrame0 | null = null;
for (let i = 0, l = frames.length; i < l; ++i) {
const frame = frames[i];
if (
i !== l - 1 &&
prevFrameA && prevFrameB &&
prevFrameA.getTweenEnabled() && prevFrameB.getTweenEnabled() &&
equalB(prevFrameA, prevFrameB, frame)
) {
prevFrameA.duration += prevFrameB.duration;
frames.splice(i - 1, 1);
i--;
l--;
prevFrameB = frame;
}
else {
prevFrameA = prevFrameB;
prevFrameB = frame;
}
}
}
function equalB(a: dbft.SingleValueFrame0, b: dbft.SingleValueFrame0, c: dbft.SingleValueFrame0) {
return Math.abs((b.value - a.value) / a.duration - (c.value - b.value) / b.duration) < 0.01;
} | the_stack |
import React, { useState } from "react";
import {
Box,
Button,
IconButton,
Popover,
Tooltip,
Typography,
useMediaQuery,
useTheme
} from "@mui/material";
import { Add, Delete } from "@mui/icons-material";
import {
AdditionalColumnDelegate,
CollectionSize,
Entity,
EntityCollection,
SaveEntityProps
} from "../../models";
import CollectionTable from "../../collection/components/CollectionTable";
import CollectionRowActions
from "../../collection/internal/CollectionRowActions";
import DeleteEntityDialog from "../../collection/internal/DeleteEntityDialog";
import ExportButton from "../../collection/internal/ExportButton";
import {
getSubcollectionColumnId,
useColumnIds
} from "../../collection/internal/common";
import { canCreate, canDelete, canEdit } from "../util/permissions";
import { OnCellValueChange, UniqueFieldValidator } from "../../collection";
import { Markdown } from "../../preview";
import {
saveEntityWithCallbacks,
useAuthController,
useDataSource, useFireCMSContext,
useSideEntityController
} from "../../hooks";
/**
* @category Core components
*/
export interface EntityCollectionProps<M extends { [Key: string]: any }> {
path: string;
collection: EntityCollection<M>;
}
/**
* This component is in charge of binding a datasource path with an {@link EntityCollection}
* where it's configuration is defined. This is useful if you have defined already
* your entity collections and need to build a custom component.
*
* Please note that you only need to use this component if you are building
* a custom view. If you just need to create a default view you can do it
* exclusively with config options.
*
* If you need a lower level implementation with more granular options, you
* can try {@link CollectionTable}, which still does data fetching from the datasource.
*
* @param path
* @param collectionConfig
* @constructor
* @category Core components
*/
export default function EntityCollectionTable<M extends { [Key: string]: any }>({
path,
collection
}: EntityCollectionProps<M>
) {
const sideEntityController = useSideEntityController();
const dataSource = useDataSource();
const context = useFireCMSContext();
const authController = useAuthController();
const theme = useTheme();
const largeLayout = useMediaQuery(theme.breakpoints.up("md"));
const [deleteEntityClicked, setDeleteEntityClicked] = React.useState<Entity<M> | Entity<M>[] | undefined>(undefined);
const [selectedEntities, setSelectedEntities] = useState<Entity<M>[]>([]);
const exportable = collection.exportable === undefined || collection.exportable;
const inlineEditing = collection.inlineEditing === undefined || collection.inlineEditing;
const selectionEnabled = collection.selectionEnabled === undefined || collection.selectionEnabled;
const paginationEnabled = collection.pagination === undefined || Boolean(collection.pagination);
const pageSize = typeof collection.pagination === "number" ? collection.pagination : undefined;
const displayedProperties = useColumnIds(collection, true);
const [anchorEl, setAnchorEl] = React.useState<HTMLElement | null>(null);
const subcollectionColumns: AdditionalColumnDelegate<any>[] = collection.subcollections?.map((subcollection) => {
return {
id: getSubcollectionColumnId(subcollection),
title: subcollection.name,
width: 200,
builder: ({ entity }) => (
<Button color={"primary"}
onClick={(event) => {
event.stopPropagation();
sideEntityController.open({
path,
entityId: entity.id,
selectedSubpath: subcollection.path,
permissions: collection.permissions,
schema: collection.schema,
subcollections: collection.subcollections,
callbacks: collection.callbacks,
overrideSchemaResolver: false
});
}}>
{subcollection.name}
</Button>
)
};
}) ?? [];
const additionalColumns = [...(collection.additionalColumns ?? []), ...subcollectionColumns];
const onEntityClick = (entity: Entity<M>) => {
sideEntityController.open({
entityId: entity.id,
path,
permissions: collection.permissions,
schema: collection.schema,
subcollections: collection.subcollections,
callbacks: collection.callbacks,
overrideSchemaResolver: false
});
};
const onNewClick = (e: React.MouseEvent) => {
e.stopPropagation();
return path && sideEntityController.open({
path,
permissions: collection.permissions,
schema: collection.schema,
subcollections: collection.subcollections,
callbacks: collection.callbacks,
overrideSchemaResolver: false
});
};
const internalOnEntityDelete = (path: string, entity: Entity<M>) => {
setSelectedEntities(selectedEntities.filter((e) => e.id !== entity.id));
};
const internalOnMultipleEntitiesDelete = (path: string, entities: Entity<M>[]) => {
setSelectedEntities([]);
setDeleteEntityClicked(undefined);
};
const checkInlineEditing = (entity: Entity<any>) => {
if (!canEdit(collection.permissions, entity, authController, path, context)) {
return false;
}
return inlineEditing;
};
const onCellChanged: OnCellValueChange<any, M> = ({
value,
name,
setSaved,
setError,
entity
}) => {
const saveProps: SaveEntityProps<M> = {
path,
entityId: entity.id,
values: {
...entity.values,
[name]: value
},
schema: collection.schema,
status: "existing"
};
return saveEntityWithCallbacks({
...saveProps,
callbacks: collection.callbacks,
dataSource,
context,
onSaveSuccess: () => setSaved(true),
onSaveFailure: ((e: Error) => {
setError(e);
})
});
};
const open = anchorEl != null;
const title = (
<div style={{
padding: "4px"
}}>
<Typography
variant="h6"
style={{
lineHeight: "1.0",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
overflow: "hidden",
maxWidth: "160px",
cursor: collection.description ? "pointer" : "inherit"
}}
onClick={collection.description ? (e) => {
setAnchorEl(e.currentTarget);
e.stopPropagation();
} : undefined}
>
{`${collection.name}`}
</Typography>
<Typography
style={{
display: "block",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
overflow: "hidden",
maxWidth: "160px",
direction: "rtl",
textAlign: "left"
}}
variant={"caption"}
color={"textSecondary"}>
{`/${path}`}
</Typography>
{collection.description &&
<Popover
id={"info-dialog"}
open={open}
anchorEl={anchorEl}
elevation={1}
onClose={() => {
setAnchorEl(null);
}}
anchorOrigin={{
vertical: "bottom",
horizontal: "center"
}}
transformOrigin={{
vertical: "top",
horizontal: "center"
}}
>
<Box m={2}>
<Markdown source={collection.description}/>
</Box>
</Popover>
}
</div>
);
const toggleEntitySelection = (entity: Entity<M>) => {
let newValue;
if (selectedEntities.indexOf(entity) > -1) {
newValue = selectedEntities.filter((item: Entity<M>) => item !== entity);
} else {
newValue = [...selectedEntities, entity];
}
setSelectedEntities(newValue);
setDeleteEntityClicked(undefined);
};
const uniqueFieldValidator: UniqueFieldValidator = ({
name,
value,
property,
entityId
}) => dataSource.checkUniqueField(path, name, value, property, entityId);
const tableRowActionsBuilder = ({
entity,
size
}: { entity: Entity<any>, size: CollectionSize }) => {
const isSelected = selectedEntities.indexOf(entity) > -1;
const createEnabled = canCreate(collection.permissions, authController, path, context);
const editEnabled = canEdit(collection.permissions, entity, authController, path, context);
const deleteEnabled = canDelete(collection.permissions, entity, authController, path, context);
const onCopyClicked = (entity: Entity<M>) => sideEntityController.open({
entityId: entity.id,
path,
copy: true,
permissions: {
edit: editEnabled,
create: createEnabled,
delete: deleteEnabled
},
schema: collection.schema,
subcollections: collection.subcollections,
callbacks: collection.callbacks,
overrideSchemaResolver: false
});
const onEditClicked = (entity: Entity<M>) => sideEntityController.open({
entityId: entity.id,
path,
permissions: {
edit: editEnabled,
create: createEnabled,
delete: deleteEnabled
},
schema: collection.schema,
subcollections: collection.subcollections,
callbacks: collection.callbacks,
overrideSchemaResolver: false
});
return (
<CollectionRowActions
entity={entity}
isSelected={isSelected}
selectionEnabled={selectionEnabled}
size={size}
toggleEntitySelection={toggleEntitySelection}
onEditClicked={onEditClicked}
onCopyClicked={createEnabled ? onCopyClicked : undefined}
onDeleteClicked={deleteEnabled ? setDeleteEntityClicked : undefined}
/>
);
};
function toolbarActionsBuilder({
size,
data
}: { size: CollectionSize, data: Entity<any>[] }) {
const addButton = canCreate(collection.permissions, authController, path, context) && onNewClick && (largeLayout ?
<Button
onClick={onNewClick}
startIcon={<Add/>}
size="large"
variant="contained"
color="primary">
Add {collection.schema.name}
</Button>
: <Button
onClick={onNewClick}
size="medium"
variant="contained"
color="primary"
>
<Add/>
</Button>);
const multipleDeleteEnabled = selectedEntities.every((entity) => canDelete(collection.permissions, entity, authController, path, context));
const onMultipleDeleteClick = (event: React.MouseEvent) => {
event.stopPropagation();
setDeleteEntityClicked(selectedEntities);
};
const multipleDeleteButton = selectionEnabled &&
<Tooltip
title={multipleDeleteEnabled ? "Multiple delete" : "You have selected one entity you cannot delete"}>
<span>
{largeLayout && <Button
disabled={!(selectedEntities?.length) || !multipleDeleteEnabled}
startIcon={<Delete/>}
onClick={onMultipleDeleteClick}
color={"primary"}
>
<p style={{ minWidth: 24 }}>({selectedEntities?.length})</p>
</Button>}
{!largeLayout &&
<IconButton
color={"primary"}
disabled={!(selectedEntities?.length) || !multipleDeleteEnabled}
onClick={onMultipleDeleteClick}
size="large">
<Delete/>
</IconButton>}
</span>
</Tooltip>;
const extraActions = collection.extraActions ? collection.extraActions({
path,
collection,
selectedEntities,
context
}) : undefined;
const exportButton = exportable &&
<ExportButton schema={collection.schema}
exportConfig={typeof collection.exportable === "object" ? collection.exportable : undefined}
path={path}/>;
return (
<>
{extraActions}
{multipleDeleteButton}
{exportButton}
{addButton}
</>
);
}
return (
<>
<CollectionTable
title={title}
frozenIdColumn={largeLayout}
path={path}
schema={collection.schema}
additionalColumns={additionalColumns}
defaultSize={collection.defaultSize}
displayedProperties={displayedProperties}
initialFilter={collection.initialFilter}
initialSort={collection.initialSort}
textSearchEnabled={collection.textSearchEnabled}
paginationEnabled={paginationEnabled}
pageSize={pageSize}
filterCombinations={collection.filterCombinations}
inlineEditing={checkInlineEditing}
uniqueFieldValidator={uniqueFieldValidator}
onEntityClick={onEntityClick}
onCellValueChange={onCellChanged}
tableRowActionsBuilder={tableRowActionsBuilder}
toolbarActionsBuilder={toolbarActionsBuilder}
/>
<DeleteEntityDialog entityOrEntitiesToDelete={deleteEntityClicked}
path={path}
schema={collection.schema}
callbacks={collection.callbacks}
open={!!deleteEntityClicked}
onEntityDelete={internalOnEntityDelete}
onMultipleEntitiesDelete={internalOnMultipleEntitiesDelete}
onClose={() => setDeleteEntityClicked(undefined)}/>
</>
);
}
export { EntityCollectionTable }; | the_stack |
import { validate } from 'class-validator';
import { ArgumentValidationError } from 'type-graphql';
import {
Brackets,
DeepPartial,
EntityManager,
getRepository,
Repository,
SelectQueryBuilder
} from 'typeorm';
import { ColumnMetadata } from 'typeorm/metadata/ColumnMetadata';
import { isArray } from 'util';
import { debug } from '../decorators';
import { StandardDeleteResponse } from '../tgql';
import { addQueryBuilderWhereItem } from '../torm';
import { BaseModel } from './';
import { ConnectionInputFields, GraphQLInfoService } from './GraphQLInfoService';
import {
ConnectionResult,
RelayFirstAfter,
RelayLastBefore,
RelayPageOptions,
RelayService
} from './RelayService';
import { StringMap, WhereInput } from './types';
export interface BaseOptions {
manager?: EntityManager; // Allows consumers to pass in a TransactionManager
}
interface WhereFilterAttributes {
[key: string]: string | number | null;
}
type WhereExpression = {
AND?: WhereExpression[];
OR?: WhereExpression[];
} & WhereFilterAttributes;
export type LimitOffset = {
limit: number;
offset?: number;
};
export type PaginationOptions = LimitOffset | RelayPageOptions;
export type RelayPageOptionsInput = {
first?: number;
after?: string;
last?: number;
before?: string;
};
function isLastBefore(
pageType: PaginationOptions | RelayPageOptionsInput
): pageType is RelayLastBefore {
return (pageType as RelayLastBefore).last !== undefined;
}
export class BaseService<E extends BaseModel> {
manager: EntityManager;
columnMap: StringMap;
klass: string;
relayService: RelayService;
graphQLInfoService: GraphQLInfoService;
// TODO: any -> ObjectType<E> (or something close)
// V3: Only ask for entityClass, we can get repository and manager from that
constructor(protected entityClass: any, protected repository: Repository<E>) {
if (!entityClass) {
throw new Error('BaseService requires an entity Class');
}
// TODO: use DI
this.relayService = new RelayService();
this.graphQLInfoService = new GraphQLInfoService();
// V3: remove the need to inject a repository, we simply need the entityClass and then we can do
// everything we need to do.
// For now, we'll keep the API the same so that there are no breaking changes
this.manager = this.repository.manager;
// TODO: This handles an issue with typeorm-typedi-extensions where it is unable to
// Inject the proper repository
if (!repository) {
this.repository = getRepository(entityClass);
}
if (!repository) {
throw new Error(`BaseService requires a valid repository, class ${entityClass}`);
}
// Need a mapping of camelCase field name to the modified case using the naming strategy. For the standard
// SnakeNamingStrategy this would be something like { id: 'id', stringField: 'string_field' }
this.columnMap = this.repository.metadata.columns.reduce(
(prev: StringMap, column: ColumnMetadata) => {
prev[column.propertyPath] = column.databasePath;
return prev;
},
{}
);
this.klass = this.repository.metadata.name.toLowerCase();
}
async find<W extends WhereInput>(
where?: any, // V3: WhereExpression = {},
orderBy?: string,
limit?: number,
offset?: number,
fields?: string[]
): Promise<E[]> {
// TODO: FEATURE - make the default limit configurable
limit = limit ?? 20;
return this.buildFindQuery<W>(where, orderBy, { limit, offset }, fields).getMany();
}
@debug('base-service:findConnection')
async findConnection<W extends WhereInput>(
whereUserInput: any = {}, // V3: WhereExpression = {},
orderBy?: string | string[],
_pageOptions: RelayPageOptionsInput = {},
fields?: ConnectionInputFields
): Promise<ConnectionResult<E>> {
// TODO: if the orderby items aren't included in `fields`, should we automatically include?
// TODO: FEATURE - make the default limit configurable
const DEFAULT_LIMIT = 50;
const { first, after, last, before } = _pageOptions;
let relayPageOptions;
let limit;
let cursor;
if (isLastBefore(_pageOptions)) {
limit = last || DEFAULT_LIMIT;
cursor = before;
relayPageOptions = {
last: limit,
before
} as RelayLastBefore;
} else {
limit = first || DEFAULT_LIMIT;
cursor = after;
relayPageOptions = {
first: limit,
after
} as RelayFirstAfter;
}
const requestedFields = this.graphQLInfoService.connectionOptions(fields);
const sorts = this.relayService.normalizeSort(orderBy);
let whereFromCursor = {};
if (cursor) {
whereFromCursor = this.relayService.getFilters(orderBy, relayPageOptions);
}
const whereCombined: any = { AND: [whereUserInput, whereFromCursor] };
const qb = this.buildFindQuery<W>(
whereCombined,
this.relayService.effectiveOrderStrings(sorts, relayPageOptions),
{ limit: limit + 1 }, // We ask for 1 too many so that we know if there is an additional page
requestedFields.selectFields
);
let rawData;
let totalCountOption = {};
if (requestedFields.totalCount) {
let totalCount;
[rawData, totalCount] = await qb.getManyAndCount();
totalCountOption = { totalCount };
} else {
rawData = await qb.getMany();
}
// If we got the n+1 that we requested, pluck the last item off
const returnData = rawData.length > limit ? rawData.slice(0, limit) : rawData;
return {
...totalCountOption,
edges: returnData.map((item: E) => {
return {
node: item,
cursor: this.relayService.encodeCursor(item, sorts)
};
}),
pageInfo: this.relayService.getPageInfo(rawData, sorts, relayPageOptions)
};
}
@debug('base-service:buildFindQuery')
buildFindQuery<W extends WhereInput>(
where: WhereExpression = {},
orderBy?: string | string[],
pageOptions?: LimitOffset,
fields?: string[]
): SelectQueryBuilder<E> {
const DEFAULT_LIMIT = 50;
let qb = this.manager.createQueryBuilder<E>(this.entityClass, this.klass);
if (!pageOptions) {
pageOptions = {
limit: DEFAULT_LIMIT
};
}
qb = qb.take(pageOptions.limit || DEFAULT_LIMIT);
if (pageOptions.offset) {
qb = qb.skip(pageOptions.offset);
}
if (fields) {
// We always need to select ID or dataloaders will not function properly
if (fields.indexOf('id') === -1) {
fields.push('id');
}
// Querybuilder requires you to prefix all fields with the table alias. It also requires you to
// specify the field name using it's TypeORM attribute name, not the camel-cased DB column name
const selection = fields
.filter(field => this.columnMap[field]) // This will filter out any association records that come in @Fields
.map(field => `${this.klass}.${field}`);
qb = qb.select(selection);
}
if (orderBy) {
if (!isArray(orderBy)) {
orderBy = [orderBy];
}
orderBy.forEach((orderByItem: string) => {
const parts = orderByItem.toString().split('_');
// TODO: ensure attr is one of the properties on the model
const attr = parts[0];
const direction: 'ASC' | 'DESC' = parts[1] as 'ASC' | 'DESC';
qb = qb.addOrderBy(this.attrToDBColumn(attr), direction);
});
}
// Soft-deletes are filtered out by default, setting `deletedAt_all` is the only way to turn this off
const hasDeletedAts = Object.keys(where).find(key => key.indexOf('deletedAt_') === 0);
// If no deletedAt filters specified, hide them by default
if (!hasDeletedAts) {
// eslint-disable-next-line @typescript-eslint/camelcase
where.deletedAt_eq = null; // Filter out soft-deleted items
} else if (typeof where.deletedAt_all !== 'undefined') {
// Delete this param so that it doesn't try to filter on the magic `all` param
// Put this here so that we delete it even if `deletedAt_all: false` specified
delete where.deletedAt_all;
} else {
// If we get here, the user has added a different deletedAt filter, like deletedAt_gt: <date>
// do nothing because the specific deleted at filters will be added by processWhereOptions
}
// Keep track of a counter so that TypeORM doesn't reuse our variables that get passed into the query if they
// happen to reference the same column
const paramKeyCounter = { counter: 0 };
const processWheres = (
qb: SelectQueryBuilder<E>,
where: WhereFilterAttributes
): SelectQueryBuilder<E> => {
// where is of shape { userName_contains: 'a' }
Object.keys(where).forEach((k: string) => {
const paramKey = `param${paramKeyCounter.counter}`;
// increment counter each time we add a new where clause so that TypeORM doesn't reuse our input variables
paramKeyCounter.counter = paramKeyCounter.counter + 1;
const key = k as keyof W; // userName_contains
const parts = key.toString().split('_'); // ['userName', 'contains']
const attr = parts[0]; // userName
const operator = parts.length > 1 ? parts[1] : 'eq'; // contains
return addQueryBuilderWhereItem(
qb,
paramKey,
this.attrToDBColumn(attr),
operator,
where[key]
);
});
return qb;
};
// WhereExpression comes in the following shape:
// {
// AND?: WhereInput[];
// OR?: WhereInput[];
// [key: string]: string | number | null;
// }
const processWhereInput = (
qb: SelectQueryBuilder<E>,
where: WhereExpression
): SelectQueryBuilder<E> => {
const { AND, OR, ...rest } = where;
if (AND && AND.length) {
const ands = AND.filter(value => JSON.stringify(value) !== '{}');
if (ands.length) {
qb.andWhere(
new Brackets(qb2 => {
ands.forEach((where: WhereExpression) => {
if (Object.keys(where).length === 0) {
return; // disregard empty where objects
}
qb2.andWhere(
new Brackets(qb3 => {
processWhereInput(qb3 as SelectQueryBuilder<any>, where);
return qb3;
})
);
});
})
);
}
}
if (OR && OR.length) {
const ors = OR.filter(value => JSON.stringify(value) !== '{}');
if (ors.length) {
qb.andWhere(
new Brackets(qb2 => {
ors.forEach((where: WhereExpression) => {
if (Object.keys(where).length === 0) {
return; // disregard empty where objects
}
qb2.orWhere(
new Brackets(qb3 => {
processWhereInput(qb3 as SelectQueryBuilder<any>, where);
return qb3;
})
);
});
})
);
}
}
if (rest) {
processWheres(qb, rest);
}
return qb;
};
if (Object.keys(where).length) {
processWhereInput(qb, where);
}
return qb;
}
async findOne<W>(
where: W // V3: WhereExpression
): Promise<E> {
const items = await this.find(where);
if (!items.length) {
throw new Error(`Unable to find ${this.entityClass.name} where ${JSON.stringify(where)}`);
} else if (items.length > 1) {
throw new Error(
`Found ${items.length} ${this.entityClass.name}s where ${JSON.stringify(where)}`
);
}
return items[0];
}
async create(data: DeepPartial<E>, userId: string, options?: BaseOptions): Promise<E> {
const manager = options?.manager ?? this.manager;
const entity = manager.create<E>(this.entityClass, { ...data, createdById: userId });
// Validate against the the data model
// Without `skipMissingProperties`, some of the class-validator validations (like MinLength)
// will fail if you don't specify the property
const errors = await validate(entity, { skipMissingProperties: true });
if (errors.length) {
// TODO: create our own error format
throw new ArgumentValidationError(errors);
}
// TODO: remove any when this is fixed: https://github.com/Microsoft/TypeScript/issues/21592
// TODO: Fix `any`
return manager.save(entity as any, { reload: true });
}
async createMany(data: DeepPartial<E>[], userId: string, options?: BaseOptions): Promise<E[]> {
const manager = options?.manager ?? this.manager;
data = data.map(item => {
return { ...item, createdById: userId };
});
const results = manager.create(this.entityClass, data);
// Validate against the the data model
// Without `skipMissingProperties`, some of the class-validator validations (like MinLength)
// will fail if you don't specify the property
for (const obj of results) {
const errors = await validate(obj, { skipMissingProperties: true });
if (errors.length) {
// TODO: create our own error format that matches Mike B's format
throw new ArgumentValidationError(errors);
}
}
return manager.save(results, { reload: true });
}
// TODO: There must be a more succinct way to:
// - Test the item exists
// - Update
// - Return the full object
// NOTE: assumes all models have a unique `id` field
// W extends Partial<E>
async update<W extends any>(
data: DeepPartial<E>,
where: W, // V3: WhereExpression,
userId: string,
options?: BaseOptions
): Promise<E> {
const manager = options?.manager ?? this.manager;
const found = await this.findOne(where);
const mergeData = ({ id: found.id, updatedById: userId } as any) as DeepPartial<E>;
const entity = manager.merge<E>(this.entityClass, new this.entityClass(), data, mergeData);
// skipMissingProperties -> partial validation of only supplied props
const errors = await validate(entity, { skipMissingProperties: true });
if (errors.length) {
throw new ArgumentValidationError(errors);
}
const result = await manager.save<E>(entity);
return manager.findOneOrFail(this.entityClass, result.id);
}
async delete<W extends object>(
where: W,
userId: string,
options?: BaseOptions
): Promise<StandardDeleteResponse> {
const manager = options?.manager ?? this.manager;
const data = {
deletedAt: new Date().toISOString(),
deletedById: userId
};
const whereNotDeleted = {
...where,
deletedAt: null
};
const found = await manager.findOneOrFail<E>(this.entityClass, whereNotDeleted as any);
const idData = ({ id: found.id } as any) as DeepPartial<E>;
const entity = manager.merge<E>(this.entityClass, new this.entityClass(), data as any, idData);
await manager.save(entity as any);
return { id: found.id };
}
attrsToDBColumns = (attrs: string[]): string[] => {
return attrs.map(this.attrToDBColumn);
};
attrToDBColumn = (attr: string): string => {
return `"${this.klass}"."${this.columnMap[attr]}"`;
};
} | the_stack |
"use strict";
// uuid: f3413d18-79c1-4c02-92c6-8ecef7f9da79
// ------------------------------------------------------------------------
// Copyright (c) 2018 Alexandre Bento Freire. All rights reserved.
// Licensed under the MIT License+uuid License. See License.txt for details
// ------------------------------------------------------------------------
// Implementation of ElementAdapters and SceneAdapters in order to
// support DOM Elements/Scenes and virtual Elements/Scenes
/** @module end-user | The lines bellow convey information for the end-user */
/**
* ## Description
*
* An **adapter** allows ABeamer to decouple from DOM by serving as an agent
* between the ABeamer library and elements and scenes.
*
* For DOM adapters, ABeamer uses `jQuery` to query DOM and
* maps special properties such `text` and `html` to
* `textContent` and `innerHTML`.
*
* DOM adapters map [DOM Properties](DOM Property) into either HtmlElement attributes
* or CSS properties, depending on the Animation Property name.
*
* For HtmlElement attributes, the DOM Adapter uses `element.getAttribute`.
* For CSS Properties, it uses `element.style`, but if it's empty,
* it retrieves all the computed CSS properties via `window.getComputedStyle`
* and caches its content.
*
* DOM Adapters use the attribute `data-abeamer-display` to define which
* value will be used in `display` when visible is set to true.
* If it's not defined, it will be set to `inline` for `span` tags,
* and `block` for all the other tags.
*
* 'DOM Scenes' are typically a DIV. 'DOM Elements' can be any HtmlElement.
*
* 'DOM Scenes' can provide Virtual Elements via ids starting with `%`,
* and `story.onGetVirtualElement`.
*
* For Virtual adapters there is a direct connection to the Virtual Element
* and Scene property.
*
* Unlike DOM elements which only provide textual values, Virtual Elements can
* get and set numerical values.
*/
namespace ABeamer {
// #generate-group-section
// ------------------------------------------------------------------------
// Elements
// ------------------------------------------------------------------------
// The following section contains data for the end-user
// generated by `gulp build-definition-files`
// -------------------------------
// #export-section-start: release
/**
* Defines the special names for [Adapter properties](#Adapter property) names.
*/
export type SpecialAdapterPropName =
// modifies the textContent property.
'text'
// same as text. It's preferable to use 'text'.
| 'textContent'
// modifies the innerHTML attribute.
| 'html'
// same as html. It's preferable to use 'html'.
| 'innerHTML'
// modifies outerHTML attribute.
| 'outerHTML'
// changes the style.display CSS property for DOM Elements/Scenes.
// Uses DOM attribute `data-abeamer-display`.
| 'visible'
// modifies the attribute `src`.
| 'src'
// modifies the `classList` if it has `+` or `-` if has it starts a class.
// otherwise it sets `className`.
| 'class'
;
/**
* **Dual properties** are properties that map one animation property into 2 [](DOM properties).
*/
export type DualPropName = 'width-height'
| 'left-top'
| 'right-top'
| 'left-bottom'
| 'right-bottom';
/**
* List of Property Names that a DOM or Virtual Element should support.
*/
export type ElPropName = string
| 'id'
| 'visible'
| 'uid'
| 'data-abeamer-display'
;
/**
* List of Property Names that a DOM or Virtual Scene should support.
*/
export type ScenePropName = string
| 'html'
| 'left'
| 'top'
| 'width'
| 'height'
/** If this value is set, it will for `Visible=true` */
| 'data-abeamer-display'
;
/**
* List of Property Names that a DOM or Virtual Story should support.
*/
export type StoryPropName = string
| 'frame-width'
| 'frame-height'
/** clip-path is a set only. see CSS clip-story properties */
| 'clip-path'
| 'fps'
;
/**
* Union of Property Names that a DOM or Virtual Adapter should support.
*/
export type PropName = string
| ElPropName
| ScenePropName
| StoryPropName
| SpecialAdapterPropName
| DualPropName
;
/**
* Although, DOM only returns string values, a virtual Element can use
* more rich data types.
* e.g. DOM adapter maps a boolean `visible` into CSS display.
* A virtual element can use directly booleans.
*/
export type PropValue = string | number | int | boolean;
export enum WaitForWhat {
Custom,
ImageLoad,
MediaSync,
}
export interface WaitFor {
prop: PropName;
value?: string | number;
what?: WaitForWhat;
}
export type WaitForList = WaitFor[];
/**
* Base interface for virtual elements such as WebGL, Canvas or Task animator.
*/
export interface VirtualElement {
getProp(name: PropName, args?: ABeamerArgs): PropValue;
setProp(name: PropName, value: PropValue, args?: ABeamerArgs): void;
waitFor?(waitFor: WaitFor, onDone: DoneFunc, args?: ABeamerArgs): void;
/**
* Called after the frame is rendered, and before moves to the next frame.
* This method is called even if no property changed.
* It's an optional method, but future version might require its implementation.
*/
frameRendered?(args?: ABeamerArgs): void;
}
export type PElement = HTMLElement | VirtualElement;
// ------------------------------------------------------------------------
// VirtualAnimator
// ------------------------------------------------------------------------
/**
* Used by plugin creators to allow their content to be animated.
* A plugin can animate canvas, WebGl, svg or reduce the complexity of a CSS animation.
* The story uses `uid` to manage animators.
*/
export interface VirtualAnimator extends VirtualElement {
selector: string;
}
/**
* It simplifies the usage of [](VirtualAnimator) by plugins.
* In many cases plugins just need to receive the changing property,
* in order to modify its state.
* Override `animateProp` to receive the changing property.
* animateProp isn't called if the property is `uid`.
*/
export class SimpleVirtualAnimator implements VirtualAnimator {
props: AnyParams = {};
selector: string;
propsChanged: boolean = false;
onAnimateProp: (name: PropName, value: PropValue) => void;
onAnimateProps: (args?: ABeamerArgs) => void;
/**
* Called after property value changed.
* Use this method instead animateProps, if the rendering should be right after
* each property is updated, otherwise use animateProps.
*/
animateProp(name: PropName, value: PropValue): void {
if (this.onAnimateProp) {
this.onAnimateProp(name, value);
}
}
/**
* Called after actions from the frame are rendered, and if at least one property changed.
* Use this method instead animateProp, if the animation has multiple virtual properties and
* each animation can be done after all are updated.
*/
animateProps(args?: ABeamerArgs): void {
if (this.onAnimateProps) {
this.onAnimateProps(args);
}
}
getProp(name: PropName): PropValue {
return this.props[name];
}
setProp(name: PropName, value: PropValue): void {
this.props[name] = value;
if (name !== 'uid') {
this.propsChanged = true;
this.animateProp(name, value);
}
}
frameRendered(args?: ABeamerArgs) {
if (this.propsChanged) {
this.animateProps(args);
this.propsChanged = false;
}
}
}
// ------------------------------------------------------------------------
// Scene Selectors
// ------------------------------------------------------------------------
/**
* Base interface for virtual scenes such as WebGL, Canvas.
*/
export interface VirtualScene {
/**
* Must support `id` and `visible` attributes.
*/
getProp(name: PropName, args?: ABeamerArgs): string;
/**
* Must support `visible` and `uid` attributes.
*/
setProp(name: PropName, value: string, args?: ABeamerArgs): void;
/**
* Must call iterator for each element represented on the selector.
*
* @param selector CSS style selectors
*/
query(selector: string,
iterator: (element: PElement, index: uint) => void);
}
/**
* Scene Selector defined by the user.
*/
export type SceneSelector = string | JQuery | VirtualScene;
// ------------------------------------------------------------------------
// Element Selector
// ------------------------------------------------------------------------
/**
* Defines css selectors, JQuery, meta-selectors, and Virtual selectors.
* Virtual selectors start with `%`.
*/
export type ElSelector = JQuery
// (DOM or virtual) selectors
| string
// list of (DOM or virtual) elements ids
| string[]
// list of html elements
| HTMLElement[]
// list of virtual elements
| VirtualElement[]
// An pEls containing elements
| pEls
;
/**
* User defined function that return an Element Selector.
* Doesn't supports remote rendering.
*/
export type ElSelectorFunc = (args?: ABeamerArgs) => ElSelector;
/**
* Element Selector defined by the user.
*/
export type ElSelectorHandler = ElSelector | ElSelectorFunc;
// ------------------------------------------------------------------------
// Browser
// ------------------------------------------------------------------------
export interface Browser {
isMsIE: boolean;
vendorPrefix: string;
prefixedProps: string[];
}
export const browser: Browser = {
isMsIE: false,
vendorPrefix: '',
prefixedProps: [],
};
// #export-section-end: release
// -------------------------------
// ------------------------------------------------------------------------
// Implementation
// ------------------------------------------------------------------------
/* ---- Animation Property Type ---- */
export const DPT_ID = 0;
export const DPT_VISIBLE = 1;
export const DPT_ATTR = 2;
export const DPT_ATTR_FUNC = 3;
export const DPT_STYLE = 4;
export const DPT_PIXEL = 5;
export const DPT_DUAL_PIXELS = 6;
export const DPT_CLASS = 7;
export const DPT_MEDIA_TIME = 8;
export const DPT_SRC = 9;
export const DPT_ELEMENT = 10;
/**
* Maps user property names to DOM property names.
*
* In general, property names represent style attributes.
* This map is used to handle the special cases.
*/
const domPropMapper: { [name: string]: [uint, any] } = {
'element': [DPT_ELEMENT, ''],
'uid': [DPT_ATTR_FUNC, 'data-abeamer'],
'id': [DPT_ATTR, 'id'],
'html': [DPT_ATTR, 'innerHTML'],
'text': [DPT_ATTR, 'textContent'],
'innerHTML': [DPT_ATTR, 'innerHTML'],
'outerHML': [DPT_ATTR, 'outerHML'],
'textContent': [DPT_ATTR, 'textContent'],
'currentTime': [DPT_MEDIA_TIME, 'currentTime'],
'src': [DPT_SRC, 'src'],
'class': [DPT_CLASS, 'className'],
'visible': [DPT_VISIBLE, ''],
'left': [DPT_PIXEL, 'left'],
'right': [DPT_PIXEL, 'right'],
'bottom': [DPT_PIXEL, 'bottom'],
'top': [DPT_PIXEL, 'top'],
'width': [DPT_PIXEL, 'width'],
'height': [DPT_PIXEL, 'height'],
'width-height': [DPT_DUAL_PIXELS, ['width', 'height']],
'left-top': [DPT_DUAL_PIXELS, ['left', 'top']],
'right-top': [DPT_DUAL_PIXELS, ['right', 'top']],
'left-bottom': [DPT_DUAL_PIXELS, ['left', 'bottom']],
'right-bottom': [DPT_DUAL_PIXELS, ['right', 'bottom']],
};
/**
* Used to map css Properties due the differences between the web browser
* used to build the animation and the web browser used to render the image.
*/
const cssPropNameMapper: { [name: string]: string; } = {};
/**
* Maps attribute names when server doesn't supports a certain attribute.
*
* e.g.
* Chrome has already the support for transform css attribute,
* but phantomJS uses Chromium which only supports via webKit prefix.
*
* @see server-features
*/
export function _addServerDOMPropMaps(map: { [name: string]: string }): void {
Object.keys(map).forEach(name => { cssPropNameMapper[name] = map[name]; });
}
// ------------------------------------------------------------------------
// _AbstractAdapter
// ------------------------------------------------------------------------
/**
* Base class for all adapters: Element, Scene, Story,
* and both DOM and virtual.
*/
export abstract class _AbstractAdapter implements AbstractAdapter {
isVirtual: boolean;
abstract getProp(name: PropName, args?: ABeamerArgs): PropValue;
abstract setProp(name: PropName, value: PropValue, args?: ABeamerArgs): void;
waitFor?(waitItem: WaitFor, onDone: DoneFunc, args?: ABeamerArgs): void { }
frameRendered?(args?: ABeamerArgs): void { }
}
// ------------------------------------------------------------------------
// _ElementAdapter
// ------------------------------------------------------------------------
/**
* Base class for Element adapters both DOM and virtual.
*/
export abstract class _ElementAdapter extends _AbstractAdapter implements ElementAdapter {
constructor(element: PElement) { super(); }
getId(args?: ABeamerArgs): string { return this.getProp('id', args) as string; }
_clearComputerData(): void { }
}
// ------------------------------------------------------------------------
// _DOMAdapter
// ------------------------------------------------------------------------
interface _DOMAdapter {
htmlElement: HTMLElement;
compStyle: CSSStyleDeclaration;
getComputedStyle(): any;
}
function _setDOMProp(adapter: _DOMAdapter,
propName: PropName, value: PropValue, args?: ABeamerArgs): void {
const [propType, domPropName] = domPropMapper[propName]
|| [DPT_STYLE, propName];
const element = adapter.htmlElement;
switch (propType) {
case DPT_CLASS:
if (value && (value as string).search(/(?:^| )[\-+]/) !== -1) {
(value as string).split(/\s+/).forEach(aClass => {
const first = aClass[0];
if (first === '-') {
element.classList.remove(aClass.substr(1));
} else if (first === '+') {
element.classList.add(aClass.substr(1));
} else {
element.classList.add(aClass);
}
});
break;
}
// flows to `DPT_ID`.
case DPT_ID:
// flows to `DPT_ATTR`.
case DPT_ATTR: element[domPropName] = value; break;
case DPT_MEDIA_TIME:
_waitForMediaSync(element as HTMLMediaElement, args, value as number);
break;
case DPT_VISIBLE:
const defDisplay = element['data-abeamer-display'];
const curDisplay = element.style.display || adapter.getComputedStyle()['display'];
if (value !== false && value !== 'false' && value !== 0) {
if (curDisplay === 'none') {
element.style.display =
defDisplay || (element.tagName === 'SPAN'
? 'inline' : 'block');
}
} else {
if (!defDisplay) {
element['data-abeamer-display'] = curDisplay;
}
element.style.display = 'none';
}
break;
case DPT_SRC:
// flows to DPT_ATTR_FUNC
case DPT_ATTR_FUNC:
element.setAttribute(domPropName, value as string);
if (propType === DPT_SRC && element.tagName === 'IMG') {
_waitForImageLoad(element as HTMLImageElement, args);
}
break;
case DPT_STYLE:
const cssPropName = cssPropNameMapper[domPropName] || domPropName;
element.style[cssPropName] = value as string;
break;
case DPT_PIXEL:
element.style[domPropName] = typeof value === 'number'
? value + 'px' : value as string;
break;
case DPT_DUAL_PIXELS:
const values = (value as string).split(',');
(domPropName as string[]).forEach((propNameXY, index) => {
element.style[propNameXY] = values[index] + 'px';
});
break;
}
}
function _NullToUnd(v: any): any {
return v === null ? undefined : v;
}
function _getDOMProp(adapter: _DOMAdapter,
propName: PropName, args?: ABeamerArgs): PropValue {
const [propType, domPropName] = domPropMapper[propName]
|| [DPT_STYLE, propName];
switch (propType) {
case DPT_ELEMENT:
return adapter.htmlElement as any;
case DPT_MEDIA_TIME:
// flows to `DPT_CLASS`.
case DPT_CLASS:
// flows to `DPT_ID`.
case DPT_ID:
// flows to `DPT_ATTR`.
case DPT_ATTR: return _NullToUnd(adapter.htmlElement[domPropName]);
case DPT_VISIBLE:
const value = adapter.htmlElement.style.display || adapter.getComputedStyle()['display'];
return (value === '' || value !== 'none') ? true : false;
case DPT_SRC:
// flows to DPT_ATTR_FUNC
case DPT_ATTR_FUNC: return _NullToUnd(adapter.htmlElement.getAttribute(domPropName));
case DPT_PIXEL:
case DPT_STYLE:
const cssPropName = cssPropNameMapper[domPropName] || domPropName;
return adapter.htmlElement.style[cssPropName]
|| adapter.getComputedStyle()[cssPropName];
}
}
// ------------------------------------------------------------------------
// _DOMElementAdapter
// ------------------------------------------------------------------------
/**
* DOM Element adapter.
* Gets and sets attributes from HTMLElements.
* Maps the ABeamer animation property names into DOM attributes.
*/
export class _DOMElementAdapter extends _ElementAdapter implements _DOMAdapter {
htmlElement: HTMLElement;
compStyle: CSSStyleDeclaration;
constructor(element: PElement) {
super(element);
this.isVirtual = false;
this.htmlElement = element as HTMLElement;
}
/**
* Requests the DOM engine the calculated information for CSS property.
*/
getComputedStyle(): any {
let compStyle = this['__compStyle'];
if (!compStyle) {
compStyle = window.getComputedStyle(this.htmlElement);
this['__compStyle'] = compStyle;
}
return compStyle;
}
getProp(propName: PropName, args?: ABeamerArgs): PropValue {
return _getDOMProp(this, propName, args);
}
setProp(propName: PropName, value: PropValue, args?: ABeamerArgs): void {
_setDOMProp(this, propName, value, args);
}
_clearComputerData(): void {
// @TODO: Discover to clear data when is no longer used
// this.compStyle = undefined;
}
waitFor?(waitFor: WaitFor, onDone: DoneFunc, args?: ABeamerArgs): void {
switch (waitFor.what) {
case WaitForWhat.ImageLoad:
_waitForImageLoad(this.htmlElement as HTMLImageElement, args);
break;
case WaitForWhat.MediaSync:
_waitForMediaSync(this.htmlElement as HTMLMediaElement, args,
waitFor.value as number);
break;
}
}
}
// ------------------------------------------------------------------------
// _SVGElementAdapter
// ------------------------------------------------------------------------
/** This feature is not implemented yet..._Coming soon_ . */
class _SVGElementAdapter extends _ElementAdapter {
}
// ------------------------------------------------------------------------
// _VirtualElementAdapter
// ------------------------------------------------------------------------
/**
* Virtual Element adapter.
* Allows ABeamer to decouple from the details of any virtual element.
*/
class _VirtualElementAdapter extends _ElementAdapter {
vElement: VirtualElement;
constructor(element: PElement) {
super(element);
this.isVirtual = true;
this.vElement = element as VirtualElement;
}
getProp(propName: PropName, args?: ABeamerArgs): PropValue {
return this.vElement.getProp(propName, args);
}
setProp(propName: PropName, value: PropValue, args?: ABeamerArgs): void {
this.vElement.setProp(propName, value, args);
}
waitFor?(waitItem: WaitFor, onDone: DoneFunc, args?: ABeamerArgs): void {
this.vElement.waitFor(waitItem, onDone, args);
}
frameRendered?(args: ABeamerArgs) {
if (this.vElement.frameRendered) { this.vElement.frameRendered(args); }
}
}
// ------------------------------------------------------------------------
// Global Utility Functions
// ------------------------------------------------------------------------
/**
* Returns true if the element is Virtual.
*/
export const _isElementVirtual = (element: PElement): boolean =>
(element as VirtualElement).getProp !== undefined;
/**
* Returns true if the id is Virtual.
*/
export const _isIdVirtual = (id: string): boolean => id[0] === '%';
/**
* Safely retrieves the Virtual Element from `story.onGetVirtualElement`.
*/
export function _getVirtualElement(story: _StoryImpl,
fullId: string): PElement {
const selector = fullId.substr(1);
// Although there is _virtualAnimatorMap and provides faster access,
// until the access to virtualAnimators has been disabled, it can't be used.
const animator = story._virtualAnimators.find(vAnimator =>
vAnimator.selector === selector,
);
if (animator) {
return animator;
}
if (!story.onGetVirtualElement) {
throwErr(`Story must have onGetVirtualElement to support virtual elements mapping`);
}
return story.onGetVirtualElement(selector, story._args);
}
// ------------------------------------------------------------------------
// SceneAdapter
// ------------------------------------------------------------------------
/**
* Returns true if the Scene is Virtual.
*/
export const _isVirtualScene = (sceneSelector: SceneSelector) =>
typeof sceneSelector === 'object' &&
(sceneSelector as VirtualScene).query !== undefined;
/**
* Virtual Scene adapter.
* Allows ABeamer to decouple from the details of any virtual scene.
*/
export abstract class _SceneAdapter extends _AbstractAdapter implements SceneAdapter {
constructor(sceneSelector: SceneSelector) { super(); }
abstract query(selector: string,
iterator: (element: PElement, index: uint) => void);
}
// ------------------------------------------------------------------------
// _DOMSceneAdapter
// ------------------------------------------------------------------------
/**
* DOM Scene and Story adapter.
* Both of them are similar. No need for 2 separated classes.
* Gets and sets properties from HTMLElements.
* Maps the animation property names into DOM attributes.
*/
export class _DOMSceneAdapter extends _SceneAdapter implements _DOMAdapter {
// JQuery is used to query
$scene: JQuery;
// HTMLElement is used to get/set attributes
htmlElement: HTMLElement;
compStyle: CSSStyleDeclaration;
constructor(sceneSelector: SceneSelector) {
super(sceneSelector);
this.$scene = typeof sceneSelector === 'string' ? $(sceneSelector)
: sceneSelector as JQuery;
throwIfI8n(!this.$scene.length, Msgs.NoEmptySelector, { p: sceneSelector as string });
this.htmlElement = this.$scene.get(0);
this.isVirtual = false;
}
/**
* Requests the DOM engine the calculated information for CSS property.
*/
getComputedStyle(): any {
let compStyle = this['__compStyle'];
if (!compStyle) {
compStyle = window.getComputedStyle(this.htmlElement);
this['__compStyle'] = compStyle;
}
return compStyle;
}
getProp(propName: PropName, args?: ABeamerArgs): PropValue {
switch (propName) {
// story attributes
case 'fps':
return parseInt(document.body.getAttribute('data-fps'));
case 'frame-width':
return document.body.clientWidth;
case 'frame-height':
return document.body.clientHeight;
// scene attributes
case 'id': return this.htmlElement.id;
// case 'html': return this.htmlElement.innerHTML;
// case 'left':
// case 'top':
// case 'width':
// case 'height':
// let value = this.htmlElement.style[propName];
// if (!value) {
// if (!this.compStyle) {
// this.compStyle = window.getComputedStyle(this.htmlElement);
// }
// value = this.compStyle[propName];
// }
// return value;
default:
return _getDOMProp(this, propName);
}
}
setProp(propName: PropName, value: PropValue, args?: ABeamerArgs): void {
const htmlElement = this.htmlElement;
function setDim(dimName: string, clientDim: uint): void {
const pxValue = value + 'px';
document.body.style[dimName] = pxValue;
if (clientDim !== value) {
htmlElement.style[dimName] = pxValue;
}
}
switch (propName) {
// story attributes
case 'clip-path':
htmlElement.style.clipPath = value as string;
break;
case 'frame-width':
setDim('width', htmlElement.clientWidth);
break;
case 'frame-height':
setDim('height', htmlElement.clientHeight);
break;
// // scene attributes
// case 'visible':
// if (value === 'true' || value === true) {
// this.$scene.show();
// } else {
// this.$scene.hide();
// }
// break;
// case 'opacity':
// this.htmlElement.style.opacity = value.toString();
// break;
// case 'html':
// this.htmlElement.innerHTML = value as string;
// break;
// case 'left':
// case 'top':
// case 'width':
// case 'height':
// this.htmlElement.style[propName] = typeof value === 'number'
// ? value + 'px' : value as string;
// break;
default:
_setDOMProp(this, propName, value);
}
}
query(selector: string,
iterator: (element: PElement, index: uint) => void): void {
this.$scene.find(selector as string).each((index, element) => {
iterator(element, index);
});
}
}
// ------------------------------------------------------------------------
// _VirtualSceneAdapter
// ------------------------------------------------------------------------
export class _VirtualSceneAdapter extends _SceneAdapter {
vScene: VirtualScene;
constructor(sceneSelector: SceneSelector) {
super(sceneSelector);
this.vScene = sceneSelector as VirtualScene;
this.isVirtual = true;
}
getProp(propName: PropName, args?: ABeamerArgs): string {
return this.vScene.getProp(propName, args);
}
setProp(propName: PropName, value: string, args?: ABeamerArgs): void {
this.vScene.setProp(propName, value, args);
}
query(selector: string,
iterator: (element: PElement, index: uint) => void): void {
this.vScene.query(selector, iterator);
}
}
// ------------------------------------------------------------------------
// Factory
// ------------------------------------------------------------------------
/**
* Creates and Adds an Element Adapter defined by a Element selector
* to a list of ElementAdapters.
*/
function _addElementAdapter(story: _StoryImpl,
elementOrStr: PElement | string,
elementAdapters: _ElementAdapter[],
isVirtual?: boolean,
isString?: boolean): void {
let element: PElement;
if ((isString !== false) && (isString || typeof elementOrStr === 'string')) {
if ((isVirtual === false) ||
(isVirtual === undefined && !_isIdVirtual(elementOrStr as string))) {
throwErr(`selector ${elementOrStr} must be virtual`);
}
element = _getVirtualElement(story, elementOrStr as string) as PElement;
isVirtual = true;
} else {
element = elementOrStr as PElement;
}
isVirtual = isVirtual || _isElementVirtual(element);
elementAdapters.push(isVirtual ? new _VirtualElementAdapter(element) :
new _DOMElementAdapter(element));
}
/**
* Parses the user defined Element Selector, returning an Element Adapter
*/
export function _parseInElSelector(
story: _StoryImpl,
elementAdapters: _ElementAdapter[],
sceneAdpt: _SceneAdapter,
elSelector: ElSelectorHandler): _ElementAdapter[] {
// test of _pEls
if (elSelector instanceof _pEls) {
return (elSelector as _pEls)._elementAdapters as _ElementAdapter[];
}
if (typeof elSelector === 'function') {
elSelector = (elSelector as ElSelectorFunc)(story._args);
}
if (typeof elSelector === 'string') {
if (_isIdVirtual(elSelector)) {
_addElementAdapter(story, elSelector, elementAdapters, true, true);
} else {
sceneAdpt.query(elSelector as string, (element, index) => {
_addElementAdapter(story, element, elementAdapters, false, false);
});
}
} else {
if (typeof elSelector === 'object' && ((elSelector as any).length !== undefined)) {
if (!(elSelector as any).length) { return; }
((elSelector as (PElement | string)[])).forEach(element => {
_addElementAdapter(story, element, elementAdapters);
});
} else {
throwI8n(Msgs.UnknownType, { p: elSelector.toString() });
}
}
return elementAdapters;
}
// ------------------------------------------------------------------------
// Wait Events
// ------------------------------------------------------------------------
function _waitForImageLoad(elImg: HTMLImageElement,
args: ABeamerArgs): void {
if (!elImg.complete) {
args.waitMan.addWaitFunc((_args, _params, onDone) => {
if (!elImg.complete) {
elImg.addEventListener('load', () => {
onDone();
}, { once: true });
} else {
onDone();
}
}, {});
}
}
function _waitForMediaSync(elMedia: HTMLMediaElement, args: ABeamerArgs,
pos: number): void {
args.waitMan.addWaitFunc((_args, _params, onDone) => {
// @TODO: Find a way to sync video.
// this code doesn't work on chrome.
if (pos !== undefined) {
if (elMedia.readyState < 3) {
elMedia.addEventListener('loadeddata', () => {
_waitForMediaSync(elMedia, args, pos);
}, { once: true });
return;
}
elMedia.addEventListener('seeked', () => {
// #debug-start
if (_args.isVerbose) {
args.story.logFrmt('video-sync', [
['expected', pos],
['actual', elMedia.currentTime],
], LT_MSG);
}
// #debug-end
onDone();
}, { once: true });
elMedia.currentTime = pos;
} else {
onDone();
}
}, {});
}
export interface _WorkWaitForParams extends AnyParams {
waitFor: WaitFor;
elAdapter: _ElementAdapter;
}
export function _handleWaitFor(args: ABeamerArgs, params: _WorkWaitForParams,
onDone: DoneFunc) {
params.elAdapter.waitFor(params.waitFor, onDone, args);
}
// ------------------------------------------------------------------------
// Browser
// ------------------------------------------------------------------------
/**
* List of CSS properties by vendor prefix that aren't caught by
* `window.getComputedStyle`
*/
const FORCED_PROP_REMAPS = {
'-webkit-': ['background-clip'],
};
const vendorRegEx = /^(-webkit-|-moz-|-ie-|-ms-)(.*)$/;
/**
* Maps an input CSS property into the current CSS property, adding a prefixed
* CSS property if necessary.
*/
export function _propNameToVendorProps(propName: string): string[] {
const subPropName = propName.replace(vendorRegEx, '$2');
const mapValue = domPropMapper[subPropName];
if (mapValue && mapValue[1] && mapValue[1] !== subPropName) {
return [subPropName, mapValue[1]];
}
return [subPropName];
}
/**
* Adds a vendor prefixed CSS properties to the domPropMapper.
*/
function _addPropToDomPropMapper(subPropName: string, propName: string,
canOverwrite: boolean): void {
const mapValue = domPropMapper[subPropName];
if (!canOverwrite && mapValue !== undefined && mapValue[1][0] === '-') {
return;
}
const propType = mapValue !== undefined ? mapValue[0] : DPT_STYLE;
domPropMapper[propName] = [propType, propName];
domPropMapper[subPropName] = [propType, propName];
}
/**
* Discovers the vendor prefix and vendor prefixed CSS properties
* by using `window.getComputedStyle`.
*/
export function _initBrowser(_args: ABeamerArgs): void {
if (browser.vendorPrefix) { return; }
const isMsIE = navigator.userAgent.search(/Trident/) !== -1;
browser.isMsIE = isMsIE;
const cssMap = window.getComputedStyle(document.body);
const cssMapLen = (cssMap || []).length;
let foundVendorPrefix = false;
for (let i = 0; i < cssMapLen; i++) {
const propName = cssMap[i];
const parts = propName.match(vendorRegEx);
if (parts) {
if (!foundVendorPrefix) {
const vendorPrefix = parts[1];
browser.vendorPrefix = vendorPrefix;
foundVendorPrefix = true;
const forcedProps = FORCED_PROP_REMAPS[vendorPrefix] as string[];
if (forcedProps) {
forcedProps.forEach(forcedProp => {
_addPropToDomPropMapper(forcedProp, vendorPrefix + forcedProp, !isMsIE);
});
}
}
const subPropName = parts[2];
browser.prefixedProps.push(subPropName);
_addPropToDomPropMapper(subPropName, propName, !isMsIE);
}
}
}
} | the_stack |
import * as protos from '../protos/protos';
import * as assert from 'assert';
import * as sinon from 'sinon';
import {SinonStub} from 'sinon';
import {describe, it, beforeEach, afterEach} from 'mocha';
import * as instancesModule from '../src';
import {PassThrough} from 'stream';
import {GoogleAuth, protobuf} from 'google-gax';
function generateSampleMessage<T extends object>(instance: T) {
const filledObject = (
instance.constructor as typeof protobuf.Message
).toObject(instance as protobuf.Message<T>, {defaults: true});
return (instance.constructor as typeof protobuf.Message).fromObject(
filledObject
) as T;
}
function stubSimpleCall<ResponseType>(response?: ResponseType, error?: Error) {
return error
? sinon.stub().rejects(error)
: sinon.stub().resolves([response]);
}
function stubSimpleCallWithCallback<ResponseType>(
response?: ResponseType,
error?: Error
) {
return error
? sinon.stub().callsArgWith(2, error)
: sinon.stub().callsArgWith(2, null, response);
}
function stubPageStreamingCall<ResponseType>(
responses?: ResponseType[],
error?: Error
) {
const pagingStub = sinon.stub();
if (responses) {
for (let i = 0; i < responses.length; ++i) {
pagingStub.onCall(i).callsArgWith(2, null, responses[i]);
}
}
const transformStub = error
? sinon.stub().callsArgWith(2, error)
: pagingStub;
const mockStream = new PassThrough({
objectMode: true,
transform: transformStub,
});
// trigger as many responses as needed
if (responses) {
for (let i = 0; i < responses.length; ++i) {
setImmediate(() => {
mockStream.write({});
});
}
setImmediate(() => {
mockStream.end();
});
} else {
setImmediate(() => {
mockStream.write({});
});
setImmediate(() => {
mockStream.end();
});
}
return sinon.stub().returns(mockStream);
}
function stubAsyncIterationCall<ResponseType>(
responses?: ResponseType[],
error?: Error
) {
let counter = 0;
const asyncIterable = {
[Symbol.asyncIterator]() {
return {
async next() {
if (error) {
return Promise.reject(error);
}
if (counter >= responses!.length) {
return Promise.resolve({done: true, value: undefined});
}
return Promise.resolve({done: false, value: responses![counter++]});
},
};
},
};
return sinon.stub().returns(asyncIterable);
}
describe('v1.InstancesClient', () => {
let googleAuth: GoogleAuth;
beforeEach(() => {
googleAuth = {
getClient: sinon.stub().resolves({
getRequestHeaders: sinon
.stub()
.resolves({Authorization: 'Bearer SOME_TOKEN'}),
}),
} as unknown as GoogleAuth;
});
afterEach(() => {
sinon.restore();
});
it('has servicePath', () => {
const servicePath = instancesModule.v1.InstancesClient.servicePath;
assert(servicePath);
});
it('has apiEndpoint', () => {
const apiEndpoint = instancesModule.v1.InstancesClient.apiEndpoint;
assert(apiEndpoint);
});
it('has port', () => {
const port = instancesModule.v1.InstancesClient.port;
assert(port);
assert(typeof port === 'number');
});
it('should create a client with no option', () => {
const client = new instancesModule.v1.InstancesClient();
assert(client);
});
it('should create a client with gRPC fallback', () => {
const client = new instancesModule.v1.InstancesClient({
fallback: true,
});
assert(client);
});
it('has initialize method and supports deferred initialization', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
assert.strictEqual(client.instancesStub, undefined);
await client.initialize();
assert(client.instancesStub);
});
it('has close method', () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.close();
});
it('has getProjectId method', async () => {
const fakeProjectId = 'fake-project-id';
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.auth.getProjectId = sinon.stub().resolves(fakeProjectId);
const result = await client.getProjectId();
assert.strictEqual(result, fakeProjectId);
assert((client.auth.getProjectId as SinonStub).calledWithExactly());
});
it('has getProjectId method with callback', async () => {
const fakeProjectId = 'fake-project-id';
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.auth.getProjectId = sinon
.stub()
.callsArgWith(0, null, fakeProjectId);
const promise = new Promise((resolve, reject) => {
client.getProjectId((err?: Error | null, projectId?: string | null) => {
if (err) {
reject(err);
} else {
resolve(projectId);
}
});
});
const result = await promise;
assert.strictEqual(result, fakeProjectId);
});
describe('addAccessConfig', () => {
it('invokes addAccessConfig without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.AddAccessConfigInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.addAccessConfig = stubSimpleCall(expectedResponse);
const [response] = await client.addAccessConfig(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.addAccessConfig as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes addAccessConfig without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.AddAccessConfigInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.addAccessConfig =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.addAccessConfig(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.addAccessConfig as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes addAccessConfig with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.AddAccessConfigInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.addAccessConfig = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.addAccessConfig(request), expectedError);
assert(
(client.innerApiCalls.addAccessConfig as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('addResourcePolicies', () => {
it('invokes addResourcePolicies without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.AddResourcePoliciesInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.addResourcePolicies =
stubSimpleCall(expectedResponse);
const [response] = await client.addResourcePolicies(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.addResourcePolicies as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes addResourcePolicies without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.AddResourcePoliciesInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.addResourcePolicies =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.addResourcePolicies(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.addResourcePolicies as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes addResourcePolicies with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.AddResourcePoliciesInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.addResourcePolicies = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.addResourcePolicies(request), expectedError);
assert(
(client.innerApiCalls.addResourcePolicies as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('attachDisk', () => {
it('invokes attachDisk without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.AttachDiskInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.attachDisk = stubSimpleCall(expectedResponse);
const [response] = await client.attachDisk(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.attachDisk as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes attachDisk without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.AttachDiskInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.attachDisk =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.attachDisk(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.attachDisk as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes attachDisk with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.AttachDiskInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.attachDisk = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.attachDisk(request), expectedError);
assert(
(client.innerApiCalls.attachDisk as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('bulkInsert', () => {
it('invokes bulkInsert without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.BulkInsertInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.bulkInsert = stubSimpleCall(expectedResponse);
const [response] = await client.bulkInsert(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.bulkInsert as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes bulkInsert without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.BulkInsertInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.bulkInsert =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.bulkInsert(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.bulkInsert as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes bulkInsert with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.BulkInsertInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.bulkInsert = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.bulkInsert(request), expectedError);
assert(
(client.innerApiCalls.bulkInsert as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('delete', () => {
it('invokes delete without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.DeleteInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.delete = stubSimpleCall(expectedResponse);
const [response] = await client.delete(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.delete as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes delete without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.DeleteInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.delete =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.delete(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.delete as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes delete with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.DeleteInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.delete = stubSimpleCall(undefined, expectedError);
await assert.rejects(client.delete(request), expectedError);
assert(
(client.innerApiCalls.delete as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('deleteAccessConfig', () => {
it('invokes deleteAccessConfig without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.DeleteAccessConfigInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.deleteAccessConfig =
stubSimpleCall(expectedResponse);
const [response] = await client.deleteAccessConfig(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.deleteAccessConfig as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes deleteAccessConfig without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.DeleteAccessConfigInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.deleteAccessConfig =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.deleteAccessConfig(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.deleteAccessConfig as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes deleteAccessConfig with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.DeleteAccessConfigInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.deleteAccessConfig = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.deleteAccessConfig(request), expectedError);
assert(
(client.innerApiCalls.deleteAccessConfig as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('detachDisk', () => {
it('invokes detachDisk without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.DetachDiskInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.detachDisk = stubSimpleCall(expectedResponse);
const [response] = await client.detachDisk(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.detachDisk as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes detachDisk without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.DetachDiskInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.detachDisk =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.detachDisk(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.detachDisk as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes detachDisk with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.DetachDiskInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.detachDisk = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.detachDisk(request), expectedError);
assert(
(client.innerApiCalls.detachDisk as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('get', () => {
it('invokes get without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.GetInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Instance()
);
client.innerApiCalls.get = stubSimpleCall(expectedResponse);
const [response] = await client.get(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.get as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes get without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.GetInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Instance()
);
client.innerApiCalls.get = stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.get(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IInstance | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.get as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes get with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.GetInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.get = stubSimpleCall(undefined, expectedError);
await assert.rejects(client.get(request), expectedError);
assert(
(client.innerApiCalls.get as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('getEffectiveFirewalls', () => {
it('invokes getEffectiveFirewalls without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.GetEffectiveFirewallsInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.InstancesGetEffectiveFirewallsResponse()
);
client.innerApiCalls.getEffectiveFirewalls =
stubSimpleCall(expectedResponse);
const [response] = await client.getEffectiveFirewalls(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getEffectiveFirewalls as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes getEffectiveFirewalls without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.GetEffectiveFirewallsInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.InstancesGetEffectiveFirewallsResponse()
);
client.innerApiCalls.getEffectiveFirewalls =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.getEffectiveFirewalls(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IInstancesGetEffectiveFirewallsResponse | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getEffectiveFirewalls as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes getEffectiveFirewalls with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.GetEffectiveFirewallsInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.getEffectiveFirewalls = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(
client.getEffectiveFirewalls(request),
expectedError
);
assert(
(client.innerApiCalls.getEffectiveFirewalls as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('getGuestAttributes', () => {
it('invokes getGuestAttributes without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.GetGuestAttributesInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.GuestAttributes()
);
client.innerApiCalls.getGuestAttributes =
stubSimpleCall(expectedResponse);
const [response] = await client.getGuestAttributes(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getGuestAttributes as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes getGuestAttributes without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.GetGuestAttributesInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.GuestAttributes()
);
client.innerApiCalls.getGuestAttributes =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.getGuestAttributes(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IGuestAttributes | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getGuestAttributes as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes getGuestAttributes with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.GetGuestAttributesInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.getGuestAttributes = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.getGuestAttributes(request), expectedError);
assert(
(client.innerApiCalls.getGuestAttributes as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('getIamPolicy', () => {
it('invokes getIamPolicy without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.GetIamPolicyInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Policy()
);
client.innerApiCalls.getIamPolicy = stubSimpleCall(expectedResponse);
const [response] = await client.getIamPolicy(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getIamPolicy as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes getIamPolicy without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.GetIamPolicyInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Policy()
);
client.innerApiCalls.getIamPolicy =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.getIamPolicy(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IPolicy | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getIamPolicy as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes getIamPolicy with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.GetIamPolicyInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.getIamPolicy = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.getIamPolicy(request), expectedError);
assert(
(client.innerApiCalls.getIamPolicy as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('getScreenshot', () => {
it('invokes getScreenshot without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.GetScreenshotInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Screenshot()
);
client.innerApiCalls.getScreenshot = stubSimpleCall(expectedResponse);
const [response] = await client.getScreenshot(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getScreenshot as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes getScreenshot without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.GetScreenshotInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Screenshot()
);
client.innerApiCalls.getScreenshot =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.getScreenshot(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IScreenshot | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getScreenshot as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes getScreenshot with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.GetScreenshotInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.getScreenshot = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.getScreenshot(request), expectedError);
assert(
(client.innerApiCalls.getScreenshot as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('getSerialPortOutput', () => {
it('invokes getSerialPortOutput without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.GetSerialPortOutputInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.SerialPortOutput()
);
client.innerApiCalls.getSerialPortOutput =
stubSimpleCall(expectedResponse);
const [response] = await client.getSerialPortOutput(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getSerialPortOutput as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes getSerialPortOutput without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.GetSerialPortOutputInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.SerialPortOutput()
);
client.innerApiCalls.getSerialPortOutput =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.getSerialPortOutput(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.ISerialPortOutput | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getSerialPortOutput as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes getSerialPortOutput with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.GetSerialPortOutputInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.getSerialPortOutput = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.getSerialPortOutput(request), expectedError);
assert(
(client.innerApiCalls.getSerialPortOutput as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('getShieldedInstanceIdentity', () => {
it('invokes getShieldedInstanceIdentity without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.GetShieldedInstanceIdentityInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.ShieldedInstanceIdentity()
);
client.innerApiCalls.getShieldedInstanceIdentity =
stubSimpleCall(expectedResponse);
const [response] = await client.getShieldedInstanceIdentity(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getShieldedInstanceIdentity as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes getShieldedInstanceIdentity without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.GetShieldedInstanceIdentityInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.ShieldedInstanceIdentity()
);
client.innerApiCalls.getShieldedInstanceIdentity =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.getShieldedInstanceIdentity(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IShieldedInstanceIdentity | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.getShieldedInstanceIdentity as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes getShieldedInstanceIdentity with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.GetShieldedInstanceIdentityInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.getShieldedInstanceIdentity = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(
client.getShieldedInstanceIdentity(request),
expectedError
);
assert(
(client.innerApiCalls.getShieldedInstanceIdentity as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('insert', () => {
it('invokes insert without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.InsertInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.insert = stubSimpleCall(expectedResponse);
const [response] = await client.insert(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.insert as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes insert without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.InsertInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.insert =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.insert(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.insert as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes insert with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.InsertInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.insert = stubSimpleCall(undefined, expectedError);
await assert.rejects(client.insert(request), expectedError);
assert(
(client.innerApiCalls.insert as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('removeResourcePolicies', () => {
it('invokes removeResourcePolicies without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.RemoveResourcePoliciesInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.removeResourcePolicies =
stubSimpleCall(expectedResponse);
const [response] = await client.removeResourcePolicies(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.removeResourcePolicies as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes removeResourcePolicies without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.RemoveResourcePoliciesInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.removeResourcePolicies =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.removeResourcePolicies(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.removeResourcePolicies as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes removeResourcePolicies with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.RemoveResourcePoliciesInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.removeResourcePolicies = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(
client.removeResourcePolicies(request),
expectedError
);
assert(
(client.innerApiCalls.removeResourcePolicies as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('reset', () => {
it('invokes reset without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.ResetInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.reset = stubSimpleCall(expectedResponse);
const [response] = await client.reset(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.reset as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes reset without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.ResetInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.reset = stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.reset(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.reset as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes reset with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.ResetInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.reset = stubSimpleCall(undefined, expectedError);
await assert.rejects(client.reset(request), expectedError);
assert(
(client.innerApiCalls.reset as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('sendDiagnosticInterrupt', () => {
it('invokes sendDiagnosticInterrupt without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SendDiagnosticInterruptInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.SendDiagnosticInterruptInstanceResponse()
);
client.innerApiCalls.sendDiagnosticInterrupt =
stubSimpleCall(expectedResponse);
const [response] = await client.sendDiagnosticInterrupt(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.sendDiagnosticInterrupt as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes sendDiagnosticInterrupt without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SendDiagnosticInterruptInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.SendDiagnosticInterruptInstanceResponse()
);
client.innerApiCalls.sendDiagnosticInterrupt =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.sendDiagnosticInterrupt(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.ISendDiagnosticInterruptInstanceResponse | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.sendDiagnosticInterrupt as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes sendDiagnosticInterrupt with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SendDiagnosticInterruptInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.sendDiagnosticInterrupt = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(
client.sendDiagnosticInterrupt(request),
expectedError
);
assert(
(client.innerApiCalls.sendDiagnosticInterrupt as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('setDeletionProtection', () => {
it('invokes setDeletionProtection without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetDeletionProtectionInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.setDeletionProtection =
stubSimpleCall(expectedResponse);
const [response] = await client.setDeletionProtection(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.setDeletionProtection as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes setDeletionProtection without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetDeletionProtectionInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.setDeletionProtection =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.setDeletionProtection(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.setDeletionProtection as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes setDeletionProtection with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetDeletionProtectionInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.setDeletionProtection = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(
client.setDeletionProtection(request),
expectedError
);
assert(
(client.innerApiCalls.setDeletionProtection as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('setDiskAutoDelete', () => {
it('invokes setDiskAutoDelete without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetDiskAutoDeleteInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.setDiskAutoDelete = stubSimpleCall(expectedResponse);
const [response] = await client.setDiskAutoDelete(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.setDiskAutoDelete as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes setDiskAutoDelete without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetDiskAutoDeleteInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.setDiskAutoDelete =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.setDiskAutoDelete(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.setDiskAutoDelete as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes setDiskAutoDelete with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetDiskAutoDeleteInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.setDiskAutoDelete = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.setDiskAutoDelete(request), expectedError);
assert(
(client.innerApiCalls.setDiskAutoDelete as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('setIamPolicy', () => {
it('invokes setIamPolicy without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetIamPolicyInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Policy()
);
client.innerApiCalls.setIamPolicy = stubSimpleCall(expectedResponse);
const [response] = await client.setIamPolicy(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.setIamPolicy as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes setIamPolicy without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetIamPolicyInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Policy()
);
client.innerApiCalls.setIamPolicy =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.setIamPolicy(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IPolicy | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.setIamPolicy as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes setIamPolicy with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetIamPolicyInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.setIamPolicy = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.setIamPolicy(request), expectedError);
assert(
(client.innerApiCalls.setIamPolicy as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('setLabels', () => {
it('invokes setLabels without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetLabelsInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.setLabels = stubSimpleCall(expectedResponse);
const [response] = await client.setLabels(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.setLabels as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes setLabels without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetLabelsInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.setLabels =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.setLabels(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.setLabels as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes setLabels with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetLabelsInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.setLabels = stubSimpleCall(undefined, expectedError);
await assert.rejects(client.setLabels(request), expectedError);
assert(
(client.innerApiCalls.setLabels as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('setMachineResources', () => {
it('invokes setMachineResources without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetMachineResourcesInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.setMachineResources =
stubSimpleCall(expectedResponse);
const [response] = await client.setMachineResources(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.setMachineResources as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes setMachineResources without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetMachineResourcesInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.setMachineResources =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.setMachineResources(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.setMachineResources as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes setMachineResources with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetMachineResourcesInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.setMachineResources = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.setMachineResources(request), expectedError);
assert(
(client.innerApiCalls.setMachineResources as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('setMachineType', () => {
it('invokes setMachineType without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetMachineTypeInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.setMachineType = stubSimpleCall(expectedResponse);
const [response] = await client.setMachineType(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.setMachineType as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes setMachineType without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetMachineTypeInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.setMachineType =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.setMachineType(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.setMachineType as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes setMachineType with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetMachineTypeInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.setMachineType = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.setMachineType(request), expectedError);
assert(
(client.innerApiCalls.setMachineType as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('setMetadata', () => {
it('invokes setMetadata without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetMetadataInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.setMetadata = stubSimpleCall(expectedResponse);
const [response] = await client.setMetadata(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.setMetadata as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes setMetadata without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetMetadataInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.setMetadata =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.setMetadata(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.setMetadata as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes setMetadata with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetMetadataInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.setMetadata = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.setMetadata(request), expectedError);
assert(
(client.innerApiCalls.setMetadata as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('setMinCpuPlatform', () => {
it('invokes setMinCpuPlatform without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetMinCpuPlatformInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.setMinCpuPlatform = stubSimpleCall(expectedResponse);
const [response] = await client.setMinCpuPlatform(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.setMinCpuPlatform as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes setMinCpuPlatform without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetMinCpuPlatformInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.setMinCpuPlatform =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.setMinCpuPlatform(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.setMinCpuPlatform as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes setMinCpuPlatform with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetMinCpuPlatformInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.setMinCpuPlatform = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.setMinCpuPlatform(request), expectedError);
assert(
(client.innerApiCalls.setMinCpuPlatform as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('setScheduling', () => {
it('invokes setScheduling without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetSchedulingInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.setScheduling = stubSimpleCall(expectedResponse);
const [response] = await client.setScheduling(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.setScheduling as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes setScheduling without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetSchedulingInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.setScheduling =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.setScheduling(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.setScheduling as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes setScheduling with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetSchedulingInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.setScheduling = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.setScheduling(request), expectedError);
assert(
(client.innerApiCalls.setScheduling as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('setServiceAccount', () => {
it('invokes setServiceAccount without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetServiceAccountInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.setServiceAccount = stubSimpleCall(expectedResponse);
const [response] = await client.setServiceAccount(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.setServiceAccount as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes setServiceAccount without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetServiceAccountInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.setServiceAccount =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.setServiceAccount(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.setServiceAccount as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes setServiceAccount with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetServiceAccountInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.setServiceAccount = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.setServiceAccount(request), expectedError);
assert(
(client.innerApiCalls.setServiceAccount as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('setShieldedInstanceIntegrityPolicy', () => {
it('invokes setShieldedInstanceIntegrityPolicy without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetShieldedInstanceIntegrityPolicyInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.setShieldedInstanceIntegrityPolicy =
stubSimpleCall(expectedResponse);
const [response] = await client.setShieldedInstanceIntegrityPolicy(
request
);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.setShieldedInstanceIntegrityPolicy as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes setShieldedInstanceIntegrityPolicy without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetShieldedInstanceIntegrityPolicyInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.setShieldedInstanceIntegrityPolicy =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.setShieldedInstanceIntegrityPolicy(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.setShieldedInstanceIntegrityPolicy as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes setShieldedInstanceIntegrityPolicy with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetShieldedInstanceIntegrityPolicyInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.setShieldedInstanceIntegrityPolicy = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(
client.setShieldedInstanceIntegrityPolicy(request),
expectedError
);
assert(
(client.innerApiCalls.setShieldedInstanceIntegrityPolicy as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('setTags', () => {
it('invokes setTags without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetTagsInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.setTags = stubSimpleCall(expectedResponse);
const [response] = await client.setTags(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.setTags as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes setTags without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetTagsInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.setTags =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.setTags(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.setTags as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes setTags with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SetTagsInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.setTags = stubSimpleCall(undefined, expectedError);
await assert.rejects(client.setTags(request), expectedError);
assert(
(client.innerApiCalls.setTags as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('simulateMaintenanceEvent', () => {
it('invokes simulateMaintenanceEvent without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SimulateMaintenanceEventInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.simulateMaintenanceEvent =
stubSimpleCall(expectedResponse);
const [response] = await client.simulateMaintenanceEvent(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.simulateMaintenanceEvent as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes simulateMaintenanceEvent without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SimulateMaintenanceEventInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.simulateMaintenanceEvent =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.simulateMaintenanceEvent(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.simulateMaintenanceEvent as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes simulateMaintenanceEvent with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.SimulateMaintenanceEventInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.simulateMaintenanceEvent = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(
client.simulateMaintenanceEvent(request),
expectedError
);
assert(
(client.innerApiCalls.simulateMaintenanceEvent as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('start', () => {
it('invokes start without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.StartInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.start = stubSimpleCall(expectedResponse);
const [response] = await client.start(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.start as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes start without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.StartInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.start = stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.start(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.start as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes start with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.StartInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.start = stubSimpleCall(undefined, expectedError);
await assert.rejects(client.start(request), expectedError);
assert(
(client.innerApiCalls.start as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('startWithEncryptionKey', () => {
it('invokes startWithEncryptionKey without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.StartWithEncryptionKeyInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.startWithEncryptionKey =
stubSimpleCall(expectedResponse);
const [response] = await client.startWithEncryptionKey(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.startWithEncryptionKey as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes startWithEncryptionKey without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.StartWithEncryptionKeyInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.startWithEncryptionKey =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.startWithEncryptionKey(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.startWithEncryptionKey as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes startWithEncryptionKey with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.StartWithEncryptionKeyInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.startWithEncryptionKey = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(
client.startWithEncryptionKey(request),
expectedError
);
assert(
(client.innerApiCalls.startWithEncryptionKey as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('stop', () => {
it('invokes stop without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.StopInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.stop = stubSimpleCall(expectedResponse);
const [response] = await client.stop(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.stop as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes stop without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.StopInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.stop = stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.stop(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.stop as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes stop with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.StopInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.stop = stubSimpleCall(undefined, expectedError);
await assert.rejects(client.stop(request), expectedError);
assert(
(client.innerApiCalls.stop as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('testIamPermissions', () => {
it('invokes testIamPermissions without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.TestIamPermissionsInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.TestPermissionsResponse()
);
client.innerApiCalls.testIamPermissions =
stubSimpleCall(expectedResponse);
const [response] = await client.testIamPermissions(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.testIamPermissions as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes testIamPermissions without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.TestIamPermissionsInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.TestPermissionsResponse()
);
client.innerApiCalls.testIamPermissions =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.testIamPermissions(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.ITestPermissionsResponse | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.testIamPermissions as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes testIamPermissions with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.TestIamPermissionsInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.testIamPermissions = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.testIamPermissions(request), expectedError);
assert(
(client.innerApiCalls.testIamPermissions as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('update', () => {
it('invokes update without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.UpdateInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.update = stubSimpleCall(expectedResponse);
const [response] = await client.update(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.update as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes update without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.UpdateInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.update =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.update(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.update as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes update with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.UpdateInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.update = stubSimpleCall(undefined, expectedError);
await assert.rejects(client.update(request), expectedError);
assert(
(client.innerApiCalls.update as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('updateAccessConfig', () => {
it('invokes updateAccessConfig without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.UpdateAccessConfigInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.updateAccessConfig =
stubSimpleCall(expectedResponse);
const [response] = await client.updateAccessConfig(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.updateAccessConfig as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes updateAccessConfig without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.UpdateAccessConfigInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.updateAccessConfig =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.updateAccessConfig(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.updateAccessConfig as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes updateAccessConfig with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.UpdateAccessConfigInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.updateAccessConfig = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.updateAccessConfig(request), expectedError);
assert(
(client.innerApiCalls.updateAccessConfig as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('updateDisplayDevice', () => {
it('invokes updateDisplayDevice without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.UpdateDisplayDeviceInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.updateDisplayDevice =
stubSimpleCall(expectedResponse);
const [response] = await client.updateDisplayDevice(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.updateDisplayDevice as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes updateDisplayDevice without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.UpdateDisplayDeviceInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.updateDisplayDevice =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.updateDisplayDevice(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.updateDisplayDevice as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes updateDisplayDevice with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.UpdateDisplayDeviceInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.updateDisplayDevice = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.updateDisplayDevice(request), expectedError);
assert(
(client.innerApiCalls.updateDisplayDevice as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('updateNetworkInterface', () => {
it('invokes updateNetworkInterface without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.UpdateNetworkInterfaceInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.updateNetworkInterface =
stubSimpleCall(expectedResponse);
const [response] = await client.updateNetworkInterface(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.updateNetworkInterface as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes updateNetworkInterface without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.UpdateNetworkInterfaceInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.updateNetworkInterface =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.updateNetworkInterface(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.updateNetworkInterface as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes updateNetworkInterface with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.UpdateNetworkInterfaceInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.updateNetworkInterface = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(
client.updateNetworkInterface(request),
expectedError
);
assert(
(client.innerApiCalls.updateNetworkInterface as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('updateShieldedInstanceConfig', () => {
it('invokes updateShieldedInstanceConfig without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.UpdateShieldedInstanceConfigInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.updateShieldedInstanceConfig =
stubSimpleCall(expectedResponse);
const [response] = await client.updateShieldedInstanceConfig(request);
assert.deepStrictEqual(response.latestResponse, expectedResponse);
assert(
(client.innerApiCalls.updateShieldedInstanceConfig as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes updateShieldedInstanceConfig without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.UpdateShieldedInstanceConfigInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = generateSampleMessage(
new protos.google.cloud.compute.v1.Operation()
);
client.innerApiCalls.updateShieldedInstanceConfig =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.updateShieldedInstanceConfig(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IOperation | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.updateShieldedInstanceConfig as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes updateShieldedInstanceConfig with error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.UpdateShieldedInstanceConfigInstanceRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.updateShieldedInstanceConfig = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(
client.updateShieldedInstanceConfig(request),
expectedError
);
assert(
(client.innerApiCalls.updateShieldedInstanceConfig as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
});
describe('aggregatedList', () => {
it('uses async iteration with aggregatedList without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.AggregatedListInstancesRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedResponse = [
[
'tuple_key_1',
generateSampleMessage(
new protos.google.cloud.compute.v1.InstancesScopedList()
),
],
[
'tuple_key_2',
generateSampleMessage(
new protos.google.cloud.compute.v1.InstancesScopedList()
),
],
[
'tuple_key_3',
generateSampleMessage(
new protos.google.cloud.compute.v1.InstancesScopedList()
),
],
];
client.descriptors.page.aggregatedList.asyncIterate =
stubAsyncIterationCall(expectedResponse);
const responses: Array<
[string, protos.google.cloud.compute.v1.IInstancesScopedList]
> = [];
const iterable = client.aggregatedListAsync(request);
for await (const resource of iterable) {
responses.push(resource!);
}
assert.deepStrictEqual(responses, expectedResponse);
assert.deepStrictEqual(
(
client.descriptors.page.aggregatedList.asyncIterate as SinonStub
).getCall(0).args[1],
request
);
assert.strictEqual(
(
client.descriptors.page.aggregatedList.asyncIterate as SinonStub
).getCall(0).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('uses async iteration with aggregatedList with error', async () => {
const client = new instancesModule.v1.InstancesClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.AggregatedListInstancesRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedError = new Error('expected');
client.descriptors.page.aggregatedList.asyncIterate =
stubAsyncIterationCall(undefined, expectedError);
const iterable = client.aggregatedListAsync(request);
await assert.rejects(async () => {
const responses: Array<
[string, protos.google.cloud.compute.v1.IInstancesScopedList]
> = [];
for await (const resource of iterable) {
responses.push(resource!);
}
});
assert.deepStrictEqual(
(
client.descriptors.page.aggregatedList.asyncIterate as SinonStub
).getCall(0).args[1],
request
);
assert.strictEqual(
(
client.descriptors.page.aggregatedList.asyncIterate as SinonStub
).getCall(0).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
});
describe('list', () => {
it('invokes list without error', async () => {
const client = new instancesModule.v1.InstancesClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.ListInstancesRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = [
generateSampleMessage(new protos.google.cloud.compute.v1.Instance()),
generateSampleMessage(new protos.google.cloud.compute.v1.Instance()),
generateSampleMessage(new protos.google.cloud.compute.v1.Instance()),
];
client.innerApiCalls.list = stubSimpleCall(expectedResponse);
const [response] = await client.list(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.list as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes list without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.ListInstancesRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = [
generateSampleMessage(new protos.google.cloud.compute.v1.Instance()),
generateSampleMessage(new protos.google.cloud.compute.v1.Instance()),
generateSampleMessage(new protos.google.cloud.compute.v1.Instance()),
];
client.innerApiCalls.list = stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.list(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IInstance[] | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.list as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes list with error', async () => {
const client = new instancesModule.v1.InstancesClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.ListInstancesRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.list = stubSimpleCall(undefined, expectedError);
await assert.rejects(client.list(request), expectedError);
assert(
(client.innerApiCalls.list as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes listStream without error', async () => {
const client = new instancesModule.v1.InstancesClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.ListInstancesRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedResponse = [
generateSampleMessage(new protos.google.cloud.compute.v1.Instance()),
generateSampleMessage(new protos.google.cloud.compute.v1.Instance()),
generateSampleMessage(new protos.google.cloud.compute.v1.Instance()),
];
client.descriptors.page.list.createStream =
stubPageStreamingCall(expectedResponse);
const stream = client.listStream(request);
const promise = new Promise((resolve, reject) => {
const responses: protos.google.cloud.compute.v1.Instance[] = [];
stream.on(
'data',
(response: protos.google.cloud.compute.v1.Instance) => {
responses.push(response);
}
);
stream.on('end', () => {
resolve(responses);
});
stream.on('error', (err: Error) => {
reject(err);
});
});
const responses = await promise;
assert.deepStrictEqual(responses, expectedResponse);
assert(
(client.descriptors.page.list.createStream as SinonStub)
.getCall(0)
.calledWith(client.innerApiCalls.list, request)
);
assert.strictEqual(
(client.descriptors.page.list.createStream as SinonStub).getCall(0)
.args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('invokes listStream with error', async () => {
const client = new instancesModule.v1.InstancesClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.ListInstancesRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedError = new Error('expected');
client.descriptors.page.list.createStream = stubPageStreamingCall(
undefined,
expectedError
);
const stream = client.listStream(request);
const promise = new Promise((resolve, reject) => {
const responses: protos.google.cloud.compute.v1.Instance[] = [];
stream.on(
'data',
(response: protos.google.cloud.compute.v1.Instance) => {
responses.push(response);
}
);
stream.on('end', () => {
resolve(responses);
});
stream.on('error', (err: Error) => {
reject(err);
});
});
await assert.rejects(promise, expectedError);
assert(
(client.descriptors.page.list.createStream as SinonStub)
.getCall(0)
.calledWith(client.innerApiCalls.list, request)
);
assert.strictEqual(
(client.descriptors.page.list.createStream as SinonStub).getCall(0)
.args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('uses async iteration with list without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.ListInstancesRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedResponse = [
generateSampleMessage(new protos.google.cloud.compute.v1.Instance()),
generateSampleMessage(new protos.google.cloud.compute.v1.Instance()),
generateSampleMessage(new protos.google.cloud.compute.v1.Instance()),
];
client.descriptors.page.list.asyncIterate =
stubAsyncIterationCall(expectedResponse);
const responses: protos.google.cloud.compute.v1.IInstance[] = [];
const iterable = client.listAsync(request);
for await (const resource of iterable) {
responses.push(resource!);
}
assert.deepStrictEqual(responses, expectedResponse);
assert.deepStrictEqual(
(client.descriptors.page.list.asyncIterate as SinonStub).getCall(0)
.args[1],
request
);
assert.strictEqual(
(client.descriptors.page.list.asyncIterate as SinonStub).getCall(0)
.args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('uses async iteration with list with error', async () => {
const client = new instancesModule.v1.InstancesClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.ListInstancesRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedError = new Error('expected');
client.descriptors.page.list.asyncIterate = stubAsyncIterationCall(
undefined,
expectedError
);
const iterable = client.listAsync(request);
await assert.rejects(async () => {
const responses: protos.google.cloud.compute.v1.IInstance[] = [];
for await (const resource of iterable) {
responses.push(resource!);
}
});
assert.deepStrictEqual(
(client.descriptors.page.list.asyncIterate as SinonStub).getCall(0)
.args[1],
request
);
assert.strictEqual(
(client.descriptors.page.list.asyncIterate as SinonStub).getCall(0)
.args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
});
describe('listReferrers', () => {
it('invokes listReferrers without error', async () => {
const client = new instancesModule.v1.InstancesClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.ListReferrersInstancesRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = [
generateSampleMessage(new protos.google.cloud.compute.v1.Reference()),
generateSampleMessage(new protos.google.cloud.compute.v1.Reference()),
generateSampleMessage(new protos.google.cloud.compute.v1.Reference()),
];
client.innerApiCalls.listReferrers = stubSimpleCall(expectedResponse);
const [response] = await client.listReferrers(request);
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.listReferrers as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes listReferrers without error using callback', async () => {
const client = new instancesModule.v1.InstancesClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.ListReferrersInstancesRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedResponse = [
generateSampleMessage(new protos.google.cloud.compute.v1.Reference()),
generateSampleMessage(new protos.google.cloud.compute.v1.Reference()),
generateSampleMessage(new protos.google.cloud.compute.v1.Reference()),
];
client.innerApiCalls.listReferrers =
stubSimpleCallWithCallback(expectedResponse);
const promise = new Promise((resolve, reject) => {
client.listReferrers(
request,
(
err?: Error | null,
result?: protos.google.cloud.compute.v1.IReference[] | null
) => {
if (err) {
reject(err);
} else {
resolve(result);
}
}
);
});
const response = await promise;
assert.deepStrictEqual(response, expectedResponse);
assert(
(client.innerApiCalls.listReferrers as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions /*, callback defined above */)
);
});
it('invokes listReferrers with error', async () => {
const client = new instancesModule.v1.InstancesClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.ListReferrersInstancesRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedOptions = {
otherArgs: {
headers: {
'x-goog-request-params': expectedHeaderRequestParams,
},
},
};
const expectedError = new Error('expected');
client.innerApiCalls.listReferrers = stubSimpleCall(
undefined,
expectedError
);
await assert.rejects(client.listReferrers(request), expectedError);
assert(
(client.innerApiCalls.listReferrers as SinonStub)
.getCall(0)
.calledWith(request, expectedOptions, undefined)
);
});
it('invokes listReferrersStream without error', async () => {
const client = new instancesModule.v1.InstancesClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.ListReferrersInstancesRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedResponse = [
generateSampleMessage(new protos.google.cloud.compute.v1.Reference()),
generateSampleMessage(new protos.google.cloud.compute.v1.Reference()),
generateSampleMessage(new protos.google.cloud.compute.v1.Reference()),
];
client.descriptors.page.listReferrers.createStream =
stubPageStreamingCall(expectedResponse);
const stream = client.listReferrersStream(request);
const promise = new Promise((resolve, reject) => {
const responses: protos.google.cloud.compute.v1.Reference[] = [];
stream.on(
'data',
(response: protos.google.cloud.compute.v1.Reference) => {
responses.push(response);
}
);
stream.on('end', () => {
resolve(responses);
});
stream.on('error', (err: Error) => {
reject(err);
});
});
const responses = await promise;
assert.deepStrictEqual(responses, expectedResponse);
assert(
(client.descriptors.page.listReferrers.createStream as SinonStub)
.getCall(0)
.calledWith(client.innerApiCalls.listReferrers, request)
);
assert.strictEqual(
(
client.descriptors.page.listReferrers.createStream as SinonStub
).getCall(0).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('invokes listReferrersStream with error', async () => {
const client = new instancesModule.v1.InstancesClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.ListReferrersInstancesRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedError = new Error('expected');
client.descriptors.page.listReferrers.createStream =
stubPageStreamingCall(undefined, expectedError);
const stream = client.listReferrersStream(request);
const promise = new Promise((resolve, reject) => {
const responses: protos.google.cloud.compute.v1.Reference[] = [];
stream.on(
'data',
(response: protos.google.cloud.compute.v1.Reference) => {
responses.push(response);
}
);
stream.on('end', () => {
resolve(responses);
});
stream.on('error', (err: Error) => {
reject(err);
});
});
await assert.rejects(promise, expectedError);
assert(
(client.descriptors.page.listReferrers.createStream as SinonStub)
.getCall(0)
.calledWith(client.innerApiCalls.listReferrers, request)
);
assert.strictEqual(
(
client.descriptors.page.listReferrers.createStream as SinonStub
).getCall(0).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('uses async iteration with listReferrers without error', async () => {
const client = new instancesModule.v1.InstancesClient({
auth: googleAuth,
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.ListReferrersInstancesRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedResponse = [
generateSampleMessage(new protos.google.cloud.compute.v1.Reference()),
generateSampleMessage(new protos.google.cloud.compute.v1.Reference()),
generateSampleMessage(new protos.google.cloud.compute.v1.Reference()),
];
client.descriptors.page.listReferrers.asyncIterate =
stubAsyncIterationCall(expectedResponse);
const responses: protos.google.cloud.compute.v1.IReference[] = [];
const iterable = client.listReferrersAsync(request);
for await (const resource of iterable) {
responses.push(resource!);
}
assert.deepStrictEqual(responses, expectedResponse);
assert.deepStrictEqual(
(
client.descriptors.page.listReferrers.asyncIterate as SinonStub
).getCall(0).args[1],
request
);
assert.strictEqual(
(
client.descriptors.page.listReferrers.asyncIterate as SinonStub
).getCall(0).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
it('uses async iteration with listReferrers with error', async () => {
const client = new instancesModule.v1.InstancesClient({
credentials: {client_email: 'bogus', private_key: 'bogus'},
projectId: 'bogus',
});
client.initialize();
const request = generateSampleMessage(
new protos.google.cloud.compute.v1.ListReferrersInstancesRequest()
);
request.project = '';
const expectedHeaderRequestParams = 'project=';
const expectedError = new Error('expected');
client.descriptors.page.listReferrers.asyncIterate =
stubAsyncIterationCall(undefined, expectedError);
const iterable = client.listReferrersAsync(request);
await assert.rejects(async () => {
const responses: protos.google.cloud.compute.v1.IReference[] = [];
for await (const resource of iterable) {
responses.push(resource!);
}
});
assert.deepStrictEqual(
(
client.descriptors.page.listReferrers.asyncIterate as SinonStub
).getCall(0).args[1],
request
);
assert.strictEqual(
(
client.descriptors.page.listReferrers.asyncIterate as SinonStub
).getCall(0).args[2].otherArgs.headers['x-goog-request-params'],
expectedHeaderRequestParams
);
});
});
}); | the_stack |
import * as d3Selection from '../../src/d3-selection';
// ---------------------------------------------------------------------------------------
// Some preparatory work for definition testing below
// ---------------------------------------------------------------------------------------
// Generic DOM related variables
let xDoc: Document,
xWindow: Window;
interface BodyDatum {
foo: string;
bar: number;
}
interface DivDatum {
padding: string;
text: string;
}
interface SVGDatum {
width: number;
height: number;
}
interface CircleDatum {
nodeId: string;
name: string;
label: string;
cx: number;
cy: number;
r: number;
}
interface CircleDatumAlternative {
nodeId: string;
name: string;
label: string;
cx: number;
cy: number;
r: number;
color: string;
}
// ---------------------------------------------------------------------------------------
// Tests of Top-Level Selection Functions
// ---------------------------------------------------------------------------------------
// test top-level .selection() -----------------------------------------------------------
let topSelection: d3Selection.Selection<HTMLElement, any, null, undefined> = d3Selection.selection();
// test top-level select() ---------------------------------------------------------------
// Using select() with string argument and no type parameters creates selection
// with Group element of type BaseType and datum of type 'any'. The parent element is of type HTMLElement with datum of type 'any'
let baseTypeEl: d3Selection.Selection<d3Selection.BaseType, any, HTMLElement, any> = d3Selection.select('body');
// Using select() with string argument and type parameters creates selection
// with Group element of type HTMLBodyElement and datum of BodyDatum type. The parent element is of type HTMLElement with datum of type 'any'
let body: d3Selection.Selection<HTMLBodyElement, BodyDatum, HTMLElement, any> = d3Selection.select<HTMLBodyElement, BodyDatum>('body');
// Using select() with node argument and no type parameters creates selection
// with Group element of type BaseType and datum of type 'any' The parent element is of type 'null' with datum of type 'undefined'
let baseTypeEl2: d3Selection.Selection<d3Selection.BaseType, any, null, undefined> = d3Selection.select(baseTypeEl.node());
// let body2: d3Selection.Selection<HTMLElement, any, null, undefined> = d3Selection.select(baseTypeEl.node()); // fails as baseTypeEl.node() is of type cannot be assigned to HTMLElement
let body3: d3Selection.Selection<HTMLBodyElement, any, null, undefined> = d3Selection.select(body.node()); // element types match, but datum is of type 'any' as it cannot be inferred from .node()
// Using select() with node argument and type parameters creates selection
// with Group element of type HTMLBodyElement and datum of BodyDatum type. The parent element is of type 'null' with datum of type 'undefined'
let body4: d3Selection.Selection<HTMLBodyElement, BodyDatum, null, undefined> = d3Selection.select<HTMLBodyElement, BodyDatum>(body.node());
// d3Selection.select<HTMLBodyElement, BodyDatum>(baseTypeEl.node()); // fails as baseTypeEl.node() is not of type HTMLBodyElement
d3Selection.select(xDoc);
d3Selection.select(xWindow);
// test top-level selectAll() -------------------------------------------------------------
// Using selectAll(), selectAll(null) or selectAll(undefined) creates an empty selection
let emptyRootSelection: d3Selection.Selection<undefined, undefined, null, undefined> = d3Selection.selectAll();
emptyRootSelection = d3Selection.selectAll(null);
emptyRootSelection = d3Selection.selectAll(undefined);
// Using selectAll(...) with string argument and no type parameters creates selection
// with Group elements of type BaseType and datum of type 'any'. The parent element is of type HTMLElement with datum of type 'any'
let baseTypeElements: d3Selection.Selection<d3Selection.BaseType, any, HTMLElement, any> = d3Selection.selectAll('div');
// Using selectAll() with string argument and type parameters creates selection
// with Group element of type HTMLDivElement and datum of DivDatum type. The parent element is of type HTMLElement with datum of type 'any'
let divElements: d3Selection.Selection<HTMLDivElement, DivDatum, HTMLElement, any> = d3Selection.selectAll<HTMLDivElement, DivDatum>('div');
// Using selectAll(...) with node array argument and no type parameters creates selection
// with Group element of type BaseType and datum of type 'any' The parent element is of type 'null' with datum of type 'undefined'
let baseTypeElements2: d3Selection.Selection<d3Selection.BaseType, any, null, undefined> = d3Selection.selectAll(baseTypeElements.nodes());
// let divElements2: d3Selection.Selection<HTMLDivElement, any, null, undefined> = d3Selection.selectAll(baseTypeElements.nodes()); // fails, group elements types not of compatible for baseTypeElements
let divElements3: d3Selection.Selection<HTMLDivElement, any, null, undefined> = d3Selection.selectAll(divElements.nodes()); // element types match, but datum is of type 'any' as it cannot be inferred from .nodes()
// Using selectAll(...) with node array argument and type parameters creates selection
// with Group element of type HTMLDivElement and datum of DivDatum type. The parent element is of type 'null' with datum of type 'undefined'
let divElements4: d3Selection.Selection<HTMLDivElement, DivDatum, null, undefined> = d3Selection.selectAll<HTMLDivElement, DivDatum>(divElements.nodes());
// d3Selection.selectAll<HTMLDivElement, DivDatum>(baseTypeElements.nodes()); // fails as baseTypeEl.node() is not of type HTMLBodyElement
// selectAll(...) accepts NodeListOf<...> argument
let xSVGCircleElementList: NodeListOf<SVGCircleElement>;
let circleSelection: d3Selection.Selection<SVGCircleElement, any, null, undefined> = d3Selection.selectAll(xSVGCircleElementList);
// selectAll(...) accepts HTMLCollection, HTMLCollectionOf<...> argument
let documentLinks: d3Selection.Selection<HTMLAnchorElement | HTMLAreaElement, any, null, undefined> = d3Selection.selectAll(document.links);
// ---------------------------------------------------------------------------------------
// Tests of Sub-Selection Functions
// ---------------------------------------------------------------------------------------
// select(...) sub-selection --------------------------------------------------------------
// Expected: datum propagates down from selected element to sub-selected descendant element
// Parent element and Parent Datum of sub-selected element is the same as starting selection
// Using select(...) sub-selection with a string argument.
let svgEl: d3Selection.Selection<SVGSVGElement, SVGDatum, HTMLElement, any> = d3Selection.select<SVGSVGElement, SVGDatum>('svg');
let firstG: d3Selection.Selection<SVGGElement, SVGDatum, HTMLElement, any> = svgEl.select<SVGGElement>('g');
// let firstG_2: d3Selection.Selection<SVGGElement, SVGDatum, SVGSVGElement, any> = svgEl.select<SVGGElement>('g'); // fails, parent element of selection does not change with .select(...)
// firstG = svgEl.select('g'); // fails, element type defaults to 'any', but SVGGElement expexted on left-hand side
// firstG = svgEl.select<SVGSVGElement>('svg'); // fails, element type of SVGSVGElement provided, but SVGGElement expexted on left-hand side (silly test to begin with)
// Using select(...) sub-selection with a selector function argument.
function svgGroupSelector(this: SVGSVGElement, d: SVGDatum, i: number, groups: Array<SVGSVGElement>): SVGGElement {
return this.querySelector('g'); // this-type compatible with group element-type to which the selector function will be appplied
}
firstG = svgEl.select(svgGroupSelector);
firstG = svgEl.select(function () {
console.log('Get <svg> Element width using "this": ', this.width.baseVal.value); // 'this' type is SVGSVGElement
return this.querySelector('g'); // this of type SVGSVGElement by type inference
});
firstG = svgEl.select(function (d, i, group) {
console.log('Get <svg> Element width using "this": ', this.width.baseVal.value); // 'this' type is SVGSVGElement
console.log('Width in datum:', d.width); // d is type of originating selection element Datum: SVGDatum
if (group.length > 1) {
console.log('Get width of 2nd <svg> Element in group: ', group[1].width.baseVal.value); // type is SVGSVGElement
}
return this.querySelector('g'); // this of type SVGSVGElement by type inference
});
// firstG = svgEl.select(function() {
// return this.querySelector('a'); // fails, return type HTMLAnchorElement is not compatible with SVGGElement expected by firstG
// });
// selectAll(...) sub-selection --------------------------------------------------------------
// Expected: datum from selected element(s) does not propagate down to sub-selected descendant elements.
// Group elements of original selection become Parent elements in sub-selection.
// selectAll(), selectAll(null) selectAll(undefined) return empty sub-selection
let emptySubSelection: d3Selection.Selection<undefined, undefined, SVGSVGElement, SVGDatum> = svgEl.selectAll();
emptySubSelection = svgEl.selectAll(null);
emptySubSelection = svgEl.selectAll(undefined);
// Using selectAll(...) sub-selection with a string argument.
let elementsUnknownData: d3Selection.Selection<d3Selection.BaseType, any, SVGSVGElement, SVGDatum> = svgEl.selectAll('g');
let gElementsOldData: d3Selection.Selection<SVGGElement, CircleDatum, SVGSVGElement, SVGDatum> = svgEl.selectAll<SVGGElement, CircleDatum>('g');
// gElementsOldData = svgEl.selectAll('g'); // fails default type parameters of selectAll for group element type and datum type do not match
// Using selectAll(...) sub-selection with a selector function argument.
function svgGroupSelectorAll(this: SVGSVGElement, d: SVGDatum, i: number, groups: Array<SVGSVGElement>): NodeListOf<SVGGElement> {
return this.querySelectorAll('g'); // this-type compatible with group element-type to which the selector function will be appplied
}
gElementsOldData = svgEl.selectAll<SVGGElement, CircleDatum>(svgGroupSelectorAll);
gElementsOldData = svgEl.selectAll<SVGGElement, CircleDatum>(function () {
console.log('Get <svg> Element width using "this": ', this.width.baseVal.value); // 'this' type is SVGSVGElement
return this.querySelectorAll('g'); // this of type SVGSVGElement by type inference
});
gElementsOldData = svgEl.selectAll<SVGGElement, CircleDatum>(function (d, i, group) {
console.log('Get <svg> Element width using "this": ', this.width.baseVal.value); // 'this' type is SVGSVGElement
console.log('Width in datum:', d.width); // type of d is SVGDatum
if (group.length > 1) {
console.log('Get width of 2nd <svg> Element in group: ', group[1].width.baseVal.value); // type of group is SVGSVGElement[]
}
return this.querySelectorAll('g');
});
// gElementsOldData = svgEl.selectAll(function() { // fails, because Datum type is not compatible as selectAll defaults to 'any', but gElementsOldData expects CircleDatum
// return this.querySelectorAll('g');
// });
// gElementsOldData = svgEl.selectAll<SVGGElement, CircleDatum>(function() { // fails, return type HTMLAnchorElement is not compatible with SVGGElement expected by selectAll-typing
// return this.querySelectorAll('a');
// });
elementsUnknownData = svgEl.selectAll(svgGroupSelectorAll);
elementsUnknownData = svgEl.selectAll(function () {
console.log('Get <svg> Element width using "this": ', this.width.baseVal.value); // 'this' type is SVGSVGElement
return this.querySelectorAll('g'); // this of type SVGSVGElement by type inference
});
// gElementsUnknownData = svgEl.selectAll(function() { // fails, return type HTMLAnchorElement is not compatible with SVGGElement
// return this.querySelectorAll('a');
// });
// Selection Helper methods -------------------------------------------------------------
// selector(...) and selectorAll(...) ----------------------------------------------------
// d3Selection.select<SVGGElement>(d3Selection.selector<SVGGElement>('g')); // fails, selector as argument to top-level select not supported
// supported on sub-selection
firstG = svgEl.select(d3Selection.selector<SVGGElement>('g')); // type parameter of select(...) inferred
// firstG = svgEl.select<SVGGElement>(d3Selection.selector<HTMLDivElement>('div')); // fails, select and selector mismatch
gElementsOldData = svgEl.selectAll<SVGGElement, CircleDatum>(d3Selection.selectorAll<SVGGElement>('g'));
// filter() ------------------------------------------------------------------------------
let filterdGElements: d3Selection.Selection<SVGGElement, CircleDatum, SVGSVGElement, SVGDatum>;
filterdGElements = gElementsOldData.filter('.top-level');
filterdGElements = gElementsOldData.filter(function (d, i, group) {
console.log('Element Id of <g> DOM element: ', this.id); // this context SVGGElement
if (group.length > 0) {
console.log('Element Id of first <g> DOM element in group: ', group[0].id); // group: Array<SVGGElement>
}
return d.r > 10; // uses CircleDatum
});
// matcher() -----------------------------------------------------------------------------
filterdGElements = gElementsOldData.filter(d3Selection.matcher('.top-level'));
// ---------------------------------------------------------------------------------------
// Tests of Modification
// ---------------------------------------------------------------------------------------
// Getter return values tests -------------------------------------------------------------
let flag: boolean,
str: string,
dummy: any;
flag = body.classed('any-class');
str = body.attr('class');
str = body.style('background-color');
dummy = body.property('foo'); // arbitrary property
str = body.text();
str = body.html();
// Setters tests -------------------------------------------------------------------------
let circles: d3Selection.Selection<SVGCircleElement, CircleDatumAlternative, HTMLElement, any>;
let divs: d3Selection.Selection<HTMLDivElement, DivDatum, HTMLElement, any>;
// attr(...) Tests
circles = d3Selection.selectAll<SVGCircleElement, CircleDatumAlternative>('circle')
.attr('cx', 10) // number
.attr('stroke', 'blue'); // string
circles = circles // re-assignment test chaining return-type
.attr('cx', function (d, i, group) {
console.log('Pre-change center x-coordinate: ', this.cx.baseVal.value); // this context SVGCircleElement
if (group.length > 0) {
console.log('Owner SVG Element of first group element:', group[0].ownerSVGElement); // group : Array<SVGCircleElement>
}
return d.cx; // numeric return value
})
.attr('stroke', function (d) {
return d.color; // string return value
});
divs = d3Selection.selectAll<HTMLDivElement, DivDatum>('div')
.attr('contenteditable', false) // boolean
.attr('contenteditable', function () {
return false; // boolean return value
});
// classed(...) Tests
divs = divs
.classed('success', true);
divs = divs
.classed('zero-px-padding', function (d, i, group) {
console.log('Client Rectangle Top: ', this.getBoundingClientRect().top); // this context HTMLDivElement
if (group.length > 0) {
console.log('Alignment of first group element:', group[0].align); // group : Array<HTMLDivElement>
}
return d.padding === '0px'; // boolean return value
});
// style(...) Tests
divs = divs
.style('background-color', 'blue') // string
.style('hidden', false) // boolean
// .style('color', 'green', 'test') // fails, invalid priority value
.style('color', 'green', 'important');
divs = divs
.style('padding', function (d, i, group) {
console.log('Client Rectangle Top: ', this.getBoundingClientRect().top); // this context HTMLDivElement
if (group.length > 0) {
console.log('Alignment of first group element:', group[0].align); // group : Array<HTMLDivElement>
}
return d.padding; // string return value
})
.style('hidden', function () {
return true;
}, null) // boolean return + test: priority = null
// .style('color', function () { return 'green'; }, 'test') // fails, test: invalid priority value
.style('color', function () { return 'green'; }, 'important'); // boolean return + test: priority = 'important';
// property(...) Tests
circles = circles
.property('__hitchhikersguide__', {
value: 42,
survival: 'towel'
}); // any
circles = circles
.property('__hitchhikersguide__', function (d, i, group) {
console.log('Pre-change center x-coordinate: ', this.cx.baseVal.value); // this context SVGCircleElement
if (group.length > 0) {
console.log('Owner SVG Element of first group element:', group[0].ownerSVGElement); // group : Array<SVGCircleElement>
}
return {
value: 42,
survival: 'towel'
}; // returns not so arbitrary object, again
});
// text(...) test
body = body
.text('Not so meaningful blurp.') // string
.text(42) // number will be converted to string by D3
.text(true); // boolean will be converted to string by D3
body = body
.text(function (d) {
console.log('Body background color: ', this.bgColor); // this context HTMLBodyElement
return d.foo; // BodyDatum
})
.text(function (d) {
return 42; // number will be converted to string by D3
})
.text(function (d) {
return true; // boolean will be converted to string by D3
});
body = body
.html('<div> 42 </div>');
body = body
.html(function (d) {
return '<div> Body Background Color: ' + this.bgColor + ', Foo Datum: ' + d.foo + '</div>'; // this context HTMLBodyElement, datum BodyDatum
});
// ---------------------------------------------------------------------------------------
// Tests of Datum and Data Join
// ---------------------------------------------------------------------------------------
let data: Array<CircleDatum> = [
{ nodeId: 'c1', cx: 10, cy: 10, r: 5, name: 'foo', label: 'Foo' },
{ nodeId: 'c2', cx: 20, cy: 20, r: 5, name: 'bar', label: 'Bar' },
{ nodeId: 'c3', cx: 30, cy: 30, r: 5, name: 'fooBar', label: 'Foo Bar' }
];
let data2: Array<CircleDatumAlternative> = [
{ nodeId: 'c1', cx: 10, cy: 10, r: 5, name: 'foo', label: 'Foo', color: 'seagreen' },
{ nodeId: 'c2', cx: 20, cy: 20, r: 5, name: 'bar', label: 'Bar', color: 'midnightblue' },
{ nodeId: 'c4', cx: 10, cy: 15, r: 10, name: 'newbie', label: 'Newbie', color: 'red' }
];
// Tests of Datum -----------------------------------------------------------------------
// TEST GETTER
let bodyDatum: BodyDatum = body.datum();
// TEST REMOVE DATUM
body.datum(null); // removes datum, i.e. return type has group datum type 'undefined'
// TEST SETTER METHODS
let newBodyDatum: { newFoo: string };
// object-based
newBodyDatum = body.datum({ newFoo: 'new foo' }).datum(); // inferred type
// body.datum<BodyDatum>({ newFoo: 'new foo' }); // fails, data type incompatible
// function-based
newBodyDatum = body.datum(function (d) {
console.log('HTML5 Custom Data Attributes of body: ', this.dataset); // this typings HTMLBodyElement
console.log('Old foo:', d.foo); // current data of type BodyDatum
return { newFoo: 'new foo' };
}).datum(); // inferred type
// newBodyDatum = body.datum<BodyDatum>(function (d) { // fails, data type incompatible with return value type
// console.log('HTML5 Custom Data Attributes of body: ', this.dataset); // this typings HTMLBodyElement
// return { newFoo: 'new foo' };
// }).datum(); // inferred type
// SCENARIO 1: Fully type-parameterized
// object-based
d3Selection.select<SVGSVGElement, SVGDatum>('#svg-1')
.select<SVGGElement>('g.circles-group') // first matching element only
.datum<CircleDatumAlternative[]>(data2)
.classed('has-transform-property', function (d) {
console.log('Color of first data element array', d.length > 0 ? d[0].color : 'Data array empty');
return this.transform !== undefined;
});
// SCENARIO 2: Partially type-parameterized (To have DOM object type -> 'this' and datum-type in 'classed' method call)
d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in last step of chain
.select<SVGGElement>('g.circles-group')
.datum(data2) // new data type inferred
.classed('has-transform-property', function (d) {
console.log('Color of first data element array', d.length > 0 ? d[0].color : 'Data array empty'); // CircleDatumAlternative type
return this.transform !== undefined;
});
// below fails, as 'this' in .classed(...) will default to BaseType, which does not have 'transform' property
// d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in last step of chain
// .select('g.circles-group') // missing typing of selected DOM element for use in .classed(...)
// .datum(data2) // new data type inferred
// .classed('has-transform-property', function (d) {
// console.log('Color of first data element array', d.length > 0? d[0].color: 'Data array empty'); // CircleDatumAlternative type
// return this.transform !== undefined;
// });
// SCENARIO 3: Only inferred typing (To have datum-type in 'classed' method call, no need for DOM object access)
d3Selection.select('#svg-1') // irrelevant typing to get contextual typing in last step of chain
.select('g.circles-group') // irrelevant typing to get contextual typing in last step of chain
.datum(data2) // new data type inferred
.classed('has-green-first-data-element', function (d) {
return d.length > 0 && d[0].color === 'green';
});
// Tests of Data Join --------------------------------------------------------------------
let dimensions: SVGDatum = {
width: 500,
height: 300
};
let startCircleData: Array<CircleDatumAlternative>,
endCircleData: Array<CircleDatumAlternative>;
let circles2: d3Selection.Selection<SVGCircleElement, CircleDatumAlternative, SVGSVGElement, SVGDatum>;
// Test creating initial data-driven circle selection
// and append materialized SVGCircleElement per enter() selection element
// - use data(...) with array-signature and infer data type from arrray type passed into data(...)
// - use enter() to obtain enter selection
// - materialize svg circles using append(...) with type-parameter and string argument
circles2 = d3Selection.select<SVGSVGElement, any>('#svg2')
.datum(dimensions)
.attr('width', function (d) { return d.width; })
.attr('height', function (d) { return d.height; })
.selectAll() // create empty Selection
.data(startCircleData) // assign data for circles to be added (no previous circles)
.enter() // obtain enter selection
.append<SVGCircleElement>('circle');
// UPDATE-selection with continuation in data type ---------------------------------
// Assign new data and use key(...) function for mapping
circles2 = circles2 // returned update selection has the same type parameters as original selection, if data type is unchanged
.data<CircleDatumAlternative>(endCircleData, function (d) { return d.nodeId; });
// circles2.data<DivDatum>(endCircleData, function (d) { return d.nodeId; }); // fails, forced data type parameter and data argument mismatch
// ENTER-selection -----------------------------------------------------------------
// TODO: Related to BaseType Choice issue
let enterElements: d3Selection.Selection<d3Selection.EnterElement, CircleDatumAlternative, SVGSVGElement, SVGDatum>;
enterElements = circles2.enter(); // enter selection
let enterCircles = enterElements
.append<SVGCircleElement>('circle') // enter selection with materialized DOM elements (svg circles)
.attr('cx', function (d) { return d.cx; })
.attr('cy', function (d) { return d.cy; })
.attr('r', function (d) { return d.r; })
.style('stroke', function (d) { return d.color; })
.style('fill', function (d) { return d.color; });
// EXIT-selection ----------------------------------------------------------------------
// tests exit(...) and remove()
let exitCircles = circles2.exit<CircleDatumAlternative>(); // Note: need to re-type datum type, as the exit selection elements have the 'old data'
exitCircles
.style('opacity', function (d) {
console.log('Circle Radius exit node: ', this.r.baseVal.value); // this type is SVGCircleElement
return d.color === 'green' ? 1 : 0; // data type as per .exit<...>() parameterization
})
.remove();
// Note: the alternative using only .exit() without typing, will fail, if access to datum properties is attemped.
// If access to d is not required, the short-hand is acceptable e.g. circles2.exit().remove();
// let exitCircles = circles2.exit(); // Note: Without explicit re-typing to the old data type, the data type default to '{}'
// exitCircles
// .style('opacity', function (d) {
// console.log('Circle Radius exit node: ', this.r.baseVal.value);
// return d.color === 'green' ? 1 : 0; // fails, as data type is defaulted to {}. If datum access is required, this should trigger the thought to type .exit<...>
// });
// MERGE ENTER + UPDATE ------------------------------------------------------------------
circles2 = enterCircles.merge(circles2); // merge enter and update selections
// FURTHER DATA-JOIN TESTs (function argument, changes in data type between old and new data)
const matrix = [
[11975, 5871, 8916, 2868],
[1951, 10048, 2060, 6171],
[8010, 16145, 8090, 8045],
[1013, 990, 940, 6907]
];
// SCENARIO 1 - Fully type parameterized, when there is a need for `this` typings in callbacks
// and enforcement of type of data used in data join as input to data(...)
let nMatrix: Array<number[]>,
nRow: Array<number>;
let tr: d3Selection.Selection<HTMLTableRowElement, number[], HTMLTableElement, any>;
tr = d3Selection.select('body')
.append<HTMLTableElement>('table')
.selectAll()
.data(matrix)
// .data([{test: 1}, {test: 2}]) // fails, using this data statement instead, would fail assignment to tr due to the data type of tr Selection
// .data<number[]>([{test: 1}, {test: 2}]) // fails, using this data statement instead, would fail because of its type parameter not being met by input
.enter().append<HTMLTableRowElement>('tr');
nMatrix = tr.data(); // i.e. matrix
let td: d3Selection.Selection<HTMLTableDataCellElement, number, HTMLTableRowElement, number[]>;
td = tr.selectAll()
.data(function (d) { return d; }) // d : Array<number> inferred (Array[4] of number per parent <tr>)
.enter().append<HTMLTableDataCellElement>('td')
.text(function (d) {
console.log('Abbreviated text for object', this.abbr); // this-type HTMLTableDataCellElement (demonstration only)
return d;
}); // d:number inferred
nRow = td.data(); // flattened matrix (Array[16] of number)
// SCENARIO 2 - Completely inferred types, when there is no need for `this` typings
let tr2 = d3Selection.select('body')
.append('table')
.selectAll('tr')
.data(matrix)
.enter().append('tr');
nMatrix = tr2.data(); // i.e. matrix
let td2 = tr2.selectAll('td')
.data(function (d) { return d; }) // d : Array<number> inferred (Array[4] of number per parent <tr>)
.enter().append('td')
.text(function (d) { return d; }); // d:number inferred
nRow = td2.data(); // flattened matrix (Array[16] of number)
// ---------------------------------------------------------------------------------------
// Tests of Alternative DOM Manipulation
// ---------------------------------------------------------------------------------------
// append(...) and creator(...) ----------------------------------------------------------
// without append<...> typing returned selection has group element of type BaseType
let newDiv: d3Selection.Selection<d3Selection.BaseType, BodyDatum, HTMLElement, any>;
newDiv = body.append('div');
let newDiv2: d3Selection.Selection<HTMLDivElement, BodyDatum, HTMLElement, any>;
newDiv2 = body.append<HTMLDivElement>('div');
// using creator
newDiv2 = body.append(d3Selection.creator<HTMLDivElement>('div'));
// newDiv2 = body.append(d3Selection.creator('div')); // fails, as creator returns BaseType element, but HTMLDivElement is expected.
newDiv2 = body.append(function (d) {
console.log('Body element foo property: ', d.foo); // data of type BodyDatum
return this.ownerDocument.createElement('div'); // this-type HTMLBodyElement
});
// newDiv2 = body.append<HTMLDivElement>(function(d) {
// return this.ownerDocument.createElement('a'); // fails, HTMLDivElement expected by type parameter, HTMLAnchorElement returned
// });
// newDiv2 = body.append(function(d) {
// return this.ownerDocument.createElement('a'); // fails, HTMLDivElement expected by inference, HTMLAnchorElement returned
// });
// insert(...) ---------------------------------------------------------------------------
// without insert<...> typing returned selection has group element of type BaseType
let newParagraph: d3Selection.Selection<d3Selection.BaseType, BodyDatum, HTMLElement, any>;
newParagraph = body.insert('p', 'p.second-paragraph');
let newParagraph2: d3Selection.Selection<HTMLParagraphElement, BodyDatum, HTMLElement, any>;
newParagraph2 = body.insert<HTMLParagraphElement>('p', 'p.second-paragraph');
newParagraph2 = body.insert(d3Selection.creator<HTMLParagraphElement>('p'), 'p.second-paragraph');
newParagraph2 = body.insert(function (d) {
console.log('Body element foo property: ', d.foo); // data of type BodyDatum
return this.ownerDocument.createElement('p'); // this-type HTMLParagraphElement
}, 'p.second-paragraph');
// newParagraph2 = body.insert<HTMLParagraphElement>(function(d) {
// return this.ownerDocument.createElement('a'); // fails, HTMLParagraphElement expected by type parameter, HTMLAnchorElement returned
// }, 'p.second-paragraph');
// newParagraph2 = body.insert(function(d) {
// return this.ownerDocument.createElement('a'); // fails, HTMLParagraphElement expected by type inference, HTMLAnchorElement returned
// }, 'p.second-paragraph');
newParagraph2 = body.insert(d3Selection.creator<HTMLParagraphElement>('p'), function (d, i, group) {
console.log('Body element foo property: ', d.foo); // data of type BodyDatum
return this.children[0]; // this type HTMLBodyElement
});
newParagraph2 = body.insert(
// type
function (d) {
console.log('Body element foo property: ', d.foo); // data of type BodyDatum
return this.ownerDocument.createElement('p'); // this-type HTMLParagraphElement
},
// before
function (d, i, group) {
console.log('Body element foo property: ', d.foo); // data of type BodyDatum
return this.children[0]; // this type HTMLBodyElement
});
// sort(...) -----------------------------------------------------------------------------
// NB: Return new selection of same type
circles2 = circles2.sort(function (a, b) {
return (b.r - a.r);
});
// order(...) ----------------------------------------------------------------------------
// returns 'this' selection
circles2 = circles2.order();
// raise() -------------------------------------------------------------------------------
// returns 'this' selection
circles2 = circles2.raise();
// lower() -------------------------------------------------------------------------------
// returns 'this' selection
circles2 = circles2.lower();
// ---------------------------------------------------------------------------------------
// Control FLow
// ---------------------------------------------------------------------------------------
// empty() -------------------------------------------------------------------------------
let emptyFlag = gElementsOldData.empty();
// node() and nodes() --------------------------------------------------------------------
let bodyNode: HTMLBodyElement = body.node();
let gElementsNodes: Array<SVGGElement> = gElementsOldData.nodes();
// size() --------------------------------------------------------------------------------
let size: number = gElementsOldData.size();
// each() -------------------------------------------------------------------------------
// returns 'this' selection
circles = circles.each(function (d, i, group) { // check chaining return type by re-assigning
if (this.r.baseVal.value < d.r) { // this of type SVGCircleElement, datum of type CircleDatumAlternative
d3Selection.select(this).attr('r', d.r);
}
console.log(group[i].cx.baseVal.value); // group : Array<SVGCircleElement>
});
// call() -------------------------------------------------------------------------------
function enforceMinRadius(selection: d3Selection.Selection<SVGCircleElement, CircleDatumAlternative, any, any>, minRadius: number): void {
selection.attr('r', function (d) {
let r: number = +d3Selection.select(this).attr('r');
return Math.max(r, minRadius);
});
}
// returns 'this' selection
circles = circles.call(enforceMinRadius, 40); // check chaining return type by re-assigning
// circles.call(function (selection: d3Selection.Selection<HTMLDivElement, CircleDatum, any, any>):void {
// // fails, group element types of selection not compatible: SVGCircleElement v HTMLDivElement
// });
// circles.call(function (selection: d3Selection.Selection<SVGCircleElement, DivDatum, any, any>):void {
// // fails, group datum types of selection not compatible: CircleDatumAlternative v DivDatum
// });
// ---------------------------------------------------------------------------------------
// Tests of Event Handling
// ---------------------------------------------------------------------------------------
// on(...) -------------------------------------------------------------------------------
let listener: (this: HTMLBodyElement, datum: BodyDatum, index: number, group: Array<HTMLBodyElement> | ArrayLike<HTMLBodyElement>) => void;
// returns 'this' selection
body = body.on('click', listener); // check chaining return type by re-assigning
body = body.on('click', function (d) {
console.log('onclick print body background color: ', this.bgColor); // HTMLBodyElement
console.log('onclick print "foo" datum property: ', d.foo); // BodyDatum type
});
// get current listener
listener = body.on('click');
// remove listener
body = body.on('click', null); // check chaining return type by re-assigning
// dispatch(...) -------------------------------------------------------------------------
let fooEventParam: d3Selection.CustomEventParameters = {
cancelable: true,
bubbles: true,
detail: [1, 2, 3, 4]
};
// returns 'this' selection
body = body.dispatch('fooEvent', fooEventParam); // re-assign for chaining test;
body = body.dispatch('fooEvent', function (d, i, group) { // re-assign for chaining test;
let eParam: d3Selection.CustomEventParameters;
console.log('fooEvent dispatch body background color', this.bgColor);
eParam = {
cancelable: true,
bubbles: true,
detail: d.foo // d is of type BodyDatum
};
return eParam;
});
// event and customEvent() ----------------------------------------------------------------
// TODO: Tests of event are related to issue #3 (https://github.com/tomwanzek/d3-v4-definitelytyped/issues/3)
// No tests for event, as it now is of type any
interface SuccessEvent {
type: string;
team: string;
sourceEvent?: any;
}
let successEvent = { type: 'wonEuro2016', team: 'Island' };
let customListener: (this: HTMLBodyElement, finalOpponent: string) => string;
customListener = function (finalOpponent) {
let e = <SuccessEvent>d3Selection.event;
return e.team + ' defeated ' + finalOpponent + ' in the EURO 2016 Cup. Who would have thought!!!';
};
let resultText: string = d3Selection.customEvent(successEvent, customListener, body.node(), 'Wales');
// result = d3Selection.customEvent(successEvent, customListener, circles.nodes()[0], 'Wales'); // fails, incompatible 'this' context in call
// let resultValue: number = d3Selection.customEvent(successEvent, customListener, body.node(), 'Wales'); // fails, incompatible return types
// d3Selection.customEvent<SVGCircleElement, any>(successEvent, customListener, circles.nodes()[0], 'Wales'); // fails, incompatible 'this' context in type parameter and call
// d3Selection.customEvent<HTMLBodyElement, any>(successEvent, customListener, circles.nodes()[0], 'Wales'); // fails, incompatible 'this' context in type parameter and call
// d3Selection.customEvent<HTMLBodyElement, number>(successEvent, customListener, body.node(), 'Wales'); // fails, incompatible return types
// mouse() ---------------------------------------------------------------------------------
let position: [number, number],
svg: SVGSVGElement,
g: SVGGElement,
h: HTMLElement,
changedTouches: TouchList;
position = d3Selection.mouse(svg);
position = d3Selection.mouse(g);
position = d3Selection.mouse(h);
// touch() and touches() ---------------------------------------------------------------------
position = d3Selection.touch(svg, 0);
position = d3Selection.touch(g, 0);
position = d3Selection.touch(h, 0);
position = d3Selection.touch(svg, changedTouches, 0);
position = d3Selection.touch(g, changedTouches, 0);
position = d3Selection.touch(h, changedTouches, 0);
let positions: Array<[number, number]>;
positions = d3Selection.touches(svg, changedTouches);
positions = d3Selection.touches(g, changedTouches);
positions = d3Selection.touches(h, changedTouches);
positions = d3Selection.touches(svg, changedTouches);
positions = d3Selection.touches(g, changedTouches);
positions = d3Selection.touches(h, changedTouches);
// ---------------------------------------------------------------------------------------
// Tests of Local
// ---------------------------------------------------------------------------------------
let xElement: Element;
let foo: d3Selection.Local<number[]> = d3Selection.local<number[]>();
let propName: string = foo.toString();
// direct set & get on Local<T> object
xElement = foo.set(xElement, [1, 2, 3]);
let array: number[] = foo.get(xElement);
// test read & write of .property() access to locals
array = d3Selection.select(xElement)
.property(foo, [3, 2, 1])
.property(foo, () => [999])
.property(foo);
foo.remove(xElement);
// ---------------------------------------------------------------------------------------
// Tests of Namespace
// ---------------------------------------------------------------------------------------
let predefinedNamespaces: d3Selection.NamespaceMap = d3Selection.namespaces;
const svgNamespace: string = predefinedNamespaces['svg'];
const svgTextObject: d3Selection.NamespaceLocalObject | string = d3Selection.namespace('svg:text');
predefinedNamespaces['dummy'] = 'http://www.w3.org/2020/dummynamespace';
// ---------------------------------------------------------------------------------------
// Tests of Window
// ---------------------------------------------------------------------------------------
xWindow = d3Selection.window(xElement);
xWindow = d3Selection.window(xDoc);
xWindow = d3Selection.window(xWindow); | the_stack |
import { Action } from '@ngrx/store';
import { schema, normalize } from 'normalizr';
import { EntityMap } from '../reducers/normalize';
/**
* Internal action namespace
*/
const ACTION_NAMESPACE = '[@@Normalize]';
/**
* A map of schema names to object property names.
* Used for removing child properties of an entity.
*/
export interface SchemaMap {
[schemaKey: string]: string;
}
/**
* Interface for a normalize action payload
*/
export interface NormalizeActionPayload {
/**
* The normalized entities mapped to their schema keys
*/
entities: EntityMap;
/**
* The original sorted id's as an array
*/
result: string[];
}
/**
* Interface for a remove action payload
*/
export interface NormalizeRemoveActionPayload {
/**
* The id of the entity that should be removed
*/
id: string;
/**
* The schema key of the entity that should be removed
*/
key: string;
/**
* If maps valid schema keys to propety names,
* children referenced by the schema key will be removed by its id
*/
removeChildren: SchemaMap | null;
}
/**
* Base interface for `AddData`, and `RemoveData` action payload.
*/
export interface NormalizeActionSchemaConfig {
/**
* Schema definition of the entity. Used for de-/ and normalizing given entities.
*/
schema: schema.Entity;
}
/**
* Base interface for AddChildData` and `RemoveChildData` action payload.
*/
export interface NormalizeChildActionSchemaConfig {
/**
* Schema definition of the entity. Used for de-/ and normalizing given entities.
*/
parentSchema: NormalizeActionSchemaConfig['schema'];
}
/**
* Typed Interface for the config of the `AddData` and `SetData` action.
* Holds an typed array of entities to be added to the store.
*/
export interface NormalizeActionConfig<T> extends NormalizeActionSchemaConfig {
/**
* The array of entities which should be normalized and added to the store.
*/
data: T[];
}
/**
* Typed Interface for the config of the `AddData` and `SetData` action.
* Holds an typed array of entities to be added to the store.
*/
export interface NormalizeUpdateActionConfig<T>
extends NormalizeActionSchemaConfig {
/**
* The id of the entity to update
*/
id: NormalizeRemoveActionPayload['id'];
/**
* Data to set in the entity
*/
changes: Partial<T>;
}
/**
* Typed Interface for the config of the `AddChildData` action.
* Holds an typed array of entities to be added to the store.
*/
export interface NormalizeChildActionConfigBase<T>
extends NormalizeChildActionSchemaConfig {
/**
* The array of entities which should be normalized and added to the store.
*/
data: T[];
}
/**
* Interface for child data related actions
*/
export interface NormalizeChildActionPayload extends NormalizeActionPayload {
/**
* The id of the parent entity
*/
parentId: string;
/**
* Key of the parent's property which holds the child references
*/
parentProperty: string;
/**
* Schema key of the parent's property
*/
parentSchemaKey: string;
}
/**
* Interface for the payload of the `RemoveChildAction`
*/
export interface NormalizeRemoveChildActionPayload {
/**
* The id of the entity that should be removed
*/
id: NormalizeRemoveActionPayload['id'];
/**
* The key of the child schema
*/
childSchemaKey: string;
/**
* The id of the parent entity
*/
parentId: NormalizeChildActionPayload['parentId'];
/**
* Key of the parent's property which holds the child references
*/
parentProperty: NormalizeChildActionPayload['parentProperty'];
/**
* Schema key of the parent's property
*/
parentSchemaKey: NormalizeChildActionPayload['parentSchemaKey'];
}
/**
* Interface for the payload of the `RemoveData` action.
* Accepts an `id` and an optional `removeChildren` property.
*/
export interface NormalizeRemoveActionConfig
extends NormalizeActionSchemaConfig {
/**
* The id of the entity that should be removed
*/
id: NormalizeRemoveActionPayload['id'];
/**
* If maps valid schema keys to propety names,
* children referenced by the schema key will be removed by its id
*/
removeChildren?: NormalizeRemoveActionPayload['removeChildren'];
}
/**
* Interface for the payload of the `AddChildData` action.
*/
export interface NormalizeChildActionConfig<T>
extends NormalizeChildActionConfigBase<T> {
/**
* The schema of the child data to add
*/
childSchema: schema.Entity;
/**
* The id of the parent entity
*/
parentId: NormalizeChildActionPayload['parentId'];
}
/**
* Interface for the payload of the `RemoveData` action.
* Accepts an `id` and an optional `removeChildren` property.
*/
export interface NormalizeRemoveChildActionConfig
extends NormalizeChildActionSchemaConfig {
/**
* The id of the entity that should be removed
*/
id: NormalizeRemoveActionPayload['id'];
/**
* The schema of the child data to add
*/
childSchema: schema.Entity;
/**
* The id of the parent entity
*/
parentId: NormalizeChildActionPayload['parentId'];
}
/**
* Payload of the `UpdateAction`
*/
export interface NormalizeUpdateActionPayload<T> {
/**
* The id of the entity that should be removed
*/
id: NormalizeUpdateActionConfig<T>['id'];
/**
* Schema key of the entity to update
*/
key: string;
/**
* The data to set in the entity
*/
changes: EntityMap;
/**
* The original sorted id's as an array
*/
result: string[];
}
/**
* Interface for result for the `actionCreators` function
*/
export interface NormalizeActionCreators<T> {
/**
* Action creator for the `SetData` action
*/
setData: (data: NormalizeActionConfig<T>['data']) => SetData<T>;
/**
* Action creator for the `AddData` action
*/
addData: (data: NormalizeActionConfig<T>['data']) => AddData<T>;
/**
* Action creator for the `AddChildData` action
*/
addChildData: <C>(
data: NormalizeChildActionConfig<C>['data'],
childSchema: NormalizeChildActionConfig<C>['childSchema'],
parentId: NormalizeChildActionConfig<C>['parentId']
) => AddChildData<C>;
/**
* Action creator for the `AddChildData` action
*/
updateData: (
id: NormalizeUpdateActionConfig<T>['id'],
changes: NormalizeUpdateActionConfig<T>['changes']
) => UpdateData<T>;
/**
* Action creator for the `removeData` action
*/
removeData: (
id: NormalizeRemoveActionConfig['id'],
removeChildren?: NormalizeRemoveActionConfig['removeChildren']
) => RemoveData;
/**
* Action creator for the `AddChildData` action
*/
removeChildData: (
id: NormalizeRemoveChildActionConfig['id'],
childSchema: NormalizeRemoveChildActionConfig['childSchema'],
parentId: NormalizeRemoveChildActionConfig['parentId']
) => RemoveChildData;
}
/**
* All types of the provided actions.
*/
export class NormalizeActionTypes {
/**
* Action type of the `SetData` action.
*/
static readonly SET_DATA = `${ACTION_NAMESPACE} Set Data`;
/**
* Action type of the `AddData` action.
*/
static readonly ADD_DATA = `${ACTION_NAMESPACE} Add Data`;
/**
* Action type of the `AddChildData` action.
*/
static readonly ADD_CHILD_DATA = `${ACTION_NAMESPACE} Add Child Data`;
/**
* Action type of the `UpdateData` action
*/
static readonly UPDATE_DATA = `${ACTION_NAMESPACE} Update Data`;
/**
* Action type of the `RemoveData` action.
*/
static readonly REMOVE_DATA = `${ACTION_NAMESPACE} Remove Data`;
/**
* Action type of the `RemoveChildData` action.
*/
static readonly REMOVE_CHILD_DATA = `${ACTION_NAMESPACE} Remove Child Data`;
}
/**
* Action for settings denormalized entities in the store.
* Also see `NormalizeDataPayload`.
*/
export class SetData<T> implements Action {
/**
* The action type: `NormalizeActionTypes.SET_DATA`
*/
readonly type = NormalizeActionTypes.SET_DATA;
/**
* The payload will be an object of the normalized entity map as `entities`
* and the original sorted id's as an array in the `result` property.
*/
public payload: NormalizeActionPayload;
/**
* SetData Constructor
* @param config The action config object
*/
constructor(config: NormalizeActionConfig<T>) {
this.payload = normalize(config.data, [config.schema]);
}
}
/**
* Action for adding/updating data to the store.
* Also see `NormalizeDataPayload`.
*/
export class AddData<T> implements Action {
/**
* The action type: `NormalizeActionTypes.ADD_DATA`
*/
readonly type = NormalizeActionTypes.ADD_DATA;
/**
* The payload will be an object of the normalized entity map as `entities`
* and the original sorted id's as an array in the `result` property.
*/
public payload: NormalizeActionPayload;
/**
* AddData Constructor
* @param config The action config object
*/
constructor(config: NormalizeActionConfig<T>) {
this.payload = normalize(config.data, [config.schema]);
}
}
/**
* Action for adding/updating data to the store.
* Also see `NormalizeDataPayload`.
*/
export class AddChildData<T> implements Action {
/**
* The action type: `NormalizeActionTypes.ADD_CHILD_DATA`
*/
readonly type = NormalizeActionTypes.ADD_CHILD_DATA;
/**
* The payload will be an object of the normalized entity map as `entities`
* and the original sorted id's as an array in the `result` property.
*/
public payload: NormalizeChildActionPayload;
/**
* AddData Constructor
* @param config The action config object
*/
constructor(config: NormalizeChildActionConfig<T>) {
const { data, parentSchema, parentId, childSchema } = config;
this.payload = {
...(normalize(data, [childSchema]) as NormalizeActionPayload),
parentSchemaKey: parentSchema.key,
parentProperty: getRelationProperty(parentSchema, childSchema),
parentId
};
}
}
/**
* Action for adding/updating data to the store.
* Also see `NormalizeDataPayload`.
*/
export class UpdateData<T> implements Action {
/**
* The action type: `NormalizeActionTypes.UPDATE_DATA`
*/
readonly type = NormalizeActionTypes.UPDATE_DATA;
/**
* The payload will be an object of the normalized entity map as `entities`
* and the original sorted id's as an array in the `result` property.
*/
public payload: NormalizeUpdateActionPayload<T>;
/**
* AddData Constructor
* @param config The action config object
*/
constructor(config: NormalizeUpdateActionConfig<T>) {
const { id, schema, changes } = config;
(changes as any)[(schema as any)._idAttribute] = id;
const normalized = normalize([config.changes], [config.schema]);
this.payload = {
id,
key: schema.key,
changes: normalized.entities,
result: normalized.result
};
}
}
/**
* Action for removing data from the store.
* Also see `NormalizeRemovePayload`.
*/
export class RemoveData implements Action {
/**
* The action type: `NormalizeActionTypes.REMOVE_DATA`
*/
readonly type = NormalizeActionTypes.REMOVE_DATA;
/**
* The payload will be an object of the normalized entity map as `entities`
* and the original sorted id's as an array in the `result` property.
*/
public payload: NormalizeRemoveActionPayload;
/**
* RemoveData Constructor
* @param payload The action payload used in the reducer
*/
constructor(config: NormalizeRemoveActionConfig) {
let { id, removeChildren, schema } = config;
let removeMap: SchemaMap = null;
// cleanup removeChildren object by setting only existing
// properties to removeMap
if (removeChildren && (schema as any).schema) {
removeMap = Object.entries(removeChildren).reduce(
(p: any, [key, entityProperty]: [string, string]) => {
if (entityProperty in (schema as any).schema) {
p[key] = entityProperty;
}
return p;
},
{}
);
}
this.payload = {
id,
key: schema.key,
removeChildren:
removeMap && Object.keys(removeMap).length ? removeMap : null
};
}
}
/**
* Action for removing data from the store.
* Also see `NormalizeRemovePayload`.
*/
export class RemoveChildData implements Action {
/**
* The action type: `NormalizeActionTypes.REMOVE_CHILD_DATA`
*/
readonly type = NormalizeActionTypes.REMOVE_CHILD_DATA;
/**
* The payload will be an object of the normalized entity map as `entities`
* and the original sorted id's as an array in the `result` property.
*/
public payload: NormalizeRemoveChildActionPayload;
/**
* RemoveData Constructor
* @param payload The action payload used in the reducer
*/
constructor(config: NormalizeRemoveChildActionConfig) {
let { id, parentSchema, childSchema, parentId } = config;
this.payload = {
id,
childSchemaKey: childSchema.key,
parentProperty: getRelationProperty(parentSchema, childSchema),
parentSchemaKey: parentSchema.key,
parentId
};
}
}
/**
* Create a add of action creators for the `AddData` and `RemoveData` actions.
* This is provided for convenience.
* @param schema The schema the action creators should be bound to
*/
export function actionCreators<T>(
schema: schema.Entity
): NormalizeActionCreators<T> {
return {
/**
* Action creator for the `SetData` action.
* @returns A new instance of the `SetData` action with the given schema.
*/
setData: (data: NormalizeActionConfig<T>['data']) =>
new SetData<T>({ data, schema }),
/**
* Action creator for the `AddData` action.
* @returns A new instance of the `AddData` action with the given schema.
*/
addData: (data: NormalizeActionConfig<T>['data']) =>
new AddData<T>({ data, schema }),
/**
* Action creator for the `AddChildData` action.
* @returns A new instance of the `AddChildData` action with the given schema.
*/
addChildData: <C>(
data: NormalizeChildActionConfig<C>['data'],
childSchema: NormalizeChildActionConfig<C>['childSchema'],
parentId: NormalizeChildActionConfig<C>['parentId']
) =>
new AddChildData<C>({
data,
parentSchema: schema,
childSchema,
parentId
}),
/**
* Action creator for the `UpdateData` action.
* @returns A new instance of the `UpdateData` action with the given schema.
*/
updateData: (
id: NormalizeUpdateActionConfig<T>['id'],
changes: NormalizeUpdateActionConfig<T>['changes']
) => new UpdateData({ id, schema, changes }),
/**
* Action creator for the `RemoveData` action.
* @returns A new instance of the `RemoveData` action with the given schema.
*/
removeData: (
id: NormalizeRemoveActionConfig['id'],
removeChildren?: NormalizeRemoveActionConfig['removeChildren']
) => new RemoveData({ id, schema, removeChildren }),
/**
* Action creator for the `RemoveChildData` action.
* @returns A new instance of the `RemoveChildData` action with the given schema.
*/
removeChildData: (
id: NormalizeRemoveChildActionConfig['id'],
childSchema: NormalizeRemoveChildActionConfig['childSchema'],
parentId: NormalizeRemoveChildActionConfig['parentId']
) =>
new RemoveChildData({ id, parentSchema: schema, childSchema, parentId })
};
}
/**
* Return the parents property name the child schema is related to
* @param schema The parent schema
* @param childSchema The child schema
*/
function getRelationProperty(
schema: schema.Entity,
childSchema: schema.Entity
): string {
let parentProperty = null;
const relations: {
[key: string]: schema.Entity | [schema.Entity];
} = (schema as any).schema;
/* istanbul ignore else */
if (relations) {
Object.keys(relations).some(k => {
let key = Array.isArray(relations[k])
? (relations[k] as [schema.Entity])[0].key
: (relations[k] as schema.Entity).key;
/* istanbul ignore else */
if (key === childSchema.key) {
parentProperty = k;
return true;
}
});
}
return parentProperty;
} | the_stack |
/**
* @license Copyright © 2013 onwards, Andrew Whewell
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @fileoverview A jQueryUI plugin that can display a list of flight/aircraft data for a report.
*/
namespace VRS
{
/*
* Global options
*/
export var globalOptions: GlobalOptions = VRS.globalOptions || {};
VRS.globalOptions.reportDetailClass = VRS.globalOptions.reportDetailClass || 'vrsAircraftDetail aircraft'; // The CSS class to attach to the report detail panel.
VRS.globalOptions.reportDetailColumns = VRS.globalOptions.reportDetailColumns || [ // The default columns to show in the detail panel.
VRS.ReportAircraftProperty.Country,
VRS.ReportAircraftProperty.Engines,
VRS.ReportAircraftProperty.WakeTurbulenceCategory,
VRS.ReportAircraftProperty.Species,
VRS.ReportAircraftProperty.SerialNumber,
VRS.ReportAircraftProperty.OperatorIcao,
VRS.ReportAircraftProperty.AircraftClass,
VRS.ReportAircraftProperty.CofACategory,
VRS.ReportAircraftProperty.CofAExpiry,
VRS.ReportAircraftProperty.CurrentRegDate,
VRS.ReportAircraftProperty.DeRegDate,
VRS.ReportAircraftProperty.FirstRegDate,
VRS.ReportAircraftProperty.GenericName,
VRS.ReportAircraftProperty.Interesting,
VRS.ReportAircraftProperty.Manufacturer,
VRS.ReportAircraftProperty.MTOW,
VRS.ReportAircraftProperty.Notes,
VRS.ReportAircraftProperty.OwnershipStatus,
VRS.ReportAircraftProperty.PopularName,
VRS.ReportAircraftProperty.PreviousId,
VRS.ReportAircraftProperty.Status,
VRS.ReportAircraftProperty.TotalHours,
VRS.ReportAircraftProperty.YearBuilt,
VRS.ReportFlightProperty.RouteFull,
VRS.ReportAircraftProperty.Picture,
VRS.ReportFlightProperty.StartTime,
VRS.ReportFlightProperty.EndTime,
VRS.ReportFlightProperty.Duration,
VRS.ReportFlightProperty.Altitude,
VRS.ReportFlightProperty.FlightLevel,
VRS.ReportFlightProperty.Speed,
VRS.ReportFlightProperty.Squawk,
VRS.ReportFlightProperty.HadEmergency,
VRS.ReportFlightProperty.HadAlert,
VRS.ReportFlightProperty.HadSPI,
VRS.ReportFlightProperty.CountModeS,
VRS.ReportFlightProperty.CountAdsb,
VRS.ReportFlightProperty.CountPositions
];
VRS.globalOptions.reportDetailAddMapToDefaultColumns = VRS.globalOptions.reportDetailAddMapToDefaultColumns !== undefined ? VRS.globalOptions.reportDetailAddMapToDefaultColumns : VRS.globalOptions.isMobile; // True if the map should be added to the default columns
if(VRS.globalOptions.reportDetailAddMapToDefaultColumns) {
if(VRS.arrayHelper.indexOf(VRS.globalOptions.reportDetailColumns, VRS.ReportFlightProperty.PositionsOnMap) === -1) {
VRS.globalOptions.reportDetailColumns.push(VRS.ReportFlightProperty.PositionsOnMap);
}
}
VRS.globalOptions.reportDetailDefaultShowUnits = VRS.globalOptions.reportDetailDefaultShowUnits !== undefined ? VRS.globalOptions.reportDetailDefaultShowUnits : true; // True if the detail panel should show units by default.
VRS.globalOptions.reportDetailDistinguishOnGround = VRS.globalOptions.reportDetailDistinguishOnGround !== undefined ? VRS.globalOptions.reportDetailDistinguishOnGround : true; // True if the detail panel should show GND for aircraft that are on the ground.
VRS.globalOptions.reportDetailUserCanConfigureColumns = VRS.globalOptions.reportDetailUserCanConfigureColumns !== undefined ? VRS.globalOptions.reportDetailUserCanConfigureColumns : true; // True if the user is allowed to configure which values are shown in the detail panel.
VRS.globalOptions.reportDetailDefaultShowEmptyValues = VRS.globalOptions.reportDetailDefaultShowEmptyValues !== undefined ? VRS.globalOptions.reportDetailDefaultShowEmptyValues : false; // True if empty values are to be shown.
VRS.globalOptions.reportDetailShowAircraftLinks = VRS.globalOptions.reportDetailShowAircraftLinks !== undefined ? VRS.globalOptions.reportDetailShowAircraftLinks : true; // True if links should be shown for the aircraft in the aircraft detail panel
VRS.globalOptions.reportDetailShowSeparateRouteLink = VRS.globalOptions.reportDetailShowSeparateRouteLink !== undefined ? VRS.globalOptions.reportDetailShowSeparateRouteLink : true; // Show a separate link to add or correct routes
/**
* The options that can be passed when creating a new ReportDetailPlugin
*/
export interface ReportDetailPlugin_Options extends ReportRender_Options
{
/**
* The name to use when saving and loading state.
*/
name?: string;
/**
* The report whose selected flight is going to be displayed in the panel.
*/
report: Report;
/**
* The VRS.UnitDisplayPreferences that dictate how values are to be displayed.
*/
unitDisplayPreferences: UnitDisplayPreferences;
/**
* The plotter options to use with map widgets.
*/
plotterOptions?: AircraftPlotterOptions;
/**
* The columns to display.
*/
columns?: ReportAircraftOrFlightPropertyEnum[];
/**
* True if the state last saved by the user against name should be loaded and applied immediately when creating the control.
*/
useSavedState?: boolean;
/**
* True if heights, distances and speeds should indicate their units.
*/
showUnits?: boolean;
/**
* True if empty values are to be shown.
*/
showEmptyValues?: boolean;
/**
* True if altitudes should distinguish between altitudes of zero and aircraft on the ground.
*/
distinguishOnGround?: boolean;
}
/**
* The settings saved between sessions by the ReportDetailPlugin.
*/
export interface ReportDetailPlugin_SaveState
{
columns: ReportAircraftOrFlightPropertyEnum[];
showUnits: boolean;
showEmptyValues: boolean;
}
/**
* Holds the state associated with a report detail panel.
*/
class ReportDetailPlugin_State
{
/**
* True if the control has been suspended because it is no longer in view, false if it's active.
*/
suspended = false;
/**
* The element that all of the content is rendered into.
*/
containerElement: JQuery = null;
/**
* The element that the header is rendered into.
*/
headerElement: JQuery = null;
/**
* The element that the body is rendered into.
*/
bodyElement: JQuery = null;
/**
* A jQuery element for the links.
*/
linksContainer: JQuery = undefined;
/**
* The flight whose details are currently on display.
*/
displayedFlight: IReportFlight;
/**
* An associative array of VRS_REPORT_PROPERTY properties against the jQuery element created for their display
* in the body.
* @type {Object.<VRS_REPORT_PROPERTY, jQuery>}
*/
bodyPropertyElements: { [index: string /* ReportAircraftPropertyEnum */]: JQuery } = {};
/**
* A direct reference to the plugin for standard aircraft links.
*/
aircraftLinksPlugin: AircraftLinksPlugin = null;
/**
* A direct reference to the plugin for links to the routes submission site.
*/
routeLinksPlugin: AircraftLinksPlugin = null;
/**
* The hook result for the selected flight changed event.
*/
selectedFlightChangedHookResult: IEventHandle = null;
/**
* The hook result for the locale changed event.
*/
localeChangedHookResult: IEventHandle = null;
}
/*
* jQueryUIHelper methods
*/
export var jQueryUIHelper: JQueryUIHelper = VRS.jQueryUIHelper || {};
VRS.jQueryUIHelper.getReportDetailPlugin = function(jQueryElement: JQuery) : ReportDetailPlugin
{
return jQueryElement.data('vrsVrsReportDetail');
}
VRS.jQueryUIHelper.getReportDetailOptions = function(overrides?: ReportDetailPlugin_Options) : ReportDetailPlugin_Options
{
return $.extend({
name: 'default',
columns: VRS.globalOptions.reportDetailColumns.slice(),
useSavedState: true,
showUnits: VRS.globalOptions.reportDetailDefaultShowUnits,
showEmptyValues: VRS.globalOptions.reportDetailDefaultShowEmptyValues,
distinguishOnGround: VRS.globalOptions.reportDetailDistinguishOnGround
}, overrides);
}
/**
* A jQuery UI widget that can display the detail for a single flight.
*/
export class ReportDetailPlugin extends JQueryUICustomWidget implements ISelfPersist<ReportDetailPlugin_SaveState>
{
options: ReportDetailPlugin_Options;
constructor()
{
super();
this.options = VRS.jQueryUIHelper.getReportDetailOptions();
}
private _getState() : ReportDetailPlugin_State
{
var result = this.element.data('reportDetailPanelState');
if(result === undefined) {
result = new ReportDetailPlugin_State();
this.element.data('reportDetailPanelState', result);
}
return result;
}
_create()
{
var state = this._getState();
var options = this.options;
if(options.useSavedState) {
this.loadAndApplyState();
}
this._displayFlightDetails(state, options.report.getSelectedFlight());
VRS.globalisation.hookLocaleChanged(this._localeChanged, this);
state.selectedFlightChangedHookResult = options.report.hookSelectedFlightCHanged(this._selectedFlightChanged, this);
}
_destroy()
{
var state = this._getState();
var options = this.options;
if(state.selectedFlightChangedHookResult && options.report) {
options.report.unhook(state.selectedFlightChangedHookResult);
}
state.selectedFlightChangedHookResult = null;
if(state.localeChangedHookResult && VRS.globalisation) {
VRS.globalisation.unhook(state.localeChangedHookResult);
}
state.localeChangedHookResult = null;
if(state.aircraftLinksPlugin) {
state.aircraftLinksPlugin.destroy();
}
state.linksContainer.empty();
state.displayedFlight = null;
this._destroyDisplay(state);
}
/**
* Saves the current state of the object.
*/
saveState()
{
VRS.configStorage.save(this._persistenceKey(), this._createSettings());
}
/**
* Loads the previously saved state of the object or the current state if it's never been saved.
*/
loadState() : ReportDetailPlugin_SaveState
{
var savedSettings = VRS.configStorage.load(this._persistenceKey(), {});
var result = $.extend(this._createSettings(), savedSettings);
result.columns = VRS.reportPropertyHandlerHelper.buildValidReportPropertiesList(result.columns, [ VRS.ReportSurface.DetailBody ]);
return result;
}
/**
* Applies a previously saved state to the object.
* @param {VRS_STATE_REPORTDETAILPANEL} settings
*/
applyState(settings: ReportDetailPlugin_SaveState)
{
this.options.columns = settings.columns;
this.options.showUnits = settings.showUnits;
this.options.showEmptyValues = settings.showEmptyValues;
}
/**
* Loads and then applies a previousy saved state to the object.
*/
loadAndApplyState()
{
this.applyState(this.loadState());
}
/**
* Returns the key under which the state will be saved.
*/
private _persistenceKey() : string
{
return 'vrsReportDetailPanel-' + this.options.report.getName() + '-' + this.options.name;
}
/**
* Creates the saved state object.
*/
private _createSettings() : ReportDetailPlugin_SaveState
{
return {
columns: this.options.columns,
showUnits: this.options.showUnits,
showEmptyValues: this.options.showEmptyValues
};
}
/**
* Returns the option pane that can be used to configure the widget via the UI.
*/
createOptionPane(displayOrder: number) : OptionPane
{
var result = new VRS.OptionPane({
name: 'vrsReportDetailPane-' + this.options.name + '_Settings',
titleKey: 'DetailPanel',
displayOrder: displayOrder,
fields: [
new VRS.OptionFieldCheckBox({
name: 'showUnits',
labelKey: 'ShowUnits',
getValue: () => this.options.showUnits,
setValue: (value) => {
this.options.showUnits = value;
this.refreshDisplay();
},
saveState: () => this.saveState()
}),
new VRS.OptionFieldCheckBox({
name: 'showEmptyValues',
labelKey: 'ShowEmptyValues',
getValue: () => this.options.showEmptyValues,
setValue: (value) => {
this.options.showEmptyValues = value;
this.refreshDisplay();
},
saveState: () => this.saveState()
})
]
});
if(VRS.globalOptions.reportDetailUserCanConfigureColumns) {
VRS.reportPropertyHandlerHelper.addReportPropertyListOptionsToPane({
pane: result,
fieldLabel: 'Columns',
surface: VRS.ReportSurface.DetailBody,
getList: () => this.options.columns,
setList: (cols) => {
this.options.columns = cols;
this.refreshDisplay();
},
saveState: () => this.saveState()
});
}
return result;
}
/**
* Suspends or actives the control.
*/
suspend(onOff: boolean)
{
onOff = !!onOff;
var state = this._getState();
if(state.suspended !== onOff) {
state.suspended = onOff;
if(!state.suspended) this.refreshDisplay();
}
}
/**
* Displays the details for the flight passed across.
*/
private _displayFlightDetails(state: ReportDetailPlugin_State, flight: IReportFlight)
{
state.displayedFlight = flight;
if(!state.suspended) {
this._destroyDisplay(state);
if(flight) {
state.containerElement = $('<div/>')
.addClass(VRS.globalOptions.reportDetailClass)
.appendTo(this.element);
this._createHeader(state, flight);
this._createBody(state, flight);
this._createLinks(state, flight);
}
}
}
/**
* Redraws the displayed flight.
*/
refreshDisplay()
{
var state = this._getState();
this._displayFlightDetails(state, state.displayedFlight);
}
/**
* Destroys the UI associated with the display.
*/
private _destroyDisplay(state: ReportDetailPlugin_State)
{
for(var propertyName in state.bodyPropertyElements) {
var handler = VRS.reportPropertyHandlers[propertyName];
var element = state.bodyPropertyElements[propertyName];
if(handler && element) {
handler.destroyWidgetInJQueryElement(element, VRS.ReportSurface.DetailBody);
}
}
state.bodyPropertyElements = {};
if(state.bodyElement) {
state.bodyElement.remove();
}
state.bodyElement = null;
if(state.headerElement) {
state.headerElement.remove();
}
state.headerElement = null;
if(state.aircraftLinksPlugin) {
state.aircraftLinksPlugin.destroy();
}
if(state.routeLinksPlugin) {
state.routeLinksPlugin.destroy();
}
if(state.linksContainer) {
state.linksContainer.empty();
state.linksContainer.remove();
}
state.linksContainer = null;
if(state.containerElement) {
state.containerElement.remove();
}
state.containerElement = null;
}
/**
* Creates and populates the header showing the important details about the flight. This is not configurable.
*/
private _createHeader(state: ReportDetailPlugin_State, flight: IReportFlight)
{
state.headerElement = $('<div/>')
.addClass('header')
.appendTo(state.containerElement);
var table = $('<table/>')
.appendTo(state.headerElement);
var row1 = $('<tr/>').appendTo(table);
this._addHeaderCell(state, row1, 1, flight, VRS.ReportAircraftProperty.Registration, 'reg');
this._addHeaderCell(state, row1, 1, flight, VRS.ReportAircraftProperty.Icao, 'icao');
this._addHeaderCell(state, row1, 1, flight, VRS.ReportAircraftProperty.OperatorFlag, 'flag');
var row2 = $('<tr/>').appendTo(table);
this._addHeaderCell(state, row2, 2, flight, VRS.ReportAircraftProperty.Operator, 'op');
this._addHeaderCell(state, row2, 1, flight, VRS.ReportFlightProperty.Callsign, 'callsign');
var row3 = $('<tr/>').appendTo(table);
this._addHeaderCell(state, row3, 2, flight, VRS.ReportAircraftProperty.ModeSCountry, 'country');
this._addHeaderCell(state, row3, 1, flight, VRS.ReportAircraftProperty.Military, 'military');
var row4 = $('<tr/>').appendTo(table);
this._addHeaderCell(state, row4, 2, flight, VRS.ReportAircraftProperty.Model, 'model');
this._addHeaderCell(state, row4, 1, flight, VRS.ReportAircraftProperty.ModelIcao, 'modelType');
}
/**
* Adds a cell to a row in the header table.
*/
private _addHeaderCell(state: ReportDetailPlugin_State, row: JQuery, colspan: number, flight: IReportFlight, property: ReportAircraftOrFlightPropertyEnum, classes: string)
{
var cell = $('<td/>')
.addClass(classes)
.appendTo(row);
if(colspan > 1) cell.attr('colspan', colspan);
var handler = VRS.reportPropertyHandlers[property];
if(!handler) throw 'Cannot find the handler for the ' + property + ' property';
handler.renderIntoJQueryElement(cell, handler.isAircraftProperty ? flight.aircraft : flight, this.options, VRS.ReportSurface.DetailHead);
}
/**
* Creates and populates the body of the detail panel.
*/
private _createBody(state: ReportDetailPlugin_State, flight: IReportFlight)
{
var options = this.options;
var columns = options.columns;
state.bodyElement = $('<div/>')
.addClass('body')
.appendTo(state.containerElement);
var list = $('<ul/>')
.appendTo(state.bodyElement);
var length = columns.length;
for(var i = 0;i < length;++i) {
var property = columns[i];
var handler = VRS.reportPropertyHandlers[property];
if(handler && (options.showEmptyValues || handler.hasValue(flight))) {
var suppressLabel = handler.suppressLabelCallback(VRS.ReportSurface.DetailBody);
var listItem = $('<li/>')
.appendTo(list);
if(suppressLabel) {
// We want an empty label here so that the print media CSS can reserve space for it
$('<div/>')
.addClass('noLabel')
.appendTo(listItem);
} else {
$('<div/>')
.addClass('label')
.append($('<span/>')
.text(VRS.globalisation.getText(handler.labelKey) + ':')
)
.appendTo(listItem);
}
var contentContainer = $('<div/>')
.addClass('content')
.appendTo(listItem);
var content = $('<span/>')
.appendTo(contentContainer);
if(suppressLabel) {
listItem.addClass('wide');
contentContainer.addClass('wide');
}
if(handler.isMultiLine) {
listItem.addClass('multiline');
contentContainer.addClass('multiline');
}
state.bodyPropertyElements[property] = content;
var json = handler.isAircraftProperty ? flight.aircraft : flight;
handler.createWidgetInJQueryElement(content, VRS.ReportSurface.DetailBody, options);
handler.renderIntoJQueryElement(content, json, options, VRS.ReportSurface.DetailBody);
}
}
}
/**
* Creates the links panel for the flight.
*/
private _createLinks(state: ReportDetailPlugin_State, flight: IReportFlight)
{
if(VRS.globalOptions.reportDetailShowAircraftLinks) {
state.linksContainer =
$('<div/>')
.addClass('links')
.appendTo(state.containerElement);
var aircraftLinksElement = $('<div/>')
.appendTo(state.linksContainer)
.vrsAircraftLinks();
state.aircraftLinksPlugin = VRS.jQueryUIHelper.getAircraftLinksPlugin(aircraftLinksElement);
var aircraft = Report.convertFlightToVrsAircraft(flight, true);
state.aircraftLinksPlugin.renderForAircraft(aircraft, true);
var routeLinks: (LinkSiteEnum | LinkRenderHandler)[] = [];
if(VRS.globalOptions.reportDetailShowSeparateRouteLink) {
routeLinks.push(VRS.LinkSite.StandingDataMaintenance);
}
if(routeLinks.length > 0) {
var routeLinksElement = $('<div/>')
.appendTo(state.linksContainer)
.vrsAircraftLinks({
linkSites: routeLinks
});
state.routeLinksPlugin = VRS.jQueryUIHelper.getAircraftLinksPlugin(routeLinksElement);
state.routeLinksPlugin.renderForAircraft(aircraft, true);
}
}
}
/**
* Called when the user chooses another language.
*/
private _localeChanged()
{
this.refreshDisplay();
}
/**
* Called when the selected flight changes.
*/
private _selectedFlightChanged()
{
var selectedFlight = this.options.report.getSelectedFlight();
this._displayFlightDetails(this._getState(), selectedFlight);
}
}
$.widget('vrs.vrsReportDetail', new ReportDetailPlugin());
}
declare interface JQuery
{
vrsReportDetail();
vrsReportDetail(options: VRS.ReportDetailPlugin_Options);
vrsReportDetail(methodName: string, param1?: any, param2?: any, param3?: any, param4?: any);
} | the_stack |
import {
ArrayGetNullOptionalParams,
ArrayGetNullResponse,
ArrayGetInvalidOptionalParams,
ArrayGetInvalidResponse,
ArrayGetEmptyOptionalParams,
ArrayGetEmptyResponse,
ArrayPutEmptyOptionalParams,
ArrayGetBooleanTfftOptionalParams,
ArrayGetBooleanTfftResponse,
ArrayPutBooleanTfftOptionalParams,
ArrayGetBooleanInvalidNullOptionalParams,
ArrayGetBooleanInvalidNullResponse,
ArrayGetBooleanInvalidStringOptionalParams,
ArrayGetBooleanInvalidStringResponse,
ArrayGetIntegerValidOptionalParams,
ArrayGetIntegerValidResponse,
ArrayPutIntegerValidOptionalParams,
ArrayGetIntInvalidNullOptionalParams,
ArrayGetIntInvalidNullResponse,
ArrayGetIntInvalidStringOptionalParams,
ArrayGetIntInvalidStringResponse,
ArrayGetLongValidOptionalParams,
ArrayGetLongValidResponse,
ArrayPutLongValidOptionalParams,
ArrayGetLongInvalidNullOptionalParams,
ArrayGetLongInvalidNullResponse,
ArrayGetLongInvalidStringOptionalParams,
ArrayGetLongInvalidStringResponse,
ArrayGetFloatValidOptionalParams,
ArrayGetFloatValidResponse,
ArrayPutFloatValidOptionalParams,
ArrayGetFloatInvalidNullOptionalParams,
ArrayGetFloatInvalidNullResponse,
ArrayGetFloatInvalidStringOptionalParams,
ArrayGetFloatInvalidStringResponse,
ArrayGetDoubleValidOptionalParams,
ArrayGetDoubleValidResponse,
ArrayPutDoubleValidOptionalParams,
ArrayGetDoubleInvalidNullOptionalParams,
ArrayGetDoubleInvalidNullResponse,
ArrayGetDoubleInvalidStringOptionalParams,
ArrayGetDoubleInvalidStringResponse,
ArrayGetStringValidOptionalParams,
ArrayGetStringValidResponse,
ArrayPutStringValidOptionalParams,
ArrayGetEnumValidOptionalParams,
ArrayGetEnumValidResponse,
FooEnum,
ArrayPutEnumValidOptionalParams,
ArrayGetStringEnumValidOptionalParams,
ArrayGetStringEnumValidResponse,
Enum1,
ArrayPutStringEnumValidOptionalParams,
ArrayGetStringWithNullOptionalParams,
ArrayGetStringWithNullResponse,
ArrayGetStringWithInvalidOptionalParams,
ArrayGetStringWithInvalidResponse,
ArrayGetUuidValidOptionalParams,
ArrayGetUuidValidResponse,
ArrayPutUuidValidOptionalParams,
ArrayGetUuidInvalidCharsOptionalParams,
ArrayGetUuidInvalidCharsResponse,
ArrayGetDateValidOptionalParams,
ArrayGetDateValidResponse,
ArrayPutDateValidOptionalParams,
ArrayGetDateInvalidNullOptionalParams,
ArrayGetDateInvalidNullResponse,
ArrayGetDateInvalidCharsOptionalParams,
ArrayGetDateInvalidCharsResponse,
ArrayGetDateTimeValidOptionalParams,
ArrayGetDateTimeValidResponse,
ArrayPutDateTimeValidOptionalParams,
ArrayGetDateTimeInvalidNullOptionalParams,
ArrayGetDateTimeInvalidNullResponse,
ArrayGetDateTimeInvalidCharsOptionalParams,
ArrayGetDateTimeInvalidCharsResponse,
ArrayGetDateTimeRfc1123ValidOptionalParams,
ArrayGetDateTimeRfc1123ValidResponse,
ArrayPutDateTimeRfc1123ValidOptionalParams,
ArrayGetDurationValidOptionalParams,
ArrayGetDurationValidResponse,
ArrayPutDurationValidOptionalParams,
ArrayGetByteValidOptionalParams,
ArrayGetByteValidResponse,
ArrayPutByteValidOptionalParams,
ArrayGetByteInvalidNullOptionalParams,
ArrayGetByteInvalidNullResponse,
ArrayGetBase64UrlOptionalParams,
ArrayGetBase64UrlResponse,
ArrayGetComplexNullOptionalParams,
ArrayGetComplexNullResponse,
ArrayGetComplexEmptyOptionalParams,
ArrayGetComplexEmptyResponse,
ArrayGetComplexItemNullOptionalParams,
ArrayGetComplexItemNullResponse,
ArrayGetComplexItemEmptyOptionalParams,
ArrayGetComplexItemEmptyResponse,
ArrayGetComplexValidOptionalParams,
ArrayGetComplexValidResponse,
Product,
ArrayPutComplexValidOptionalParams,
ArrayGetArrayNullOptionalParams,
ArrayGetArrayNullResponse,
ArrayGetArrayEmptyOptionalParams,
ArrayGetArrayEmptyResponse,
ArrayGetArrayItemNullOptionalParams,
ArrayGetArrayItemNullResponse,
ArrayGetArrayItemEmptyOptionalParams,
ArrayGetArrayItemEmptyResponse,
ArrayGetArrayValidOptionalParams,
ArrayGetArrayValidResponse,
ArrayPutArrayValidOptionalParams,
ArrayGetDictionaryNullOptionalParams,
ArrayGetDictionaryNullResponse,
ArrayGetDictionaryEmptyOptionalParams,
ArrayGetDictionaryEmptyResponse,
ArrayGetDictionaryItemNullOptionalParams,
ArrayGetDictionaryItemNullResponse,
ArrayGetDictionaryItemEmptyOptionalParams,
ArrayGetDictionaryItemEmptyResponse,
ArrayGetDictionaryValidOptionalParams,
ArrayGetDictionaryValidResponse,
ArrayPutDictionaryValidOptionalParams
} from "../models";
/** Interface representing a Array. */
export interface Array {
/**
* Get null array value
* @param options The options parameters.
*/
getNull(options?: ArrayGetNullOptionalParams): Promise<ArrayGetNullResponse>;
/**
* Get invalid array [1, 2, 3
* @param options The options parameters.
*/
getInvalid(
options?: ArrayGetInvalidOptionalParams
): Promise<ArrayGetInvalidResponse>;
/**
* Get empty array value []
* @param options The options parameters.
*/
getEmpty(
options?: ArrayGetEmptyOptionalParams
): Promise<ArrayGetEmptyResponse>;
/**
* Set array value empty []
* @param arrayBody The empty array value []
* @param options The options parameters.
*/
putEmpty(
arrayBody: string[],
options?: ArrayPutEmptyOptionalParams
): Promise<void>;
/**
* Get boolean array value [true, false, false, true]
* @param options The options parameters.
*/
getBooleanTfft(
options?: ArrayGetBooleanTfftOptionalParams
): Promise<ArrayGetBooleanTfftResponse>;
/**
* Set array value empty [true, false, false, true]
* @param arrayBody The array value [true, false, false, true]
* @param options The options parameters.
*/
putBooleanTfft(
arrayBody: boolean[],
options?: ArrayPutBooleanTfftOptionalParams
): Promise<void>;
/**
* Get boolean array value [true, null, false]
* @param options The options parameters.
*/
getBooleanInvalidNull(
options?: ArrayGetBooleanInvalidNullOptionalParams
): Promise<ArrayGetBooleanInvalidNullResponse>;
/**
* Get boolean array value [true, 'boolean', false]
* @param options The options parameters.
*/
getBooleanInvalidString(
options?: ArrayGetBooleanInvalidStringOptionalParams
): Promise<ArrayGetBooleanInvalidStringResponse>;
/**
* Get integer array value [1, -1, 3, 300]
* @param options The options parameters.
*/
getIntegerValid(
options?: ArrayGetIntegerValidOptionalParams
): Promise<ArrayGetIntegerValidResponse>;
/**
* Set array value empty [1, -1, 3, 300]
* @param arrayBody The array value [1, -1, 3, 300]
* @param options The options parameters.
*/
putIntegerValid(
arrayBody: number[],
options?: ArrayPutIntegerValidOptionalParams
): Promise<void>;
/**
* Get integer array value [1, null, 0]
* @param options The options parameters.
*/
getIntInvalidNull(
options?: ArrayGetIntInvalidNullOptionalParams
): Promise<ArrayGetIntInvalidNullResponse>;
/**
* Get integer array value [1, 'integer', 0]
* @param options The options parameters.
*/
getIntInvalidString(
options?: ArrayGetIntInvalidStringOptionalParams
): Promise<ArrayGetIntInvalidStringResponse>;
/**
* Get integer array value [1, -1, 3, 300]
* @param options The options parameters.
*/
getLongValid(
options?: ArrayGetLongValidOptionalParams
): Promise<ArrayGetLongValidResponse>;
/**
* Set array value empty [1, -1, 3, 300]
* @param arrayBody The array value [1, -1, 3, 300]
* @param options The options parameters.
*/
putLongValid(
arrayBody: number[],
options?: ArrayPutLongValidOptionalParams
): Promise<void>;
/**
* Get long array value [1, null, 0]
* @param options The options parameters.
*/
getLongInvalidNull(
options?: ArrayGetLongInvalidNullOptionalParams
): Promise<ArrayGetLongInvalidNullResponse>;
/**
* Get long array value [1, 'integer', 0]
* @param options The options parameters.
*/
getLongInvalidString(
options?: ArrayGetLongInvalidStringOptionalParams
): Promise<ArrayGetLongInvalidStringResponse>;
/**
* Get float array value [0, -0.01, 1.2e20]
* @param options The options parameters.
*/
getFloatValid(
options?: ArrayGetFloatValidOptionalParams
): Promise<ArrayGetFloatValidResponse>;
/**
* Set array value [0, -0.01, 1.2e20]
* @param arrayBody The array value [0, -0.01, 1.2e20]
* @param options The options parameters.
*/
putFloatValid(
arrayBody: number[],
options?: ArrayPutFloatValidOptionalParams
): Promise<void>;
/**
* Get float array value [0.0, null, -1.2e20]
* @param options The options parameters.
*/
getFloatInvalidNull(
options?: ArrayGetFloatInvalidNullOptionalParams
): Promise<ArrayGetFloatInvalidNullResponse>;
/**
* Get boolean array value [1.0, 'number', 0.0]
* @param options The options parameters.
*/
getFloatInvalidString(
options?: ArrayGetFloatInvalidStringOptionalParams
): Promise<ArrayGetFloatInvalidStringResponse>;
/**
* Get float array value [0, -0.01, 1.2e20]
* @param options The options parameters.
*/
getDoubleValid(
options?: ArrayGetDoubleValidOptionalParams
): Promise<ArrayGetDoubleValidResponse>;
/**
* Set array value [0, -0.01, 1.2e20]
* @param arrayBody The array value [0, -0.01, 1.2e20]
* @param options The options parameters.
*/
putDoubleValid(
arrayBody: number[],
options?: ArrayPutDoubleValidOptionalParams
): Promise<void>;
/**
* Get float array value [0.0, null, -1.2e20]
* @param options The options parameters.
*/
getDoubleInvalidNull(
options?: ArrayGetDoubleInvalidNullOptionalParams
): Promise<ArrayGetDoubleInvalidNullResponse>;
/**
* Get boolean array value [1.0, 'number', 0.0]
* @param options The options parameters.
*/
getDoubleInvalidString(
options?: ArrayGetDoubleInvalidStringOptionalParams
): Promise<ArrayGetDoubleInvalidStringResponse>;
/**
* Get string array value ['foo1', 'foo2', 'foo3']
* @param options The options parameters.
*/
getStringValid(
options?: ArrayGetStringValidOptionalParams
): Promise<ArrayGetStringValidResponse>;
/**
* Set array value ['foo1', 'foo2', 'foo3']
* @param arrayBody The array value ['foo1', 'foo2', 'foo3']
* @param options The options parameters.
*/
putStringValid(
arrayBody: string[],
options?: ArrayPutStringValidOptionalParams
): Promise<void>;
/**
* Get enum array value ['foo1', 'foo2', 'foo3']
* @param options The options parameters.
*/
getEnumValid(
options?: ArrayGetEnumValidOptionalParams
): Promise<ArrayGetEnumValidResponse>;
/**
* Set array value ['foo1', 'foo2', 'foo3']
* @param arrayBody The array value ['foo1', 'foo2', 'foo3']
* @param options The options parameters.
*/
putEnumValid(
arrayBody: FooEnum[],
options?: ArrayPutEnumValidOptionalParams
): Promise<void>;
/**
* Get enum array value ['foo1', 'foo2', 'foo3']
* @param options The options parameters.
*/
getStringEnumValid(
options?: ArrayGetStringEnumValidOptionalParams
): Promise<ArrayGetStringEnumValidResponse>;
/**
* Set array value ['foo1', 'foo2', 'foo3']
* @param arrayBody The array value ['foo1', 'foo2', 'foo3']
* @param options The options parameters.
*/
putStringEnumValid(
arrayBody: Enum1[],
options?: ArrayPutStringEnumValidOptionalParams
): Promise<void>;
/**
* Get string array value ['foo', null, 'foo2']
* @param options The options parameters.
*/
getStringWithNull(
options?: ArrayGetStringWithNullOptionalParams
): Promise<ArrayGetStringWithNullResponse>;
/**
* Get string array value ['foo', 123, 'foo2']
* @param options The options parameters.
*/
getStringWithInvalid(
options?: ArrayGetStringWithInvalidOptionalParams
): Promise<ArrayGetStringWithInvalidResponse>;
/**
* Get uuid array value ['6dcc7237-45fe-45c4-8a6b-3a8a3f625652',
* 'd1399005-30f7-40d6-8da6-dd7c89ad34db', 'f42f6aa1-a5bc-4ddf-907e-5f915de43205']
* @param options The options parameters.
*/
getUuidValid(
options?: ArrayGetUuidValidOptionalParams
): Promise<ArrayGetUuidValidResponse>;
/**
* Set array value ['6dcc7237-45fe-45c4-8a6b-3a8a3f625652', 'd1399005-30f7-40d6-8da6-dd7c89ad34db',
* 'f42f6aa1-a5bc-4ddf-907e-5f915de43205']
* @param arrayBody The array value ['6dcc7237-45fe-45c4-8a6b-3a8a3f625652',
* 'd1399005-30f7-40d6-8da6-dd7c89ad34db', 'f42f6aa1-a5bc-4ddf-907e-5f915de43205']
* @param options The options parameters.
*/
putUuidValid(
arrayBody: string[],
options?: ArrayPutUuidValidOptionalParams
): Promise<void>;
/**
* Get uuid array value ['6dcc7237-45fe-45c4-8a6b-3a8a3f625652', 'foo']
* @param options The options parameters.
*/
getUuidInvalidChars(
options?: ArrayGetUuidInvalidCharsOptionalParams
): Promise<ArrayGetUuidInvalidCharsResponse>;
/**
* Get integer array value ['2000-12-01', '1980-01-02', '1492-10-12']
* @param options The options parameters.
*/
getDateValid(
options?: ArrayGetDateValidOptionalParams
): Promise<ArrayGetDateValidResponse>;
/**
* Set array value ['2000-12-01', '1980-01-02', '1492-10-12']
* @param arrayBody The array value ['2000-12-01', '1980-01-02', '1492-10-12']
* @param options The options parameters.
*/
putDateValid(
arrayBody: Date[],
options?: ArrayPutDateValidOptionalParams
): Promise<void>;
/**
* Get date array value ['2012-01-01', null, '1776-07-04']
* @param options The options parameters.
*/
getDateInvalidNull(
options?: ArrayGetDateInvalidNullOptionalParams
): Promise<ArrayGetDateInvalidNullResponse>;
/**
* Get date array value ['2011-03-22', 'date']
* @param options The options parameters.
*/
getDateInvalidChars(
options?: ArrayGetDateInvalidCharsOptionalParams
): Promise<ArrayGetDateInvalidCharsResponse>;
/**
* Get date-time array value ['2000-12-01t00:00:01z', '1980-01-02T00:11:35+01:00',
* '1492-10-12T10:15:01-08:00']
* @param options The options parameters.
*/
getDateTimeValid(
options?: ArrayGetDateTimeValidOptionalParams
): Promise<ArrayGetDateTimeValidResponse>;
/**
* Set array value ['2000-12-01t00:00:01z', '1980-01-02T00:11:35+01:00', '1492-10-12T10:15:01-08:00']
* @param arrayBody The array value ['2000-12-01t00:00:01z', '1980-01-02T00:11:35+01:00',
* '1492-10-12T10:15:01-08:00']
* @param options The options parameters.
*/
putDateTimeValid(
arrayBody: Date[],
options?: ArrayPutDateTimeValidOptionalParams
): Promise<void>;
/**
* Get date array value ['2000-12-01t00:00:01z', null]
* @param options The options parameters.
*/
getDateTimeInvalidNull(
options?: ArrayGetDateTimeInvalidNullOptionalParams
): Promise<ArrayGetDateTimeInvalidNullResponse>;
/**
* Get date array value ['2000-12-01t00:00:01z', 'date-time']
* @param options The options parameters.
*/
getDateTimeInvalidChars(
options?: ArrayGetDateTimeInvalidCharsOptionalParams
): Promise<ArrayGetDateTimeInvalidCharsResponse>;
/**
* Get date-time array value ['Fri, 01 Dec 2000 00:00:01 GMT', 'Wed, 02 Jan 1980 00:11:35 GMT', 'Wed,
* 12 Oct 1492 10:15:01 GMT']
* @param options The options parameters.
*/
getDateTimeRfc1123Valid(
options?: ArrayGetDateTimeRfc1123ValidOptionalParams
): Promise<ArrayGetDateTimeRfc1123ValidResponse>;
/**
* Set array value ['Fri, 01 Dec 2000 00:00:01 GMT', 'Wed, 02 Jan 1980 00:11:35 GMT', 'Wed, 12 Oct
* 1492 10:15:01 GMT']
* @param arrayBody The array value ['Fri, 01 Dec 2000 00:00:01 GMT', 'Wed, 02 Jan 1980 00:11:35 GMT',
* 'Wed, 12 Oct 1492 10:15:01 GMT']
* @param options The options parameters.
*/
putDateTimeRfc1123Valid(
arrayBody: Date[],
options?: ArrayPutDateTimeRfc1123ValidOptionalParams
): Promise<void>;
/**
* Get duration array value ['P123DT22H14M12.011S', 'P5DT1H0M0S']
* @param options The options parameters.
*/
getDurationValid(
options?: ArrayGetDurationValidOptionalParams
): Promise<ArrayGetDurationValidResponse>;
/**
* Set array value ['P123DT22H14M12.011S', 'P5DT1H0M0S']
* @param arrayBody The array value ['P123DT22H14M12.011S', 'P5DT1H0M0S']
* @param options The options parameters.
*/
putDurationValid(
arrayBody: string[],
options?: ArrayPutDurationValidOptionalParams
): Promise<void>;
/**
* Get byte array value [hex(FF FF FF FA), hex(01 02 03), hex (25, 29, 43)] with each item encoded in
* base64
* @param options The options parameters.
*/
getByteValid(
options?: ArrayGetByteValidOptionalParams
): Promise<ArrayGetByteValidResponse>;
/**
* Put the array value [hex(FF FF FF FA), hex(01 02 03), hex (25, 29, 43)] with each elementencoded in
* base 64
* @param arrayBody The array value [hex(FF FF FF FA), hex(01 02 03), hex (25, 29, 43)] with each
* elementencoded in base 64
* @param options The options parameters.
*/
putByteValid(
arrayBody: Uint8Array[],
options?: ArrayPutByteValidOptionalParams
): Promise<void>;
/**
* Get byte array value [hex(AB, AC, AD), null] with the first item base64 encoded
* @param options The options parameters.
*/
getByteInvalidNull(
options?: ArrayGetByteInvalidNullOptionalParams
): Promise<ArrayGetByteInvalidNullResponse>;
/**
* Get array value ['a string that gets encoded with base64url', 'test string' 'Lorem ipsum'] with the
* items base64url encoded
* @param options The options parameters.
*/
getBase64Url(
options?: ArrayGetBase64UrlOptionalParams
): Promise<ArrayGetBase64UrlResponse>;
/**
* Get array of complex type null value
* @param options The options parameters.
*/
getComplexNull(
options?: ArrayGetComplexNullOptionalParams
): Promise<ArrayGetComplexNullResponse>;
/**
* Get empty array of complex type []
* @param options The options parameters.
*/
getComplexEmpty(
options?: ArrayGetComplexEmptyOptionalParams
): Promise<ArrayGetComplexEmptyResponse>;
/**
* Get array of complex type with null item [{'integer': 1 'string': '2'}, null, {'integer': 5,
* 'string': '6'}]
* @param options The options parameters.
*/
getComplexItemNull(
options?: ArrayGetComplexItemNullOptionalParams
): Promise<ArrayGetComplexItemNullResponse>;
/**
* Get array of complex type with empty item [{'integer': 1 'string': '2'}, {}, {'integer': 5,
* 'string': '6'}]
* @param options The options parameters.
*/
getComplexItemEmpty(
options?: ArrayGetComplexItemEmptyOptionalParams
): Promise<ArrayGetComplexItemEmptyResponse>;
/**
* Get array of complex type with [{'integer': 1 'string': '2'}, {'integer': 3, 'string': '4'},
* {'integer': 5, 'string': '6'}]
* @param options The options parameters.
*/
getComplexValid(
options?: ArrayGetComplexValidOptionalParams
): Promise<ArrayGetComplexValidResponse>;
/**
* Put an array of complex type with values [{'integer': 1 'string': '2'}, {'integer': 3, 'string':
* '4'}, {'integer': 5, 'string': '6'}]
* @param arrayBody array of complex type with [{'integer': 1 'string': '2'}, {'integer': 3, 'string':
* '4'}, {'integer': 5, 'string': '6'}]
* @param options The options parameters.
*/
putComplexValid(
arrayBody: Product[],
options?: ArrayPutComplexValidOptionalParams
): Promise<void>;
/**
* Get a null array
* @param options The options parameters.
*/
getArrayNull(
options?: ArrayGetArrayNullOptionalParams
): Promise<ArrayGetArrayNullResponse>;
/**
* Get an empty array []
* @param options The options parameters.
*/
getArrayEmpty(
options?: ArrayGetArrayEmptyOptionalParams
): Promise<ArrayGetArrayEmptyResponse>;
/**
* Get an array of array of strings [['1', '2', '3'], null, ['7', '8', '9']]
* @param options The options parameters.
*/
getArrayItemNull(
options?: ArrayGetArrayItemNullOptionalParams
): Promise<ArrayGetArrayItemNullResponse>;
/**
* Get an array of array of strings [['1', '2', '3'], [], ['7', '8', '9']]
* @param options The options parameters.
*/
getArrayItemEmpty(
options?: ArrayGetArrayItemEmptyOptionalParams
): Promise<ArrayGetArrayItemEmptyResponse>;
/**
* Get an array of array of strings [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
* @param options The options parameters.
*/
getArrayValid(
options?: ArrayGetArrayValidOptionalParams
): Promise<ArrayGetArrayValidResponse>;
/**
* Put An array of array of strings [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
* @param arrayBody An array of array of strings [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
* @param options The options parameters.
*/
putArrayValid(
arrayBody: string[][],
options?: ArrayPutArrayValidOptionalParams
): Promise<void>;
/**
* Get an array of Dictionaries with value null
* @param options The options parameters.
*/
getDictionaryNull(
options?: ArrayGetDictionaryNullOptionalParams
): Promise<ArrayGetDictionaryNullResponse>;
/**
* Get an array of Dictionaries of type <string, string> with value []
* @param options The options parameters.
*/
getDictionaryEmpty(
options?: ArrayGetDictionaryEmptyOptionalParams
): Promise<ArrayGetDictionaryEmptyResponse>;
/**
* Get an array of Dictionaries of type <string, string> with value [{'1': 'one', '2': 'two', '3':
* 'three'}, null, {'7': 'seven', '8': 'eight', '9': 'nine'}]
* @param options The options parameters.
*/
getDictionaryItemNull(
options?: ArrayGetDictionaryItemNullOptionalParams
): Promise<ArrayGetDictionaryItemNullResponse>;
/**
* Get an array of Dictionaries of type <string, string> with value [{'1': 'one', '2': 'two', '3':
* 'three'}, {}, {'7': 'seven', '8': 'eight', '9': 'nine'}]
* @param options The options parameters.
*/
getDictionaryItemEmpty(
options?: ArrayGetDictionaryItemEmptyOptionalParams
): Promise<ArrayGetDictionaryItemEmptyResponse>;
/**
* Get an array of Dictionaries of type <string, string> with value [{'1': 'one', '2': 'two', '3':
* 'three'}, {'4': 'four', '5': 'five', '6': 'six'}, {'7': 'seven', '8': 'eight', '9': 'nine'}]
* @param options The options parameters.
*/
getDictionaryValid(
options?: ArrayGetDictionaryValidOptionalParams
): Promise<ArrayGetDictionaryValidResponse>;
/**
* Get an array of Dictionaries of type <string, string> with value [{'1': 'one', '2': 'two', '3':
* 'three'}, {'4': 'four', '5': 'five', '6': 'six'}, {'7': 'seven', '8': 'eight', '9': 'nine'}]
* @param arrayBody An array of Dictionaries of type <string, string> with value [{'1': 'one', '2':
* 'two', '3': 'three'}, {'4': 'four', '5': 'five', '6': 'six'}, {'7': 'seven', '8': 'eight', '9':
* 'nine'}]
* @param options The options parameters.
*/
putDictionaryValid(
arrayBody: { [propertyName: string]: string }[],
options?: ArrayPutDictionaryValidOptionalParams
): Promise<void>;
} | the_stack |
import { Dataset, Attributes, AttributeInfo, PlyType } from "plywood";
interface VariableRow {
VARIABLE_NAME: string;
VARIABLE_VALUE: string;
}
let variablesData: VariableRow[] = [
{ "VARIABLE_NAME": "auto_generate_certs", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "auto_increment_increment", "VARIABLE_VALUE": "1" },
{ "VARIABLE_NAME": "auto_increment_offset", "VARIABLE_VALUE": "1" },
{ "VARIABLE_NAME": "autocommit", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "automatic_sp_privileges", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "avoid_temporal_upgrade", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "back_log", "VARIABLE_VALUE": "80" },
{ "VARIABLE_NAME": "basedir", "VARIABLE_VALUE": "/usr/" },
{ "VARIABLE_NAME": "big_tables", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "bind_address", "VARIABLE_VALUE": "*" },
{ "VARIABLE_NAME": "binlog_cache_size", "VARIABLE_VALUE": "32768" },
{ "VARIABLE_NAME": "binlog_checksum", "VARIABLE_VALUE": "CRC32" },
{ "VARIABLE_NAME": "binlog_direct_non_transactional_updates", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "binlog_error_action", "VARIABLE_VALUE": "ABORT_SERVER" },
{ "VARIABLE_NAME": "binlog_format", "VARIABLE_VALUE": "ROW" },
{ "VARIABLE_NAME": "binlog_group_commit_sync_delay", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "binlog_group_commit_sync_no_delay_count", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "binlog_gtid_simple_recovery", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "binlog_max_flush_queue_time", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "binlog_order_commits", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "binlog_row_image", "VARIABLE_VALUE": "FULL" },
{ "VARIABLE_NAME": "binlog_rows_query_log_events", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "binlog_stmt_cache_size", "VARIABLE_VALUE": "32768" },
{ "VARIABLE_NAME": "block_encryption_mode", "VARIABLE_VALUE": "aes-128-ecb" },
{ "VARIABLE_NAME": "bulk_insert_buffer_size", "VARIABLE_VALUE": "8388608" },
{ "VARIABLE_NAME": "character_set_client", "VARIABLE_VALUE": "utf8mb4" },
{ "VARIABLE_NAME": "character_set_connection", "VARIABLE_VALUE": "utf8mb4" },
{ "VARIABLE_NAME": "character_set_database", "VARIABLE_VALUE": "utf8mb4" },
{ "VARIABLE_NAME": "character_set_filesystem", "VARIABLE_VALUE": "binary" },
{ "VARIABLE_NAME": "character_set_results", "VARIABLE_VALUE": "utf8mb4" },
{ "VARIABLE_NAME": "character_set_server", "VARIABLE_VALUE": "utf8mb4" },
{ "VARIABLE_NAME": "character_set_system", "VARIABLE_VALUE": "utf8mb4" },
{ "VARIABLE_NAME": "character_sets_dir", "VARIABLE_VALUE": "/usr/share/mysql/charsets/" },
{ "VARIABLE_NAME": "check_proxy_users", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "collation_connection", "VARIABLE_VALUE": "utf8mb4_unicode_ci" },
{ "VARIABLE_NAME": "collation_database", "VARIABLE_VALUE": "utf8mb4_unicode_ci" },
{ "VARIABLE_NAME": "collation_server", "VARIABLE_VALUE": "utf8mb4_unicode_ci" },
{ "VARIABLE_NAME": "completion_type", "VARIABLE_VALUE": "NO_CHAIN" },
{ "VARIABLE_NAME": "concurrent_insert", "VARIABLE_VALUE": "AUTO" },
{ "VARIABLE_NAME": "connect_timeout", "VARIABLE_VALUE": "10" },
{ "VARIABLE_NAME": "core_file", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "datadir", "VARIABLE_VALUE": "/var/lib/mysql/" },
{ "VARIABLE_NAME": "date_format", "VARIABLE_VALUE": "%Y-%m-%d" },
{ "VARIABLE_NAME": "datetime_format", "VARIABLE_VALUE": "%Y-%m-%d %H:%i:%s" },
{ "VARIABLE_NAME": "default_authentication_plugin", "VARIABLE_VALUE": "mysql_native_password" },
{ "VARIABLE_NAME": "default_password_lifetime", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "default_storage_engine", "VARIABLE_VALUE": "InnoDB" },
{ "VARIABLE_NAME": "default_tmp_storage_engine", "VARIABLE_VALUE": "InnoDB" },
{ "VARIABLE_NAME": "default_week_format", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "delay_key_write", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "delayed_insert_limit", "VARIABLE_VALUE": "100" },
{ "VARIABLE_NAME": "delayed_insert_timeout", "VARIABLE_VALUE": "300" },
{ "VARIABLE_NAME": "delayed_queue_size", "VARIABLE_VALUE": "1000" },
{ "VARIABLE_NAME": "disabled_storage_engines", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "disconnect_on_expired_password", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "div_precision_increment", "VARIABLE_VALUE": "4" },
{ "VARIABLE_NAME": "end_markers_in_json", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "enforce_gtid_consistency", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "eq_range_index_dive_limit", "VARIABLE_VALUE": "200" },
{ "VARIABLE_NAME": "event_scheduler", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "expire_logs_days", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "explicit_defaults_for_timestamp", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "flush", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "flush_time", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "foreign_key_checks", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "ft_boolean_syntax", "VARIABLE_VALUE": "+ -><()~*:" },
{ "VARIABLE_NAME": "ft_max_word_len", "VARIABLE_VALUE": "84" },
{ "VARIABLE_NAME": "ft_min_word_len", "VARIABLE_VALUE": "4" },
{ "VARIABLE_NAME": "ft_query_expansion_limit", "VARIABLE_VALUE": "20" },
{ "VARIABLE_NAME": "ft_stopword_file", "VARIABLE_VALUE": "(built-in)" },
{ "VARIABLE_NAME": "general_log", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "general_log_file", "VARIABLE_VALUE": "/var/lib/mysql/6bd10615ae09.log" },
{ "VARIABLE_NAME": "group_concat_max_len", "VARIABLE_VALUE": "1024" },
{ "VARIABLE_NAME": "gtid_executed", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "gtid_executed_compression_period", "VARIABLE_VALUE": "1000" },
{ "VARIABLE_NAME": "gtid_mode", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "gtid_owned", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "gtid_purged", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "have_compress", "VARIABLE_VALUE": "YES" },
{ "VARIABLE_NAME": "have_crypt", "VARIABLE_VALUE": "YES" },
{ "VARIABLE_NAME": "have_dynamic_loading", "VARIABLE_VALUE": "YES" },
{ "VARIABLE_NAME": "have_geometry", "VARIABLE_VALUE": "YES" },
{ "VARIABLE_NAME": "have_openssl", "VARIABLE_VALUE": "YES" },
{ "VARIABLE_NAME": "have_profiling", "VARIABLE_VALUE": "YES" },
{ "VARIABLE_NAME": "have_query_cache", "VARIABLE_VALUE": "YES" },
{ "VARIABLE_NAME": "have_rtree_keys", "VARIABLE_VALUE": "YES" },
{ "VARIABLE_NAME": "have_ssl", "VARIABLE_VALUE": "YES" },
{ "VARIABLE_NAME": "have_statement_timeout", "VARIABLE_VALUE": "YES" },
{ "VARIABLE_NAME": "have_symlink", "VARIABLE_VALUE": "DISABLED" },
{ "VARIABLE_NAME": "host_cache_size", "VARIABLE_VALUE": "279" },
{ "VARIABLE_NAME": "hostname", "VARIABLE_VALUE": "6bd10615ae09" },
{ "VARIABLE_NAME": "ignore_builtin_innodb", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "ignore_db_dirs", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "init_connect", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "init_file", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "init_slave", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "innodb_adaptive_flushing", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "innodb_adaptive_flushing_lwm", "VARIABLE_VALUE": "10" },
{ "VARIABLE_NAME": "innodb_adaptive_hash_index", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "innodb_adaptive_hash_index_parts", "VARIABLE_VALUE": "8" },
{ "VARIABLE_NAME": "innodb_adaptive_max_sleep_delay", "VARIABLE_VALUE": "150000" },
{ "VARIABLE_NAME": "innodb_api_bk_commit_interval", "VARIABLE_VALUE": "5" },
{ "VARIABLE_NAME": "innodb_api_disable_rowlock", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "innodb_api_enable_binlog", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "innodb_api_enable_mdl", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "innodb_api_trx_level", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "innodb_autoextend_increment", "VARIABLE_VALUE": "64" },
{ "VARIABLE_NAME": "innodb_autoinc_lock_mode", "VARIABLE_VALUE": "1" },
{ "VARIABLE_NAME": "innodb_buffer_pool_chunk_size", "VARIABLE_VALUE": "134217728" },
{ "VARIABLE_NAME": "innodb_buffer_pool_dump_at_shutdown", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "innodb_buffer_pool_dump_now", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "innodb_buffer_pool_dump_pct", "VARIABLE_VALUE": "25" },
{ "VARIABLE_NAME": "innodb_buffer_pool_filename", "VARIABLE_VALUE": "ib_buffer_pool" },
{ "VARIABLE_NAME": "innodb_buffer_pool_instances", "VARIABLE_VALUE": "1" },
{ "VARIABLE_NAME": "innodb_buffer_pool_load_abort", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "innodb_buffer_pool_load_at_startup", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "innodb_buffer_pool_load_now", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "innodb_buffer_pool_size", "VARIABLE_VALUE": "134217728" },
{ "VARIABLE_NAME": "innodb_change_buffer_max_size", "VARIABLE_VALUE": "25" },
{ "VARIABLE_NAME": "innodb_change_buffering", "VARIABLE_VALUE": "all" },
{ "VARIABLE_NAME": "innodb_checksum_algorithm", "VARIABLE_VALUE": "crc32" },
{ "VARIABLE_NAME": "innodb_checksums", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "innodb_cmp_per_index_enabled", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "innodb_commit_concurrency", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "innodb_compression_failure_threshold_pct", "VARIABLE_VALUE": "5" },
{ "VARIABLE_NAME": "innodb_compression_level", "VARIABLE_VALUE": "6" },
{ "VARIABLE_NAME": "innodb_compression_pad_pct_max", "VARIABLE_VALUE": "50" },
{ "VARIABLE_NAME": "innodb_concurrency_tickets", "VARIABLE_VALUE": "5000" },
{ "VARIABLE_NAME": "innodb_data_file_path", "VARIABLE_VALUE": "ibdata1:12M:autoextend" },
{ "VARIABLE_NAME": "innodb_data_home_dir", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "innodb_default_row_format", "VARIABLE_VALUE": "dynamic" },
{ "VARIABLE_NAME": "innodb_disable_sort_file_cache", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "innodb_doublewrite", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "innodb_fast_shutdown", "VARIABLE_VALUE": "1" },
{ "VARIABLE_NAME": "innodb_file_format", "VARIABLE_VALUE": "Barracuda" },
{ "VARIABLE_NAME": "innodb_file_format_check", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "innodb_file_format_max", "VARIABLE_VALUE": "Barracuda" },
{ "VARIABLE_NAME": "innodb_file_per_table", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "innodb_fill_factor", "VARIABLE_VALUE": "100" },
{ "VARIABLE_NAME": "innodb_flush_log_at_timeout", "VARIABLE_VALUE": "1" },
{ "VARIABLE_NAME": "innodb_flush_log_at_trx_commit", "VARIABLE_VALUE": "1" },
{ "VARIABLE_NAME": "innodb_flush_method", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "innodb_flush_neighbors", "VARIABLE_VALUE": "1" },
{ "VARIABLE_NAME": "innodb_flush_sync", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "innodb_flushing_avg_loops", "VARIABLE_VALUE": "30" },
{ "VARIABLE_NAME": "innodb_force_load_corrupted", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "innodb_force_recovery", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "innodb_ft_aux_table", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "innodb_ft_cache_size", "VARIABLE_VALUE": "8000000" },
{ "VARIABLE_NAME": "innodb_ft_enable_diag_print", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "innodb_ft_enable_stopword", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "innodb_ft_max_token_size", "VARIABLE_VALUE": "84" },
{ "VARIABLE_NAME": "innodb_ft_min_token_size", "VARIABLE_VALUE": "3" },
{ "VARIABLE_NAME": "innodb_ft_num_word_optimize", "VARIABLE_VALUE": "2000" },
{ "VARIABLE_NAME": "innodb_ft_result_cache_limit", "VARIABLE_VALUE": "2000000000" },
{ "VARIABLE_NAME": "innodb_ft_server_stopword_table", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "innodb_ft_sort_pll_degree", "VARIABLE_VALUE": "2" },
{ "VARIABLE_NAME": "innodb_ft_total_cache_size", "VARIABLE_VALUE": "640000000" },
{ "VARIABLE_NAME": "innodb_ft_user_stopword_table", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "innodb_io_capacity", "VARIABLE_VALUE": "200" },
{ "VARIABLE_NAME": "innodb_io_capacity_max", "VARIABLE_VALUE": "2000" },
{ "VARIABLE_NAME": "innodb_large_prefix", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "innodb_lock_wait_timeout", "VARIABLE_VALUE": "50" },
{ "VARIABLE_NAME": "innodb_locks_unsafe_for_binlog", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "innodb_log_buffer_size", "VARIABLE_VALUE": "16777216" },
{ "VARIABLE_NAME": "innodb_log_checksums", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "innodb_log_compressed_pages", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "innodb_log_file_size", "VARIABLE_VALUE": "50331648" },
{ "VARIABLE_NAME": "innodb_log_files_in_group", "VARIABLE_VALUE": "2" },
{ "VARIABLE_NAME": "innodb_log_group_home_dir", "VARIABLE_VALUE": "./" },
{ "VARIABLE_NAME": "innodb_log_write_ahead_size", "VARIABLE_VALUE": "8192" },
{ "VARIABLE_NAME": "innodb_lru_scan_depth", "VARIABLE_VALUE": "1024" },
{ "VARIABLE_NAME": "innodb_max_dirty_pages_pct", "VARIABLE_VALUE": "75" },
{ "VARIABLE_NAME": "innodb_max_dirty_pages_pct_lwm", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "innodb_max_purge_lag", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "innodb_max_purge_lag_delay", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "innodb_max_undo_log_size", "VARIABLE_VALUE": "1073741824" },
{ "VARIABLE_NAME": "innodb_monitor_disable", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "innodb_monitor_enable", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "innodb_monitor_reset", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "innodb_monitor_reset_all", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "innodb_old_blocks_pct", "VARIABLE_VALUE": "37" },
{ "VARIABLE_NAME": "innodb_old_blocks_time", "VARIABLE_VALUE": "1000" },
{ "VARIABLE_NAME": "innodb_online_alter_log_max_size", "VARIABLE_VALUE": "134217728" },
{ "VARIABLE_NAME": "innodb_open_files", "VARIABLE_VALUE": "2000" },
{ "VARIABLE_NAME": "innodb_optimize_fulltext_only", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "innodb_page_cleaners", "VARIABLE_VALUE": "1" },
{ "VARIABLE_NAME": "innodb_page_size", "VARIABLE_VALUE": "16384" },
{ "VARIABLE_NAME": "innodb_print_all_deadlocks", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "innodb_purge_batch_size", "VARIABLE_VALUE": "300" },
{ "VARIABLE_NAME": "innodb_purge_rseg_truncate_frequency", "VARIABLE_VALUE": "128" },
{ "VARIABLE_NAME": "innodb_purge_threads", "VARIABLE_VALUE": "4" },
{ "VARIABLE_NAME": "innodb_random_read_ahead", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "innodb_read_ahead_threshold", "VARIABLE_VALUE": "56" },
{ "VARIABLE_NAME": "innodb_read_io_threads", "VARIABLE_VALUE": "4" },
{ "VARIABLE_NAME": "innodb_read_only", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "innodb_replication_delay", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "innodb_rollback_on_timeout", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "innodb_rollback_segments", "VARIABLE_VALUE": "128" },
{ "VARIABLE_NAME": "innodb_sort_buffer_size", "VARIABLE_VALUE": "1048576" },
{ "VARIABLE_NAME": "innodb_spin_wait_delay", "VARIABLE_VALUE": "6" },
{ "VARIABLE_NAME": "innodb_stats_auto_recalc", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "innodb_stats_method", "VARIABLE_VALUE": "nulls_equal" },
{ "VARIABLE_NAME": "innodb_stats_on_metadata", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "innodb_stats_persistent", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "innodb_stats_persistent_sample_pages", "VARIABLE_VALUE": "20" },
{ "VARIABLE_NAME": "innodb_stats_sample_pages", "VARIABLE_VALUE": "8" },
{ "VARIABLE_NAME": "innodb_stats_transient_sample_pages", "VARIABLE_VALUE": "8" },
{ "VARIABLE_NAME": "innodb_status_output", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "innodb_status_output_locks", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "innodb_strict_mode", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "innodb_support_xa", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "innodb_sync_array_size", "VARIABLE_VALUE": "1" },
{ "VARIABLE_NAME": "innodb_sync_spin_loops", "VARIABLE_VALUE": "30" },
{ "VARIABLE_NAME": "innodb_table_locks", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "innodb_temp_data_file_path", "VARIABLE_VALUE": "ibtmp1:12M:autoextend" },
{ "VARIABLE_NAME": "innodb_thread_concurrency", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "innodb_thread_sleep_delay", "VARIABLE_VALUE": "10000" },
{ "VARIABLE_NAME": "innodb_tmpdir", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "innodb_undo_directory", "VARIABLE_VALUE": "./" },
{ "VARIABLE_NAME": "innodb_undo_log_truncate", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "innodb_undo_logs", "VARIABLE_VALUE": "128" },
{ "VARIABLE_NAME": "innodb_undo_tablespaces", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "innodb_use_native_aio", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "innodb_version", "VARIABLE_VALUE": "5.7.11" },
{ "VARIABLE_NAME": "innodb_write_io_threads", "VARIABLE_VALUE": "4" },
{ "VARIABLE_NAME": "interactive_timeout", "VARIABLE_VALUE": "28800" },
{ "VARIABLE_NAME": "internal_tmp_disk_storage_engine", "VARIABLE_VALUE": "InnoDB" },
{ "VARIABLE_NAME": "join_buffer_size", "VARIABLE_VALUE": "262144" },
{ "VARIABLE_NAME": "keep_files_on_create", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "key_buffer_size", "VARIABLE_VALUE": "8388608" },
{ "VARIABLE_NAME": "key_cache_age_threshold", "VARIABLE_VALUE": "300" },
{ "VARIABLE_NAME": "key_cache_block_size", "VARIABLE_VALUE": "1024" },
{ "VARIABLE_NAME": "key_cache_division_limit", "VARIABLE_VALUE": "100" },
{ "VARIABLE_NAME": "keyring_file_data", "VARIABLE_VALUE": "/var/lib/mysql-keyring/keyring" },
{ "VARIABLE_NAME": "large_files_support", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "large_page_size", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "large_pages", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "lc_messages", "VARIABLE_VALUE": "en_US" },
{ "VARIABLE_NAME": "lc_messages_dir", "VARIABLE_VALUE": "/usr/share/mysql/" },
{ "VARIABLE_NAME": "lc_time_names", "VARIABLE_VALUE": "en_US" },
{ "VARIABLE_NAME": "license", "VARIABLE_VALUE": "Apache-2.0" },
{ "VARIABLE_NAME": "local_infile", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "lock_wait_timeout", "VARIABLE_VALUE": "31536000" },
{ "VARIABLE_NAME": "locked_in_memory", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "log_bin", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "log_bin_basename", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "log_bin_index", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "log_bin_trust_function_creators", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "log_bin_use_v1_row_events", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "log_builtin_as_identified_by_password", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "log_error", "VARIABLE_VALUE": "/var/log/mysqld.log" },
{ "VARIABLE_NAME": "log_error_verbosity", "VARIABLE_VALUE": "3" },
{ "VARIABLE_NAME": "log_output", "VARIABLE_VALUE": "FILE" },
{ "VARIABLE_NAME": "log_queries_not_using_indexes", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "log_slave_updates", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "log_slow_admin_statements", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "log_slow_slave_statements", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "log_statements_unsafe_for_binlog", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "log_syslog", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "log_syslog_facility", "VARIABLE_VALUE": "daemon" },
{ "VARIABLE_NAME": "log_syslog_include_pid", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "log_syslog_tag", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "log_throttle_queries_not_using_indexes", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "log_timestamps", "VARIABLE_VALUE": "UTC" },
{ "VARIABLE_NAME": "log_warnings", "VARIABLE_VALUE": "2" },
{ "VARIABLE_NAME": "long_query_time", "VARIABLE_VALUE": "10" },
{ "VARIABLE_NAME": "low_priority_updates", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "lower_case_file_system", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "lower_case_table_names", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "master_info_repository", "VARIABLE_VALUE": "FILE" },
{ "VARIABLE_NAME": "master_verify_checksum", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "max_allowed_packet", "VARIABLE_VALUE": "4194304" },
{ "VARIABLE_NAME": "max_binlog_cache_size", "VARIABLE_VALUE": "18446744073709548000" },
{ "VARIABLE_NAME": "max_binlog_size", "VARIABLE_VALUE": "1073741824" },
{ "VARIABLE_NAME": "max_binlog_stmt_cache_size", "VARIABLE_VALUE": "18446744073709548000" },
{ "VARIABLE_NAME": "max_connect_errors", "VARIABLE_VALUE": "100" },
{ "VARIABLE_NAME": "max_connections", "VARIABLE_VALUE": "151" },
{ "VARIABLE_NAME": "max_delayed_threads", "VARIABLE_VALUE": "20" },
{ "VARIABLE_NAME": "max_digest_length", "VARIABLE_VALUE": "1024" },
{ "VARIABLE_NAME": "max_error_count", "VARIABLE_VALUE": "64" },
{ "VARIABLE_NAME": "max_execution_time", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "max_heap_table_size", "VARIABLE_VALUE": "16777216" },
{ "VARIABLE_NAME": "max_insert_delayed_threads", "VARIABLE_VALUE": "20" },
{ "VARIABLE_NAME": "max_join_size", "VARIABLE_VALUE": "18446744073709552000" },
{ "VARIABLE_NAME": "max_length_for_sort_data", "VARIABLE_VALUE": "1024" },
{ "VARIABLE_NAME": "max_points_in_geometry", "VARIABLE_VALUE": "65536" },
{ "VARIABLE_NAME": "max_prepared_stmt_count", "VARIABLE_VALUE": "16382" },
{ "VARIABLE_NAME": "max_relay_log_size", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "max_seeks_for_key", "VARIABLE_VALUE": "18446744073709552000" },
{ "VARIABLE_NAME": "max_sort_length", "VARIABLE_VALUE": "1024" },
{ "VARIABLE_NAME": "max_sp_recursion_depth", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "max_tmp_tables", "VARIABLE_VALUE": "32" },
{ "VARIABLE_NAME": "max_user_connections", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "max_write_lock_count", "VARIABLE_VALUE": "18446744073709552000" },
{ "VARIABLE_NAME": "metadata_locks_cache_size", "VARIABLE_VALUE": "1024" },
{ "VARIABLE_NAME": "metadata_locks_hash_instances", "VARIABLE_VALUE": "8" },
{ "VARIABLE_NAME": "min_examined_row_limit", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "multi_range_count", "VARIABLE_VALUE": "256" },
{ "VARIABLE_NAME": "myisam_data_pointer_size", "VARIABLE_VALUE": "6" },
{ "VARIABLE_NAME": "myisam_max_sort_file_size", "VARIABLE_VALUE": "9223372036853727000" },
{ "VARIABLE_NAME": "myisam_mmap_size", "VARIABLE_VALUE": "18446744073709552000" },
{ "VARIABLE_NAME": "myisam_recover_options", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "myisam_repair_threads", "VARIABLE_VALUE": "1" },
{ "VARIABLE_NAME": "myisam_sort_buffer_size", "VARIABLE_VALUE": "8388608" },
{ "VARIABLE_NAME": "myisam_stats_method", "VARIABLE_VALUE": "nulls_unequal" },
{ "VARIABLE_NAME": "myisam_use_mmap", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "mysql_native_password_proxy_users", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "net_buffer_length", "VARIABLE_VALUE": "16384" },
{ "VARIABLE_NAME": "net_read_timeout", "VARIABLE_VALUE": "30" },
{ "VARIABLE_NAME": "net_retry_count", "VARIABLE_VALUE": "10" },
{ "VARIABLE_NAME": "net_write_timeout", "VARIABLE_VALUE": "60" },
{ "VARIABLE_NAME": "new", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "ngram_token_size", "VARIABLE_VALUE": "2" },
{ "VARIABLE_NAME": "offline_mode", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "old", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "old_alter_table", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "old_passwords", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "open_files_limit", "VARIABLE_VALUE": "1048576" },
{ "VARIABLE_NAME": "optimizer_prune_level", "VARIABLE_VALUE": "1" },
{ "VARIABLE_NAME": "optimizer_search_depth", "VARIABLE_VALUE": "62" },
{ "VARIABLE_NAME": "optimizer_switch", "VARIABLE_VALUE": "index_merge=on,index_merge_union=on,index_merge_sort_union=on,index_merge_intersection=on,engine_condition_pushdown=on,index_condition_pushdown=on,mrr=on,mrr_cost_based=on,block_nested_loop=on,batched_key_access=off,materialization=on,semijoin=on,loosescan=on,firstmatch=on,duplicateweedout=on,subquery_materialization_cost_based=on,use_index_extensions=on,condition_fanout_filter=on,derived_merge=on" },
{ "VARIABLE_NAME": "optimizer_trace", "VARIABLE_VALUE": "enabled=off,one_line=off" },
{ "VARIABLE_NAME": "optimizer_trace_features", "VARIABLE_VALUE": "greedy_search=on,range_optimizer=on,dynamic_range=on,repeated_subselect=on" },
{ "VARIABLE_NAME": "optimizer_trace_limit", "VARIABLE_VALUE": "1" },
{ "VARIABLE_NAME": "optimizer_trace_max_mem_size", "VARIABLE_VALUE": "16384" },
{ "VARIABLE_NAME": "optimizer_trace_offset", "VARIABLE_VALUE": "-1" },
{ "VARIABLE_NAME": "performance_schema", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "performance_schema_accounts_size", "VARIABLE_VALUE": "-1" },
{ "VARIABLE_NAME": "performance_schema_digests_size", "VARIABLE_VALUE": "10000" },
{ "VARIABLE_NAME": "performance_schema_events_stages_history_long_size", "VARIABLE_VALUE": "10000" },
{ "VARIABLE_NAME": "performance_schema_events_stages_history_size", "VARIABLE_VALUE": "10" },
{ "VARIABLE_NAME": "performance_schema_events_statements_history_long_size", "VARIABLE_VALUE": "10000" },
{ "VARIABLE_NAME": "performance_schema_events_statements_history_size", "VARIABLE_VALUE": "10" },
{ "VARIABLE_NAME": "performance_schema_events_transactions_history_long_size", "VARIABLE_VALUE": "10000" },
{ "VARIABLE_NAME": "performance_schema_events_transactions_history_size", "VARIABLE_VALUE": "10" },
{ "VARIABLE_NAME": "performance_schema_events_waits_history_long_size", "VARIABLE_VALUE": "10000" },
{ "VARIABLE_NAME": "performance_schema_events_waits_history_size", "VARIABLE_VALUE": "10" },
{ "VARIABLE_NAME": "performance_schema_hosts_size", "VARIABLE_VALUE": "-1" },
{ "VARIABLE_NAME": "performance_schema_max_cond_classes", "VARIABLE_VALUE": "80" },
{ "VARIABLE_NAME": "performance_schema_max_cond_instances", "VARIABLE_VALUE": "-1" },
{ "VARIABLE_NAME": "performance_schema_max_digest_length", "VARIABLE_VALUE": "1024" },
{ "VARIABLE_NAME": "performance_schema_max_file_classes", "VARIABLE_VALUE": "80" },
{ "VARIABLE_NAME": "performance_schema_max_file_handles", "VARIABLE_VALUE": "32768" },
{ "VARIABLE_NAME": "performance_schema_max_file_instances", "VARIABLE_VALUE": "-1" },
{ "VARIABLE_NAME": "performance_schema_max_index_stat", "VARIABLE_VALUE": "-1" },
{ "VARIABLE_NAME": "performance_schema_max_memory_classes", "VARIABLE_VALUE": "320" },
{ "VARIABLE_NAME": "performance_schema_max_metadata_locks", "VARIABLE_VALUE": "-1" },
{ "VARIABLE_NAME": "performance_schema_max_mutex_classes", "VARIABLE_VALUE": "200" },
{ "VARIABLE_NAME": "performance_schema_max_mutex_instances", "VARIABLE_VALUE": "-1" },
{ "VARIABLE_NAME": "performance_schema_max_prepared_statements_instances", "VARIABLE_VALUE": "-1" },
{ "VARIABLE_NAME": "performance_schema_max_program_instances", "VARIABLE_VALUE": "-1" },
{ "VARIABLE_NAME": "performance_schema_max_rwlock_classes", "VARIABLE_VALUE": "40" },
{ "VARIABLE_NAME": "performance_schema_max_rwlock_instances", "VARIABLE_VALUE": "-1" },
{ "VARIABLE_NAME": "performance_schema_max_socket_classes", "VARIABLE_VALUE": "10" },
{ "VARIABLE_NAME": "performance_schema_max_socket_instances", "VARIABLE_VALUE": "-1" },
{ "VARIABLE_NAME": "performance_schema_max_sql_text_length", "VARIABLE_VALUE": "1024" },
{ "VARIABLE_NAME": "performance_schema_max_stage_classes", "VARIABLE_VALUE": "150" },
{ "VARIABLE_NAME": "performance_schema_max_statement_classes", "VARIABLE_VALUE": "193" },
{ "VARIABLE_NAME": "performance_schema_max_statement_stack", "VARIABLE_VALUE": "10" },
{ "VARIABLE_NAME": "performance_schema_max_table_handles", "VARIABLE_VALUE": "-1" },
{ "VARIABLE_NAME": "performance_schema_max_table_instances", "VARIABLE_VALUE": "-1" },
{ "VARIABLE_NAME": "performance_schema_max_table_lock_stat", "VARIABLE_VALUE": "-1" },
{ "VARIABLE_NAME": "performance_schema_max_thread_classes", "VARIABLE_VALUE": "50" },
{ "VARIABLE_NAME": "performance_schema_max_thread_instances", "VARIABLE_VALUE": "-1" },
{ "VARIABLE_NAME": "performance_schema_session_connect_attrs_size", "VARIABLE_VALUE": "512" },
{ "VARIABLE_NAME": "performance_schema_setup_actors_size", "VARIABLE_VALUE": "-1" },
{ "VARIABLE_NAME": "performance_schema_setup_objects_size", "VARIABLE_VALUE": "-1" },
{ "VARIABLE_NAME": "performance_schema_users_size", "VARIABLE_VALUE": "-1" },
{ "VARIABLE_NAME": "pid_file", "VARIABLE_VALUE": "/var/run/mysqld/mysqld.pid" },
{ "VARIABLE_NAME": "plugin_dir", "VARIABLE_VALUE": "/usr/lib64/mysql/plugin/" },
{ "VARIABLE_NAME": "port", "VARIABLE_VALUE": "3306" },
{ "VARIABLE_NAME": "preload_buffer_size", "VARIABLE_VALUE": "32768" },
{ "VARIABLE_NAME": "profiling", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "profiling_history_size", "VARIABLE_VALUE": "15" },
{ "VARIABLE_NAME": "protocol_version", "VARIABLE_VALUE": "10" },
{ "VARIABLE_NAME": "query_alloc_block_size", "VARIABLE_VALUE": "8192" },
{ "VARIABLE_NAME": "query_cache_limit", "VARIABLE_VALUE": "1048576" },
{ "VARIABLE_NAME": "query_cache_min_res_unit", "VARIABLE_VALUE": "4096" },
{ "VARIABLE_NAME": "query_cache_size", "VARIABLE_VALUE": "1048576" },
{ "VARIABLE_NAME": "query_cache_type", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "query_cache_wlock_invalidate", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "query_prealloc_size", "VARIABLE_VALUE": "8192" },
{ "VARIABLE_NAME": "range_alloc_block_size", "VARIABLE_VALUE": "4096" },
{ "VARIABLE_NAME": "range_optimizer_max_mem_size", "VARIABLE_VALUE": "1536000" },
{ "VARIABLE_NAME": "rbr_exec_mode", "VARIABLE_VALUE": "STRICT" },
{ "VARIABLE_NAME": "read_buffer_size", "VARIABLE_VALUE": "131072" },
{ "VARIABLE_NAME": "read_only", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "read_rnd_buffer_size", "VARIABLE_VALUE": "262144" },
{ "VARIABLE_NAME": "relay_log", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "relay_log_basename", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "relay_log_index", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "relay_log_info_file", "VARIABLE_VALUE": "relay-log.info" },
{ "VARIABLE_NAME": "relay_log_info_repository", "VARIABLE_VALUE": "FILE" },
{ "VARIABLE_NAME": "relay_log_purge", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "relay_log_recovery", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "relay_log_space_limit", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "report_host", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "report_password", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "report_port", "VARIABLE_VALUE": "3306" },
{ "VARIABLE_NAME": "report_user", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "require_secure_transport", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "rpl_stop_slave_timeout", "VARIABLE_VALUE": "31536000" },
{ "VARIABLE_NAME": "secure_auth", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "secure_file_priv", "VARIABLE_VALUE": "/var/lib/mysql-files/" },
{ "VARIABLE_NAME": "server_id", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "server_id_bits", "VARIABLE_VALUE": "32" },
{ "VARIABLE_NAME": "server_uuid", "VARIABLE_VALUE": "cd084b7c-01dc-11e6-87db-0242ac110003" },
{ "VARIABLE_NAME": "session_track_gtids", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "session_track_schema", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "session_track_state_change", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "session_track_system_variables", "VARIABLE_VALUE": "time_zone,autocommit,character_set_client,character_set_results,character_set_connection" },
{ "VARIABLE_NAME": "session_track_transaction_info", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "sha256_password_auto_generate_rsa_keys", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "sha256_password_private_key_path", "VARIABLE_VALUE": "private_key.pem" },
{ "VARIABLE_NAME": "sha256_password_proxy_users", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "sha256_password_public_key_path", "VARIABLE_VALUE": "public_key.pem" },
{ "VARIABLE_NAME": "show_compatibility_56", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "show_old_temporals", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "skip_external_locking", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "skip_name_resolve", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "skip_networking", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "skip_show_database", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "slave_allow_batching", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "slave_checkpoint_group", "VARIABLE_VALUE": "512" },
{ "VARIABLE_NAME": "slave_checkpoint_period", "VARIABLE_VALUE": "300" },
{ "VARIABLE_NAME": "slave_compressed_protocol", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "slave_exec_mode", "VARIABLE_VALUE": "STRICT" },
{ "VARIABLE_NAME": "slave_load_tmpdir", "VARIABLE_VALUE": "/tmp" },
{ "VARIABLE_NAME": "slave_max_allowed_packet", "VARIABLE_VALUE": "1073741824" },
{ "VARIABLE_NAME": "slave_net_timeout", "VARIABLE_VALUE": "60" },
{ "VARIABLE_NAME": "slave_parallel_type", "VARIABLE_VALUE": "DATABASE" },
{ "VARIABLE_NAME": "slave_parallel_workers", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "slave_pending_jobs_size_max", "VARIABLE_VALUE": "16777216" },
{ "VARIABLE_NAME": "slave_preserve_commit_order", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "slave_rows_search_algorithms", "VARIABLE_VALUE": "TABLE_SCAN,INDEX_SCAN" },
{ "VARIABLE_NAME": "slave_skip_errors", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "slave_sql_verify_checksum", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "slave_transaction_retries", "VARIABLE_VALUE": "10" },
{ "VARIABLE_NAME": "slave_type_conversions", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "slow_launch_time", "VARIABLE_VALUE": "2" },
{ "VARIABLE_NAME": "slow_query_log", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "slow_query_log_file", "VARIABLE_VALUE": "/var/lib/mysql/slow.log" },
{ "VARIABLE_NAME": "socket", "VARIABLE_VALUE": "/var/lib/mysql/mysql.sock" },
{ "VARIABLE_NAME": "sort_buffer_size", "VARIABLE_VALUE": "262144" },
{ "VARIABLE_NAME": "sql_auto_is_null", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "sql_big_selects", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "sql_buffer_result", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "sql_log_off", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "sql_mode", "VARIABLE_VALUE": "ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION" },
{ "VARIABLE_NAME": "sql_notes", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "sql_quote_show_create", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "sql_safe_updates", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "sql_select_limit", "VARIABLE_VALUE": "18446744073709552000" },
{ "VARIABLE_NAME": "sql_slave_skip_counter", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "sql_warnings", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "ssl_ca", "VARIABLE_VALUE": "ca.pem" },
{ "VARIABLE_NAME": "ssl_capath", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "ssl_cert", "VARIABLE_VALUE": "server-cert.pem" },
{ "VARIABLE_NAME": "ssl_cipher", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "ssl_crl", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "ssl_crlpath", "VARIABLE_VALUE": "0" },
{ "VARIABLE_NAME": "ssl_key", "VARIABLE_VALUE": "server-key.pem" },
{ "VARIABLE_NAME": "stored_program_cache", "VARIABLE_VALUE": "256" },
{ "VARIABLE_NAME": "super_read_only", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "sync_binlog", "VARIABLE_VALUE": "1" },
{ "VARIABLE_NAME": "sync_frm", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "sync_master_info", "VARIABLE_VALUE": "10000" },
{ "VARIABLE_NAME": "sync_relay_log", "VARIABLE_VALUE": "10000" },
{ "VARIABLE_NAME": "sync_relay_log_info", "VARIABLE_VALUE": "10000" },
{ "VARIABLE_NAME": "system_time_zone", "VARIABLE_VALUE": "UTC" },
{ "VARIABLE_NAME": "table_definition_cache", "VARIABLE_VALUE": "1400" },
{ "VARIABLE_NAME": "table_open_cache", "VARIABLE_VALUE": "2000" },
{ "VARIABLE_NAME": "table_open_cache_instances", "VARIABLE_VALUE": "16" },
{ "VARIABLE_NAME": "thread_cache_size", "VARIABLE_VALUE": "9" },
{ "VARIABLE_NAME": "thread_handling", "VARIABLE_VALUE": "one-thread-per-connection" },
{ "VARIABLE_NAME": "thread_stack", "VARIABLE_VALUE": "262144" },
{ "VARIABLE_NAME": "time_format", "VARIABLE_VALUE": "%H:%i:%s" },
{ "VARIABLE_NAME": "time_zone", "VARIABLE_VALUE": "UTC" },
{ "VARIABLE_NAME": "tls_version", "VARIABLE_VALUE": "TLSv1,TLSv1.1,TLSv1.2" },
{ "VARIABLE_NAME": "tmp_table_size", "VARIABLE_VALUE": "16777216" },
{ "VARIABLE_NAME": "tmpdir", "VARIABLE_VALUE": "/tmp" },
{ "VARIABLE_NAME": "transaction_alloc_block_size", "VARIABLE_VALUE": "8192" },
{ "VARIABLE_NAME": "transaction_prealloc_size", "VARIABLE_VALUE": "4096" },
{ "VARIABLE_NAME": "transaction_write_set_extraction", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "tx_isolation", "VARIABLE_VALUE": "REPEATABLE-READ" },
{ "VARIABLE_NAME": "tx_read_only", "VARIABLE_VALUE": "OFF" },
{ "VARIABLE_NAME": "unique_checks", "VARIABLE_VALUE": "ON" },
{ "VARIABLE_NAME": "updatable_views_with_limit", "VARIABLE_VALUE": "YES" },
{ "VARIABLE_NAME": "version", "VARIABLE_VALUE": "5.7.11" },
{ "VARIABLE_NAME": "version_comment", "VARIABLE_VALUE": "MySQL PlyQL Gateway (Apache 2.0)" },
{ "VARIABLE_NAME": "version_compile_machine", "VARIABLE_VALUE": "x86_64" },
{ "VARIABLE_NAME": "version_compile_os", "VARIABLE_VALUE": "Linux" },
{ "VARIABLE_NAME": "wait_timeout", "VARIABLE_VALUE": "28800" },
{ "VARIABLE_NAME": "warning_count", "VARIABLE_VALUE": "0" }
];
export function getVariablesDataset() {
return Dataset.fromJS(variablesData);
}
export function getVariablesFlatDataset() {
let attributes: Attributes = [];
let flatDatum: Record<string, string> = {};
for (let variablesDatum of variablesData) {
let name = variablesDatum['VARIABLE_NAME'];
let value: any = variablesDatum['VARIABLE_VALUE'];
let type: PlyType = 'STRING';
// Do this crazy MySQL conversion (I am not making this up)
if (value === 'ON' || value === 'OFF') {
value = value === 'ON';
type = 'BOOLEAN';
}
flatDatum[name] = value;
attributes.push(new AttributeInfo({ name, type }));
}
return Dataset.fromJS([flatDatum]);
} | the_stack |
import { LinkedListNode, LinkedList } from "./list";
import { CancellationToken, CancelError } from "./cancellation";
import { isMissing, isInstance } from "./utils";
import { Cancelable } from "@esfx/cancelable";
import { getToken } from "./adapter";
import { Disposable } from "@esfx/disposable";
/**
* Coordinates readers and writers for a resource.
*/
export class ReaderWriterLock {
private _readers = new LinkedList<() => void>();
private _upgradeables = new LinkedList<() => void>();
private _upgrades = new LinkedList<() => void>();
private _writers = new LinkedList<() => void>();
private _upgradeable: UpgradeableLockHandle | undefined;
private _upgraded: LockHandle | undefined;
private _count = 0;
/**
* Asynchronously waits for and takes a read lock on a resource.
*
* @param token A CancellationToken used to cancel the request.
*/
public read(token?: CancellationToken | Cancelable): Promise<LockHandle> {
return new Promise<LockHandle>((resolve, reject) => {
const _token = getToken(token);
_token.throwIfCancellationRequested();
if (this._canTakeReadLock()) {
resolve(this._takeReadLock());
return;
}
const node = this._readers.push(() => {
registration.unregister();
if (_token!.cancellationRequested) {
reject(new CancelError());
}
else {
resolve(this._takeReadLock());
}
});
const registration = _token.register(() => {
if (node.list) {
node.list.deleteNode(node);
reject(new CancelError());
}
});
});
}
/**
* Asynchronously waits for and takes a read lock on a resource
* that can later be upgraded to a write lock.
*
* @param token A CancellationToken used to cancel the request.
*/
public upgradeableRead(token?: CancellationToken | Cancelable): Promise<UpgradeableLockHandle> {
return new Promise<UpgradeableLockHandle>((resolve, reject) => {
const _token = getToken(token);
_token.throwIfCancellationRequested();
if (this._canTakeUpgradeableReadLock()) {
resolve(this._takeUpgradeableReadLock());
return;
}
const node = this._upgradeables.push(() => {
registration.unregister();
if (_token!.cancellationRequested) {
reject(new CancelError());
}
else {
resolve(this._takeUpgradeableReadLock());
}
});
const registration = _token.register(() => {
if (node.list) {
node.list.deleteNode(node);
reject(new CancelError());
}
});
});
}
/**
* Asynchronously waits for and takes a write lock on a resource.
*
* @param token A CancellationToken used to cancel the request.
*/
public write(token?: CancellationToken | Cancelable): Promise<LockHandle> {
return new Promise<LockHandle>((resolve, reject) => {
const _token = getToken(token);
_token.throwIfCancellationRequested();
if (this._canTakeWriteLock()) {
resolve(this._takeWriteLock());
return;
}
const node = this._writers.push(() => {
registration.unregister();
if (_token!.cancellationRequested) {
reject(new CancelError());
}
else {
resolve(this._takeWriteLock());
}
});
const registration = _token.register(() => {
if (node.list) {
node.list.deleteNode(node);
reject(new CancelError());
}
});
});
}
private _upgrade(token?: CancellationToken | Cancelable): Promise<LockHandle> {
return new Promise<LockHandle>((resolve, reject) => {
const _token = getToken(token);
_token.throwIfCancellationRequested();
if (this._canTakeUpgradeLock()) {
resolve(this._takeUpgradeLock());
return;
}
const node = this._upgrades.push(() => {
registration.unregister();
if (_token!.cancellationRequested) {
reject(new CancelError());
}
else {
resolve(this._takeUpgradeLock());
}
});
const registration = _token.register(() => {
if (node.list) {
node.list.deleteNode(node);
reject(new CancelError());
}
});
});
}
private _processLockRequests(): void {
if (this._processWriteLockRequest()) return;
if (this._processUpgradeRequest()) return;
this._processUpgradeableReadLockRequest();
this._processReadLockRequests();
}
private _canTakeReadLock() {
return this._count >= 0
&& this._writers.size === 0
&& this._upgrades.size === 0
&& this._writers.size === 0;
}
private _processReadLockRequests(): void {
if (this._canTakeReadLock()) {
this._readers.forEach(resolve => resolve());
this._readers.clear();
}
}
private _takeReadLock(): LockHandle {
let released = false;
this._count++;
const release = () => {
if (released)
throw new Error("Lock already released.");
released = true;
this._releaseReadLock();
};
return {
release,
[Disposable.dispose]: release,
};
}
private _releaseReadLock(): void {
this._count--;
this._processLockRequests();
}
private _canTakeUpgradeableReadLock() {
return this._count >= 0 && !this._upgradeable;
}
private _processUpgradeableReadLockRequest(): void {
if (this._canTakeUpgradeableReadLock()) {
const resolve = this._upgradeables.shift();
if (resolve) {
resolve();
}
}
}
private _takeUpgradeableReadLock(): UpgradeableLockHandle {
const upgrade = (token?: CancellationToken | Cancelable) => {
if (this._upgradeable !== hold)
throw new Error("Lock already released.");
return this._upgrade(token);
};
const release = () => {
if (this._upgradeable !== hold)
throw new Error("Lock already released.");
this._releaseUpgradeableReadLock();
};
const hold: UpgradeableLockHandle = {
upgrade,
release,
[Disposable.dispose]: release,
};
this._count++;
this._upgradeable = hold;
return hold;
}
private _releaseUpgradeableReadLock(): void {
if (this._count === -1) {
this._count = 0;
}
else {
this._count--;
}
this._upgraded = undefined;
this._upgradeable = undefined;
this._processLockRequests();
}
private _canTakeUpgradeLock() {
return this._count === 1
&& this._upgradeable
&& !this._upgraded;
}
private _processUpgradeRequest(): boolean {
if (this._canTakeUpgradeLock()) {
const resolve = this._upgrades.shift();
if (resolve) {
resolve();
return true;
}
}
return false;
}
private _takeUpgradeLock(): LockHandle {
const release = () => {
if (this._upgraded !== hold)
throw new Error("Lock already released.");
this._releaseUpgradeLock();
};
const hold: LockHandle = {
release,
[Disposable.dispose]: release
};
this._upgraded = hold;
this._count = -1;
return hold;
}
private _releaseUpgradeLock(): void {
this._upgraded = undefined;
this._count = 1;
this._processLockRequests();
}
private _canTakeWriteLock() {
return this._count === 0;
}
private _processWriteLockRequest(): boolean {
if (this._canTakeWriteLock()) {
const resolve = this._writers.shift();
if (resolve) {
resolve();
return true;
}
}
return false;
}
private _takeWriteLock(): LockHandle {
let released = false;
this._count = -1;
const release = () => {
if (released)
throw new Error("Lock already released.");
released = true;
this._releaseWriteLock();
};
return {
release,
[Disposable.dispose]: release,
};
}
private _releaseWriteLock(): void {
this._count = 0;
this._processLockRequests();
}
}
/**
* An object used to release a held lock.
*/
export interface LockHandle extends Disposable {
/**
* Releases the lock.
*/
release(): void;
}
/**
* An object used to release a held lock or upgrade to a write lock.
*/
export interface UpgradeableLockHandle extends LockHandle, Disposable {
/**
* Upgrades the lock to a write lock.
*
* @param token A CancellationToken used to cancel the request.
*/
upgrade(token?: CancellationToken | Cancelable): Promise<LockHandle>;
} | the_stack |
// clang-format off
import 'chrome://webui-test/cr_elements/cr_policy_strings.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {LocalDataBrowserProxyImpl, SiteEntryElement, SiteSettingsPrefsBrowserProxyImpl, SortMethod} from 'chrome://settings/lazy_load.js';
import {Router, routes} from 'chrome://settings/settings.js';
import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js';
import {eventToPromise, isChildVisible} from 'chrome://webui-test/test_util.js';
import {TestLocalDataBrowserProxy} from './test_local_data_browser_proxy.js';
import {TestSiteSettingsPrefsBrowserProxy} from './test_site_settings_prefs_browser_proxy.js';
import { createOriginInfo,createSiteGroup} from './test_util.js';
// clang-format on
suite('SiteEntry_DisabledConsolidatedControls', function() {
/**
* An example eTLD+1 Object with multiple origins grouped under it.
*/
const TEST_MULTIPLE_SITE_GROUP = createSiteGroup('example.com', [
'http://example.com',
'https://www.example.com',
'https://login.example.com',
]);
/**
* An example eTLD+1 Object with a single origin in it.
*/
const TEST_SINGLE_SITE_GROUP = createSiteGroup('foo.com', [
'https://login.foo.com',
]);
/**
* The mock proxy object to use during test.
*/
let browserProxy: TestSiteSettingsPrefsBrowserProxy;
/**
* The mock local data proxy object to use during test.
*/
let localDataBrowserProxy: TestLocalDataBrowserProxy;
/**
* A site list element created before each test.
*/
let testElement: SiteEntryElement;
suiteSetup(function() {
loadTimeData.overrideValues({
consolidatedSiteStorageControlsEnabled: false,
});
});
// Initialize a site-list before each test.
setup(function() {
browserProxy = new TestSiteSettingsPrefsBrowserProxy();
localDataBrowserProxy = new TestLocalDataBrowserProxy();
SiteSettingsPrefsBrowserProxyImpl.setInstance(browserProxy);
LocalDataBrowserProxyImpl.setInstance(localDataBrowserProxy);
document.body.innerHTML = '';
testElement = document.createElement('site-entry');
document.body.appendChild(testElement);
});
teardown(function() {
// The code being tested changes the Route. Reset so that state is not
// leaked across tests.
Router.getInstance().resetRouteForTesting();
});
test('displays the correct number of origins', function() {
testElement.siteGroup = TEST_MULTIPLE_SITE_GROUP;
flush();
const collapseChild = testElement.$.originList.get();
flush();
assertEquals(3, collapseChild.querySelectorAll('.origin-link').length);
});
test('expands and closes to show more origins', function() {
testElement.siteGroup = TEST_MULTIPLE_SITE_GROUP;
assertFalse(testElement.$.expandIcon.hidden);
assertEquals(
'false', testElement.$.toggleButton.getAttribute('aria-expanded'));
const originList = testElement.$.originList.get();
assertTrue(originList.classList.contains('iron-collapse-closed'));
assertEquals('true', originList.getAttribute('aria-hidden'));
testElement.$.toggleButton.click();
assertEquals(
'true', testElement.$.toggleButton.getAttribute('aria-expanded'));
assertTrue(originList.classList.contains('iron-collapse-opened'));
assertEquals('false', originList.getAttribute('aria-hidden'));
});
test('with single origin navigates to Site Details', function() {
testElement.siteGroup = TEST_SINGLE_SITE_GROUP;
assertTrue(testElement.$.expandIcon.hidden);
assertEquals(
'false', testElement.$.toggleButton.getAttribute('aria-expanded'));
const originList = testElement.$.originList.get();
assertTrue(originList.classList.contains('iron-collapse-closed'));
assertEquals('true', originList.getAttribute('aria-hidden'));
testElement.$.toggleButton.click();
assertEquals(
'false', testElement.$.toggleButton.getAttribute('aria-expanded'));
assertTrue(originList.classList.contains('iron-collapse-closed'));
assertEquals('true', originList.getAttribute('aria-hidden'));
assertEquals(
routes.SITE_SETTINGS_SITE_DETAILS.path,
Router.getInstance().getCurrentRoute().path);
assertEquals(
'https://login.foo.com',
Router.getInstance().getQueryParameters().get('site'));
});
test('with multiple origins navigates to Site Details', function() {
testElement.siteGroup = TEST_MULTIPLE_SITE_GROUP;
flush();
const collapseChild = testElement.$.originList.get();
flush();
const originList =
collapseChild.querySelectorAll<HTMLElement>('.origin-link');
assertEquals(3, originList.length);
// Test clicking on one of these origins takes the user to Site Details,
// with the correct origin.
originList[1]!.click();
assertEquals(
routes.SITE_SETTINGS_SITE_DETAILS.path,
Router.getInstance().getCurrentRoute().path);
assertEquals(
TEST_MULTIPLE_SITE_GROUP.origins[1]!.origin,
Router.getInstance().getQueryParameters().get('site'));
});
test('with single origin, shows overflow menu', function() {
testElement.siteGroup = TEST_SINGLE_SITE_GROUP;
flush();
const overflowMenuButton =
testElement.$$<HTMLElement>('#overflowMenuButton')!;
assertFalse(
overflowMenuButton.closest<HTMLElement>('.row-aligned')!.hidden);
});
test('clear data for single origin fires the right method', async function() {
testElement.siteGroup =
JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP));
flush();
const collapseChild = testElement.$.originList.get();
flush();
const originList = collapseChild.querySelectorAll('.hr');
assertEquals(3, originList.length);
for (let i = 0; i < originList.length; i++) {
const menuOpened = eventToPromise('open-menu', testElement);
const originEntry = originList[i]!;
const overflowMenuButton =
originEntry.querySelector<HTMLElement>('#originOverflowMenuButton')!;
overflowMenuButton.click();
const openMenuEvent = await menuOpened;
const args = openMenuEvent.detail;
const {actionScope, index, origin} = args;
assertEquals('origin', actionScope);
assertEquals(testElement.listIndex, index);
assertEquals(testElement.siteGroup.origins[i]!.origin, origin);
}
});
test(
'moving from grouped to ungrouped does not get stuck in opened state',
function() {
// Clone this object to avoid propagating changes made in this test.
testElement.siteGroup =
JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP));
flush();
testElement.$.toggleButton.click();
assertTrue(testElement.$.originList.get().opened);
// Remove all origins except one, then make sure it's not still
// expanded.
const siteGroupUpdated =
JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP));
siteGroupUpdated.origins.splice(1);
testElement.siteGroup = siteGroupUpdated;
assertEquals(1, testElement.siteGroup.origins.length);
assertFalse(testElement.$.originList.get().opened);
});
test('cookies show correctly for grouped entries', function() {
testElement.siteGroup = TEST_MULTIPLE_SITE_GROUP;
flush();
const cookiesLabel = testElement.$.cookies;
assertTrue(cookiesLabel.hidden);
// When the number of cookies is more than zero, the label appears.
const testSiteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP));
const numCookies = 3;
testSiteGroup.numCookies = numCookies;
testElement.siteGroup = testSiteGroup;
flush();
return localDataBrowserProxy.whenCalled('getNumCookiesString')
.then((args) => {
assertEquals(3, args);
assertFalse(cookiesLabel.hidden);
assertEquals('· 3 cookies', cookiesLabel.textContent!.trim());
});
});
test('cookies show for ungrouped entries', function() {
testElement.siteGroup = TEST_SINGLE_SITE_GROUP;
flush();
const cookiesLabel = testElement.$.cookies;
assertTrue(cookiesLabel.hidden);
const testSiteGroup = JSON.parse(JSON.stringify(TEST_SINGLE_SITE_GROUP));
const numCookies = 3;
testSiteGroup.numCookies = numCookies;
testElement.siteGroup = testSiteGroup;
flush();
return localDataBrowserProxy.whenCalled('getNumCookiesString')
.then((args) => {
assertEquals(3, args);
assertFalse(cookiesLabel.hidden);
assertEquals('· 3 cookies', cookiesLabel.textContent!.trim());
});
});
test('data usage shown correctly for grouped entries', function() {
// Clone this object to avoid propagating changes made in this test.
const testSiteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP));
const numBytes1 = 74622;
const numBytes2 = 1274;
const numBytes3 = 0;
testSiteGroup.origins[0].usage = numBytes1;
testSiteGroup.origins[1].usage = numBytes2;
testSiteGroup.origins[2].usage = numBytes3;
testElement.siteGroup = testSiteGroup;
flush();
return browserProxy.whenCalled('getFormattedBytes').then(args => {
const sumBytes = numBytes1 + numBytes2 + numBytes3;
assertEquals(sumBytes, args);
assertEquals(
`${sumBytes} B`,
testElement.shadowRoot!
.querySelector<HTMLElement>(
'#displayName .data-unit')!.textContent!.trim());
});
});
test('data usage shown correctly for ungrouped entries', function() {
// Clone this object to avoid propagating changes made in this test.
const testSiteGroup = JSON.parse(JSON.stringify(TEST_SINGLE_SITE_GROUP));
const numBytes = 74622;
testSiteGroup.origins[0].usage = numBytes;
testElement.siteGroup = testSiteGroup;
flush();
return browserProxy.whenCalled('getFormattedBytes').then(args => {
assertEquals(numBytes, args);
assertEquals(
`${numBytes} B`,
testElement.shadowRoot!
.querySelector<HTMLElement>(
'#displayName .data-unit')!.textContent!.trim());
});
});
test(
'large number data usage shown correctly for grouped entries',
function() {
// Clone this object to avoid propagating changes made in this test.
const testSiteGroup =
JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP));
const numBytes1 = 2000000000;
const numBytes2 = 10000000000;
const numBytes3 = 7856;
testSiteGroup.origins[0].usage = numBytes1;
testSiteGroup.origins[1].usage = numBytes2;
testSiteGroup.origins[2].usage = numBytes3;
testElement.siteGroup = testSiteGroup;
flush();
return browserProxy.whenCalled('getFormattedBytes').then((args) => {
const sumBytes = numBytes1 + numBytes2 + numBytes3;
assertEquals(sumBytes, args);
assertEquals(
`${sumBytes} B`,
testElement.shadowRoot!
.querySelector<HTMLElement>(
'#displayName .data-unit')!.textContent!.trim());
});
});
test('favicon with www.etld+1 chosen for site group', function() {
// Clone this object to avoid propagating changes made in this test.
const testSiteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP));
testSiteGroup.origins[0].usage = 0;
testSiteGroup.origins[1].usage = 1274;
testSiteGroup.origins[2].usage = 74622;
testElement.siteGroup = testSiteGroup;
flush();
assertEquals(
testElement.$.collapseParent.querySelector('site-favicon')!.url,
'https://www.example.com');
});
test('favicon with largest storage chosen for site group', function() {
// Clone this object to avoid propagating changes made in this test.
const testSiteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP));
testSiteGroup.origins[0].usage = 0;
testSiteGroup.origins[1].usage = 1274;
testSiteGroup.origins[2].usage = 74622;
testSiteGroup.origins[1].origin = 'https://abc.example.com';
testElement.siteGroup = testSiteGroup;
flush();
assertEquals(
testElement.$.collapseParent.querySelector('site-favicon')!.url,
'https://login.example.com');
});
test('favicon with largest cookies number chosen for site group', function() {
// Clone this object to avoid propagating changes made in this test.
const testSiteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP));
testSiteGroup.origins[0].usage = 0;
testSiteGroup.origins[1].usage = 1274;
testSiteGroup.origins[2].usage = 1274;
testSiteGroup.origins[0].numCookies = 10;
testSiteGroup.origins[1].numCookies = 3;
testSiteGroup.origins[2].numCookies = 1;
testSiteGroup.origins[1].origin = 'https://abc.example.com';
testElement.siteGroup = testSiteGroup;
flush();
assertEquals(
testElement.$.collapseParent.querySelector('site-favicon')!.url,
'https://abc.example.com');
});
test('can be sorted by most visited', function() {
// Clone this object to avoid propagating changes made in this test.
const testSiteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP));
testSiteGroup.origins[0].engagement = 20;
testSiteGroup.origins[1].engagement = 30;
testSiteGroup.origins[2].engagement = 10;
testSiteGroup.origins[0].usage = 0;
testSiteGroup.origins[1].usage = 1274;
testSiteGroup.origins[2].usage = 1274;
testSiteGroup.origins[0].numCookies = 10;
testSiteGroup.origins[1].numCookies = 3;
testSiteGroup.origins[2].numCookies = 1;
testElement.sortMethod = SortMethod.MOST_VISITED;
testElement.siteGroup = testSiteGroup;
flush();
const collapseChild = testElement.$.originList.get();
flush();
const origins = collapseChild.querySelectorAll('.origin-link');
assertEquals(3, origins.length);
assertEquals(
'www.example.com',
origins[0]!.querySelector<HTMLElement>(
'#originSiteRepresentation')!.innerText.trim());
assertEquals(
'example.com',
origins[1]!.querySelector<HTMLElement>(
'#originSiteRepresentation')!.innerText.trim());
assertEquals(
'login.example.com',
origins[2]!.querySelector<HTMLElement>(
'#originSiteRepresentation')!.innerText.trim());
});
test('can be sorted by storage', function() {
// Clone this object to avoid propagating changes made in this test.
const testSiteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP));
testSiteGroup.origins[0].engagement = 20;
testSiteGroup.origins[1].engagement = 30;
testSiteGroup.origins[2].engagement = 10;
testSiteGroup.origins[0].usage = 0;
testSiteGroup.origins[1].usage = 1274;
testSiteGroup.origins[2].usage = 1274;
testSiteGroup.origins[0].numCookies = 10;
testSiteGroup.origins[1].numCookies = 3;
testSiteGroup.origins[2].numCookies = 1;
testElement.sortMethod = SortMethod.STORAGE;
testElement.siteGroup = testSiteGroup;
flush();
const collapseChild = testElement.$.originList.get();
flush();
const origins = collapseChild.querySelectorAll('.origin-link');
assertEquals(3, origins.length);
assertEquals(
'www.example.com',
origins[0]!.querySelector<HTMLElement>(
'#originSiteRepresentation')!.innerText.trim());
assertEquals(
'login.example.com',
origins[1]!.querySelector<HTMLElement>(
'#originSiteRepresentation')!.innerText.trim());
assertEquals(
'example.com',
origins[2]!.querySelector<HTMLElement>(
'#originSiteRepresentation')!.innerText.trim());
});
test('can be sorted by name', function() {
// Clone this object to avoid propagating changes made in this test.
const testSiteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP));
testSiteGroup.origins[0].engagement = 20;
testSiteGroup.origins[1].engagement = 30;
testSiteGroup.origins[2].engagement = 10;
testSiteGroup.origins[0].usage = 0;
testSiteGroup.origins[1].usage = 1274;
testSiteGroup.origins[2].usage = 1274;
testSiteGroup.origins[0].numCookies = 10;
testSiteGroup.origins[1].numCookies = 3;
testSiteGroup.origins[2].numCookies = 1;
testElement.sortMethod = SortMethod.NAME;
testElement.siteGroup = testSiteGroup;
flush();
const collapseChild = testElement.$.originList.get();
flush();
const origins = collapseChild.querySelectorAll('.origin-link');
assertEquals(3, origins.length);
assertEquals(
'example.com',
origins[0]!.querySelector<HTMLElement>(
'#originSiteRepresentation')!.innerText.trim());
assertEquals(
'login.example.com',
origins[1]!.querySelector<HTMLElement>(
'#originSiteRepresentation')!.innerText.trim());
assertEquals(
'www.example.com',
origins[2]!.querySelector<HTMLElement>(
'#originSiteRepresentation')!.innerText.trim());
});
});
suite('SiteEntry_EnabledConsolidatedControls', function() {
/**
* An example eTLD+1 Object with multiple origins grouped under it.
*/
const TEST_MULTIPLE_SITE_GROUP = createSiteGroup('example.com', [
'http://example.com',
'https://www.example.com',
'https://login.example.com',
]);
/**
* An example eTLD+1 Object with a single origin in it.
*/
const TEST_SINGLE_SITE_GROUP = createSiteGroup('foo.com', [
'https://login.foo.com',
]);
/**
* The mock proxy object to use during test.
*/
let browserProxy: TestSiteSettingsPrefsBrowserProxy;
/**
* The mock local data proxy object to use during test.
*/
let localDataBrowserProxy: TestLocalDataBrowserProxy;
/**
* A site list element created before each test.
*/
let testElement: SiteEntryElement;
suiteSetup(function() {
loadTimeData.overrideValues({
consolidatedSiteStorageControlsEnabled: true,
});
});
// Initialize a site-list before each test.
setup(function() {
browserProxy = new TestSiteSettingsPrefsBrowserProxy();
localDataBrowserProxy = new TestLocalDataBrowserProxy();
SiteSettingsPrefsBrowserProxyImpl.setInstance(browserProxy);
LocalDataBrowserProxyImpl.setInstance(localDataBrowserProxy);
document.body.innerHTML = '';
testElement = document.createElement('site-entry');
document.body.appendChild(testElement);
});
test('remove site fires correct event for individual site', async function() {
testElement.siteGroup =
JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP));
flush();
const collapseChild = testElement.$.originList.get();
flush();
const originList = collapseChild.querySelectorAll('.hr');
assertEquals(3, originList.length);
for (let i = 0; i < originList.length; i++) {
const siteRemoved = eventToPromise('remove-site', testElement);
originList[i]!.querySelector<HTMLElement>('#removeOriginButton')!.click();
const siteRemovedEvent = await siteRemoved;
const {actionScope, index, origin} = siteRemovedEvent.detail;
assertEquals('origin', actionScope);
assertEquals(testElement.listIndex, index);
assertEquals(testElement.siteGroup.origins[i]!.origin, origin);
}
});
test('remove site fires correct event for site group', async function() {
testElement.siteGroup =
JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP));
flush();
const siteRemoved = eventToPromise('remove-site', testElement);
testElement.$$<HTMLElement>('#removeSiteButton')!.click();
const siteRemovedEvent = await siteRemoved;
const {actionScope, index, origin} = siteRemovedEvent.detail;
// Site groups are removed exclusively based on their index.
assertEquals(undefined, actionScope);
assertEquals(testElement.listIndex, index);
assertEquals(undefined, origin);
});
test('partitioned entry interaction', async function() {
// Clone this object to avoid propagating changes made in this test.
const testSiteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP));
// Add a partitioned entry for an unrelated origin.
testSiteGroup.origins.push(
createOriginInfo('wwww.unrelated.com', {isPartitioned: true}));
testElement.siteGroup = testSiteGroup;
flush();
const collapseChild = testElement.$.originList.get();
testElement.$.toggleButton.click();
flush();
const originList = collapseChild.querySelectorAll('.hr');
assertEquals(4, originList.length);
// Partitioned entries should not be displaying a link arrow, while
// unpartitioned entries should.
assertTrue(isChildVisible(
originList[0]!, 'cr-icon-button', /*checkLightDom=*/ true));
assertFalse(isChildVisible(
originList[3]!, 'cr-icon-button', /*checkLightDom=*/ true));
// Removing a partitioned entry should fire the appropriate event.
const siteRemoved = eventToPromise('remove-site', testElement);
originList[3]!.querySelector<HTMLElement>('#removeOriginButton')!.click();
const siteRemovedEvent = await siteRemoved;
const args = siteRemovedEvent.detail;
const {actionScope, index, origin, isPartitioned} = args;
assertEquals('origin', actionScope);
assertEquals(testElement.listIndex, index);
assertEquals(testElement.siteGroup.origins[3]!.origin, origin);
assertTrue(isPartitioned);
});
test('partitioned entry prevents collapse', function() {
// If a siteGroup has a partitioned entry, even if it is the only entry,
// it should keep the site entry as a top level + collapse list.
const testSingleSite = JSON.parse(JSON.stringify(TEST_SINGLE_SITE_GROUP));
testSingleSite.origins[0].isPartitioned = true;
testElement.siteGroup = testSingleSite;
flush();
const collapseChild = testElement.$.originList.get();
// The toggle button should expand the collapse, rather than navigate.
const startingRoute = Router.getInstance().getCurrentRoute();
testElement.$.toggleButton.click();
flush();
assertEquals(startingRoute, Router.getInstance().getCurrentRoute());
const originList = collapseChild.querySelectorAll('.hr');
assertEquals(1, originList.length);
});
test('unpartitioned entry remains collapsed', async function() {
// Check that a single origin containing unpartitioned storage only is
// correctly collapsed.
testElement.siteGroup = JSON.parse(JSON.stringify(TEST_SINGLE_SITE_GROUP));
flush();
const collapseChild = testElement.$.originList.get();
const originList = collapseChild.querySelectorAll('.hr');
testElement.$.toggleButton.click();
flush();
assertEquals(0, originList.length);
// Clicking the toggleButton should navigate the page away, as there is
// only one entry.
testElement.$.toggleButton.click();
flush();
assertEquals(
routes.SITE_SETTINGS_SITE_DETAILS.path,
Router.getInstance().getCurrentRoute().path);
});
}); | the_stack |
import { Readable } from 'stream';
import { ActionContext, Bus } from '@comunica/core';
import type * as RDF from '@rdfjs/types';
import { DataFactory } from 'rdf-data-factory';
import 'jest-rdf';
import { RdfSourceQpf } from '../lib/RdfSourceQpf';
const arrayifyStream = require('arrayify-stream');
const quad = require('rdf-quad');
const streamifyArray = require('streamify-array');
const DF = new DataFactory();
const v = DF.variable('v');
describe('RdfSourceQpf', () => {
let source: RdfSourceQpf;
let bus: any;
let metadata: any;
let mediatorMetadata: any;
let mediatorMetadataExtract: any;
let mediatorRdfDereference: any;
let S: RDF.Term;
let P: RDF.Term;
let O: RDF.Term;
let G: RDF.Term;
beforeEach(() => {
bus = new Bus({ name: 'bus' });
mediatorMetadata = {
mediate: (args: any) => Promise.resolve({
data: args.quads,
metadata: args.quads,
}),
};
mediatorMetadataExtract = {
mediate: (action: any) => new Promise((resolve, reject) => {
action.metadata.on('error', reject);
action.metadata.on('end', () => resolve({ metadata: { next: 'NEXT' }}));
}),
};
mediatorRdfDereference = {
mediate: (args: any) => Promise.resolve({
url: args.url,
quads: streamifyArray([
quad('s1', 'p1', 'o1'),
quad('s2', 'p2', 'o2'),
]),
triples: false,
}),
};
metadata = {
searchForms: {
values: [
{
getUri: (entries: any) => `${entries.s || '_'},${entries.p || '_'},${entries.o || '_'
},${entries.g || '_'}`,
mappings: {
g: 'G',
o: 'O',
p: 'P',
s: 'S',
},
},
],
},
};
source = new RdfSourceQpf(
mediatorMetadata,
mediatorMetadataExtract,
mediatorRdfDereference,
's',
'p',
'o',
'g',
metadata,
ActionContext({}),
streamifyArray([
quad('s1', 'p1', 'o1'),
quad('s2', 'p2', 'o2'),
]),
);
S = DF.namedNode('S');
P = DF.namedNode('P');
O = DF.namedNode('O');
G = DF.namedNode('G');
});
describe('#constructor', () => {
it('should be a function', () => {
return expect(RdfSourceQpf).toBeInstanceOf(Function);
});
it('should be constructable without initialQuads', () => {
const s = new RdfSourceQpf(
mediatorMetadata,
mediatorMetadataExtract,
mediatorRdfDereference,
'o',
'p',
's',
'g',
metadata,
ActionContext({}),
undefined,
);
expect(s).toBeInstanceOf(RdfSourceQpf);
expect((<any> s).initialQuads).toBeFalsy();
});
it('should be constructable with initialQuads', async() => {
const s = new RdfSourceQpf(
mediatorMetadata,
mediatorMetadataExtract,
mediatorRdfDereference,
'o',
'p',
's',
'g',
metadata,
ActionContext({}),
streamifyArray([
quad('s1', 'p1', 'o1'),
quad('s2', 'p2', 'o2'),
]),
);
expect(s).toBeInstanceOf(RdfSourceQpf);
expect(await arrayifyStream((<any> s).getCachedQuads(v, v, v, v))).toBeRdfIsomorphic([
quad('s1', 'p1', 'o1'),
quad('s2', 'p2', 'o2'),
]);
});
});
describe('getSearchForm', () => {
it('should return a searchForm', () => {
return expect(source.getSearchForm(metadata)).toEqual(metadata.searchForms.values[0]);
});
it('should return a searchForm without graph', () => {
metadata = {
searchForms: {
values: [
{
getUri: (entries: any) => `${entries.s || '_'},${entries.p || '_'},${entries.o || '_'
},${entries.g || '_'}`,
mappings: {
o: 'O',
p: 'P',
s: 'S',
},
},
],
},
};
return expect(source.getSearchForm(metadata)).toEqual(metadata.searchForms.values[0]);
});
it('should return null when no valid mappings are present', () => {
metadata = {
searchForms: {
values: [
{
mappings: {},
},
],
},
};
return expect(source.getSearchForm(metadata)).toBe(undefined);
});
it('should return null when no values are present', () => {
metadata = {
searchForms: {},
};
return expect(source.getSearchForm(metadata)).toBe(undefined);
});
it('should return null when no search forms are present', () => {
metadata = {
};
return expect(source.getSearchForm(metadata)).toBe(undefined);
});
});
describe('createFragmentUri', () => {
it('should create a valid fragment URI with materialized terms', () => {
return expect(source.createFragmentUri(metadata.searchForms.values[0],
DF.namedNode('S'),
DF.namedNode('P'),
DF.namedNode('O'),
DF.namedNode('G')))
.toEqual('S,P,O,G');
});
it('should create a valid fragment URI with only a few materialized terms', () => {
return expect(source.createFragmentUri(metadata.searchForms.values[0],
v,
DF.namedNode('P'),
v,
DF.namedNode('G')))
.toEqual('_,P,_,G');
});
});
describe('match', () => {
it('should return a copy of the initial quads for the empty pattern', async() => {
expect(await arrayifyStream(source.match(v, v, v, v))).toBeRdfIsomorphic([
quad('s1', 'p1', 'o1'),
quad('s2', 'p2', 'o2'),
]);
});
it('should emit metadata for the empty pattern', async() => {
const output = source.match(v, v, v, v);
const metadataPromise = new Promise(resolve => output.getProperty('metadata', resolve));
await arrayifyStream(output);
expect(await metadataPromise).toBe(metadata);
});
it('should return a copy of the initial quads for the empty pattern with the default graph', async() => {
expect(await arrayifyStream(source.match(
v, v, v, DF.defaultGraph(),
)))
.toBeRdfIsomorphic([
quad('s1', 'p1', 'o1'),
quad('s2', 'p2', 'o2'),
]);
});
it('should return multiple copies of the initial quads for the empty pattern', async() => {
expect(await arrayifyStream(source.match(v, v, v, v))).toBeRdfIsomorphic([
quad('s1', 'p1', 'o1'),
quad('s2', 'p2', 'o2'),
]);
expect(await arrayifyStream(source.match(v, v, v, v))).toBeRdfIsomorphic([
quad('s1', 'p1', 'o1'),
quad('s2', 'p2', 'o2'),
]);
expect(await arrayifyStream(source.match(v, v, v, v))).toBeRdfIsomorphic([
quad('s1', 'p1', 'o1'),
quad('s2', 'p2', 'o2'),
]);
});
it('should handle a non-empty pattern and filter only matching quads', async() => {
expect(await arrayifyStream(source.match(
DF.namedNode('s1'), v, DF.namedNode('o1'), v,
)))
.toBeRdfIsomorphic([
quad('s1', 'p1', 'o1'),
]);
expect(await arrayifyStream(source.match(
DF.namedNode('s2'), v, DF.namedNode('o2'), v,
)))
.toBeRdfIsomorphic([
quad('s2', 'p2', 'o2'),
]);
expect(await arrayifyStream(source.match(
DF.namedNode('s3'), v, DF.namedNode('o3'), v,
)))
.toBeRdfIsomorphic([]);
});
it('should emit metadata for a non-empty pattern', async() => {
const output = source.match(DF.namedNode('s1'), v, DF.namedNode('o1'), v);
const metadataPromise = new Promise(resolve => output.getProperty('metadata', resolve));
await arrayifyStream(output);
expect(await metadataPromise).toEqual({ next: 'NEXT' });
});
// The following test is not applicable anymore.
// Filtering with shared variables has been moved up into the quad pattern query operation actor
// it('should handle a pattern with variables that occur multiple times in the pattern', async () => {
// mediatorRdfDereference.mediate = (args) => Promise.resolve({
// url: args.url,
// quads: streamifyArray([
// quad('s1', 'p1', 'o1'),
// quad('s2', 'p2', 'o2'),
// quad('t', 'p2', 't'),
// ]),
// triples: false,
// });
//
// expect(await arrayifyStream(source.match(
// DF.variable('v'), null, DF.variable('v'))))
// .toBeRdfIsomorphic([
// quad('t', 'p2', 't'),
// ]);
// });
it('should delegate errors from the RDF dereference stream', () => {
const quads = new Readable();
quads._read = () => {
quads.emit('error', error);
};
mediatorRdfDereference.mediate = (args: any) => Promise.resolve({
url: args.url,
quads,
triples: false,
});
const error = new Error('a');
return new Promise<void>((resolve, reject) => {
const output: RDF.Stream = source.match(S, P, O, G);
output.on('error', e => {
expect(e).toEqual(error);
resolve();
});
output.on('data', reject);
output.on('end', reject);
});
});
it('should delegate errors from the metadata split stream', () => {
const quads = new Readable();
quads._read = () => {
quads.emit('error', error);
};
mediatorMetadata.mediate = () => Promise.resolve({
data: quads,
metadata: quads,
});
const error = new Error('a');
return new Promise<void>((resolve, reject) => {
const output: RDF.Stream = source.match(S, P, O, G);
output.on('error', e => {
expect(e).toEqual(error);
resolve();
});
output.on('data', reject);
output.on('end', reject);
});
});
it('should ignore errors from the metadata extract mediator', async() => {
mediatorMetadataExtract.mediate = () => Promise.reject(new Error('abc'));
expect(await arrayifyStream(source.match(v, v, v, v))).toBeRdfIsomorphic([
quad('s1', 'p1', 'o1'),
quad('s2', 'p2', 'o2'),
]);
});
});
});
// eslint-disable-next-line mocha/max-top-level-suites
describe('RdfSourceQpf with a custom default graph', () => {
let source: RdfSourceQpf;
let bus: any;
let metadata: any;
let mediatorMetadata: any;
let mediatorMetadataExtract: any;
let mediatorRdfDereference: any;
let S: RDF.Term;
let P: RDF.Term;
let O: RDF.Term;
let G: RDF.Term;
beforeEach(() => {
bus = new Bus({ name: 'bus' });
mediatorMetadata = {
mediate: (args: any) => Promise.resolve({
data: args.quads,
metadata: null,
}),
};
mediatorMetadataExtract = {
mediate: () => Promise.resolve({ metadata: { next: 'NEXT' }}),
};
mediatorRdfDereference = {
mediate: (args: any) => Promise.resolve({
url: args.url,
quads: streamifyArray([
quad('s1', 'p1', 'o1', 'DEFAULT_GRAPH'),
quad('s2', 'p2', 'o2', 'DEFAULT_GRAPH'),
quad('s1', 'p3', 'o1', 'CUSTOM_GRAPH'),
quad('s2', 'p4', 'o2', 'CUSTOM_GRAPH'),
quad('DEFAULT_GRAPH', 'defaultInSubject', 'o2', 'DEFAULT_GRAPH'),
quad('s1-', 'actualDefaultGraph', 'o1'),
]),
triples: false,
}),
};
metadata = {
defaultGraph: 'DEFAULT_GRAPH',
searchForms: {
values: [
{
getUri: (entries: any) => `${entries.s || '_'},${entries.p || '_'},${entries.o || '_'
},${entries.g || '_'}`,
mappings: {
g: 'G',
o: 'O',
p: 'P',
s: 'S',
},
},
],
},
};
source = new RdfSourceQpf(
mediatorMetadata,
mediatorMetadataExtract,
mediatorRdfDereference,
's',
'p',
'o',
'g',
metadata,
ActionContext({}),
streamifyArray([
quad('s1', 'p1', 'o1', 'DEFAULT_GRAPH'),
quad('s2', 'p2', 'o2', 'DEFAULT_GRAPH'),
quad('s1', 'p3', 'o1', 'CUSTOM_GRAPH'),
quad('s2', 'p4', 'o2', 'CUSTOM_GRAPH'),
quad('DEFAULT_GRAPH', 'defaultInSubject', 'o2', 'DEFAULT_GRAPH'),
quad('s1-', 'actualDefaultGraph', 'o1'),
]),
);
S = DF.namedNode('S');
P = DF.namedNode('P');
O = DF.namedNode('O');
G = DF.namedNode('G');
});
describe('match', () => {
it('should return quads in the overridden default graph', async() => {
expect(await arrayifyStream(source.match(
DF.namedNode('s1'), v, DF.namedNode('o1'), DF.defaultGraph(),
)))
.toBeRdfIsomorphic([
quad('s1', 'p1', 'o1'),
]);
expect(await arrayifyStream(source.match(
DF.namedNode('s2'), v, DF.namedNode('o2'), DF.defaultGraph(),
)))
.toBeRdfIsomorphic([
quad('s2', 'p2', 'o2'),
]);
expect(await arrayifyStream(source.match(
DF.namedNode('s3'), v, DF.namedNode('o3'), DF.defaultGraph(),
)))
.toBeRdfIsomorphic([]);
});
it('should return quads in all graphs', async() => {
expect(await arrayifyStream(source.match(
DF.namedNode('s1'), v, DF.namedNode('o1'), v,
)))
.toBeRdfIsomorphic([
quad('s1', 'p1', 'o1'),
quad('s1', 'p3', 'o1', 'CUSTOM_GRAPH'),
]);
expect(await arrayifyStream(source.match(
DF.namedNode('s2'), v, DF.namedNode('o2'), v,
)))
.toBeRdfIsomorphic([
quad('s2', 'p2', 'o2'),
quad('s2', 'p4', 'o2', 'CUSTOM_GRAPH'),
]);
expect(await arrayifyStream(source.match(
DF.namedNode('s3'), v, DF.namedNode('o3'), v,
)))
.toBeRdfIsomorphic([]);
});
it('should return quads in a custom graph', async() => {
expect(await arrayifyStream(source.match(
DF.namedNode('s1'), v, DF.namedNode('o1'), DF.namedNode('CUSTOM_GRAPH'),
)))
.toBeRdfIsomorphic([
quad('s1', 'p3', 'o1', 'CUSTOM_GRAPH'),
]);
expect(await arrayifyStream(source.match(
DF.namedNode('s2'), v, DF.namedNode('o2'), DF.namedNode('CUSTOM_GRAPH'),
)))
.toBeRdfIsomorphic([
quad('s2', 'p4', 'o2', 'CUSTOM_GRAPH'),
]);
expect(await arrayifyStream(source.match(
DF.namedNode('s3'), v, DF.namedNode('o3'), DF.namedNode('CUSTOM_GRAPH'),
)))
.toBeRdfIsomorphic([]);
});
it('should not modify an overridden default graph in the subject position', async() => {
expect(await arrayifyStream(source.match(
v, DF.namedNode('defaultInSubject'), v, v,
)))
.toBeRdfIsomorphic([
quad('DEFAULT_GRAPH', 'defaultInSubject', 'o2', DF.defaultGraph()),
]);
});
it('should also return triples from the actual default graph', async() => {
expect(await arrayifyStream(source.match(
v, DF.namedNode('actualDefaultGraph'), v, v,
)))
.toBeRdfIsomorphic([
quad('s1-', 'actualDefaultGraph', 'o1', DF.defaultGraph()),
]);
expect(await arrayifyStream(source.match(
v, DF.namedNode('actualDefaultGraph'), v, DF.defaultGraph(),
)))
.toBeRdfIsomorphic([
quad('s1-', 'actualDefaultGraph', 'o1', DF.defaultGraph()),
]);
});
it('should return a mapped copy of the initial quads for the empty pattern', async() => {
expect(await arrayifyStream(source.match(v, v, v, v))).toBeRdfIsomorphic([
quad('s1', 'p1', 'o1', DF.defaultGraph()),
quad('s2', 'p2', 'o2', DF.defaultGraph()),
quad('s1', 'p3', 'o1', 'CUSTOM_GRAPH'),
quad('s2', 'p4', 'o2', 'CUSTOM_GRAPH'),
quad('DEFAULT_GRAPH', 'defaultInSubject', 'o2', DF.defaultGraph()),
quad('s1-', 'actualDefaultGraph', 'o1'),
]);
});
});
}); | the_stack |
import { define } from 'elements-sk/define';
import { html } from 'lit-html';
import { ParamSet, toParamSet, fromParamSet } from 'common-sk/modules/query';
import { ElementSk } from '../../../infra-sk/modules/ElementSk';
import {
TaskSchedulerService,
SearchJobsResponse,
SearchJobsRequest,
Job,
JobStatus,
} from '../rpc';
import 'elements-sk/icon/delete-icon-sk';
import 'elements-sk/styles/buttons';
import 'elements-sk/styles/table';
import { $$ } from 'common-sk/modules/dom';
// Names and types of search terms.
interface DisplaySearchTerm {
label: string;
type: string;
}
// TODO(borenet): Find a way not to duplicate the contents of SearchJobRequest.
const searchTerms: { [key: string]: DisplaySearchTerm } = {
name: { label: 'Name', type: 'text' },
repo: { label: 'Repo', type: 'text' },
revision: { label: 'Revision', type: 'text' },
issue: { label: 'Issue', type: 'text' },
patchset: { label: 'Patchset', type: 'text' },
buildbucketBuildId: { label: 'Buildbucket Build ID', type: 'text' },
isForce: { label: 'Manually Triggered', type: 'checkbox' },
status: { label: 'Status', type: 'text' },
timeStart: { label: 'Start Time', type: 'datetime-local' },
timeEnd: { label: 'End Time', type: 'datetime-local' },
};
// Display parameters for job results.
interface DisplayJobResult {
label: string;
class: string;
}
const jobStatusToLabelAndClass: { [key: string]: DisplayJobResult } = {
[JobStatus.JOB_STATUS_IN_PROGRESS]: {
label: 'in progress',
class: 'bg-in-progress',
},
[JobStatus.JOB_STATUS_SUCCESS]: {
label: 'succeeded',
class: 'bg-success',
},
[JobStatus.JOB_STATUS_FAILURE]: {
label: 'failed',
class: 'bg-failure',
},
[JobStatus.JOB_STATUS_MISHAP]: {
label: 'mishap',
class: 'bg-mishap',
},
[JobStatus.JOB_STATUS_CANCELED]: {
label: 'canceled',
class: 'bg-canceled',
},
};
interface SearchTerm {
key: string;
value: string;
}
export class JobSearchSk extends ElementSk {
private static template = (ele: JobSearchSk) => html`
<div class="container">
<table class="searchTerms">
${Array.from(ele.searchTerms.values()).map(
(term: SearchTerm) => html`
<tr class="searchTerms">
<th>
<label for="${term.key}">
${searchTerms[term.key]!.label}
</label>
</th>
<td>
${term.key == 'status'
? html`
<select
id="${term.key}"
@change="${(ev: Event) => {
const input = (<HTMLSelectElement>ev.target)!;
term.value = input.value;
ele.updateQuery();
}}"
selected=
>
${Object.entries(jobStatusToLabelAndClass).map(
([status, labelAndClass]) => html`
<option
value="${status}"
?selected="${term.value == status}"
>
${labelAndClass.label}
</option>
`,
)}
</select>
`
: html`
<input
.id="${term.key}"
.type="${searchTerms[term.key]!.type}"
.value="${term.value}"
?checked="${
searchTerms[term.key]!.type == 'checkbox'
&& term.value == 'true'
}"
@change="${(ev: Event) => {
const input = (<HTMLInputElement>ev.target)!;
if (searchTerms[term.key]!.type == 'checkbox') {
term.value = input.checked ? 'true' : 'false';
} else {
term.value = input.value;
}
ele.updateQuery();
}}"
>
</input>
`}
</td>
<td>
<button
class="delete"
@click="${() => {
ele.searchTerms.delete(term.key);
ele._render();
ele.updateQuery();
}}"
>
<delete-icon-sk></delete-icon-sk>
</button>
</td>
</tr>
`,
)}
<tr class="searchTerms">
<td>
<select
@change="${(ev: Event) => {
const select = <HTMLSelectElement>ev.target!;
const selected = select.value;
ele.searchTerms.set(selected, {
key: select.value,
value: '',
});
select.selectedIndex = 0;
ele._render();
ele.updateQuery();
// Auto-focus the new input field.
const inp = $$<HTMLInputElement>(`#${selected}`, ele)!;
inp?.focus();
}}"
>
<option disabled selected>Add Search Term</option>
${Object.entries(searchTerms)
.filter(([key, _]) => !ele.searchTerms.get(key))
.map(
([key, term]) => html`
<option .value="${key}">${term.label}</option>
`,
)}
</select>
</td>
<td></td>
<td>
<button class="search" @click="${ele.search}">Search</button>
</td>
</tr>
</table>
</div>
${ele.results && ele.results.length > 0
? html`
<div class="container">
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Repo</th>
<th>Revision</th>
<th>Codereview Link</th>
<th>Status</th>
<th>Manually Triggered</th>
<th>Created At</th>
<th>
<button class="cancel" @click="${ele.cancelAll}">
<delete-icon-sk></delete-icon-sk>
Cancel All
</button>
</th>
</tr>
${ele.results.map(
(job: Job) => html`
<tr>
<td>
<a href="/job/${job.id}" target="_blank">${job.id}</a>
</td>
<td>${job.name}</td>
<td>
<a href="${job.repoState?.repo}" target="_blank">
${job.repoState?.repo}
</a>
</td>
<td>
<a
href="${job.repoState!.repo}/+show/${job.repoState!
.revision}"
target="_blank"
>
${job.repoState!.revision.substring(0, 12)}
</a>
</td>
<td>
${job.repoState?.patch?.issue
&& job.repoState?.patch?.patchset
&& job.repoState?.patch?.server
? html`
<a
href="${job.repoState?.patch?.server}/c/${job
.repoState?.patch?.issue}/${job.repoState?.patch
?.patchset}"
target="_blank"
>${job.repoState?.patch?.server}/c/${job.repoState
?.patch?.issue}/${job.repoState?.patch
?.patchset}
</a>
`
: html``}
</td>
<td class="${jobStatusToLabelAndClass[job.status]!.class}">
${jobStatusToLabelAndClass[job.status]!.label}
</td>
<td>${job.isForce ? 'true' : 'false'}</td>
<td>${job.createdAt}</td>
<td>
${job.status === JobStatus.JOB_STATUS_IN_PROGRESS
? html`
<button
class="cancel"
@click="${() => ele.cancel(job)}"
>
<delete-icon-sk></delete-icon-sk>
Cancel
</button>
`
: html``}
</td>
</tr>
`,
)}
</table>
</div>
`
: html``}
`;
private results: Job[] = [];
private _rpc: TaskSchedulerService | null = null;
private searchTerms: Map<string, SearchTerm> = new Map();
constructor() {
super(JobSearchSk.template);
}
get rpc(): TaskSchedulerService | null {
return this._rpc;
}
set rpc(rpc: TaskSchedulerService | null) {
this._rpc = rpc;
if (this.searchTerms.size > 0) {
this.search();
}
}
connectedCallback() {
super.connectedCallback();
if (window.location.search) {
const params = toParamSet(window.location.search.substring(1));
Object.entries(params).forEach((entry: [string, string[]]) => {
const key = entry[0];
const value = entry[1][0]; // Just take the first one.
this.searchTerms.set(key, {
key: key,
value: value,
});
});
if (this.rpc) {
this.search();
}
}
this._render();
}
private updateQuery() {
const params: ParamSet = {};
this.searchTerms.forEach((term: SearchTerm) => {
params[term.key] = [term.value];
});
const newUrl = `${window.location.href.split('?')[0]}?${fromParamSet(params)}`;
window.history.replaceState('', '', newUrl);
}
private search() {
const req = {
buildbucketBuildId: this.searchTerms.get('buildbucketBuildId')?.value || '',
hasBuildbucketBuildId: !!this.searchTerms.get('buildbucketBuildId'),
isForce: this.searchTerms.get('isForce')?.value === 'true',
hasIsForce: !!this.searchTerms.get('isForce'),
issue: this.searchTerms.get('issue')?.value || '',
hasIssue: !!this.searchTerms.get('issue'),
name: this.searchTerms.get('name')?.value || '',
hasName: !!this.searchTerms.get('name'),
patchset: this.searchTerms.get('patchset')?.value || '',
hasPatchset: !!this.searchTerms.get('patchset'),
repo: this.searchTerms.get('repo')?.value || '',
hasRepo: !!this.searchTerms.get('repo'),
revision: this.searchTerms.get('revision')?.value || '',
hasRevision: !!this.searchTerms.get('revision'),
status: (this.searchTerms.get('status')?.value || null) as JobStatus,
hasStatus: !!this.searchTerms.get('status'),
timeEnd: new Date(
this.searchTerms.get('timeEnd')?.value || 0,
).toISOString(),
hasTimeEnd: !!this.searchTerms.get('timeEnd'),
timeStart: new Date(
this.searchTerms.get('timeStart')?.value || 0,
).toISOString(),
hasTimeStart: !!this.searchTerms.get('timeStart'),
};
this.rpc!.searchJobs(req as SearchJobsRequest).then(
(resp: SearchJobsResponse) => {
this.results = resp.jobs!;
this._render();
},
);
}
private cancel(job: Job) {
this.rpc!.cancelJob({ id: job.id }).then(() => {
const result = this.results.find((result: Job) => result.id == job.id);
if (result) {
result.status = JobStatus.JOB_STATUS_CANCELED;
this._render();
}
});
}
private cancelAll() {
this.results.forEach((job: Job) => {
if (job.status == JobStatus.JOB_STATUS_IN_PROGRESS) {
this.cancel(job);
}
});
}
}
define('job-search-sk', JobSearchSk); | the_stack |
/**
* number of valid bits
*/
type BitSize = "128" | "192" | "256";
/**
* implementation of AES ( Advanced Encryption Standard ) in TypeScript
*/
export class AES {
private static sBox = [
0x63,
0x7c,
0x77,
0x7b,
0xf2,
0x6b,
0x6f,
0xc5,
0x30,
0x01,
0x67,
0x2b,
0xfe,
0xd7,
0xab,
0x76,
0xca,
0x82,
0xc9,
0x7d,
0xfa,
0x59,
0x47,
0xf0,
0xad,
0xd4,
0xa2,
0xaf,
0x9c,
0xa4,
0x72,
0xc0,
0xb7,
0xfd,
0x93,
0x26,
0x36,
0x3f,
0xf7,
0xcc,
0x34,
0xa5,
0xe5,
0xf1,
0x71,
0xd8,
0x31,
0x15,
0x04,
0xc7,
0x23,
0xc3,
0x18,
0x96,
0x05,
0x9a,
0x07,
0x12,
0x80,
0xe2,
0xeb,
0x27,
0xb2,
0x75,
0x09,
0x83,
0x2c,
0x1a,
0x1b,
0x6e,
0x5a,
0xa0,
0x52,
0x3b,
0xd6,
0xb3,
0x29,
0xe3,
0x2f,
0x84,
0x53,
0xd1,
0x00,
0xed,
0x20,
0xfc,
0xb1,
0x5b,
0x6a,
0xcb,
0xbe,
0x39,
0x4a,
0x4c,
0x58,
0xcf,
0xd0,
0xef,
0xaa,
0xfb,
0x43,
0x4d,
0x33,
0x85,
0x45,
0xf9,
0x02,
0x7f,
0x50,
0x3c,
0x9f,
0xa8,
0x51,
0xa3,
0x40,
0x8f,
0x92,
0x9d,
0x38,
0xf5,
0xbc,
0xb6,
0xda,
0x21,
0x10,
0xff,
0xf3,
0xd2,
0xcd,
0x0c,
0x13,
0xec,
0x5f,
0x97,
0x44,
0x17,
0xc4,
0xa7,
0x7e,
0x3d,
0x64,
0x5d,
0x19,
0x73,
0x60,
0x81,
0x4f,
0xdc,
0x22,
0x2a,
0x90,
0x88,
0x46,
0xee,
0xb8,
0x14,
0xde,
0x5e,
0x0b,
0xdb,
0xe0,
0x32,
0x3a,
0x0a,
0x49,
0x06,
0x24,
0x5c,
0xc2,
0xd3,
0xac,
0x62,
0x91,
0x95,
0xe4,
0x79,
0xe7,
0xc8,
0x37,
0x6d,
0x8d,
0xd5,
0x4e,
0xa9,
0x6c,
0x56,
0xf4,
0xea,
0x65,
0x7a,
0xae,
0x08,
0xba,
0x78,
0x25,
0x2e,
0x1c,
0xa6,
0xb4,
0xc6,
0xe8,
0xdd,
0x74,
0x1f,
0x4b,
0xbd,
0x8b,
0x8a,
0x70,
0x3e,
0xb5,
0x66,
0x48,
0x03,
0xf6,
0x0e,
0x61,
0x35,
0x57,
0xb9,
0x86,
0xc1,
0x1d,
0x9e,
0xe1,
0xf8,
0x98,
0x11,
0x69,
0xd9,
0x8e,
0x94,
0x9b,
0x1e,
0x87,
0xe9,
0xce,
0x55,
0x28,
0xdf,
0x8c,
0xa1,
0x89,
0x0d,
0xbf,
0xe6,
0x42,
0x68,
0x41,
0x99,
0x2d,
0x0f,
0xb0,
0x54,
0xbb,
0x16,
];
private static rCon = [
[0x00, 0x00, 0x00, 0x00],
[0x01, 0x00, 0x00, 0x00],
[0x02, 0x00, 0x00, 0x00],
[0x04, 0x00, 0x00, 0x00],
[0x08, 0x00, 0x00, 0x00],
[0x10, 0x00, 0x00, 0x00],
[0x20, 0x00, 0x00, 0x00],
[0x40, 0x00, 0x00, 0x00],
[0x80, 0x00, 0x00, 0x00],
[0x1b, 0x00, 0x00, 0x00],
[0x36, 0x00, 0x00, 0x00],
];
private static cipher(input: any, w: any) {
const Nb = 4; // block size (in words): no of columns in state (fixed at 4 for AES)
const Nr = w.length / Nb - 1; // no of rounds: 10/12/14 for 128/192/256-bit keys
let state = [[], [], [], []] as any[][]; // initialise 4xNb byte-array 'state' with input [§3.4]
for (let i = 0; i < 4 * Nb; i++) {
state[i % 4][Math.floor(i / 4)] = input[i];
}
state = AES.addRoundKey(state, w, 0, Nb);
for (let round = 1; round < Nr; round++) {
state = AES.subBytes(state, Nb);
state = AES.shiftRows(state, Nb);
state = AES.mixColumns(state, Nb);
state = AES.addRoundKey(state, w, round, Nb);
}
state = AES.subBytes(state, Nb);
state = AES.shiftRows(state, Nb);
state = AES.addRoundKey(state, w, Nr, Nb);
const output = new Array(4 * Nb); // convert state to 1-d array before returning [§3.4]
for (let i = 0; i < 4 * Nb; i++)
output[i] = state[i % 4][Math.floor(i / 4)];
return output;
}
private static keyExpansion(key: any) {
const Nb = 4; // block size (in words): no of columns in state (fixed at 4 for AES)
const Nk = key.length / 4; // key length (in words): 4/6/8 for 128/192/256-bit keys
const Nr = Nk + 6; // no of rounds: 10/12/14 for 128/192/256-bit keys
const w = new Array(Nb * (Nr + 1));
let temp = new Array(4);
// initialize first Nk words of expanded key with cipher key
for (let i = 0; i < Nk; i++) {
const r = [key[4 * i], key[4 * i + 1], key[4 * i + 2], key[4 * i + 3]];
w[i] = r;
}
// expand the key into the remainder of the schedule
for (let i = Nk; i < Nb * (Nr + 1); i++) {
w[i] = new Array(4);
for (let t = 0; t < 4; t++) {
temp[t] = w[i - 1][t];
}
// each Nk'th word has extra transformation
if (i % Nk == 0) {
temp = AES.subWord(AES.rotWord(temp));
for (let t = 0; t < 4; t++) {
temp[t] ^= AES.rCon[i / Nk][t];
}
}
// 256-bit key has subWord applied every 4th word
else if (Nk > 6 && i % Nk == 4) {
temp = AES.subWord(temp);
}
// xor w[i] with w[i-1] and w[i-Nk]
for (let t = 0; t < 4; t++) {
w[i][t] = w[i - Nk][t] ^ temp[t];
}
}
return w;
}
private static subBytes(s: any, Nb: any) {
for (let r = 0; r < 4; r++) {
for (let c = 0; c < Nb; c++) {
s[r][c] = AES.sBox[s[r][c]];
}
}
return s;
}
private static shiftRows(s: any, Nb: any) {
const t = new Array(4);
for (let r = 1; r < 4; r++) {
for (let c = 0; c < 4; c++) {
t[c] = s[r][(c + r) % Nb];
} // shift into temp copy
for (let c = 0; c < 4; c++) {
s[r][c] = t[c];
} // and copy back
} // note that this will work for Nb=4,5,6, but not 7,8 (always 4 for AES):
return s; // see asmaes.sourceforge.net/rijndael/rijndaelImplementation.pdf
}
private static mixColumns(s: any) {
for (let c = 0; c < 4; c++) {
const a = new Array(4); // 'a' is a copy of the current column from 's'
const b = new Array(4); // 'b' is a•{02} in GF(2^8)
for (let i = 0; i < 4; i++) {
a[i] = s[i][c];
b[i] = s[i][c] & 0x80 ? (s[i][c] << 1) ^ 0x011b : s[i][c] << 1;
}
// a[n] ^ b[n] is a•{03} in GF(2^8)
s[0][c] = b[0] ^ a[1] ^ b[1] ^ a[2] ^ a[3]; // {02}•a0 + {03}•a1 + a2 + a3
s[1][c] = a[0] ^ b[1] ^ a[2] ^ b[2] ^ a[3]; // a0 • {02}•a1 + {03}•a2 + a3
s[2][c] = a[0] ^ a[1] ^ b[2] ^ a[3] ^ b[3]; // a0 + a1 + {02}•a2 + {03}•a3
s[3][c] = a[0] ^ b[0] ^ a[1] ^ a[2] ^ b[3]; // {03}•a0 + a1 + a2 + {02}•a3
}
return s;
}
private static addRoundKey(state: any, w: any, rnd: any, Nb: any) {
for (let r = 0; r < 4; r++) {
for (let c = 0; c < Nb; c++) {
state[r][c] ^= w[rnd * 4 + c][r];
}
}
return state;
}
private static subWord(w: any[]) {
for (let i = 0; i < 4; i++) {
w[i] = AES.sBox[w[i]];
}
return w;
}
private static rotWord(w: any[]) {
const tmp = w[0];
for (let i = 0; i < 3; i++) {
w[i] = w[i + 1];
}
w[3] = tmp;
return w;
}
private static base64Decode(text: string) {
return atob(text);
}
private static base64Encode(text: string) {
return btoa(text);
}
private static utf8Encode(text: string) {
return unescape(encodeURIComponent(text));
}
private static utf8Decode(text: string) {
try {
return decodeURIComponent(escape(text));
} catch (err) {
return text;
}
}
public static get Ctr() {
return {
/**
*
* @param ciphertext - encrypted text
* @param password - encryption password
* @param nBits - bits size
*```ts
* const Text = AES.Ctr.decrypt("uAIyZlqGe18XRt2+akj3wzCKbhtcINuC3RItd0U=", "elsa land", "128");
*
* console.log(Text); // hello world from elsa
* ```
*/
decrypt(ciphertext: string, password: string, nBits: BitSize) {
const blockSize = 16; // block size fixed at 16 bytes / 128 bits (Nb=4) for AES
if (
!(
parseInt(nBits) === 128 ||
parseInt(nBits) === 192 ||
parseInt(nBits) === 256
)
) {
throw new Error("Key size is not 128 / 192 / 256");
}
ciphertext = AES.base64Decode(ciphertext);
password = AES.utf8Encode(password);
// use AES to encrypt password (mirroring encrypt routine)
const nBytes = parseInt(nBits) / 8; // no bytes in key
const pwBytes = new Array(nBytes);
for (let i = 0; i < nBytes; i++) {
pwBytes[i] = i < password.length ? password.charCodeAt(i) : 0;
}
let key = AES.cipher(pwBytes, AES.keyExpansion(pwBytes));
key = key.concat(key.slice(0, nBytes - 16)); // expand key to 16/24/32 bytes long
// recover nonce from 1st 8 bytes of ciphertext
const counterBlock = new Array(8);
const ctrTxt = ciphertext.slice(0, 8);
for (let i = 0; i < 8; i++) {
counterBlock[i] = ctrTxt.charCodeAt(i);
}
// generate key schedule
const keySchedule = AES.keyExpansion(key);
// separate ciphertext into blocks (skipping past initial 8 bytes)
const nBlocks = Math.ceil((ciphertext.length - 8) / blockSize);
const ct = new Array(nBlocks);
for (let b = 0; b < nBlocks; b++)
ct[b] = ciphertext.slice(
8 + b * blockSize,
8 + b * blockSize + blockSize
);
((ciphertext as unknown) as any[]) = ct; // ciphertext is now array of block-length strings
// plaintext will get generated block-by-block into array of block-length strings
let plaintext = "";
for (let b = 0; b < nBlocks; b++) {
// set counter (block #) in last 8 bytes of counter block (leaving nonce in 1st 8 bytes)
for (let c = 0; c < 4; c++) {
counterBlock[15 - c] = (b >>> (c * 8)) & 0xff;
}
for (let c = 0; c < 4; c++) {
counterBlock[15 - c - 4] =
(((b + 1) / 0x100000000 - 1) >>> (c * 8)) & 0xff;
}
const cipherCntr = AES.cipher(counterBlock, keySchedule); // encrypt counter block
const plaintxtByte = new Array(ciphertext[b].length);
for (let i = 0; i < ciphertext[b].length; i++) {
// -- xor plaintext with ciphered counter byte-by-byte --
plaintxtByte[i] = cipherCntr[i] ^ ciphertext[b].charCodeAt(i);
plaintxtByte[i] = String.fromCharCode(plaintxtByte[i]);
}
plaintext += plaintxtByte.join("");
// if within web worker, announce progress every 1000 blocks (roughly every 50ms)
}
plaintext = AES.utf8Decode(plaintext); // decode from UTF8 back to Unicode multi-byte chars
return plaintext;
},
/**
*
* @param plaintext - text to encrypt
* @param password - encryption password
* @param nBits - bits size
*```ts
* const Text = AES.Ctr.decrypt("hello world from elsa", "elsa land", "128");
*
* console.log(Text); // uAIyZlqGe18XRt2+akj3wzCKbhtcINuC3RItd0U=
* ```
*/
encrypt(plaintext: string, password: string, nBits: BitSize) {
const blockSize = 16; // block size fixed at 16 bytes / 128 bits (Nb=4) for AES
if (
!(
parseInt(nBits) === 128 ||
parseInt(nBits) === 192 ||
parseInt(nBits) === 256
)
) {
throw new Error("Key size is not 128 / 192 / 256");
}
plaintext = AES.utf8Encode(plaintext);
password = AES.utf8Encode(password);
// use AES itself to encrypt password to get cipher key (using plain password as source for key
// expansion) - gives us well encrypted key (though hashed key might be preferred for prod'n use)
const nBytes = parseInt(nBits) / 8; // no bytes in key (16/24/32)
const pwBytes = new Array(nBytes);
for (let i = 0; i < nBytes; i++) {
// use 1st 16/24/32 chars of password for key
pwBytes[i] = i < password.length ? password.charCodeAt(i) : 0;
}
let key = AES.cipher(pwBytes, AES.keyExpansion(pwBytes)); // gives us 16-byte key
key = key.concat(key.slice(0, nBytes - 16)); // expand key to 16/24/32 bytes long
// initialise 1st 8 bytes of counter block with nonce (NIST SP800-38A §B.2): [0-1] = millisec,
// [2-3] = random, [4-7] = seconds, together giving full sub-millisec uniqueness up to Feb 2106
const counterBlock = new Array(blockSize);
const nonce = new Date().getTime(); // timestamp: milliseconds since 1-Jan-1970
const nonceMs = nonce % 1000;
const nonceSec = Math.floor(nonce / 1000);
const nonceRnd = Math.floor(Math.random() * 0xffff);
// for debugging: nonce = nonceMs = nonceSec = nonceRnd = 0;
for (let i = 0; i < 2; i++) {
counterBlock[i] = (nonceMs >>> (i * 8)) & 0xff;
}
for (let i = 0; i < 2; i++) {
counterBlock[i + 2] = (nonceRnd >>> (i * 8)) & 0xff;
}
for (let i = 0; i < 4; i++) {
counterBlock[i + 4] = (nonceSec >>> (i * 8)) & 0xff;
}
// and convert it to a string to go on the front of the ciphertext
let ctrTxt = "";
for (let i = 0; i < 8; i++) {
ctrTxt += String.fromCharCode(counterBlock[i]);
}
// generate key schedule - an expansion of the key into distinct Key Rounds for each round
const keySchedule = AES.keyExpansion(key);
const blockCount = Math.ceil(plaintext.length / blockSize);
let ciphertext = "";
for (let b = 0; b < blockCount; b++) {
// set counter (block #) in last 8 bytes of counter block (leaving nonce in 1st 8 bytes)
// done in two stages for 32-bit ops: using two words allows us to go past 2^32 blocks (68GB)
for (let c = 0; c < 4; c++) {
counterBlock[15 - c] = (b >>> (c * 8)) & 0xff;
}
for (let c = 0; c < 4; c++) {
counterBlock[15 - c - 4] = (b / 0x100000000) >>> (c * 8);
}
const cipherCntr = AES.cipher(counterBlock, keySchedule); // -- encrypt counter block --
// block size is reduced on final block
const blockLength =
b < blockCount - 1
? blockSize
: ((plaintext.length - 1) % blockSize) + 1;
const cipherChar = new Array(blockLength);
for (let i = 0; i < blockLength; i++) {
// -- xor plaintext with ciphered counter char-by-char --
cipherChar[i] =
cipherCntr[i] ^ plaintext.charCodeAt(b * blockSize + i);
cipherChar[i] = String.fromCharCode(cipherChar[i]);
}
ciphertext += cipherChar.join("");
// if within web worker, announce progress every 1000 blocks (roughly every 50ms)
}
ciphertext = AES.base64Encode(ctrTxt + ciphertext);
return ciphertext;
},
};
}
} | the_stack |
import logger from '../logger'
import * as TeamBuildingGen from '../actions/team-building-gen'
import * as Constants from '../constants/wallets'
import * as Container from '../util/container'
import * as Types from '../constants/types/wallets'
import * as WalletsGen from '../actions/wallets-gen'
import HiddenString from '../util/hidden-string'
import {editTeambuildingDraft} from './team-building'
import {teamBuilderReducerCreator} from '../team-building/reducer-helper'
import shallowEqual from 'shallowequal'
import {mapEqual} from '../util/map'
const initialState: Types.State = Constants.makeState()
const updateAssetMap = (
assetMap: Map<Types.AssetID, Types.AssetDescription>,
assets: Array<Types.AssetDescription>
) =>
assets.forEach(asset => {
const key = Types.assetDescriptionToAssetID(asset)
const oldAsset = assetMap.get(key)
if (!shallowEqual(asset, oldAsset)) {
assetMap.set(key, asset)
}
})
type Actions = WalletsGen.Actions | TeamBuildingGen.Actions
export default Container.makeReducer<Actions, Types.State>(initialState, {
[WalletsGen.resetStore]: draftState => {
return {...initialState, staticConfig: draftState.staticConfig} as Types.State
},
[WalletsGen.didSetAccountAsDefault]: (draftState, action) => {
draftState.accountMap = new Map(action.payload.accounts.map(account => [account.accountID, account]))
},
[WalletsGen.accountsReceived]: (draftState, action) => {
draftState.accountMap = new Map(action.payload.accounts.map(account => [account.accountID, account]))
},
[WalletsGen.changedAccountName]: (draftState, action) => {
const {account} = action.payload
// accept the updated account if we've loaded it already
// this is because we get the sort order from the full accounts load,
// and can't figure it out from these notifications alone.
if (account) {
// } && state.accountMap.get(account.accountID)) {
const {accountID} = account
const old = draftState.accountMap.get(accountID)
if (old) {
draftState.accountMap.set(accountID, {...old, ...account})
}
}
},
[WalletsGen.accountUpdateReceived]: (draftState, action) => {
const {account} = action.payload
// accept the updated account if we've loaded it already
// this is because we get the sort order from the full accounts load,
// and can't figure it out from these notifications alone.
if (account) {
const {accountID} = account
const old = draftState.accountMap.get(accountID)
if (old) {
draftState.accountMap.set(accountID, {...old, ...account})
}
}
},
[WalletsGen.assetsReceived]: (draftState, action) => {
draftState.assetsMap.set(action.payload.accountID, action.payload.assets)
},
[WalletsGen.buildPayment]: draftState => {
draftState.buildCounter++
},
[WalletsGen.builtPaymentReceived]: (draftState, action) => {
if (action.payload.forBuildCounter === draftState.buildCounter) {
draftState.builtPayment = {
...draftState.builtPayment,
...Constants.makeBuiltPayment(action.payload.build),
}
}
},
[WalletsGen.builtRequestReceived]: (draftState, action) => {
if (action.payload.forBuildCounter === draftState.buildCounter) {
draftState.builtRequest = {
...draftState.builtRequest,
...Constants.makeBuiltRequest(action.payload.build),
}
}
},
[WalletsGen.openSendRequestForm]: (draftState, action) => {
if (!draftState.acceptedDisclaimer) {
return
}
draftState.building = {
...Constants.makeBuilding(),
amount: action.payload.amount || '',
currency:
action.payload.currency || // explicitly set
(draftState.lastSentXLM && 'XLM') || // lastSentXLM override
(action.payload.from &&
Constants.getDisplayCurrencyInner(draftState as Types.State, action.payload.from).code) || // display currency of explicitly set 'from' account
Constants.getDefaultDisplayCurrencyInner(draftState as Types.State).code || // display currency of default account
'', // Empty string -> not loaded
from: action.payload.from || Types.noAccountID,
isRequest: !!action.payload.isRequest,
publicMemo: action.payload.publicMemo || new HiddenString(''),
recipientType: action.payload.recipientType || 'keybaseUser',
secretNote: action.payload.secretNote || new HiddenString(''),
to: action.payload.to || '',
}
draftState.builtPayment = Constants.makeBuiltPayment()
draftState.builtRequest = Constants.makeBuiltRequest()
draftState.sentPaymentError = ''
},
[WalletsGen.abandonPayment]: draftState => {
draftState.building = Constants.makeBuilding()
},
[WalletsGen.clearBuilding]: draftState => {
draftState.building = Constants.makeBuilding()
},
[WalletsGen.clearBuiltPayment]: draftState => {
draftState.builtPayment = Constants.makeBuiltPayment()
},
[WalletsGen.clearBuiltRequest]: draftState => {
draftState.builtRequest = Constants.makeBuiltRequest()
},
[WalletsGen.externalPartnersReceived]: (draftState, action) => {
draftState.externalPartners = action.payload.externalPartners
},
[WalletsGen.paymentDetailReceived]: (draftState, action) => {
const emptyMap: Map<Types.PaymentID, Types.Payment> = new Map()
const map = draftState.paymentsMap.get(action.payload.accountID) ?? emptyMap
const paymentDetail = action.payload.payment
map.set(paymentDetail.id, {
...(map.get(paymentDetail.id) ?? Constants.makePayment()),
...action.payload.payment,
})
draftState.paymentsMap.set(action.payload.accountID, map)
},
[WalletsGen.paymentsReceived]: (draftState, action) => {
const emptyMap: Map<Types.PaymentID, Types.Payment> = new Map()
const map = draftState.paymentsMap.get(action.payload.accountID) ?? emptyMap
const paymentResults = [...action.payload.payments, ...action.payload.pending]
paymentResults.forEach(paymentResult => {
map.set(paymentResult.id, {
...(map.get(paymentResult.id) ?? Constants.makePayment()),
...paymentResult,
})
})
draftState.loadPaymentsError = action.payload.error
draftState.paymentsMap.set(action.payload.accountID, map)
draftState.paymentCursorMap.set(action.payload.accountID, action.payload.paymentCursor)
draftState.paymentLoadingMoreMap.set(action.payload.accountID, false)
// allowClearOldestUnread dictates whether this action is allowed to delete the value of oldestUnread.
// GetPaymentsLocal can erroneously return an empty oldestUnread value when a non-latest page is requested
// and oldestUnread points into the latest page.
if (
action.payload.allowClearOldestUnread ||
(action.payload.oldestUnread || Types.noPaymentID) !== Types.noPaymentID
) {
draftState.paymentOldestUnreadMap.set(action.payload.accountID, action.payload.oldestUnread)
}
},
[WalletsGen.pendingPaymentsReceived]: (draftState, action) => {
const newPending = action.payload.pending.map(p => [p.id, Constants.makePayment(p)] as const)
const emptyMap: Map<Types.PaymentID, Types.Payment> = new Map()
const oldFiltered = [
...(draftState.paymentsMap.get(action.payload.accountID) ?? emptyMap).entries(),
].filter(([_k, v]) => v.section !== 'pending')
const val = new Map([...oldFiltered, ...newPending])
draftState.paymentsMap.set(action.payload.accountID, val)
},
[WalletsGen.recentPaymentsReceived]: (draftState, action) => {
const newPayments = action.payload.payments.map(p => [p.id, Constants.makePayment(p)] as const)
const emptyMap: Map<Types.PaymentID, Types.Payment> = new Map()
const old = (draftState.paymentsMap.get(action.payload.accountID) ?? emptyMap).entries()
draftState.paymentsMap.set(action.payload.accountID, new Map([...old, ...newPayments]))
draftState.paymentCursorMap.set(
action.payload.accountID,
draftState.paymentCursorMap.get(action.payload.accountID) || action.payload.paymentCursor
)
draftState.paymentOldestUnreadMap.set(action.payload.accountID, action.payload.oldestUnread)
},
[WalletsGen.displayCurrenciesReceived]: (draftState, action) => {
draftState.currencies = action.payload.currencies
},
[WalletsGen.displayCurrencyReceived]: (draftState, action) => {
const account = Constants.getAccountInner(
draftState as Types.State,
action.payload.accountID || Types.noAccountID
)
if (account.accountID === Types.noAccountID) {
return
}
draftState.accountMap.set(account.accountID, {...account, displayCurrency: action.payload.currency})
},
[WalletsGen.reviewPayment]: draftState => {
draftState.builtPayment.reviewBanners = []
draftState.reviewCounter++
draftState.reviewLastSeqno = undefined
},
[WalletsGen.reviewedPaymentReceived]: (draftState, action) => {
// paymentReviewed notifications can arrive out of order, so check their freshness.
const {bid, reviewID, seqno, banners, nextButton} = action.payload
const useable =
draftState.building.bid === bid &&
draftState.reviewCounter === reviewID &&
(draftState.reviewLastSeqno || 0) <= seqno
if (!useable) {
logger.info(`ignored stale reviewPaymentReceived`)
return
}
draftState.builtPayment.readyToSend = nextButton
draftState.builtPayment.reviewBanners = banners ?? null
draftState.reviewLastSeqno = seqno
},
[WalletsGen.secretKeyReceived]: (draftState, action) => {
draftState.exportedSecretKey = action.payload.secretKey
draftState.exportedSecretKeyAccountID = draftState.selectedAccount
},
[WalletsGen.secretKeySeen]: draftState => {
draftState.exportedSecretKey = new HiddenString('')
draftState.exportedSecretKeyAccountID = Types.noAccountID
},
[WalletsGen.selectAccount]: (draftState, action) => {
if (!action.payload.accountID) {
logger.error('Selecting empty account ID')
}
draftState.exportedSecretKey = new HiddenString('')
const old = draftState.selectedAccount
draftState.selectedAccount = action.payload.accountID
// we clear the old selected payments and cursors
if (!old) {
return
}
draftState.paymentCursorMap.delete(old)
draftState.paymentsMap.delete(old)
},
[WalletsGen.setBuildingAmount]: (draftState, action) => {
draftState.building.amount = action.payload.amount
draftState.builtPayment.amountErrMsg = ''
draftState.builtPayment.worthDescription = ''
draftState.builtPayment.worthInfo = ''
draftState.builtRequest.amountErrMsg = ''
draftState.builtRequest.worthDescription = ''
draftState.builtRequest.worthInfo = ''
},
[WalletsGen.setBuildingCurrency]: (draftState, action) => {
draftState.building.currency = action.payload.currency
draftState.builtPayment = Constants.makeBuiltPayment()
},
[WalletsGen.setBuildingFrom]: (draftState, action) => {
draftState.building.from = action.payload.from
draftState.builtPayment = Constants.makeBuiltPayment()
},
[WalletsGen.setBuildingIsRequest]: (draftState, action) => {
draftState.building.isRequest = action.payload.isRequest
draftState.builtPayment = Constants.makeBuiltPayment()
draftState.builtRequest = Constants.makeBuiltRequest()
},
[WalletsGen.setBuildingPublicMemo]: (draftState, action) => {
draftState.building.publicMemo = action.payload.publicMemo
draftState.builtPayment.publicMemoErrMsg = new HiddenString('')
},
[WalletsGen.setBuildingRecipientType]: (draftState, action) => {
draftState.building.recipientType = action.payload.recipientType
draftState.builtPayment = Constants.makeBuiltPayment()
},
[WalletsGen.setBuildingSecretNote]: (draftState, action) => {
draftState.building.secretNote = action.payload.secretNote
draftState.builtPayment.secretNoteErrMsg = new HiddenString('')
draftState.builtRequest.secretNoteErrMsg = new HiddenString('')
},
[WalletsGen.setBuildingTo]: (draftState, action) => {
draftState.building.to = action.payload.to
draftState.builtPayment.toErrMsg = ''
draftState.builtRequest.toErrMsg = ''
},
[WalletsGen.clearBuildingAdvanced]: draftState => {
draftState.buildingAdvanced = Constants.emptyBuildingAdvanced
draftState.builtPaymentAdvanced = Constants.emptyBuiltPaymentAdvanced
},
[WalletsGen.setBuildingAdvancedRecipient]: (draftState, action) => {
draftState.buildingAdvanced.recipient = action.payload.recipient
},
[WalletsGen.setBuildingAdvancedRecipientAmount]: (draftState, action) => {
draftState.buildingAdvanced.recipientAmount = action.payload.recipientAmount
draftState.builtPaymentAdvanced = Constants.emptyBuiltPaymentAdvanced
},
[WalletsGen.setBuildingAdvancedRecipientAsset]: (draftState, action) => {
draftState.buildingAdvanced.recipientAsset = action.payload.recipientAsset
draftState.builtPaymentAdvanced = Constants.emptyBuiltPaymentAdvanced
},
[WalletsGen.setBuildingAdvancedRecipientType]: (draftState, action) => {
draftState.buildingAdvanced.recipientType = action.payload.recipientType
},
[WalletsGen.setBuildingAdvancedPublicMemo]: (draftState, action) => {
draftState.buildingAdvanced.publicMemo = action.payload.publicMemo
// TODO PICNIC-142 clear error when we have that
},
[WalletsGen.setBuildingAdvancedSenderAccountID]: (draftState, action) => {
draftState.buildingAdvanced.senderAccountID = action.payload.senderAccountID
},
[WalletsGen.setBuildingAdvancedSenderAsset]: (draftState, action) => {
draftState.buildingAdvanced.senderAsset = action.payload.senderAsset
draftState.builtPaymentAdvanced = Constants.emptyBuiltPaymentAdvanced
},
[WalletsGen.setBuildingAdvancedSecretNote]: (draftState, action) => {
draftState.buildingAdvanced.secretNote = action.payload.secretNote
// TODO PICNIC-142 clear error when we have that
},
[WalletsGen.sendAssetChoicesReceived]: (draftState, action) => {
const {sendAssetChoices} = action.payload
draftState.building.sendAssetChoices = sendAssetChoices
},
[WalletsGen.buildingPaymentIDReceived]: (draftState, action) => {
const {bid} = action.payload
draftState.building.bid = bid
},
[WalletsGen.setLastSentXLM]: (draftState, action) => {
draftState.lastSentXLM = action.payload.lastSentXLM
},
[WalletsGen.setReadyToReview]: (draftState, action) => {
draftState.builtPayment.readyToReview = action.payload.readyToReview
},
[WalletsGen.validateAccountName]: (draftState, action) => {
draftState.accountName = action.payload.name
draftState.accountNameValidationState = 'waiting'
},
[WalletsGen.validatedAccountName]: (draftState, action) => {
if (action.payload.name !== draftState.accountName) {
// this wasn't from the most recent call
return
}
draftState.accountName = ''
draftState.accountNameError = action.payload.error ? action.payload.error : ''
draftState.accountNameValidationState = action.payload.error ? 'error' : 'valid'
},
[WalletsGen.validateSecretKey]: (draftState, action) => {
draftState.secretKey = action.payload.secretKey
draftState.secretKeyValidationState = 'waiting'
},
[WalletsGen.validatedSecretKey]: (draftState, action) => {
if (action.payload.secretKey.stringValue() !== draftState.secretKey.stringValue()) {
// this wasn't from the most recent call
return
}
draftState.secretKey = new HiddenString('')
draftState.secretKeyError = action.payload.error ? action.payload.error : ''
draftState.secretKeyValidationState = action.payload.error ? 'error' : 'valid'
},
[WalletsGen.changedTrustline]: (draftState, action) => {
draftState.changeTrustlineError = action.payload.error || ''
},
[WalletsGen.clearErrors]: draftState => {
draftState.accountName = ''
draftState.accountNameError = ''
draftState.accountNameValidationState = 'none'
draftState.builtPayment.readyToSend = 'spinning'
draftState.changeTrustlineError = ''
draftState.createNewAccountError = ''
draftState.linkExistingAccountError = ''
draftState.secretKey = new HiddenString('')
draftState.secretKeyError = ''
draftState.secretKeyValidationState = 'none'
draftState.sentPaymentError = ''
},
[WalletsGen.createdNewAccount]: (draftState, action) => {
if (action.payload.error) {
draftState.createNewAccountError = action.payload.error ?? ''
} else {
draftState.accountName = ''
draftState.accountNameError = ''
draftState.accountNameValidationState = 'none'
draftState.changeTrustlineError = ''
draftState.createNewAccountError = ''
draftState.linkExistingAccountError = ''
draftState.secretKey = new HiddenString('')
draftState.secretKeyError = ''
draftState.secretKeyValidationState = 'none'
draftState.selectedAccount = action.payload.accountID
}
},
[WalletsGen.linkedExistingAccount]: (draftState, action) => {
if (action.payload.error) {
draftState.linkExistingAccountError = action.payload.error ?? ''
} else {
draftState.accountName = ''
draftState.accountNameError = ''
draftState.accountNameValidationState = 'none'
draftState.createNewAccountError = ''
draftState.linkExistingAccountError = ''
draftState.secretKey = new HiddenString('')
draftState.secretKeyError = ''
draftState.secretKeyValidationState = 'none'
draftState.selectedAccount = action.payload.accountID
}
},
[WalletsGen.sentPaymentError]: (draftState, action) => {
draftState.sentPaymentError = action.payload.error
},
[WalletsGen.loadMorePayments]: (draftState, action) => {
if (draftState.paymentCursorMap.get(action.payload.accountID)) {
draftState.paymentLoadingMoreMap.set(action.payload.accountID, true)
}
},
[WalletsGen.badgesUpdated]: (draftState, action) => {
action.payload.accounts.forEach(({accountID, numUnread}) =>
draftState.unreadPaymentsMap.set(accountID, numUnread)
)
},
[WalletsGen.walletDisclaimerReceived]: (draftState, action) => {
draftState.acceptedDisclaimer = action.payload.accepted
},
[WalletsGen.acceptDisclaimer]: draftState => {
draftState.acceptingDisclaimerDelay = true
},
[WalletsGen.resetAcceptingDisclaimer]: draftState => {
draftState.acceptingDisclaimerDelay = false
},
[WalletsGen.loadedMobileOnlyMode]: (draftState, action) => {
draftState.mobileOnlyMap.set(action.payload.accountID, action.payload.enabled)
},
[WalletsGen.validateSEP7Link]: draftState => {
// Clear out old state just in [
draftState.sep7ConfirmError = ''
draftState.sep7ConfirmInfo = undefined
draftState.sep7ConfirmPath = Constants.emptyBuiltPaymentAdvanced
draftState.sep7ConfirmURI = ''
draftState.sep7SendError = ''
},
[WalletsGen.setSEP7SendError]: (draftState, action) => {
draftState.sep7SendError = action.payload.error
},
[WalletsGen.validateSEP7LinkError]: (draftState, action) => {
draftState.sep7ConfirmError = action.payload.error
},
[WalletsGen.setSEP7Tx]: (draftState, action) => {
draftState.sep7ConfirmInfo = action.payload.tx
draftState.sep7ConfirmFromQR = action.payload.fromQR
draftState.sep7ConfirmURI = action.payload.confirmURI
},
[WalletsGen.setTrustlineExpanded]: (draftState, action) => {
if (action.payload.expanded) {
draftState.trustline.expandedAssets.add(action.payload.assetID)
} else {
draftState.trustline.expandedAssets.delete(action.payload.assetID)
}
},
[WalletsGen.setTrustlineAcceptedAssets]: (draftState, action) => {
const {accountID, limits} = action.payload
const accountAcceptedAssets = draftState.trustline.acceptedAssets.get(accountID)
if (!accountAcceptedAssets || !mapEqual(limits, accountAcceptedAssets)) {
draftState.trustline.acceptedAssets.set(accountID, limits)
}
updateAssetMap(draftState.trustline.assetMap, action.payload.assets)
},
[WalletsGen.setTrustlineAcceptedAssetsByUsername]: (draftState, action) => {
const {username, limits, assets} = action.payload
const accountAcceptedAssets = draftState.trustline.acceptedAssetsByUsername.get(username)
if (!accountAcceptedAssets || !mapEqual(limits, accountAcceptedAssets)) {
draftState.trustline.acceptedAssetsByUsername.set(username, limits)
}
updateAssetMap(draftState.trustline.assetMap, assets)
},
[WalletsGen.setTrustlinePopularAssets]: (draftState, action) => {
draftState.trustline.popularAssets = action.payload.assets.map(asset =>
Types.assetDescriptionToAssetID(asset)
)
updateAssetMap(draftState.trustline.assetMap, action.payload.assets)
draftState.trustline.totalAssetsCount = action.payload.totalCount
draftState.trustline.loaded = true
},
[WalletsGen.setTrustlineSearchText]: (draftState, action) => {
if (!action.payload.text) {
draftState.trustline.searchingAssets = []
}
},
[WalletsGen.setTrustlineSearchResults]: (draftState, action) => {
draftState.trustline.searchingAssets = action.payload.assets.map(asset =>
Types.assetDescriptionToAssetID(asset)
)
updateAssetMap(draftState.trustline.assetMap, action.payload.assets)
},
[WalletsGen.clearTrustlineSearchResults]: draftState => {
draftState.trustline.searchingAssets = undefined
},
[WalletsGen.setBuiltPaymentAdvanced]: (draftState, action) => {
if (action.payload.forSEP7) {
draftState.sep7ConfirmPath = action.payload.builtPaymentAdvanced
} else {
draftState.builtPaymentAdvanced = action.payload.builtPaymentAdvanced
}
},
[WalletsGen.staticConfigLoaded]: (draftState, action) => {
draftState.staticConfig = action.payload.staticConfig
},
[WalletsGen.assetDeposit]: draftState => {
draftState.sep6Error = false
draftState.sep6Message = ''
},
[WalletsGen.assetWithdraw]: draftState => {
draftState.sep6Error = false
draftState.sep6Message = ''
},
[WalletsGen.setSEP6Message]: (draftState, action) => {
draftState.sep6Error = action.payload.error
draftState.sep6Message = action.payload.message
},
...teamBuilderReducerCreator<Types.State>(
(draftState: Container.Draft<Types.State>, action: TeamBuildingGen.Actions) => {
const val = editTeambuildingDraft('wallets', draftState.teamBuilding, action)
if (val !== undefined) {
draftState.teamBuilding = val
}
}
),
}) | the_stack |
import { shallow, mount } from 'enzyme';
import toJson from 'enzyme-to-json';
import * as React from 'react';
import { Spot } from 'domain/Spot';
import { Employee } from 'domain/Employee';
import { Shift } from 'domain/Shift';
import { RosterState } from 'domain/RosterState';
import moment from 'moment-timezone';
import 'moment/locale/en-ca';
import color from 'color';
import { useTranslation, Trans } from 'react-i18next';
import Actions from 'ui/components/Actions';
import Schedule from 'ui/components/calendar/Schedule';
import { getRouterProps } from 'util/BookmarkableTestUtils';
import { getShiftColor } from './ShiftEvent';
import { ShiftRosterPage, Props, ShiftRosterUrlProps } from './CurrentShiftRosterPage';
import ExportScheduleModal from './ExportScheduleModal';
describe('Current Shift Roster Page', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('should render correctly when loaded', () => {
const shiftRosterPage = shallow(<ShiftRosterPage
{...baseProps}
/>);
expect(toJson(shiftRosterPage)).toMatchSnapshot();
});
it('should render correctly when loading', () => {
const shiftRosterPage = shallow(<ShiftRosterPage
{...baseProps}
isLoading
allSpotList={[]}
shownSpotList={[]}
spotIdToShiftListMap={new Map()}
/>);
expect(toJson(shiftRosterPage)).toMatchSnapshot();
});
it('should render correctly when solving', () => {
const shiftRosterPage = shallow(<ShiftRosterPage
{...baseProps}
isSolving
/>);
expect(toJson(shiftRosterPage)).toMatchSnapshot();
});
it('should render correctly when creating a new shift via button', () => {
const shiftRosterPage = shallow(<ShiftRosterPage
{...baseProps}
/>);
shiftRosterPage.find(Actions).prop('actions')
.filter(a => a.name === 'Trans(i18nKey=createShift)')
.forEach(a => a.action());
expect(toJson(shiftRosterPage)).toMatchSnapshot();
});
it('should call addShift on addShift', () => {
const shiftRosterPage = new ShiftRosterPage(baseProps);
const newShift: Shift = {
...shift,
id: undefined,
version: undefined,
startDateTime: startDate,
endDateTime: endDate,
};
shiftRosterPage.addShift(newShift);
expect(baseProps.addShift).toBeCalled();
expect(baseProps.addShift).toBeCalledWith(newShift);
});
it('should call updateShift on updateShift', () => {
const shiftRosterPage = new ShiftRosterPage(baseProps);
const updatedShift: Shift = {
...shift,
startDateTime: startDate,
endDateTime: endDate,
};
shiftRosterPage.updateShift(updatedShift);
expect(baseProps.updateShift).toBeCalled();
expect(baseProps.updateShift).toBeCalledWith(updatedShift);
});
it('should call removeShift on deleteShift', () => {
const shiftRosterPage = new ShiftRosterPage(baseProps);
shiftRosterPage.deleteShift(shift);
expect(baseProps.removeShift).toBeCalled();
expect(baseProps.removeShift).toBeCalledWith(shift);
});
it('should go to the Spots page if the user click on the link', () => {
const shiftRosterPage = shallow(<ShiftRosterPage
{...baseProps}
allSpotList={[]}
shownSpotList={[]}
spotIdToShiftListMap={new Map()}
/>);
mount((shiftRosterPage.find(Trans).prop('components') as any)[2]).simulate('click');
expect(baseProps.history.push).toBeCalled();
expect(baseProps.history.push).toBeCalledWith('/0/wards');
});
it('should change the week when the user change the week', () => {
const shiftRosterPage = shallow(<ShiftRosterPage
{...baseProps}
/>);
const newDateStart = moment(startDate).add(7, 'days').toDate();
const newDateEnd = moment(endDate).add(7, 'days').toDate();
shiftRosterPage.find('[aria-label="Select Week to View"]').simulate('change', newDateStart, newDateEnd);
expect(baseProps.getShiftRosterFor).toBeCalled();
expect(baseProps.getShiftRosterFor).toBeCalledWith({
fromDate: newDateStart,
toDate: newDateEnd,
spotList: baseProps.shownSpotList,
});
});
it('should change the spot when the user change the spot', () => {
const shiftRosterPage = shallow(<ShiftRosterPage
{...baseProps}
/>);
shiftRosterPage.find('[aria-label="Select Spot"]').simulate('change', newSpot);
expect(baseProps.getShiftRosterFor).toBeCalled();
expect(baseProps.getShiftRosterFor).toBeCalledWith({
fromDate: startDate,
toDate: endDate,
spotList: [newSpot],
});
});
it('should call publishRoster when the publish button is clicked', () => {
const shiftRosterPage = shallow(<ShiftRosterPage
{...baseProps}
/>);
shiftRosterPage.find(Actions).prop('actions')
.filter(a => a.name === 'Trans(i18nKey=commitChanges)')
.forEach(a => a.action());
expect(baseProps.commitChanges).toBeCalled();
});
it('should call solveRoster when the schedule button is clicked', () => {
const shiftRosterPage = shallow(<ShiftRosterPage
{...baseProps}
/>);
shiftRosterPage.find(Actions).prop('actions')
.filter(a => a.name === 'Trans(i18nKey=reschedule)')
.forEach(a => a.action());
expect(baseProps.replanRoster).toBeCalled();
});
it('should open the export schedule modal when export is clicked', () => {
const shiftRosterPage = shallow(<ShiftRosterPage
{...baseProps}
/>);
shiftRosterPage.find(Actions).prop('actions')
.filter(a => a.name === 'Trans(i18nKey=exportToExcel)')
.forEach(a => a.action());
expect(shiftRosterPage.find(ExportScheduleModal).prop('isOpen')).toEqual(true);
});
it('should close the export schedule modal when export is closed', () => {
const shiftRosterPage = shallow(<ShiftRosterPage
{...baseProps}
/>);
shiftRosterPage.find(Actions).prop('actions')
.filter(a => a.name === 'Trans(i18nKey=exportToExcel)')
.forEach(a => a.action());
expect(shiftRosterPage.find(ExportScheduleModal).simulate('close'));
expect(shiftRosterPage.find(ExportScheduleModal).prop('isOpen')).toEqual(false);
});
it('should call terminateSolvingRosterEarly when the Terminate Early button is clicked', () => {
const shiftRosterPage = shallow(<ShiftRosterPage
{...baseProps}
isSolving
/>);
shiftRosterPage.find(Actions).prop('actions')
.filter(a => a.name === 'Trans(i18nKey=terminateEarly)')
.forEach(a => a.action());
expect(baseProps.terminateSolvingRosterEarly).toBeCalled();
});
it('should call refreshShiftRoster and show an info message when the refresh button is clicked', () => {
const shiftRosterPage = shallow(<ShiftRosterPage
{...baseProps}
/>);
shiftRosterPage.find(Actions).prop('actions')
.filter(a => a.name === 'Trans(i18nKey=refresh)')
.forEach(a => a.action());
expect(baseProps.refreshShiftRoster).toBeCalled();
expect(baseProps.showInfoMessage).toBeCalled();
expect(baseProps.showInfoMessage).toBeCalledWith('shiftRosterRefresh');
});
it('call deleteShift when the EditShiftModal delete a shift', () => {
const shiftRosterPage = shallow(<ShiftRosterPage
{...baseProps}
/>);
shiftRosterPage.setState({
selectedShift: shift,
isCreatingOrEditingShift: true,
});
shiftRosterPage.find('[aria-label="Edit Shift"]').simulate('delete', shift);
expect(baseProps.removeShift).toBeCalled();
expect(baseProps.removeShift).toBeCalledWith(shift);
expect(shiftRosterPage.state('isCreatingOrEditingShift')).toEqual(false);
});
it('call addShift when the EditShiftModal add a new shift', () => {
const shiftRosterPage = shallow(<ShiftRosterPage
{...baseProps}
/>);
shiftRosterPage.setState({
isCreatingOrEditingShift: true,
});
const newShift: Shift = {
...shift,
id: undefined,
version: undefined,
startDateTime: startDate,
endDateTime: endDate,
};
shiftRosterPage.find('[aria-label="Edit Shift"]').simulate('save', newShift);
expect(baseProps.addShift).toBeCalled();
expect(baseProps.addShift).toBeCalledWith(newShift);
expect(shiftRosterPage.state('isCreatingOrEditingShift')).toEqual(false);
});
it('call updateShift when the EditShiftModal updates a shift', () => {
const shiftRosterPage = shallow(<ShiftRosterPage
{...baseProps}
/>);
shiftRosterPage.setState({
selectedShift: shift,
isCreatingOrEditingShift: true,
});
const newShift: Shift = {
...shift,
startDateTime: startDate,
endDateTime: endDate,
};
shiftRosterPage.find('[aria-label="Edit Shift"]').simulate('save', newShift);
expect(baseProps.updateShift).toBeCalled();
expect(baseProps.updateShift).toBeCalledWith(newShift);
expect(shiftRosterPage.state('isCreatingOrEditingShift')).toEqual(false);
});
it('should set isEditingOrCreatingShift to false when closed', () => {
const shiftRosterPage = shallow(<ShiftRosterPage
{...baseProps}
/>);
shiftRosterPage.setState({
isCreatingOrEditingShift: true,
});
shiftRosterPage.find('[aria-label="Edit Shift"]').simulate('close');
expect(shiftRosterPage.state('isCreatingOrEditingShift')).toEqual(false);
});
it('should call addShift when a timeslot is selected', () => {
const shiftRosterPage = shallow(<ShiftRosterPage
{...baseProps}
/>);
const newDateStart = moment(startDate).add(7, 'days').toDate();
const newDateEnd = moment(endDate).add(7, 'days').toDate();
shiftRosterPage.find(Schedule).simulate('addEvent', newDateStart,
newDateEnd);
expect(baseProps.addShift).toBeCalled();
expect(baseProps.addShift).toBeCalledWith({
tenantId: spot.tenantId,
startDateTime: newDateStart,
endDateTime: newDateEnd,
spot,
requiredSkillSet: [],
originalEmployee: null,
employee: null,
rotationEmployee: null,
pinnedByUser: false,
});
});
it('should call updateShift when an event is updated', () => {
const shiftRosterPage = shallow(<ShiftRosterPage
{...baseProps}
/>);
const newDateStart = moment(startDate).add(7, 'days').toDate();
const newDateEnd = moment(endDate).add(7, 'days').toDate();
shiftRosterPage.find(Schedule).simulate('updateEvent', shift, newDateStart,
newDateEnd);
expect(baseProps.updateShift).toBeCalled();
expect(baseProps.updateShift).toBeCalledWith({
...shift,
startDateTime: newDateStart,
endDateTime: newDateEnd,
});
});
it('should have a solid border for published shifts published', () => {
const shiftRosterPage = new ShiftRosterPage(baseProps);
const publishedShift: Shift = {
...shift,
startDateTime: moment(startDate).subtract('1', 'day').toDate(),
};
const style = shiftRosterPage.getShiftStyle(publishedShift);
expect(style).toEqual({
style: {
border: '1px solid',
backgroundColor: color(getShiftColor(publishedShift)).hex(),
},
});
});
it('should keep the color and have a dashed border and translucent if the shift is draft', () => {
const shiftRosterPage = new ShiftRosterPage(baseProps);
const style = shiftRosterPage.getShiftStyle(shift);
expect(style).toEqual({
style: {
border: '1px dashed',
backgroundColor: getShiftColor(shift),
opacity: 0.3,
},
});
});
it('day should be white if it is draft', () => {
const shiftRosterPage = new ShiftRosterPage(baseProps);
const style = shiftRosterPage.getDayStyle(endDate);
expect(style).toEqual({
className: 'draft-day',
style: {
backgroundColor: 'var(--pf-global--BackgroundColor--100)',
},
});
});
it('day should be gray if it is published', () => {
const shiftRosterPage = new ShiftRosterPage(baseProps);
const style = shiftRosterPage.getDayStyle(moment(startDate).subtract(1, 'day').toDate());
expect(style).toEqual({
className: 'published-day',
style: {
backgroundColor: 'var(--pf-global--BackgroundColor--300)',
},
});
});
});
const spot: Spot = {
tenantId: 0,
id: 2,
version: 0,
name: 'Spot',
requiredSkillSet: [
{
tenantId: 0,
id: 3,
version: 0,
name: 'Skill',
},
],
};
const newSpot: Spot = {
...spot,
id: 111,
name: 'New Spot',
};
const employee: Employee = {
tenantId: 0,
id: 4,
version: 0,
name: 'Employee 1',
contract: {
tenantId: 0,
id: 5,
version: 0,
name: 'Basic Contract',
maximumMinutesPerDay: 10,
maximumMinutesPerWeek: 70,
maximumMinutesPerMonth: 500,
maximumMinutesPerYear: 6000,
},
skillProficiencySet: [{
tenantId: 0,
id: 6,
version: 0,
name: 'Not Required Skill',
}],
shortId: 'e1',
color: '#FFFFFF',
};
const shift: Shift = {
tenantId: 0,
id: 1,
version: 0,
startDateTime: moment('2018-07-01T09:00').toDate(),
endDateTime: moment('2018-07-01T17:00').toDate(),
spot,
requiredSkillSet: [],
originalEmployee: null,
employee,
rotationEmployee: {
...employee,
id: 7,
name: 'Rotation Employee',
},
pinnedByUser: false,
indictmentScore: { hardScore: 0, mediumScore: 0, softScore: 0 },
requiredSkillViolationList: [],
unavailableEmployeeViolationList: [],
shiftEmployeeConflictList: [],
desiredTimeslotForEmployeeRewardList: [],
undesiredTimeslotForEmployeePenaltyList: [],
rotationViolationPenaltyList: [],
unassignedShiftPenaltyList: [],
contractMinutesViolationPenaltyList: [],
};
const startDate = moment('2018-07-01T09:00').startOf('week').toDate();
const endDate = moment('2018-07-01T09:00').endOf('week').toDate();
const rosterState: RosterState = {
tenant: {
id: 0,
version: 0,
name: 'Tenant',
},
publishNotice: 14,
publishLength: 7,
firstDraftDate: new Date('2018-07-01'),
draftLength: 7,
unplannedRotationOffset: 0,
rotationLength: 7,
lastHistoricDate: new Date('2018-07-01'),
timeZone: 'EST',
};
const baseProps: Props = {
...useTranslation('ShiftRosterPage'),
tenantId: 0,
score: { hardScore: 0, mediumScore: 0, softScore: 0 },
indictmentSummary: {
constraintToCountMap: {},
constraintToScoreImpactMap: {},
},
tReady: true,
isSolving: false,
isLoading: false,
allSpotList: [spot, newSpot],
shownSpotList: [spot],
spotIdToShiftListMap: new Map<number, Shift[]>([
[2, [shift]],
]),
totalNumOfSpots: 1,
rosterState,
addShift: jest.fn(),
removeShift: jest.fn(),
updateShift: jest.fn(),
getShiftRosterFor: jest.fn(),
refreshShiftRoster: jest.fn(),
replanRoster: jest.fn(),
commitChanges: jest.fn(),
terminateSolvingRosterEarly: jest.fn(),
showInfoMessage: jest.fn(),
...getRouterProps<ShiftRosterUrlProps>('/shift', { spot: 'Spot', week: '2018-07-01' }),
}; | the_stack |
import Container from '../../login/forms/container'
import * as Kb from '../../common-adapters'
import * as React from 'react'
import * as Styles from '../../styles'
import {RPCError} from '../../util/errors'
import {StatusCode} from '../../constants/types/rpc-gen'
import {Box2, Button, Icon, Text, Markdown} from '../../common-adapters'
import {styleSheetCreate, globalStyles, globalMargins, isMobile} from '../../styles'
type Props = {
error?: RPCError
onAccountReset: () => void
onBack: () => void
onKBHome: () => void
onPasswordReset: () => void
}
const List = p => (
<Box2 direction="vertical" style={styles.list}>
{p.children}
</Box2>
)
const Wrapper = (p: {onBack: () => void; children: React.ReactNode}) => (
<Container onBack={p.onBack}>
<Icon type="icon-illustration-zen-240-180" style={styles.icon} />
<Text type="Header" style={styles.header}>
Oops, something went wrong.
</Text>
<Box2 direction="vertical" gap="small" gapStart={true} gapEnd={true} style={styles.container}>
{p.children}
</Box2>
{Styles.isMobile && <Button label="Close" onClick={p.onBack} />}
</Container>
)
const rewriteErrorDesc = {
'Provisioner is a different user than we wanted.':
'Is the other device using the username you expect? It seems to be different.',
}
// Normally this would be a component but I want the children to be flat so i can use a Box2 as the parent and have nice gaps
const Render = ({error, onBack, onAccountReset, onPasswordReset, onKBHome}: Props) => {
if (!error) {
return (
<Wrapper onBack={onBack}>
<Text center={true} type="Body">
Unknown error: Please report this to us.
</Text>
</Wrapper>
)
}
const fields = (Array.isArray(error.fields) ? error.fields : []).reduce((acc, f) => {
const k = f && typeof f.key === 'string' ? f.key : ''
acc[k] = f.value || ''
return acc
}, {})
switch (error.code) {
case StatusCode.scdeviceprovisionoffline:
case StatusCode.scapinetworkerror:
return (
<Wrapper onBack={onBack}>
<Text center={true} type="Body">
The device authorization failed because this device went offline.
</Text>
<Text center={true} type="Body">
Please check your network connection and try again.
</Text>
</Wrapper>
)
case StatusCode.scdevicenoprovision:
return (
<Wrapper onBack={onBack}>
<Text center={true} type="Body">
You can't authorize by password, since you have established device or paper keys.
</Text>
<Text center={true} type="Body">
You can go back and pick a device or paper key, or{' '}
<Text type="BodyPrimaryLink" onClick={onAccountReset}>
reset your account entirely
</Text>
.
</Text>
</Wrapper>
)
case StatusCode.scdeviceprevprovisioned:
return (
<Wrapper onBack={onBack}>
<Text center={true} type="Body">
You have already authorized this device.{' '}
</Text>
<Text center={true} type="Body">
Please use 'keybase login [username]' to log in.{' '}
</Text>
</Wrapper>
)
case StatusCode.sckeynomatchinggpg:
if (fields.has_active_device) {
return (
<Wrapper onBack={onBack}>
<Text center={true} type="Body">
You can't authorize using solely a password, since you have active device keys.
</Text>
<Text center={true} type="BodySemibold">
You have options:
</Text>
<List>
<Text center={true} type="Body">
{' '}
- Go back and select a device or paper key
</Text>
<Text center={true} type="Body">
{' '}
- Install Keybase on a machine that has your PGP private key in it
</Text>
<Text center={true} type="Body">
{' '}
- Login to the website and host an encrypted copy of your PGP private key
</Text>
<Text center={true} type="Body">
{' '}
- or,{' '}
<Text type="BodyPrimaryLink" onClick={onAccountReset}>
reset your account entirely
</Text>
.
</Text>
</List>
</Wrapper>
)
} else {
return (
<Wrapper onBack={onBack}>
<Text center={true} type="Body">
You can't authorize using a password, since you've established a PGP key.
</Text>
<Text center={true} type="BodySemibold" style={{textAlign: 'left'}}>
You have options:
</Text>
<List>
<Text center={true} type="Body">
{' '}
- Use <Text type="TerminalInline">keybase login</Text> on the command line to log in
</Text>
{!isMobile && (
<Text center={true} type="Body">
{' '}
- Install GPG on this machine and import your PGP private key into it
</Text>
)}
<Text center={true} type="Body">
{' '}
- Install Keybase on a different machine that has your PGP key
</Text>
<Text center={true} type="Body">
{' '}
- Login to the website and host an encrypted copy of your PGP private key
</Text>
<Text center={true} type="Body">
{' '}
- Or,{' '}
<Text type="BodyPrimaryLink" onClick={onAccountReset}>
reset your account entirely
</Text>
.
</Text>
</List>
</Wrapper>
)
}
case StatusCode.sckeynotfound:
return error.desc ? (
<Wrapper onBack={onBack}>
<Markdown>{error.desc}</Markdown>
</Wrapper>
) : (
<Wrapper onBack={onBack}>
<Text center={true} type="Body">
Your PGP keychain has multiple keys installed, and we're not sure which one to use to authorize
your account.
</Text>
<Text center={true} type="Body">
Please run <Text type="TerminalInline">keybase login</Text> on the command line to continue.
</Text>
</Wrapper>
)
case StatusCode.scbadloginpassword:
return (
<Wrapper onBack={onBack}>
<Text center={true} type="Body">
Looks like that's a bad password.
</Text>
<Text center={true} type="BodyPrimaryLink" onClick={onPasswordReset}>
Reset your password?
</Text>
</Wrapper>
)
case StatusCode.sckeysyncedpgpnotfound:
case StatusCode.scgpgunavailable:
case StatusCode.sckeynosecret:
return (
<Wrapper onBack={onBack}>
<Text center={true} type="Body">
Sorry, your account is already established with a PGP public key, but we can't access the
corresponding private key.
</Text>
<Text center={true} type="BodySemibold">
You have options:
</Text>
<List>
<Text center={true} type="Body">
{' '}
- Run <Text type="TerminalInline">keybase login</Text> on the device with the corresponding PGP
private key
</Text>
{!isMobile && (
<Text center={true} type="Body">
{' '}
- Install GPG, put your PGP private key on this machine and try again
</Text>
)}
<Text center={true} type="Body">
{' '}
- Go back and authorize with another device or paper key
</Text>
<Text center={true} type="Body">
{' '}
- Or, if none of the above are possible,{' '}
<Text type="BodyPrimaryLink" onClick={onAccountReset}>
reset your account and start fresh
</Text>
</Text>
</List>
</Wrapper>
)
case StatusCode.scinputcanceled:
return (
<Wrapper onBack={onBack}>
<Text center={true} type="Body">
Login cancelled.
</Text>
</Wrapper>
)
case StatusCode.sckeycorrupted:
return (
<Wrapper onBack={onBack}>
<Text center={true} type="Body">
{error.message}
</Text>
<Text center={true} type="Body">
We were able to generate a PGP signature but it was rejected by the server.
</Text>
<Text type="Body">This often means that this PGP key is expired or unusable.</Text>
<Text center={true} type="Body">
You can update your key on{' '}
<Text type="BodyPrimaryLink" onClick={onKBHome}>
keybase.io
</Text>
.
</Text>
</Wrapper>
)
case StatusCode.scdeleted:
return (
<Wrapper onBack={onBack}>
<Text center={true} type="Body">
This user has been deleted.
</Text>
</Wrapper>
)
default:
return (
<Wrapper onBack={onBack}>
<Kb.Box2 direction="vertical">
<Text center={true} type="Body" selectable={true}>
{rewriteErrorDesc[error.desc] || error.desc}
</Text>
<Text center={true} type="BodySmall" selectable={true}>
{' '}
{error.details}
</Text>
</Kb.Box2>
</Wrapper>
)
}
}
Render.navigationOptions = {
modal2: true,
}
const styles = styleSheetCreate(
() =>
({
container: {
maxWidth: 550,
},
header: {
alignSelf: 'center',
marginBottom: 20,
marginTop: 46,
},
icon: {
alignSelf: 'center',
height: 180,
width: 240,
},
list: {
marginBottom: 10,
marginLeft: globalMargins.tiny,
...globalStyles.flexBoxColumn,
maxWidth: 460,
},
} as const)
)
export default Render | the_stack |
import Vue from 'vue';
import {autobind} from '../utils';
import Request from '../HTTP/Request';
import Response from '../HTTP/Response';
import RequestError from '../Errors/RequestError';
import ResponseError from '../Errors/ResponseError';
import ValidationError, {Errors} from '../Errors/ValidationError';
import assign from 'lodash/assign';
import defaults from 'lodash/defaults';
import defaultsDeep from 'lodash/defaultsDeep';
import defaultTo from 'lodash/defaultTo';
import each from 'lodash/each';
import get from 'lodash/get';
import invoke from 'lodash/invoke';
import isFunction from 'lodash/isFunction';
import map from 'lodash/map';
import reduce from 'lodash/reduce';
import replace from 'lodash/replace';
import set from 'lodash/set';
import split from 'lodash/split';
import trim from 'lodash/trim';
import uniqueId from 'lodash/uniqueId';
import {AxiosRequestConfig, Method} from 'axios';
import Model from './Model';
import {BaseResponse} from '../HTTP/BaseResponse';
export enum RequestOperation {
REQUEST_CONTINUE = 0,
REQUEST_REDUNDANT = 1,
REQUEST_SKIP = 2,
}
/**
* Base class for all things common between Model and Collection.
*/
abstract class Base {
static readonly REQUEST_CONTINUE = RequestOperation.REQUEST_CONTINUE;
static readonly REQUEST_REDUNDANT = RequestOperation.REQUEST_REDUNDANT;
static readonly REQUEST_SKIP = RequestOperation.REQUEST_SKIP;
readonly _uid!: string;
private readonly _listeners!: Record<string, Listener[]>;
private readonly _options!: Record<string, any>;
protected constructor(options: Options) {
autobind(this);
// Define an automatic unique ID. This is primarily to distinguish
// between multiple instances of the same name and data.
Object.defineProperty(this, '_uid', {
value: uniqueId(),
enumerable: false,
configurable: false,
writable: false,
});
Vue.set(this, '_listeners', {}); // Event listeners
Vue.set(this, '_options', {}); // Internal option store
this.setOptions(options);
this.boot();
}
/**
* @returns {string} The class name of this instance.
*/
get $class(): string {
return (Object.getPrototypeOf(this)).constructor.name;
}
/**
* Called after construction, this hook allows you to add some extra setup
* logic without having to override the constructor.
*/
boot(): void {
}
/**
* Returns a route configuration in the form {key: name}, where key may be
* 'save', 'fetch', 'delete' or any other custom key, and the name is what
* will be passed to the route resolver to generate the URL. See @getURL
*
* @returns {Object}
*/
routes(): Routes {
return {};
}
/**
* Returns the default context for all events emitted by this instance.
*
* @returns {Object}
*/
getDefaultEventContext(): {target: Base} {
return {target: this};
}
/**
* @returns {string} Default string representation.
*/
toString(): string {
return `<${this.$class} #${this._uid}>`;
}
/**
* Emits an event by name to all registered listeners on that event.
* Listeners will be called in the order that they were added. If a listener
* returns `false`, no other listeners will be called.
*
* @param {string} event The name of the event to emit.
* @param {Object} context The context of the event, passed to listeners.
*/
emit(event: string, context: Record<string, any> = {}): void {
let listeners: Listener[] = get(this._listeners, event);
if ( ! listeners) {
return;
}
// Create the context for the event.
context = defaults({}, context, this.getDefaultEventContext());
// Run through each listener. If any of them return false, stop the
// iteration and mark that the event wasn't handled by all listeners.
each(listeners, (listener: Listener): void => listener(context));
}
/**
* Registers an event listener for a given event.
*
* Event names can be comma-separated to register multiple events.
*
* @param {string} event The name of the event to listen for.
* @param {function} listener The event listener, accepts context.
*/
on(event: string, listener: Listener): void {
let events: string[] = map(split(event, ','), trim);
each(events, (event: string): void => {
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
});
}
/**
* @returns {Object} Parameters to use for replacement in route patterns.
*/
getRouteParameters(): Record<string, string> {
return {};
}
/**
* @returns {RegExp|string} Pattern to match and group route parameters.
*/
getRouteParameterPattern(): RegExp | string {
return this.getOption('routeParameterPattern');
}
/**
* @returns {RegExp} The default route parameter pattern.
*/
getDefaultRouteParameterPattern(): RegExp {
return /\{([^}]+)\}/;
}
/**
* @returns {Object} This class' default options.
*/
getDefaultOptions(): Options {
return {
// Default HTTP methods for requests.
methods: this.getDefaultMethods(),
// Default route parameter interpolation pattern.
routeParameterPattern: this.getDefaultRouteParameterPattern(),
// The HTTP status code to use for indicating a validation error.
validationErrorStatus: 422,
};
}
/**
* @param {Array|string} path Option path resolved by `get`
* @param {*} fallback Fallback value if the option is not set.
*
* @returns {*} The value of the given option path.
*/
getOption(path: string | string[], fallback: any = null): any {
return get(this._options, path, fallback);
}
/**
* @returns {Object} This instance's default options.
*/
options(): Options {
return {};
}
/**
* Sets an option.
*
* @param {string} path
* @param {*} value
*/
setOption(path: string, value: any): void {
set(this._options, path, value);
}
/**
* Sets all given options. Successive values for the same option won't be
* overwritten, so this follows the 'defaults' behaviour, and not 'merge'.
*
* @param {...Object} options One or more objects of options.
*/
setOptions(...options: Options[]): void {
Vue.set(this, '_options', defaultsDeep(
{},
...options, // Given options
this.options(), // Instance defaults
this.getDefaultOptions() // Class defaults
));
}
/**
* Returns all the options that are currently set on this instance.
*
* @return {Object}
*/
getOptions(): Options {
return defaultTo(this._options, {});
}
/**
* Returns a function that translates a route key and parameters to a URL.
*
* @returns {Function} Will be passed `route` and `parameters`
*/
getRouteResolver(): RouteResolver {
return this.getDefaultRouteResolver();
}
/**
* @returns {Object} An object consisting of all route string replacements.
*/
getRouteReplacements(route: string, parameters: Record<string, string> = {}): Record<string, string> {
const replace: Record<string, string> = {};
let pattern: string | RegExp = this.getRouteParameterPattern();
pattern = new RegExp(pattern instanceof RegExp ? pattern.source : pattern, 'g');
for (let parameter: RegExpExecArray | null; (parameter = pattern.exec(route)) !== null; ) {
replace[parameter[0]] = parameters[parameter[1]];
}
return replace;
}
/**
* Returns the default URL provider, which assumes that route keys are URL's,
* and parameter replacement syntax is in the form "{param}".
*
* @returns {Function}
*/
getDefaultRouteResolver(): RouteResolver {
return (route, parameters: Record<string, string> = {}): string => {
let replacements: Record<string, string> = this.getRouteReplacements(route, parameters);
// Replace all route parameters with their replacement values.
return reduce(replacements, (result, value, parameter): string => {
return replace(result, parameter, value);
}, route);
};
}
/**
* @returns {Object} The data to send to the server when saving this model.
*/
getDeleteBody(): any {
return {};
}
/**
* @returns {Object} Query parameters that will be appended to the `fetch` URL.
*/
getFetchQuery(): Record<string, any> {
return {};
}
/**
* @returns {Object} Query parameters that will be appended to the `save` URL.
*/
getSaveQuery(): Record<string, any> {
return {};
}
/**
* @returns {Object} Query parameters that will be appended to the `delete` URL.
*/
getDeleteQuery(): Record<string, any> {
return {};
}
/**
* @returns {string} The key to use when generating the `fetch` URL.
*/
getFetchRoute(): string {
return this.getRoute('fetch');
}
/**
* @returns {string} The key to use when generating the `save` URL.
*/
getSaveRoute(): string {
return this.getRoute('save');
}
/**
* @returns {string} The key to use when generating the `delete` URL.
*/
getDeleteRoute(): string {
return this.getRoute('delete');
}
/**
* @returns {Object} Headers to use when making any request.
*/
getDefaultHeaders(): Record<string, any> {
return {};
}
/**
* @returns {Object} Headers to use when making a save request.
*/
getSaveHeaders(): Record<string, any> {
return this.getDefaultHeaders();
}
/**
* @returns {Object} Headers to use when making a fetch request.
*/
getFetchHeaders(): Record<string, any> {
return this.getDefaultHeaders();
}
/**
* @returns {Object} Headers to use when making a delete request.
*/
getDeleteHeaders(): Record<string, any> {
return this.getDefaultHeaders();
}
/**
* @returns {Object} Default HTTP methods.
*/
getDefaultMethods(): object {
return {
fetch: 'GET',
save: 'POST',
update: 'POST',
create: 'POST',
patch: 'PATCH',
delete: 'DELETE',
};
}
/**
* @returns {string} HTTP method to use when making a save request.
*/
getSaveMethod(): Method {
return this.getOption('methods.save');
}
/**
* @returns {string} HTTP method to use when making a fetch request.
*/
getFetchMethod(): Method {
return this.getOption('methods.fetch');
}
/**
* @returns {string} HTTP method to use when updating a resource.
*/
getUpdateMethod(): Method {
return this.getOption('methods.update');
}
/**
* @returns {string} HTTP method to use when patching a resource.
*/
getPatchMethod(): Method {
return this.getOption('methods.patch');
}
/**
* @returns {string} HTTP method to use when creating a resource.
*/
getCreateMethod(): Method {
return this.getOption('methods.create');
}
/**
* @returns {string} HTTP method to use when deleting a resource.
*/
getDeleteMethod(): Method {
return this.getOption('methods.delete');
}
/**
* @returns {number} The HTTP status code that indicates a validation error.
*/
getValidationErrorStatus(): number {
return defaultTo(this.getOption('validationErrorStatus'), 422);
}
/**
* @returns {boolean} `true` if the response indicates a validation error.
*/
isBackendValidationError(error: RequestError | any): boolean {
// The error must have a response for it to be a validation error.
if ( ! invoke(error, 'getResponse')) {
return false;
}
let status: number = (error as RequestError).getResponse().getStatus();
let invalid: number = this.getValidationErrorStatus();
return status === invalid;
}
/**
* @return {string|undefined} Route value by key.
*/
getRoute(key: string, fallback?: string): string {
let route: string | undefined = get(this.routes(), key, fallback ? get(this.routes(), fallback) : undefined);
if ( ! route) {
throw new Error(`Invalid or missing route`);
}
return route;
}
/**
* @returns {string} The full URL to use when making a fetch request.
*/
getFetchURL(): string {
return this.getURL(this.getFetchRoute(), this.getRouteParameters());
}
/**
* @returns {string} The full URL to use when making a save request.
*/
getSaveURL(): string {
return this.getURL(this.getSaveRoute(), this.getRouteParameters());
}
/**
* @returns {string} The full URL to use when making a delete request.
*/
getDeleteURL(): string {
return this.getURL(this.getDeleteRoute(), this.getRouteParameters());
}
/**
* @param {string} route The route key to use to generate the URL.
* @param {Object} parameters Route parameters.
*
* @returns {string} A URL that was generated using the given route key.
*/
getURL(route: string, parameters: Record<string, any> = {}): string {
return this.getRouteResolver()(route, parameters);
}
/**
* @returns {Request} A new `Request` using the given configuration.
*/
createRequest(config: AxiosRequestConfig): Request {
return new Request(config);
}
/**
* Creates a request error based on a given existing error and optional response.
*/
createRequestError(error: any, response: Response): RequestError {
return new RequestError(error, response);
}
/**
* Creates a response error based on a given existing error and response.
*/
createResponseError(error: any, response?: Response): ResponseError {
return new ResponseError(error, response);
}
/**
* Creates a validation error using given errors and an optional message.
*/
createValidationError(errors: Errors | Errors[], message?: string): ValidationError {
return new ValidationError(errors, message);
}
/**
* This is the central component for all HTTP requests and handling.
*
* @param {Object} config Request configuration
* @param {function} onRequest Called before the request is made.
* @param {function} onSuccess Called when the request was successful.
* @param {function} onFailure Called when the request failed.
*/
request(config: AxiosRequestConfig | (() => AxiosRequestConfig), onRequest: OnRequestCallback,
onSuccess: RequestSuccessCallback, onFailure: RequestFailureCallback): Promise<Response | null> {
return new Promise((resolve, reject): Promise<void> => {
return onRequest().then((status: RequestOperation | boolean): void | Promise<void> => {
switch (status) {
case RequestOperation.REQUEST_CONTINUE:
break;
case RequestOperation.REQUEST_SKIP:
return;
case RequestOperation.REQUEST_REDUNDANT: // Skip, but consider it a success.
onSuccess(null);
resolve(null);
return;
}
// Support passing the request configuration as a function, to allow
// for deferred resolution of certain values that may have changed
// during the call to "onRequest".
if (isFunction(config)) {
config = config();
}
// Make the request.
return this
.createRequest(config)
.send()
.then((response): void => {
onSuccess(response);
resolve(response);
})
.catch((error: ResponseError): void => {
onFailure(error, error.response);
reject(error);
})
.catch(reject); // For errors that occur in `onFailure`.
}).catch(reject);
});
}
abstract onFetch(): Promise<RequestOperation>;
abstract onFetchFailure(error: any, response: Response | undefined): void;
abstract onFetchSuccess(response: Response | null): void;
/**
* Fetches data from the database/API.
*
* @param {options} Fetch options
* @param {options.method} Fetch HTTP method
* @param {options.url} Fetch URL
* @param {options.params} Query params
* @param {options.headers} Query headers
*
* @returns {Promise}
*/
fetch(options: RequestOptions = {}): Promise<Response | null> {
let config = (): AxiosRequestConfig => {
return {
url: defaultTo(options.url, this.getFetchURL()),
method: defaultTo(options.method, this.getFetchMethod()),
params: defaults(options.params, this.getFetchQuery()),
headers: defaults(options.headers, this.getFetchHeaders()),
}
};
return this.request(
config,
this.onFetch,
this.onFetchSuccess,
this.onFetchFailure
);
}
abstract getSaveData(): Record<any, any>;
abstract onSave(): Promise<RequestOperation>;
abstract onSaveFailure(error: any, response: Response | undefined): void;
abstract onSaveSuccess(response: BaseResponse | null): void;
/**
* Persists data to the database/API.
*
* @param {options} Save options
* @param {options.method} Save HTTP method
* @param {options.url} Save URL
* @param {options.data} Save data
* @param {options.params} Query params
* @param {options.headers} Query headers
*
* @returns {Promise}
*/
save(options: RequestOptions = {}): Promise<Response | null> {
let config = (): AxiosRequestConfig => {
return {
url: defaultTo(options.url, this.getSaveURL()),
method: defaultTo(options.method, this.getSaveMethod()),
data: defaultTo(options.data, this.getSaveData()),
params: defaultTo(options.params, this.getSaveQuery()),
headers: defaultTo(options.headers, this.getSaveHeaders()),
}
};
return this.request(
config,
this.onSave,
this.onSaveSuccess,
this.onSaveFailure
);
}
/**
* Converts given data to FormData for uploading.
*
* @param {Object} data
* @returns {FormData}
*/
convertObjectToFormData(data: Record<string, string | Blob>): FormData {
let form: FormData = new FormData();
each(data, (value, key): void => {
form.append(key, value);
});
return form;
}
/**
* Persists data to the database/API using FormData.
*
* @param {options} Save options
* @param {options.method} Save HTTP method
* @param {options.url} Save URL
* @param {options.params} Query params
* @param {options.headers} Query headers
*
* @returns {Promise}
*/
upload(options: Record<any, any> = {}): Promise<Response | null> {
let data: any = defaultTo(options.data, this.getSaveData());
let config: object = (): object => assign(options, {
data: this.convertObjectToFormData(data),
});
return this.save(config);
}
abstract onDelete(): Promise<RequestOperation>;
abstract onDeleteFailure(error: any, response: Response | undefined): void;
abstract onDeleteSuccess(response: Response | null): void;
/**
* Removes model or collection data from the database/API.
*
* @param {options} Delete options
* @param {options.method} Delete HTTP method
* @param {options.url} Delete URL
* @param {options.params} Query params
* @param {options.headers} Query headers
*
* @returns {Promise}
*/
delete(options: RequestOptions = {}): Promise<Response | null> {
let config = (): AxiosRequestConfig => {
return {
url: defaultTo(options.url, this.getDeleteURL()),
method: defaultTo(options.method, this.getDeleteMethod()),
data: defaultTo(options.data, this.getDeleteBody()),
params: defaultTo(options.params, this.getDeleteQuery()),
headers: defaultTo(options.headers, this.getDeleteHeaders()),
}
};
return this.request(
config,
this.onDelete,
this.onDeleteSuccess,
this.onDeleteFailure
);
}
}
export default Base;
export interface Options {
[key: string]: any;
model?: typeof Model;
methods?: Partial<Record<RequestType, HttpMethods>>;
routeParameterPattern?: RegExp;
// validationErrorStatus?: number;
useDeleteBody?: boolean;
}
export type Routes = Record<'fetch' | 'save' | 'delete' | string, string>;
export type Listener = (context: Record<string, any>) => void;
export type RouteResolver = (route: string, parameters: Record<string, string>) => string;
export type RequestFailureCallback = (error: any, response: Response | undefined) => void;
export type RequestSuccessCallback = (response: Response | null) => void;
export type OnRequestCallback = () => Promise<number | boolean>;
export type HttpMethods = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE' | string;
export type RequestType = 'fetch' | 'save' | 'update' | 'create' | 'patch' | 'delete' | string;
export interface RequestOptions {
url?: string;
method?: Method;
data?: any;
params?: Record<string, any>;
headers?: Record<string, any>;
} | the_stack |
import {TypesFetcher} from '../typescript-worker/types-fetcher.js';
import {ImportMapResolver} from '../typescript-worker/import-map-resolver.js';
import {configureFakeCdn} from './worker-test-util.js';
import {assert} from '@esm-bundle/chai';
import {CachingCdn} from '../typescript-worker/caching-cdn.js';
import type {ModuleImportMap} from '../shared/worker-api.js';
import type {CdnData} from './fake-cdn-plugin.js';
import type {PackageJson} from '../typescript-worker/util.js';
import type {
DependencyGraph,
NodeModulesDirectory,
PackageDependencies,
} from '../typescript-worker/node-modules-layout-maker.js';
interface ExpectedDependencyGraph {
root: PackageDependencies;
deps: DependencyGraph;
}
const checkTypesFetcher = async (opts: {
sourceTexts: string[];
packageJson: PackageJson;
cdnData: CdnData;
tsLibs?: string[];
importMap?: ModuleImportMap;
expectedFiles: Map<string, string>;
expectedDependencyGraph?: ExpectedDependencyGraph;
expectedLayout?: NodeModulesDirectory;
}) => {
const {cdnBaseUrl, deleteCdnData} = await configureFakeCdn(opts.cdnData);
try {
await checkTypesFetcherImpl(opts, cdnBaseUrl);
} finally {
await deleteCdnData();
}
};
const checkTypesFetcherImpl = async (
opts: Parameters<typeof checkTypesFetcher>[0],
cdnBaseUrl: string
) => {
const cdn = new CachingCdn(cdnBaseUrl);
const importMapResolver = new ImportMapResolver(opts.importMap ?? {});
const actual = await TypesFetcher.fetchTypes(
cdn,
importMapResolver,
opts.packageJson,
opts.sourceTexts,
opts.tsLibs ?? []
);
if (opts.expectedDependencyGraph !== undefined) {
assert.deepEqual(actual.dependencyGraph, opts.expectedDependencyGraph);
}
if (opts.expectedLayout !== undefined) {
assert.deepEqual(actual.layout, opts.expectedLayout);
}
// Note assert.deepEqual does compare Maps correctly, but it always displays
// "{}" as the difference in the error message, hence this conversion :(
assert.deepEqual(
[...actual.files].sort(([keyA], [keyB]) => keyA.localeCompare(keyB)),
[...opts.expectedFiles].sort(([keyA], [keyB]) => keyA.localeCompare(keyB))
);
};
suite('types fetcher', () => {
test('no sources', async () => {
const sourceTexts: string[] = [];
const packageJson: PackageJson = {};
const cdnData: CdnData = {};
const expectedFiles = new Map();
const expectedDependencyGraph: ExpectedDependencyGraph = {
root: {},
deps: {},
};
const expectedLayout: NodeModulesDirectory = {};
await checkTypesFetcher({
sourceTexts,
packageJson,
cdnData,
expectedLayout,
expectedDependencyGraph,
expectedFiles,
});
});
test('no dependencies', async () => {
const sourceTexts: string[] = [`export const foo = "foo";`];
const packageJson: PackageJson = {};
const cdnData: CdnData = {};
const expectedFiles = new Map();
const expectedDependencyGraph: ExpectedDependencyGraph = {
root: {},
deps: {},
};
const expectedLayout: NodeModulesDirectory = {};
await checkTypesFetcher({
sourceTexts,
packageJson,
cdnData,
expectedFiles,
expectedDependencyGraph,
expectedLayout,
});
});
test('only direct dependencies', async () => {
// ROOT
// /\
// / \
// v v
// A1 B2
const sourceTexts: string[] = [`import 'a';`, `import 'b';`];
const packageJson: PackageJson = {
dependencies: {
a: '^1.0.0',
b: '^1.0.0',
},
};
const cdnData: CdnData = {
a: {
versions: {
'1.0.0': {
files: {
'index.d.ts': {
content: `declare export const a: 1;`,
},
},
},
},
},
b: {
versions: {
'1.0.0': {
files: {
'index.d.ts': {
content: `declare export const b: 1;`,
},
},
},
},
},
};
const expectedDependencyGraph: ExpectedDependencyGraph = {
root: {a: '1.0.0', b: '1.0.0'},
deps: {},
};
// ROOT
// ├── A1
// └── B2
const expectedLayout: NodeModulesDirectory = {
a: {version: '1.0.0', nodeModules: {}},
b: {version: '1.0.0', nodeModules: {}},
};
const expectedFiles = new Map([
['a/package.json', '{}'],
['a/index.d.ts', 'declare export const a: 1;'],
['b/package.json', '{}'],
['b/index.d.ts', 'declare export const b: 1;'],
]);
await checkTypesFetcher({
sourceTexts,
packageJson,
cdnData,
expectedFiles,
expectedDependencyGraph,
expectedLayout,
});
});
test('dependency shared between root and branch', async () => {
// ROOT
// /\
// / \
// v v
// A1 -> B1
const sourceTexts: string[] = [`import 'a';`, `import 'b';`];
const packageJson: PackageJson = {
dependencies: {
a: '^1.0.0',
b: '^1.1.0',
},
};
const cdnData: CdnData = {
a: {
versions: {
'1.1.0': {
files: {
'index.d.ts': {
content: `import 'b';`,
},
'package.json': {
content: `{"dependencies": {"b": "^1.2.0"}}`,
},
},
},
},
},
b: {
versions: {
'1.3.0': {
files: {
'index.d.ts': {
content: `declare export const b: 1;`,
},
},
},
},
},
};
const expectedDependencyGraph: ExpectedDependencyGraph = {
root: {a: '1.1.0', b: '1.3.0'},
deps: {
a: {
'1.1.0': {
b: '1.3.0',
},
},
},
};
// ROOT
// ├── A1
// └── B2
const expectedLayout: NodeModulesDirectory = {
a: {version: '1.1.0', nodeModules: {}},
b: {version: '1.3.0', nodeModules: {}},
};
const expectedFiles = new Map([
['a/package.json', `{"dependencies": {"b": "^1.2.0"}}`],
['a/index.d.ts', `import 'b';`],
['b/package.json', '{}'],
['b/index.d.ts', 'declare export const b: 1;'],
]);
await checkTypesFetcher({
sourceTexts,
packageJson,
cdnData,
expectedFiles,
expectedDependencyGraph,
expectedLayout,
});
});
test('simple chain', async () => {
// ROOT
// |
// v
// A1
// |
// v
// B2
// |
// v
// C3
const sourceTexts: string[] = [`import 'a';`];
const packageJson: PackageJson = {};
const cdnData: CdnData = {
a: {
versions: {
'1.0.0': {
files: {
'index.d.ts': {
content: `declare export * from 'b';`,
},
},
},
},
},
b: {
versions: {
'2.0.0': {
files: {
'index.d.ts': {
content: `declare export * from 'c';`,
},
},
},
},
},
c: {
versions: {
'3.0.0': {
files: {
'index.d.ts': {
content: `declare export const c: 3;`,
},
},
},
},
},
};
const expectedDependencyGraph: ExpectedDependencyGraph = {
root: {a: '1.0.0'},
deps: {
a: {
'1.0.0': {
b: '2.0.0',
},
},
b: {
'2.0.0': {
c: '3.0.0',
},
},
},
};
// ROOT
// ├── A1
// ├── B2
// └── C3
const expectedLayout: NodeModulesDirectory = {
a: {version: '1.0.0', nodeModules: {}},
b: {version: '2.0.0', nodeModules: {}},
c: {version: '3.0.0', nodeModules: {}},
};
const expectedFiles = new Map([
['a/package.json', '{}'],
['a/index.d.ts', `declare export * from 'b';`],
['b/package.json', '{}'],
['b/index.d.ts', `declare export * from 'c';`],
['c/package.json', '{}'],
['c/index.d.ts', `declare export const c: 3;`],
]);
await checkTypesFetcher({
sourceTexts,
packageJson,
cdnData,
expectedFiles,
expectedDependencyGraph,
expectedLayout,
});
});
test('short loop', async () => {
// ROOT --> A1 --> B1
// ^ |
// | |
// +-----+
const sourceTexts: string[] = [`import 'a';`];
const packageJson: PackageJson = {};
const cdnData: CdnData = {
a: {
versions: {
'1.0.0': {
files: {
'index.d.ts': {
content: `declare export * from 'b';`,
},
},
},
},
},
b: {
versions: {
'1.0.0': {
files: {
'index.d.ts': {
content: `declare export * from 'a';`,
},
},
},
},
},
};
const expectedDependencyGraph: ExpectedDependencyGraph = {
root: {a: '1.0.0'},
deps: {
a: {
'1.0.0': {
b: '1.0.0',
},
},
b: {
'1.0.0': {
a: '1.0.0',
},
},
},
};
// ROOT
// ├── A1
// └── B1
const expectedLayout: NodeModulesDirectory = {
a: {version: '1.0.0', nodeModules: {}},
b: {version: '1.0.0', nodeModules: {}},
};
const expectedFiles = new Map([
['a/package.json', '{}'],
['a/index.d.ts', `declare export * from 'b';`],
['b/package.json', '{}'],
['b/index.d.ts', `declare export * from 'a';`],
]);
await checkTypesFetcher({
sourceTexts,
packageJson,
cdnData,
expectedFiles,
expectedDependencyGraph,
expectedLayout,
});
});
test('bare -> relative -> bare', async () => {
// ROOT
// |
// v
// A1 --> A1/other
// |
// v
// B1
const sourceTexts: string[] = [`import 'a';`];
const packageJson: PackageJson = {};
const cdnData: CdnData = {
a: {
versions: {
'1.2.3': {
files: {
'index.d.ts': {
content: `import "./other.js";`,
},
'other.d.ts': {
content: 'import "b";',
},
},
},
},
},
b: {
versions: {
'1.3.4': {
files: {
'index.d.ts': {
content: `declare export const b: 2;`,
},
},
},
},
},
};
const expectedDependencyGraph: ExpectedDependencyGraph = {
root: {a: '1.2.3'},
deps: {
a: {
'1.2.3': {b: '1.3.4'},
},
},
};
// ROOT
// ├── A1
// └── B1
const expectedLayout: NodeModulesDirectory = {
a: {
version: '1.2.3',
nodeModules: {},
},
b: {
version: '1.3.4',
nodeModules: {},
},
};
const expectedFiles = new Map([
['a/package.json', '{}'],
['a/index.d.ts', `import "./other.js";`],
['a/other.d.ts', `import "b";`],
['b/package.json', '{}'],
['b/index.d.ts', `declare export const b: 2;`],
]);
await checkTypesFetcher({
sourceTexts,
packageJson,
cdnData,
expectedFiles,
expectedDependencyGraph,
expectedLayout,
});
});
test('version conflict between root and branch', async () => {
// ROOT
// /\
// v v
// A1 B1
// |
// v
// B2
const sourceTexts: string[] = [`import 'a';`, `import 'b';`];
const packageJson: PackageJson = {
dependencies: {
a: '^1.0.0',
b: '^1.0.0',
},
};
const cdnData: CdnData = {
a: {
versions: {
'1.0.0': {
files: {
'index.d.ts': {
content: `declare export * from 'b';`,
},
'package.json': {
content: `{"dependencies": {"b": "^2.0.0"}}`,
},
},
},
},
},
b: {
versions: {
'1.0.0': {
files: {
'index.d.ts': {
content: `declare export const b: 1;`,
},
},
},
'2.0.0': {
files: {
'index.d.ts': {
content: `declare export const b: 2;`,
},
},
},
},
},
};
const expectedDependencyGraph: ExpectedDependencyGraph = {
root: {a: '1.0.0', b: '1.0.0'},
deps: {
a: {
'1.0.0': {
b: '2.0.0',
},
},
},
};
// ROOT
// ├── A1
// │ └── B2
// └── B1
const expectedLayout: NodeModulesDirectory = {
a: {
version: '1.0.0',
nodeModules: {
b: {version: '2.0.0', nodeModules: {}},
},
},
b: {version: '1.0.0', nodeModules: {}},
};
const expectedFiles = new Map([
['a/package.json', `{"dependencies": {"b": "^2.0.0"}}`],
['a/index.d.ts', `declare export * from 'b';`],
['a/node_modules/b/package.json', '{}'],
['a/node_modules/b/index.d.ts', `declare export const b: 2;`],
['b/package.json', '{}'],
['b/index.d.ts', `declare export const b: 1;`],
]);
await checkTypesFetcher({
sourceTexts,
packageJson,
cdnData,
expectedFiles,
expectedDependencyGraph,
expectedLayout,
});
});
test('tslibs', async () => {
const sourceTexts: string[] = [];
const tsLibs = ['es2020', 'DOM'];
const packageJson: PackageJson = {};
const cdnData: CdnData = {
typescript: {
versions: {
'4.3.5': {
files: {
'lib/lib.es2020.d.ts': {
// References are the same as imports from our perspective.
content: `/// <reference lib="es2020.promise" />`,
},
'lib/lib.es2020.promise.d.ts': {
content: `interface PromiseConstructor { }`,
},
// Note standard lib files are always lower-case.
'lib/lib.dom.d.ts': {
content: `interface HTMLElement { }`,
},
},
},
},
},
};
const expectedDependencyGraph: ExpectedDependencyGraph = {
root: {
typescript: '4.3.5',
},
deps: {},
};
const expectedLayout: NodeModulesDirectory = {
typescript: {
version: '4.3.5',
nodeModules: {},
},
};
const expectedFiles = new Map([
[
'typescript/lib/lib.es2020.d.ts',
`/// <reference lib="es2020.promise" />`,
],
[
'typescript/lib/lib.es2020.promise.d.ts',
`interface PromiseConstructor { }`,
],
['typescript/lib/lib.dom.d.ts', `interface HTMLElement { }`],
]);
await checkTypesFetcher({
sourceTexts,
tsLibs,
packageJson,
cdnData,
expectedFiles,
expectedDependencyGraph,
expectedLayout,
});
});
test('declare module', async () => {
// Declaring a module should not count as an import, but anything imported
// from within the declare module block should.
const sourceTexts: string[] = [
`
declare module "x" {
declare export * from "a";
}
`,
];
const packageJson: PackageJson = {
dependencies: {
a: '^1.0.0',
x: '^1.0.0',
},
};
const cdnData: CdnData = {
a: {
versions: {
'1.0.0': {
files: {
'index.d.ts': {
content: `
declare module "a" {
declare export * from "a/internal.js";
}`,
},
'internal.d.ts': {
content: `declare export const a: 1;`,
},
},
},
},
},
x: {
versions: {
'1.0.0': {
files: {
'index.d.ts': {
content: `declare export const x: 1;`,
},
},
},
},
},
};
const expectedDependencyGraph: ExpectedDependencyGraph = {
root: {a: '1.0.0'},
deps: {},
};
const expectedLayout: NodeModulesDirectory = {
a: {
version: '1.0.0',
nodeModules: {},
},
};
const expectedFiles = new Map([
['a/package.json', '{}'],
[
'a/index.d.ts',
`
declare module "a" {
declare export * from "a/internal.js";
}`,
],
['a/internal.d.ts', 'declare export const a: 1;'],
]);
await checkTypesFetcher({
sourceTexts,
packageJson,
cdnData,
expectedFiles,
expectedDependencyGraph,
expectedLayout,
});
});
test('version conflict requiring directory duplication', async () => {
// ROOT
// /|\
// / | \
// / | \
// v v v
// A1 B1 C1
// \ /
// \ /
// v
// A2
const sourceTexts: string[] = [
`import 'a';
import 'b';
import 'c';
`,
];
const packageJson: PackageJson = {
dependencies: {
a: '1.0.0',
b: '1.0.0',
c: '1.0.0',
},
};
const cdnData: CdnData = {
a: {
versions: {
'1.0.0': {
files: {
'index.d.ts': {
content: `declare export const: 1;`,
},
},
},
'2.0.0': {
files: {
'index.d.ts': {
content: `declare export const: 2;`,
},
},
},
},
},
b: {
versions: {
'1.0.0': {
files: {
'index.d.ts': {
content: `declare export * from 'a';`,
},
'package.json': {
content: `{"dependencies": {"a": "2.0.0"}}`,
},
},
},
},
},
c: {
versions: {
'1.0.0': {
files: {
'index.d.ts': {
content: `declare export * from 'a';`,
},
'package.json': {
content: `{"dependencies": {"a": "2.0.0"}}`,
},
},
},
},
},
};
const expectedDependencyGraph: ExpectedDependencyGraph = {
root: {a: '1.0.0', b: '1.0.0', c: '1.0.0'},
deps: {
b: {
'1.0.0': {
a: '2.0.0',
},
},
c: {
'1.0.0': {
a: '2.0.0',
},
},
},
};
// ROOT
// ├── A1
// ├── B1
// │ └── A2
// └── C1
// └── A2
const expectedLayout: NodeModulesDirectory = {
a: {
version: '1.0.0',
nodeModules: {},
},
b: {
version: '1.0.0',
nodeModules: {
a: {
version: '2.0.0',
nodeModules: {},
},
},
},
c: {
version: '1.0.0',
nodeModules: {
a: {
version: '2.0.0',
nodeModules: {},
},
},
},
};
const expectedFiles = new Map([
['a/package.json', '{}'],
['a/index.d.ts', `declare export const: 1;`],
['b/package.json', `{"dependencies": {"a": "2.0.0"}}`],
['b/index.d.ts', `declare export * from 'a';`],
['b/node_modules/a/package.json', `{}`],
['b/node_modules/a/index.d.ts', `declare export const: 2;`],
['c/package.json', `{"dependencies": {"a": "2.0.0"}}`],
['c/index.d.ts', `declare export * from 'a';`],
['c/node_modules/a/package.json', `{}`],
['c/node_modules/a/index.d.ts', `declare export const: 2;`],
]);
await checkTypesFetcher({
sourceTexts,
packageJson,
cdnData,
expectedFiles,
expectedDependencyGraph,
expectedLayout,
});
});
test('import map: specifier includes filename', async () => {
const sourceTexts: string[] = [`import {foo} from 'foo/foo.js';`];
const packageJson: PackageJson = {};
const cdnData: CdnData = {
foo: {
versions: {
'2.0.0': {
files: {},
},
'1.2.3': {
files: {
'foo.d.ts': {
content: 'declare export const foo: string;',
},
},
},
},
},
};
// Note we're using the fake CDN in a slightly different way in this test by
// directly providing the URL in the import maps.
const {cdnBaseUrl, deleteCdnData} = await configureFakeCdn(cdnData);
const importMap: ModuleImportMap = {
imports: {
foo: `${cdnBaseUrl}foo@1.2.3`,
'foo/': `${cdnBaseUrl}foo@1.2.3/`,
},
};
const expectedFiles = new Map([
['foo/foo.d.ts', 'declare export const foo: string;'],
]);
try {
await checkTypesFetcherImpl(
{
sourceTexts,
packageJson,
cdnData,
importMap,
expectedFiles,
},
cdnBaseUrl
);
} finally {
await deleteCdnData();
}
});
test('import map: dependency has relative import', async () => {
const sourceTexts: string[] = [`import {foo} from 'foo/foo.js';`];
const packageJson: PackageJson = {};
const cdnData: CdnData = {
foo: {
versions: {
'2.0.0': {
files: {},
},
'1.2.3': {
files: {
'foo.d.ts': {
content: 'export * from "./bar.js";',
},
'bar.d.ts': {
content: 'declare export const foo: string;',
},
},
},
},
},
};
const {cdnBaseUrl, deleteCdnData} = await configureFakeCdn(cdnData);
const importMap: ModuleImportMap = {
imports: {
foo: `${cdnBaseUrl}foo@1.2.3`,
'foo/': `${cdnBaseUrl}foo@1.2.3/`,
},
};
const expectedFiles = new Map([
['foo/foo.d.ts', 'export * from "./bar.js";'],
['foo/bar.d.ts', 'declare export const foo: string;'],
]);
try {
await checkTypesFetcherImpl(
{
sourceTexts,
packageJson,
cdnData,
importMap,
expectedFiles,
},
cdnBaseUrl
);
} finally {
await deleteCdnData();
}
});
test('import map: reads "typings" from package.json', async () => {
const sourceTexts: string[] = [
`import {foo} from 'foo';
import {foo as alsofoo} from 'alsofoo';`,
];
const packageJson: PackageJson = {};
const cdnData: CdnData = {
foo: {
versions: {
'2.0.0': {
files: {},
},
'1.2.3': {
files: {
'package.json': {
content: '{"typings": "typings.d.ts"}',
},
'typings.d.ts': {
content: 'declare export const foo: string;',
},
},
},
},
},
};
const {cdnBaseUrl, deleteCdnData} = await configureFakeCdn(cdnData);
const importMap: ModuleImportMap = {
imports: {
foo: `${cdnBaseUrl}foo@1.2.3`,
'foo/': `${cdnBaseUrl}foo@1.2.3/`,
// Two packages can be mapped to the same URL. The typings will be
// duplicated into both node_modules/ directories.
alsofoo: `${cdnBaseUrl}foo@1.2.3`,
'alsofoo/': `${cdnBaseUrl}foo@1.2.3/`,
},
};
const expectedFiles = new Map([
['foo/package.json', '{"typings": "typings.d.ts"}'],
['foo/typings.d.ts', 'declare export const foo: string;'],
['alsofoo/package.json', '{"typings": "typings.d.ts"}'],
['alsofoo/typings.d.ts', 'declare export const foo: string;'],
]);
try {
await checkTypesFetcherImpl(
{
sourceTexts,
packageJson,
cdnData,
importMap,
expectedFiles,
},
cdnBaseUrl
);
} finally {
await deleteCdnData();
}
});
test('CDN HTTP errors', async () => {
// a/b/c should still resolve, even though there are 404 and 500 errors
// served by other imports.
const sourceTexts: string[] = [
`import 'a';
import 'missing';
import 'b';
import 'broken';
import 'c';`,
];
const packageJson: PackageJson = {
dependencies: {
a: '^1.0.0',
b: '^1.0.0',
c: '^1.0.0',
broken: '^1.0.0',
},
};
const cdnData: CdnData = {
a: {
versions: {
'1.0.0': {
files: {
'index.d.ts': {
content: `declare export const a: 1;`,
},
},
},
},
},
b: {
versions: {
'1.0.0': {
files: {
'index.d.ts': {
content: `declare export const b: 1;`,
},
},
},
},
},
c: {
versions: {
'1.0.0': {
files: {
'index.d.ts': {
content: `declare export const c: 1;`,
},
},
},
},
},
broken: {
versions: {
'1.0.0': {
files: {
'package.json': {
status: 500,
content: 'Internal error',
},
'index.d.ts': {
status: 500,
content: 'Internal error',
},
},
},
},
},
};
const expectedDependencyGraph: ExpectedDependencyGraph = {
root: {
a: '1.0.0',
b: '1.0.0',
c: '1.0.0',
},
deps: {},
};
const expectedLayout: NodeModulesDirectory = {
a: {
version: '1.0.0',
nodeModules: {},
},
b: {
version: '1.0.0',
nodeModules: {},
},
c: {
version: '1.0.0',
nodeModules: {},
},
};
const expectedFiles = new Map([
['a/package.json', '{}'],
['a/index.d.ts', 'declare export const a: 1;'],
['b/package.json', '{}'],
['b/index.d.ts', 'declare export const b: 1;'],
['c/package.json', '{}'],
['c/index.d.ts', 'declare export const c: 1;'],
]);
await checkTypesFetcher({
sourceTexts,
packageJson,
cdnData,
expectedFiles,
expectedDependencyGraph,
expectedLayout,
});
});
}); | the_stack |
import * as k8s from "@kubernetes/client-node";
import * as http from "http";
import * as request from "request";
import { requestError } from "../support/error";
import { K8sDefaultNamespace } from "../support/namespace";
import { logObject } from "./resource";
/** Response from methods that operate on an resource. */
export interface K8sObjectResponse {
body: k8s.KubernetesObject;
response: http.IncomingMessage;
}
/** Response from list method. */
export interface K8sListResponse {
body: k8s.KubernetesListObject<k8s.KubernetesObject>;
response: http.IncomingMessage;
}
/** Response from delete method. */
export interface K8sDeleteResponse {
body: k8s.V1Status;
response: http.IncomingMessage;
}
/** Response from list API method. */
export interface K8sApiResponse {
body: k8s.V1APIResourceList;
response: http.IncomingMessage;
}
/** Union type of all response types. */
type K8sRequestResponse = K8sObjectResponse | K8sDeleteResponse | K8sListResponse | K8sApiResponse;
/** Kubernetes API verbs. */
export type K8sApiAction = "create" | "delete" | "list" | "patch" | "read" | "replace";
/** Type of option argument for object API requests. */
export interface K8sObjectRequestOptions { headers: { [name: string]: string; }; }
/**
* Valid Content-Type header values for patch operations. See
* https://kubernetes.io/docs/tasks/run-application/update-api-object-kubectl-patch/
* for details.
*/
export enum K8sPatchStrategies {
/** Diff-like JSON format. */
JsonPatch = "application/json-patch+json",
/** Simple merge. */
MergePatch = "application/merge-patch+json",
/** Merge with different strategies depending on field metadata. */
StrategicMergePatch = "application/strategic-merge-patch+json",
}
/**
* Dynamically construct Kubernetes API request URIs so client does
* not have to know what type of object it is acting on, create the
* appropriate client, and call the appropriate method.
*/
export class K8sObjectApi extends k8s.ApisApi {
private static readonly defaultDeleteBody: k8s.V1DeleteOptions = { propagationPolicy: "Background" };
/**
* Read any Kubernetes resource.
*/
public async create(spec: k8s.KubernetesObject, options?: K8sObjectRequestOptions): Promise<K8sObjectResponse> {
const requestOptions = this.baseRequestOptions("POST", options);
requestOptions.uri += await this.specUriPath(spec, "create");
requestOptions.body = spec;
return this.requestPromise(requestOptions) as unknown as K8sObjectResponse;
}
/**
* Delete any Kubernetes resource.
*/
public async delete(spec: k8s.KubernetesObject, body?: k8s.V1DeleteOptions, options?: K8sObjectRequestOptions): Promise<K8sDeleteResponse> {
const requestOptions = this.baseRequestOptions("DELETE", options);
requestOptions.uri += await this.specUriPath(spec, "delete");
requestOptions.body = body || K8sObjectApi.defaultDeleteBody;
return this.requestPromise(requestOptions) as unknown as K8sDeleteResponse;
}
/**
* List any Kubernetes resource.
*/
public async list(spec: k8s.KubernetesObject, options?: K8sObjectRequestOptions): Promise<K8sListResponse> {
const requestOptions = this.baseRequestOptions("GET", options);
requestOptions.uri += await this.specUriPath(spec, "list");
return this.requestPromise(requestOptions) as unknown as K8sListResponse;
}
/**
* Patch any Kubernetes resource.
*/
public async patch(spec: k8s.KubernetesObject, options?: K8sObjectRequestOptions): Promise<K8sObjectResponse> {
const requestOptions = this.baseRequestOptions("PATCH", options);
requestOptions.uri += await this.specUriPath(spec, "patch");
requestOptions.body = spec;
return this.requestPromise(requestOptions) as unknown as K8sObjectResponse;
}
/**
* Read any Kubernetes resource.
*/
public async read(spec: k8s.KubernetesObject, options?: K8sObjectRequestOptions): Promise<K8sObjectResponse> {
const requestOptions = this.baseRequestOptions("GET", options);
requestOptions.uri += await this.specUriPath(spec, "read");
return this.requestPromise(requestOptions) as unknown as K8sObjectResponse;
}
/**
* Replace any Kubernetes resource.
*/
public async replace(spec: k8s.KubernetesObject, options?: K8sObjectRequestOptions): Promise<K8sObjectResponse> {
const requestOptions = this.baseRequestOptions("PUT", options);
requestOptions.uri += await this.specUriPath(spec, "replace");
requestOptions.body = spec;
return this.requestPromise(requestOptions) as unknown as K8sObjectResponse;
}
/**
* Get metadata from Kubernetes API for resources described by
* `kind` and `apiVersion`. If it is unable to find the resource
* `kind` under the provided `apiVersion`, `undefined` is
* returned.
*/
public async resource(apiVersion: string, kind: string): Promise<k8s.V1APIResource | undefined> {
try {
const requestOptions = this.baseRequestOptions();
const prefix = (apiVersion.includes("/")) ? "apis" : "api";
requestOptions.uri += [prefix, apiVersion].join("/");
const getApiResponse = await this.requestPromise(requestOptions);
const apiResourceList = getApiResponse.body as unknown as k8s.V1APIResourceList;
return apiResourceList.resources.find(r => r.kind === kind);
} catch (e) {
e.message = `Failed to fetch resource metadata for ${apiVersion}/${kind}: ${e.message}`;
throw e;
}
}
/**
* Generate request options. Largely copied from the common
* elements of @kubernetes/client-node action methods.
*/
public baseRequestOptions(method: string = "GET", options?: K8sObjectRequestOptions): request.UriOptions & request.CoreOptions {
const localVarPath = this.basePath + "/";
const queryParameters = {};
const headerParams = Object.assign({}, this.defaultHeaders, K8sObjectApi.methodHeaders(method), options?.headers || {});
const requestOptions = {
method,
qs: queryParameters,
headers: headerParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
this.authentications.BearerToken.applyToRequest(requestOptions);
this.authentications.default.applyToRequest(requestOptions);
return requestOptions;
}
/**
* Use spec information to construct resource URI path. If any
* required information in not provided, an Error is thrown. If an
* `apiVersion` is not provided, "v1" is used. If a `metadata.namespace`
* is not provided for a request that requires one, "default" is used.
*
* @param spec resource spec which must kind and apiVersion properties
* @param action API action, see [[K8sApiAction]]
* @return tail of resource-specific URI
*/
public async specUriPath(spec: k8s.KubernetesObject, action: K8sApiAction): Promise<string> {
if (!spec.kind) {
throw new Error(`Spec does not contain kind: ${logObject(spec)}`);
}
if (!spec.apiVersion) {
spec.apiVersion = "v1";
}
if (!spec.metadata) {
spec.metadata = {};
}
const resource = await this.resource(spec.apiVersion, spec.kind);
if (!resource) {
throw new Error(`Unrecognized API version and kind: ${spec.apiVersion} ${spec.kind}`);
}
if (namespaceRequired(resource, action) && !spec.metadata.namespace) {
spec.metadata.namespace = K8sDefaultNamespace;
}
const prefix = (spec.apiVersion.includes("/")) ? "apis" : "api";
const parts = [prefix, spec.apiVersion];
if (resource.namespaced && spec.metadata.namespace) {
parts.push("namespaces", spec.metadata.namespace);
}
parts.push(resource.name);
if (appendName(action)) {
if (!spec.metadata.name) {
throw new Error(`Spec does not contain name: ${logObject(spec)}`);
}
parts.push(spec.metadata.name);
}
return parts.join("/").toLowerCase();
}
/**
* Wrap request in a Promise. Largely copied from @kubernetes/client-node/dist/api.js.
*/
private requestPromise(requestOptions: request.UriOptions & request.CoreOptions): Promise<K8sRequestResponse> {
return new Promise((resolve, reject) => {
request(requestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode >= 200 && response.statusCode <= 299) {
resolve({ response, body });
} else {
reject(requestError({ response, body }));
}
}
});
});
}
/**
* Return default headers based on action.
*/
private static methodHeaders(method: string): { [name: string]: string } {
return (method === "PATCH") ? { "Content-Type": K8sPatchStrategies.StrategicMergePatch } : {};
}
}
/**
* Return whether the name of the resource should be appended to the
* API URI path. When creating and listing resources, it is not
* appended.
*
* @param action API action, see [[K8sApiAction]]
* @return true if name should be appended to URI
*/
export function appendName(action: K8sApiAction): boolean {
return !(action === "create" || action === "list");
}
/**
* Return whether namespace must be included in resource API URI.
* It returns true of the resource is namespaced and the action is
* not "list". The namespace can be provided when the action is
* "list", but it need not be.
*
* @param resource resource metadata
* @param action API action, see [[K8sApiAction]]
* @return true is the namespace is required in the API URI path
*/
export function namespaceRequired(resource: k8s.V1APIResource, action: K8sApiAction): boolean {
// return action !== "list" || resource.namespaced;
// return !(action === "list" || !resource.namespaced);
return resource.namespaced && action !== "list";
} | the_stack |
import { Room } from "matrix-js-sdk/src/models/room";
import { logger } from "matrix-js-sdk/src/logger";
import { RoomUpdateCause, TagID } from "../../models";
import { SortAlgorithm } from "../models";
import { sortRoomsWithAlgorithm } from "../tag-sorting";
import { OrderingAlgorithm } from "./OrderingAlgorithm";
import { NotificationColor } from "../../../notifications/NotificationColor";
import { RoomNotificationStateStore } from "../../../notifications/RoomNotificationStateStore";
interface ICategorizedRoomMap {
// @ts-ignore - TS wants this to be a string, but we know better
[category: NotificationColor]: Room[];
}
interface ICategoryIndex {
// @ts-ignore - TS wants this to be a string, but we know better
[category: NotificationColor]: number; // integer
}
// Caution: changing this means you'll need to update a bunch of assumptions and
// comments! Check the usage of Category carefully to figure out what needs changing
// if you're going to change this array's order.
const CATEGORY_ORDER = [
NotificationColor.Unsent,
NotificationColor.Red,
NotificationColor.Grey,
NotificationColor.Bold,
NotificationColor.None, // idle
];
/**
* An implementation of the "importance" algorithm for room list sorting. Where
* the tag sorting algorithm does not interfere, rooms will be ordered into
* categories of varying importance to the user. Alphabetical sorting does not
* interfere with this algorithm, however manual ordering does.
*
* The importance of a room is defined by the kind of notifications, if any, are
* present on the room. These are classified internally as Unsent, Red, Grey,
* Bold, and Idle. 'Unsent' rooms have unsent messages, Red rooms have mentions,
* grey have unread messages, bold is a less noisy version of grey, and idle
* means all activity has been seen by the user.
*
* The algorithm works by monitoring all room changes, including new messages in
* tracked rooms, to determine if it needs a new category or different placement
* within the same category. For more information, see the comments contained
* within the class.
*/
export class ImportanceAlgorithm extends OrderingAlgorithm {
// This tracks the category for the tag it represents by tracking the index of
// each category within the list, where zero is the top of the list. This then
// tracks when rooms change categories and splices the orderedRooms array as
// needed, preventing many ordering operations.
private indices: ICategoryIndex = {};
public constructor(tagId: TagID, initialSortingAlgorithm: SortAlgorithm) {
super(tagId, initialSortingAlgorithm);
}
// noinspection JSMethodCanBeStatic
private categorizeRooms(rooms: Room[]): ICategorizedRoomMap {
const map: ICategorizedRoomMap = {
[NotificationColor.Unsent]: [],
[NotificationColor.Red]: [],
[NotificationColor.Grey]: [],
[NotificationColor.Bold]: [],
[NotificationColor.None]: [],
};
for (const room of rooms) {
const category = this.getRoomCategory(room);
map[category].push(room);
}
return map;
}
// noinspection JSMethodCanBeStatic
private getRoomCategory(room: Room): NotificationColor {
// It's fine for us to call this a lot because it's cached, and we shouldn't be
// wasting anything by doing so as the store holds single references
const state = RoomNotificationStateStore.instance.getRoomState(room);
return state.color;
}
public setRooms(rooms: Room[]): void {
if (this.sortingAlgorithm === SortAlgorithm.Manual) {
this.cachedOrderedRooms = sortRoomsWithAlgorithm(rooms, this.tagId, this.sortingAlgorithm);
} else {
// Every other sorting type affects the categories, not the whole tag.
const categorized = this.categorizeRooms(rooms);
for (const category of Object.keys(categorized)) {
const roomsToOrder = categorized[category];
categorized[category] = sortRoomsWithAlgorithm(roomsToOrder, this.tagId, this.sortingAlgorithm);
}
const newlyOrganized: Room[] = [];
const newIndices: ICategoryIndex = {};
for (const category of CATEGORY_ORDER) {
newIndices[category] = newlyOrganized.length;
newlyOrganized.push(...categorized[category]);
}
this.indices = newIndices;
this.cachedOrderedRooms = newlyOrganized;
}
}
private handleSplice(room: Room, cause: RoomUpdateCause): boolean {
if (cause === RoomUpdateCause.NewRoom) {
const category = this.getRoomCategory(room);
this.alterCategoryPositionBy(category, 1, this.indices);
this.cachedOrderedRooms.splice(this.indices[category], 0, room); // splice in the new room (pre-adjusted)
this.sortCategory(category);
} else if (cause === RoomUpdateCause.RoomRemoved) {
const roomIdx = this.getRoomIndex(room);
if (roomIdx === -1) {
logger.warn(`Tried to remove unknown room from ${this.tagId}: ${room.roomId}`);
return false; // no change
}
const oldCategory = this.getCategoryFromIndices(roomIdx, this.indices);
this.alterCategoryPositionBy(oldCategory, -1, this.indices);
this.cachedOrderedRooms.splice(roomIdx, 1); // remove the room
} else {
throw new Error(`Unhandled splice: ${cause}`);
}
// changes have been made if we made it here, so say so
return true;
}
public handleRoomUpdate(room: Room, cause: RoomUpdateCause): boolean {
if (cause === RoomUpdateCause.NewRoom || cause === RoomUpdateCause.RoomRemoved) {
return this.handleSplice(room, cause);
}
if (cause !== RoomUpdateCause.Timeline && cause !== RoomUpdateCause.ReadReceipt) {
throw new Error(`Unsupported update cause: ${cause}`);
}
const category = this.getRoomCategory(room);
if (this.sortingAlgorithm === SortAlgorithm.Manual) {
return; // Nothing to do here.
}
const roomIdx = this.getRoomIndex(room);
if (roomIdx === -1) {
throw new Error(`Room ${room.roomId} has no index in ${this.tagId}`);
}
// Try to avoid doing array operations if we don't have to: only move rooms within
// the categories if we're jumping categories
const oldCategory = this.getCategoryFromIndices(roomIdx, this.indices);
if (oldCategory !== category) {
// Move the room and update the indices
this.moveRoomIndexes(1, oldCategory, category, this.indices);
this.cachedOrderedRooms.splice(roomIdx, 1); // splice out the old index (fixed position)
this.cachedOrderedRooms.splice(this.indices[category], 0, room); // splice in the new room (pre-adjusted)
// Note: if moveRoomIndexes() is called after the splice then the insert operation
// will happen in the wrong place. Because we would have already adjusted the index
// for the category, we don't need to determine how the room is moving in the list.
// If we instead tried to insert before updating the indices, we'd have to determine
// whether the room was moving later (towards IDLE) or earlier (towards RED) from its
// current position, as it'll affect the category's start index after we remove the
// room from the array.
}
// Sort the category now that we've dumped the room in
this.sortCategory(category);
return true; // change made
}
private sortCategory(category: NotificationColor) {
// This should be relatively quick because the room is usually inserted at the top of the
// category, and most popular sorting algorithms will deal with trying to keep the active
// room at the top/start of the category. For the few algorithms that will have to move the
// thing quite far (alphabetic with a Z room for example), the list should already be sorted
// well enough that it can rip through the array and slot the changed room in quickly.
const nextCategoryStartIdx = category === CATEGORY_ORDER[CATEGORY_ORDER.length - 1]
? Number.MAX_SAFE_INTEGER
: this.indices[CATEGORY_ORDER[CATEGORY_ORDER.indexOf(category) + 1]];
const startIdx = this.indices[category];
const numSort = nextCategoryStartIdx - startIdx; // splice() returns up to the max, so MAX_SAFE_INT is fine
const unsortedSlice = this.cachedOrderedRooms.splice(startIdx, numSort);
const sorted = sortRoomsWithAlgorithm(unsortedSlice, this.tagId, this.sortingAlgorithm);
this.cachedOrderedRooms.splice(startIdx, 0, ...sorted);
}
// noinspection JSMethodCanBeStatic
private getCategoryFromIndices(index: number, indices: ICategoryIndex): NotificationColor {
for (let i = 0; i < CATEGORY_ORDER.length; i++) {
const category = CATEGORY_ORDER[i];
const isLast = i === (CATEGORY_ORDER.length - 1);
const startIdx = indices[category];
const endIdx = isLast ? Number.MAX_SAFE_INTEGER : indices[CATEGORY_ORDER[i + 1]];
if (index >= startIdx && index < endIdx) {
return category;
}
}
// "Should never happen" disclaimer goes here
throw new Error("Programming error: somehow you've ended up with an index that isn't in a category");
}
// noinspection JSMethodCanBeStatic
private moveRoomIndexes(
nRooms: number,
fromCategory: NotificationColor,
toCategory: NotificationColor,
indices: ICategoryIndex,
) {
// We have to update the index of the category *after* the from/toCategory variables
// in order to update the indices correctly. Because the room is moving from/to those
// categories, the next category's index will change - not the category we're modifying.
// We also need to update subsequent categories as they'll all shift by nRooms, so we
// loop over the order to achieve that.
this.alterCategoryPositionBy(fromCategory, -nRooms, indices);
this.alterCategoryPositionBy(toCategory, +nRooms, indices);
}
private alterCategoryPositionBy(category: NotificationColor, n: number, indices: ICategoryIndex) {
// Note: when we alter a category's index, we actually have to modify the ones following
// the target and not the target itself.
// XXX: If this ever actually gets more than one room passed to it, it'll need more index
// handling. For instance, if 45 rooms are removed from the middle of a 50 room list, the
// index for the categories will be way off.
const nextOrderIndex = CATEGORY_ORDER.indexOf(category) + 1;
if (n > 0) {
for (let i = nextOrderIndex; i < CATEGORY_ORDER.length; i++) {
const nextCategory = CATEGORY_ORDER[i];
indices[nextCategory] += Math.abs(n);
}
} else if (n < 0) {
for (let i = nextOrderIndex; i < CATEGORY_ORDER.length; i++) {
const nextCategory = CATEGORY_ORDER[i];
indices[nextCategory] -= Math.abs(n);
}
}
// Do a quick check to see if we've completely broken the index
for (let i = 1; i <= CATEGORY_ORDER.length; i++) {
const lastCat = CATEGORY_ORDER[i - 1];
const thisCat = CATEGORY_ORDER[i];
if (indices[lastCat] > indices[thisCat]) {
// "should never happen" disclaimer goes here
logger.warn(
`!! Room list index corruption: ${lastCat} (i:${indices[lastCat]}) is greater ` +
`than ${thisCat} (i:${indices[thisCat]}) - category indices are likely desynced from reality`);
// TODO: Regenerate index when this happens: https://github.com/vector-im/element-web/issues/14234
}
}
}
} | the_stack |
import { DeepPartial } from '../utils/DeepPartial';
import { deepMerge } from '../utils/DeepMerge';
import { MatchEngine } from '../MatchEngine';
import { Agent } from '../Agent';
import { Logger } from '../Logger';
import { Design } from '../Design';
import {
FatalError,
MatchDestroyedError,
MatchWarn,
MatchError,
NotSupportedError,
MatchReplayFileError,
AgentError,
AgentCompileError,
AgentInstallError,
} from '../DimensionError';
import { Tournament } from '../Tournament';
import EngineOptions = MatchEngine.EngineOptions;
import COMMAND_STREAM_TYPE = MatchEngine.COMMAND_STREAM_TYPE;
import Command = MatchEngine.Command;
import { ChildProcess } from 'child_process';
import { NanoID, Dimension } from '../Dimension';
import { genID } from '../utils';
import { deepCopy } from '../utils/DeepCopy';
import path from 'path';
import extract from 'extract-zip';
import { removeDirectory, removeFile } from '../utils/System';
import { BOT_DIR } from '../Station';
import { mkdirSync, existsSync, statSync } from 'fs';
/**
* An match created using a {@link Design} and a list of Agents. The match can be stopped and resumed with
* {@link stop}, {@link resume}, and state and configurations can be retrieved at any point in time with the
* {@link state} and {@link configs} fields
*
* @see {@link Design} for Design information
* @see {@link Agent} for Agent information
*/
export class Match {
/**
* When the match was created (called with new)
*/
public creationDate: Date;
/**
* When the match finished
*/
public finishDate: Date;
/**
* Name of the match
*/
public name: string;
/**
* Match ID. It's always a 12 character NanoID
*/
public id: NanoID;
/**
* The state field. This can be used to store anything by the user when this `match` is passed to the {@link Design}
* life cycle functions {@link Design.initialize}, {@link Design.update}, and {@link Design.getResults}
*
* This is also used by the {@link CustomDesign} class to store all standard outputted match output for
* matches running using a custom design and passing in {@link Design.OverrideOptions}.
*/
public state: any;
/**
* List of the agents currently involved in the match.
* @See {@link Agent} for details on the agents.
*/
public agents: Array<Agent> = [];
/**
* Map from an {@link Agent.ID} ID to the {@link Agent}
*/
public idToAgentsMap: Map<Agent.ID, Agent> = new Map();
/**
* The current time step of the Match. This time step is independent of any {@link Design} and agents are coordianted
* against this timeStep
*/
public timeStep = 0;
/**
* The associated {@link MatchEngine} that is running this match and serves as the backend for this match.
*/
public matchEngine: MatchEngine;
/**
* The match logger.
* @see {@link Logger} for details on how to use this
*/
public log = new Logger();
/**
* The results field meant to store any results retrieved with {@link Design.getResults}
* @default `null`
*/
public results: any = null;
/**
* The current match status
*/
public matchStatus: Match.Status = Match.Status.UNINITIALIZED;
/**
* A mapping from {@link Agent} IDs to the tournament id of the {@link Player} in a tournament that generated the
* {@link Agent}
*/
public mapAgentIDtoTournamentID: Map<Agent.ID, Tournament.ID> = new Map();
/**
* Match Configurations. See {@link Match.Configs} for configuration options
*/
public configs: Match.Configs = {
name: '',
loggingLevel: Logger.LEVEL.INFO,
engineOptions: {},
secureMode: false,
agentOptions: deepCopy(Agent.OptionDefaults),
languageSpecificAgentOptions: {},
storeReplay: true,
storeReplayDirectory: 'replays',
storeErrorLogs: true,
storeErrorDirectory: 'errorlogs',
agentSpecificOptions: [],
storeMatchErrorLogs: false,
detached: false,
};
/** Match process used to store the process governing a match running on a custom design */
matchProcess: ChildProcess;
/** The timer set for the match process */
matchProcessTimer: any;
/** Signal to stop at next time step */
private shouldStop = false;
/** Promise for resuming */
private resumePromise: Promise<void>;
/** Resolver for the above promise */
private resumeResolve: Function;
/** Resolver for stop Promise */
private resolveStopPromise: Function;
/** Rejecter for the run promise */
private runReject: Function;
/**
* Path to the replay file for this match
*/
public replayFile: string;
/**
* Key used to retrieve the replay file from a storage plugin
*/
public replayFileKey: string;
/**
* Non local files that should be removed as they are stored somewhere else. Typically bot files are non local if
* using a backing storage service
*/
private nonLocalFiles: Array<string> = [];
/**
* Match Constructor
* @param design - The {@link Design} used
* @param agents - List of agents used to create Match.
* @param configs - Configurations that are passed to every run through {@link Design.initialize}, {@link Design.update}, and {@link Design.getResults} functioon in the
* given {@link Design}
*/
constructor(
public design: Design,
/**
* agent meta data regarding files, ids, etc.
*/
public agentFiles: /** array of file paths to agents */
Agent.GenerationMetaData,
configs: DeepPartial<Match.Configs> = {},
private dimension: Dimension
) {
// override configs with provided configs argument
this.configs = deepMerge(deepCopy(this.configs), deepCopy(configs));
// agent runs in securemode if parent match is in securemode
this.configs.agentOptions.secureMode = this.configs.secureMode;
// agent logging level is inherited from parent match.
this.configs.agentOptions.loggingLevel = this.configs.loggingLevel;
this.id = Match.genMatchID();
this.creationDate = new Date();
if (this.configs.name) {
this.name = this.configs.name;
} else {
this.name = `match_${this.id}`;
}
// set logging level to what was given
this.log.level = this.configs.loggingLevel;
this.log.identifier = this.name;
// store reference to the matchEngine used and override any options
this.matchEngine = new MatchEngine(this.design, this.log.level);
this.matchEngine.setEngineOptions(configs.engineOptions);
}
/**
* Initializes this match using its configurations and using the {@link Design.initialize} function. This can
* throw error with agent generation, design initialization, or with engine initialization. In engine initialization,
* errors that can be thrown can be {@link AgentCompileError | AgentCompileErrors},
* {@link AgentInstallError | AgentInstallErrors}, etc.
*
*
* @returns a promise that resolves true if initialized correctly
*/
public async initialize(): Promise<boolean> {
try {
this.log.infobar();
this.log.info(
`Design: ${this.design.name} | Initializing match - ID: ${this.id}, Name: ${this.name}`
);
const overrideOptions = this.design.getDesignOptions().override;
this.log.detail('Match Configs', this.configs);
this.timeStep = 0;
if (this.configs.storeErrorLogs) {
// create error log folder if it does not exist
if (!existsSync(this.configs.storeErrorDirectory)) {
mkdirSync(this.configs.storeErrorDirectory);
}
const matchErrorLogDirectory = this.getMatchErrorLogDirectory();
if (!existsSync(matchErrorLogDirectory)) {
mkdirSync(matchErrorLogDirectory);
}
}
// this allows engine to be reused after it ran once
this.matchEngine.killOffSignal = false;
// copy over any agent bot files if dimension has a backing storage service and the agent has botkey specified
// copy them over the agent's specified file location to use
const retrieveBotFilePromises: Array<Promise<any>> = [];
const retrieveBotFileIndexes: Array<number> = [];
if (this.dimension.hasStorage()) {
this.agentFiles.forEach((agentFile, index) => {
if (agentFile.botkey && agentFile.file) {
let useCachedBotFile = false;
if (
this.configs.agentSpecificOptions[index] &&
this.configs.agentSpecificOptions[index].useCachedBotFile
) {
useCachedBotFile = true;
}
retrieveBotFilePromises.push(
this.retrieveBot(
agentFile.botkey,
agentFile.file,
useCachedBotFile
)
);
retrieveBotFileIndexes.push(index);
}
});
}
const retrievedBotFiles = await Promise.all(retrieveBotFilePromises);
retrieveBotFileIndexes.forEach((val, index) => {
if (!(typeof this.agentFiles[val] === 'string')) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this.agentFiles[val].file = retrievedBotFiles[index];
// push them as non local files so they can be removed when match is done
this.nonLocalFiles.push(path.dirname(retrievedBotFiles[index]));
}
});
// Initialize agents with agent files
this.agents = Agent.generateAgents(
this.agentFiles,
this.configs.agentOptions,
this.configs.languageSpecificAgentOptions
);
this.agents.forEach((agent) => {
this.idToAgentsMap.set(agent.id, agent);
if (agent.tournamentID !== null) {
this.mapAgentIDtoTournamentID.set(agent.id, agent.tournamentID);
}
});
// use the matchengine to initialize agents if not in detached mode
if (!this.configs.detached) {
// if overriding with custom design, log some other info and use a different engine initialization function
if (overrideOptions.active) {
this.log.detail('Match Arguments', overrideOptions.arguments);
await this.matchEngine.initializeCustom();
} else {
// Initialize the matchEngine and get it ready to run and process I/O for agents
await this.matchEngine.initialize(this.agents, this);
}
}
// by now all agents should up and running, all compiled and ready
// Initialize match according to `design` by delegating intialization task to the enforced `design`
await this.design.initialize(this);
// remove initialized status and set as READY
this.matchStatus = Match.Status.READY;
return true;
} catch (err) {
await this.handleLogFiles();
// kill processes and clean up and then throw the error
await this.killAndCleanUp();
if (err instanceof AgentError) {
if (
err instanceof AgentCompileError ||
err instanceof AgentInstallError
) {
// mark agents with compile or install error as having crashed
// console.log(err, err.agentID);
this.agents[err.agentID].status = Agent.Status.CRASHED;
}
}
throw err;
}
}
/**
* Retrieves a bot through its key and downloads it to a random generated folder. Returns the new file's path
* @param botkey
* @param file
* @param useCached - if true, storage plugin will avoid redownloading data. If false, storage plugin will always
* redownload data
*/
private async retrieveBot(botkey: string, file: string, useCached: boolean) {
const dir = BOT_DIR + '/anon-' + genID(18);
mkdirSync(dir);
const zipFile = path.join(dir, 'bot.zip');
// if useCached is true, actualZipFileLocation will likely be different than zipFile, and we directly re-extract
// the bot from that zip file. It can be argued that it would be better to cache the unzipped bot instead but this
// could potentially be a security concern by repeatedly copying over unzipped bot files instead of the submitted
// zip file; and zip is smaller to cache
const actualZipFileLocation = await this.dimension.storagePlugin.download(
botkey,
zipFile,
useCached
);
await extract(actualZipFileLocation, {
dir: dir,
});
return path.join(dir, path.basename(file));
}
/**
* Runs this match to completion. Sets this.results to match results and resolves with the match results when done
*/
public run(): Promise<any> {
// returning new promise explicitly here because we need to store reject
// eslint-disable-next-line no-async-promise-executor
return new Promise(async (resolve, reject) => {
try {
this.runReject = reject;
let status: Match.Status;
this.matchStatus = Match.Status.RUNNING;
// check if our design is a javascript/typescript based design or custom and to be executed with a
// provided command
const overrideOptions = this.design.getDesignOptions().override;
if (overrideOptions.active) {
this.log.system('Running custom');
await this.matchEngine.runCustom(this);
this.results = await this.getResults();
// process results with result handler if necessary
if (overrideOptions.resultHandler) {
this.results = overrideOptions.resultHandler(this.results);
}
} else {
// otherwise run the match using the design with calls to this.next()
do {
status = await this.next();
} while (status != Match.Status.FINISHED);
this.agents.forEach((agent: Agent) => {
agent._clearTimer();
});
this.results = await this.getResults();
}
// kill processes and clean up
await this.killAndCleanUp();
// upload replayfile if given and using storage plugin
if (this.results.replayFile) {
// verify file exists and its a file
if (existsSync(this.results.replayFile)) {
if (!statSync(this.results.replayFile).isDirectory()) {
if (this.configs.storeReplay) {
this.replayFile = this.results.replayFile;
if (this.dimension.hasStorage()) {
const fileName = path.basename(this.results.replayFile);
// store to storage and get key
const key = await this.dimension.storagePlugin.upload(
this.results.replayFile,
`${path.join(this.configs.storeReplayDirectory, fileName)}`
);
this.replayFileKey = key;
// once uploaded and meta data stored, remove old file
removeFile(this.replayFile);
}
} else {
removeFile(this.results.replayFile);
}
} else {
reject(
new MatchReplayFileError(
`Replay file provided ${this.results.replayFile} is not a file`
)
);
}
} else {
reject(
new MatchReplayFileError(
`Replay file provided ${this.results.replayFile} does not exist`
)
);
}
}
await this.handleLogFiles();
this.finishDate = new Date();
resolve(this.results);
} catch (error) {
reject(error);
}
});
}
/**
* Handles log files and stores / uploads / deletes them as necessary
*/
private async handleLogFiles() {
const uploadLogPromises: Array<Promise<{
key: string;
agentID: number;
}>> = [];
const fileLogsToRemove: Array<string> = [];
// upload error logs if stored
if (this.configs.storeErrorLogs) {
// upload each agent error log
for (const agent of this.agents) {
const filepath = path.join(
this.getMatchErrorLogDirectory(),
agent.getAgentErrorLogFilename()
);
if (existsSync(filepath)) {
// check if replay file is empty
if (agent._logsize === 0) {
fileLogsToRemove.push(filepath);
} else if (this.dimension.hasStorage()) {
const uploadKeyPromise = this.dimension.storagePlugin
.upload(filepath, filepath)
.then((key) => {
return { key: key, agentID: agent.id };
});
uploadLogPromises.push(uploadKeyPromise);
fileLogsToRemove.push(filepath);
}
} else {
// this shouldn't happen
this.log.error(
`Agent ${this.id} log file at ${filepath} does not exist`
);
}
}
}
const logkeys = await Promise.all(uploadLogPromises);
logkeys.forEach((val) => {
this.idToAgentsMap.get(val.agentID).logkey = val.key;
});
if (fileLogsToRemove.length === this.agents.length) {
removeDirectory(this.getMatchErrorLogDirectory());
} else {
fileLogsToRemove.forEach((logPath) => {
removeFile(logPath);
});
}
}
/**
* Step forward the match by one timestep by sending commands individually.
*/
public async step(commands: Array<Command>): Promise<Match.Status> {
const engineOptions = this.matchEngine.getEngineOptions();
if (engineOptions.commandStreamType === COMMAND_STREAM_TYPE.SEQUENTIAL) {
const status =
(await this.design.update(this, commands)) ?? Match.Status.RUNNING;
return status;
} else {
throw new NotSupportedError('Only sequential streaming is allowed');
}
}
/**
* Next function. Moves match forward by one timestep. Resolves with the match status
* This function should always used to advance forward a match unless a custom design is provided
*
* Gathers commands from agents via the {@link MatchEngine}
*
* Should not be called by user
*/
public async next(): Promise<Match.Status> {
const engineOptions = this.matchEngine.getEngineOptions();
if (engineOptions.commandStreamType === COMMAND_STREAM_TYPE.SEQUENTIAL) {
// if this.shouldStop is set to true, await for the resume promise to resolve
if (this.shouldStop == true) {
// set status and stop the engine
this.matchStatus = Match.Status.STOPPED;
this.matchEngine.stop(this);
this.log.info('Stopped match');
this.resolveStopPromise();
await this.resumePromise;
this.matchEngine.resume(this);
this.log.info('Resumed match');
this.shouldStop = false;
}
// we reset each Agent for the next move
this.agents.forEach((agent: Agent) => {
// continue agents again
agent.resume();
// setup the agent and its promises and get it ready for the next move
agent._setupMove();
// if timeout is set active and agent not already terminated
if (engineOptions.timeout.active && !agent.isTerminated()) {
agent._setTimeout(() => {
// if agent times out, emit the timeout event
agent.timeout();
}, engineOptions.timeout.max + MatchEngine.timeoutBuffer);
}
// each of these steps can take ~2 ms
});
// after agebts are reset, we are ready to receive commands from them
// Updates sent by agents on previous timestep can be obtained with MatchEngine.getCommands
// This is also the COORDINATION step, where we essentially wait for all commands from all agents to be
// delivered out or until one of them fails
const commands: Array<Command> = await this.matchEngine.getCommands(this);
this.log.system(`Retrieved ${commands.length} commands`);
// Updates the match state and sends appropriate signals to all Agents based on the stored `Design`
const status: Match.Status = await this.design.update(this, commands);
// default status is running if no status returned
if (!status) {
this.matchStatus = Match.Status.RUNNING;
} else {
this.matchStatus = status;
}
// update timestep now
this.timeStep += 1;
return status;
}
// TODO: implement this
else if (engineOptions.commandStreamType === COMMAND_STREAM_TYPE.PARALLEL) {
// with a parallel structure, the `Design` updates the match after each command sequence, delimited by \n
// this means agents end up sending commands using out of sync state information, so the `Design` would need to
// adhere to this. Possibilities include stateless designs, or heavily localized designs where out of
// sync states wouldn't matter much
throw new NotSupportedError(
'PARALLEL command streaming has not been implemented yet'
);
}
}
/**
* Stops the match. For non-custom designs, stops at the next nearest timestep possible. Otherwise attempts to stop
* the match using the {@link MatchEngine} stopCustom function.
*
* Notes:
* - If design uses a PARALLEL match engine, stopping behavior can be a little unpredictable
* - If design uses a SEQUENTIAL match engine, a stop will result in ensuring all agents complete all their actions up
* to a coordinated stopping `timeStep`
*/
public stop(): Promise<void> {
return new Promise((resolve, reject) => {
if (this.matchStatus != Match.Status.RUNNING) {
this.log.warn("You can't stop a match that is not running");
reject(new MatchWarn('You can\t stop a match that is not running'));
return;
}
// if override is on, we stop using the matchEngine stop function
if (this.design.getDesignOptions().override.active) {
this.matchEngine
.stopCustom(this)
.then(() => {
this.matchStatus = Match.Status.STOPPED;
resolve();
})
.catch(reject);
return;
} else {
this.resolveStopPromise = resolve;
this.log.info('Stopping match...');
this.resumePromise = new Promise((resolve) => {
this.resumeResolve = resolve;
});
this.shouldStop = true;
}
});
}
/**
* Resume the match if it was in the stopped state
* @returns true if succesfully resumed
*/
public resume(): Promise<void> {
return new Promise((resolve, reject) => {
if (this.matchStatus != Match.Status.STOPPED) {
this.log.warn("You can't resume a match that is not stopped");
reject(new MatchWarn("You can't resume a match that is not stopped"));
return;
}
this.log.info('Resuming match...');
// if override is on, we resume using the matchEngine resume function
if (this.design.getDesignOptions().override.active) {
this.matchEngine
.resumeCustom(this)
.then(() => {
this.matchStatus = Match.Status.RUNNING;
resolve();
})
.catch(reject);
} else {
// set back to running and resolve
this.matchStatus = Match.Status.RUNNING;
this.resumeResolve();
resolve();
}
});
}
/**
* Stop all agents through the match engine and clean up any other files and processes
*
* Used by custom and dimensions based designs
*/
private async killAndCleanUp() {
await this.matchEngine.killAndClean(this);
const removeNonLocalFilesPromises: Array<Promise<any>> = [];
this.nonLocalFiles.forEach((nonLocalFile) => {
removeNonLocalFilesPromises.push(removeDirectory(nonLocalFile));
});
await Promise.all(removeNonLocalFilesPromises);
}
/**
* Terminate an {@link Agent}, kill the process. Note, the agent is still stored in the Match, but you can't send or
* receive messages from it anymore
*
* @param agent - id of agent or the Agent object to kill
* @param reason - an optional reason string to provide for logging purposes
*/
public async kill(agent: Agent.ID | Agent, reason?: string): Promise<void> {
if (agent instanceof Agent) {
this.matchEngine.kill(agent, reason);
} else {
this.matchEngine.kill(this.idToAgentsMap.get(agent), reason);
}
}
/**
* Retrieve results through delegating the task to {@link Design.getResults}
*/
public async getResults(): Promise<any> {
// Retrieve match results according to `design` by delegating storeResult task to the enforced `design`
return await this.design.getResults(this);
}
/**
* Sends a message to the standard input of all agents in this match
* @param message - the message to send to all agents available
* @returns a promise resolving true/false if it was succesfully sent
*/
public sendAll(message: string): Promise<boolean> {
return new Promise((resolve) => {
const sendPromises: Array<Promise<boolean>> = [];
this.agents.forEach((agent: Agent) => {
sendPromises.push(this.send(message, agent));
});
Promise.all(sendPromises).then((sendStatus) => {
// if all promises resolve, we sent all messages
resolve(sendStatus.every((v) => v === true));
});
});
}
/**
* Functional method for sending a message string to a particular {@link Agent}. Returns a promise that resolves true
* if succesfully sent. Returns false if could not send message, meaning agent was also killed.
* @param message - the string message to send
* @param receiver - receiver of message can be specified by the {@link Agent} or it's {@link Agent.ID} (a number)
*/
public async send(
message: string,
receiver: Agent | Agent.ID
): Promise<boolean> {
if (receiver instanceof Agent) {
try {
await this.matchEngine.send(this, message, receiver.id);
} catch (err) {
this.log.error(err);
await this.kill(receiver, 'could not send message anymore');
return false;
}
} else {
try {
await this.matchEngine.send(this, message, receiver);
} catch (err) {
this.log.error(err);
await this.kill(receiver, 'could not send message anymore');
return false;
}
}
return true;
}
/**
* Throw an {@link FatalError}, {@link MatchError}, or {@link MatchWarn} within the Match. Indicates that the
* {@link Agent} with id agentID caused this error/warning.
*
* Throwing MatchWarn will just log a warning level message and throwing a MatchError will just log it as an error
* level message.
*
* Throwing FatalError will cause the match to automatically be destroyed. This is highly not recommended and it is
* suggested to have some internal logic to handle moments when the match cannot continue.
*
*
* Examples are misuse of an existing command or using incorrect commands or sending too many commands
* @param agentID - the misbehaving agent's ID
* @param error - The error
*/
public async throw(agentID: Agent.ID, error: Error): Promise<void> {
// Fatal errors are logged and should end the whole match
const agent = this.idToAgentsMap.get(agentID);
if (error instanceof FatalError) {
await this.destroy();
const msg = `FatalError: ${agent.name} | ${error.message}`;
this.log.error(msg);
if (this.configs.storeMatchErrorLogs) agent.writeToErrorLog(msg);
} else if (error instanceof MatchWarn) {
const msg = `ID: ${agentID}, ${this.idToAgentsMap.get(agentID).name} | ${
error.message
}`;
this.log.warn(msg);
if (this.configs.storeMatchErrorLogs) agent.writeToErrorLog(msg);
} else if (error instanceof MatchError) {
const msg = `ID: ${agentID}, ${this.idToAgentsMap.get(agentID).name} | ${
error.message
}`;
this.log.error(msg);
if (this.configs.storeMatchErrorLogs) agent.writeToErrorLog(msg);
} else {
this.log.error(
'User tried throwing an error of type other than FatalError, MatchWarn, or MatchError'
);
}
}
/**
* Destroys this match and makes sure to remove any leftover processes
*/
public async destroy(): Promise<void> {
// reject the run promise first if it exists
if (this.runReject)
this.runReject(new MatchDestroyedError('Match was destroyed'));
// now actually stop and clean up
await this.killAndCleanUp(); // Theoretically this line is not needed for custom matches, but in here in case
await this.matchEngine.killAndCleanCustom(this);
}
/**
* Generates a 12 character nanoID string for identifying matches
*/
public static genMatchID(): string {
return genID(12);
}
public getMatchErrorLogDirectory(): string {
return path.join(this.configs.storeErrorDirectory, `match_${this.id}`);
}
}
export namespace Match {
/**
* Match Configurations. Has 5 specified fields. All other fields are up to user discretion
*/
export interface Configs {
/**
* Name of the match
*/
name: string;
/**
* Logging level for this match.
* @see {@link Logger}
*/
loggingLevel: Logger.LEVEL;
/**
* The engine options to use in this match.
*/
engineOptions: DeepPartial<EngineOptions>;
/**
* Whether to run match in secure mode or not
* @default true
*/
secureMode: boolean;
/**
* Default Agent options to use for all agents in a match. Commonly used for setting resource use boundaries
*/
agentOptions: DeepPartial<Agent.Options>;
/**
* Agent options to override with depending on extension of file
* @default `{}` - an empty object
*/
languageSpecificAgentOptions: Agent.LanguageSpecificOptions;
/**
* Agent options to lastly overridde with depending on agent index
* @default `[]` - empty array meaning no more overrides
*/
agentSpecificOptions: Array<DeepPartial<Agent.Options>>;
/**
* Whether or not to store a replay file if match results indicate a replay file was stored
*
* @default `true`
*/
storeReplay: boolean;
/**
* Used only when a {@link Storage} plugin is used. Indicates the directory to use to store onto the storage.
* (Typically some path in the bucket).
*
* @default `replays`
*/
storeReplayDirectory: string;
/**
* Whether to store error output for each {@link Match}
*
* @default true
*/
storeErrorLogs: boolean;
/**
* Whether to store error and warnings outputted by match from calling match.throw
*
* @default false
*/
storeMatchErrorLogs: boolean;
/**
* Directory to store error logs locally. When a {@link Storage} plugin is used, this indicates the path in the
* bucket to store the log in, and removes the local copy.
*
* @default `errorlogs`
*/
storeErrorDirectory: string;
/**
* Whether to run in detached mode. When in detached mode (true), the match can initialize within dimensions using the {@link Design} but will now
* instead update step by step
*
* @default `false`
*/
detached: boolean;
[key: string]: any;
}
export enum Status {
/** Match was created with new but initialize was not called */
UNINITIALIZED = 'uninitialized',
/**
* If the match has been initialized and checks have been passed, the match is ready to run using {@link Match.run}
*/
READY = 'ready',
/**
* If the match is running at the moment
*/
RUNNING = 'running',
/**
* If the match is stopped
*/
STOPPED = 'stopped',
/**
* If the match is completed
*/
FINISHED = 'finished',
/**
* If fatal error occurs in Match, appears when match stops itself
*/
ERROR = 'error',
}
} | the_stack |
import { join } from 'path';
import {
readVersionOfDependencies,
scanSrcTsFiles,
validateRequiredFilesExist,
validateTsConfigSettings
} from './build/util';
import { bundle, bundleUpdate } from './bundle';
import { clean } from './clean';
import { copy } from './copy';
import { deepLinking, deepLinkingUpdate } from './deep-linking';
import { lint, lintUpdate } from './lint';
import { Logger } from './logger/logger';
import { minifyCss, minifyJs } from './minify';
import { ngc } from './ngc';
import { getTsConfigAsync, TsConfig } from './transpile';
import { postprocess } from './postprocess';
import { preprocess, preprocessUpdate } from './preprocess';
import { sass, sassUpdate } from './sass';
import { templateUpdate } from './template';
import { transpile, transpileUpdate, transpileDiagnosticsOnly } from './transpile';
import * as Constants from './util/constants';
import { BuildError } from './util/errors';
import { emit, EventType } from './util/events';
import { getBooleanPropertyValue, readFileAsync, setContext } from './util/helpers';
import { BuildContext, BuildState, BuildUpdateMessage, ChangedFile } from './util/interfaces';
export function build(context: BuildContext) {
setContext(context);
const logger = new Logger(`build ${(context.isProd ? 'prod' : 'dev')}`);
return buildWorker(context)
.then(() => {
// congrats, we did it! (•_•) / ( •_•)>⌐■-■ / (⌐■_■)
logger.finish();
})
.catch(err => {
if (err.isFatal) { throw err; }
throw logger.fail(err);
});
}
async function buildWorker(context: BuildContext) {
const promises: Promise<any>[] = [];
promises.push(validateRequiredFilesExist(context));
promises.push(readVersionOfDependencies(context));
const results = await Promise.all(promises);
const tsConfigContents = results[0][1];
await validateTsConfigSettings(tsConfigContents);
await buildProject(context);
}
function buildProject(context: BuildContext) {
// sync empty the www/build directory
clean(context);
buildId++;
const copyPromise = copy(context);
return scanSrcTsFiles(context)
.then(() => {
if (getBooleanPropertyValue(Constants.ENV_PARSE_DEEPLINKS)) {
return deepLinking(context);
}
})
.then(() => {
const compilePromise = (context.runAot) ? ngc(context) : transpile(context);
return compilePromise;
})
.then(() => {
return preprocess(context);
})
.then(() => {
return bundle(context);
})
.then(() => {
const minPromise = (context.runMinifyJs) ? minifyJs(context) : Promise.resolve();
const sassPromise = sass(context)
.then(() => {
return (context.runMinifyCss) ? minifyCss(context) : Promise.resolve();
});
return Promise.all([
minPromise,
sassPromise,
copyPromise
]);
})
.then(() => {
return postprocess(context);
})
.then(() => {
if (getBooleanPropertyValue(Constants.ENV_ENABLE_LINT)) {
// kick off the tslint after everything else
// nothing needs to wait on its completion unless bailing on lint error is enabled
const result = lint(context, null, false);
if (getBooleanPropertyValue(Constants.ENV_BAIL_ON_LINT_ERROR)) {
return result;
}
}
})
.catch(err => {
throw new BuildError(err);
});
}
export function buildUpdate(changedFiles: ChangedFile[], context: BuildContext) {
return new Promise(resolve => {
const logger = new Logger('build');
buildId++;
const buildUpdateMsg: BuildUpdateMessage = {
buildId: buildId,
reloadApp: false
};
emit(EventType.BuildUpdateStarted, buildUpdateMsg);
function buildTasksDone(resolveValue: BuildTaskResolveValue) {
// all build tasks have been resolved or one of them
// bailed early, stopping all others to not run
parallelTasksPromise.then(() => {
// all parallel tasks are also done
// so now we're done done
const buildUpdateMsg: BuildUpdateMessage = {
buildId: buildId,
reloadApp: resolveValue.requiresAppReload
};
emit(EventType.BuildUpdateCompleted, buildUpdateMsg);
if (!resolveValue.requiresAppReload) {
// just emit that only a certain file changed
// this one is useful when only a sass changed happened
// and the webpack only needs to livereload the css
// but does not need to do a full page refresh
emit(EventType.FileChange, resolveValue.changedFiles);
}
let requiresLintUpdate = false;
for (const changedFile of changedFiles) {
if (changedFile.ext === '.ts') {
if (changedFile.event === 'change' || changedFile.event === 'add') {
requiresLintUpdate = true;
break;
}
}
}
if (requiresLintUpdate) {
// a ts file changed, so let's lint it too, however
// this task should run as an after thought
if (getBooleanPropertyValue(Constants.ENV_ENABLE_LINT)) {
lintUpdate(changedFiles, context, false);
}
}
logger.finish('green', true);
Logger.newLine();
// we did it!
resolve();
});
}
// kick off all the build tasks
// and the tasks that can run parallel to all the build tasks
const buildTasksPromise = buildUpdateTasks(changedFiles, context);
const parallelTasksPromise = buildUpdateParallelTasks(changedFiles, context);
// whether it was resolved or rejected, we need to do the same thing
buildTasksPromise
.then(buildTasksDone)
.catch(() => {
buildTasksDone({
requiresAppReload: false,
changedFiles: changedFiles
});
});
});
}
/**
* Collection of all the build tasks than need to run
* Each task will only run if it's set with eacn BuildState.
*/
function buildUpdateTasks(changedFiles: ChangedFile[], context: BuildContext) {
const resolveValue: BuildTaskResolveValue = {
requiresAppReload: false,
changedFiles: []
};
return loadFiles(changedFiles, context)
.then(() => {
// DEEP LINKING
if (getBooleanPropertyValue(Constants.ENV_PARSE_DEEPLINKS)) {
return deepLinkingUpdate(changedFiles, context);
}
})
.then(() => {
// TEMPLATE
if (context.templateState === BuildState.RequiresUpdate) {
resolveValue.requiresAppReload = true;
return templateUpdate(changedFiles, context);
}
// no template updates required
return Promise.resolve();
})
.then(() => {
// TRANSPILE
if (context.transpileState === BuildState.RequiresUpdate) {
resolveValue.requiresAppReload = true;
// we've already had a successful transpile once, only do an update
// not that we've also already started a transpile diagnostics only
// build that only needs to be completed by the end of buildUpdate
return transpileUpdate(changedFiles, context);
} else if (context.transpileState === BuildState.RequiresBuild) {
// run the whole transpile
resolveValue.requiresAppReload = true;
return transpile(context);
}
// no transpiling required
return Promise.resolve();
})
.then(() => {
// PREPROCESS
return preprocessUpdate(changedFiles, context);
})
.then(() => {
// BUNDLE
if (context.bundleState === BuildState.RequiresUpdate) {
// we need to do a bundle update
resolveValue.requiresAppReload = true;
return bundleUpdate(changedFiles, context);
} else if (context.bundleState === BuildState.RequiresBuild) {
// we need to do a full bundle build
resolveValue.requiresAppReload = true;
return bundle(context);
}
// no bundling required
return Promise.resolve();
})
.then(() => {
// SASS
if (context.sassState === BuildState.RequiresUpdate) {
// we need to do a sass update
return sassUpdate(changedFiles, context).then(outputCssFile => {
const changedFile: ChangedFile = {
event: Constants.FILE_CHANGE_EVENT,
ext: '.css',
filePath: outputCssFile
};
context.fileCache.set(outputCssFile, { path: outputCssFile, content: outputCssFile });
resolveValue.changedFiles.push(changedFile);
});
} else if (context.sassState === BuildState.RequiresBuild) {
// we need to do a full sass build
return sass(context).then(outputCssFile => {
const changedFile: ChangedFile = {
event: Constants.FILE_CHANGE_EVENT,
ext: '.css',
filePath: outputCssFile
};
context.fileCache.set(outputCssFile, { path: outputCssFile, content: outputCssFile });
resolveValue.changedFiles.push(changedFile);
});
}
// no sass build required
return Promise.resolve();
})
.then(() => {
return resolveValue;
});
}
function loadFiles(changedFiles: ChangedFile[], context: BuildContext) {
// UPDATE IN-MEMORY FILE CACHE
let promises: Promise<any>[] = [];
for (const changedFile of changedFiles) {
if (changedFile.event === Constants.FILE_DELETE_EVENT) {
// remove from the cache on delete
context.fileCache.remove(changedFile.filePath);
} else {
// load the latest since the file changed
const promise = readFileAsync(changedFile.filePath);
promises.push(promise);
promise.then((content: string) => {
context.fileCache.set(changedFile.filePath, { path: changedFile.filePath, content: content });
});
}
}
return Promise.all(promises);
}
interface BuildTaskResolveValue {
requiresAppReload: boolean;
changedFiles: ChangedFile[];
}
/**
* parallelTasks are for any tasks that can run parallel to the entire
* build, but we still need to make sure they've completed before we're
* all done, it's also possible there are no parallelTasks at all
*/
function buildUpdateParallelTasks(changedFiles: ChangedFile[], context: BuildContext) {
const parallelTasks: Promise<any>[] = [];
if (context.transpileState === BuildState.RequiresUpdate) {
parallelTasks.push(transpileDiagnosticsOnly(context));
}
return Promise.all(parallelTasks);
}
let buildId = 0; | the_stack |
import { EventEmitter } from "events";
import { assert } from "node-opcua-assert";
import { BinaryStream } from "node-opcua-binary-stream";
import { createFastUninitializedBuffer } from "node-opcua-buffer-utils";
import { readMessageHeader } from "./read_message_header";
export function verify_message_chunk(messageChunk: Buffer): void {
assert(messageChunk);
assert(messageChunk instanceof Buffer);
const header = readMessageHeader(new BinaryStream(messageChunk));
if (messageChunk.length !== header.length) {
throw new Error(" chunk length = " + messageChunk.length + " message length " + header.length);
}
}
// see https://github.com/substack/_buffer-handbook
// http://blog.nodejs.org/2012/12/20/streams2/
// http://codewinds.com/blog/2013-08-20-nodejs-transform-streams.html
// +----------------+----
// | message header | ^
// +----------------+ |<- data to sign
// | security header| |
// +----------------+ | ---
// | Sequence header| | ^
// +----------------+ | |<- data to encrypt
// | BODY | | |
// +----------------+ | |
// | padding | v |
// +----------------+--- |
// | Signature | v
// +----------------+------
//
// chunkSize = 8192
// plainBlockSize = 256-11
// cipherBlockSize = 256
// headerSize = messageHeaderSize + securityHeaderSize
// maxBodySize = plainBlockSize*floor((chunkSize–headerSize–signatureLength-1)/cipherBlockSize)-sequenceHeaderSize;
// length(data to encrypt) = n *
// Rules:
// - The SequenceHeaderSize is always 8 bytes
// - The HeaderSize includes the MessageHeader and the SecurityHeader.
// - The PaddingSize and Padding fields are not present if the MessageChunk is not encrypted.
// - The Signature field is not present if the MessageChunk is not signed.
export type WriteHeaderFunc = (chunk: Buffer, isLast: boolean, expectedLength: number) => void;
export type WriteSequenceHeaderFunc = (chunk: Buffer) => void;
export type SignBufferFunc = (buffer: Buffer) => Buffer;
export type EncryptBufferFunc = (buffer: Buffer) => Buffer;
export interface IChunkManagerOptions {
chunkSize: number;
signatureLength: number;
sequenceHeaderSize: number;
cipherBlockSize: number;
plainBlockSize: number;
signBufferFunc?: SignBufferFunc;
encryptBufferFunc?: EncryptBufferFunc;
writeSequenceHeaderFunc?: WriteSequenceHeaderFunc;
headerSize: number;
writeHeaderFunc?: WriteHeaderFunc; // write header must be specified if headerSize !=0
}
export class ChunkManager extends EventEmitter {
public signBufferFunc?: SignBufferFunc;
public encryptBufferFunc?: EncryptBufferFunc;
public writeSequenceHeaderFunc?: WriteSequenceHeaderFunc;
public writeHeaderFunc?: WriteHeaderFunc;
private readonly chunkSize: number;
private readonly headerSize: number;
private readonly signatureLength: number;
private readonly sequenceHeaderSize: number;
private readonly cipherBlockSize: number;
private readonly plainBlockSize: number;
// --------------
private readonly maxBodySize: number;
private readonly maxBlock?: number;
private readonly dataOffset: number;
private chunk: Buffer | null;
private cursor: number;
private pendingChunk: Buffer | null;
private dataEnd: number;
constructor(options: IChunkManagerOptions) {
super();
// { chunkSize : 32, headerSize : 10 ,signatureLength: 32 }
this.chunkSize = options.chunkSize;
this.headerSize = options.headerSize || 0;
if (this.headerSize) {
this.writeHeaderFunc = options.writeHeaderFunc;
assert(typeof this.writeHeaderFunc === "function");
}
this.sequenceHeaderSize = options.sequenceHeaderSize === undefined ? 8 : options.sequenceHeaderSize;
if (this.sequenceHeaderSize > 0) {
this.writeSequenceHeaderFunc = options.writeSequenceHeaderFunc;
assert(typeof this.writeSequenceHeaderFunc === "function");
}
this.signatureLength = options.signatureLength || 0;
this.signBufferFunc = options.signBufferFunc;
this.plainBlockSize = options.plainBlockSize || 0; // 256-14;
this.cipherBlockSize = options.cipherBlockSize || 0; // 256;
this.dataEnd = 0;
if (this.cipherBlockSize === 0) {
assert(this.plainBlockSize === 0);
// unencrypted block
this.maxBodySize = this.chunkSize - this.headerSize - this.signatureLength - this.sequenceHeaderSize;
this.encryptBufferFunc = undefined;
} else {
assert(this.plainBlockSize !== 0);
// During encryption a block with a size equal to PlainTextBlockSize is processed to produce a block
// with size equal to CipherTextBlockSize. These values depend on the encryption algorithm and may
// be the same.
this.encryptBufferFunc = options.encryptBufferFunc;
assert(typeof this.encryptBufferFunc === "function", "an encryptBufferFunc is required");
// this is the formula proposed by OPCUA
this.maxBodySize =
this.plainBlockSize *
Math.floor((this.chunkSize - this.headerSize - this.signatureLength - 1) / this.cipherBlockSize) -
this.sequenceHeaderSize;
// this is the formula proposed by ERN
this.maxBlock = Math.floor((this.chunkSize - this.headerSize) / this.cipherBlockSize);
this.maxBodySize = this.plainBlockSize * this.maxBlock - this.sequenceHeaderSize - this.signatureLength - 1;
if (this.plainBlockSize > 256) {
this.maxBodySize -= 1;
}
}
assert(this.maxBodySize > 0); // no space left to write data
// where the data starts in the block
this.dataOffset = this.headerSize + this.sequenceHeaderSize;
this.chunk = null;
this.cursor = 0;
this.pendingChunk = null;
}
public write(buffer: Buffer, length?: number) {
length = length || buffer.length;
assert(buffer instanceof Buffer || buffer === null);
assert(length > 0);
let l = length;
let inputCursor = 0;
while (l > 0) {
assert(length - inputCursor !== 0);
if (this.cursor === 0) {
this._push_pending_chunk(false);
}
// space left in current chunk
const spaceLeft = this.maxBodySize - this.cursor;
const nbToWrite = Math.min(length - inputCursor, spaceLeft);
this.chunk = this.chunk || createFastUninitializedBuffer(this.chunkSize);
if (buffer) {
buffer.copy(this.chunk!, this.cursor + this.dataOffset, inputCursor, inputCursor + nbToWrite);
}
inputCursor += nbToWrite;
this.cursor += nbToWrite;
if (this.cursor >= this.maxBodySize) {
this._post_process_current_chunk();
}
l -= nbToWrite;
}
}
public end() {
if (this.cursor > 0) {
this._post_process_current_chunk();
}
this._push_pending_chunk(true);
}
/**
* compute the signature of the chunk and append it at the end
* of the data block.
*
* @method _write_signature
* @private
*/
private _write_signature(chunk: Buffer) {
if (this.signBufferFunc) {
assert(typeof this.signBufferFunc === "function");
assert(this.signatureLength !== 0);
const signatureStart = this.dataEnd;
const sectionToSign = chunk.slice(0, signatureStart);
const signature = this.signBufferFunc(sectionToSign);
assert(signature.length === this.signatureLength);
signature.copy(chunk, signatureStart);
} else {
assert(this.signatureLength === 0, "expecting NO SIGN");
}
}
private _encrypt(chunk: Buffer) {
if (this.plainBlockSize > 0) {
assert(this.dataEnd !== undefined);
const startEncryptionPos = this.headerSize;
const endEncryptionPos = this.dataEnd + this.signatureLength;
const areaToEncrypt = chunk.slice(startEncryptionPos, endEncryptionPos);
assert(areaToEncrypt.length % this.plainBlockSize === 0); // padding should have been applied
const nbBlock = areaToEncrypt.length / this.plainBlockSize;
const encryptedBuffer = this.encryptBufferFunc!(areaToEncrypt);
assert(encryptedBuffer.length % this.cipherBlockSize === 0);
assert(encryptedBuffer.length === nbBlock * this.cipherBlockSize);
encryptedBuffer.copy(chunk, this.headerSize, 0);
}
}
private _push_pending_chunk(isLast: boolean) {
if (this.pendingChunk) {
const expectedLength = this.pendingChunk.length;
if (this.headerSize > 0) {
// Release 1.02 39 OPC Unified Architecture, Part 6:
// The sequence header ensures that the first encrypted block of every Message sent over
// a channel will start with different data.
this.writeHeaderFunc!(this.pendingChunk.slice(0, this.headerSize), isLast, expectedLength);
}
if (this.sequenceHeaderSize > 0) {
this.writeSequenceHeaderFunc!(this.pendingChunk.slice(this.headerSize, this.headerSize + this.sequenceHeaderSize));
}
this._write_signature(this.pendingChunk);
this._encrypt(this.pendingChunk);
/**
* @event chunk
* @param chunk {Buffer}
* @param isLast {Boolean} , true if final chunk
*/
this.emit("chunk", this.pendingChunk, isLast);
this.pendingChunk = null;
}
}
private _write_padding_bytes(nbPaddingByteTotal: number) {
const nbPaddingByte = nbPaddingByteTotal % 256;
const extraNbPaddingByte = Math.floor(nbPaddingByteTotal / 256);
assert(extraNbPaddingByte === 0 || this.plainBlockSize > 256, "extraNbPaddingByte only requested when key size > 2048");
// write the padding byte
this.chunk!.writeUInt8(nbPaddingByte, this.cursor + this.dataOffset);
this.cursor += 1;
for (let i = 0; i < nbPaddingByteTotal; i++) {
this.chunk!.writeUInt8(nbPaddingByte, this.cursor + this.dataOffset + i);
}
this.cursor += nbPaddingByteTotal;
if (this.plainBlockSize > 256) {
this.chunk!.writeUInt8(extraNbPaddingByte, this.cursor + this.dataOffset);
this.cursor += 1;
}
}
private _post_process_current_chunk() {
let extraEncryptionBytes = 0;
// add padding bytes if needed
if (this.plainBlockSize > 0) {
// write padding ( if encryption )
// let's calculate curLength = the length of the block to encrypt without padding yet
// +---------------+---------------+-------------+---------+--------------+------------+
// |SequenceHeader | data | paddingByte | padding | extraPadding | signature |
// +---------------+---------------+-------------+---------+--------------+------------+
let curLength = this.sequenceHeaderSize + this.cursor + this.signatureLength;
if (this.plainBlockSize > 256) {
curLength += 2; // account for extraPadding Byte Number;
} else {
curLength += 1;
}
// let's calculate the required number of padding bytes
const n = curLength % this.plainBlockSize;
const nbPaddingByteTotal = (this.plainBlockSize - n) % this.plainBlockSize;
this._write_padding_bytes(nbPaddingByteTotal);
const adjustedLength = this.sequenceHeaderSize + this.cursor + this.signatureLength;
assert(adjustedLength % this.plainBlockSize === 0);
const nbBlock = adjustedLength / this.plainBlockSize;
extraEncryptionBytes = nbBlock * (this.cipherBlockSize - this.plainBlockSize);
}
this.dataEnd = this.dataOffset + this.cursor;
// calculate the expected length of the chunk, once encrypted if encryption apply
const expectedLength = this.dataEnd + this.signatureLength + extraEncryptionBytes;
this.pendingChunk = this.chunk!.slice(0, expectedLength);
// note :
// - this.pending_chunk has the correct size but is not signed nor encrypted yet
// as we don't know what to write in the header yet
// - as a result,
this.chunk = null;
this.cursor = 0;
}
} | the_stack |
import { Literal } from "./literal";
import { AnyStaticType, Trait, Type, TypeConstraint } from "./type";
import { Predicate } from "./logic";
import { SimulationGoal } from "./goal";
type Metadata = number;
type uint32 = number;
export enum OpTag {
DROP = 1,
LET, // meta name (value)
PUSH_VARIABLE, // meta name
PUSH_SELF, // meta
PUSH_GLOBAL, // meta
PUSH_LITERAL, // meta
PUSH_RETURN, // meta
PUSH_LIST, // meta arity (value...)
PUSH_NEW, // meta type arity (value...)
PUSH_STATIC_TYPE, // meta name
PUSH_RECORD, // meta key... (value...)
RECORD_AT_PUT, // meta (key value)
PROJECT, // meta (object key)
PROJECT_STATIC, // meta key (object)
INTERPOLATE, // meta parts (value...)
PUSH_LAZY, // meta expr
FORCE, // meta
PUSH_LAMBDA, // meta param... body
INVOKE_FOREIGN, // meta name arity (value...)
INVOKE, // meta name arity (value...)
APPLY, // meta arity (value...)
RETURN, // meta (expr)
PUSH_PARTIAL, // meta name
ASSERT, // meta tag message
BRANCH, // meta consequent alternate
TYPE_TEST, // meta type
TRAIT_TEST, // meta trait
INTRINSIC_EQUAL, // meta (left right)
REGISTER_INSTANCE, // meta (value)
SEARCH,
MATCH_SEARCH,
FACT,
FORGET,
SIMULATE,
HANDLE,
PERFORM,
CONTINUE_WITH,
DSL,
}
export enum AssertType {
PRECONDITION = 1,
POSTCONDITION,
RETURN_TYPE,
ASSERT,
UNREACHABLE,
}
export class BasicBlock {
constructor(readonly ops: Op[]) {}
}
export type Op =
| Drop
| Let
| PushVariable
| PushSelf
| PushGlobal
| PushLiteral
| PushReturn
| PushList
| PushNew
| PushStaticType
| PushRecord
| RecordAtPut
| Project
| ProjectStatic
| PushLazy
| Force
| Interpolate
| PushLambda
| InvokeForeign
| Invoke
| Apply
| Return
| PushPartial
| Assert
| Branch
| TypeTest
| TraitTest
| IntrinsicEqual
| RegisterInstance
| Search
| MatchSearch
| Fact
| Forget
| Simulate
| Handle
| Perform
| ContinueWith
| Dsl;
export abstract class BaseOp {
abstract tag: OpTag;
abstract meta: Metadata | null;
}
export class Drop extends BaseOp {
readonly tag = OpTag.DROP;
constructor(readonly meta: Metadata) {
super();
}
}
export class Let extends BaseOp {
readonly tag = OpTag.LET;
constructor(readonly meta: Metadata, readonly name: string) {
super();
}
}
export class PushVariable extends BaseOp {
readonly tag = OpTag.PUSH_VARIABLE;
constructor(readonly meta: Metadata, readonly name: string) {
super();
}
}
export class PushSelf extends BaseOp {
readonly tag = OpTag.PUSH_SELF;
constructor(readonly meta: Metadata) {
super();
}
}
export class PushGlobal extends BaseOp {
readonly tag = OpTag.PUSH_GLOBAL;
constructor(readonly meta: Metadata, readonly name: string) {
super();
}
}
export class PushLiteral extends BaseOp {
readonly tag = OpTag.PUSH_LITERAL;
readonly meta = null;
constructor(readonly value: Literal) {
super();
}
}
export class PushReturn extends BaseOp {
readonly tag = OpTag.PUSH_RETURN;
constructor(readonly meta: Metadata) {
super();
}
}
export class PushList extends BaseOp {
readonly tag = OpTag.PUSH_LIST;
constructor(readonly meta: Metadata, readonly arity: uint32) {
super();
}
}
export class PushNew extends BaseOp {
readonly tag = OpTag.PUSH_NEW;
constructor(
readonly meta: Metadata,
readonly type: Type,
readonly arity: uint32
) {
super();
}
}
export class PushStaticType extends BaseOp {
readonly tag = OpTag.PUSH_STATIC_TYPE;
constructor(readonly meta: Metadata, readonly type: AnyStaticType) {
super();
}
}
export class PushRecord extends BaseOp {
readonly tag = OpTag.PUSH_RECORD;
constructor(readonly meta: Metadata, readonly keys: string[]) {
super();
}
}
export class RecordAtPut extends BaseOp {
readonly tag = OpTag.RECORD_AT_PUT;
constructor(readonly meta: Metadata) {
super();
}
}
export class Project extends BaseOp {
readonly tag = OpTag.PROJECT;
constructor(readonly meta: Metadata) {
super();
}
}
export class ProjectStatic extends BaseOp {
readonly tag = OpTag.PROJECT_STATIC;
constructor(readonly meta: Metadata, readonly key: string) {
super();
}
}
export class PushLazy extends BaseOp {
readonly tag = OpTag.PUSH_LAZY;
constructor(readonly meta: Metadata, readonly body: BasicBlock) {
super();
}
}
export class Force extends BaseOp {
readonly tag = OpTag.FORCE;
constructor(readonly meta: Metadata) {
super();
}
}
export class Interpolate extends BaseOp {
readonly tag = OpTag.INTERPOLATE;
constructor(readonly meta: Metadata, readonly parts: (string | null)[]) {
super();
}
}
export class PushLambda extends BaseOp {
readonly tag = OpTag.PUSH_LAMBDA;
constructor(
readonly meta: Metadata,
readonly parameters: string[],
readonly body: BasicBlock
) {
super();
}
}
export class InvokeForeign extends BaseOp {
readonly tag = OpTag.INVOKE_FOREIGN;
constructor(
readonly meta: Metadata,
readonly name: string,
readonly arity: uint32
) {
super();
}
}
export class Invoke extends BaseOp {
readonly tag = OpTag.INVOKE;
constructor(
readonly meta: Metadata,
readonly name: string,
readonly arity: uint32
) {
super();
}
}
export class Apply extends BaseOp {
readonly tag = OpTag.APPLY;
constructor(readonly meta: Metadata, readonly arity: uint32) {
super();
}
}
export class Return extends BaseOp {
readonly tag = OpTag.RETURN;
constructor(readonly meta: Metadata) {
super();
}
}
export class PushPartial extends BaseOp {
readonly tag = OpTag.PUSH_PARTIAL;
constructor(
readonly meta: Metadata,
readonly name: string,
readonly arity: number
) {
super();
}
}
export class Assert extends BaseOp {
readonly tag = OpTag.ASSERT;
constructor(
readonly meta: Metadata,
readonly kind: AssertType,
readonly assert_tag: string,
readonly message: string,
readonly expression: null | [string, string[]]
) {
super();
}
}
export class Branch extends BaseOp {
readonly tag = OpTag.BRANCH;
constructor(
readonly meta: Metadata,
readonly consequent: BasicBlock,
readonly alternate: BasicBlock
) {
super();
}
}
export class TypeTest extends BaseOp {
readonly tag = OpTag.TYPE_TEST;
constructor(readonly meta: Metadata, readonly type: Type) {
super();
}
}
export class TraitTest extends BaseOp {
readonly tag = OpTag.TRAIT_TEST;
constructor(readonly meta: Metadata, readonly trait: Trait) {
super();
}
}
export class IntrinsicEqual extends BaseOp {
readonly tag = OpTag.INTRINSIC_EQUAL;
constructor(readonly meta: Metadata) {
super();
}
}
export class RegisterInstance extends BaseOp {
readonly tag = OpTag.REGISTER_INSTANCE;
constructor(readonly meta: Metadata) {
super();
}
}
export class Search extends BaseOp {
readonly tag = OpTag.SEARCH;
constructor(readonly meta: Metadata, readonly predicate: Predicate) {
super();
}
}
export class MatchSearch extends BaseOp {
readonly tag = OpTag.MATCH_SEARCH;
constructor(
readonly meta: Metadata,
readonly block: BasicBlock,
readonly alternate: BasicBlock
) {
super();
}
}
export class Fact extends BaseOp {
readonly tag = OpTag.FACT;
constructor(
readonly meta: Metadata,
readonly relation: string,
readonly arity: uint32
) {
super();
}
}
export class Forget extends BaseOp {
readonly tag = OpTag.FORGET;
constructor(
readonly meta: Metadata,
readonly relation: string,
readonly arity: uint32
) {
super();
}
}
export class SimulationSignal {
constructor(
readonly meta: Metadata,
readonly parameters: string[],
readonly name: string,
readonly body: BasicBlock
) {}
}
export class Simulate extends BaseOp {
readonly tag = OpTag.SIMULATE;
constructor(
readonly meta: Metadata,
readonly context: string | null,
readonly goal: SimulationGoal,
readonly signals: SimulationSignal[]
) {
super();
}
}
export class Handle extends BaseOp {
readonly tag = OpTag.HANDLE;
constructor(
readonly meta: Metadata,
readonly body: BasicBlock,
readonly handlers: HandlerCase[]
) {
super();
}
}
export class HandlerCase {
constructor(
readonly meta: Metadata,
readonly effect: string,
readonly variant: string,
readonly parameters: string[],
readonly block: BasicBlock
) {}
}
export class Perform extends BaseOp {
readonly tag = OpTag.PERFORM;
constructor(
readonly meta: Metadata,
readonly effect: string,
readonly variant: string,
readonly arity: number
) {
super();
}
}
export class ContinueWith extends BaseOp {
readonly tag = OpTag.CONTINUE_WITH;
constructor(readonly meta: Metadata) {
super();
}
}
export class Dsl extends BaseOp {
readonly tag = OpTag.DSL;
constructor(
readonly meta: Metadata,
readonly type: Type,
readonly ast: DslNode[]
) {
super();
}
}
export enum DslNodeTag {
NODE = 1,
LITERAL,
VARIABLE,
LIST,
INTERPOLATION,
EXPRESSION,
}
export type DslNode =
| DslAstNode
| DslAstLiteral
| DslAstVariable
| DslAstExpression
| DslAstInterpolation
| DslAstNodeList;
export type DslMeta = {
line: number;
column: number;
};
export class DslAstNode {
readonly tag = DslNodeTag.NODE;
constructor(
readonly meta: DslMeta,
readonly name: string,
readonly children: DslNode[],
readonly attributes: Map<string, DslNode>
) {}
}
export class DslAstLiteral {
readonly tag = DslNodeTag.LITERAL;
constructor(readonly meta: DslMeta, readonly value: Literal) {}
}
export class DslAstVariable {
readonly tag = DslNodeTag.VARIABLE;
constructor(readonly meta: DslMeta, readonly name: string) {}
}
export class DslAstNodeList {
readonly tag = DslNodeTag.LIST;
constructor(readonly meta: DslMeta, readonly children: DslNode[]) {}
}
export class DslAstExpression {
readonly tag = DslNodeTag.EXPRESSION;
constructor(
readonly meta: DslMeta,
readonly source: string,
readonly value: BasicBlock
) {}
}
export class DslAstInterpolation {
readonly tag = DslNodeTag.INTERPOLATION;
constructor(readonly meta: DslMeta, readonly parts: DslInterpolationPart[]) {}
}
export enum DslInterpolationTag {
STATIC,
DYNAMIC,
}
export type DslInterpolationPart =
| DslInterpolationStatic
| DslInterpolationDynamic;
export class DslInterpolationStatic {
readonly tag = DslInterpolationTag.STATIC;
constructor(readonly text: string) {}
}
export class DslInterpolationDynamic {
readonly tag = DslInterpolationTag.DYNAMIC;
constructor(readonly node: DslNode) {}
} | the_stack |
const { warn, error } = require("danger")
const { promises: fs, createReadStream } = require("fs")
const path = require("path")
const { createHash } = require("crypto")
const { spawn } = require("child_process")
const schemaV1Path = path.join(process.cwd(), "src/schema/v1")
const schemaV2Path = path.join(process.cwd(), "src/schema/v2")
/** Represents the git status of a file */
enum FileStatus {
Deleted = "deleted",
Modified = "modified",
Added = "added",
Renamed = "renamed",
Unknown = "unknown",
}
type DeltaFileMap = { [filePath: string]: FileStatus }
/**
* Converts git status short codes to their `FileStatus` equivalent.
* @param change Single character shorthand git file state
*/
const GitChangeToFileStatus = (change: string) => {
switch (change) {
case "M":
return FileStatus.Modified
case "A":
return FileStatus.Added
case "D":
return FileStatus.Deleted
case "R":
return FileStatus.Renamed
default:
return FileStatus.Unknown
}
}
interface BranchState {
commitsAhead: number
commitsBehind: number
}
/**
* Gives status information on the current branch as compared to origin/master
*/
const getBranchDrift = (): Promise<BranchState> =>
new Promise((resolve, reject) => {
let output = ""
const delta = spawn("git", [
"rev-list",
"--left-right",
"--count",
"origin/master...HEAD",
])
delta.stdout.on("data", data => {
output += data
})
delta.on("close", code => {
if (code !== 0) {
reject("Failed to get branch drift")
} else {
const commitChanges = output.match(/(\d+)\s+(\d+)/)
if (!commitChanges) {
reject("Something was wrong with the branch drift output")
}
let [, commitsBehind, commitsAhead] = Array.from(commitChanges!).map(
x => Number(x)
)
resolve({
commitsAhead,
commitsBehind,
})
}
})
})
/**
* Uses git to generate a delta map of files that have changed since master
*/
const getChangedFiles = (): Promise<DeltaFileMap> =>
new Promise((resolve, reject) => {
let changedBlob = ""
const changed = spawn("git", ["diff", "--name-status", "origin/master"])
changed.stdout.on("data", data => {
changedBlob += data
})
changed.on("close", code => {
if (code !== 0) {
reject("Failed to find changed files via git")
} else {
resolve(
changedBlob
.split("\n")
.map(status => {
const match = status.match(/([A-Z])\s+(.+)/)
if (match) {
const [, status, filePath] = match
return {
[path.resolve(filePath)]: GitChangeToFileStatus(status),
}
}
return {} as any
})
.reduce((a, b) => ({ ...a, ...b }), {})
)
}
})
})
/**
* Determines if a given path is a directory
* @param filePath The full path to a file (include its name)
*/
const isDirectory = async (filepath: string): Promise<boolean> =>
(await fs.lstat(filepath)).isDirectory()
/**
* Asynchronously generates an md5 of a file
* @param filePath The full path to a file (include its name)
*/
const hashFile = (filePath: string): Promise<string> =>
new Promise((resolve, reject) => {
const stream = createReadStream(filePath)
const hash = createHash("md5")
stream.on("data", data => hash.update(data, "utf8"))
stream.on("end", () => {
resolve(hash.digest("hex"))
})
stream.on("error", error => {
reject(error)
})
})
type FSNode = File | Directory
type FileMap = { [path: string]: File }
class File {
name: string
path: string
fullPath: string
relativePath: string
hash: string
private constructor(fullPath: string, hash: string) {
this.name = path.basename(fullPath)
this.path = path.dirname(fullPath)
this.fullPath = fullPath
this.relativePath = path.relative(process.cwd(), fullPath)
this.hash = hash
}
static async create(fullPath: string) {
return new File(fullPath, await hashFile(fullPath))
}
}
class Directory {
name: string
path: string
fullPath: string
nodes: Array<File | Directory>
fileMap: { [path: string]: File }
private constructor(fullPath: string, nodes: FSNode[], fileMap: FileMap) {
this.name = path.basename(fullPath)
this.path = path.dirname(fullPath)
this.fullPath = fullPath
this.nodes = nodes
this.fileMap = fileMap
}
static async create(fullPath: string, _deltaFileMap: DeltaFileMap = {}) {
const [children, childMap] = await this.getChildren(fullPath)
return new Directory(fullPath, children, childMap)
}
private static async getChildren(fullPath): Promise<[FSNode[], FileMap]> {
const nodes: FSNode[] = []
const fileNames = await fs.readdir(fullPath)
let fileMap: FileMap = {}
for (let fileName of fileNames) {
const currentPath = path.join(fullPath, fileName)
if (await isDirectory(currentPath)) {
let dir = await Directory.create(currentPath)
nodes.push(dir)
fileMap = { ...fileMap, ...dir.fileMap }
} else {
let file = await File.create(currentPath)
nodes.push(file)
fileMap[file.fullPath] = file
}
}
return [nodes, fileMap]
}
/**
* Calls a callback for every file of this directory and its sub directories
*/
public walk(callback: (File) => void) {
for (let child of this.nodes) {
if (child instanceof Directory) {
child.walk(callback)
} else {
callback(child)
}
}
}
public hasFile(fullPath: string) {
!!this.fileMap[fullPath]
}
public getFile(fullPath: string): File {
return this.fileMap[fullPath]
}
public listFiles(): string[] {
return Object.keys(this.fileMap)
}
}
const isFromSchemaV1 = (filePath: string) => filePath.includes("/schema/v1/")
/** Convert an absolute file path to a partial path that starts after `/v1/` or `/v2/` */
const fromSchemaRoot = (filePath: string) =>
isFromSchemaV1(filePath)
? filePath.split("/schema/v1/")[1]
: filePath.split("/schema/v2/")[1]
/** Updates a path from `/v1/` to `/v2/` or vice versa */
const switchSchemaPath = (filePath: string) =>
isFromSchemaV1(filePath)
? filePath.replace("/schema/v1/", "/schema/v2/")
: filePath.replace("/schema/v2/", "/schema/v1/")
/**
* @param directoryMapper Used to establish a common path between files of the two directories
*/
const diffDirectories = (
directory1: Directory,
directory2: Directory,
directoryMapper = p => p
): [string[], string[], string[]] => {
const fileList1 = directory1.listFiles().map(directoryMapper)
const fileList2 = directory2.listFiles().map(directoryMapper)
const sharedFiles = fileList1.filter(x => fileList2.includes(x))
const filesUniqueTo1 = fileList1.filter(x => !sharedFiles.includes(x))
const filesUniqueTo2 = fileList2.filter(x => !sharedFiles.includes(x))
return [filesUniqueTo1, sharedFiles, filesUniqueTo2]
}
// Main work
;(async () => {
const branchState = await getBranchDrift()
// Is there a better way to handle this?
if (branchState.commitsBehind > 0) {
warn(
"Branch is currently behind master, might not reflect accurate state\n"
)
}
const fileChanges = Object.entries(await getChangedFiles()).filter(
([file]) => file.includes("schema/v1/") || file.includes("schema/v2/")
)
// If no file updates, skip
if (fileChanges.length === 0) {
console.log("No updates detected in schema/v1 or schema/v2, skipping...\n")
return
}
// Read files from the FS
const schemaV1 = await Directory.create(schemaV1Path)
const schemaV2 = await Directory.create(schemaV2Path)
// Sort out which files are shared by v1 and v2
const [
filesUniqueToSchemaV1,
filesInBothSchemas,
// filesUniqueToSchemaV2,
] = diffDirectories(schemaV1, schemaV2, fromSchemaRoot)
const unknownChanges = fileChanges
.filter(([, status]) => status === FileStatus.Unknown)
.map(([file]) => file)
const modifiedFiles = fileChanges
.filter(([, status]) => status === FileStatus.Modified)
.map(([file]) => file)
const addedFiles = fileChanges
.filter(([, status]) => status === FileStatus.Added)
.map(([file]) => file)
// const deletedFiles = fileChanges
// .filter(([, status]) => status === FileStatus.Deleted)
// .map(([file]) => file)
// const renamedFiles = fileChanges
// .filter(([, status]) => status === FileStatus.Renamed)
// .map(([file]) => file)
if (unknownChanges.length > 0) {
error(
"File changes detect with unknown git status, please verify the following and update the schema drift script\n" +
unknownChanges.map(file => `- ${file}\n`)
)
}
// Scenarios
//
// For files that exist in both places
// File A was modified in (v1|v2), should it also be modified in (v2|v1)?
modifiedFiles
.map(filePath => [fromSchemaRoot(filePath), filePath])
.filter(([file]) => filesInBothSchemas.includes(file))
.forEach(([, filePath]) => {
if (isFromSchemaV1(filePath)) {
const schemaV1File = schemaV1.getFile(filePath)
const schemaV2File = schemaV2.getFile(switchSchemaPath(filePath))
// Both files are the same now, nothing to do here
if (schemaV1File.hash === schemaV2File.hash) return
warn(
`${
schemaV1File.relativePath
} has been modified, should this update also happen in ${
schemaV2File.relativePath
}?`
)
} else {
const schemaV2File = schemaV2.getFile(filePath)
const schemaV1File = schemaV1.getFile(switchSchemaPath(filePath))
// The files are the same, skip
if (schemaV2File.hash === schemaV1File.hash) return
warn(
`${
schemaV2File.relativePath
} has been modified, should this update also happen in ${
schemaV1File.relativePath
}?`
)
}
})
// For files added during transition
// File was added to v1, should it also exist in v2?
addedFiles
.map(filePath => [fromSchemaRoot(filePath), filePath])
.filter(([file]) => filesUniqueToSchemaV1.includes(file))
.forEach(([, filePath]) => {
const file = schemaV1.getFile(filePath)
warn(
`${file.relativePath} was added to v1, should it also be added to v2?`
)
})
// For updates in v1 that don't match to V2
// An update was made to a file in v1, but it doesn't exist in V2. Double
// check that there aren't updates required.
modifiedFiles
.map(filePath => [fromSchemaRoot(filePath), filePath])
.filter(([file]) => filesUniqueToSchemaV1.includes(file))
.forEach(([, filePath]) => {
const file = schemaV1.getFile(filePath)
warn(
`${
file.relativePath
} was modified in v1, but doesn't exist in v2. Ensure no v2 changes are required.`
)
})
})() | the_stack |
import * as path from "path";
import * as assert from "assert";
import Sinon = require("sinon");
import { QuickPickItem, window } from "vscode";
import { AdbHelper } from "../../src/extension/android/adb";
import {
IMobileTarget,
IDebuggableMobileTarget,
MobileTarget,
} from "../../src/extension/mobileTarget";
import {
IOSTargetManager,
IDebuggableIOSTarget,
IOSTarget,
} from "../../src/extension/ios/iOSTargetManager";
import {
AndroidTarget,
AndroidTargetManager,
} from "../../src/extension/android/androidTargetManager";
import { MobileTargetManager } from "../../src/extension/mobileTargetManager";
suite("MobileTargetManager", function () {
const testProjectPath = path.join(__dirname, "..", "resources", "testCordovaProject");
let onlineSimulator1: IMobileTarget;
let onlineSimulator2: IMobileTarget;
let offlineSimulator1: IMobileTarget;
let offlineSimulator2: IMobileTarget;
let device1: IMobileTarget;
let device2: IMobileTarget;
let revertTargetsStates: () => void;
let targetManager: MobileTargetManager;
let targetsForSelection: string[];
let showQuickPickStub: Sinon.SinonStub;
let launchSimulatorStub: Sinon.SinonStub;
let collectTargetsStub: Sinon.SinonStub;
async function checkTargetType(
assertFun: () => Promise<void>,
catchFun?: () => void,
): Promise<void> {
try {
await assertFun();
} catch {
if (catchFun) {
catchFun();
}
}
}
async function checkTargetSeletionResult(
filter: (target: IMobileTarget) => boolean = () => true,
selectionListCheck: (options: string[]) => boolean = () => true,
resultCheck: (target?: MobileTarget) => boolean = () => true,
): Promise<void> {
const target = await targetManager.selectAndPrepareTarget(filter);
if (selectionListCheck) {
assert.ok(selectionListCheck(targetsForSelection), "Did not pass options list check");
}
if (resultCheck) {
assert.ok(resultCheck(target), "Did not pass result target check");
}
}
function runTargetTypeCheckTests() {
test("Should properly recognize virtual target type", async function () {
await checkTargetType(
async () =>
assert.strictEqual(
await targetManager.isVirtualTarget("simulator"),
true,
"Could not recognize any simulator",
),
() => assert.fail("Could not recognize any simulator"),
);
await checkTargetType(
async () =>
assert.strictEqual(
await targetManager.isVirtualTarget(onlineSimulator1.id as string),
true,
`Could not recognize simulator id: ${onlineSimulator1.id as string}`,
),
() =>
assert.fail(
`Could not recognize simulator id: ${onlineSimulator1.id as string}`,
),
);
await checkTargetType(async () =>
assert.strictEqual(
await targetManager.isVirtualTarget("simulatorId11"),
false,
"Misrecognized simulator id: simulatorId11",
),
);
await checkTargetType(
async () =>
assert.strictEqual(
await targetManager.isVirtualTarget(onlineSimulator2.name as string),
true,
`Could not recognize simulator name: ${onlineSimulator2.name as string}`,
),
() =>
assert.fail(
`Could not recognize simulator name: ${onlineSimulator2.name as string}`,
),
);
await checkTargetType(async () =>
assert.strictEqual(
await targetManager.isVirtualTarget("simulatorName22"),
false,
"Misrecognized simulator name: simulatorName22",
),
);
});
test("Should properly recognize device target", async function () {
await checkTargetType(
async () =>
assert.strictEqual(
await targetManager.isVirtualTarget("device"),
false,
"Could not recognize any device",
),
() => assert.fail("Could not recognize any device"),
);
await checkTargetType(
async () =>
assert.strictEqual(
await targetManager.isVirtualTarget(device1.id as string),
false,
`Could not recognize device id: ${device1.id as string}`,
),
() => assert.fail(`Could not recognize device id: ${device1.id as string}`),
);
await checkTargetType(async () =>
assert.strictEqual(
await targetManager.isVirtualTarget("deviceid111"),
false,
"Misrecognized device id: deviceid111",
),
);
});
}
function runTargetSelectionTests() {
test("Should show all targets in case filter has not been defined", async function () {
await checkTargetSeletionResult(undefined, options => options.length === 6);
});
test("Should show targets by filter", async function () {
const onlineTargetsFilter = (target: IMobileTarget) => target.isOnline;
await checkTargetSeletionResult(onlineTargetsFilter, options => options.length === 4);
});
test("Should auto select option in case there is only one target", async function () {
const showQuickPickCallCount = showQuickPickStub.callCount;
const specificNameTargetFilter = (target: IMobileTarget) =>
target.name === onlineSimulator1.name;
await checkTargetSeletionResult(
specificNameTargetFilter,
undefined,
(target: MobileTarget) => target.id === onlineSimulator1.id,
);
assert.strictEqual(
showQuickPickStub.callCount - showQuickPickCallCount,
0,
"There is only one target, but quick pick was shown",
);
});
test("Should launch the selected simulator in case it's offline", async function () {
const specificNameTargetFilter = (target: IMobileTarget) =>
target.name === offlineSimulator1.name;
await checkTargetSeletionResult(
specificNameTargetFilter,
undefined,
(target: MobileTarget) =>
target.isOnline && !!target.id && target.name === offlineSimulator1.name,
);
});
}
suiteSetup(() => {
showQuickPickStub = Sinon.stub(
window,
"showQuickPick",
async (
items: string[] | Thenable<string[]> | QuickPickItem[] | Thenable<QuickPickItem[]>,
) => {
targetsForSelection = <string[]>await items;
return items[0];
},
);
targetsForSelection = [];
});
suiteTeardown(() => {
showQuickPickStub.reset();
});
suite("IOSTargetManager", function () {
suiteSetup(() => {
targetManager = new IOSTargetManager();
revertTargetsStates = () => {
onlineSimulator1 = {
name: "simulatorName1",
id: "simulatorId1",
isVirtualTarget: true,
isOnline: true,
system: "1",
} as IDebuggableIOSTarget;
onlineSimulator2 = {
name: "simulatorName2",
id: "simulatorId2",
isVirtualTarget: true,
isOnline: true,
system: "1",
} as IDebuggableIOSTarget;
offlineSimulator1 = {
name: "simulatorName3",
id: "simulatorId3",
isVirtualTarget: true,
isOnline: false,
system: "1",
} as IDebuggableIOSTarget;
offlineSimulator2 = {
name: "simulatorName4",
id: "simulatorId4",
isVirtualTarget: true,
isOnline: false,
system: "1",
} as IDebuggableIOSTarget;
device1 = {
name: "deviceName1",
id: "deviceid1",
isVirtualTarget: false,
isOnline: true,
system: "1",
} as IDebuggableIOSTarget;
device2 = {
name: "deviceName2",
id: "deviceid2",
isVirtualTarget: false,
isOnline: true,
system: "1",
} as IDebuggableIOSTarget;
};
collectTargetsStub = Sinon.stub(targetManager as any, "collectTargets", async () => {
revertTargetsStates();
(targetManager as any).targets = [
onlineSimulator1,
onlineSimulator2,
offlineSimulator1,
offlineSimulator2,
device1,
device2,
];
});
launchSimulatorStub = Sinon.stub(
targetManager as any,
"launchSimulator",
async (simulator: IMobileTarget) => {
simulator.isOnline = true;
return IOSTarget.fromInterface(<IDebuggableIOSTarget>simulator);
},
);
targetsForSelection = [];
});
suiteTeardown(() => {
launchSimulatorStub.reset();
collectTargetsStub.reset();
});
suite("Target selection", function () {
setup(async () => {
await targetManager.collectTargets();
});
runTargetSelectionTests();
test("Should select target after system selection", async () => {
(onlineSimulator2 as IDebuggableIOSTarget).system = "2";
(offlineSimulator2 as IDebuggableIOSTarget).system = "2";
(device1 as IDebuggableIOSTarget).system = "2";
const showQuickPickCallCount = showQuickPickStub.callCount;
await checkTargetSeletionResult(undefined, options => options.length === 3);
assert.strictEqual(
showQuickPickStub.callCount - showQuickPickCallCount,
2,
"Incorrect number of selection steps",
);
});
});
suite("Target identification", function () {
runTargetTypeCheckTests();
});
});
suite("AndroidTargetManager", function () {
let adbHelper: AdbHelper;
let getAbdsNamesStub: Sinon.SinonStub;
let getOnlineTargetsStub: Sinon.SinonStub;
suiteSetup(() => {
adbHelper = new AdbHelper(testProjectPath, path.join(testProjectPath, "node_modules"));
targetManager = new AndroidTargetManager(adbHelper);
revertTargetsStates = () => {
onlineSimulator1 = {
name: "emulatorName1",
id: "emulator-5551",
isVirtualTarget: true,
isOnline: true,
};
onlineSimulator2 = {
name: "emulatorName2",
id: "emulator-5552",
isVirtualTarget: true,
isOnline: true,
};
offlineSimulator1 = {
name: "emulatorName3",
id: undefined,
isVirtualTarget: true,
isOnline: false,
}; //id: emulator-5553
offlineSimulator2 = {
name: "emulatorName4",
id: undefined,
isVirtualTarget: true,
isOnline: false,
}; //id: emulator-5554
device1 = { id: "deviceid1", isVirtualTarget: false, isOnline: true };
device2 = { id: "deviceid2", isVirtualTarget: false, isOnline: true };
};
collectTargetsStub = Sinon.stub(targetManager as any, "collectTargets", async () => {
revertTargetsStates();
(targetManager as any).targets = [
onlineSimulator1,
onlineSimulator2,
offlineSimulator1,
offlineSimulator2,
device1,
device2,
];
});
launchSimulatorStub = Sinon.stub(
targetManager as any,
"launchSimulator",
async (simulatorTarget: IMobileTarget) => {
simulatorTarget.isOnline = true;
switch (simulatorTarget.name) {
case "emulatorName1":
simulatorTarget.id = "emulator-5551";
break;
case "emulatorName2":
simulatorTarget.id = "emulator-5552";
break;
case "emulatorName3":
simulatorTarget.id = "emulator-5553";
break;
case "emulatorName4":
simulatorTarget.id = "emulator-5554";
break;
}
return AndroidTarget.fromInterface(<IDebuggableMobileTarget>simulatorTarget);
},
);
getAbdsNamesStub = Sinon.stub(adbHelper, "getAvdsNames", async () => {
return [
onlineSimulator1.name,
onlineSimulator2.name,
offlineSimulator1.name,
offlineSimulator2.name,
];
});
getOnlineTargetsStub = Sinon.stub(adbHelper, "getOnlineTargets", async () => {
return <IDebuggableMobileTarget[]>(
[
onlineSimulator1,
onlineSimulator2,
offlineSimulator1,
offlineSimulator2,
device1,
device2,
].filter(target => target.isOnline)
);
});
targetsForSelection = [];
});
suiteTeardown(() => {
getAbdsNamesStub.reset();
getOnlineTargetsStub.reset();
launchSimulatorStub.reset();
});
suite("Target selection", function () {
setup(async () => {
await targetManager.collectTargets();
});
runTargetSelectionTests();
});
suite("Target identification", function () {
runTargetTypeCheckTests();
});
});
}); | the_stack |
/**
* @license
*
* This file is based on https://github.com/lodash/lodash and thus licensed as follows.
* The code & license is based on https://github.com/lodash/lodash/tree/2da024c3b4f9947a48517639de7560457cd4ec6c
*
* The MIT License
*
* Copyright JS Foundation and other contributors <https://js.foundation/>
*
* Based on Underscore.js, copyright Jeremy Ashkenas,
* DocumentCloud and Investigative Reporters & Editors <http://underscorejs.org/>
*
* This software consists of voluntary contributions made by many
* individuals. For exact contribution history, see the revision history
* available at https://github.com/lodash/lodash
*
* The following license applies to all parts of this software except as
* documented below:
*
* ====
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* ====
*
* Copyright and related rights for sample code are waived via CC0. Sample
* code is defined as all source code displayed within the prose of the
* documentation.
*
* CC0: http://creativecommons.org/publicdomain/zero/1.0/
*
* ====
*
* Files located in the node_modules and vendor directories are externally
* maintained libraries used by this software which have their own
* licenses; we recommend you read them, as their terms may differ from the
* terms above.
*
*/
//BEGIN https://github.com/lodash/lodash/blob/master/isObject.js
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* isObject({})
* // => true
*
* isObject([1, 2, 3])
* // => true
*
* isObject(Function)
* // => true
*
* isObject(null)
* // => false
*/
function isObject(value) {
const type = typeof value
return value != null && (type === 'object' || type === 'function')
}
//END https://github.com/lodash/lodash/blob/master/isObject.js
//BEGIN https://github.com/lodash/lodash/blob/master/.internal/freeGlobal.js
const freeGlobal = typeof global === 'object' && global !== null && global.Object === Object && global
//END https://github.com/lodash/lodash/blob/master/.internal/freeGlobal.js
//BEGIN https://github.com/lodash/lodash/blob/master/.internal/root.js
/** Detect free variable `globalThis` */
const freeGlobalThis = typeof globalThis === 'object' && globalThis !== null && globalThis.Object == Object && globalThis
/** Detect free variable `self`. */
const freeSelf = typeof self === 'object' && self !== null && self.Object === Object && self
/** Used as a reference to the global object. */
const root = freeGlobalThis || freeGlobal || freeSelf || Function('return this')()
//END https://github.com/lodash/lodash/blob/master/.internal/root.js
//BEGIN https://github.com/lodash/lodash/blob/master/debounce.js
/**
* Creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked, or until the next browser frame is drawn. The debounced function
* comes with a `cancel` method to cancel delayed `func` invocations and a
* `flush` method to immediately invoke them. Provide `options` to indicate
* whether `func` should be invoked on the leading and/or trailing edge of the
* `wait` timeout. The `func` is invoked with the last arguments provided to the
* debounced function. Subsequent calls to the debounced function return the
* result of the last `func` invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the debounced function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until the next tick, similar to `setTimeout` with a timeout of `0`.
*
* If `wait` is omitted in an environment with `requestAnimationFrame`, `func`
* invocation will be deferred until the next frame is drawn (typically about
* 16ms).
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `debounce` and `throttle`.
*
* @since 0.1.0
* @category Function
* @param {Function} func The function to debounce.
* @param {number} [wait=0]
* The number of milliseconds to delay; if omitted, `requestAnimationFrame` is
* used (if available).
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=false]
* Specify invoking on the leading edge of the timeout.
* @param {number} [options.maxWait]
* The maximum time `func` is allowed to be delayed before it's invoked.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // Avoid costly calculations while the window size is in flux.
* jQuery(window).on('resize', debounce(calculateLayout, 150))
*
* // Invoke `sendMail` when clicked, debouncing subsequent calls.
* jQuery(element).on('click', debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* }))
*
* // Ensure `batchLog` is invoked once after 1 second of debounced calls.
* const debounced = debounce(batchLog, 250, { 'maxWait': 1000 })
* const source = new EventSource('/stream')
* jQuery(source).on('message', debounced)
*
* // Cancel the trailing debounced invocation.
* jQuery(window).on('popstate', debounced.cancel)
*
* // Check for pending invocations.
* const status = debounced.pending() ? "Pending..." : "Ready"
*/
function debounce(func, wait, options) {
let lastArgs,
lastThis: any,
maxWait,
result,
timerId,
lastCallTime
let lastInvokeTime = 0
let leading = false
let maxing = false
let trailing = true
// Bypass `requestAnimationFrame` by explicitly setting `wait=0`.
const useRAF = (!wait && wait !== 0 && typeof root.requestAnimationFrame === 'function')
if (typeof func !== 'function') {
throw new TypeError('Expected a function')
}
wait = +wait || 0
if (isObject(options)) {
leading = !!options.leading
maxing = 'maxWait' in options
maxWait = maxing ? Math.max(+options.maxWait || 0, wait) : maxWait
trailing = 'trailing' in options ? !!options.trailing : trailing
}
function invokeFunc(time) {
const args = lastArgs
const thisArg = lastThis
lastArgs = lastThis = undefined
lastInvokeTime = time
result = func.apply(thisArg, args)
return result
}
function startTimer(pendingFunc, wait) {
if (useRAF) {
root.cancelAnimationFrame(timerId)
return root.requestAnimationFrame(pendingFunc)
}
return setTimeout(pendingFunc, wait)
}
function cancelTimer(id) {
if (useRAF) {
return root.cancelAnimationFrame(id)
}
clearTimeout(id)
}
function leadingEdge(time) {
// Reset any `maxWait` timer.
lastInvokeTime = time
// Start the timer for the trailing edge.
timerId = startTimer(timerExpired, wait)
// Invoke the leading edge.
return leading ? invokeFunc(time) : result
}
function remainingWait(time) {
const timeSinceLastCall = time - lastCallTime
const timeSinceLastInvoke = time - lastInvokeTime
const timeWaiting = wait - timeSinceLastCall
return maxing
? Math.min(timeWaiting, maxWait - timeSinceLastInvoke)
: timeWaiting
}
function shouldInvoke(time) {
const timeSinceLastCall = time - lastCallTime
const timeSinceLastInvoke = time - lastInvokeTime
// Either this is the first call, activity has stopped and we're at the
// trailing edge, the system time has gone backwards and we're treating
// it as the trailing edge, or we've hit the `maxWait` limit.
return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
(timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait))
}
function timerExpired() {
const time = Date.now()
if (shouldInvoke(time)) {
return trailingEdge(time)
}
// Restart the timer.
timerId = startTimer(timerExpired, remainingWait(time))
}
function trailingEdge(time) {
timerId = undefined
// Only invoke if we have `lastArgs` which means `func` has been
// debounced at least once.
if (trailing && lastArgs) {
return invokeFunc(time)
}
lastArgs = lastThis = undefined
return result
}
function cancel() {
if (timerId !== undefined) {
cancelTimer(timerId)
}
lastInvokeTime = 0
lastArgs = lastCallTime = lastThis = timerId = undefined
}
function flush() {
return timerId === undefined ? result : trailingEdge(Date.now())
}
function pending() {
return timerId !== undefined
}
function debounced(this: any, ...args) {
const time = Date.now()
const isInvoking = shouldInvoke(time)
lastArgs = args
lastThis = this
lastCallTime = time
if (isInvoking) {
if (timerId === undefined) {
return leadingEdge(lastCallTime)
}
if (maxing) {
// Handle invocations in a tight loop.
timerId = startTimer(timerExpired, wait)
return invokeFunc(lastCallTime)
}
}
if (timerId === undefined) {
timerId = startTimer(timerExpired, wait)
}
return result
}
debounced.cancel = cancel
debounced.flush = flush
debounced.pending = pending
return debounced
}
// END https://github.com/lodash/lodash/blob/master/debounce.js
//BEGIN https://github.com/lodash/lodash/blob/master/throttle.js
/**
* Creates a throttled function that only invokes `func` at most once per
* every `wait` milliseconds (or once per browser frame). The throttled function
* comes with a `cancel` method to cancel delayed `func` invocations and a
* `flush` method to immediately invoke them. Provide `options` to indicate
* whether `func` should be invoked on the leading and/or trailing edge of the
* `wait` timeout. The `func` is invoked with the last arguments provided to the
* throttled function. Subsequent calls to the throttled function return the
* result of the last `func` invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the throttled function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until the next tick, similar to `setTimeout` with a timeout of `0`.
*
* If `wait` is omitted in an environment with `requestAnimationFrame`, `func`
* invocation will be deferred until the next frame is drawn (typically about
* 16ms).
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `throttle` and `debounce`.
*
* @since 0.1.0
* @category Function
* @param {Function} func The function to throttle.
* @param {number} [wait=0]
* The number of milliseconds to throttle invocations to; if omitted,
* `requestAnimationFrame` is used (if available).
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=true]
* Specify invoking on the leading edge of the timeout.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new throttled function.
* @example
*
* // Avoid excessively updating the position while scrolling.
* jQuery(window).on('scroll', throttle(updatePosition, 100))
*
* // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
* const throttled = throttle(renewToken, 300000, { 'trailing': false })
* jQuery(element).on('click', throttled)
*
* // Cancel the trailing throttled invocation.
* jQuery(window).on('popstate', throttled.cancel)
*/
function throttle(func, wait, options) {
let leading = true
let trailing = true
if (typeof func !== 'function') {
throw new TypeError('Expected a function')
}
if (isObject(options)) {
leading = 'leading' in options ? !!options.leading : leading
trailing = 'trailing' in options ? !!options.trailing : trailing
}
return debounce(func, wait, {
leading,
trailing,
'maxWait': wait
})
}
//END https://github.com/lodash/lodash/blob/master/throttle.js
export { throttle, debounce } | the_stack |
import { Injectable } from '@angular/core';
import { Subject, Subscription } from 'rxjs';
import { ILocalNotification } from '@ionic-native/local-notifications';
import { CoreApp } from '@services/app';
import { CoreConfig } from '@services/config';
import { CoreEventObserver, CoreEvents } from '@singletons/events';
import { CoreTextUtils } from '@services/utils/text';
import { CoreUtils } from '@services/utils/utils';
import { SQLiteDB } from '@classes/sqlitedb';
import { CoreQueueRunner } from '@classes/queue-runner';
import { CoreError } from '@classes/errors/error';
import { CoreConstants } from '@/core/constants';
import { makeSingleton, NgZone, Platform, Translate, LocalNotifications, Push } from '@singletons';
import { CoreLogger } from '@singletons/logger';
import {
APP_SCHEMA,
TRIGGERED_TABLE_NAME,
COMPONENTS_TABLE_NAME,
SITES_TABLE_NAME,
CodeRequestsQueueItem,
} from '@services/database/local-notifications';
/**
* Service to handle local notifications.
*/
@Injectable({ providedIn: 'root' })
export class CoreLocalNotificationsProvider {
protected logger: CoreLogger;
protected codes: { [s: string]: number } = {};
protected codeRequestsQueue: {[key: string]: CodeRequestsQueueItem} = {};
protected observables: {[eventName: string]: {[component: string]: Subject<unknown>}} = {};
protected triggerSubscription?: Subscription;
protected clickSubscription?: Subscription;
protected clearSubscription?: Subscription;
protected cancelSubscription?: Subscription;
protected addSubscription?: Subscription;
protected updateSubscription?: Subscription;
protected queueRunner: CoreQueueRunner; // Queue to decrease the number of concurrent calls to the plugin (see MOBILE-3477).
// Variables for DB.
protected appDB: Promise<SQLiteDB>;
protected resolveAppDB!: (appDB: SQLiteDB) => void;
constructor() {
this.appDB = new Promise(resolve => this.resolveAppDB = resolve);
this.logger = CoreLogger.getInstance('CoreLocalNotificationsProvider');
this.queueRunner = new CoreQueueRunner(10);
this.init();
}
/**
* Initialize database.
*/
async initializeDatabase(): Promise<void> {
try {
await CoreApp.createTablesFromSchema(APP_SCHEMA);
} catch (e) {
// Ignore errors.
}
this.resolveAppDB(CoreApp.getDB());
}
/**
* Init some properties.
*/
protected async init(): Promise<void> {
await Platform.ready();
if (!this.isAvailable()) {
return;
}
// Listen to events.
this.triggerSubscription = LocalNotifications.on('trigger').subscribe((notification: ILocalNotification) => {
this.trigger(notification);
this.handleEvent('trigger', notification);
});
this.clickSubscription = LocalNotifications.on('click').subscribe((notification: ILocalNotification) => {
this.handleEvent('click', notification);
});
this.clearSubscription = LocalNotifications.on('clear').subscribe((notification: ILocalNotification) => {
this.handleEvent('clear', notification);
});
this.cancelSubscription = LocalNotifications.on('cancel').subscribe((notification: ILocalNotification) => {
this.handleEvent('cancel', notification);
});
this.addSubscription = LocalNotifications.on('schedule').subscribe((notification: ILocalNotification) => {
this.handleEvent('schedule', notification);
});
this.updateSubscription = LocalNotifications.on('update').subscribe((notification: ILocalNotification) => {
this.handleEvent('update', notification);
});
// Create the default channel for local notifications.
this.createDefaultChannel();
Translate.onLangChange.subscribe(() => {
// Update the channel name.
this.createDefaultChannel();
});
CoreEvents.on(CoreEvents.SITE_DELETED, (site) => {
if (site) {
this.cancelSiteNotifications(site.id!);
}
});
}
/**
* Cancel a local notification.
*
* @param id Notification id.
* @param component Component of the notification.
* @param siteId Site ID.
* @return Promise resolved when the notification is cancelled.
*/
async cancel(id: number, component: string, siteId: string): Promise<void> {
const uniqueId = await this.getUniqueNotificationId(id, component, siteId);
const queueId = 'cancel-' + uniqueId;
await this.queueRunner.run(queueId, () => LocalNotifications.cancel(uniqueId), {
allowRepeated: true,
});
}
/**
* Cancel all the scheduled notifications belonging to a certain site.
*
* @param siteId Site ID.
* @return Promise resolved when the notifications are cancelled.
*/
async cancelSiteNotifications(siteId: string): Promise<void> {
if (!this.isAvailable()) {
return;
} else if (!siteId) {
throw new Error('No site ID supplied.');
}
const scheduled = await this.getAllScheduled();
const ids: number[] = [];
const queueId = 'cancelSiteNotifications-' + siteId;
scheduled.forEach((notif) => {
notif.data = this.parseNotificationData(notif.data);
if (notif.id && typeof notif.data == 'object' && notif.data.siteId === siteId) {
ids.push(notif.id);
}
});
await this.queueRunner.run(queueId, () => LocalNotifications.cancel(ids), {
allowRepeated: true,
});
}
/**
* Check whether sound can be disabled for notifications.
*
* @return Whether sound can be disabled for notifications.
*/
canDisableSound(): boolean {
// Only allow disabling sound in Android 7 or lower. In iOS and Android 8+ it can easily be done with system settings.
return this.isAvailable() && CoreApp.isAndroid() && CoreApp.getPlatformMajorVersion() < 8;
}
/**
* Create the default channel. It is used to change the name.
*
* @return Promise resolved when done.
*/
protected async createDefaultChannel(): Promise<void> {
if (!CoreApp.isAndroid()) {
return;
}
await Push.createChannel({
id: 'default-channel-id',
description: Translate.instant('addon.calendar.calendarreminders'),
importance: 4,
}).catch((error) => {
this.logger.error('Error changing channel name', error);
});
}
/**
* Get all scheduled notifications.
*
* @return Promise resolved with the notifications.
*/
protected getAllScheduled(): Promise<ILocalNotification[]> {
return this.queueRunner.run('allScheduled', () => LocalNotifications.getAllScheduled());
}
/**
* Get a code to create unique notifications. If there's no code assigned, create a new one.
*
* @param table Table to search in local DB.
* @param id ID of the element to get its code.
* @return Promise resolved when the code is retrieved.
*/
protected async getCode(table: string, id: string): Promise<number> {
const key = table + '#' + id;
// Check if the code is already in memory.
if (typeof this.codes[key] != 'undefined') {
return this.codes[key];
}
const db = await this.appDB;
try {
// Check if we already have a code stored for that ID.
const entry = await db.getRecord<{id: string; code: number}>(table, { id: id });
this.codes[key] = entry.code;
return entry.code;
} catch (err) {
// No code stored for that ID. Create a new code for it.
const entries = await db.getRecords<{id: string; code: number}>(table, undefined, 'code DESC');
let newCode = 0;
if (entries.length > 0) {
newCode = entries[0].code + 1;
}
await db.insertRecord(table, { id: id, code: newCode });
this.codes[key] = newCode;
return newCode;
}
}
/**
* Get a notification component code to be used.
* If it's the first time this component is used to send notifications, create a new code for it.
*
* @param component Component name.
* @return Promise resolved when the component code is retrieved.
*/
protected getComponentCode(component: string): Promise<number> {
return this.requestCode(COMPONENTS_TABLE_NAME, component);
}
/**
* Get a site code to be used.
* If it's the first time this site is used to send notifications, create a new code for it.
*
* @param siteId Site ID.
* @return Promise resolved when the site code is retrieved.
*/
protected getSiteCode(siteId: string): Promise<number> {
return this.requestCode(SITES_TABLE_NAME, siteId);
}
/**
* Create a unique notification ID, trying to prevent collisions. Generated ID must be a Number (Android).
* The generated ID shouldn't be higher than 2147483647 or it's going to cause problems in Android.
* This function will prevent collisions and keep the number under Android limit if:
* - User has used less than 21 sites.
* - There are less than 11 components.
* - The notificationId passed as parameter is lower than 10000000.
*
* @param notificationId Notification ID.
* @param component Component triggering the notification.
* @param siteId Site ID.
* @return Promise resolved when the notification ID is generated.
*/
protected async getUniqueNotificationId(notificationId: number, component: string, siteId: string): Promise<number> {
if (!siteId || !component) {
return Promise.reject(new CoreError('Site ID or component not supplied.'));
}
const siteCode = await this.getSiteCode(siteId);
const componentCode = await this.getComponentCode(component);
// We use the % operation to keep the number under Android's limit.
return (siteCode * 100000000 + componentCode * 10000000 + notificationId) % 2147483647;
}
/**
* Handle an event triggered by the local notifications plugin.
*
* @param eventName Name of the event.
* @param notification Notification.
*/
protected handleEvent(eventName: string, notification: ILocalNotification): void {
if (notification && notification.data) {
this.logger.debug('Notification event: ' + eventName + '. Data:', notification.data);
this.notifyEvent(eventName, notification.data);
}
}
/**
* Returns whether local notifications plugin is installed.
*
* @return Whether local notifications plugin is installed.
*/
isAvailable(): boolean {
const win = <any> window; // eslint-disable-line @typescript-eslint/no-explicit-any
return !!win.cordova?.plugins?.notification?.local;
}
/**
* Check if a notification has been triggered with the same trigger time.
*
* @param notification Notification to check.
* @param useQueue Whether to add the call to the queue.
* @return Promise resolved with a boolean indicating if promise is triggered (true) or not.
*/
async isTriggered(notification: ILocalNotification, useQueue: boolean = true): Promise<boolean> {
const db = await this.appDB;
try {
const stored = await db.getRecord<{ id: number; at: number }>(
TRIGGERED_TABLE_NAME,
{ id: notification.id },
);
let triggered = (notification.trigger && notification.trigger.at) || 0;
if (typeof triggered != 'number') {
triggered = triggered.getTime();
}
return stored.at === triggered;
} catch (err) {
if (useQueue) {
const queueId = 'isTriggered-' + notification.id;
return this.queueRunner.run(queueId, () => LocalNotifications.isTriggered(notification.id!), {
allowRepeated: true,
});
} else {
return LocalNotifications.isTriggered(notification.id || 0);
}
}
}
/**
* Notify notification click to observers. Only the observers with the same component as the notification will be notified.
*
* @param data Data received by the notification.
*/
notifyClick(data: Record<string, unknown>): void {
this.notifyEvent('click', data);
}
/**
* Notify a certain event to observers. Only the observers with the same component as the notification will be notified.
*
* @param eventName Name of the event to notify.
* @param data Data received by the notification.
*/
notifyEvent(eventName: string, data: Record<string, unknown>): void {
// Execute the code in the Angular zone, so change detection doesn't stop working.
NgZone.run(() => {
const component = <string> data.component;
if (component) {
if (this.observables[eventName] && this.observables[eventName][component]) {
this.observables[eventName][component].next(data);
}
}
});
}
/**
* Parse some notification data.
*
* @param data Notification data.
* @return Parsed data.
*/
protected parseNotificationData(data: unknown): unknown {
if (!data) {
return {};
} else if (typeof data == 'string') {
return CoreTextUtils.parseJSON(data, {});
} else {
return data;
}
}
/**
* Process the next request in queue.
*/
protected async processNextRequest(): Promise<void> {
const nextKey = Object.keys(this.codeRequestsQueue)[0];
if (typeof nextKey == 'undefined') {
// No more requests in queue, stop.
return;
}
const request = this.codeRequestsQueue[nextKey];
try {
// Check if request is valid.
if (typeof request != 'object' || request.table === undefined || request.id === undefined) {
return;
}
// Get the code and resolve/reject all the promises of this request.
const code = await this.getCode(request.table, request.id);
request.deferreds.forEach((p) => {
p.resolve(code);
});
} catch (error) {
request.deferreds.forEach((p) => {
p.reject(error);
});
} finally {
// Once this item is treated, remove it and process next.
delete this.codeRequestsQueue[nextKey];
this.processNextRequest();
}
}
/**
* Register an observer to be notified when a notification belonging to a certain component is clicked.
*
* @param component Component to listen notifications for.
* @param callback Function to call with the data received by the notification.
* @return Object with an "off" property to stop listening for clicks.
*/
registerClick<T = unknown>(component: string, callback: CoreLocalNotificationsClickCallback<T>): CoreEventObserver {
return this.registerObserver<T>('click', component, callback);
}
/**
* Register an observer to be notified when a certain event is fired for a notification belonging to a certain component.
*
* @param eventName Name of the event to listen to.
* @param component Component to listen notifications for.
* @param callback Function to call with the data received by the notification.
* @return Object with an "off" property to stop listening for events.
*/
registerObserver<T = unknown>(
eventName: string,
component: string,
callback: CoreLocalNotificationsClickCallback<T>,
): CoreEventObserver {
this.logger.debug(`Register observer '${component}' for event '${eventName}'.`);
if (typeof this.observables[eventName] == 'undefined') {
this.observables[eventName] = {};
}
if (typeof this.observables[eventName][component] == 'undefined') {
// No observable for this component, create a new one.
this.observables[eventName][component] = new Subject<T>();
}
this.observables[eventName][component].subscribe(callback);
return {
off: (): void => {
this.observables[eventName][component].unsubscribe();
},
};
}
/**
* Remove a notification from triggered store.
*
* @param id Notification ID.
* @return Promise resolved when it is removed.
*/
async removeTriggered(id: number): Promise<void> {
const db = await this.appDB;
await db.deleteRecords(TRIGGERED_TABLE_NAME, { id: id });
}
/**
* Request a unique code. The request will be added to the queue and the queue is going to be started if it's paused.
*
* @param table Table to search in local DB.
* @param id ID of the element to get its code.
* @return Promise resolved when the code is retrieved.
*/
protected requestCode(table: string, id: string): Promise<number> {
const deferred = CoreUtils.promiseDefer<number>();
const key = table + '#' + id;
const isQueueEmpty = Object.keys(this.codeRequestsQueue).length == 0;
if (typeof this.codeRequestsQueue[key] != 'undefined') {
// There's already a pending request for this store and ID, add the promise to it.
this.codeRequestsQueue[key].deferreds.push(deferred);
} else {
// Add a pending request to the queue.
this.codeRequestsQueue[key] = {
table: table,
id: id,
deferreds: [deferred],
};
}
if (isQueueEmpty) {
this.processNextRequest();
}
return deferred.promise;
}
/**
* Reschedule all notifications that are already scheduled.
*
* @return Promise resolved when all notifications have been rescheduled.
*/
async rescheduleAll(): Promise<void> {
// Get all the scheduled notifications.
const notifications = await this.getAllScheduled();
await Promise.all(notifications.map(async (notification) => {
// Convert some properties to the needed types.
notification.data = this.parseNotificationData(notification.data);
const queueId = 'schedule-' + notification.id;
await this.queueRunner.run(queueId, () => this.scheduleNotification(notification), {
allowRepeated: true,
});
}));
}
/**
* Schedule a local notification.
*
* @param notification Notification to schedule. Its ID should be lower than 10000000 and it should
* be unique inside its component and site.
* @param component Component triggering the notification. It is used to generate unique IDs.
* @param siteId Site ID.
* @param alreadyUnique Whether the ID is already unique.
* @return Promise resolved when the notification is scheduled.
*/
async schedule(notification: ILocalNotification, component: string, siteId: string, alreadyUnique?: boolean): Promise<void> {
if (!alreadyUnique) {
notification.id = await this.getUniqueNotificationId(notification.id || 0, component, siteId);
}
notification.data = notification.data || {};
notification.data.component = component;
notification.data.siteId = siteId;
if (CoreApp.isAndroid()) {
notification.icon = notification.icon || 'res://icon';
notification.smallIcon = notification.smallIcon || 'res://smallicon';
notification.color = notification.color || CoreConstants.CONFIG.notificoncolor;
if (notification.led !== false) {
let ledColor = 'FF9900';
let ledOn = 1000;
let ledOff = 1000;
if (typeof notification.led === 'string') {
ledColor = notification.led;
} else if (Array.isArray(notification.led)) {
ledColor = notification.led[0] || ledColor;
ledOn = notification.led[1] || ledOn;
ledOff = notification.led[2] || ledOff;
} else if (typeof notification.led === 'object') {
ledColor = notification.led.color || ledColor;
ledOn = notification.led.on || ledOn;
ledOff = notification.led.off || ledOff;
}
notification.led = {
color: ledColor,
on: ledOn,
off: ledOff,
};
}
}
const queueId = 'schedule-' + notification.id;
await this.queueRunner.run(queueId, () => this.scheduleNotification(notification), {
allowRepeated: true,
});
}
/**
* Helper function to schedule a notification object if it hasn't been triggered already.
*
* @param notification Notification to schedule.
* @return Promise resolved when scheduled.
*/
protected async scheduleNotification(notification: ILocalNotification): Promise<void> {
// Check if the notification has been triggered already.
const triggered = await this.isTriggered(notification, false);
// Cancel the current notification in case it gets scheduled twice.
LocalNotifications.cancel(notification.id).finally(async () => {
if (!triggered) {
let soundEnabled: boolean;
// Check if sound is enabled for notifications.
if (!this.canDisableSound()) {
soundEnabled = true;
} else {
soundEnabled = await CoreConfig.get(CoreConstants.SETTINGS_NOTIFICATION_SOUND, true);
}
if (!soundEnabled) {
notification.sound = undefined;
} else {
delete notification.sound; // Use default value.
}
notification.foreground = true;
// Remove from triggered, since the notification could be in there with a different time.
this.removeTriggered(notification.id || 0);
LocalNotifications.schedule(notification);
}
});
}
/**
* Function to call when a notification is triggered. Stores the notification so it's not scheduled again unless the
* time is changed.
*
* @param notification Triggered notification.
* @return Promise resolved when stored, rejected otherwise.
*/
async trigger(notification: ILocalNotification): Promise<number> {
const db = await this.appDB;
const entry = {
id: notification.id,
at: notification.trigger && notification.trigger.at ? notification.trigger.at.getTime() : Date.now(),
};
return db.insertRecord(TRIGGERED_TABLE_NAME, entry);
}
/**
* Update a component name.
*
* @param oldName The old name.
* @param newName The new name.
* @return Promise resolved when done.
*/
async updateComponentName(oldName: string, newName: string): Promise<void> {
const db = await this.appDB;
const oldId = COMPONENTS_TABLE_NAME + '#' + oldName;
const newId = COMPONENTS_TABLE_NAME + '#' + newName;
await db.updateRecords(COMPONENTS_TABLE_NAME, { id: newId }, { id: oldId });
}
}
export const CoreLocalNotifications = makeSingleton(CoreLocalNotificationsProvider);
export type CoreLocalNotificationsClickCallback<T = unknown> = (value: T) => void; | the_stack |
import { observable, action } from 'mobx';
import { Injectable, Autowired } from '@opensumi/di';
import { IRecycleListHandler } from '@opensumi/ide-components';
import {
IPreferenceViewDesc,
IPreferenceSettingsService,
ISettingGroup,
ISettingSection,
PreferenceProviderProvider,
Emitter,
Event,
CommandService,
getDebugLogger,
isString,
getIcon,
PreferenceScope,
PreferenceProvider,
PreferenceSchemaProvider,
IDisposable,
arrays,
getAvailableLanguages,
PreferenceService,
replaceLocalizePlaceholder,
ThrottledDelayer,
TerminalSettingsId,
} from '@opensumi/ide-core-browser';
import { SearchSettingId } from '@opensumi/ide-core-common/lib/settings/search';
import { IFileServiceClient } from '@opensumi/ide-file-service';
import { toPreferenceReadableName, PreferenceSettingId, getPreferenceItemLabel } from '../common';
import { PREFERENCE_COMMANDS } from './preference-contribution';
const { addElement } = arrays;
@Injectable()
export class PreferenceSettingsService implements IPreferenceSettingsService {
private static DEFAULT_CHANGE_DELAY = 500;
@Autowired(PreferenceService)
protected readonly preferenceService: PreferenceService;
@Autowired(PreferenceSchemaProvider)
protected readonly schemaProvider: PreferenceSchemaProvider;
@Autowired(PreferenceProviderProvider)
protected readonly providerProvider: PreferenceProviderProvider;
@Autowired(IFileServiceClient)
protected readonly fileServiceClient: IFileServiceClient;
@Autowired(CommandService)
protected readonly commandService: CommandService;
@observable
public currentGroup = '';
@observable
public currentSearch = '';
private currentScope: PreferenceScope;
public setCurrentGroup(groupId: string) {
if (this.settingsGroups.find((n) => n.id === groupId)) {
this.currentGroup = groupId;
return;
}
getDebugLogger('Preference').warn('PreferenceService#setCurrentGroup is called with an invalid groupId:', groupId);
}
private settingsGroups: ISettingGroup[] = [];
private settingsSections: Map<string, ISettingSection[]> = new Map();
private enumLabels: Map<string, { [key: string]: string }> = new Map();
private cachedGroupSection: Map<string, ISettingSection[]> = new Map();
private _listHandler: IRecycleListHandler;
private onDidEnumLabelsChangeEmitter: Emitter<void> = new Emitter();
private enumLabelsChangeDelayer = new ThrottledDelayer<void>(PreferenceSettingsService.DEFAULT_CHANGE_DELAY);
private onDidSettingsChangeEmitter: Emitter<void> = new Emitter();
constructor() {
this.setEnumLabels(
'general.language',
new Proxy(
{},
{
get: (target, key) => getAvailableLanguages().find((l) => l.languageId === key)!.localizedLanguageName,
},
),
);
this.setEnumLabels('files.eol', {
'\n': 'LF',
'\r\n': 'CRLF',
auto: 'auto',
});
}
get onDidEnumLabelsChange() {
return this.onDidEnumLabelsChangeEmitter.event;
}
get onDidSettingsChange() {
return this.onDidSettingsChangeEmitter.event;
}
fireDidSettingsChange() {
this.onDidSettingsChangeEmitter.fire();
}
private isContainSearchValue(value: string, search: string) {
return value.toLocaleLowerCase().indexOf(search.toLocaleLowerCase()) > -1;
}
private filterPreferences(preference: string | IPreferenceViewDesc, scope: PreferenceScope): boolean {
return (
typeof preference !== 'string' &&
Array.isArray(preference.hiddenInScope) &&
preference.hiddenInScope.includes(scope)
);
}
@action
private doSearch(value) {
if (value) {
this.currentSearch = value;
} else {
this.currentSearch = '';
}
}
openJSON = (scope: PreferenceScope, preferenceId: string) => {
// 根据节点信息打开 Settings.json 配置文件
this.commandService.executeCommand(PREFERENCE_COMMANDS.OPEN_SOURCE_FILE.id, scope, preferenceId);
};
/**
* 设置某个作用域下的配置值
* @param key 配置Key
* @param value 配置值
* @param scope 作用域
*/
async setPreference(key: string, value: any, scope: PreferenceScope) {
await this.preferenceService.set(key, value, scope);
}
get listHandler() {
return this._listHandler;
}
handleListHandler = (handler: any) => {
this._listHandler = handler;
};
/**
* 获取搜索条件下展示的设置面板配置组
* @param scope 作用域
* @param search 搜索值
*/
getSettingGroups(scope: PreferenceScope, search?: string | undefined): ISettingGroup[] {
this.currentScope = scope;
const groups = this.settingsGroups.slice();
return groups.filter((g) => this.getSections(g.id, scope, search).length > 0);
}
async hasThisScopeSetting(scope: PreferenceScope) {
const url = await this.getPreferenceUrl(scope);
if (!url) {
return;
}
const exist = await this.fileServiceClient.access(url);
return exist;
}
/**
* 注册配置组
* @param group 配置组
*/
registerSettingGroup(group: ISettingGroup): IDisposable {
const disposable = addElement(this.settingsGroups, group);
this.fireDidSettingsChange();
return disposable;
}
/**
* 在某个配置组下注册配置项
* @param groupId 配置组ID
* @param section 配置项内容
*/
registerSettingSection(groupId: string, section: ISettingSection): IDisposable {
if (!this.settingsSections.has(groupId)) {
this.settingsSections.set(groupId, []);
}
this.cachedGroupSection.clear();
const disposable = addElement(this.settingsSections.get(groupId)!, section);
this.fireDidSettingsChange();
return disposable;
}
/**
* 通过配置项ID获取配置项展示信息
* @param preferenceId 配置项ID
*/
getSectionByPreferenceId(preferenceId: string) {
const groups = this.settingsSections.values();
for (const sections of groups) {
for (const section of sections) {
for (const preference of section.preferences) {
if (!isString(preference)) {
if (preference.id === preferenceId) {
return preference;
}
}
}
}
}
}
/**
* 获取特定作用域及搜索条件下的配置项
* @param groupId 配置组ID
* @param scope 作用域
* @param search 搜索条件
*/
getSections(groupId: string, scope: PreferenceScope, search?: string): ISettingSection[] {
const key = [groupId, scope, search || ''].join('-');
if (this.cachedGroupSection.has(key)) {
return this.cachedGroupSection.get(key)!;
}
const res = (this.settingsSections.get(groupId) || []).filter((section) => {
if (section.hiddenInScope && section.hiddenInScope.indexOf(scope) >= 0) {
return false;
} else {
return true;
}
});
const result: ISettingSection[] = [];
res.forEach((section) => {
if (section.preferences) {
const sec = { ...section };
sec.preferences = section.preferences.filter((pref) => {
if (this.filterPreferences(pref, scope)) {
return false;
}
if (!search) {
return true;
}
const prefId = typeof pref === 'string' ? pref : pref.id;
const schema = this.schemaProvider.getPreferenceProperty(prefId);
const prefLabel = typeof pref === 'string' ? toPreferenceReadableName(pref) : getPreferenceItemLabel(pref);
const description = schema && replaceLocalizePlaceholder(schema.description);
return (
this.isContainSearchValue(prefId, search) ||
this.isContainSearchValue(prefLabel, search) ||
(description && this.isContainSearchValue(description, search))
);
});
if (sec.preferences.length > 0) {
result.push(sec);
}
}
});
this.cachedGroupSection.set(key.toLocaleLowerCase(), result);
return result;
}
/**
* 获取某个配置名在特定作用域下的值
* @param preferenceName 配置名
* @param scope 作用域
* @param inherited 是否继承低优先级的配置值
*/
getPreference(
preferenceName: string,
scope: PreferenceScope,
inherited = false,
): { value: any; effectingScope: PreferenceScope } {
const { value } = this.preferenceService.resolve(preferenceName, undefined, undefined, undefined, scope) || {
value: undefined,
scope: PreferenceScope.Default,
};
const { scope: effectingScope } = this.preferenceService.resolve(preferenceName) || {
value: undefined,
scope: PreferenceScope.Default,
};
return {
value,
effectingScope: effectingScope || PreferenceScope.Default,
};
}
/**
* 获取某个配置名下存在的Enum枚举项
* @param preferenceName 配置名
*/
getEnumLabels(preferenceName: string): { [key: string]: string } {
return this.enumLabels.get(preferenceName) || {};
}
/**
* 设置某个配置名下的Enum枚举项
* @param preferenceName 配置名
* @param labels 枚举项
*/
setEnumLabels(preferenceName: string, labels: { [key: string]: string }) {
if (this.enumLabelsChangeDelayer && !this.enumLabelsChangeDelayer.isTriggered()) {
this.enumLabelsChangeDelayer.cancel();
}
this.enumLabelsChangeDelayer.trigger(async () => {
this.onDidEnumLabelsChangeEmitter.fire();
});
this.enumLabels.set(preferenceName, labels);
}
/**
* 重置某个配置项在特定作用域下的值
* @param preferenceName 配置名
* @param scope 作用域
*/
async reset(preferenceName: string, scope: PreferenceScope) {
await this.preferenceService.set(preferenceName, undefined, scope);
}
/**
* 获取特定作用域下的配置文件路径
* @param scope 作用域
*/
async getPreferenceUrl(scope: PreferenceScope) {
const preferenceProvider: PreferenceProvider = this.providerProvider(scope);
const resource = await preferenceProvider.resource;
if (resource) {
return resource.uri;
} else {
return preferenceProvider.getConfigUri()?.toString();
}
}
/**
* 获取当前面板下对应的配置文件路径
* @param scope 作用域
*/
async getCurrentPreferenceUrl(scope?: PreferenceScope) {
// 默认获取全局设置的URI
const url = await this.getPreferenceUrl(scope || this.currentScope || PreferenceScope.User)!;
if (!url) {
return;
}
const exist = await this.fileServiceClient.access(url);
if (!exist) {
const fileStat = await this.fileServiceClient.createFile(url);
if (fileStat) {
await this.fileServiceClient.setContent(fileStat!, '{\n}');
}
}
return url;
}
/**
* 在设置面板下搜索配置
* @param value 搜索值
*/
search = (value: string) => {
this.doSearch(value);
};
private readonly _onFocus: Emitter<void> = new Emitter<void>();
get onFocus(): Event<void> {
return this._onFocus.event;
}
focusInput() {
this._onFocus.fire();
}
}
export const defaultSettingGroup: ISettingGroup[] = [
{
id: PreferenceSettingId.General,
title: '%settings.group.general%',
iconClass: getIcon('setting'),
},
{
id: PreferenceSettingId.Editor,
title: '%settings.group.editor%',
iconClass: getIcon('editor'),
},
{
id: PreferenceSettingId.Terminal,
title: '%settings.group.terminal%',
iconClass: getIcon('terminal'),
},
{
id: PreferenceSettingId.Feature,
title: '%settings.group.feature%',
iconClass: getIcon('file-text'),
},
{
id: PreferenceSettingId.View,
title: '%settings.group.view%',
iconClass: getIcon('detail'),
},
];
export const defaultSettingSections: {
[key: string]: ISettingSection[];
} = {
general: [
{
preferences: [
{ id: 'general.theme', localized: 'preference.general.theme' },
{ id: 'general.icon', localized: 'preference.general.icon' },
{
id: 'general.language',
localized: 'preference.general.language',
hiddenInScope: [PreferenceScope.Workspace],
},
],
},
],
editor: [
{
preferences: [
// 预览模式
{ id: 'editor.previewMode' },
{
id: 'editor.enablePreviewFromCodeNavigation',
},
// 自动保存
{ id: 'editor.autoSave', localized: 'preference.editor.autoSave' },
{ id: 'editor.autoSaveDelay', localized: 'preference.editor.autoSaveDelay' },
{
id: 'workbench.refactoringChanges.showPreviewStrategy',
localized: 'preference.workbench.refactoringChanges.showPreviewStrategy.title',
},
{ id: 'editor.askIfDiff', localized: 'preference.editor.askIfDiff' },
// 光标样式
{ id: 'editor.cursorStyle', localized: 'preference.editor.cursorStyle' },
// 字体
{ id: 'editor.fontSize', localized: 'preference.editor.fontSize' },
{ id: 'editor.fontWeight', localized: 'preference.editor.fontWeight' },
{ id: 'editor.fontFamily', localized: 'preference.editor.fontFamily' },
{ id: 'editor.lineHeight', localized: 'preference.editor.lineHeight' },
{ id: 'editor.trimAutoWhitespace' },
// workbench
{ id: 'workbench.editorAssociations' },
// 补全
{ id: 'editor.suggest.insertMode' },
{ id: 'editor.suggest.filterGraceful' },
{ id: 'editor.suggest.localityBonus' },
{ id: 'editor.suggest.shareSuggestSelections' },
{ id: 'editor.suggest.snippetsPreventQuickSuggestions' },
{ id: 'editor.suggest.showIcons' },
{ id: 'editor.suggest.maxVisibleSuggestions' },
{ id: 'editor.suggest.showMethods' },
{ id: 'editor.suggest.showFunctions' },
{ id: 'editor.suggest.showConstructors' },
{ id: 'editor.suggest.showFields' },
{ id: 'editor.suggest.showVariables' },
{ id: 'editor.suggest.showClasses' },
{ id: 'editor.suggest.showStructs' },
{ id: 'editor.suggest.showInterfaces' },
{ id: 'editor.suggest.showModules' },
{ id: 'editor.suggest.showProperties' },
{ id: 'editor.suggest.showEvents' },
{ id: 'editor.suggest.showOperators' },
{ id: 'editor.suggest.showUnits' },
{ id: 'editor.suggest.showValues' },
{ id: 'editor.suggest.showConstants' },
{ id: 'editor.suggest.showEnums' },
{ id: 'editor.suggest.showEnumMembers' },
{ id: 'editor.suggest.showKeywords' },
{ id: 'editor.suggest.showWords' },
{ id: 'editor.suggest.showColors' },
{ id: 'editor.suggest.showFiles' },
{ id: 'editor.suggest.showReferences' },
{ id: 'editor.suggest.showCustomcolors' },
{ id: 'editor.suggest.showFolders' },
{ id: 'editor.suggest.showTypeParameters' },
{ id: 'editor.suggest.showSnippets' },
{ id: 'editor.suggest.showUsers' },
{ id: 'editor.suggest.showIssues' },
{ id: 'editor.suggest.preview' },
// Guides
{ id: 'editor.guides.bracketPairs', localized: 'preference.editor.guides.bracketPairs' },
{ id: 'editor.guides.indentation', localized: 'preference.editor.guides.indentation' },
{
id: 'editor.guides.highlightActiveIndentation',
localized: 'preference.editor.guides.highlightActiveIndentation',
},
// 行内补全
{ id: 'editor.inlineSuggest.enabled', localized: 'preference.editor.inlineSuggest.enabled' },
// 缩进
{ id: 'editor.detectIndentation', localized: 'preference.editor.detectIndentation' },
{ id: 'editor.tabSize', localized: 'preference.editor.tabSize' },
{ id: 'editor.insertSpaces', localized: 'preference.editor.insertSpace' },
// 显示
{ id: 'editor.wrapTab', localized: 'preference.editor.wrapTab' },
{ id: 'editor.wordWrap', localized: 'preference.editor.wordWrap' },
{ id: 'editor.renderLineHighlight', localized: 'preference.editor.renderLineHighlight' },
{ id: 'editor.renderWhitespace', localized: 'preference.editor.renderWhitespace' },
{ id: 'editor.minimap', localized: 'preference.editor.minimap' },
// 格式化
{ id: 'editor.preferredFormatter', localized: 'preference.editor.preferredFormatter' },
{ id: 'editor.formatOnSave', localized: 'preference.editor.formatOnSave' },
{ id: 'editor.formatOnSaveTimeout', localized: 'preference.editor.formatOnSaveTimeout' },
{ id: 'editor.formatOnPaste', localized: 'preference.editor.formatOnPaste' },
// 智能提示
{ id: 'editor.quickSuggestionsDelay', localized: 'preference.editor.quickSuggestionsDelay' },
// 文件
// `forceReadOnly` 选项暂时不对用户暴露
// {id: 'editor.forceReadOnly', localized: 'preference.editor.forceReadOnly'},
{ id: 'editor.maxTokenizationLineLength', localized: 'preference.editor.maxTokenizationLineLength' },
{ id: 'editor.largeFile', localized: 'preference.editor.largeFile' },
{ id: 'editor.readonlyFiles', localized: 'preference.editor.readonlyFiles' },
{
id: 'editor.bracketPairColorization.enabled',
localized: 'preference.editor.bracketPairColorization.enabled',
},
// Diff 编辑器
{ id: 'diffEditor.renderSideBySide', localized: 'preference.diffEditor.renderSideBySide' },
{ id: 'diffEditor.ignoreTrimWhitespace', localized: 'preference.diffEditor.ignoreTrimWhitespace' },
{ id: 'files.autoGuessEncoding', localized: 'preference.files.autoGuessEncoding.title' },
{ id: 'files.encoding', localized: 'preference.files.encoding.title' },
{ id: 'files.eol' },
{ id: 'files.trimFinalNewlines' },
{ id: 'files.trimTrailingWhitespace' },
{ id: 'files.insertFinalNewline' },
{ id: 'files.exclude', localized: 'preference.files.exclude.title' },
{ id: 'files.watcherExclude', localized: 'preference.files.watcherExclude.title' },
{ id: 'files.associations', localized: 'preference.files.associations.title' },
],
},
],
terminal: [
{
preferences: [
// 终端类型
{ id: TerminalSettingsId.Type, localized: 'preference.terminal.type' },
// 字体
{ id: TerminalSettingsId.FontFamily, localized: 'preference.terminal.fontFamily' },
{ id: TerminalSettingsId.FontSize, localized: 'preference.terminal.fontSize' },
{ id: TerminalSettingsId.FontWeight, localized: 'preference.terminal.fontWeight' },
{ id: TerminalSettingsId.LineHeight, localized: 'preference.terminal.lineHeight' },
// 光标
{ id: TerminalSettingsId.CursorBlink, localized: 'preference.terminal.cursorBlink' },
// 显示
{ id: TerminalSettingsId.Scrollback, localized: 'preference.terminal.scrollback' },
// 命令行参数
{ id: 'terminal.integrated.shellArgs.linux', localized: 'preference.terminal.integrated.shellArgs.linux' },
{ id: 'terminal.integrated.copyOnSelection', localized: 'preference.terminal.integrated.copyOnSelection' },
// Local echo
{ id: 'terminal.integrated.localEchoEnabled', localized: 'preference.terminal.integrated.localEchoEnabled' },
{
id: 'terminal.integrated.localEchoLatencyThreshold',
localized: 'preference.terminal.integrated.localEchoLatencyThreshold',
},
{
id: 'terminal.integrated.localEchoExcludePrograms',
localized: 'preference.terminal.integrated.localEchoExcludePrograms',
},
{ id: 'terminal.integrated.localEchoStyle', localized: 'preference.terminal.integrated.localEchoStyle' },
],
},
],
feature: [
{
preferences: [
// 树/列表项
{ id: 'workbench.list.openMode', localized: 'preference.workbench.list.openMode.title' },
{ id: 'explorer.autoReveal', localized: 'preference.explorer.autoReveal' },
// 搜索
{ id: SearchSettingId.Include },
{ id: SearchSettingId.Exclude, localized: 'preference.search.exclude.title' },
{ id: SearchSettingId.UseReplacePreview },
// { id: 'search.maxResults' },
{ id: SearchSettingId.SearchOnType },
{ id: SearchSettingId.SearchOnTypeDebouncePeriod },
// { id: 'search.showLineNumbers' },
// { id: 'search.smartCase' },
// { id: 'search.useGlobalIgnoreFiles' },
// { id: 'search.useIgnoreFiles' },
// { id: 'search.useParentIgnoreFiles' },
// { id: 'search.quickOpen.includeHistory' },
// { id: 'search.quickOpen.includeSymbols' },
// 输出
{ id: 'output.maxChannelLine', localized: 'output.maxChannelLine' },
{ id: 'output.enableLogHighlight', localized: 'output.enableLogHighlight' },
{ id: 'output.enableSmartScroll', localized: 'output.enableSmartScroll' },
// 调试
// 由于筛选器的匹配模式搜索存在性能、匹配难度大等问题,先暂时隐藏
// { id: 'debug.console.filter.mode', localized: 'preference.debug.console.filter.mode' },
{ id: 'debug.console.wordWrap', localized: 'preference.debug.console.wordWrap' },
{ id: 'debug.inline.values', localized: 'preference.debug.inline.values' },
],
},
],
view: [
{
preferences: [
// 资源管理器
{ id: 'explorer.fileTree.baseIndent', localized: 'preference.explorer.fileTree.baseIndent.title' },
{ id: 'explorer.fileTree.indent', localized: 'preference.explorer.fileTree.indent.title' },
{ id: 'explorer.compactFolders', localized: 'preference.explorer.compactFolders.title' },
// 运行与调试
{ id: 'debug.toolbar.float', localized: 'preference.debug.toolbar.float.title' },
// 布局信息
{ id: 'view.saveLayoutWithWorkspace', localized: 'preference.view.saveLayoutWithWorkspace.title' },
],
},
],
}; | the_stack |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="es">
<context>
<name>LC::Poshuku::WebKitView::CustomWebPage</name>
<message>
<location filename="customwebpage.cpp" line="237"/>
<source>Unable to send the request to %1. Please try submitting it again.</source>
<translation>No se puede enviar la solicitud a %1. Por favor, intente enviarlo de nuevo.</translation>
</message>
<message>
<location filename="customwebpage.cpp" line="463"/>
<source><a href="http://downforeveryoneorjustme.com/{host}" target="_blank">check</a> if the site <strong>{host}</strong> is down for you only;</source>
<comment>{host} would be substituded with site's host name.</comment>
<translation><a href="http://downforeveryoneorjustme.com/{host}" target="_blank">check</a> if the site <strong>{host}</strong> is down for you only;</translation>
</message>
<message>
<location filename="customwebpage.cpp" line="466"/>
<source>try again later</source>
<translation>Prueba despues de nuevo</translation>
</message>
<message>
<location filename="customwebpage.cpp" line="467"/>
<source>contact remote server's administrator (typically at <a href="mailto:webmaster@{host}">webmaster@{host}</a>)</source>
<translation>Contacta al administrador del servidor remoto (típicamente en <a href="mailto:webmaster@{host}">webmaster@{host}</a>)</translation>
</message>
<message>
<location filename="customwebpage.cpp" line="469"/>
<source>contact your system/network administrator, especially if you can't load any single page</source>
<translation>Contacta a vuestro sysadmin, si no puede cargar ninguna pagina</translation>
</message>
<message>
<location filename="customwebpage.cpp" line="471"/>
<source>check your proxy settings</source>
<translation>Verifica la configuración del proxy</translation>
</message>
<message>
<location filename="customwebpage.cpp" line="482"/>
<location filename="customwebpage.cpp" line="515"/>
<source>check if the URL is written correctly;</source>
<translation>Verifica que el URL esta escrito correctamente</translation>
</message>
<message>
<location filename="customwebpage.cpp" line="483"/>
<source>try changing your DNS servers;</source>
<translation>Prueba a cambiar los servidores DNS</translation>
</message>
<message>
<location filename="customwebpage.cpp" line="484"/>
<source>make sure that LeechCraft is allowed to access the Internet and particularly web sites;</source>
<translation>Asegurase de que a LeechCraft se le permite acceder a Internet y en particular los sitios web</translation>
</message>
<message>
<location filename="customwebpage.cpp" line="489"/>
<source>check whether some downloads consume too much bandwidth: try limiting their speed or reducing number of connections for them;</source>
<translation>Comprueba si algunas descargas consumen demasiado ancho de banda: trata de limitar su velocidad o reducir el número de conexiones para ellas;</translation>
</message>
<message>
<location filename="customwebpage.cpp" line="494"/>
<source>try again.</source>
<translation>prueba de nuevo.</translation>
</message>
<message>
<location filename="customwebpage.cpp" line="496"/>
<source>make sure that remote server is really what it claims to be;</source>
<translation>Asegurase de que el servidor remoto es realmente lo que dice ser;</translation>
</message>
<message>
<location filename="customwebpage.cpp" line="516"/>
<source>go to web site's <a href="{schema}://{host}/">main page</a> and find the required page from there.</source>
<translation>Va a la página del sitio web <a href="{schema}://{host}/"> principal </ a> y encuentra la pagina deseada desde alli.</translation>
</message>
<message>
<location filename="customwebpage.cpp" line="518"/>
<source>check the login and password you entered and try again</source>
<translation>Comprueba el login y contraseña y vuelva a intentarlo</translation>
</message>
<message>
<location filename="customwebpage.cpp" line="522"/>
<source>check if the URL is written correctly, particularly, the part before the '://';</source>
<translation>Comprueba que el URL esta escrito correctamente, sobre todo, la parte antes de '://';</translation>
</message>
<message>
<location filename="customwebpage.cpp" line="523"/>
<source>try installing plugins that are known to support this protocol;</source>
<translation>Trata de instalar plugins que se sabe que soportan este protocolo;</translation>
</message>
<message>
<location filename="customwebpage.cpp" line="563"/>
<source>Error loading %1</source>
<translation>Error leyendo %1</translation>
</message>
<message>
<location filename="customwebpage.cpp" line="568"/>
<source>%1 (%2)</source>
<translation>%1 (%2)</translation>
</message>
<message>
<location filename="customwebpage.cpp" line="573"/>
<source>%1</source>
<translation>%1</translation>
</message>
<message>
<location filename="customwebpage.cpp" line="575"/>
<source>The page you tried to access cannot be loaded now.</source>
<translation>La página que intentó acceder no se puede cargar ahora.</translation>
</message>
<message>
<location filename="customwebpage.cpp" line="582"/>
<source>Try doing the following:</source>
<translation>Trate de hacer lo siguiente:</translation>
</message>
</context>
<context>
<name>LC::Poshuku::WebKitView::CustomWebView</name>
<message>
<location filename="customwebview.cpp" line="168"/>
<location filename="customwebview.cpp" line="178"/>
<source>Loading...</source>
<translation>Cargando...</translation>
</message>
<message>
<location filename="customwebview.cpp" line="564"/>
<source>Installed plugins</source>
<translation>agregados instalados</translation>
</message>
<message>
<location filename="customwebview.cpp" line="565"/>
<source>No plugins installed</source>
<translation>No hay plugins instalados</translation>
</message>
<message>
<location filename="customwebview.cpp" line="566"/>
<source>File name</source>
<translation>Nombre del archivo</translation>
</message>
<message>
<location filename="customwebview.cpp" line="567"/>
<source>MIME type</source>
<translation>Tipo MIME</translation>
</message>
<message>
<location filename="customwebview.cpp" line="568"/>
<source>Description</source>
<translation>Descripción</translation>
</message>
<message>
<location filename="customwebview.cpp" line="569"/>
<source>Suffixes</source>
<translation>Sufijos</translation>
</message>
<message>
<location filename="customwebview.cpp" line="570"/>
<source>Enabled</source>
<translation>Habilitado</translation>
</message>
<message>
<location filename="customwebview.cpp" line="571"/>
<source>No</source>
<translation>No</translation>
</message>
<message>
<location filename="customwebview.cpp" line="572"/>
<source>Yes</source>
<translation>Si</translation>
</message>
<message>
<location filename="customwebview.cpp" line="590"/>
<location filename="customwebview.cpp" line="592"/>
<source>Welcome to LeechCraft!</source>
<translation>Bienvenido a LeechCraft!</translation>
</message>
<message>
<location filename="customwebview.cpp" line="594"/>
<source>Welcome to LeechCraft, the integrated internet-client.<br />More info is available on the <a href='https://leechcraft.org'>project's site</a>.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="customwebview.cpp" line="626"/>
<source>Print web page</source>
<translation>Imprimir página web</translation>
</message>
</context>
<context>
<name>LC::Poshuku::WebKitView::Plugin</name>
<message>
<location filename="webkitview.cpp" line="129"/>
<source>Provides QtWebKit-based backend for Poshuku.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>LC::Poshuku::WebKitView::SslStateDialog</name>
<message>
<location filename="sslstatedialog.cpp" line="56"/>
<source>SSL encryption is not used.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="sslstatedialog.cpp" line="60"/>
<source>Some SSL errors where encountered.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="sslstatedialog.cpp" line="64"/>
<source>Some elements were loaded via unencrypted connection.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="sslstatedialog.cpp" line="68"/>
<source>Everything is secure!</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>LC::Poshuku::WebKitView::WebViewSslWatcherHandler</name>
<message>
<location filename="webviewsslwatcherhandler.cpp" line="77"/>
<source>Some SSL errors where encountered.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="webviewsslwatcherhandler.cpp" line="81"/>
<source>Some elements were loaded via unencrypted connection.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="webviewsslwatcherhandler.cpp" line="85"/>
<source>Everything is secure!</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>QObject</name>
<message>
<location filename="interceptadaptor.cpp" line="162"/>
<source>Blocked</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="interceptadaptor.cpp" line="164"/>
<source>Blocked: %1</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>SslStateDialog</name>
<message>
<location filename="sslstatedialog.ui" line="14"/>
<source>SSL state</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="sslstatedialog.ui" line="55"/>
<source>Certificate information</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="sslstatedialog.ui" line="63"/>
<source>Certificate:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="sslstatedialog.ui" line="86"/>
<source>Insecure elements</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="sslstatedialog.ui" line="108"/>
<source>SSL errors</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>poshukuwebkitviewsettings</name>
<message>
<location filename="dummy.cpp" line="2"/>
<source>Poshuku WebKitView</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="dummy.cpp" line="3"/>
<source>General</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="dummy.cpp" line="4"/>
<source>Allow Java</source>
<translation>Permitir java</translation>
</message>
<message>
<location filename="dummy.cpp" line="5"/>
<source>Offline storage database</source>
<translation>Base de datos de almacenamiento offline</translation>
</message>
<message>
<location filename="dummy.cpp" line="6"/>
<source>Offline web application cache</source>
<translation>Web sin conexión caché de la aplicación</translation>
</message>
<message>
<location filename="dummy.cpp" line="7"/>
<source>Enable HTML5 notifications</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="dummy.cpp" line="8"/>
<source>Developer extras</source>
<translation>desarrollador extras</translation>
</message>
<message>
<location filename="dummy.cpp" line="9"/>
<source>Fix palettes with non-white background</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="dummy.cpp" line="10"/>
<source>User CSS URL:</source>
<translation>User CSS URL:</translation>
</message>
<message>
<location filename="dummy.cpp" line="11"/>
<location filename="dummy.cpp" line="12"/>
<source>Rendering</source>
<translation>Rendering</translation>
</message>
<message>
<location filename="dummy.cpp" line="13"/>
<source>Antialias primitives if possible</source>
<translation>Antialias primitivas, si es posible</translation>
</message>
<message>
<location filename="dummy.cpp" line="14"/>
<source>Antialias text if possible</source>
<translation>Suavizar texto si es posible</translation>
</message>
<message>
<location filename="dummy.cpp" line="15"/>
<source>Smooth pixmap transform</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="dummy.cpp" line="16"/>
<source>Security</source>
<translation>Seguridad</translation>
</message>
<message>
<location filename="dummy.cpp" line="17"/>
<source>Store local link history</source>
<translation>Almacenar el historial de enlace local</translation>
</message>
<message>
<location filename="dummy.cpp" line="18"/>
<source>Cache</source>
<translation>Caché</translation>
</message>
<message>
<location filename="dummy.cpp" line="19"/>
<source>Offline storage</source>
<translation>Almacenamiento fuera de línea</translation>
</message>
<message>
<location filename="dummy.cpp" line="20"/>
<source>Offline storage default quota:</source>
<translation>Almacenamiento fuera de línea cuota predeterminada:</translation>
</message>
<message>
<location filename="dummy.cpp" line="21"/>
<source> KB</source>
<translation> KB</translation>
</message>
<message>
<location filename="dummy.cpp" line="22"/>
<source>Clear favicon database</source>
<translation>Borrar la base de favicon datos</translation>
</message>
<message>
<location filename="dummy.cpp" line="23"/>
<source>In-memory</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="dummy.cpp" line="24"/>
<source>Prefetch DNS entries</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="dummy.cpp" line="25"/>
<source>Maximum pages:</source>
<translation>Páginas como máximo:</translation>
</message>
<message>
<location filename="dummy.cpp" line="26"/>
<source>Minimum dead capacity:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="dummy.cpp" line="27"/>
<location filename="dummy.cpp" line="29"/>
<location filename="dummy.cpp" line="31"/>
<source> MB</source>
<translation> MB</translation>
</message>
<message>
<location filename="dummy.cpp" line="28"/>
<source>Maximum dead capacity:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="dummy.cpp" line="30"/>
<source>Total capacity:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="dummy.cpp" line="32"/>
<source>Clear in-memory caches</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS> | the_stack |
import * as Octokit from '@octokit/rest'
import * as fs from 'fs'
import * as inquirer from 'inquirer'
import { openUrl, getCurrentFolderName, userRanValidFlags } from '../utils'
import * as url from 'url'
import * as base from '../base'
import * as git from '../git'
import { produce } from 'immer'
import { afterHooks, beforeHooks } from '../hooks'
import * as logger from '../logger'
const config = base.getConfig()
// -- Constants ------------------------------------------------------------------------------------
export const name = 'Repo'
export const DETAILS = {
alias: 're',
description: 'Provides a set of util commands to work with Repositories.',
commands: ['browser', 'clone', 'delete', 'fork', 'list', 'new', 'update', 'search'],
options: {
browser: Boolean,
clone: Boolean,
color: String,
date: String,
delete: String,
description: String,
detailed: Boolean,
gitignore: String,
fork: String,
homepage: String,
init: Boolean,
label: Boolean,
list: Boolean,
new: String,
organization: String,
page: String,
per_page: String,
private: Boolean,
protocol: String,
repo: String,
search: String,
type: ['all', 'forks', 'member', 'owner', 'public', 'private', 'source'],
update: String,
user: String,
},
shorthands: {
B: ['--browser'],
c: ['--clone'],
C: ['--color'],
D: ['--delete'],
d: ['--detailed'],
f: ['--fork'],
L: ['--label'],
l: ['--list'],
N: ['--new'],
O: ['--organization'],
p: ['--private'],
P: ['--protocol'],
r: ['--repo'],
s: ['--search'],
t: ['--type'],
U: ['--update'],
u: ['--user'],
},
}
const TYPE_ALL = 'all'
const TYPE_OWNER = 'owner'
const TYPE_PRIVATE = 'private'
// -- Commands -------------------------------------------------------------------------------------
export async function run(options, done) {
let user = options.loggedUser
options = produce(options, draft => {
if (
!userRanValidFlags(DETAILS.commands, draft) &&
draft.browser !== false &&
draft.argv.cooked.length === 1
) {
draft.browser = true
}
})
if (options.browser) {
browser(options.user, options.repo)
} else if (options.delete && !options.label) {
await beforeHooks('repo.delete', { options })
logger.log(`Deleting repo ${logger.colors.green(`${options.user}/${options.delete}`)}`)
const answers = await inquirer.prompt([
{
type: 'input',
message: 'Are you sure? This action CANNOT be undone. [y/N]',
name: 'confirmation',
},
])
if (answers.confirmation.toLowerCase() === 'y') {
try {
const { status } = await deleteRepo(options, options.user, options.delete)
status === 204 &&
logger.log(`${logger.colors.green('✓')} Successfully deleted repo.`)
} catch (err) {
logger.error(`${logger.colors.red('✗')} Can't delete repo.\n${err}`)
}
await afterHooks('repo.delete', { options })
} else {
logger.log(`${logger.colors.red('✗')} Not deleted.`)
}
} else if (options.fork) {
await beforeHooks('repo.fork', { options })
if (options.organization) {
user = options.organization
}
options = produce(options, draft => {
draft.repo = draft.fork
})
logger.log(
`Forking repo ${logger.colors.green(
`${options.user}/${options.repo}`
)} into ${logger.colors.green(`${user}/${options.repo}`)}`
)
try {
var { data: forkData } = await fork(options)
} catch (err) {
throw new Error(`Can't fork. ${err}`)
}
logger.log(`Successfully forked: ${forkData.html_url}`)
if (forkData && options.clone) {
clone_(user, options.repo, forkData.ssh_url)
}
await afterHooks('repo.fork', { options })
} else if (options.label) {
if (options.organization) {
user = options.organization
} else if (options.user) {
user = options.user
}
if (options.delete) {
await beforeHooks('repo.deleteLabel', { options })
options = produce(options, draft => {
draft.label = draft.delete
})
logger.log(
`Deleting label ${logger.colors.green(options.label)} on ${logger.colors.green(
`${user}/${options.repo}`
)}`
)
try {
var { status } = await deleteLabel(options, user)
} catch (err) {
throw new Error(`Can't delete label.\n${err}`)
}
status === 204 && logger.log('Successful.')
await afterHooks('repo.deleteLabel', { options })
} else if (options.list) {
await beforeHooks('repo.listLabels', { options })
if (options.page) {
logger.log(
`Listing labels from page ${logger.colors.green(
options.page
)} on ${logger.colors.green(`${user}/${options.repo}`)}`
)
} else {
logger.log(`Listing labels on ${logger.colors.green(`${user}/${options.repo}`)}`)
}
try {
var { data: labelData } = await listLabels(options, user)
} catch (err) {
throw new Error(`Can't list labels\n${err}`)
}
labelData.forEach(label => logger.log(logger.colors.yellow(label.name)))
await afterHooks('repo.listLabels', { options })
} else if (options.new) {
await beforeHooks('repo.createLabel', { options })
options = produce(options, draft => {
draft.label = draft.new
})
logger.log(
`Creating label ${logger.colors.green(options.label)} on ${logger.colors.green(
`${user}/${options.repo}`
)}`
)
try {
await createLabel(options, user)
} catch (err) {
throw new Error(`Can't create label.\n${err}`)
}
await afterHooks('repo.createLabel', { options })
} else if (options.update) {
await beforeHooks('repo.updateLabel', { options })
options = produce(options, draft => {
draft.label = draft.update
})
logger.log(
`Updating label ${logger.colors.green(options.label)} on ${logger.colors.green(
`${user}/${options.repo}`
)}`
)
try {
var { status } = await updateLabel(options, user)
} catch (err) {
throw new Error(`Can't update label.\n${err}`)
}
status === 200 && logger.log('Success')
await afterHooks('repo.updateLabel', { options })
}
} else if (options.list && !options.label) {
await beforeHooks('repo.list', { options })
options = produce(options, draft => {
if (draft.organization) {
user = options.organization
draft.type = draft.type || TYPE_ALL
} else {
user = draft.user
draft.type = draft.type || TYPE_OWNER
}
})
// Add a isTTY value on the options to determine whether or not the command is executed in a TTY context or not.
// Will be false if cmd is piped like: gh re --list | cat
if (Boolean(process.stdout.isTTY)) {
logger.log(
`Listing ${logger.colors.green(options.type)} repos for ${logger.colors.green(
user
)}`
)
}
try {
var listData = await list(options, user)
} catch (err) {
throw new Error(`Can't list repos.\n${err}`)
}
listCallback_(options, listData)
await afterHooks('repo.list', { options })
} else if (options.search) {
await beforeHooks('repo.search', { options })
let type = options.type || TYPE_OWNER
if (options.organization) {
type = options.type || TYPE_ALL
}
const query = buildSearchQuery(options, type)
logger.log(`Searching for repos using the criteria: ${logger.colors.green(query)}`)
try {
await search(options, query)
} catch (error) {
logger.error(`Can't list repos.\n${error}`)
}
await afterHooks('repo.search', { options })
} else if (options.clone && !options.new && options.new !== '') {
await beforeHooks('repo.get', { options })
if (options.organization) {
user = options.organization
} else if (options.user) {
user = options.user
}
if (fs.existsSync(`${process.cwd()}/${options.repo}`)) {
logger.error(
`Can't clone ${logger.colors.green(
`${user}/${options.repo}`
)}. ${logger.colors.green(options.repo)} already exists in this directory.`
)
return
}
try {
var { data } = await getRepo(options)
} catch (err) {
throw new Error(
`Can't clone ${logger.colors.green(`${user}/${options.repo}`)}.\n${err}`
)
}
logger.log(data.html_url)
if (data) {
clone_(user, options.repo, getCloneUrl(options, config.api.ssh_host))
}
await afterHooks('repo.get', { options })
} else if ((options.new || options.new === '') && !options.label) {
if (!options.new.trim()) {
options = produce(options, draft => {
draft.new = getCurrentFolderName()
})
}
await beforeHooks('repo.new', { options })
options = produce(options, draft => {
draft.repo = draft.new
if (draft.organization) {
draft.user = draft.organization
}
})
logger.log(
`Creating a new repo on ${logger.colors.green(`${options.user}/${options.new}`)}`
)
try {
var { data: repoData, options: updatedOptions } = await newRepo(options)
} catch (err) {
throw new Error(`Can't create new repo.\n${err}`)
}
logger.log(repoData.html_url)
if (repoData && options.clone) {
clone_(options.user, options.repo, repoData.ssh_url)
}
await afterHooks('repo.new', { options: updatedOptions })
}
done && done()
}
function browser(user, repo) {
openUrl(`${config.github_host}/${user}/${repo}`)
}
/**
* If the current directory where gh was run from matches the repo name
* we will clone into the current directory
* otherwise we will clone into a new directory
*/
function clone_(user: string, repo: string, repoUrl: string): void {
const currentDir = process.cwd()
const currentDirName = currentDir.slice(currentDir.lastIndexOf('/') + 1)
const cloneUrl = url.parse(repoUrl).href
logger.log(`Cloning ${logger.colors.green(`${user}/${repo}`)}`)
git.clone(cloneUrl, currentDirName === repo ? '.' : repo)
}
function createLabel(options, user): Promise<Octokit.IssuesCreateLabelResponse> {
const payload: Octokit.IssuesCreateLabelParams = {
owner: user,
color: normalizeColor(options.color),
name: options.new,
repo: options.repo,
}
if (options.description) {
payload.description = options.description
}
return options.GitHub.issues.createLabel(payload)
}
function deleteRepo(options, user, repo): Promise<Octokit.Response<Octokit.ReposDeleteResponse>> {
const payload = {
repo,
owner: user,
}
return options.GitHub.repos.delete(payload)
}
function deleteLabel(options, user): Promise<Octokit.Response<Octokit.IssuesDeleteLabelResponse>> {
const payload = {
owner: user,
name: options.delete,
repo: options.repo,
}
return options.GitHub.issues.deleteLabel(payload)
}
/**
* If user has a custom git_host defined we will use that (helpful for custom ssh rules).
* Otherwise pluck it from the previously set up github_host.
*/
interface CloneOptions {
repo: string
user: string
protocol?: string
github_host?: string
}
type GetCloneUrl = (options: CloneOptions, customSshHost?: string) => string
export const getCloneUrl: GetCloneUrl = ({ repo, user, protocol, github_host }, customSshHost) => {
const hostWithoutProtocol = github_host.split('://')[1]
let repoUrl = `git@${customSshHost || hostWithoutProtocol}:${user}/${repo}.git`
if (protocol === 'https') {
repoUrl = `https://${hostWithoutProtocol}/${user}/${repo}.git`
}
return repoUrl
}
function getRepo(options): Promise<Octokit.Response<Octokit.IssuesGetResponse>> {
const payload = {
repo: options.repo,
owner: options.user,
}
return options.GitHub.repos.get(payload)
}
function list(options, user): Promise<Octokit.AnyResponse | Octokit.ReposListForOrgResponse> {
let method = 'listForUser'
const payload: any = {
type: options.type,
}
if (options.organization) {
method = 'listForOrg'
payload.org = options.organization
} else {
payload.username = options.user
}
if (options.type === 'public' || options.type === 'private') {
if (user === options.user) {
method = 'listForUser'
} else {
logger.error('You can only list your own public and private repos.')
return
}
}
return options.GitHub.paginate(options.GitHub.repos[method].endpoint(payload))
}
function listCallback_(options, repos): void {
let pos
let repo
if (repos && repos.length > 0) {
for (pos in repos) {
if (repos.hasOwnProperty(pos) && repos[pos].full_name) {
repo = repos[pos]
logger.log(repo.full_name)
if (options.detailed) {
logger.log(logger.colors.blue(repo.html_url))
if (repo.description) {
logger.log(logger.colors.blue(repo.description))
}
if (repo.homepage) {
logger.log(logger.colors.blue(repo.homepage))
}
logger.log(`last update ${logger.getDuration(repo.updated_at, options.date)}`)
}
if (Boolean(process.stdout.isTTY)) {
logger.log(
`${logger.colors.green(
`forks: ${repo.forks}, stars: ${repo.watchers}, issues: ${
repo.open_issues
}`
)}\n`
)
}
}
}
}
}
function listLabels(
options,
user
): Promise<Octokit.Response<Octokit.IssuesListLabelsForRepoResponse>> {
const payload: Octokit.IssuesListLabelsForRepoParams = {
owner: user,
repo: options.repo,
...(options.page && { page: options.page }),
...(options.per_page && { per_page: options.per_page }),
}
return options.GitHub.issues.listLabelsForRepo(payload)
}
function fork(options): Promise<Octokit.Response<Octokit.ReposCreateForkResponse>> {
const payload: Octokit.ReposCreateForkParams = {
owner: options.user,
repo: options.repo,
}
if (options.organization) {
payload.organization = options.organization
}
return options.GitHub.repos.createFork(payload)
}
async function newRepo(options) {
let method = 'createForAuthenticatedUser'
options = produce(options, draft => {
draft.description = draft.description || ''
draft.gitignore = draft.gitignore || ''
draft.homepage = draft.homepage || ''
draft.init = draft.init || false
if (draft.type === TYPE_PRIVATE) {
draft.private = true
}
draft.private = draft.private || false
if (draft.gitignore) {
draft.init = true
}
})
const payload: any = {
auto_init: options.init,
description: options.description,
gitignore_template: options.gitignore,
homepage: options.homepage,
name: options.new,
private: options.private,
}
if (options.organization) {
method = 'createInOrg'
payload.org = options.organization
}
const { data } = await options.GitHub.repos[method](payload)
return { data, options }
}
function updateLabel(options, user): Promise<Octokit.Response<Octokit.IssuesUpdateLabelResponse>> {
const payload: Octokit.IssuesUpdateLabelParams = {
owner: user,
color: normalizeColor(options.color),
current_name: options.update,
repo: options.repo,
}
return options.GitHub.issues.updateLabel(payload)
}
function buildSearchQuery(options, type) {
let terms = [options.search]
if (options.argv.original.some(arg => arg === '-u' || arg === '--user')) {
terms.push(`user:${options.user}`)
}
if (options.organization) {
terms.push(`org:${options.organization}`)
}
if (type === 'public' || type === 'private') {
terms.push(`is:${type}`)
}
// add remaining search terms
terms = terms.concat(options.argv.remain.slice(1))
return terms.join(' ')
}
async function search(options, query: string) {
const payload = {
q: query,
per_page: 30,
}
const { data } = await options.GitHub.search.repos(payload)
listCallback_(options, data.items)
}
function normalizeColor(color) {
return color.includes('#') ? color.replace('#', '') : color
} | the_stack |
import { Utils } from '@rpgjs/common'
import { Effect } from '@rpgjs/database'
import { ItemLog } from '../logs'
import { ItemModel } from '../models/Item'
import { EffectManager } from './EffectManager'
import { GoldManager } from './GoldManager'
import { StateManager } from './StateManager'
import {
ATK,
PDEF,
SDEF
} from '../presets'
const {
isString,
isInstanceOf,
applyMixins
} = Utils
type ItemClass = { new(...args: any[]), price?: number, _type?: string }
type Inventory = { nb: number, item: ItemModel }
export class ItemManager {
items: Inventory[]
equipments: ItemModel[] = []
/**
* Retrieves the information of an object: the number and the instance
* @title Get Item
* @method player.getItem(itemClass)
* @param {ItemClass | string} itemClass Identifier of the object if the parameter is a string
* @returns {{ nb: number, item: instance of ItemClass }}
* @memberof ItemManager
* @example
*
* ```ts
* import Potion from 'your-database/potion'
*
* player.addItem(Potion, 5)
* const inventory = player.getItem(Potion)
* console.log(inventory) // { nb: 5, item: <instance of Potion> }
* ```
*/
getItem(itemClass: ItemClass | string): Inventory {
const index: number = this._getItemIndex(itemClass)
return this.items[index]
}
/**
* Check if the player has the item in his inventory.
* @title Has Item
* @method player.hasItem(itemClass)
* @param {ItemClass | string} itemClass Identifier of the object if the parameter is a string
* @returns {boolean}
* @memberof ItemManager
* @example
*
* ```ts
* import Potion from 'your-database/potion'
*
* player.hasItem(Potion) // false
* ```
*/
hasItem(itemClass: ItemClass | string): boolean {
return !!this.getItem(itemClass)
}
_getItemIndex(itemClass: ItemClass | string): number {
return this.items.findIndex((it: Inventory): boolean => {
if (isString(itemClass)) {
return it.item.id == itemClass
}
return isInstanceOf(it.item, itemClass)
})
}
/**
* Add an item in the player's inventory. You can give more than one by specifying `nb`
*
* `onAdd()` method is called on the ItemClass
*
* @title Add Item
* @method player.addItem(item,nb=1)
* @param {ItemClass} itemClass
* @param {number} [nb] Default 1
* @returns {{ nb: number, item: instance of ItemClass }}
* @memberof ItemManager
* @example
*
* ```ts
* import Potion from 'your-database/potion'
* player.addItem(Potion, 5)
* ```
*/
addItem(itemClass: ItemClass, nb: number = 1): Inventory {
let itemIndex: number = this._getItemIndex(itemClass)
if (itemIndex != -1) {
this.items[itemIndex].nb += nb
}
else {
const instance = new itemClass()
this.items.push({
item: instance,
nb
})
itemIndex = this.items.length - 1
}
const { item } = this.items[itemIndex]
this['execMethod']('onAdd', [this], item)
return this.items[itemIndex]
}
/**
* Deletes an item. Decreases the value `nb`. If the number falls to 0, then the item is removed from the inventory. The method then returns `undefined`
*
* `onRemove()` method is called on the ItemClass
*
* @title Remove Item
* @method player.removeItem(item,nb=1)
* @param {ItemClass | string} itemClass string is item id
* @param {number} [nb] Default 1
* @returns {{ nb: number, item: instance of ItemClass } | undefined}
* @throws {ItemLog} notInInventory
* If the object is not in the inventory, an exception is raised
* ```
* {
* id: ITEM_NOT_INVENTORY,
* msg: '...'
* }
* ```
* @memberof ItemManager
* @example
*
* ```ts
* import Potion from 'your-database/potion'
*
* try {
* player.removeItem(Potion, 5)
* }
* catch (err) {
* console.log(err)
* }
* ```
*/
removeItem(itemClass: ItemClass | string, nb: number = 1): Inventory | undefined {
const itemIndex: number = this._getItemIndex(itemClass)
if (itemIndex == -1) {
throw ItemLog.notInInventory(itemClass)
}
const currentNb: number = this.items[itemIndex].nb
const { item } = this.items[itemIndex]
if (currentNb - nb <= 0) {
this.items.splice(itemIndex, 1)
}
else {
this.items[itemIndex].nb -= nb
}
this['execMethod']('onRemove', [this], item)
return this.items[itemIndex]
}
/**
* Purchases an item and reduces the amount of gold
*
* `onAdd()` method is called on the ItemClass
*
* @title Buy Item
* @method player.buyItem(item,nb=1)
* @param {ItemClass | string} itemClass string is item id
* @param {number} [nb] Default 1
* @returns {{ nb: number, item: instance of ItemClass }}
* @throws {ItemLog} haveNotPrice
* If you have not set a price on the item
* ```
* {
* id: NOT_PRICE,
* msg: '...'
* }
* ```
* @throws {ItemLog} notEnoughGold
* If the player does not have enough money
* ```
* {
* id: NOT_ENOUGH_GOLD,
* msg: '...'
* }
* ```
* @memberof ItemManager
* @example
*
* ```ts
* import Potion from 'your-database/potion'
*
* try {
* player.buyItem(Potion)
* }
* catch (err) {
* console.log(err)
* }
* ```
*/
buyItem(itemClass: ItemClass | string, nb = 1): Inventory {
if (isString(itemClass)) itemClass = this.databaseById(itemClass)
const ItemClass = itemClass as ItemClass
if (!ItemClass.price) {
throw ItemLog.haveNotPrice(itemClass)
}
const totalPrice = nb * ItemClass.price
if (this.gold < totalPrice) {
throw ItemLog.notEnoughGold(itemClass, nb)
}
this.gold -= totalPrice
return this.addItem(ItemClass, nb)
}
/**
* Sell an item and the player wins the amount of the item divided by 2
*
* `onRemove()` method is called on the ItemClass
*
* @title Sell Item
* @method player.sellItem(item,nb=1)
* @param {ItemClass | string} itemClass string is item id
* @param {number} [nbToSell] Default 1
* @returns {{ nb: number, item: instance of ItemClass }}
* @throws {ItemLog} haveNotPrice
* If you have not set a price on the item
* ```
* {
* id: NOT_PRICE,
* msg: '...'
* }
* ```
* @throws {ItemLog} notInInventory
* If the object is not in the inventory, an exception is raised
* ```
* {
* id: ITEM_NOT_INVENTORY,
* msg: '...'
* }
* ```
* @throws {ItemLog} tooManyToSell
* If the number of items for sale exceeds the number of actual items in the inventory
* ```
* {
* id: TOO_MANY_ITEM_TO_SELL,
* msg: '...'
* }
* ```
* @memberof ItemManager
* @example
*
* ```ts
* import Potion from 'your-database/potion'
*
* try {
* player.addItem(Potion)
* player.sellItem(Potion)
* }
* catch (err) {
* console.log(err)
* }
* ```
*/
sellItem(itemClass: ItemClass | string, nbToSell = 1): Inventory {
if (isString(itemClass)) itemClass = this.databaseById(itemClass)
const ItemClass = itemClass as ItemClass
const inventory = this.getItem(ItemClass)
if (!inventory) {
throw ItemLog.notInInventory(itemClass)
}
const { item, nb } = inventory
if (nb - nbToSell < 0) {
throw ItemLog.tooManyToSell(itemClass, nbToSell, nb)
}
if (!ItemClass.price) {
throw ItemLog.haveNotPrice(itemClass)
}
this.gold += (ItemClass.price / 2) * nbToSell
this.removeItem(ItemClass, nbToSell)
return inventory
}
private getParamItem(name) {
let nb = 0
for (let item of this.equipments) {
nb += item[name] || 0
}
const modifier = this.paramsModifier[name]
if (modifier) {
if (modifier.value) nb += modifier.value
if (modifier.rate) nb *= modifier.rate
}
return nb
}
get atk(): number {
return this.getParamItem(ATK)
}
get pdef(): number {
return this.getParamItem(PDEF)
}
get sdef(): number {
return this.getParamItem(SDEF)
}
/**
* Use an object. Applies effects and states. Removes the object from the inventory then
*
* `onUse()` method is called on the ItemClass (If the use has worked)
* `onRemove()` method is called on the ItemClass
*
* @title Use an Item
* @method player.useItem(item,nb=1)
* @param {ItemClass | string} itemClass string is item id
* @returns {{ nb: number, item: instance of ItemClass }}
* @throws {ItemLog} restriction
* If the player has the `Effect.CAN_NOT_ITEM` effect
* ```
* {
* id: RESTRICTION_ITEM,
* msg: '...'
* }
* ```
* @throws {ItemLog} notInInventory
* If the object is not in the inventory, an exception is raised
* ```
* {
* id: ITEM_NOT_INVENTORY,
* msg: '...'
* }
* ```
* @throws {ItemLog} notUseItem
* If the `consumable` property is on false
* ```
* {
* id: NOT_USE_ITEM,
* msg: '...'
* }
* ```
* @throws {ItemLog} chanceToUseFailed
* Chance to use the item has failed. Chances of use is defined with `ItemClass.hitRate`
* ```
* {
* id: USE_CHANCE_ITEM_FAILED,
* msg: '...'
* }
* ```
* > the item is still deleted from the inventory
*
* `onUseFailed()` method is called on the ItemClass
*
* @memberof ItemManager
* @example
*
* ```ts
* import Potion from 'your-database/potion'
*
* try {
* player.addItem(Potion)
* player.useItem(Potion)
* }
* catch (err) {
* console.log(err)
* }
* ```
*/
useItem(itemClass: ItemClass | string): Inventory {
const inventory = this.getItem(itemClass)
if (this.hasEffect(Effect.CAN_NOT_ITEM)) {
throw ItemLog.restriction(itemClass)
}
if (!inventory) {
throw ItemLog.notInInventory(itemClass)
}
const { item } = inventory
if (item.consumable === false) {
throw ItemLog.notUseItem(itemClass)
}
const hitRate = item.hitRate || 1
if (Math.random() > hitRate) {
this.removeItem(itemClass)
this['execMethod']('onUseFailed', [this], item)
throw ItemLog.chanceToUseFailed(itemClass)
}
this.applyEffect(item)
this.applyStates(<any>this, <any>item)
this['execMethod']('onUse', [this], item)
this.removeItem(itemClass)
return inventory
}
/**
* Equips a weapon or armor on a player. Think first to add the item in the inventory with the `addItem()` method before equipping the item.
*
* `onEquip()` method is called on the ItemClass
*
* @title Equip Weapon or Armor
* @method player.equip(itemClass,equip=true)
* @param {ItemClass | string} itemClass string is item id
* @param {number} [equip] Equip the object if true or un-equipped if false
* @returns {void}
* @throws {ItemLog} notInInventory
* If the item is not in the inventory
* ```
{
id: ITEM_NOT_INVENTORY,
msg: '...'
}
```
* @throws {ItemLog} invalidToEquiped
If the item is not by a weapon or armor
```
{
id: INVALID_ITEM_TO_EQUIP,
msg: '...'
}
```
* @throws {ItemLog} isAlreadyEquiped
If the item Is already equipped
```
{
id: ITEM_ALREADY_EQUIPED,
msg: '...'
}
```
* @memberof ItemManager
* @example
*
* ```ts
* import Sword from 'your-database/sword'
*
* try {
* player.addItem(Sword)
* player.equip(Sword)
* }
* catch (err) {
* console.log(err)
* }
* ```
*/
equip(itemClass: ItemClass | string, equip: boolean = true): void {
const inventory: Inventory = this.getItem(itemClass)
if (!inventory) {
throw ItemLog.notInInventory(itemClass)
}
if ((itemClass as ItemClass)._type == 'item') {
throw ItemLog.invalidToEquiped(itemClass)
}
const { item } = inventory
if (item.equipped && equip) {
throw ItemLog.isAlreadyEquiped(itemClass)
}
item.equipped = equip
if (!equip) {
const index = this.equipments.findIndex(it => it.id == item.id)
this.equipments.splice(index, 1)
}
else {
this.equipments.push(item)
}
this['execMethod']('onEquip', [this, equip], item)
}
}
applyMixins(ItemManager, [GoldManager, StateManager, EffectManager])
export interface ItemManager extends GoldManager, StateManager, EffectManager {
databaseById(itemClass: any),
} | the_stack |
import {
useCallbackRef,
useDeepMemo,
useEventCallback,
useFirstMount,
useIsomorphicLayoutEffect,
} from '@fluentui/react-bindings';
import * as PopperJs from '@popperjs/core';
import * as React from 'react';
import { getReactFiberFromNode } from '../getReactFiberFromNode';
import { isBrowser } from '../isBrowser';
import { getBoundary } from './getBoundary';
import { getScrollParent } from './getScrollParent';
import { applyRtlToOffset, getPlacement } from './positioningHelper';
import { PopperInstance, PopperOptions } from './types';
//
// Dev utils to detect if nodes have "autoFocus" props.
//
/**
* Detects if a passed HTML node has "autoFocus" prop on a React's fiber. Is needed as React handles autofocus behavior
* in React DOM and will not pass "autoFocus" to an actual HTML.
*
* @param {Node} node
* @returns {Boolean}
*/
function hasAutofocusProp(node: Node): boolean {
// https://github.com/facebook/react/blob/848bb2426e44606e0a55dfe44c7b3ece33772485/packages/react-dom/src/client/ReactDOMHostConfig.js#L157-L166
const isAutoFocusableElement =
node.nodeName === 'BUTTON' ||
node.nodeName === 'INPUT' ||
node.nodeName === 'SELECT' ||
node.nodeName === 'TEXTAREA';
if (isAutoFocusableElement) {
return !!getReactFiberFromNode(node).pendingProps.autoFocus;
}
return false;
}
function hasAutofocusFilter(node: Node) {
return hasAutofocusProp(node) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
}
/**
* Provides a callback to resolve Popper options, it's stable and should be used as a dependency to trigger updates
* of Popper options.
*
* A callback is used there intentionally as some of Popper.js modifiers require DOM nodes (targer, container, arrow)
* that can't be resolved properly during an initial rendering.
*
* @param {PopperOptions} options
* @param {React.MutableRefObject} popperOriginalPositionRef
*
* @returns {Function}
*/
function usePopperOptions(options: PopperOptions, popperOriginalPositionRef: React.MutableRefObject<string>) {
const {
autoSize,
flipBoundary,
offset,
onStateUpdate,
overflowBoundary,
rtl,
unstable_disableTether,
unstable_pinned,
} = options;
const placement = getPlacement(options.align, options.position, options.rtl);
const strategy = options.positionFixed ? 'fixed' : 'absolute';
const handleStateUpdate = useEventCallback(({ state }: { state: Partial<PopperJs.State> }) => {
if (onStateUpdate) {
onStateUpdate(state);
}
});
const offsetModifier = React.useMemo(
() =>
offset
? {
name: 'offset',
options: { offset: rtl ? applyRtlToOffset(offset) : offset },
}
: null,
[offset, rtl],
);
const userModifiers = useDeepMemo(() => options.modifiers, options.modifiers);
return React.useCallback(
(
target: HTMLElement | PopperJs.VirtualElement,
container: HTMLElement,
arrow: HTMLElement | null,
): PopperJs.Options => {
const scrollParentElement: HTMLElement = getScrollParent(container);
const hasScrollableElement = scrollParentElement
? scrollParentElement !== scrollParentElement.ownerDocument.body
: false;
const modifiers: PopperJs.Options['modifiers'] = [
/**
* We are setting the position to `fixed` in the first effect to prevent scroll jumps in case of the content
* with managed focus. Modifier sets the position to `fixed` before all other modifier effects. Another part of
* a patch modifies ".forceUpdate()" directly after a Popper will be created.
*/
{
name: 'positionStyleFix',
enabled: true,
phase: 'afterWrite' as PopperJs.ModifierPhases,
effect: ({ state, instance }: { state: Partial<PopperJs.State>; instance: PopperInstance }) => {
// ".isFirstRun" is a part of our patch, on a first evaluation it will "undefined"
// should be disabled for subsequent runs as it breaks positioning for them
if (instance.isFirstRun !== false) {
popperOriginalPositionRef.current = state.elements.popper.style['position'];
state.elements.popper.style['position'] = 'fixed';
}
return () => {};
},
requires: [],
},
{ name: 'flip', options: { flipVariations: true } },
/**
* unstable_pinned disables the flip modifier by setting flip.enabled to false; this
* disables automatic repositioning of the popper box; it will always be placed according to
* the values of `align` and `position` props, regardless of the size of the component, the
* reference element or the viewport.
*/
unstable_pinned && { name: 'flip', enabled: false },
/**
* When the popper box is placed in the context of a scrollable element, we need to set
* preventOverflow.escapeWithReference to true and flip.boundariesElement to 'scrollParent'
* (default is 'viewport') so that the popper box will stick with the targetRef when we
* scroll targetRef out of the viewport.
*/
hasScrollableElement && { name: 'flip', options: { boundary: 'clippingParents' } },
hasScrollableElement && { name: 'preventOverflow', options: { boundary: 'clippingParents' } },
offsetModifier,
...(typeof userModifiers === 'function' ? userModifiers(target, container, arrow) : userModifiers),
/**
* This modifier is necessary to retain behaviour from popper v1 where untethered poppers are allowed by
* default. i.e. popper is still rendered fully in the viewport even if anchor element is no longer in the
* viewport.
*/
unstable_disableTether && {
name: 'preventOverflow',
options: { altAxis: unstable_disableTether === 'all', tether: false },
},
flipBoundary && {
name: 'flip',
options: {
altBoundary: true,
boundary: getBoundary(container, flipBoundary),
},
},
overflowBoundary && {
name: 'preventOverflow',
options: {
altBoundary: true,
boundary: getBoundary(container, overflowBoundary),
},
},
{
name: 'onUpdate',
enabled: true,
phase: 'afterWrite' as PopperJs.ModifierPhases,
fn: handleStateUpdate,
},
autoSize && {
// Similar code as popper-maxsize-modifier: https://github.com/atomiks/popper.js/blob/master/src/modifiers/maxSize.js
// popper-maxsize-modifier only calculates the max sizes.
// This modifier can apply max sizes always, or apply the max sizes only when overflow is detected
name: 'applyMaxSize',
enabled: true,
phase: 'beforeWrite' as PopperJs.ModifierPhases,
requiresIfExists: ['offset', 'preventOverflow', 'flip'],
options: {
altBoundary: true,
boundary: getBoundary(container, overflowBoundary),
},
fn({ state, options: modifierOptions }: PopperJs.ModifierArguments<{}>) {
const overflow = PopperJs.detectOverflow(state, modifierOptions);
const { x, y } = state.modifiersData.preventOverflow || { x: 0, y: 0 };
const { width, height } = state.rects.popper;
const [basePlacement] = state.placement.split('-');
const widthProp: keyof PopperJs.SideObject = basePlacement === 'left' ? 'left' : 'right';
const heightProp: keyof PopperJs.SideObject = basePlacement === 'top' ? 'top' : 'bottom';
const applyMaxWidth =
autoSize === 'always' ||
autoSize === 'width-always' ||
(overflow[widthProp] > 0 && (autoSize === true || autoSize === 'width'));
const applyMaxHeight =
autoSize === 'always' ||
autoSize === 'height-always' ||
(overflow[heightProp] > 0 && (autoSize === true || autoSize === 'height'));
if (applyMaxWidth) {
state.styles.popper.maxWidth = `${width - overflow[widthProp] - x}px`;
}
if (applyMaxHeight) {
state.styles.popper.maxHeight = `${height - overflow[heightProp] - y}px`;
}
},
},
/**
* This modifier is necessary in order to render the pointer. Refs are resolved in effects, so it can't be
* placed under computed modifiers. Deep merge is not required as this modifier has only these properties.
*/
{
name: 'arrow',
enabled: !!arrow,
options: { element: arrow },
},
].filter(Boolean);
const popperOptions: PopperJs.Options = {
modifiers,
placement,
strategy,
onFirstUpdate: state => handleStateUpdate({ state }),
};
return popperOptions;
},
[
autoSize,
flipBoundary,
offsetModifier,
overflowBoundary,
placement,
strategy,
unstable_disableTether,
unstable_pinned,
userModifiers,
// These can be skipped from deps as they will not ever change
handleStateUpdate,
popperOriginalPositionRef,
],
);
}
/**
* Exposes Popper positioning API via React hook. Contains few important differences between an official "react-popper"
* package:
* - style attributes are applied directly on DOM to avoid re-renders
* - refs changes and resolution is handled properly without re-renders
* - contains a specific to React fix related to initial positioning when containers have components with managed focus
* to avoid focus jumps
*
* @param {PopperOptions} options
*/
export function usePopper(
options: PopperOptions = {},
): {
// React refs are supposed to be contravariant (allows a more general type to be passed rather than a more specific one)
// However, Typescript currently can't infer that fact for refs
// See https://github.com/microsoft/TypeScript/issues/30748 for more information
targetRef: React.MutableRefObject<any>;
containerRef: React.MutableRefObject<any>;
arrowRef: React.MutableRefObject<any>;
} {
const { enabled = true } = options;
const isFirstMount = useFirstMount();
const popperOriginalPositionRef = React.useRef<string>('absolute');
const resolvePopperOptions = usePopperOptions(options, popperOriginalPositionRef);
const popperInstanceRef = React.useRef<PopperInstance | null>(null);
const handlePopperUpdate = useEventCallback(() => {
popperInstanceRef.current?.destroy();
popperInstanceRef.current = null;
let popperInstance: PopperInstance | null = null;
if (isBrowser() && enabled) {
if (targetRef.current && containerRef.current) {
popperInstance = PopperJs.createPopper(
targetRef.current,
containerRef.current,
resolvePopperOptions(targetRef.current, containerRef.current, arrowRef.current),
);
}
}
if (popperInstance) {
/**
* The patch updates `.forceUpdate()` Popper function which restores the original position before the first
* forceUpdate() call. See also "positionStyleFix" modifier in usePopperOptions().
*/
const originalForceUpdate = popperInstance.forceUpdate;
popperInstance.isFirstRun = true;
popperInstance.forceUpdate = () => {
if (popperInstance.isFirstRun) {
popperInstance.state.elements.popper.style['position'] = popperOriginalPositionRef.current;
popperInstance.isFirstRun = false;
}
originalForceUpdate();
};
}
popperInstanceRef.current = popperInstance;
});
// Refs are managed by useCallbackRef() to handle ref updates scenarios.
//
// The first scenario are updates for a targetRef, we can handle it properly only via callback refs, but it causes
// re-renders (we would like to avoid them).
//
// The second problem is related to refs resolution on React's layer: refs are resolved in the same order as effects
// that causes an issue when you have a container inside a target, for example: a menu in ChatMessage.
//
// function ChatMessage(props) {
// <div className="message" ref={targetRef}> // 3) ref will be resolved only now, but it's too late already
// <Popper target={targetRef}> // 2) create a popper instance
// <div className="menu" /> // 1) capture ref from this element
// </Popper>
// </div>
// }
//
// Check a demo on CodeSandbox: https://codesandbox.io/s/popper-refs-emy60.
//
// This again can be solved with callback refs. It's not a huge issue as with hooks we are moving popper's creation
// to ChatMessage itself, however, without `useCallback()` refs it's still a Pandora box.
const targetRef = useCallbackRef<HTMLElement | PopperJs.VirtualElement | null>(null, handlePopperUpdate, true);
const containerRef = useCallbackRef<HTMLElement | null>(null, handlePopperUpdate, true);
const arrowRef = useCallbackRef<HTMLElement | null>(null, handlePopperUpdate, true);
React.useImperativeHandle(
options.popperRef,
() => ({
updatePosition: () => {
popperInstanceRef.current?.update();
},
}),
[],
);
useIsomorphicLayoutEffect(() => {
handlePopperUpdate();
return () => {
popperInstanceRef.current?.destroy();
popperInstanceRef.current = null;
};
}, [options.enabled]);
useIsomorphicLayoutEffect(() => {
if (!isFirstMount) {
popperInstanceRef.current?.setOptions(
resolvePopperOptions(targetRef.current, containerRef.current, arrowRef.current),
);
}
}, [resolvePopperOptions]);
if (process.env.NODE_ENV !== 'production') {
// This checked should run only in development mode
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useEffect(() => {
if (containerRef.current) {
const contentNode = containerRef.current;
const treeWalker = contentNode.ownerDocument?.createTreeWalker(contentNode, NodeFilter.SHOW_ELEMENT, {
acceptNode: hasAutofocusFilter,
});
while (treeWalker.nextNode()) {
const node = treeWalker.currentNode;
// eslint-disable-next-line no-console
console.warn('<Popper>:', node);
// eslint-disable-next-line no-console
console.warn(
[
'<Popper>: ^ this node contains "autoFocus" prop on a React element. This can break the initial',
'positioning of an element and cause a window jump effect. This issue occurs because React polyfills',
'"autoFocus" behavior to solve inconsistencies between different browsers:',
'https://github.com/facebook/react/issues/11851#issuecomment-351787078',
'\n',
'However, ".focus()" in this case occurs before any other React effects will be executed',
'(React.useEffect(), componentDidMount(), etc.) and we can not prevent this behavior. If you really',
'want to use "autoFocus" please add "position: fixed" to styles of the element that is wrapped by',
'"Popper".',
`In general, it's not recommended to use "autoFocus" as it may break accessibility aspects:`,
'https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-autofocus.md',
'\n',
'We suggest to use the "trapFocus" prop on Fluent components or a catch "ref" and then use',
'"ref.current.focus" in React.useEffect():',
'https://reactjs.org/docs/refs-and-the-dom.html#adding-a-ref-to-a-dom-element',
].join(' '),
);
}
}
// We run this check once, no need to add deps here
// TODO: Should be rework to handle options.enabled and contentRef updates
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
}
return { targetRef, containerRef, arrowRef };
} | the_stack |
import * as React from 'react';
import classNames from 'classnames';
import { Button, Heading, Text, Icon } from '@/index';
import { BaseProps, extractBaseProps } from '@/utils/types';
import config from './config';
import { Size, Day, View, Events } from './types';
import {
compareDate,
compareYearBlock,
getDateInfo,
getDaysInMonth,
getFirstDayOfMonth,
getIndexOfDay,
getYearBlock,
convertToDate,
} from './utility';
type OnHover = React.MouseEvent<HTMLSpanElement> | React.MouseEvent<HTMLDivElement>;
interface hoveredDateProps {
value: number;
isToday: boolean;
isDisabled: boolean;
todayDate?: Date;
fullDate: Date;
date: number;
month: string;
year: number;
dayName: string;
}
interface hoveredMonthProps {
value: string;
month: string;
year?: number;
isCurrentMonth: boolean;
isDisabled: boolean;
}
interface hoveredYearProps {
value: number;
year: number;
isCurrentYear: boolean;
isDisabled: boolean;
}
export interface SharedProps extends BaseProps {
/**
* Size of `Calendar`
*/
size: Size;
/**
* Number of months rendered in view
*/
monthsInView: number;
/**
* Enables jumping to different view on clicking on Calendar Header
*
* **set to `false` if monthsInView > 1**
* @default true
*/
jumpView?: boolean;
/**
* Specifies first day of week to be rendered
*/
firstDayOfWeek: Day;
/**
* Specifies initial view of `Calendar`
*/
view: View;
/**
* Dates to be disabled before mentioned date
*/
disabledBefore?: Date;
/**
* Dates to be disabled after mentioned date
*/
disabledAfter?: Date;
/**
* Initial year to be set for navigation
*
* **use only if date, startDate and endDate are all set or undefined**
*/
yearNav?: number;
/**
* Initial month to be set for navigation
*
* **0 indexed(0-11)**
*
* **use only if date, startDate and endDate are all set or undefined**
*/
monthNav?: number;
}
export type CalendarProps = {
/**
* Callback function called when date is changed
*/
onDateChange?: (date: Date) => void;
/**
* Callback function called when range is changed
*/
onRangeChange?: (startDate: Date | undefined, endDate: Date | undefined) => void;
/**
* Callback function called when a date is hovered
*/
onDateHover?: (dateData: hoveredDateProps, evnt: OnHover) => void;
/**
* Callback function called when a month is hovered
*/
onMonthHover?: (monthData: hoveredMonthProps, evnt: OnHover) => void;
/**
* Callback function called when a year is hovered
*/
onYearHover?: (yearData: hoveredYearProps, evnt: OnHover) => void;
/**
* Selected date
*/
date?: Date;
/**
* Set if want to use as RangePicker
*/
rangePicker?: boolean;
/**
* Selected startDate for RangePicker
*/
startDate?: Date;
/**
* Selected endDate for RangePicker
*/
endDate?: Date;
/**
* Allowed limit for difference in startDate and endDate
*
* **set `0` or `undefined` for infinite limit**
*/
rangeLimit?: number;
/**
* Adds event highlighter to given date
* `events: {
* 'mm/dd/yyyy': true
* }`
*/
events?: Events;
} & SharedProps;
interface CalendarState {
view: View;
year?: number;
month?: number;
date?: number;
currDate?: Date;
hoverDate?: Date;
startDate?: Date;
endDate?: Date;
yearBlockNav: number;
yearNav: number;
monthNav: number;
todayDate: number;
currMonth: number;
currYear: number;
}
export class Calendar extends React.Component<CalendarProps, CalendarState> {
static defaultProps = {
size: 'large',
monthsInView: 1,
view: 'date',
firstDayOfWeek: 'sunday',
jumpView: true,
};
constructor(props: CalendarProps) {
super(props);
const { rangePicker, startDate, endDate, monthsInView, view } = this.props;
const currDate = rangePicker ? endDate || startDate : props.date;
const yearNav = props.yearNav !== undefined ? props.yearNav : getDateInfo(currDate || Date.now()).year;
const monthNav = props.monthNav !== undefined ? props.monthNav : getDateInfo(currDate || Date.now()).month;
const { year, month, date } = getDateInfo(currDate);
const todayCompleteDate = getDateInfo(new Date());
this.state = {
currDate,
startDate,
endDate,
yearNav,
monthNav,
year,
month,
date,
todayDate: todayCompleteDate.date,
currMonth: todayCompleteDate.month,
currYear: todayCompleteDate.year,
view: monthsInView > 1 ? 'date' : view,
yearBlockNav: getYearBlock(yearNav),
};
}
componentDidUpdate(prevProps: CalendarProps, prevState: CalendarState) {
const { monthsInView } = this.props;
if (prevProps.date !== this.props.date) {
const { year, month, date } = getDateInfo(this.props.date);
this.updateState(year, month, date);
const d = convertToDate(this.props.date);
this.setState({
currDate: d,
});
}
if (prevProps.startDate !== this.props.startDate) {
const d = convertToDate(this.props.startDate);
this.setState({
startDate: d,
});
}
if (prevProps.endDate !== this.props.endDate) {
const d = convertToDate(this.props.endDate);
this.setState({
endDate: d,
});
}
if (prevProps.view !== this.props.view) {
if (this.props.monthsInView === 1) {
this.setState({
view: this.props.view,
});
}
}
if (prevProps.yearNav !== this.props.yearNav) {
const { yearNav } = this.props;
if (yearNav) {
this.setState({
yearNav,
yearBlockNav: getYearBlock(yearNav),
});
}
}
if (prevProps.monthNav !== this.props.monthNav) {
const { monthNav } = this.props;
if (monthNav) {
this.setState({
monthNav,
});
}
}
if (prevState.currDate !== this.state.currDate) {
const { rangePicker, onDateChange } = this.props;
const { currDate, startDate, endDate } = this.state;
if (currDate) {
if (onDateChange) onDateChange(currDate);
if (rangePicker) {
this.setState({
hoverDate: undefined,
});
if (startDate && endDate) {
this.setState({
startDate: currDate,
endDate: undefined,
});
} else {
const { year, month, date } = getDateInfo(currDate);
if (startDate) {
if (compareDate(startDate, 'more', year, month, date)) {
this.setState({ startDate: currDate });
} else {
this.setState({ endDate: currDate });
}
} else if (endDate) {
if (compareDate(endDate, 'less', year, month, date)) {
this.setState({ endDate: currDate });
} else {
this.setState({ startDate: currDate });
}
} else {
this.setState({ startDate: currDate });
}
}
} else {
this.setState({ startDate: currDate });
}
}
}
if (prevState.startDate !== this.state.startDate || prevState.endDate !== this.state.endDate) {
const { onRangeChange } = this.props;
const { startDate, endDate } = this.state;
if (onRangeChange) onRangeChange(startDate, endDate);
}
if (prevState.year !== this.state.year) {
const { year } = this.state;
if (year !== undefined && monthsInView === 1) {
this.setState({
year,
yearBlockNav: getYearBlock(year),
yearNav: year,
});
}
}
if (prevState.month !== this.state.month) {
const { month } = this.state;
if (month !== undefined && monthsInView === 1) {
this.setState({
monthNav: month,
});
}
}
}
updateState = (year: number, month?: number, date?: number) => {
this.setState({
year,
month,
date,
});
};
getDateValue = (year: number, month: number, date: number): Date | undefined => {
const d = new Date(year, month, date);
return d;
};
getNavDateInfo = (index: number): Record<string, any> => {
const { yearBlockNav, yearNav, monthNav } = this.state;
const { monthBlock } = config;
const yearBlock = yearBlockNav;
const month = (monthNav + index) % monthBlock === -1 ? 11 : (monthNav + index) % monthBlock;
// const year = yearNav + (index !== 0 && month < monthNav ? 1 : 0);
let year;
if (index >= 0) {
year = yearNav + (index !== 0 && month < monthNav ? 1 : 0);
} else {
year = yearNav - (index !== 0 && month > monthNav ? 1 : 0);
}
return { yearBlock, year, month };
};
getInRangeError = () => {
const { rangePicker, rangeLimit } = this.props;
const { startDate: startDateState, endDate: endDateState, hoverDate: hoverDateState } = this.state;
if (rangePicker && rangeLimit) {
const { year: startYear, month: startMonth, date: startDate } = getDateInfo(startDateState);
const { year: endYear, month: endMonth, date: endDate } = getDateInfo(endDateState);
const { year: hoverYear, month: hoverMonth, date: hoverDate } = getDateInfo(hoverDateState);
let limitDate: Date;
if (startDateState) {
limitDate = new Date(startDateState);
limitDate.setDate(startDate + rangeLimit);
return (
compareDate(limitDate, 'less', hoverYear, hoverMonth, hoverDate + 1) ||
compareDate(limitDate, 'less', endYear, endMonth, endDate + 1)
);
}
if (endDateState) {
limitDate = new Date(endDateState);
limitDate.setDate(endDate - rangeLimit);
return (
compareDate(limitDate, 'more', hoverYear, hoverMonth, hoverDate - 1) ||
compareDate(limitDate, 'more', startYear, startMonth, startDate - 1)
);
}
}
return false;
};
selectYear = (year: number) => () => {
this.updateState(year);
this.setState({
view: 'month',
});
};
yearMouseOverHandler = (
year: number,
isCurrentYear: boolean,
isDisabled: boolean,
ev: React.MouseEvent<HTMLDivElement>
) => {
const { onYearHover } = this.props;
const yearData = {
value: year,
year: year,
isCurrentYear: isCurrentYear,
isDisabled: isDisabled,
};
if (onYearHover) onYearHover(yearData, ev);
};
selectMonth = (month: number) => () => {
this.updateState(this.state.yearNav, month);
this.setState({
view: 'date',
});
};
monthMouseOverHandler = (
month: number,
isCurrentMonth: boolean,
isDisabled: boolean,
ev: React.MouseEvent<HTMLDivElement>
) => {
const { months } = config;
const { onMonthHover } = this.props;
const monthData = {
value: months[month],
month: months[month],
year: this.state.year,
isCurrentMonth: isCurrentMonth,
isDisabled: isDisabled,
};
if (onMonthHover) onMonthHover(monthData, ev);
};
selectDate = (index: number, date: number, prevMonthDayRange: number, dayRange: number) => {
const d = this.calculateDate(index, date, prevMonthDayRange, dayRange, false);
this.setState({
currDate: d,
});
};
calculateDate = (
index: number,
date: number,
prevMonthDayRange: number,
dayRange: number,
isDateHovered: boolean
) => {
let neighbouringMonthIndex;
let neighbouringMonthDate;
let type = '';
if (date <= 0) {
neighbouringMonthIndex = index - 1;
neighbouringMonthDate = prevMonthDayRange + date;
type = 'prev';
} else if (date > dayRange) {
neighbouringMonthIndex = index + 1;
neighbouringMonthDate = date - dayRange;
type = 'next';
} else {
neighbouringMonthIndex = index;
neighbouringMonthDate = date;
}
const { year, month } = this.getNavDateInfo(neighbouringMonthIndex);
if (isDateHovered === false) {
this.updateState(year, month, neighbouringMonthDate);
this.onNavIconClickHandler(type)();
}
const d = this.getDateValue(year, month, neighbouringMonthDate);
return d;
};
onNavIconClickHandler = (type: string) => () => {
const { view, yearBlockNav, yearNav, monthNav } = this.state;
const { yearBlockRange, monthBlock } = config;
switch (view) {
case 'year':
if (type === 'prev') this.setState({ yearBlockNav: yearBlockNav - yearBlockRange });
if (type === 'next') this.setState({ yearBlockNav: yearBlockNav + yearBlockRange });
break;
case 'month':
if (type === 'prev') this.setState({ yearNav: yearNav - 1 });
if (type === 'next') this.setState({ yearNav: yearNav + 1 });
break;
case 'date':
if (type === 'prev') {
if (monthNav === 0) this.setState({ yearNav: yearNav - 1 });
this.setState({ monthNav: (monthBlock + monthNav - 1) % monthBlock });
}
if (type === 'next') {
if (monthNav === monthBlock - 1) this.setState({ yearNav: yearNav + 1 });
this.setState({ monthNav: (monthNav + 1) % monthBlock });
}
break;
}
};
renderJumpButton = (type: string) => {
const { disabledBefore, disabledAfter, size } = this.props;
const { view, yearBlockNav, yearNav, monthNav } = this.state;
let disabled = false;
switch (view) {
case 'year':
if (type === 'prev') {
disabled =
compareYearBlock(disabledBefore, 'more', yearBlockNav) ||
compareYearBlock(disabledBefore, 'equal', yearBlockNav);
}
if (type === 'next') {
disabled =
compareYearBlock(disabledAfter, 'less', yearBlockNav) ||
compareYearBlock(disabledAfter, 'equal', yearBlockNav);
}
break;
case 'month':
if (type === 'prev') {
disabled = compareDate(disabledBefore, 'more', yearNav - 1);
}
if (type === 'next') {
disabled = compareDate(disabledAfter, 'less', yearNav + 1);
}
break;
case 'date':
if (type === 'prev') {
disabled = compareDate(disabledBefore, 'more', yearNav, monthNav - 1);
}
if (type === 'next') {
disabled = compareDate(disabledAfter, 'less', yearNav, monthNav + 1);
}
break;
}
const headerIconClass = classNames({
'Calendar-headerIcon': true,
[`Calendar-headerIcon--${type}`]: type,
});
return (
<Button
type="button"
className={headerIconClass}
appearance="basic"
icon={`arrow_${type === 'next' ? 'forward' : 'back'}`}
disabled={disabled}
size={size === 'small' ? 'tiny' : 'regular'}
onClick={this.onNavIconClickHandler(type)}
/>
);
};
onNavHeadingClickHandler = (currView: View) => () => {
const { monthsInView } = this.props;
let { jumpView } = this.props;
if (jumpView) {
if (monthsInView > 1) jumpView = false;
}
if (jumpView) {
if (currView === 'year') this.setState({ view: 'date' });
if (currView === 'month') this.setState({ view: 'year' });
if (currView === 'date') this.setState({ view: 'month' });
}
};
renderHeaderContent = (index: number) => {
const { size, monthsInView } = this.props;
const { view, yearBlockNav } = this.state;
const { yearBlockRange, months } = config;
const { year: yearNavVal, month: monthNavVal } = this.getNavDateInfo(index);
const headerContentClass = classNames({
'Calendar-headerContent': true,
'Calendar-headerContent--noIcon-left': index === monthsInView - 1,
'Calendar-headerContent--noIcon-right': index === 0,
});
let headerContent = '';
if (view === 'year') headerContent = `${yearBlockNav} - ${yearBlockNav + (yearBlockRange - 1)}`;
if (view === 'month') headerContent = `${yearNavVal}`;
const renderHeading = (content: string) => {
if (size === 'small') {
return (
<>
<Text weight="strong">{content}</Text>
{view !== 'year' && <Icon appearance="inverse" className="pl-3" name="keyboard_arrow_down" />}
</>
);
}
return (
<>
<Heading size="s">{content}</Heading>
{view !== 'year' && <Icon appearance="inverse" className="pl-3" name="keyboard_arrow_down" />}
</>
);
};
return (
<div className={headerContentClass}>
{view !== 'date' && (
// TODO(a11y)
// eslint-disable-next-line
<div
className="d-flex justify-content-center align-items-center"
onClick={this.onNavHeadingClickHandler(view)}
>
{renderHeading(headerContent)}
</div>
)}
{view === 'date' && (
<>
{/* TODO(a11y) */}
{/* eslint-disable-next-line */}
<div
onClick={this.onNavHeadingClickHandler(view)}
className="d-flex justify-content-center align-items-center"
>
{renderHeading(months[monthNavVal])}
</div>
{/* TODO(a11y) */}
{/* eslint-disable-next-line */}
<div
className="ml-4 d-flex justify-content-center align-items-center"
onClick={this.onNavHeadingClickHandler('month')}
>
{renderHeading(yearNavVal)}
</div>
</>
)}
</div>
);
};
renderBodyYear = () => {
const { yearBlockRange, yearsInRow } = config;
const { size, rangePicker, disabledBefore, disabledAfter } = this.props;
const { yearBlockNav, currYear } = this.state;
const noOfRows = Math.ceil(yearBlockRange / yearsInRow);
return Array.from({ length: noOfRows }, (_y, row) => (
<div key={row} className="Calendar-valueRow">
{Array.from({ length: yearsInRow }, (_x, col) => {
const offset = yearsInRow * row + col;
if (offset === yearBlockNav) return undefined;
const year = yearBlockNav + offset;
const disabled = compareDate(disabledBefore, 'more', year) || compareDate(disabledAfter, 'less', year);
const active = !disabled && !rangePicker && year === this.state.year;
const isCurrentYear = () => {
return year === currYear;
};
const valueClass = classNames({
'Calendar-value': true,
'Calendar-value--active': active,
'Calendar-value--disabled': disabled,
'Calendar-yearValue': true,
[`Calendar-yearValue--${size}`]: size,
'Calendar-value--currDateMonthYear': isCurrentYear(),
});
return (
// TODO(a11y)
// eslint-disable-next-line
<div
key={`${row}-${col}`}
data-test="DesignSystem-Calendar--yearValue"
className={valueClass}
onClick={this.selectYear(year)}
onMouseOver={this.yearMouseOverHandler.bind(this, year, isCurrentYear(), disabled)}
>
<Text
size={size === 'small' ? 'small' : 'regular'}
appearance={active ? 'white' : disabled ? 'disabled' : isCurrentYear() ? 'link' : 'default'}
>
{year}
</Text>
</div>
);
})}
</div>
));
};
renderBodyMonth = () => {
const { monthBlock, monthsInRow, months } = config;
const { size, disabledBefore, disabledAfter } = this.props;
const { yearNav, year, currYear, currMonth } = this.state;
const noOfRows = Math.ceil(monthBlock / monthsInRow);
return Array.from({ length: noOfRows }, (_y, row) => (
<div key={row} className="Calendar-valueRow">
{Array.from({ length: monthsInRow }, (_x, col) => {
const month = monthsInRow * row + col;
const disabled =
compareDate(disabledBefore, 'more', yearNav, month) || compareDate(disabledAfter, 'less', yearNav, month);
const active = !disabled && year === yearNav && month === this.state.month;
const isCurrentMonth = () => {
return currYear === yearNav && currMonth === month;
};
const valueClass = classNames({
'Calendar-value': true,
'Calendar-value--active': active,
'Calendar-value--dummy': disabled,
'Calendar-monthValue': true,
[`Calendar-monthValue--${size}`]: size,
'Calendar-value--currDateMonthYear': isCurrentMonth(),
});
return (
//TODO(a11y)
//eslint-disable-next-line
<div
key={`${row}-${col}`}
data-test="DesignSystem-Calendar--monthValue"
className={valueClass}
onClick={this.selectMonth(month)}
onMouseOver={this.monthMouseOverHandler.bind(this, month, isCurrentMonth(), disabled)}
>
<Text
size={size === 'small' ? 'small' : 'regular'}
appearance={active ? 'white' : disabled ? 'disabled' : isCurrentMonth() ? 'link' : 'default'}
>
{months[month]}
</Text>
</div>
);
})}
</div>
));
};
onDateRowMouseLeaveHandler = () => {
const { rangePicker } = this.props;
if (rangePicker) {
this.setState({
hoverDate: undefined,
});
}
};
renderBodyDate = (index: number) => {
const { daysInRow, days } = config;
const { size, firstDayOfWeek } = this.props;
const textSize = size === 'large' ? 'regular' : 'small';
return (
<>
<div className="Calendar-dayValues">
{Array.from({ length: 7 }, (_x, day) => {
const valueClass = classNames({
'Calendar-valueWrapper': true,
});
const dayValue = (day + daysInRow + getIndexOfDay(firstDayOfWeek)) % daysInRow;
return (
<Text key={day} className={valueClass} appearance="default" weight="strong" size={textSize}>
{days[size][dayValue]}
</Text>
);
})}
</div>
<div className="Calendar-dateValues" onMouseLeave={this.onDateRowMouseLeaveHandler}>
{this.renderDateValues(index)}
</div>
</>
);
};
renderEventsIndicator(size: string, active: boolean) {
const eventsIndicatorClass = classNames({
'Calendar-eventsIndicator': true,
[`Calendar-eventsIndicator--${size}`]: true,
'Calendar-eventsIndicator--active': active,
});
return <span data-test="DesignSystem-Calendar-Event-Indicator" className={eventsIndicatorClass} />;
}
renderDateValues = (index: number) => {
const { daysInRow, monthBlock } = config;
const { size, rangePicker, firstDayOfWeek, disabledBefore, disabledAfter, monthsInView, onDateHover } = this.props;
const {
startDate,
endDate,
hoverDate,
year: yearState,
month: monthState,
date: dateState,
currMonth,
currYear,
todayDate,
} = this.state;
const { year: yearNavVal, month: monthNavVal } = this.getNavDateInfo(index);
const prevMonth = monthNavVal - 1;
const prevYear = yearNavVal;
const prevMonthDayRange = getDaysInMonth(prevYear, prevMonth);
const dayRange = getDaysInMonth(yearNavVal, monthNavVal);
const dayDiff = getFirstDayOfMonth(yearNavVal, monthNavVal) - getIndexOfDay(firstDayOfWeek);
const dummyDays = Math.abs(dayDiff);
let noOfRows = Math.ceil((dayRange + dummyDays) / daysInRow);
// TODO: @veekays
// if(noOfRows !== 6 && monthsInView <= 1) ?
if (noOfRows === 6) {
} else if (monthsInView > 1) {
} else {
noOfRows = noOfRows + 1;
}
const inRangeError = this.getInRangeError();
const events = this.props.events;
const onClickHandler = (date: number) => () => {
if (rangePicker) {
if (startDate && endDate) {
this.selectDate(index, date, prevMonthDayRange, dayRange);
} else {
if (!inRangeError) this.selectDate(index, date, prevMonthDayRange, dayRange);
}
} else {
this.selectDate(index, date, prevMonthDayRange, dayRange);
}
};
const onMouseOverHandler = (date: number) => () => {
if (rangePicker) {
const d = this.getDateValue(yearNavVal, monthNavVal, date);
if (!startDate || !endDate) {
this.setState({
hoverDate: d,
});
}
}
};
const onMouseEnterHandler = (
date: number,
isToday: boolean,
isDisabled: boolean,
ev: React.MouseEvent<HTMLSpanElement>
) => {
const d = this.calculateDate(index, date, prevMonthDayRange, dayRange, true) || new Date();
const { months, days } = config;
const dayName = days.large[d.getDay()];
const dateData = {
value: d.getDate(),
isToday: isToday,
isDisabled: isDisabled,
todayDate: this.state.currDate,
fullDate: d,
date: d.getDate(),
month: months[d.getMonth()],
year: d.getFullYear(),
dayName: dayName,
};
if (onDateHover) onDateHover(dateData, ev);
};
return Array.from({ length: noOfRows }, (_y, row) => {
return (
<div key={row} className="Calendar-valueRow">
{Array.from({ length: daysInRow }, (_x, col) => {
const date = daysInRow * row + col - dummyDays + 1;
const dummy = date <= 0 || date > dayRange;
const disabled =
compareDate(disabledBefore, 'more', yearNavVal, monthNavVal, date) ||
compareDate(disabledAfter, 'less', yearNavVal, monthNavVal, date);
let active = !disabled && yearState === yearNavVal && monthState === monthNavVal && dateState === date;
const today = () => {
let boolVal;
if (date <= 0) {
boolVal =
currYear === yearNavVal && currMonth === monthNavVal - 1 && todayDate === prevMonthDayRange + date;
} else if (date > dayRange) {
boolVal = currYear === yearNavVal && currMonth === monthNavVal + 1 && todayDate === date - dayRange;
} else {
boolVal = currYear === yearNavVal && currMonth === monthNavVal && todayDate === date;
}
return boolVal;
};
let startActive = false;
let endActive = false;
let inRange = false;
let inRangeLast = false;
if (rangePicker) {
startActive = compareDate(startDate, 'equal', yearNavVal, monthNavVal, date);
endActive = compareDate(endDate, 'equal', yearNavVal, monthNavVal, date);
inRangeLast = compareDate(hoverDate, 'equal', yearNavVal, monthNavVal, date);
active = !disabled && (startActive || endActive);
if (startDate && endDate) {
inRange =
!disabled &&
(compareDate(startDate, 'less', yearNavVal, monthNavVal, date) || startActive) &&
(compareDate(endDate, 'more', yearNavVal, monthNavVal, date) || endActive);
} else if (startDate) {
inRange =
!disabled &&
(compareDate(hoverDate, 'more', yearNavVal, monthNavVal, date) || inRangeLast) &&
compareDate(startDate, 'less', yearNavVal, monthNavVal, date);
} else if (endDate) {
inRange =
!disabled &&
(compareDate(hoverDate, 'less', yearNavVal, monthNavVal, date) || inRangeLast) &&
compareDate(endDate, 'more', yearNavVal, monthNavVal, date);
}
}
const { year: sYear, month: sMonth, date: sDate } = getDateInfo(startDate);
const { year: eYear, month: eMonth, date: eDate } = getDateInfo(endDate);
const isStart =
startActive || (endDate && inRangeLast && compareDate(hoverDate, 'less', eYear, eMonth, eDate));
const isEnd =
endActive || (startDate && inRangeLast && compareDate(hoverDate, 'more', sYear, sMonth, sDate));
const isRangeError = inRange && inRangeError;
const dateInString = `${date <= 0 ? prevMonthDayRange + date : date > dayRange ? date - dayRange : date}`;
const monthInString = `${
date <= 0
? monthNavVal === 0
? monthNavVal + monthBlock
: ((monthNavVal - 1) % monthBlock) + 1
: date > dayRange
? ((monthNavVal + 1) % monthBlock) + 1
: monthNavVal + 1
}`;
const yearInString = `${
date <= 0 && monthNavVal + 1 === 1
? yearNavVal - 1
: date > dayRange && monthNavVal + 1 === 12
? yearNavVal + 1
: yearNavVal
}`;
const completeDateString = `${monthInString.length === 2 ? monthInString : `0${monthInString}`}/${
dateInString.length === 2 ? dateInString : `0${dateInString}`
}/${yearInString}`;
const isEventExist = events && typeof events === 'object' && events.hasOwnProperty(completeDateString);
const wrapperClass = classNames({
'Calendar-valueWrapper': true,
'Calendar-valueWrapper--inRange': inRange || (rangePicker && active),
'Calendar-valueWrapper--inRangeError': isRangeError,
'Calendar-valueWrapper--start': isStart && !isEnd,
'Calendar-valueWrapper--end': isEnd && !isStart,
'Calendar-valueWrapper--startEnd': isStart && isEnd,
'Calendar-valueWrapper--startError': isStart && isRangeError,
'Calendar-valueWrapper--endError': isEnd && isRangeError,
'Calendar-valueWrapper--dummy': dummy,
});
const valueClass = classNames({
'Calendar-value': true,
'Calendar-value--start': isStart && !isEnd,
'Calendar-value--end': isEnd && !isStart,
'Calendar-value--startError': isStart && isRangeError,
'Calendar-value--endError': isEnd && isRangeError,
'Calendar-value--active': active,
'Calendar-value--disabled': disabled,
'Calendar-dateValue': true,
[`Calendar-dateValue--${size}`]: size,
'Calendar-value--currDateMonthYear': today(),
});
return (
<div key={`${row}-${col}`} className={wrapperClass} data-test="designSystem-Calendar-WrapperClass">
{!dummy && (
<>
<Text
appearance={active ? 'white' : disabled ? 'disabled' : today() ? 'link' : 'default'}
size={size === 'small' ? 'small' : 'regular'}
data-test="DesignSystem-Calendar--dateValue"
className={valueClass}
onClick={onClickHandler(date)}
onMouseOver={onMouseOverHandler(date)}
onMouseEnter={onMouseEnterHandler.bind(this, date, today(), disabled)}
>
{date}
</Text>
{isEventExist && this.renderEventsIndicator(size, active)}
</>
)}
{((dummy && date > 0 && index === monthsInView - 1) || (dummy && date <= 0 && index === 0)) && (
<>
<Text
appearance={active ? 'white' : disabled ? 'disabled' : today() ? 'link' : 'default'}
size={size === 'small' ? 'small' : 'regular'}
data-test="DesignSystem-Calendar--dateValue"
className={valueClass}
onClick={onClickHandler(date)}
onMouseOver={onMouseOverHandler(date)}
onMouseEnter={onMouseEnterHandler.bind(this, date, today(), disabled)}
>
{date <= 0 ? prevMonthDayRange + date : date - dayRange}
</Text>
{isEventExist && this.renderEventsIndicator(size, active)}
</>
)}
</div>
);
})}
</div>
);
});
};
renderCalendar = (index: number) => {
const { size, monthsInView } = this.props;
const { view } = this.state;
const containerClass = classNames({
['Calendar']: true,
[`Calendar--${view}--${size}`]: view,
[`Calendar--${size}`]: size,
});
const headerClass = classNames({
[`Calendar-header--${size}`]: size,
});
const bodyClass = classNames({
'Calendar-body': true,
});
return (
<div key={index} data-test="DesignSystem-Calendar" className={containerClass}>
<div className={headerClass}>
{index === 0 && this.renderJumpButton('prev')}
{this.renderHeaderContent(index)}
{index === monthsInView - 1 && this.renderJumpButton('next')}
</div>
<div className={bodyClass}>
{view === 'year' && this.renderBodyYear()}
{view === 'month' && this.renderBodyMonth()}
{view === 'date' && this.renderBodyDate(index)}
</div>
</div>
);
};
render() {
const { monthsInView, className } = this.props;
const baseProps = extractBaseProps(this.props);
const classes = classNames(
{
'Calendar-wrapper': true,
},
className
);
return (
<div {...baseProps} className={classes} data-test="DesignSystem-Calendar-Wrapper">
{Array.from({ length: monthsInView }, (_x, index) => {
return this.renderCalendar(index);
})}
</div>
);
}
}
export default Calendar; | the_stack |
import * as vscode from "vscode";
import {
BazelWorkspaceInfo,
createBazelTask,
getBazelTaskInfo,
queryQuickPickPackage,
queryQuickPickTargets,
} from "../bazel";
import {
exitCodeToUserString,
IBazelCommandAdapter,
parseExitCode,
} from "../bazel";
import {
BuildifierDiagnosticsManager,
BuildifierFormatProvider,
checkBuildifierIsAvailable,
} from "../buildifier";
import { BazelBuildCodeLensProvider } from "../codelens";
import { BazelCompletionItemProvider } from "../completion-provider";
import { BazelGotoDefinitionProvider } from "../definition/bazel_goto_definition_provider";
import { BazelTargetSymbolProvider } from "../symbols";
import { BazelWorkspaceTreeProvider } from "../workspace-tree";
import { getDefaultBazelExecutablePath } from "./configuration";
/**
* Called when the extension is activated; that is, when its first command is
* executed.
*
* @param context The extension context.
*/
export function activate(context: vscode.ExtensionContext) {
const workspaceTreeProvider = new BazelWorkspaceTreeProvider(context);
const codeLensProvider = new BazelBuildCodeLensProvider(context);
const buildifierDiagnostics = new BuildifierDiagnosticsManager();
const completionItemProvider = new BazelCompletionItemProvider();
// tslint:disable-next-line:no-floating-promises
completionItemProvider.refresh();
context.subscriptions.push(
vscode.languages.registerCompletionItemProvider(
[{ pattern: "**/BUILD" }, { pattern: "**/BUILD.bazel" }],
completionItemProvider,
"/",
":",
),
vscode.window.registerTreeDataProvider(
"bazelWorkspace",
workspaceTreeProvider,
),
// Commands
vscode.commands.registerCommand("bazel.buildTarget", bazelBuildTarget),
vscode.commands.registerCommand(
"bazel.buildTargetWithDebugging",
bazelBuildTargetWithDebugging,
),
vscode.commands.registerCommand("bazel.buildAll", bazelbuildAll),
vscode.commands.registerCommand(
"bazel.buildAllRecursive",
bazelbuildAllRecursive,
),
vscode.commands.registerCommand("bazel.testTarget", bazelTestTarget),
vscode.commands.registerCommand("bazel.testAll", bazelTestAll),
vscode.commands.registerCommand(
"bazel.testAllRecursive",
bazelTestAllRecursive,
),
vscode.commands.registerCommand("bazel.clean", bazelClean),
vscode.commands.registerCommand("bazel.refreshBazelBuildTargets", () => {
// tslint:disable-next-line:no-floating-promises
completionItemProvider.refresh();
workspaceTreeProvider.refresh();
}),
vscode.commands.registerCommand(
"bazel.copyTargetToClipboard",
bazelCopyTargetToClipboard,
),
// CodeLens provider for BUILD files
vscode.languages.registerCodeLensProvider(
[{ pattern: "**/BUILD" }, { pattern: "**/BUILD.bazel" }],
codeLensProvider,
),
// Buildifier formatting support
vscode.languages.registerDocumentFormattingEditProvider(
[
{ language: "starlark" },
{ pattern: "**/BUILD" },
{ pattern: "**/BUILD.bazel" },
{ pattern: "**/WORKSPACE" },
{ pattern: "**/WORKSPACE.bazel" },
{ pattern: "**/*.BUILD" },
{ pattern: "**/*.bzl" },
{ pattern: "**/*.sky" },
],
new BuildifierFormatProvider(),
),
buildifierDiagnostics,
// Symbol provider for BUILD files
vscode.languages.registerDocumentSymbolProvider(
[{ pattern: "**/BUILD" }, { pattern: "**/BUILD.bazel" }],
new BazelTargetSymbolProvider(),
),
// Goto definition for BUILD files
vscode.languages.registerDefinitionProvider(
[{ pattern: "**/BUILD" }, { pattern: "**/BUILD.bazel" }],
new BazelGotoDefinitionProvider(),
),
// Task events.
vscode.tasks.onDidStartTask(onTaskStart),
vscode.tasks.onDidStartTaskProcess(onTaskProcessStart),
vscode.tasks.onDidEndTaskProcess(onTaskProcessEnd),
);
// Notify the user if buildifier is not available on their path (or where
// their settings expect it).
checkBuildifierIsAvailable();
}
/** Called when the extension is deactivated. */
export function deactivate() {
// Nothing to do here.
}
/**
* Builds a Bazel target and streams output to the terminal.
*
* @param adapter An object that implements {@link IBazelCommandAdapter} from
* which the command's arguments will be determined.
*/
async function bazelBuildTarget(adapter: IBazelCommandAdapter | undefined) {
if (adapter === undefined) {
// If the command adapter was unspecified, it means this command is being
// invoked via the command palatte. Provide quickpick build targets for
// the user to choose from.
const quickPick = await vscode.window.showQuickPick(
queryQuickPickTargets("kind('.* rule', ...)"),
{
canPickMany: false,
},
);
// If the result was undefined, the user cancelled the quick pick, so don't
// try again.
if (quickPick) {
await bazelBuildTarget(quickPick);
}
return;
}
const commandOptions = adapter.getBazelCommandOptions();
const task = createBazelTask("build", commandOptions);
vscode.tasks.executeTask(task);
}
/**
* Builds a Bazel target and attaches the Starlark debugger.
*
* @param adapter An object that implements {@link IBazelCommandAdapter} from
* which the command's arguments will be determined.
*/
async function bazelBuildTargetWithDebugging(
adapter: IBazelCommandAdapter | undefined,
) {
if (adapter === undefined) {
// If the command adapter was unspecified, it means this command is being
// invoked via the command palatte. Provide quickpick build targets for
// the user to choose from.
const quickPick = await vscode.window.showQuickPick(
queryQuickPickTargets("kind('.* rule', ...)"),
{
canPickMany: false,
},
);
// If the result was undefined, the user cancelled the quick pick, so don't
// try again.
if (quickPick) {
await bazelBuildTargetWithDebugging(quickPick);
}
return;
}
const bazelConfigCmdLine =
vscode.workspace.getConfiguration("bazel.commandLine");
const startupOptions = bazelConfigCmdLine.get<string[]>("startupOptions");
const commandArgs = bazelConfigCmdLine.get<string[]>("commandArgs");
const commandOptions = adapter.getBazelCommandOptions();
const fullArgs = commandArgs
.concat(commandOptions.targets)
.concat(commandOptions.options);
vscode.debug.startDebugging(undefined, {
args: fullArgs,
bazelCommand: "build",
bazelExecutablePath: getDefaultBazelExecutablePath(),
bazelStartupOptions: startupOptions,
cwd: commandOptions.workspaceInfo.bazelWorkspacePath,
name: "On-demand Bazel Build Debug",
request: "launch",
type: "bazel-launch-build",
});
}
/**
* Builds a Bazel package and streams output to the terminal.
*
* @param adapter An object that implements {@link IBazelCommandAdapter} from
* which the command's arguments will be determined.
*/
async function bazelbuildAll(adapter: IBazelCommandAdapter | undefined) {
await buildPackage(":all", adapter);
}
/**
* Builds a Bazel package recursively and streams output to the terminal.
*
* @param adapter An object that implements {@link IBazelCommandAdapter} from
* which the command's arguments will be determined.
*/
async function bazelbuildAllRecursive(
adapter: IBazelCommandAdapter | undefined,
) {
await buildPackage("/...", adapter);
}
async function buildPackage(
suffix: string,
adapter: IBazelCommandAdapter | undefined,
) {
if (adapter === undefined) {
// If the command adapter was unspecified, it means this command is being
// invoked via the command palatte. Provide quickpick build targets for
// the user to choose from.
const quickPick = await vscode.window.showQuickPick(
queryQuickPickPackage(),
{
canPickMany: false,
},
);
// If the result was undefined, the user cancelled the quick pick, so don't
// try again.
if (quickPick) {
await buildPackage(suffix, quickPick);
}
return;
}
const commandOptions = adapter.getBazelCommandOptions();
const allCommandOptions = {
options: commandOptions.options,
targets: commandOptions.targets.map((s) => s + suffix),
workspaceInfo: commandOptions.workspaceInfo,
};
const task = createBazelTask("build", allCommandOptions);
vscode.tasks.executeTask(task);
}
/**
* Tests a Bazel target and streams output to the terminal.
*
* @param adapter An object that implements {@link IBazelCommandAdapter} from
* which the command's arguments will be determined.
*/
async function bazelTestTarget(adapter: IBazelCommandAdapter | undefined) {
if (adapter === undefined) {
// If the command adapter was unspecified, it means this command is being
// invoked via the command palatte. Provide quickpick test targets for
// the user to choose from.
const quickPick = await vscode.window.showQuickPick(
queryQuickPickTargets("kind('.*_test rule', ...)"),
{
canPickMany: false,
},
);
// If the result was undefined, the user cancelled the quick pick, so don't
// try again.
if (quickPick) {
await bazelTestTarget(quickPick);
}
return;
}
const commandOptions = adapter.getBazelCommandOptions();
const task = createBazelTask("test", commandOptions);
vscode.tasks.executeTask(task);
}
/**
* Tests a Bazel package and streams output to the terminal.
*
* @param adapter An object that implements {@link IBazelCommandAdapter} from
* which the command's arguments will be determined.
*/
async function bazelTestAll(adapter: IBazelCommandAdapter | undefined) {
await testPackage(":all", adapter);
}
/**
* Tests a Bazel package recursively and streams output to the terminal.
*
* @param adapter An object that implements {@link IBazelCommandAdapter} from
* which the command's arguments will be determined.
*/
async function bazelTestAllRecursive(
adapter: IBazelCommandAdapter | undefined,
) {
await testPackage("/...", adapter);
}
async function testPackage(
suffix: string,
adapter: IBazelCommandAdapter | undefined,
) {
if (adapter === undefined) {
// If the command adapter was unspecified, it means this command is being
// invoked via the command palatte. Provide quickpick build targets for
// the user to choose from.
const quickPick = await vscode.window.showQuickPick(
queryQuickPickPackage(),
{
canPickMany: false,
},
);
// If the result was undefined, the user cancelled the quick pick, so don't
// try again.
if (quickPick) {
await testPackage(suffix, quickPick);
}
return;
}
const commandOptions = adapter.getBazelCommandOptions();
const allCommandOptions = {
options: commandOptions.options,
targets: commandOptions.targets.map((s) => s + suffix),
workspaceInfo: commandOptions.workspaceInfo,
};
const task = createBazelTask("test", allCommandOptions);
vscode.tasks.executeTask(task);
}
/**
* Cleans a Bazel workspace.
*
* If there is only a single workspace open, it will be cleaned immediately. If
* there are multiple workspace folders open, a quick-pick window will be opened
* asking the user to choose one.
*/
async function bazelClean() {
const workspaces = vscode.workspace.workspaceFolders;
let workspaceFolder: vscode.WorkspaceFolder;
switch (workspaces.length) {
case 0:
vscode.window.showInformationMessage(
"Please open a Bazel workspace folder to use this command.",
);
return;
case 1:
workspaceFolder = workspaces[0];
break;
default:
workspaceFolder = await vscode.window.showWorkspaceFolderPick();
if (workspaceFolder === undefined) {
return;
}
}
const task = createBazelTask("clean", {
options: [],
targets: [],
workspaceInfo: BazelWorkspaceInfo.fromWorkspaceFolder(workspaceFolder),
});
vscode.tasks.executeTask(task);
}
/**
* Copies a target to the clipboard.
*/
async function bazelCopyTargetToClipboard(
adapter: IBazelCommandAdapter | undefined,
) {
if (adapter === undefined) {
// This command should not be enabled in the commands palette, so adapter
// should always be present.
return;
}
// This can only be called on single targets, so we can assume there is only
// one of them.
const target = adapter.getBazelCommandOptions().targets[0];
vscode.env.clipboard.writeText(target);
}
function onTaskStart(event: vscode.TaskStartEvent) {
const bazelTaskInfo = getBazelTaskInfo(event.execution.task);
if (bazelTaskInfo) {
bazelTaskInfo.startTime = process.hrtime();
}
}
function onTaskProcessStart(event: vscode.TaskProcessStartEvent) {
const bazelTaskInfo = getBazelTaskInfo(event.execution.task);
if (bazelTaskInfo) {
bazelTaskInfo.processId = event.processId;
}
}
function onTaskProcessEnd(event: vscode.TaskProcessEndEvent) {
const bazelTaskInfo = getBazelTaskInfo(event.execution.task);
if (bazelTaskInfo) {
const rawExitCode = event.exitCode;
bazelTaskInfo.exitCode = rawExitCode;
const exitCode = parseExitCode(rawExitCode, bazelTaskInfo.command);
if (rawExitCode !== 0) {
vscode.window.showErrorMessage(
`Bazel ${bazelTaskInfo.command} failed: ${exitCodeToUserString(
exitCode,
)}`,
);
} else {
const timeInSeconds = measurePerformance(bazelTaskInfo.startTime);
vscode.window.showInformationMessage(
`Bazel ${bazelTaskInfo.command} completed successfully in ${timeInSeconds} seconds.`,
);
}
}
}
/**
* Returns the number of seconds elapsed with a single decimal place.
*
*/
function measurePerformance(start: [number, number]) {
const diff = process.hrtime(start);
return (diff[0] + diff[1] / 1e9).toFixed(1);
} | the_stack |
import * as DOM from 'vs/base/browser/dom';
import { Disposable, DisposableStore, toDisposable } from 'vs/base/common/lifecycle';
import { dirname } from 'vs/base/common/resources';
import { URI } from 'vs/base/common/uri';
import { MarkdownRenderer } from 'vs/editor/browser/core/markdownRenderer';
import { IEditorConstructionOptions } from 'vs/editor/browser/editorBrowser';
import { CodeEditorWidget } from 'vs/editor/browser/widget/codeEditorWidget';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IModeService } from 'vs/editor/common/services/modeService';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ILogService } from 'vs/platform/log/common/log';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { handleANSIOutput } from 'vs/workbench/contrib/debug/browser/debugANSIHandling';
import { LinkDetector } from 'vs/workbench/contrib/debug/browser/linkDetector';
import { ICellOutputViewModel, ICommonNotebookEditor, IOutputTransformContribution as IOutputRendererContribution, IRenderOutput, RenderOutputType } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { OutputRendererRegistry } from 'vs/workbench/contrib/notebook/browser/view/output/rendererRegistry';
import { truncatedArrayOfString } from 'vs/workbench/contrib/notebook/browser/view/output/transforms/textHelper';
import { IOutputItemDto } from 'vs/workbench/contrib/notebook/common/notebookCommon';
class JavaScriptRendererContrib extends Disposable implements IOutputRendererContribution {
getType() {
return RenderOutputType.Html;
}
getMimetypes() {
return ['application/javascript'];
}
constructor(
public notebookEditor: ICommonNotebookEditor,
) {
super();
}
render(output: ICellOutputViewModel, items: IOutputItemDto[], container: HTMLElement, notebookUri: URI): IRenderOutput {
let scriptVal = '';
items.forEach(item => {
const str = getStringValue(item);
scriptVal += `<script type="application/javascript">${str}</script>`;
});
return {
type: RenderOutputType.Html,
source: output,
htmlContent: scriptVal
};
}
}
class CodeRendererContrib extends Disposable implements IOutputRendererContribution {
getType() {
return RenderOutputType.Mainframe;
}
getMimetypes() {
return ['text/x-javascript'];
}
constructor(
public notebookEditor: ICommonNotebookEditor,
@IInstantiationService private readonly instantiationService: IInstantiationService,
@IModelService private readonly modelService: IModelService,
@IModeService private readonly modeService: IModeService,
) {
super();
}
render(output: ICellOutputViewModel, items: IOutputItemDto[], container: HTMLElement): IRenderOutput {
const value = items.map(getStringValue).join('');
return this._render(output, container, value, 'javascript');
}
protected _render(output: ICellOutputViewModel, container: HTMLElement, value: string, modeId: string): IRenderOutput {
const disposable = new DisposableStore();
const editor = this.instantiationService.createInstance(CodeEditorWidget, container, getOutputSimpleEditorOptions(), { isSimpleWidget: true });
const mode = this.modeService.create(modeId);
const textModel = this.modelService.createModel(value, mode, undefined, false);
editor.setModel(textModel);
const width = this.notebookEditor.getCellOutputLayoutInfo(output.cellViewModel).width;
const fontInfo = this.notebookEditor.getCellOutputLayoutInfo(output.cellViewModel).fontInfo;
const height = Math.min(textModel.getLineCount(), 16) * (fontInfo.lineHeight || 18);
editor.layout({ height, width });
disposable.add(editor);
disposable.add(textModel);
container.style.height = `${height + 8}px`;
return { type: RenderOutputType.Mainframe, initHeight: height, disposable };
}
}
class JSONRendererContrib extends CodeRendererContrib {
override getMimetypes() {
return ['application/json'];
}
override render(output: ICellOutputViewModel, items: IOutputItemDto[], container: HTMLElement): IRenderOutput {
const str = items.map(getStringValue).join('');
return this._render(output, container, str, 'jsonc');
}
}
class StreamRendererContrib extends Disposable implements IOutputRendererContribution {
getType() {
return RenderOutputType.Mainframe;
}
getMimetypes() {
return ['application/vnd.code.notebook.stdout', 'application/x.notebook.stdout', 'application/x.notebook.stream'];
}
constructor(
public notebookEditor: ICommonNotebookEditor,
@IOpenerService private readonly openerService: IOpenerService,
@IThemeService private readonly themeService: IThemeService,
@IInstantiationService private readonly instantiationService: IInstantiationService,
) {
super();
}
render(output: ICellOutputViewModel, items: IOutputItemDto[], container: HTMLElement, notebookUri: URI): IRenderOutput {
const linkDetector = this.instantiationService.createInstance(LinkDetector);
items.forEach(item => {
const text = getStringValue(item);
const contentNode = DOM.$('span.output-stream');
truncatedArrayOfString(notebookUri!, output.cellViewModel, contentNode, [text], linkDetector, this.openerService, this.themeService);
container.appendChild(contentNode);
});
return { type: RenderOutputType.Mainframe };
}
}
class StderrRendererContrib extends StreamRendererContrib {
override getType() {
return RenderOutputType.Mainframe;
}
override getMimetypes() {
return ['application/vnd.code.notebook.stderr', 'application/x.notebook.stderr'];
}
override render(output: ICellOutputViewModel, items: IOutputItemDto[], container: HTMLElement, notebookUri: URI): IRenderOutput {
const result = super.render(output, items, container, notebookUri);
container.classList.add('error');
return result;
}
}
class JSErrorRendererContrib implements IOutputRendererContribution {
constructor(
public notebookEditor: ICommonNotebookEditor,
@IThemeService private readonly _themeService: IThemeService,
@IInstantiationService private readonly _instantiationService: IInstantiationService,
@ILogService private readonly _logService: ILogService,
) { }
dispose(): void {
// nothing
}
getType() {
return RenderOutputType.Mainframe;
}
getMimetypes() {
return ['application/vnd.code.notebook.error'];
}
render(_output: ICellOutputViewModel, items: IOutputItemDto[], container: HTMLElement, _notebookUri: URI): IRenderOutput {
const linkDetector = this._instantiationService.createInstance(LinkDetector);
type ErrorLike = Partial<Error>;
for (let item of items) {
let err: ErrorLike;
try {
err = <ErrorLike>JSON.parse(getStringValue(item));
} catch (e) {
this._logService.warn('INVALID output item (failed to parse)', e);
continue;
}
const header = document.createElement('div');
const headerMessage = err.name && err.message ? `${err.name}: ${err.message}` : err.name || err.message;
if (headerMessage) {
header.innerText = headerMessage;
container.appendChild(header);
}
const stack = document.createElement('pre');
stack.classList.add('traceback');
if (err.stack) {
stack.appendChild(handleANSIOutput(err.stack, linkDetector, this._themeService, undefined));
}
container.appendChild(stack);
container.classList.add('error');
}
return { type: RenderOutputType.Mainframe };
}
}
class PlainTextRendererContrib extends Disposable implements IOutputRendererContribution {
getType() {
return RenderOutputType.Mainframe;
}
getMimetypes() {
return ['text/plain'];
}
constructor(
public notebookEditor: ICommonNotebookEditor,
@IOpenerService private readonly openerService: IOpenerService,
@IThemeService private readonly themeService: IThemeService,
@IInstantiationService private readonly instantiationService: IInstantiationService
) {
super();
}
render(output: ICellOutputViewModel, items: IOutputItemDto[], container: HTMLElement, notebookUri: URI): IRenderOutput {
const linkDetector = this.instantiationService.createInstance(LinkDetector);
const str = items.map(getStringValue);
const contentNode = DOM.$('.output-plaintext');
truncatedArrayOfString(notebookUri!, output.cellViewModel, contentNode, str, linkDetector, this.openerService, this.themeService);
container.appendChild(contentNode);
return { type: RenderOutputType.Mainframe, supportAppend: true };
}
}
class HTMLRendererContrib extends Disposable implements IOutputRendererContribution {
getType() {
return RenderOutputType.Html;
}
getMimetypes() {
return ['text/html', 'image/svg+xml'];
}
constructor(
public notebookEditor: ICommonNotebookEditor,
) {
super();
}
render(output: ICellOutputViewModel, items: IOutputItemDto[], container: HTMLElement, notebookUri: URI): IRenderOutput {
const str = items.map(getStringValue).join('');
return {
type: RenderOutputType.Html,
source: output,
htmlContent: str
};
}
}
class MdRendererContrib extends Disposable implements IOutputRendererContribution {
getType() {
return RenderOutputType.Mainframe;
}
getMimetypes() {
return ['text/markdown'];
}
constructor(
public notebookEditor: ICommonNotebookEditor,
@IInstantiationService private readonly instantiationService: IInstantiationService,
) {
super();
}
render(output: ICellOutputViewModel, items: IOutputItemDto[], container: HTMLElement, notebookUri: URI): IRenderOutput {
const disposable = new DisposableStore();
for (let item of items) {
const str = getStringValue(item);
const mdOutput = document.createElement('div');
const mdRenderer = this.instantiationService.createInstance(MarkdownRenderer, { baseUrl: dirname(notebookUri) });
mdOutput.appendChild(mdRenderer.render({ value: str, isTrusted: true, supportThemeIcons: true }, undefined, { gfm: true }).element);
container.appendChild(mdOutput);
disposable.add(mdRenderer);
}
return { type: RenderOutputType.Mainframe, disposable };
}
}
class ImgRendererContrib extends Disposable implements IOutputRendererContribution {
getType() {
return RenderOutputType.Mainframe;
}
getMimetypes() {
return ['image/png', 'image/jpeg', 'image/gif'];
}
constructor(
public notebookEditor: ICommonNotebookEditor,
) {
super();
}
render(output: ICellOutputViewModel, items: IOutputItemDto[], container: HTMLElement, notebookUri: URI): IRenderOutput {
const disposable = new DisposableStore();
for (let item of items) {
const bytes = new Uint8Array(item.valueBytes);
const blob = new Blob([bytes], { type: item.mime });
const src = URL.createObjectURL(blob);
disposable.add(toDisposable(() => URL.revokeObjectURL(src)));
const image = document.createElement('img');
image.src = src;
const display = document.createElement('div');
display.classList.add('display');
display.appendChild(image);
container.appendChild(display);
}
return { type: RenderOutputType.Mainframe, disposable };
}
}
OutputRendererRegistry.registerOutputTransform(JSONRendererContrib);
OutputRendererRegistry.registerOutputTransform(JavaScriptRendererContrib);
OutputRendererRegistry.registerOutputTransform(HTMLRendererContrib);
OutputRendererRegistry.registerOutputTransform(MdRendererContrib);
OutputRendererRegistry.registerOutputTransform(ImgRendererContrib);
OutputRendererRegistry.registerOutputTransform(PlainTextRendererContrib);
OutputRendererRegistry.registerOutputTransform(CodeRendererContrib);
OutputRendererRegistry.registerOutputTransform(JSErrorRendererContrib);
OutputRendererRegistry.registerOutputTransform(StreamRendererContrib);
OutputRendererRegistry.registerOutputTransform(StderrRendererContrib);
// --- utils ---
function getStringValue(item: IOutputItemDto): string {
// todo@jrieken NOT proper, should be VSBuffer
return new TextDecoder().decode(new Uint8Array(item.valueBytes));
}
function getOutputSimpleEditorOptions(): IEditorConstructionOptions {
return {
dimension: { height: 0, width: 0 },
readOnly: true,
wordWrap: 'on',
overviewRulerLanes: 0,
glyphMargin: false,
selectOnLineNumbers: false,
hideCursorInOverviewRuler: true,
selectionHighlight: false,
lineDecorationsWidth: 0,
overviewRulerBorder: false,
scrollBeyondLastLine: false,
renderLineHighlight: 'none',
minimap: {
enabled: false
},
lineNumbers: 'off',
scrollbar: {
alwaysConsumeMouseWheel: false
},
automaticLayout: true,
};
} | the_stack |
declare module '@fullcalendar/resource-timeline' {
import ResourceTimelineView from '@fullcalendar/resource-timeline/ResourceTimelineView';
export { ResourceTimelineView };
const _default: import("@fullcalendar/core").PluginDef;
export default _default;
}
declare module '@fullcalendar/resource-timeline/ResourceTimelineView' {
import { ElementDragging, SplittableProps, PositionCache, Hit, View, ComponentContext, DateProfile, Duration, DateProfileGenerator } from '@fullcalendar/core';
import { ScrollJoiner, TimelineLane, StickyScroller, TimeAxis } from '@fullcalendar/timeline';
import { GroupNode, ResourceNode, ResourceViewProps } from '@fullcalendar/resource-common';
import GroupRow from '@fullcalendar/resource-timeline/GroupRow';
import ResourceRow from '@fullcalendar/resource-timeline/ResourceRow';
import Spreadsheet from '@fullcalendar/resource-timeline/Spreadsheet';
export { ResourceTimelineView as default, ResourceTimelineView };
class ResourceTimelineView extends View {
static needsResourceData: boolean;
props: ResourceViewProps;
spreadsheet: Spreadsheet;
timeAxis: TimeAxis;
lane: TimelineLane;
bodyScrollJoiner: ScrollJoiner;
spreadsheetBodyStickyScroller: StickyScroller;
isStickyScrollDirty: boolean;
timeAxisTbody: HTMLElement;
miscHeight: number;
rowNodes: (GroupNode | ResourceNode)[];
rowComponents: (GroupRow | ResourceRow)[];
rowComponentsById: {
[id: string]: (GroupRow | ResourceRow);
};
resourceAreaHeadEl: HTMLElement;
resourceAreaWidth?: number;
resourceAreaWidthDraggings: ElementDragging[];
superHeaderText: any;
isVGrouping: any;
isHGrouping: any;
groupSpecs: any;
colSpecs: any;
orderSpecs: any;
rowPositions: PositionCache;
_startInteractive(timeAxisEl: HTMLElement): void;
_stopInteractive(): void;
render(props: ResourceViewProps, context: ComponentContext): void;
_renderSkeleton(context: ComponentContext): void;
_unrenderSkeleton(context: ComponentContext): void;
renderSkeletonHtml(): string;
_updateHasNesting(isNesting: boolean): void;
diffRows(newNodes: any): void;
addRow(index: any, rowNode: any): void;
removeRows(startIndex: any, len: any, oldRowNodes: any): void;
buildChildComponent(node: (GroupNode | ResourceNode), spreadsheetTbody: HTMLElement, spreadsheetNext: HTMLElement, timeAxisTbody: HTMLElement, timeAxisNext: HTMLElement): GroupRow | ResourceRow;
updateRowProps(dateProfile: DateProfile, fallbackBusinessHours: any, splitProps: {
[resourceId: string]: SplittableProps;
}): void;
updateSize(isResize: any, viewHeight: any, isAuto: any): void;
syncHeadHeights(): void;
updateRowSizes(isResize: boolean): number;
destroyRows(): void;
destroy(): void;
getNowIndicatorUnit(dateProfile: DateProfile, dateProfileGenerator: DateProfileGenerator): string;
renderNowIndicator(date: any): void;
unrenderNowIndicator(): void;
queryScroll(): any;
applyScroll(scroll: any, isResize: any): void;
computeDateScroll(duration: Duration): {
left: number;
};
queryDateScroll(): {
left: number;
};
applyDateScroll(scroll: any): void;
queryResourceScroll(): any;
applyResourceScroll(scroll: any): void;
buildPositionCaches(): void;
queryHit(positionLeft: number, positionTop: number): Hit;
setResourceAreaWidth(widthVal: any): void;
initResourceAreaWidthDragging(): void;
}
}
declare module '@fullcalendar/resource-timeline/GroupRow' {
import { Group } from '@fullcalendar/resource-common';
import Row from '@fullcalendar/resource-timeline/Row';
export interface GroupRowProps {
spreadsheetColCnt: number;
id: string;
isExpanded: boolean;
group: Group;
}
export { GroupRow as default, GroupRow };
class GroupRow extends Row<GroupRowProps> {
spreadsheetHeightEl: HTMLElement;
timeAxisHeightEl: HTMLElement;
expanderIconEl: HTMLElement;
render(props: GroupRowProps): void;
destroy(): void;
renderCells(group: Group, spreadsheetColCnt: number): void;
unrenderCells(): void;
renderSpreadsheetContent(group: Group): HTMLElement;
renderCellText(group: Group): any;
getHeightEls(): HTMLElement[];
updateExpanderIcon(isExpanded: boolean): void;
onExpanderClick: (ev: UIEvent) => void;
}
}
declare module '@fullcalendar/resource-timeline/ResourceRow' {
import { Duration, ComponentContext, EventInteractionState, DateSpan, EventUiHash, EventStore, DateProfile } from '@fullcalendar/core';
import { TimelineLane, TimeAxis } from '@fullcalendar/timeline';
import Row from '@fullcalendar/resource-timeline/Row';
import SpreadsheetRow from '@fullcalendar/resource-timeline/SpreadsheetRow';
import { Resource } from '@fullcalendar/resource-common';
export interface ResourceRowProps {
dateProfile: DateProfile;
nextDayThreshold: Duration;
businessHours: EventStore | null;
eventStore: EventStore | null;
eventUiBases: EventUiHash;
dateSelection: DateSpan | null;
eventSelection: string;
eventDrag: EventInteractionState | null;
eventResize: EventInteractionState | null;
colSpecs: any;
id: string;
rowSpans: number[];
depth: number;
isExpanded: boolean;
hasChildren: boolean;
resource: Resource;
}
export { ResourceRow as default, ResourceRow };
class ResourceRow extends Row<ResourceRowProps> {
cellEl: HTMLElement;
innerContainerEl: HTMLElement;
timeAxis: TimeAxis;
spreadsheetRow: SpreadsheetRow;
lane: TimelineLane;
constructor(a: any, b: any, c: any, d: any, timeAxis: TimeAxis);
render(props: ResourceRowProps, context: ComponentContext): void;
destroy(): void;
_renderSkeleton(context: ComponentContext): void;
_unrenderSkeleton(): void;
updateSize(isResize: boolean): void;
getHeightEls(): HTMLElement[];
}
}
declare module '@fullcalendar/resource-timeline/Spreadsheet' {
import { Component, ComponentContext } from '@fullcalendar/core';
import { HeaderBodyLayout } from '@fullcalendar/timeline';
import SpreadsheetHeader from '@fullcalendar/resource-timeline/SpreadsheetHeader';
export interface SpreadsheetProps {
superHeaderText: string;
colSpecs: any;
}
export { Spreadsheet as default, Spreadsheet };
class Spreadsheet extends Component<SpreadsheetProps> {
header: SpreadsheetHeader;
layout: HeaderBodyLayout;
bodyContainerEl: HTMLElement;
bodyColGroup: HTMLElement;
bodyTbody: HTMLElement;
bodyColEls: HTMLElement[];
constructor(headParentEl: HTMLElement, bodyParentEl: HTMLElement);
render(props: SpreadsheetProps, context: ComponentContext): void;
destroy(): void;
_renderSkeleton(context: ComponentContext): void;
_unrenderSkeleton(): void;
_renderCells(superHeaderText: any, colSpecs: any): void;
_unrenderCells(): void;
renderColTags(colSpecs: any): string;
updateSize(isResize: any, totalHeight: any, isAuto: any): void;
applyColWidths(colWidths: (number | string)[]): void;
}
}
declare module '@fullcalendar/resource-timeline/Row' {
import { Component } from '@fullcalendar/core';
export { Row as default, Row };
abstract class Row<PropsType> extends Component<PropsType> {
spreadsheetTr: HTMLElement;
timeAxisTr: HTMLElement;
isSizeDirty: boolean;
constructor(spreadsheetParent: HTMLElement, spreadsheetNextSibling: HTMLElement, timeAxisParent: HTMLElement, timeAxisNextSibling: HTMLElement);
destroy(): void;
abstract getHeightEls(): HTMLElement[];
updateSize(isResize: boolean): void;
}
}
declare module '@fullcalendar/resource-timeline/SpreadsheetRow' {
import { Component } from '@fullcalendar/core';
import { Resource } from '@fullcalendar/resource-common';
export interface SpreadsheetRowProps {
colSpecs: any;
id: string;
rowSpans: number[];
depth: number;
isExpanded: boolean;
hasChildren: boolean;
resource: Resource;
}
export { SpreadsheetRow as default, SpreadsheetRow };
class SpreadsheetRow extends Component<SpreadsheetRowProps> {
tr: HTMLElement;
heightEl: HTMLElement;
expanderIconEl: HTMLElement;
constructor(tr: HTMLElement);
render(props: SpreadsheetRowProps): void;
destroy(): void;
renderRow(resource: Resource, rowSpans: number[], depth: number, colSpecs: any): void;
unrenderRow(): void;
updateExpanderIcon(hasChildren: boolean, isExpanded: boolean): void;
onExpanderClick: (ev: UIEvent) => void;
}
}
declare module '@fullcalendar/resource-timeline/SpreadsheetHeader' {
import { ElementDragging, Component, ComponentContext, EmitterMixin } from '@fullcalendar/core';
export interface SpreadsheetHeaderProps {
superHeaderText: string;
colSpecs: any;
colTags: string;
}
export { SpreadsheetHeader as default, SpreadsheetHeader };
class SpreadsheetHeader extends Component<SpreadsheetHeaderProps> {
parentEl: HTMLElement;
tableEl: HTMLElement;
resizerEls: HTMLElement[];
resizables: ElementDragging[];
thEls: HTMLElement[];
colEls: HTMLElement[];
colWidths: number[];
emitter: EmitterMixin;
constructor(parentEl: HTMLElement);
render(props: SpreadsheetHeaderProps, context: ComponentContext): void;
destroy(): void;
_renderSkeleton(context: ComponentContext): void;
_unrenderSkeleton(): void;
initColResizing(): void;
}
} | the_stack |
import { HttpProvider } from 'web3-core'
import { RelayProvider } from '@opengsn/provider/dist/RelayProvider'
import { Address, AsyncDataCallback } from '@opengsn/common/dist/types/Aliases'
import {
RelayHubInstance, StakeManagerInstance,
TestPaymasterEverythingAcceptedInstance, TestPaymasterPreconfiguredApprovalInstance,
TestRecipientInstance, TestTokenInstance
} from '@opengsn/contracts/types/truffle-contracts'
import { deployHub, emptyBalance, startRelay, stopRelay } from './TestUtils'
import { ChildProcessWithoutNullStreams } from 'child_process'
import { GSNConfig } from '@opengsn/provider/dist/GSNConfigurator'
import { registerForwarderForGsn } from '@opengsn/common/dist/EIP712/ForwarderUtil'
import { defaultEnvironment } from '@opengsn/common/dist/Environments'
import { constants, ether } from '@opengsn/common'
import Web3 from 'web3'
const TestRecipient = artifacts.require('TestRecipient')
const TestPaymasterEverythingAccepted = artifacts.require('TestPaymasterEverythingAccepted')
const TestPaymasterPreconfiguredApproval = artifacts.require('TestPaymasterPreconfiguredApproval')
const StakeManager = artifacts.require('StakeManager')
const Penalizer = artifacts.require('Penalizer')
const Forwarder = artifacts.require('Forwarder')
const TestToken = artifacts.require('TestToken')
const options = [
{
title: 'Direct-',
relay: false
},
{
title: 'Legacy Relayed-',
relay: true,
type: 0
},
{
title: 'Type 2 Relayed-',
relay: true,
type: 2
}
]
options.forEach(params => {
contract(params.title + 'Flow', function (accounts) {
let from: Address
let sr: TestRecipientInstance
let paymaster: TestPaymasterEverythingAcceptedInstance
let rhub: RelayHubInstance
let sm: StakeManagerInstance
let testToken: TestTokenInstance
const gasless = accounts[10]
let relayproc: ChildProcessWithoutNullStreams
let relayClientConfig: Partial<GSNConfig>
let relayProvider: RelayProvider
before(async () => {
await emptyBalance(gasless, accounts[0])
const gasPriceFactor = 1
testToken = await TestToken.new()
sm = await StakeManager.new(defaultEnvironment.maxUnstakeDelay, 0, 0, constants.BURN_ADDRESS, constants.BURN_ADDRESS)
const stake = 1e18.toString()
await testToken.mint(stake)
await testToken.approve(sm.address, stake)
const p = await Penalizer.new(defaultEnvironment.penalizerConfiguration.penalizeBlockDelay, defaultEnvironment.penalizerConfiguration.penalizeBlockExpiration)
rhub = await deployHub(sm.address, p.address, testToken.address, constants.ZERO_ADDRESS, stake)
await rhub.setMinimumStakes([testToken.address], [stake])
if (params.relay) {
relayproc = await startRelay(rhub.address, testToken, sm, {
stake,
stakeTokenAddress: testToken.address,
delay: 3600 * 24 * 7,
pctRelayFee: 12,
url: 'asd',
relayOwner: accounts[0],
// @ts-ignore
ethereumNodeUrl: web3.currentProvider.host,
gasPriceFactor,
initialReputation: 100,
workerTargetBalance: ether('5'),
value: ether('10'),
relaylog: process.env.relaylog
})
console.log('relay started')
}
const forwarder = await Forwarder.new()
// truffle uses web3.version 1.2.1 which doesn't support eip 1559.
// It passes both gasPrice and maxFeePerGas/maxPriorityFeePerGas to the node, which returns
// error: 'Cannot send both gasPrice and maxFeePerGas params'
// TODO update truffle version
// @ts-ignore
TestRecipient.web3 = new Web3(web3.currentProvider.host)
sr = await TestRecipient.new(forwarder.address)
await registerForwarderForGsn(forwarder)
paymaster = await TestPaymasterEverythingAccepted.new()
await paymaster.setTrustedForwarder(forwarder.address)
await paymaster.setRelayHub(rhub.address)
})
after(async function () {
await stopRelay(relayproc)
})
if (params.relay) {
before(params.title + 'enable relay', async function () {
await rhub.depositFor(paymaster.address, { value: (5e18).toString() })
relayClientConfig = {
loggerConfiguration: { logLevel: 'error' },
paymasterAddress: paymaster.address,
maxApprovalDataLength: 4,
maxPaymasterDataLength: 4
}
relayProvider = await RelayProvider.newProvider(
{
provider: web3.currentProvider as HttpProvider,
config: relayClientConfig
}).init()
// web3.setProvider(relayProvider)
// NOTE: in real application its enough to set the provider in web3.
// however, in Truffle, all contracts are built BEFORE the test have started, and COPIED the web3,
// so changing the global one is not enough...
// @ts-ignore
TestRecipient.web3.setProvider(relayProvider)
from = gasless
})
} else {
from = accounts[0]
}
it(params.title + 'send normal transaction', async () => {
console.log('running emitMessage (should succeed)')
let res
try {
const gas = await sr.contract.methods.emitMessage('hello').estimateGas()
res = await sr.emitMessage('hello', { from: from, gas })
} catch (e: any) {
console.log('error is ', e.message)
throw e
}
assert.equal('hello', res.logs[0].args.message)
})
it(params.title + 'send gasless transaction', async () => {
console.log('gasless=' + gasless)
console.log('running gasless-emitMessage (should fail for direct, succeed for relayed)')
let ex: Error | undefined
try {
const txDetails: any = { from: gasless, gas: 1e6 }
await fixTxDetails(txDetails, relayProvider)
const res = await sr.emitMessage('hello, from gasless', txDetails)
console.log('res after gasless emit:', res.logs[0].args.message)
} catch (e: any) {
ex = e
}
if (params.relay) {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
assert.ok(ex == null, `should succeed sending gasless transaction through relay. got: ${ex?.toString()}`)
} else {
// eslint-disable-next-line @typescript-eslint/no-base-to-string,@typescript-eslint/restrict-template-expressions
assert.ok(ex!.toString().indexOf('funds') > 0, `Expected Error with 'funds'. got: ${ex?.toString()}`)
}
})
it(params.title + 'running testRevert (should always fail)', async () => {
const txDetails: any = { from }
await fixTxDetails(txDetails, relayProvider)
await asyncShouldThrow(async () => {
await sr.testRevert(txDetails)
}, 'always fail')
})
if (params.relay) {
let approvalPaymaster: TestPaymasterPreconfiguredApprovalInstance
let relayProvider: RelayProvider
/**
* RelayServer has to oversupply gas in order to pass over all the 'remaining gas' checks and give enough gas
* to the recipient. We are setting 10M as a block gas limit, so cannot go much higher than 9M gas here.
*/
describe('with different gas limits', function () {
before(async function () {
relayProvider = await RelayProvider.newProvider(
{
provider: web3.currentProvider as HttpProvider,
config: relayClientConfig
}).init()
});
// note: cannot set 'innerGasLimit' too close to 'maxViewableGasLimit' and expect it to pass
[1e4, 1e5, 1e6, 1e7]
.forEach(innerGasLimit =>
it(`should calculate valid external tx gas limit for a transaction with inner call gas limit of ${innerGasLimit.toString()}`, async function () {
const gas = innerGasLimit
let res: any
try {
const txDetails: any = { from, gas }
await fixTxDetails(txDetails, relayProvider)
res = await sr.emitMessageNoParams(txDetails)
} catch (e: any) {
console.log('error is ', e.message)
throw e
}
const actual: BN = res.logs.find((e: any) => e.event === 'SampleRecipientEmitted').args.gasLeft
assert.closeTo(actual.toNumber(), innerGasLimit, 1500)
assert.equal('Method with no parameters', res.logs[0].args.message)
})
)
})
describe('request with approvaldata', () => {
before(async function () {
approvalPaymaster = await TestPaymasterPreconfiguredApproval.new()
await approvalPaymaster.setRelayHub(rhub.address)
await approvalPaymaster.setTrustedForwarder(await sr.getTrustedForwarder())
await rhub.depositFor(approvalPaymaster.address, { value: (1e18).toString() })
relayClientConfig = { ...relayClientConfig, ...{ paymasterAddress: approvalPaymaster.address }, performDryRunViewRelayCall: false }
const relayProvider = await RelayProvider.newProvider(
{
provider: web3.currentProvider as HttpProvider,
config: relayClientConfig
}).init()
// @ts-ignore
TestRecipient.web3.setProvider(relayProvider)
})
const setRecipientProvider = async function (asyncApprovalData: AsyncDataCallback): Promise<void> {
const relayProvider =
await RelayProvider.newProvider({
provider: web3.currentProvider as HttpProvider,
config: relayClientConfig,
overrideDependencies: { asyncApprovalData }
}).init()
// @ts-ignore
TestRecipient.web3.setProvider(relayProvider)
}
it(params.title + 'wait for specific approvalData', async () => {
try {
await approvalPaymaster.setExpectedApprovalData('0x414243', {
from: accounts[0],
// @ts-ignore
useGSN: false
})
await setRecipientProvider(async () => '0x414243')
const txDetails: any = {
from: gasless,
// @ts-ignore - it seems we still allow passing paymaster as a tx parameter
paymaster: approvalPaymaster.address,
gas: 1e6
}
await fixTxDetails(txDetails, relayProvider)
await sr.emitMessage('xxx', txDetails)
} catch (e: any) {
console.log('error1: ', e)
throw e
} finally {
await approvalPaymaster.setExpectedApprovalData('0x', {
from: accounts[0],
// @ts-ignore
useGSN: false
})
}
})
it(params.title + 'fail if asyncApprovalData throws', async () => {
await setRecipientProvider(() => { throw new Error('approval-exception') })
await asyncShouldThrow(async () => {
const txDetails: any = {
from: gasless,
// @ts-ignore
paymaster: approvalPaymaster.address
}
await fixTxDetails(txDetails, relayProvider)
await sr.emitMessage('xxx', txDetails)
}, 'approval-exception')
})
it(params.title + 'fail on no approval data', async () => {
try {
// @ts-ignore
await approvalPaymaster.setExpectedApprovalData(Buffer.from('hello1'), {
from: accounts[0],
useGSN: false
})
await asyncShouldThrow(async () => {
await setRecipientProvider(async () => '0x')
const txDetails: any = {
from: gasless
}
await fixTxDetails(txDetails, relayProvider)
await sr.emitMessage('xxx', txDetails)
}, 'unexpected approvalData: \'\' instead of')
} catch (e: any) {
console.log('error3: ', e)
throw e
} finally {
// @ts-ignore
await approvalPaymaster.setExpectedApprovalData(Buffer.from(''), {
from: accounts[0],
useGSN: false
})
}
})
})
}
async function fixTxDetails (txDetails: any, relayProvider: RelayProvider): Promise<void> {
if (params.relay) {
const { maxFeePerGas, maxPriorityFeePerGas } = await relayProvider.calculateGasFees()
if (params.type === 2) {
txDetails.maxFeePerGas = maxFeePerGas
txDetails.maxPriorityFeePerGas = maxPriorityFeePerGas
} else {
txDetails.gasPrice = maxPriorityFeePerGas
}
}
}
async function asyncShouldThrow (asyncFunc: () => Promise<any>, str?: string): Promise<void> {
const msg = str ?? 'Error'
let ex: Error | undefined
try {
await asyncFunc()
} catch (e: any) {
ex = e
}
assert.ok(ex != null, `Expected to throw ${msg} but threw nothing`)
const isExpectedError = ex?.toString().includes(msg)
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
assert.ok(isExpectedError, `Expected to throw ${msg} but threw ${ex?.message}`)
}
})
}) | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.