text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
type ModuleDescriptor = {
rpcHandle: string
methods: MethodDescriptor[]
}
type MethodDescriptor = { name: string }
type DecentralandInterface = {
loadModule(moduleName: string): PromiseLike<ModuleDescriptor>
callRpc(moduleHandle: string, methodName: string, args: ArrayLike<any>): PromiseLike<any>
onStart(cb: Function)
}
type Module = {
name: string
dclamd: 1 | 2
context: any
dependencies?: string[]
handlers: Function[]
exports: any
}
declare var dcl: DecentralandInterface
// A naive attempt at getting the global `this`. Don’t use `this`!
const getGlobalThis = function () {
// @ts-ignore
if (typeof globalThis !== 'undefined') return globalThis
// @ts-ignore
if (typeof self !== 'undefined') return self
// @ts-ignore
if (typeof window !== 'undefined') return window
// Note: this might still return the wrong result!
if (typeof this !== 'undefined') return this
throw new Error('Unable to locate global `this`')
}
const globalObject = (getGlobalThis as any)()
namespace loader {
'use strict'
const MODULE_LOADING = 1
const MODULE_READY = 2
let anonymousQueue = []
const settings = {
baseUrl: ''
}
const registeredModules: Record<string, Module> = {}
export function config(config) {
if (typeof config === 'object') {
for (let x in config) {
if (config.hasOwnProperty(x)) {
settings[x] = config[x]
}
}
}
}
function createModule(name: string, context?: any, handlers: Function[] = []): Module {
return {
name,
dclamd: MODULE_LOADING,
handlers,
context,
exports: {}
}
}
export function define(factory: any)
export function define(id: string, factory: any)
export function define(id: string, dependencies: string[], factory: any)
export function define(id: string, dependencies?, factory?) {
let argCount = arguments.length
if (argCount === 1) {
factory = id
dependencies = ['require', 'exports', 'module']
id = null
} else if (argCount === 2) {
if (settings.toString.call(id) === '[object Array]') {
factory = dependencies
dependencies = id
id = null
} else {
factory = dependencies
dependencies = ['require', 'exports', 'module']
}
}
if (!id) {
anonymousQueue.push([dependencies, factory])
return
}
function ready() {
let handlers, context
if (registeredModules[id]) {
handlers = registeredModules[id].handlers
context = registeredModules[id].context
} else {
registeredModules[id] = createModule(id)
}
let module = registeredModules[id]
module.exports =
typeof factory === 'function'
? factory.apply(null, anonymousQueue.slice.call(arguments, 0)) || registeredModules[id].exports || {}
: factory
module.dclamd = MODULE_READY
module.context = context
for (let x = 0, xl = handlers ? handlers.length : 0; x < xl; x++) {
handlers[x](module.exports)
}
}
if (!registeredModules[id]) registeredModules[id] = createModule(id)
updateExistingModuleIfIndexModule(id)
registeredModules[id].dependencies = dependencies.map((dep) => _toUrl(dep, id))
require(dependencies, ready, id)
}
function updateExistingModuleIfIndexModule(id: string) {
const idParts = id.split('/')
if (idParts[idParts.length - 1] === 'index' && idParts.length > 1) {
idParts.pop()
const noIndexId = idParts.join('/')
const existingModule = registeredModules[noIndexId]
registeredModules[noIndexId] = registeredModules[id]
if (existingModule) {
registeredModules[noIndexId].context = existingModule.context
registeredModules[noIndexId].handlers.push(...existingModule.handlers)
}
}
}
export namespace define {
export const amd = {}
}
function hasDependencyWith(moduleId: string, otherModuleId: string): boolean {
if (!registeredModules[moduleId] || !registeredModules[moduleId].dependencies) {
return false
}
const directDependencies = registeredModules[moduleId].dependencies
// Dependencies can be viewed as a graph. We keep track of the transitions between nodes that we have visited (to avoid infinite loop),
// and those that we want to visit next. We want to find all the nodes reachable from moduleId, to see if those inclued otherModuleId
const visited = [moduleId, 'require', 'exports', 'module']
// If the dependency is one of those automatically assumed visited, we know we have a dependency
if (visited.indexOf(otherModuleId) !== -1) return true
const toVisit = directDependencies.filter((dep) => visited.indexOf(dep) === -1)
while (toVisit.length > 0) {
// If among the nodes we want to visit we have the module, then we know we have a dependency
if (toVisit.indexOf(otherModuleId) !== -1) return true
const dependencyId = toVisit.shift()
visited.push(dependencyId)
const module = registeredModules[dependencyId]
if (module && module.dependencies) {
for (let i = 0; i < module.dependencies.length; i++) {
const moduleDependencyId = module.dependencies[i]
if (visited.indexOf(moduleDependencyId) === -1 && toVisit.indexOf(moduleDependencyId) === -1) {
toVisit.push(moduleDependencyId)
}
}
}
}
// If we have visited all the graph and we didn't find a dependency, then as far as we know, we don't have a dependency yet
return false
}
export function require(modules: string, callback?: Function, context?: string)
export function require(modules: string[], callback?: Function, context?: string)
export function require(modules: string | string[], callback?: Function, context?: string) {
let loadedModulesExports: any[] = []
let loadedCount = 0
let hasLoaded = false
if (typeof modules === 'string') {
if (registeredModules[modules] && registeredModules[modules].dclamd === MODULE_READY) {
return registeredModules[modules]
}
throw new Error(
modules + ' has not been defined. Please include it as a dependency in ' + context + "'s define()"
)
}
const xl = modules.length
for (let x = 0; x < xl; x++) {
switch (modules[x]) {
case 'require':
let _require: typeof require = function (new_module, callback) {
return require(new_module, callback, context)
} as any
_require.toUrl = function (module) {
return _toUrl(module, context)
}
loadedModulesExports[x] = _require
loadedCount++
break
case 'exports':
loadedModulesExports[x] = registeredModules[context].exports
loadedCount++
break
case 'module':
loadedModulesExports[x] = {
id: context,
uri: _toUrl(context)
}
loadedCount++
break
default:
// If we have a circular dependency, then we resolve the module even if it hasn't loaded yet
if (hasDependencyWith(modules[x], context)) {
loadedModulesExports[x] = registeredModules[modules[x]].exports
loadedCount++
} else {
load(
modules[x],
(loadedModuleExports) => {
loadedModulesExports[x] = loadedModuleExports
loadedCount++
if (loadedCount === xl && callback) {
hasLoaded = true
callback.apply(null, loadedModulesExports)
}
},
context
)
}
}
}
if (!hasLoaded && loadedCount === xl && callback) {
callback.apply(null, loadedModulesExports)
}
}
function createMethodHandler(rpcHandle: string, method: MethodDescriptor) {
return function () {
return dcl.callRpc(rpcHandle, method.name, anonymousQueue.slice.call(arguments, 0))
}
}
function load(moduleName: string, handler: Function, context: string) {
moduleName = context ? _toUrl(moduleName, context) : moduleName
if (registeredModules[moduleName]) {
if (registeredModules[moduleName].dclamd === MODULE_LOADING) {
handler && registeredModules[moduleName].handlers.push(handler)
} else {
handler && handler(registeredModules[moduleName].exports)
}
} else {
const module = (registeredModules[moduleName] = createModule(moduleName, context, [handler]))
if (moduleName.indexOf('@') === 0) {
if (typeof dcl !== 'undefined') {
dcl.loadModule(moduleName).then((descriptor: ModuleDescriptor) => {
let createdModuleExports = {}
for (let i in descriptor.methods) {
const method = descriptor.methods[i]
createdModuleExports[method.name] = createMethodHandler(descriptor.rpcHandle, method)
}
// This is somewhat repeated with the ready function above... Should refactor with clear head
module.dclamd = MODULE_READY
module.exports = createdModuleExports
const handlers = module.handlers
for (let i = 0; i < handlers.length; i++) {
handlers[i](createdModuleExports)
}
})
}
}
}
}
if (typeof dcl !== 'undefined') {
dcl.onStart(() => {
const notLoadedModules: Module[] = []
for (let i in registeredModules) {
if (registeredModules[i] && registeredModules[i].dclamd === MODULE_LOADING) {
notLoadedModules.push(registeredModules[i])
}
}
if (notLoadedModules.length) {
throw new Error(`These modules didn't load: ${notLoadedModules.map(($) => $.name).join(', ')}`)
}
})
}
function _toUrl(id: string, context?: string) {
let changed = false
switch (id) {
case 'require':
case 'exports':
case 'module':
return id
}
const newContext = (context || settings.baseUrl).split('/')
newContext.pop()
const idParts = id.split('/')
let i = idParts.length
while (--i) {
switch (idParts[0]) {
case '..':
newContext.pop()
case '.':
case '':
idParts.shift()
changed = true
}
}
return (newContext.length && changed ? newContext.join('/') + '/' : '') + idParts.join('/')
}
require.toUrl = _toUrl
}
globalObject.define = loader.define
globalObject.dclamd = loader | the_stack |
import { createBuilder } from '@develohpanda/fluent-builder';
import { beforeEach, describe, expect, it, jest } from '@jest/globals';
import { globalBeforeEach } from '../../__jest__/before-each';
import * as models from '../../models';
import { environmentModelSchema, requestGroupModelSchema } from '../../models/__schemas__/model-schemas';
import { Environment } from '../../models/environment';
import { Workspace } from '../../models/workspace';
import * as renderUtils from '../render';
jest.mock('electron');
const envBuilder = createBuilder(environmentModelSchema);
const reqGroupBuilder = createBuilder(requestGroupModelSchema);
describe('render tests', () => {
beforeEach(async () => {
await globalBeforeEach();
await models.project.all();
envBuilder.reset();
reqGroupBuilder.reset();
});
describe('render()', () => {
it('renders hello world', async () => {
const rendered = await renderUtils.render('Hello {{ msg }}!', {
msg: 'World',
});
expect(rendered).toBe('Hello World!');
});
it('renders custom tag: uuid', async () => {
const rendered = await renderUtils.render('Hello {% uuid %}!');
expect(rendered).toMatch(/Hello [a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}!/);
});
it('renders custom tag: timestamp', async () => {
const rendered = await renderUtils.render('Hello {% timestamp %}!');
expect(rendered).toMatch(/Hello \d{13}!/);
});
it('renders nested object', async () => {
const rendered = await renderUtils.render('Hello {{ users[0].name }}!', {
users: [
{
name: 'FooBar',
},
],
});
expect(rendered).toBe('Hello FooBar!');
});
it('returns invalid template', async () => {
const rendered = await renderUtils.render('Hello {{ msg }!', {
msg: 'World',
});
expect(rendered).toBe('Hello {{ msg }!');
});
it('handles variables using tag before tag is defined as expected (incorrect order)', async () => {
const rootEnvironment = envBuilder
.data({
consume: '{{ replaced }}',
hashed: "{% hash 'md5', 'hex', value %}",
replaced: "{{ hashed | replace('f67565de946a899a534fd908e7eef872', 'cat') }}",
value: 'ThisIsATopSecretValue',
})
.dataPropertyOrder({
'&': ['value', 'replaced', 'hashed', 'consume'],
})
.build();
const context = await renderUtils.buildRenderContext({ ancestors: [], rootEnvironment });
expect(context).toEqual({
value: 'ThisIsATopSecretValue',
hashed: 'f67565de946a899a534fd908e7eef872',
replaced: 'f67565de946a899a534fd908e7eef872',
consume: 'f67565de946a899a534fd908e7eef872',
});
// In runtime, this context is used to render, which re-evaluates the expression for replaced in the rootEnvironment by using the built context
// Regression test from issue 1917 - https://github.com/Kong/insomnia/issues/1917
const renderExpression = await renderUtils.render(rootEnvironment.data.replaced, context);
expect(renderExpression).toBe('cat');
});
});
describe('buildRenderContext()', () => {
it('cascades properly', async () => {
const ancestors = [
reqGroupBuilder.environment({ foo: 'parent', ancestor: true }).build(),
reqGroupBuilder.environment({ foo: 'grandparent', ancestor: true }).build(),
];
const rootEnvironment = envBuilder.data({ foo: 'root', root: true }).build();
const subEnvironment = envBuilder.data({ foo: 'sub', sub: true }).build();
const context = await renderUtils.buildRenderContext({ ancestors, rootEnvironment, subEnvironment });
expect(context).toEqual({
foo: 'parent',
ancestor: true,
root: true,
sub: true,
});
});
it('rendered recursive should not infinite loop', async () => {
const ancestors = [
reqGroupBuilder.environment({ recursive: '{{ recursive }}/hello' }).build(),
];
const context = await renderUtils.buildRenderContext({ ancestors });
// This is longer than 3 because it multiplies every time (1 -> 2 -> 4 -> 8)
expect(context).toEqual({
recursive: '{{ recursive }}/hello/hello/hello/hello/hello/hello/hello/hello',
});
});
it('does not recursive render if itself is not used in var', async () => {
const root = envBuilder.data({
proto: 'http',
domain: 'base.com',
url: '{{ proto }}://{{ domain }}',
}).build();
const sub = envBuilder.data({
proto: 'https',
domain: 'sub.com',
port: 8000,
url: '{{ proto }}://{{ domain }}:{{ port }}',
}).build();
const ancestors = [
reqGroupBuilder.environment({
proto: 'https',
domain: 'folder.com',
port: 7000,
}).build(),
];
const context = await renderUtils.buildRenderContext({ ancestors, rootEnvironment: root, subEnvironment: sub });
expect(context).toEqual({
proto: 'https',
domain: 'folder.com',
port: 7000,
url: 'https://folder.com:7000',
});
});
it('does the thing', async () => {
const root = envBuilder.data({ url: 'insomnia.rest' }).build();
const sub = envBuilder.data({ url: '{{ url }}/sub' }).build();
const ancestors = [
reqGroupBuilder.environment({
url: '{{ url }}/{{ name }}',
name: 'folder',
}).build(),
];
const context = await renderUtils.buildRenderContext({ ancestors, rootEnvironment: root, subEnvironment: sub });
expect(context).toEqual({
url: 'insomnia.rest/sub/folder',
name: 'folder',
});
});
it('render up to 3 recursion levels', async () => {
const ancestors = [
reqGroupBuilder.environment({
d: '/d',
c: '/c{{ d }}',
b: '/b{{ c }}',
a: '/a{{ b }}',
test: 'http://insomnia.rest{{ a }}',
}).build(),
];
const context = await renderUtils.buildRenderContext({ ancestors });
expect(context).toEqual({
d: '/d',
c: '/c/d',
b: '/b/c/d',
a: '/a/b/c/d',
test: 'http://insomnia.rest/a/b/c/d',
});
});
it('rendered sibling environment variables', async () => {
const ancestors = [
reqGroupBuilder.environment({
sibling: 'sibling',
test: '{{ sibling }}/hello',
}).build(),
];
const context = await renderUtils.buildRenderContext({ ancestors });
expect(context).toEqual({
sibling: 'sibling',
test: 'sibling/hello',
});
});
it('rendered parent environment variables', async () => {
const ancestors = [
reqGroupBuilder
.name('Parent')
.environment({
test: '{{ grandparent }} parent',
})
.build(),
reqGroupBuilder
.name('Grandparent')
.environment({
grandparent: 'grandparent',
})
.build(),
];
const context = await renderUtils.buildRenderContext({ ancestors });
expect(context).toEqual({
grandparent: 'grandparent',
test: 'grandparent parent',
});
});
it('rendered parent same name environment variables', async () => {
const ancestors = [
reqGroupBuilder
.name('Parent')
.environment({
base_url: '{{ base_url }}/resource',
})
.build(),
reqGroupBuilder
.name('Grandparent')
.environment({
base_url: 'https://insomnia.rest',
})
.build(),
];
const context = await renderUtils.buildRenderContext({ ancestors });
expect(context).toEqual({
base_url: 'https://insomnia.rest/resource',
});
});
it('rendered parent, ignoring sibling environment variables', async () => {
const ancestors = [
reqGroupBuilder
.name('Parent')
.environment({
host: 'parent.com',
})
.build(),
reqGroupBuilder
.name('Grandparent')
.environment({
host: 'grandparent.com',
node: {
admin: 'admin',
test: 'test',
port: 8080,
},
urls: {
admin: 'https://{{ host }}/{{ node.admin }}',
test: 'https://{{ host }}/{{ node.test }}',
},
})
.build(),
];
const context = await renderUtils.buildRenderContext({ ancestors });
expect(await renderUtils.render('{{ urls.admin }}/foo', context)).toBe(
'https://parent.com/admin/foo',
);
expect(await renderUtils.render('{{ urls.test }}/foo', context)).toBe(
'https://parent.com/test/foo',
);
});
it('renders child environment variables', async () => {
const ancestors = [
reqGroupBuilder
.name('Parent')
.environment({
parent: 'parent',
})
.build(),
reqGroupBuilder
.name('Grandparent')
.environment({
test: '{{ parent }} grandparent',
})
.build(),
];
const context = await renderUtils.buildRenderContext({ ancestors });
expect(context).toEqual({
parent: 'parent',
test: 'parent grandparent',
});
});
it('works with object arrays', async () => {
const ancestors = [
reqGroupBuilder
.name('Parent')
.environment({})
.build(),
reqGroupBuilder
.name('Grandparent')
.environment({
users: [
{
name: 'Foo',
},
{
name: 'Bar',
},
],
})
.build(),
];
const context = await renderUtils.buildRenderContext({ ancestors });
expect(context).toEqual({
users: [
{
name: 'Foo',
},
{
name: 'Bar',
},
],
});
});
it('works with ordered objects', async () => {
const obj = {
users: [
{
name: 'Foo',
id: 1,
},
{
name: 'Bar',
id: 2,
},
],
};
const order = {
'&': ['users'],
'&~|users~|0': ['id', 'name'],
'&~|users~|1': ['id', 'name'],
};
const requestGroup = reqGroupBuilder.name('Parent').environment(obj).environmentPropertyOrder(order).build();
const rootEnvironment = envBuilder.name('Parent').data(obj).dataPropertyOrder(order).build();
const subEnvironment = envBuilder.name('Sub').data(obj).dataPropertyOrder(order).build();
const groupCtx = await renderUtils.buildRenderContext({ ancestors: [requestGroup] });
const rootCtx = await renderUtils.buildRenderContext({ ancestors: [], rootEnvironment });
const subCtx = await renderUtils.buildRenderContext({ ancestors: [], subEnvironment });
const expected = {
users: [
{
id: 1,
name: 'Foo',
},
{
id: 2,
name: 'Bar',
},
],
};
expect(groupCtx).toEqual(expected);
expect(rootCtx).toEqual(expected);
expect(subCtx).toEqual(expected);
});
it('merges nested properties when rendering', async () => {
const ancestors = [
reqGroupBuilder
.name('Parent')
.environment({
parent: 'parent',
nested: {
common: 'parent',
parentA: 'pa',
parentB: 'pb',
},
}).build(),
reqGroupBuilder
.name('Grandparent')
.environment({
test: '{{ parent }} grandparent',
nested: {
common: 'grandparent',
grandParentA: 'gpa',
grandParentB: 'gpb',
},
}).build(),
];
const context = await renderUtils.buildRenderContext({ ancestors });
expect(context).toEqual({
parent: 'parent',
test: 'parent grandparent',
nested: {
common: 'parent',
grandParentA: 'gpa',
grandParentB: 'gpb',
parentA: 'pa',
parentB: 'pb',
},
});
});
it('cascades properly and renders', async () => {
const ancestors = [
reqGroupBuilder
.environment({
url: '{{ base_url }}/resource',
ancestor: true,
winner: 'folder parent',
})
.build(),
reqGroupBuilder
.environment({
ancestor: true,
winner: 'folder grandparent',
})
.build(),
];
const subEnvironment = envBuilder.data({
winner: 'sub',
sub: true,
base_url: 'https://insomnia.rest',
}).build();
const rootEnvironment = envBuilder.data({
winner: 'root',
root: true,
base_url: 'ignore this',
}).build();
const context = await renderUtils.buildRenderContext(
{ ancestors, rootEnvironment, subEnvironment },
);
expect(context).toEqual({
base_url: 'https://insomnia.rest',
url: 'https://insomnia.rest/resource',
ancestor: true,
winner: 'folder parent',
root: true,
sub: true,
});
});
it('handles variables using tag after tag is defined as expected (correct order)', async () => {
const rootEnvironment = envBuilder
.data({
consume: '{{ replaced }}',
hashed: "{% hash 'md5', 'hex', value %}",
replaced: "{{ hashed | replace('f67565de946a899a534fd908e7eef872', 'cat') }}",
value: 'ThisIsATopSecretValue',
})
.dataPropertyOrder({
'&': ['value', 'hashed', 'replaced', 'consume'],
})
.build();
const context = await renderUtils.buildRenderContext({ ancestors: [], rootEnvironment });
expect(context).toEqual({
value: 'ThisIsATopSecretValue',
hashed: 'f67565de946a899a534fd908e7eef872',
replaced: 'cat',
consume: 'cat',
});
});
it('handles variables being used in tags', async () => {
const rootEnvironment = envBuilder
.data({
hash_input: '{{ orderId }}{{ secret }}',
hash_input_expected: '123456789012345ThisIsATopSecretValue',
orderId: 123456789012345,
password: "{% hash 'sha512', 'hex', hash_input %}",
password_expected: "{% hash 'sha512', 'hex', hash_input_expected %}",
secret: 'ThisIsATopSecretValue',
})
.build();
const context = await renderUtils.buildRenderContext({ ancestors: [], rootEnvironment });
expect(context).toEqual({
hash_input: '123456789012345ThisIsATopSecretValue',
hash_input_expected: '123456789012345ThisIsATopSecretValue',
orderId: 123456789012345,
password:
'ea84d15f33d3f9e9098fe01659b1ea0599d345770bba20ba98bf9056676a83ffe6b5528b2451ad04badbf690cf3009a94c510121cc6897045f8bb4ba0826134c',
password_expected:
'ea84d15f33d3f9e9098fe01659b1ea0599d345770bba20ba98bf9056676a83ffe6b5528b2451ad04badbf690cf3009a94c510121cc6897045f8bb4ba0826134c',
secret: 'ThisIsATopSecretValue',
});
});
it('works with minimal parameters', async () => {
const context = await renderUtils.buildRenderContext({ });
expect(context).toEqual({});
});
});
describe('render()', () => {
it('correctly renders simple Object', async () => {
const newObj = await renderUtils.render(
{
foo: '{{ foo }}',
bar: 'bar',
baz: '{{ bad }}',
},
{
foo: 'bar',
bad: 'hi',
},
);
expect(newObj).toEqual({
foo: 'bar',
bar: 'bar',
baz: 'hi',
});
});
it('correctly renders complex Object', async () => {
const d = new Date();
const obj = {
foo: '{{ foo }}',
null: null,
bool: true,
date: d,
undef: undefined,
num: 1234,
nested: {
foo: '{{ foo }}',
arr: [1, 2, '{{ foo }}'],
},
};
const newObj = await renderUtils.render(obj, {
foo: 'bar',
});
expect(newObj).toEqual({
foo: 'bar',
null: null,
bool: true,
date: d,
undef: undefined,
num: 1234,
nested: {
foo: 'bar',
arr: [1, 2, 'bar'],
},
});
// Make sure original request isn't changed
expect(obj.foo).toBe('{{ foo }}');
expect(obj.nested.foo).toBe('{{ foo }}');
expect(obj.nested.arr[2]).toBe('{{ foo }}');
});
it('fails on bad template', async () => {
try {
await renderUtils.render(
{
foo: '{{ foo }',
bar: 'bar',
baz: '{{ bad }}',
},
{
foo: 'bar',
},
);
fail('Render should have failed');
} catch (err) {
expect(err.message).toContain('attempted to output null or undefined value');
}
});
it('keep on error setting', async () => {
const template = '{{ foo }} {% invalid "hi" %}';
const context = {
foo: 'bar',
};
const resultOnlyVars = await renderUtils.render(
template,
context,
null,
renderUtils.KEEP_ON_ERROR,
);
expect(resultOnlyVars).toBe('{{ foo }} {% invalid "hi" %}');
try {
await renderUtils.render(template, context, null);
fail('Render should not have succeeded');
} catch (err) {
expect(err.message).toBe('unknown block tag: invalid');
}
});
it('outputs correct error path', async () => {
const template = {
foo: [
{
bar: '{% foo %}',
},
],
};
try {
await renderUtils.render(template);
fail('Should have failed to render');
} catch (err) {
expect(err.path).toBe('foo[0].bar');
}
});
it('outputs correct error path when private first node', async () => {
const template = {
_foo: {
_bar: {
baz: '{% foo %}',
},
},
};
try {
await renderUtils.render(template);
fail('Should have failed to render');
} catch (err) {
expect(err.path).toBe('_bar.baz');
}
});
});
describe('getRenderedGrpcRequestMessage()', () => {
it('renders only the body for a grpc request ', async () => {
const w1 = await models.workspace.create();
const env = await models.environment.create({
parentId: w1._id,
data: {
foo: 'bar',
host: 'testb.in:9000',
},
});
const grpcRequest = await models.grpcRequest.create({
parentId: w1._id,
name: 'hi {{ foo }}',
url: '{{ host }}',
description: 'hi {{ foo }}',
body: {
text: '{ "prop": "{{ foo }}" }',
},
});
const request = await renderUtils.getRenderedGrpcRequestMessage({ request: grpcRequest, environmentId: env._id });
expect(request).toEqual(
expect.objectContaining({
text: '{ "prop": "bar" }',
}),
);
});
});
describe('getRenderedGrpcRequest()', () => {
let w1: Workspace;
let env: Environment;
beforeEach(async () => {
w1 = await models.workspace.create();
env = await models.environment.create({
parentId: w1._id,
data: {
foo: 'bar',
host: 'testb.in:9000',
},
});
});
it('renders all grpc request properties', async () => {
const grpcRequest = await models.grpcRequest.create({
parentId: w1._id,
name: 'hi {{ foo }}',
url: '{{ host }}',
description: 'hi {{ foo }}',
body: {
text: '{ "prop": "{{ foo }}" }',
},
});
const request = await renderUtils.getRenderedGrpcRequest({ request: grpcRequest, environmentId: env._id });
expect(request).toEqual(
expect.objectContaining({
name: 'hi bar',
url: 'testb.in:9000',
description: 'hi bar',
body: {
text: '{ "prop": "bar" }',
},
}),
);
});
it('renders but ignores the body for a grpc request ', async () => {
const grpcRequest = await models.grpcRequest.create({
parentId: w1._id,
name: 'hi {{ foo }}',
url: '{{ host }}',
description: 'hi {{ foo }}',
body: {
text: '{ "prop": "{{ foo }}" }',
},
});
const request = await renderUtils.getRenderedGrpcRequest({ request: grpcRequest, environmentId: env._id, skipBody: true });
expect(request).toEqual(
expect.objectContaining({
name: 'hi bar',
url: 'testb.in:9000',
description: 'hi bar',
body: {
text: '{ "prop": "{{ foo }}" }',
},
}),
);
});
it('should still render with bad description', async () => {
const grpcRequest = await models.grpcRequest.create({
parentId: w1._id,
name: 'hi {{ foo }}',
url: '{{ host }}',
description: 'hi {{ some error }}',
body: {
text: '{ "prop": "{{ foo }}" }',
},
});
const request = await renderUtils.getRenderedGrpcRequest({ request: grpcRequest, environmentId: env._id });
expect(request).toEqual(
expect.objectContaining({
name: 'hi bar',
url: 'testb.in:9000',
description: 'hi {{ some error }}',
body: {
text: '{ "prop": "bar" }',
},
}),
);
});
});
}); | the_stack |
import 'date-fns';
import 'react-app-polyfill/ie11';
import * as Yup from 'yup';
import {
AppBar,
Box,
Button,
CssBaseline,
FormControlLabel,
Grid,
InputAdornment,
Link,
Checkbox as MuiCheckbox,
Paper,
Toolbar,
Typography,
} from '@mui/material';
import {
Autocomplete,
AutocompleteData,
CheckboxData,
Checkboxes,
DatePicker,
DateTimePicker,
Debug,
RadioData,
Radios,
Select,
SelectData,
SwitchData,
Switches,
TextField,
TimePicker,
makeRequired,
makeValidate,
} from '../.';
import { Form } from 'react-final-form';
import { FormSubscription } from 'final-form';
import { StyledEngineProvider, ThemeProvider, createTheme } from '@mui/material/styles';
import { createFilterOptions } from '@mui/material/useAutocomplete';
import { styled } from '@mui/system';
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import ruLocale from 'date-fns/locale/ru';
const theme = createTheme({
components: {
MuiTextField: {
defaultProps: {
margin: 'normal',
},
},
MuiFormControl: {
defaultProps: {
margin: 'normal',
},
},
},
});
const Subscription = styled(Paper)(({ theme }) => ({
marginTop: theme.spacing(3),
padding: theme.spacing(3),
}));
/**
* Little helper to see how good rendering is
*/
class RenderCount extends React.Component {
renders = 0;
render() {
return <>{++this.renders}</>;
}
}
interface FormData {
planet_one: string;
planet: string[];
best: string[];
available: boolean;
switch: string[];
terms: boolean;
date: Date;
hello: string;
cities: string[];
gender: string;
birthday: Date;
break: Date;
hidden: string;
keyboardDateTime: Date;
dateTime: Date;
dateTimeLocale: Date;
firstName: string;
lastName: string;
}
const schema = Yup.object({
planet_one: Yup.string().required(),
planet: Yup.array().of(Yup.string().required()).min(1).required(),
best: Yup.array().of(Yup.string().required()).min(1).required(),
available: Yup.boolean().oneOf([true], 'We are not available!').required(),
switch: Yup.array().of(Yup.string().required()).min(1).required(),
terms: Yup.boolean().oneOf([true], 'Please accept the terms').required(),
date: Yup.date().required(),
hello: Yup.string().required(),
cities: Yup.array().of(Yup.string().required()).min(1).required(),
gender: Yup.string().required(),
birthday: Yup.date().required(),
break: Yup.date().required(),
hidden: Yup.string().required(),
keyboardDateTime: Yup.date().required(),
dateTime: Yup.date().required(),
dateTimeLocale: Yup.date().required(),
firstName: Yup.string().required(),
lastName: Yup.string().required(),
});
/**
* Uses the optional helper makeValidate function to format the error messages
* into something usable by final form.
*/
const validate = makeValidate(schema);
/**
* Grabs all the required fields from the schema so that they can be passed into
* the components without having to declare them in both the schema and the component.
*/
const required = makeRequired(schema);
function AppWrapper() {
return (
<StyledEngineProvider injectFirst>
<ThemeProvider theme={theme}>
<App />
</ThemeProvider>
</StyledEngineProvider>
);
}
function App() {
const subscription = { submitting: true };
const [subscriptionState, setSubscriptionState] = useState<FormSubscription | undefined>(subscription);
const onChange = () => {
setSubscriptionState(subscriptionState === undefined ? subscription : undefined);
};
return (
<Box mx={2}>
<CssBaseline />
<Subscription>
<FormControlLabel
control={
<MuiCheckbox
checked={subscriptionState !== undefined}
color="secondary"
onChange={onChange}
value={true}
/>
}
label="Enable React Final Form subscription render optimization. Watch the render count when interacting with the form."
/>
<Link
href="https://final-form.org/docs/react-final-form/types/FormProps#subscription"
target="_blank"
underline="hover"
>
Documentation
</Link>
</Subscription>
<MainForm subscription={subscriptionState} />
<Footer />
</Box>
);
}
const Offset = styled('div')(({ theme }) => theme.mixins.toolbar);
function Footer() {
return (
<>
<AppBar
sx={{ top: 'auto', bottom: 0, backgroundColor: 'lightblue' }}
color="inherit"
position="fixed"
elevation={0}
>
<Toolbar>
<Grid container spacing={1} alignItems="center" justifyContent="center" direction="row">
<Grid item>
<Link
href="https://github.com/lookfirst/mui-rff"
target="_blank"
color="textSecondary"
underline="hover"
variant="body1"
>
MUI-RFF Github Project
</Link>
</Grid>
</Grid>
</Toolbar>
</AppBar>
<Offset />
</>
);
}
const PaperInner = styled(Paper)(({ theme }) => ({
marginLeft: theme.spacing(3),
marginTop: theme.spacing(3),
padding: theme.spacing(3),
}));
function MainForm({ subscription }: { subscription: any }) {
const [submittedValues, setSubmittedValues] = useState<FormData | undefined>(undefined);
const autocompleteData: AutocompleteData[] = [
{ label: 'Earth', value: 'earth' },
{ label: 'Mars', value: 'mars' },
{ label: 'Venus', value: 'venus' },
{ label: 'Brown Dwarf Glese 229B', value: '229B' },
];
const checkboxData: CheckboxData[] = [
{ label: 'Ack', value: 'ack' },
{ label: 'Bar', value: 'bar' },
{ label: 'Foo', value: 'foo' },
{ label: 'Indeterminate', value: 'indeterminate', indeterminate: true },
];
const switchData: SwitchData[] = [
{ label: 'Ack', value: 'ack' },
{ label: 'Bar', value: 'bar' },
{ label: 'Foo', value: 'foo' },
];
const selectData: SelectData[] = [
{ label: 'Choose...', value: '', disabled: true },
{ label: 'San Diego', value: 'sandiego' },
{ label: 'San Francisco', value: 'sanfrancisco' },
{ label: 'Los Angeles', value: 'losangeles' },
{ label: 'Saigon', value: 'saigon' },
];
const radioData: RadioData[] = [
{ label: 'Female', value: 'female' },
{ label: 'Male', value: 'male' },
{ label: 'Both', value: 'both' },
];
const initialValues: FormData = {
planet_one: autocompleteData[1].value,
planet: [autocompleteData[1].value],
best: [],
switch: ['bar'],
available: false,
terms: false,
date: new Date('2014-08-18T21:11:54'),
hello: 'some text',
cities: ['losangeles'],
gender: '',
birthday: new Date('2014-08-18'),
break: new Date('2019-04-20T16:20:00'),
hidden: 'secret',
keyboardDateTime: new Date('2017-06-21T17:20:00'),
dateTime: new Date('2023-05-25T12:29:10'),
dateTimeLocale: new Date('2023-04-26T12:29:10'),
firstName: '',
lastName: '',
};
const onSubmit = (values: FormData) => {
setSubmittedValues(values);
};
const onReset = () => {
setSubmittedValues(undefined);
};
const helperText = '* Required';
const filter = createFilterOptions<AutocompleteData>();
let key = 0;
const formFields = [
<Autocomplete
key={key++}
label="Choose one planet"
name="planet_one"
multiple={false}
required={required.planet}
options={autocompleteData}
getOptionValue={(option) => option.value}
getOptionLabel={(option) => option.label}
renderOption={(props, option) => <li {...props}>{option.label}</li>}
disableCloseOnSelect={true}
helperText={helperText}
freeSolo={true}
onChange={(_event, newValue, reason, details) => {
if (newValue && reason === 'selectOption' && details?.option.inputValue) {
// Create a new value from the user input
autocompleteData.push({
value: details?.option.inputValue,
label: details?.option.inputValue,
});
}
}}
filterOptions={(options, params) => {
const filtered = filter(options, params);
// Suggest the creation of a new value
if (params.inputValue.length) {
filtered.push({
inputValue: params.inputValue,
label: `Add "${params.inputValue}"`,
value: params.inputValue,
});
}
return filtered;
}}
selectOnFocus
clearOnBlur
handleHomeEndKeys
/>,
<Autocomplete
key={key++}
label="Choose at least one planet"
name="planet"
multiple={true}
required={required.planet}
options={autocompleteData}
getOptionValue={(option) => option.value}
getOptionLabel={(option) => option.label}
disableCloseOnSelect={true}
renderOption={(props, option, { selected }) =>
option.inputValue ? (
option.label
) : (
<li {...props}>
<MuiCheckbox style={{ marginRight: 8 }} checked={selected} />
{option.label}
</li>
)
}
helperText={helperText}
freeSolo={true}
onChange={(_event, newValue, reason, details) => {
if (newValue && reason === 'selectOption' && details?.option.inputValue) {
// Create a new value from the user input
autocompleteData.push({
value: details?.option.inputValue,
label: details?.option.inputValue,
});
}
}}
filterOptions={(options, params) => {
const filtered = filter(options, params);
// Suggest the creation of a new value
if (params.inputValue !== '') {
filtered.push({
inputValue: params.inputValue,
label: `Add "${params.inputValue}"`,
value: params.inputValue,
});
}
return filtered;
}}
selectOnFocus
clearOnBlur
handleHomeEndKeys
textFieldProps={{
InputProps: {
startAdornment: <InputAdornment position="start">🪐</InputAdornment>,
endAdornment: <InputAdornment position="end">🪐</InputAdornment>,
},
}}
/>,
<Switches
key={key++}
label="Available"
name="available"
required={required.available}
data={{ label: 'available', value: 'available' }}
helperText={helperText}
/>,
<Switches
key={key++}
label="Check at least one..."
name="switch"
required={required.switch}
data={switchData}
helperText={helperText}
/>,
<Checkboxes
key={key++}
label="Check at least one..."
name="best"
required={required.best}
data={checkboxData}
helperText={helperText}
/>,
<Radios
key={key++}
label="Pick a gender"
name="gender"
required={required.gender}
data={radioData}
helperText={helperText}
/>,
<DatePicker
key={key++}
label="Birthday"
name="birthday"
required={required.birthday}
helperText={helperText}
/>,
<TimePicker key={key++} label="Break time" name="break" required={required.break} helperText={helperText} />,
<DateTimePicker
key={key++}
label="Pick a date and time"
name="dateTime"
required={required.dateTime}
helperText={helperText}
/>,
<DateTimePicker
key={key++}
label="Pick a date and time (russian locale)"
name="dateTimeLocale"
required={required.dateTimeLocale}
helperText={helperText}
locale={ruLocale}
/>,
<TextField key={key++} label="Hello world" name="hello" required={required.hello} helperText={helperText} />,
<TextField
key={key++}
label="Hidden text"
name="hidden"
type="password"
autoComplete="new-password"
required={required.hidden}
helperText={helperText}
/>,
<Select
key={key++}
label="Pick some cities..."
name="cities"
required={required.cities}
data={selectData}
multiple={true}
helperText="Woah helper text"
/>,
<Checkboxes
key={key++}
name="terms"
required={required.terms}
data={{
label: 'Do you accept the terms?',
value: true,
}}
helperText={helperText}
/>,
<TextField
key={key++}
label="Field with inputProps"
name="firstName"
required={true}
inputProps={{
autoComplete: 'name',
}}
/>,
<TextField key={key++} label="Field WITHOUT inputProps" name="lastName" required={true} />,
];
return (
<Paper sx={{ marginTop: 3, padding: 3, marginBottom: 5 }}>
<Form
onSubmit={onSubmit}
initialValues={submittedValues ? submittedValues : initialValues}
subscription={subscription}
validate={validate}
key={subscription as any}
render={({ handleSubmit, submitting }) => (
<form onSubmit={handleSubmit} noValidate={true} autoComplete="new-password">
<Grid container>
<Grid item xs={6}>
{formFields.map((field, index) => (
<Grid item key={index}>
{field}
</Grid>
))}
<Grid item>
<Button
type="button"
variant="contained"
onClick={onReset}
disabled={submitting}
sx={{ mt: 3, mr: 1 }}
color="inherit"
>
Reset
</Button>
<Button
variant="contained"
type="submit"
disabled={submitting}
sx={{ mt: 3, mr: 1 }}
>
Submit
</Button>
</Grid>
</Grid>
<Grid item xs={6}>
<Grid item>
<Paper sx={{ ml: 3, mt: 3, p: 3 }} elevation={3}>
<Typography>
<strong>Render count:</strong> <RenderCount />
</Typography>
</Paper>
</Grid>
<Grid item>
<PaperInner elevation={3}>
<Typography>
<strong>Form field data</strong>
</Typography>
<Debug />
</PaperInner>
</Grid>
<Grid item>
<PaperInner elevation={3}>
<Typography>
<strong>Submitted data</strong>
</Typography>
<pre>
{JSON.stringify(submittedValues ? submittedValues : {}, undefined, 2)}
</pre>
</PaperInner>
</Grid>
</Grid>
</Grid>
</form>
)}
/>
</Paper>
);
}
ReactDOM.render(<AppWrapper />, document.getElementById('root')); | the_stack |
import * as THREE from "three";
import { Env, Value } from "./Env";
import { ExprEvaluator, ExprEvaluatorContext, OperatorDescriptor } from "./ExprEvaluator";
import { ExprInstantiator, InstantiationContext } from "./ExprInstantiator";
import { ExprParser } from "./ExprParser";
import { ExprPool } from "./ExprPool";
import {
interpolatedPropertyDefinitionToJsonExpr,
isInterpolatedPropertyDefinition
} from "./InterpolatedPropertyDefs";
import { Pixels } from "./Pixels";
import { RGBA } from "./RGBA";
import { Definitions } from "./Theme";
export * from "./Env";
const exprEvaluator = new ExprEvaluator();
const exprInstantiator = new ExprInstantiator();
/**
* A visitor for {@link Expr} nodes.
*/
export interface ExprVisitor<Result, Context> {
visitNullLiteralExpr(expr: NullLiteralExpr, context: Context): Result;
visitBooleanLiteralExpr(expr: BooleanLiteralExpr, context: Context): Result;
visitNumberLiteralExpr(expr: NumberLiteralExpr, context: Context): Result;
visitStringLiteralExpr(expr: StringLiteralExpr, context: Context): Result;
visitObjectLiteralExpr(expr: ObjectLiteralExpr, context: Context): Result;
visitVarExpr(expr: VarExpr, context: Context): Result;
visitHasAttributeExpr(expr: HasAttributeExpr, context: Context): Result;
visitCallExpr(expr: CallExpr, context: Context): Result;
visitMatchExpr(expr: MatchExpr, context: Context): Result;
visitCaseExpr(expr: CaseExpr, context: Context): Result;
visitStepExpr(expr: StepExpr, context: Context): Result;
visitInterpolateExpr(expr: InterpolateExpr, context: Context): Result;
}
/**
* The dependencies of an {@link Expr}.
*/
export class ExprDependencies {
/**
* The properties needed to evaluate the {@link Expr}.
*/
readonly properties = new Set<string>();
/**
* `true` if the expression depends on the feature state.
*/
featureState?: boolean;
/**
* `true` if this expression cannot be cached.
*/
volatile?: boolean;
}
class ComputeExprDependencies implements ExprVisitor<void, ExprDependencies> {
static instance = new ComputeExprDependencies();
/**
* Gets the dependencies of an {@link Expr}.
*
* @param expr - The {@link Expr} to process.
* @param scope - The evaluation scope. Defaults to [[ExprScope.Value]].
* @param dependencies - The output [[Set]] of dependency names.
*/
static of(expr: Expr) {
const dependencies = new ExprDependencies();
expr.accept(this.instance, dependencies);
return dependencies;
}
visitNullLiteralExpr(expr: NullLiteralExpr, context: ExprDependencies): void {
// nothing to do
}
visitBooleanLiteralExpr(expr: BooleanLiteralExpr, context: ExprDependencies): void {
// nothing to do
}
visitNumberLiteralExpr(expr: NumberLiteralExpr, context: ExprDependencies): void {
// nothing to do
}
visitStringLiteralExpr(expr: StringLiteralExpr, context: ExprDependencies): void {
// nothing to do
}
visitObjectLiteralExpr(expr: ObjectLiteralExpr, context: ExprDependencies): void {
// nothing to do
}
visitVarExpr(expr: VarExpr, context: ExprDependencies): void {
context.properties.add(expr.name);
}
visitHasAttributeExpr(expr: HasAttributeExpr, context: ExprDependencies): void {
context.properties.add(expr.name);
}
visitCallExpr(expr: CallExpr, context: ExprDependencies): void {
expr.args.forEach(childExpr => childExpr.accept(this, context));
switch (expr.op) {
case "dynamic-properties":
context.volatile = true;
break;
case "feature-state":
context.featureState = true;
context.properties.add("$state");
context.properties.add("$id");
break;
case "id":
context.properties.add("$id");
break;
case "zoom":
case "world-ppi-scale":
case "world-discrete-ppi-scale":
context.properties.add("$zoom");
break;
case "geometry-type":
context.properties.add("$geometryType");
break;
default:
break;
}
}
visitMatchExpr(expr: MatchExpr, context: ExprDependencies): void {
expr.value.accept(this, context);
expr.branches.forEach(([_, branch]) => branch.accept(this, context));
expr.fallback.accept(this, context);
}
visitCaseExpr(expr: CaseExpr, context: ExprDependencies): void {
expr.branches.forEach(([condition, branch]) => {
condition.accept(this, context);
branch.accept(this, context);
});
expr.fallback.accept(this, context);
}
visitStepExpr(expr: StepExpr, context: ExprDependencies): void {
expr.input.accept(this, context);
expr.defaultValue.accept(this, context);
expr.stops.forEach(([_, value]) => value.accept(this, context));
}
visitInterpolateExpr(expr: InterpolateExpr, context: ExprDependencies): void {
expr.input.accept(this, context);
expr.stops.forEach(([_, value]) => value.accept(this, context));
}
}
/**
* A type represeting JSON values.
*/
export type JsonValue = null | boolean | number | string | JsonObject | JsonArray;
/**
* A type representing JSON arrays.
*/
export interface JsonArray extends Array<JsonValue> {}
/**
* A type representing JSON objects.
*/
export interface JsonObject {
[name: string]: JsonValue;
}
/**
* The JSON representation of an {@link Expr} object.
*/
export type JsonExpr = JsonArray;
export function isJsonExpr(v: any): v is JsonExpr {
return Array.isArray(v) && v.length > 0 && typeof v[0] === "string";
}
/**
* Internal state needed by {@link Expr.fromJSON} to resolve `"ref"` expressions.
*/
interface ReferenceResolverState {
definitions: Definitions;
lockedNames: Set<string>;
cache: Map<string, Expr>;
}
/**
* The evaluation scope of an {@link Expr}.
*/
export enum ExprScope {
/**
* The scope of an {@link Expr} used as value of an attribute.
*/
Value,
/**
* The scope of an {@link Expr} used in a [[Technique]] `when` condition.
*/
Condition,
/**
* The scope of an {@link Expr} used as dynamic property attribute value.
*/
Dynamic
}
/**
* Abstract class representing the
* {@link https://github.com/heremaps/harp.gl/blob/master/%40here/harp-datasource-protocol/StyleExpressions.md | style expressions}
* used in {@link Theme}.
*/
export abstract class Expr {
/**
* Tests of given value is an {@link Expr}.
*
* @param value - The object to test.
*/
static isExpr(value: any): value is Expr {
return value instanceof Expr;
}
/**
* Creates an expression from the given `code`.
*
* @param code - The code to parse.
* @returns The parsed {@link Expr}.
* @deprecated `string` encoded expression are deprecated. Use {@link Expr.fromJSON} instead.
*/
static parse(code: string): Expr | never {
const parser = new ExprParser(code);
const expr = parser.parse();
return expr;
}
/**
* Creates a style expression from JSON.
*
* @remarks
* The optional set of {@link Theme.definitions | definitions} is used
* to resolve the {@link https://github.com/heremaps/harp.gl/blob/master/%40here/harp-datasource-protocol/StyleExpressions.md#ref | ref expressions}.
*
* @param json - JSON object representing the expression to parse.
* @param definitions - Optional set of definitions used to expand references.
* @param definitionExprCache - Optional cache of `Expr` instances
*
* @example
* ```typescript
* const expr = Expr.fromJSON(["all",
* ["==", ["geometry-type"], "LineString"],
* ["has", "text"]
* ]);
* ```
*/
static fromJSON(
json: JsonValue,
definitions?: Definitions,
definitionExprCache?: Map<string, Expr>
) {
const referenceResolverState: ReferenceResolverState | undefined =
definitions !== undefined
? {
definitions,
lockedNames: new Set(),
cache: definitionExprCache ?? new Map<string, Expr>()
}
: undefined;
return parseNode(json, referenceResolverState);
}
private m_dependencies?: ExprDependencies;
private m_isDynamic?: boolean;
/**
* Evaluate an expression returning a {@link Value} object.
*
* @param env - The {@link Env} used to lookup symbols.
* @param scope - The evaluation scope. Defaults to [[ExprScope.Value]].
* @param cache - A cache of previously computed results.
*/
evaluate(
env: Env,
scope: ExprScope = ExprScope.Value,
cache?: Map<Expr, Value>
): Value | never {
return this.accept(
exprEvaluator,
new ExprEvaluatorContext(exprEvaluator, env, scope, cache)
);
}
/**
* Instantiates this {@link Expr}.
*
* @remarks
* references to the `get` and `has` operator using the given instantiation context.
*
* @param context - The [[InstantationContext]] used to resolve names.
*/
instantiate(context: InstantiationContext): Expr {
return this.accept(exprInstantiator, context);
}
/**
* Gets the dependencies of this {@link Expr}.
*/
dependencies(): ExprDependencies {
if (!this.m_dependencies) {
this.m_dependencies = ComputeExprDependencies.of(this);
}
return this.m_dependencies;
}
/**
* Create a unique object that is structurally equivalent to this {@link Expr}.
*
* @param pool - The [[ExprPool]] used to create a unique
* equivalent object of this {@link Expr}.
*/
intern(pool: ExprPool): Expr {
return pool.add(this);
}
toJSON(): JsonValue {
return new ExprSerializer().serialize(this);
}
/**
* Returns `true` if a dynamic execution context is required to evaluate this {@link Expr}.
*/
isDynamic(): boolean {
if (this.m_isDynamic === undefined) {
this.m_isDynamic = this.exprIsDynamic();
}
return this.m_isDynamic;
}
/**
* Visits this expression.
*
* @param visitor The visitor used to visit the expression.
* @param context The context passed to the vistor.
*/
abstract accept<Result, Context>(
visitor: ExprVisitor<Result, Context>,
context: Context
): Result;
/**
* Update the dynamic state of this {@link Expr}.
*
* `exprIsDynamic` must never be called directly.
* @internal
*/
protected abstract exprIsDynamic(): boolean;
}
/**
* @internal
*/
export type RelationalOp = "<" | ">" | "<=" | ">=";
/**
* @internal
*/
export type EqualityOp = "~=" | "^=" | "$=" | "==" | "!=";
/**
* @internal
*/
export type BinaryOp = RelationalOp | EqualityOp;
/**
* A node representing a `get` expression.
*/
export class VarExpr extends Expr {
constructor(readonly name: string) {
super();
}
/** @override */
accept<Result, Context>(visitor: ExprVisitor<Result, Context>, context: Context): Result {
return visitor.visitVarExpr(this, context);
}
/** @override */
protected exprIsDynamic() {
return false;
}
}
/**
* A node representing a `literal` expression.
*/
export abstract class LiteralExpr extends Expr {
/**
* Create a [[LiteralExpr]] from the given value.
*
* @param value - A constant value.
*/
static fromValue(value: Value): Expr {
switch (typeof value) {
case "boolean":
return new BooleanLiteralExpr(value);
case "number":
return new NumberLiteralExpr(value);
case "string":
return new StringLiteralExpr(value);
case "object":
return value === null ? NullLiteralExpr.instance : new ObjectLiteralExpr(value);
default:
throw new Error(`failed to create a literal from '${value}'`);
} // switch
}
abstract get value(): Value;
/** @override */
protected exprIsDynamic() {
return false;
}
}
/**
* Null literal expression.
*/
export class NullLiteralExpr extends LiteralExpr {
static instance = new NullLiteralExpr();
/** @override */
readonly value: Value = null;
protected constructor() {
super();
}
/** @override */
accept<Result, Context>(visitor: ExprVisitor<Result, Context>, context: Context): Result {
return visitor.visitNullLiteralExpr(this, context);
}
/** @override */
protected exprIsDynamic() {
return false;
}
}
/**
* Boolean literal expression.
*/
export class BooleanLiteralExpr extends LiteralExpr {
constructor(readonly value: boolean) {
super();
}
/** @override */
accept<Result, Context>(visitor: ExprVisitor<Result, Context>, context: Context): Result {
return visitor.visitBooleanLiteralExpr(this, context);
}
}
/**
* Number literal expression.
*/
export class NumberLiteralExpr extends LiteralExpr {
constructor(readonly value: number) {
super();
}
/** @override */
accept<Result, Context>(visitor: ExprVisitor<Result, Context>, context: Context): Result {
return visitor.visitNumberLiteralExpr(this, context);
}
}
/**
* String literal expression.
*/
export class StringLiteralExpr extends LiteralExpr {
private m_promotedValue?: RGBA | Pixels | null;
constructor(readonly value: string) {
super();
}
/**
* Returns the value of parsing this string as [[RGBA]] or [[Pixels]] constant.
*/
get promotedValue(): RGBA | Pixels | undefined {
if (this.m_promotedValue === undefined) {
this.m_promotedValue = RGBA.parse(this.value) ?? Pixels.parse(this.value) ?? null;
}
return this.m_promotedValue ?? undefined;
}
/** @override */
accept<Result, Context>(visitor: ExprVisitor<Result, Context>, context: Context): Result {
return visitor.visitStringLiteralExpr(this, context);
}
}
/**
* Object literal expression.
*/
export class ObjectLiteralExpr extends LiteralExpr {
constructor(readonly value: object) {
super();
}
get isArrayLiteral() {
return Array.isArray(this.value);
}
/** @override */
accept<Result, Context>(visitor: ExprVisitor<Result, Context>, context: Context): Result {
return visitor.visitObjectLiteralExpr(this, context);
}
}
/**
* A node reperesenting a `has` expression.
*/
export class HasAttributeExpr extends Expr {
constructor(readonly name: string) {
super();
}
/** @override */
accept<Result, Context>(visitor: ExprVisitor<Result, Context>, context: Context): Result {
return visitor.visitHasAttributeExpr(this, context);
}
/** @override */
protected exprIsDynamic() {
return false;
}
}
/**
* A node representing a `call` expression.
*/
export class CallExpr extends Expr {
descriptor?: OperatorDescriptor;
constructor(readonly op: string, readonly args: Expr[]) {
super();
}
/**
* Returns the child nodes of this {@link Expr}.
*
* @deprecated Use {@link CallExpr.args} instead.
*/
get children() {
return this.args;
}
/** @override */
accept<Result, Context>(visitor: ExprVisitor<Result, Context>, context: Context): Result {
return visitor.visitCallExpr(this, context);
}
/** @override */
protected exprIsDynamic() {
const descriptor = this.descriptor ?? ExprEvaluator.getOperator(this.op);
if (descriptor && descriptor.isDynamicOperator && descriptor.isDynamicOperator(this)) {
return true;
}
return this.args.some(e => e.isDynamic());
}
}
/**
* The labels of a {@link MatchExpr} expression.
*/
export type MatchLabel = number | string | number[] | string[];
/**
* A node representing a `match` expression.
*/
export class MatchExpr extends Expr {
/**
* Tests if the given JSON node is a valid label for the `"match"` operator.
*
* @param node - A JSON value.
*/
static isValidMatchLabel(node: JsonValue): node is MatchLabel {
switch (typeof node) {
case "number":
case "string":
return true;
case "object":
if (!Array.isArray(node) || node.length === 0) {
return false;
}
const elementTy = typeof node[0];
if (elementTy === "number" || elementTy === "string") {
return node.every(t => typeof t === elementTy);
}
return false;
default:
return false;
} // switch
}
constructor(
readonly value: Expr,
readonly branches: Array<[MatchLabel, Expr]>,
readonly fallback: Expr
) {
super();
}
/** @override */
accept<Result, Context>(visitor: ExprVisitor<Result, Context>, context: Context): Result {
return visitor.visitMatchExpr(this, context);
}
/** @override */
protected exprIsDynamic() {
return (
this.value.isDynamic() ||
this.branches.some(([_, branch]) => branch.isDynamic()) ||
this.fallback.isDynamic()
);
}
}
/**
* A node representing a `case` expression.
*/
export class CaseExpr extends Expr {
constructor(readonly branches: Array<[Expr, Expr]>, readonly fallback: Expr) {
super();
}
/** @override */
accept<Result, Context>(visitor: ExprVisitor<Result, Context>, context: Context): Result {
return visitor.visitCaseExpr(this, context);
}
/** @override */
protected exprIsDynamic() {
return (
this.branches.some(([cond, branch]) => cond.isDynamic() || branch.isDynamic()) ||
this.fallback.isDynamic()
);
}
}
/**
* A node representing a `step` expression.
*/
export class StepExpr extends Expr {
constructor(
readonly input: Expr,
readonly defaultValue: Expr,
readonly stops: Array<[number, Expr]>
) {
super();
}
/** @override */
accept<Result, Context>(visitor: ExprVisitor<Result, Context>, context: Context): Result {
return visitor.visitStepExpr(this, context);
}
/** @override */
protected exprIsDynamic(): boolean {
return (
this.input.isDynamic() ||
this.defaultValue.isDynamic() ||
this.stops.some(([_, value]) => value.isDynamic())
);
}
}
/**
* The type of the interpolation mode.
*/
export type InterpolateMode = ["discrete"] | ["linear"] | ["cubic"] | ["exponential", number];
/**
* A node representing an `interpolate` expression.
*/
export class InterpolateExpr extends Expr {
constructor(
readonly mode: InterpolateMode,
readonly input: Expr,
readonly stops: Array<[number, Expr]>
) {
super();
}
/** @override */
accept<Result, Context>(visitor: ExprVisitor<Result, Context>, context: Context): Result {
return visitor.visitInterpolateExpr(this, context);
}
/** @override */
protected exprIsDynamic(): boolean {
return this.input.isDynamic() || this.stops.some(([_, value]) => value.isDynamic());
}
}
/**
* Serializes the Expr to JSON.
*
* @internal
*/
class ExprSerializer implements ExprVisitor<JsonValue, void> {
serialize(expr: Expr): JsonValue {
return expr.accept(this, undefined);
}
visitNullLiteralExpr(expr: NullLiteralExpr, context: void): JsonValue {
return null;
}
visitBooleanLiteralExpr(expr: BooleanLiteralExpr, context: void): JsonValue {
return expr.value;
}
visitNumberLiteralExpr(expr: NumberLiteralExpr, context: void): JsonValue {
return expr.value;
}
visitStringLiteralExpr(expr: StringLiteralExpr, context: void): JsonValue {
return expr.value;
}
visitObjectLiteralExpr(expr: ObjectLiteralExpr, context: void): JsonValue {
if (expr.value instanceof THREE.Vector2) {
return ["make-vector", expr.value.x, expr.value.y];
} else if (expr.value instanceof THREE.Vector3) {
return ["make-vector", expr.value.x, expr.value.y, expr.value.z];
} else if (expr.value instanceof THREE.Vector4) {
return ["make-vector", expr.value.x, expr.value.y, expr.value.z, expr.value.w];
}
return ["literal", expr.value as JsonObject];
}
visitVarExpr(expr: VarExpr, context: void): JsonValue {
return ["get", expr.name];
}
visitHasAttributeExpr(expr: HasAttributeExpr, context: void): JsonValue {
return ["has", expr.name];
}
visitCallExpr(expr: CallExpr, context: void): JsonValue {
return [expr.op, ...expr.args.map(childExpr => this.serialize(childExpr))];
}
visitMatchExpr(expr: MatchExpr, context: void): JsonValue {
const branches: JsonValue[] = [];
for (const [label, body] of expr.branches) {
branches.push(label, this.serialize(body));
}
return ["match", this.serialize(expr.value), ...branches, this.serialize(expr.fallback)];
}
visitCaseExpr(expr: CaseExpr, context: void): JsonValue {
const branches: JsonValue[] = [];
for (const [condition, body] of expr.branches) {
branches.push(this.serialize(condition), this.serialize(body));
}
return ["case", ...branches, this.serialize(expr.fallback)];
}
visitStepExpr(expr: StepExpr, context: void): JsonValue {
const result: JsonArray = ["step"];
result.push(this.serialize(expr.input));
result.push(this.serialize(expr.defaultValue));
expr.stops.forEach(([key, value]) => {
result.push(key);
result.push(this.serialize(value));
});
return result;
}
visitInterpolateExpr(expr: InterpolateExpr, context: void): JsonValue {
const result: JsonArray = ["interpolate", expr.mode];
result.push(this.serialize(expr.input));
expr.stops.forEach(([key, value]) => {
result.push(key);
result.push(this.serialize(value));
});
return result;
}
}
function parseNode(
node: JsonValue,
referenceResolverState: ReferenceResolverState | undefined
): Expr {
if (Array.isArray(node)) {
return parseCall(node, referenceResolverState);
} else if (node === null) {
return NullLiteralExpr.instance;
} else if (typeof node === "boolean") {
return new BooleanLiteralExpr(node);
} else if (typeof node === "number") {
return new NumberLiteralExpr(node);
} else if (typeof node === "string") {
return new StringLiteralExpr(node);
}
throw new Error(`failed to create expression from: ${JSON.stringify(node)}`);
}
function parseCall(node: JsonArray, referenceResolverState?: ReferenceResolverState): Expr {
const op = node[0];
if (typeof op !== "string") {
throw new Error("expected a builtin function name");
}
switch (op) {
case "!has":
case "!in":
return new CallExpr("!", [parseCall([op.slice(1), ...node.slice(1)])]);
case "ref":
return resolveReference(node, referenceResolverState);
case "get":
return parseGetExpr(node, referenceResolverState);
case "has":
return parseHasExpr(node, referenceResolverState);
case "literal":
return parseLiteralExpr(node);
case "match":
return parseMatchExpr(node, referenceResolverState);
case "case":
return parseCaseExpr(node, referenceResolverState);
case "interpolate":
return parseInterpolateExpr(node, referenceResolverState);
case "step":
return parseStepExpr(node, referenceResolverState);
default:
return makeCallExpr(op, node, referenceResolverState);
} // switch
}
function parseGetExpr(node: JsonArray, referenceResolverState: ReferenceResolverState | undefined) {
if (node[2] !== undefined) {
return makeCallExpr("get", node, referenceResolverState);
}
const name = node[1];
if (typeof name !== "string") {
throw new Error(`expected the name of an attribute`);
}
return new VarExpr(name);
}
function parseHasExpr(node: JsonArray, referenceResolverState: ReferenceResolverState | undefined) {
if (node[2] !== undefined) {
return makeCallExpr("has", node, referenceResolverState);
}
const name = node[1];
if (typeof name !== "string") {
throw new Error(`expected the name of an attribute`);
}
return new HasAttributeExpr(name);
}
function parseLiteralExpr(node: JsonArray) {
const obj = node[1];
if (obj === null || typeof obj !== "object") {
throw new Error("expected an object or array literal");
}
return new ObjectLiteralExpr(obj);
}
function parseMatchExpr(
node: JsonArray,
referenceResolverState: ReferenceResolverState | undefined
) {
if (node.length < 4) {
throw new Error("not enough arguments");
}
if (!(node.length % 2)) {
throw new Error("fallback is missing in 'match' expression");
}
const value = parseNode(node[1], referenceResolverState);
const conditions: Array<[MatchLabel, Expr]> = [];
for (let i = 2; i < node.length - 1; i += 2) {
const label = node[i];
if (!MatchExpr.isValidMatchLabel(label)) {
throw new Error(`'${JSON.stringify(label)}' is not a valid label for 'match'`);
}
const expr = parseNode(node[i + 1], referenceResolverState);
conditions.push([label, expr]);
}
const fallback = parseNode(node[node.length - 1], referenceResolverState);
return new MatchExpr(value, conditions, fallback);
}
function parseCaseExpr(
node: JsonArray,
referenceResolverState: ReferenceResolverState | undefined
) {
if (node.length < 3) {
throw new Error("not enough arguments");
}
if (node.length % 2) {
throw new Error("fallback is missing in 'case' expression");
}
const branches: Array<[Expr, Expr]> = [];
for (let i = 1; i < node.length - 1; i += 2) {
const condition = parseNode(node[i], referenceResolverState);
const expr = parseNode(node[i + 1], referenceResolverState);
branches.push([condition, expr]);
}
const caseFallback = parseNode(node[node.length - 1], referenceResolverState);
return new CaseExpr(branches, caseFallback);
}
function isInterpolationMode(object: any): object is InterpolateMode {
if (!Array.isArray(object)) {
return false;
}
switch (object[0]) {
case "discrete":
case "linear":
case "cubic":
case "exponential":
return true;
default:
return false;
}
}
function parseInterpolateExpr(
node: JsonArray,
referenceResolverState: ReferenceResolverState | undefined
) {
const mode: InterpolateMode = node[1] as any;
if (!isInterpolationMode(mode)) {
throw new Error("expected an interpolation type");
}
if (mode[0] === "exponential" && typeof mode[1] !== "number") {
throw new Error("expected the base of the exponential interpolation");
}
const input = node[2] !== undefined ? parseNode(node[2], referenceResolverState) : undefined;
if (!Expr.isExpr(input)) {
throw new Error(`expected the input of the interpolation`);
}
if (node.length === 3 || !(node.length % 2)) {
throw new Error("invalid number of samples");
}
const stops: Array<[number, Expr]> = [];
for (let i = 3; i < node.length - 1; i += 2) {
const key = node[i] as number;
const value = parseNode(node[i + 1], referenceResolverState);
stops.push([key, value]);
}
return new InterpolateExpr(mode, input, stops);
}
function parseStepExpr(
node: JsonArray,
referenceResolverState: ReferenceResolverState | undefined
) {
if (node.length < 2) {
throw new Error("expected the input of the 'step' operator");
}
if (node.length < 3 || !(node.length % 2)) {
throw new Error("not enough arguments");
}
const input = parseNode(node[1], referenceResolverState);
const defaultValue = parseNode(node[2], referenceResolverState);
const stops: Array<[number, Expr]> = [];
for (let i = 3; i < node.length; i += 2) {
const key = node[i] as number;
const value = parseNode(node[i + 1], referenceResolverState);
stops.push([key, value]);
}
return new StepExpr(input, defaultValue, stops);
}
function makeCallExpr(
op: string,
node: any[],
referenceResolverState?: ReferenceResolverState
): Expr {
return new CallExpr(
op,
node.slice(1).map(childExpr => parseNode(childExpr, referenceResolverState))
);
}
function resolveReference(node: JsonArray, referenceResolverState?: ReferenceResolverState) {
if (typeof node[1] !== "string") {
throw new Error(`expected the name of an attribute`);
}
if (referenceResolverState === undefined) {
throw new Error(`ref used with no definitions`);
}
const name = node[1] as string;
if (referenceResolverState.lockedNames.has(name)) {
throw new Error(`circular referene to '${name}'`);
}
if (!(name in referenceResolverState.definitions)) {
throw new Error(`definition '${name}' not found`);
}
const cachedEntry = referenceResolverState.cache.get(name);
if (cachedEntry !== undefined) {
return cachedEntry;
}
let definitionEntry = referenceResolverState.definitions[name] as any;
let result: Expr;
if (isInterpolatedPropertyDefinition(definitionEntry.value)) {
// found a reference to an interpolation using
// the deprecated object-like syntax.
return Expr.fromJSON(interpolatedPropertyDefinitionToJsonExpr(definitionEntry.value));
} else if (isJsonExpr(definitionEntry.value)) {
definitionEntry = definitionEntry.value;
} else {
return Expr.fromJSON(definitionEntry.value);
}
if (isJsonExpr(definitionEntry)) {
referenceResolverState.lockedNames.add(name);
try {
result = parseNode(definitionEntry, referenceResolverState);
} finally {
referenceResolverState.lockedNames.delete(name);
}
} else {
throw new Error(`unsupported definition ${name}`);
}
referenceResolverState.cache.set(name, result);
return result;
} | the_stack |
import _ from 'lodash'
import { Reducer } from 'redux'
import { REHYDRATE } from 'redux-persist/lib/constants'
import { ShortcutCombo, ShortcutType } from 'constants/shortcut'
import Theme from 'constants/theme'
import { SerializedAction } from 'libs/Action'
import { HighlightColors, SerializedHighlight } from 'libs/Highlight'
import { SoundId } from 'libs/Sound'
import { createAction, RehydrateAction } from 'utils/redux'
/**
* Follows sort order.
*/
export enum FollowsSortOrder {
ViewersDesc,
ViewersAsc,
UptimeDesc,
UptimeAsc,
}
/**
* Actions types.
*/
export enum Actions {
TOGGLE_THEME = 'settings/TOGGLE_THEME',
SET_VERSION = 'settings/SET_VERSION',
TOGGLE_COPY_MESSAGE_DOUBLE_CLICK = 'settings/TOGGLE_COPY_MESSAGE_DOUBLE_CLICK',
TOGGLE_SHOW_CONTEXT_MENU = 'settings/TOGGLE_SHOW_CONTEXT_MENU',
ADD_HIGHLIGHT = 'settings/ADD_HIGHLIGHT',
UPDATE_HIGHLIGHT_PATTERN = 'settings/UPDATE_HIGHLIGHT_PATTERN',
UPDATE_HIGHLIGHT_COLOR = 'settings/UPDATE_HIGHLIGHT_COLOR',
REMOVE_HIGHLIGHT = 'settings/REMOVE_HIGHLIGHT',
ADD_HIGHLIGHTS_IGNORED_USERS = 'settings/ADD_HIGHLIGHTS_IGNORED_USERS',
REMOVE_HIGHLIGHTS_IGNORED_USER = 'settings/REMOVE_HIGHLIGHTS_IGNORED_USER',
ADD_HIGHLIGHTS_PERMANENT_USERS = 'settings/ADD_HIGHLIGHTS_PERMANENT_USERS',
REMOVE_HIGHLIGHTS_PERMANENT_USER = 'settings/REMOVE_HIGHLIGHTS_PERMANENT_USER',
ADD_ACTION = 'settings/ADD_ACTION',
REMOVE_ACTION = 'settings/REMOVE_ACTION',
UPDATE_ACTION = 'settings/UPDATE_ACTION',
MOVE_ACTION = 'settings/MOVE_ACTION',
TOGGLE_HIDE_WHISPERS = 'settings/TOGGLE_HIDE_WHISPERS',
RESTORE = 'settings/RESTORE',
TOGGLE_AUTO_FOCUS_INPUT = 'settings/TOGGLE_AUTO_FOCUS_INPUT',
TOGGLE_SHOW_VIEWER_COUNT = 'settings/TOGGLE_SHOW_VIEWER_COUNT',
TOGGLE_DISABLE_DIALOG_ANIMATIONS = 'settings/TOGGLE_DISABLE_DIALOG_ANIMATIONS',
TOGGLE_HIGHLIGHT_ALL_MENTIONS = 'settings/TOGGLE_HIGHLIGHT_ALL_MENTIONS',
TOGGLE_PRIORITIZE_USERNAMES = 'settings/TOGGLE_PRIORITIZE_USERNAMES',
UPDATE_HOST_THRESHOLD = 'settings/UPDATE_HOST_THRESHOLD',
UPDATE_AUTO_HOST_THRESHOLD = 'settings/UPDATE_AUTO_HOST_THRESHOLD',
SET_FOLLOWS_SORT_ORDER = 'settings/SET_FOLLOWS_SORT_ORDER',
TOGGLE_HIDE_OFFLINE_FOLLOWS = 'settings/TOGGLE_HIDE_OFFLINE_FOLLOWS',
SET_SHORTCUT = 'settings/SET_SHORTCUT',
TOGGLE_HIDE_VIP_BADGES = 'settings/TOGGLE_HIDE_VIP_BADGES',
TOGGLE_ADD_WHISPERS_TO_HISTORY = 'settings/TOGGLE_ADD_WHISPERS_TO_HISTORY',
TOGGLE_SOUND = 'TOGGLE_SOUND',
UPDATE_SOUND_VOLUME = 'UPDATE_SOUND_VOLUME',
TOGGLE_PLAY_MESSAGE_SOUND_ONLY_IN_OWN_CHANNEL = 'TOGGLE_PLAY_MESSAGE_SOUND_ONLY_IN_OWN_CHANNEL',
UPDATE_DELAY_BETWEEN_THROTTLED_SOUNDS = 'UPDATE_DELAY_BETWEEN_THROTTLED_SOUNDS',
TOGGLE_HIDE_HEADER = 'TOGGLE_HIDE_HEADER',
TOGGLE_ALTERNATE_MESSAGE_BACKGROUNDS = 'settings/TOGGLE_ALTERNATE_MESSAGE_BACKGROUNDS',
TOGGLE_MARK_NEW_AS_UNREAD = 'settings/TOGGLE_MARK_NEW_AS_UNREAD',
TOGGLE_INCREASE_TWITCH_HIGHLIGHT = 'settings/TOGGLE_INCREASE_TWITCH_HIGHLIGHT',
}
/**
* Initial state.
*/
export const initialState = {
actions: {
allIds: [],
byId: {},
},
addWhispersToHistory: false,
alternateMessageBackgrounds: false,
autoFocusInput: true,
autoHostThreshold: 1,
copyMessageOnDoubleClick: true,
delayBetweenThrottledSounds: 10,
disableDialogAnimations: false,
followsSortOrder: FollowsSortOrder.ViewersDesc,
hideHeader: false,
hideOfflineFollows: false,
hideVIPBadges: true,
hideWhispers: false,
highlightAllMentions: false,
highlights: {},
highlightsIgnoredUsers: [],
highlightsPermanentUsers: [],
hostThreshold: 1,
increaseTwitchHighlight: false,
lastKnownVersion: null,
markNewAsUnread: false,
playMessageSoundOnlyInOwnChannel: true,
prioritizeUsernames: false,
shortcuts: {
[ShortcutType.OpenSettings]: 'alt + ,',
[ShortcutType.NavigateHome]: 'alt + h',
[ShortcutType.NavigateOwnChannel]: 'alt + o',
[ShortcutType.CreateClip]: 'alt + x',
[ShortcutType.ToggleSearch]: 'alt + f',
[ShortcutType.ToggleOmnibar]: 'alt + p',
[ShortcutType.TogglePollEditor]: 'alt + c',
[ShortcutType.FocusChatInput]: 'alt + a',
[ShortcutType.AddMarker]: 'alt + m',
[ShortcutType.CreatePoll]: 'alt + enter',
[ShortcutType.HiDeHeader]: 'alt + t',
},
showContextMenu: true,
showViewerCount: false,
sounds: {
[SoundId.Mention]: {
enabled: false,
volume: 0.5,
},
[SoundId.Message]: {
enabled: false,
volume: 0.5,
},
[SoundId.Whisper]: {
enabled: false,
volume: 0.5,
},
},
theme: Theme.Dark as SettingsState['theme'],
}
/**
* Settings reducer.
* @param [state=initialState] - Current state.
* @param action - Current action.
* @return The new state.
*/
const settingsReducer: Reducer<SettingsState, SettingsActions> = (state = initialState, action) => {
switch (action.type) {
case REHYDRATE: {
if (!_.get(action.payload, 'settings')) {
return state
}
return action.payload.settings
}
case Actions.TOGGLE_THEME: {
return {
...state,
theme: state.theme === Theme.Dark ? Theme.Light : Theme.Dark,
}
}
case Actions.SET_VERSION: {
return {
...state,
lastKnownVersion: action.payload.version,
}
}
case Actions.TOGGLE_COPY_MESSAGE_DOUBLE_CLICK: {
return {
...state,
copyMessageOnDoubleClick: !state.copyMessageOnDoubleClick,
}
}
case Actions.TOGGLE_SHOW_CONTEXT_MENU: {
return {
...state,
showContextMenu: !state.showContextMenu,
}
}
case Actions.ADD_HIGHLIGHT: {
const { highlight } = action.payload
return {
...state,
highlights: { ...state.highlights, [highlight.id]: highlight },
}
}
case Actions.UPDATE_HIGHLIGHT_PATTERN: {
const { id, pattern } = action.payload
return {
...state,
highlights: { ...state.highlights, [id]: { ...state.highlights[id], pattern } },
}
}
case Actions.UPDATE_HIGHLIGHT_COLOR: {
const { id, color } = action.payload
return {
...state,
highlights: { ...state.highlights, [id]: { ...state.highlights[id], color } },
}
}
case Actions.REMOVE_HIGHLIGHT: {
const { id } = action.payload
const { [id]: highlightToRemove, ...otherHighlights } = state.highlights
return {
...state,
highlights: otherHighlights,
}
}
case Actions.ADD_HIGHLIGHTS_IGNORED_USERS: {
return {
...state,
highlightsIgnoredUsers: [...state.highlightsIgnoredUsers, ...action.payload.usernames],
}
}
case Actions.REMOVE_HIGHLIGHTS_IGNORED_USER: {
return {
...state,
highlightsIgnoredUsers: _.filter(
state.highlightsIgnoredUsers,
(username) => username !== action.payload.username
),
}
}
case Actions.ADD_HIGHLIGHTS_PERMANENT_USERS: {
return {
...state,
highlightsPermanentUsers: [...state.highlightsPermanentUsers, ...action.payload.usernames],
}
}
case Actions.REMOVE_HIGHLIGHTS_PERMANENT_USER: {
return {
...state,
highlightsPermanentUsers: _.filter(
state.highlightsPermanentUsers,
(username) => username !== action.payload.username
),
}
}
case Actions.ADD_ACTION: {
const { action: newAction } = action.payload
return {
...state,
actions: {
allIds: [...state.actions.allIds, newAction.id],
byId: { ...state.actions.byId, [newAction.id]: newAction },
},
}
}
case Actions.REMOVE_ACTION: {
const { id } = action.payload
const { [id]: actionToRemove, ...otherActions } = state.actions.byId
const index = _.indexOf(state.actions.allIds, id)
return {
...state,
actions: {
allIds: [...state.actions.allIds.slice(0, index), ...state.actions.allIds.slice(index + 1)],
byId: otherActions,
},
}
}
case Actions.MOVE_ACTION: {
const { down, id } = action.payload
const index = _.indexOf(state.actions.allIds, id)
const otherIndex = index + (down ? 1 : -1)
const newAllIds = [...state.actions.allIds]
const actionToSwap = newAllIds[index]
newAllIds[index] = newAllIds[otherIndex]
newAllIds[otherIndex] = actionToSwap
return {
...state,
actions: {
allIds: newAllIds,
byId: state.actions.byId,
},
}
}
case Actions.UPDATE_ACTION: {
const { id, action: updatedAction } = action.payload
return {
...state,
actions: {
...state.actions,
byId: { ...state.actions.byId, [id]: { ...state.actions.byId[id], ...updatedAction } },
},
}
}
case Actions.TOGGLE_HIDE_WHISPERS: {
return {
...state,
hideWhispers: !state.hideWhispers,
}
}
case Actions.RESTORE: {
return {
...state,
...action.payload.json,
}
}
case Actions.TOGGLE_AUTO_FOCUS_INPUT: {
return {
...state,
autoFocusInput: !state.autoFocusInput,
}
}
case Actions.TOGGLE_SHOW_VIEWER_COUNT: {
return {
...state,
showViewerCount: !state.showViewerCount,
}
}
case Actions.TOGGLE_DISABLE_DIALOG_ANIMATIONS: {
return {
...state,
disableDialogAnimations: !state.disableDialogAnimations,
}
}
case Actions.TOGGLE_ALTERNATE_MESSAGE_BACKGROUNDS: {
return {
...state,
alternateMessageBackgrounds: !state.alternateMessageBackgrounds,
}
}
case Actions.TOGGLE_HIGHLIGHT_ALL_MENTIONS: {
return {
...state,
highlightAllMentions: !state.highlightAllMentions,
}
}
case Actions.TOGGLE_PRIORITIZE_USERNAMES: {
return {
...state,
prioritizeUsernames: !state.prioritizeUsernames,
}
}
case Actions.UPDATE_HOST_THRESHOLD: {
return {
...state,
hostThreshold: action.payload.threshold,
}
}
case Actions.UPDATE_AUTO_HOST_THRESHOLD: {
return {
...state,
autoHostThreshold: action.payload.threshold,
}
}
case Actions.SET_FOLLOWS_SORT_ORDER: {
return {
...state,
followsSortOrder: action.payload.order,
}
}
case Actions.TOGGLE_HIDE_OFFLINE_FOLLOWS: {
return {
...state,
hideOfflineFollows: !state.hideOfflineFollows,
}
}
case Actions.SET_SHORTCUT: {
const { combo, type } = action.payload
return {
...state,
shortcuts: {
...state.shortcuts,
[type]: combo,
},
}
}
case Actions.TOGGLE_HIDE_VIP_BADGES: {
return {
...state,
hideVIPBadges: !state.hideVIPBadges,
}
}
case Actions.TOGGLE_ADD_WHISPERS_TO_HISTORY: {
return {
...state,
addWhispersToHistory: !state.addWhispersToHistory,
}
}
case Actions.TOGGLE_SOUND: {
const { soundId } = action.payload
return {
...state,
sounds: {
...state.sounds,
[soundId]: {
...state.sounds[soundId],
enabled: !state.sounds[soundId].enabled,
},
},
}
}
case Actions.UPDATE_SOUND_VOLUME: {
const { soundId, volume } = action.payload
return {
...state,
sounds: {
...state.sounds,
[soundId]: {
...state.sounds[soundId],
volume,
},
},
}
}
case Actions.TOGGLE_PLAY_MESSAGE_SOUND_ONLY_IN_OWN_CHANNEL: {
return {
...state,
playMessageSoundOnlyInOwnChannel: !state.playMessageSoundOnlyInOwnChannel,
}
}
case Actions.UPDATE_DELAY_BETWEEN_THROTTLED_SOUNDS: {
return {
...state,
delayBetweenThrottledSounds: action.payload.delay,
}
}
case Actions.TOGGLE_HIDE_HEADER: {
return {
...state,
hideHeader: !state.hideHeader,
}
}
case Actions.TOGGLE_MARK_NEW_AS_UNREAD: {
return {
...state,
markNewAsUnread: !state.markNewAsUnread,
}
}
case Actions.TOGGLE_INCREASE_TWITCH_HIGHLIGHT: {
return {
...state,
increaseTwitchHighlight: !state.increaseTwitchHighlight,
}
}
default: {
return state
}
}
}
export default settingsReducer
/**
* Toggle between the light & dark theme.
* @return The action.
*/
export const toggleTheme = () => createAction(Actions.TOGGLE_THEME)
/**
* Sets the last known version of the application.
* @param version - The new version.
* @return The action.
*/
export const setVersion = (version: string) =>
createAction(Actions.SET_VERSION, {
version,
})
/**
* Toggle the 'Copy message on double click' setting.
* @return The action.
*/
export const toggleCopyMessageOnDoubleClick = () => createAction(Actions.TOGGLE_COPY_MESSAGE_DOUBLE_CLICK)
/**
* Toggle the 'Show context menu' setting.
* @return The action.
*/
export const toggleShowContextMenu = () => createAction(Actions.TOGGLE_SHOW_CONTEXT_MENU)
/**
* Add an highlight.
* @param highlight - The new highlight.
* @return The action.
*/
export const addHighlight = (highlight: SerializedHighlight) =>
createAction(Actions.ADD_HIGHLIGHT, {
highlight,
})
/**
* Update an highlight pattern.
* @param id - The highlight id.
* @param pattern - The new pattern.
* @return The action.
*/
export const updateHighlightPattern = (id: string, pattern: string) =>
createAction(Actions.UPDATE_HIGHLIGHT_PATTERN, {
id,
pattern,
})
/**
* Update an highlight color.
* @param id - The highlight id.
* @param color - The new color.
* @return The action.
*/
export const updateHighlightColor = (id: string, color: HighlightColors) =>
createAction(Actions.UPDATE_HIGHLIGHT_COLOR, {
color,
id,
})
/**
* Removes an highlight.
* @param id - The highlight id.
* @return The action.
*/
export const removeHighlight = (id: string) =>
createAction(Actions.REMOVE_HIGHLIGHT, {
id,
})
/**
* Ignores one or multiple users for highlights and mentions.
* @param usernames - The usernames to ignore.
* @return The action.
*/
export const addHighlightsIgnoredUsers = (usernames: string[]) =>
createAction(Actions.ADD_HIGHLIGHTS_IGNORED_USERS, {
usernames,
})
/**
* Removes an ignored user for highlights and mentions.
* @param username - The username to remove.
* @return The action.
*/
export const removeHighlightsIgnoredUser = (username: string) =>
createAction(Actions.REMOVE_HIGHLIGHTS_IGNORED_USER, {
username,
})
/**
* Adds one or multiple users to always be highlighted.
* @param usernames - The usernames to always highlight.
* @return The action.
*/
export const addHighlightsPermanentUsers = (usernames: string[]) =>
createAction(Actions.ADD_HIGHLIGHTS_PERMANENT_USERS, {
usernames,
})
/**
* Removes an always highlighted user.
* @param username - The username to remove.
* @return The action.
*/
export const removeHighlightsPermanentUser = (username: string) =>
createAction(Actions.REMOVE_HIGHLIGHTS_PERMANENT_USER, {
username,
})
/**
* Add an Action.
* @param action - The new action.
* @return The action.
*/
export const addAction = (action: SerializedAction) =>
createAction(Actions.ADD_ACTION, {
action,
})
/**
* Removes an action.
* @param id - The action id.
* @return The action.
*/
export const removeAction = (id: string) =>
createAction(Actions.REMOVE_ACTION, {
id,
})
/**
* Update an action.
* @param id - The action id.
* @param pattern - The updated action.
* @return The action.
*/
export const updateAction = (id: string, action: SerializedAction) =>
createAction(Actions.UPDATE_ACTION, {
action,
id,
})
/**
* Moves an action up or down.
* @param id - The action id.
* @param down - `true` when moving down.
* @return The action.
*/
export const moveAction = (id: string, down: boolean) =>
createAction(Actions.MOVE_ACTION, {
down,
id,
})
/**
* Toggle the 'Hide whispers' setting.
* @return The action.
*/
export const toggleHideWhispers = () => createAction(Actions.TOGGLE_HIDE_WHISPERS)
/**
* Restores settings from a backup.
* @param json - The JSON backup.
* @return The action.
*/
export const restoreSettings = (json: SettingsState) =>
createAction(Actions.RESTORE, {
json,
})
/**
* Toggle the 'Automatically focus the input field' setting.
* @return The action.
*/
export const toggleAutoFocusInput = () => createAction(Actions.TOGGLE_AUTO_FOCUS_INPUT)
/**
* Toggle the 'Show viewer count' setting.
* @return The action.
*/
export const toggleShowViewerCount = () => createAction(Actions.TOGGLE_SHOW_VIEWER_COUNT)
/**
* Toggle the 'Disable dialog animations' setting.
* @return The action.
*/
export const toggleDisableDialogAnimations = () => createAction(Actions.TOGGLE_DISABLE_DIALOG_ANIMATIONS)
/**
* Toggle the 'Alternate message background colors' setting.
* @return The action.
*/
export const toggleAlternateMessageBackgrounds = () => createAction(Actions.TOGGLE_ALTERNATE_MESSAGE_BACKGROUNDS)
/**
* Toggle the 'Highlight all mentions' setting.
* @return The action.
*/
export const toggleHighlightAllMentions = () => createAction(Actions.TOGGLE_HIGHLIGHT_ALL_MENTIONS)
/**
* Toggle the 'Prioritize usernames' setting.
* @return The action.
*/
export const togglePrioritizeUsernames = () => createAction(Actions.TOGGLE_PRIORITIZE_USERNAMES)
/**
* Updates the host threshold.
* @param threshold - The new threshold.
* @return The action.
*/
export const updateHostThreshold = (threshold: number) =>
createAction(Actions.UPDATE_HOST_THRESHOLD, {
threshold,
})
/**
* Updates the auto-host threshold.
* @param threshold - The new threshold.
* @return The action.
*/
export const updateAutoHostThreshold = (threshold: number) =>
createAction(Actions.UPDATE_AUTO_HOST_THRESHOLD, {
threshold,
})
/**
* Sets the follows sort order.
* @param order - The new sort order.
* @return The action.
*/
export const setFollowsSortOrder = (order: FollowsSortOrder) =>
createAction(Actions.SET_FOLLOWS_SORT_ORDER, {
order,
})
/**
* Toggle the 'Hide offline follows' setting.
* @return The action.
*/
export const toggleHideOfflineFollows = () => createAction(Actions.TOGGLE_HIDE_OFFLINE_FOLLOWS)
/**
* Sets the combo of a specific shortcut type.
* @param type - The shortcut type.
* @param combo - The new combo.
* @return The action.
*/
export const setShortcut = (type: ShortcutType, combo: ShortcutCombo) =>
createAction(Actions.SET_SHORTCUT, {
combo,
type,
})
/**
* Toggles the 'Hide VIP badges' setting.
* @return The action.
*/
export const toggleHideVIPBadges = () => createAction(Actions.TOGGLE_HIDE_VIP_BADGES)
/**
* Toggles the 'Add whispers to history' setting.
* @return The action.
*/
export const toggleAddWhispersToHistory = () => createAction(Actions.TOGGLE_ADD_WHISPERS_TO_HISTORY)
/**
* Toggles a sound enabled or not.
* @param soundId - The id of the sound to toggle.
* @return The action.
*/
export const toggleSound = (soundId: SoundId) =>
createAction(Actions.TOGGLE_SOUND, {
soundId,
})
/**
* Updates a sound volume.
* @param soundId - The id of the sound to update.
* @param volume - The new volume.
* @return The action.
*/
export const updateSoundVolume = (soundId: SoundId, volume: number) =>
createAction(Actions.UPDATE_SOUND_VOLUME, {
soundId,
volume,
})
/**
* Toggles the 'Play sound on messages only in my channel' setting.
* @return The action.
*/
export const togglePlayMessageSoundOnlyInOwnChannel = () =>
createAction(Actions.TOGGLE_PLAY_MESSAGE_SOUND_ONLY_IN_OWN_CHANNEL)
/**
* Updates the delay in seconds between throttled sounds.
* @param delay - The new delay.
* @return The action.
*/
export const updateDelayBetweenThrottledSounds = (delay: number) =>
createAction(Actions.UPDATE_DELAY_BETWEEN_THROTTLED_SOUNDS, {
delay,
})
/**
* Toggles the 'Hides header' setting.
* @return The action.
*/
export const toggleHideHeader = () => createAction(Actions.TOGGLE_HIDE_HEADER)
/**
* Toggles the 'Mark new messages as unread' setting.
* @return The action.
*/
export const toggleMarkNewAsUnread = () => createAction(Actions.TOGGLE_MARK_NEW_AS_UNREAD)
/**
* Toggle the 'Increase highlight for messages redeemed using Channel Points' setting.
* @return The action.
*/
export const toggleIncreaseTwitchHighlight = () => createAction(Actions.TOGGLE_INCREASE_TWITCH_HIGHLIGHT)
/**
* Settings actions.
*/
export type SettingsActions =
| RehydrateAction
| ReturnType<typeof toggleTheme>
| ReturnType<typeof setVersion>
| ReturnType<typeof toggleCopyMessageOnDoubleClick>
| ReturnType<typeof toggleShowContextMenu>
| ReturnType<typeof addHighlight>
| ReturnType<typeof updateHighlightPattern>
| ReturnType<typeof updateHighlightColor>
| ReturnType<typeof removeHighlight>
| ReturnType<typeof addHighlightsIgnoredUsers>
| ReturnType<typeof removeHighlightsIgnoredUser>
| ReturnType<typeof addHighlightsPermanentUsers>
| ReturnType<typeof removeHighlightsPermanentUser>
| ReturnType<typeof addAction>
| ReturnType<typeof removeAction>
| ReturnType<typeof updateAction>
| ReturnType<typeof toggleHideWhispers>
| ReturnType<typeof restoreSettings>
| ReturnType<typeof toggleAutoFocusInput>
| ReturnType<typeof toggleShowViewerCount>
| ReturnType<typeof toggleDisableDialogAnimations>
| ReturnType<typeof toggleAlternateMessageBackgrounds>
| ReturnType<typeof toggleHighlightAllMentions>
| ReturnType<typeof togglePrioritizeUsernames>
| ReturnType<typeof moveAction>
| ReturnType<typeof updateHostThreshold>
| ReturnType<typeof updateAutoHostThreshold>
| ReturnType<typeof setFollowsSortOrder>
| ReturnType<typeof toggleHideOfflineFollows>
| ReturnType<typeof setShortcut>
| ReturnType<typeof toggleHideVIPBadges>
| ReturnType<typeof toggleAddWhispersToHistory>
| ReturnType<typeof toggleSound>
| ReturnType<typeof updateSoundVolume>
| ReturnType<typeof togglePlayMessageSoundOnlyInOwnChannel>
| ReturnType<typeof updateDelayBetweenThrottledSounds>
| ReturnType<typeof toggleHideHeader>
| ReturnType<typeof toggleMarkNewAsUnread>
| ReturnType<typeof toggleIncreaseTwitchHighlight>
/**
* Settings state.
*/
export type SettingsState = {
/**
* Selected theme.
*/
theme: Theme
/**
* Last know version of the application.
*/
lastKnownVersion: string | null
/**
* Defines if messages should be copied in the clipboard when double clicking them.
*/
copyMessageOnDoubleClick: boolean
/**
* Defines if a context menu should be added to each message.
*/
showContextMenu: boolean
/**
* Highlights.
*/
highlights: SerializedHighlights
/**
* Users ignored for highlights & mentions.
*/
highlightsIgnoredUsers: string[]
/**
* Users with messages always highlighted.
*/
highlightsPermanentUsers: string[]
/**
* Actions.
*/
actions: {
/**
* All actions keyed by ids.
*/
byId: SerializedActions
/**
* All actions ordered by ids.
*/
allIds: string[]
}
/**
* Hides VIPs badges except in your own channel.
*/
hideVIPBadges: boolean
/**
* Hides whispers (received & sent).
*/
hideWhispers: boolean
/**
* Automatically focus the input field when focusing the application.
*/
autoFocusInput: boolean
/**
* Shows the viewer count in the header.
*/
showViewerCount: boolean
/**
* Disables dialog animations.
*/
disableDialogAnimations: boolean
/**
* Highlights all mentions (@notYou) instead of only you.
*/
highlightAllMentions: boolean
/**
* Prioritizes usernames when auto-completing.
*/
prioritizeUsernames: boolean
/**
* Hosts below this threshold will be ignored.
*/
hostThreshold: number
/**
* Auto-hosts below this threshold will be ignored.
*/
autoHostThreshold: number
/**
* Follows sort order.
*/
followsSortOrder: FollowsSortOrder
/**
* Hide offline follows.
*/
hideOfflineFollows: boolean
/**
* Shortcuts.
*/
shortcuts: Record<ShortcutType, ShortcutCombo>
/**
* Adds whispers to the history when enabled.
*/
addWhispersToHistory: boolean
/**
* Sounds.
*/
sounds: Record<SoundId, SoundSettings>
/**
* When enabled, only plays message sounds in your own channel.
*/
playMessageSoundOnlyInOwnChannel: boolean
/**
* Minimum delay (in seconds) between two throttled sounds like message sounds.
*/
delayBetweenThrottledSounds: number
/**
* Hides the header.
*/
hideHeader: boolean
/**
* Alternate message background colors.
*/
alternateMessageBackgrounds: boolean
/**
* Mark new messages as unread.
*/
markNewAsUnread: boolean
/**
* Defines if the Twitch highlight should be increased.
*/
increaseTwitchHighlight: boolean
}
/**
* Highlights.
*/
export type SerializedHighlights = Record<SerializedHighlight['id'], SerializedHighlight>
/**
* Actions.
*/
export type SerializedActions = Record<SerializedAction['id'], SerializedAction>
/**
* Sound settings.
*/
export type SoundSettings = {
enabled: boolean
volume: number
} | the_stack |
import { MOST_NEGATIVE_SINGLE_FLOAT, MOST_POSITIVE_SINGLE_FLOAT } from '../constants';
import { IAudioParam } from '../interfaces';
import { TAudioListenerFactoryFactory } from '../types';
export const createAudioListenerFactory: TAudioListenerFactoryFactory = (
createAudioParam,
createNativeChannelMergerNode,
createNativeConstantSourceNode,
createNativeScriptProcessorNode,
createNotSupportedError,
getFirstSample,
isNativeOfflineAudioContext,
overwriteAccessors
) => {
return (context, nativeContext) => {
const nativeListener = nativeContext.listener;
// Bug #117: Only Chrome, Edge & Opera support the new interface already.
const createFakeAudioParams = () => {
const buffer = new Float32Array(1);
const channelMergerNode = createNativeChannelMergerNode(nativeContext, {
channelCount: 1,
channelCountMode: 'explicit',
channelInterpretation: 'speakers',
numberOfInputs: 9
});
const isOffline = isNativeOfflineAudioContext(nativeContext);
let isScriptProcessorNodeCreated = false;
let lastOrientation: [number, number, number, number, number, number] = [0, 0, -1, 0, 1, 0];
let lastPosition: [number, number, number] = [0, 0, 0];
const createScriptProcessorNode = () => {
if (isScriptProcessorNodeCreated) {
return;
}
isScriptProcessorNodeCreated = true;
const scriptProcessorNode = createNativeScriptProcessorNode(nativeContext, 256, 9, 0);
// tslint:disable-next-line:deprecation
scriptProcessorNode.onaudioprocess = ({ inputBuffer }) => {
const orientation: [number, number, number, number, number, number] = [
getFirstSample(inputBuffer, buffer, 0),
getFirstSample(inputBuffer, buffer, 1),
getFirstSample(inputBuffer, buffer, 2),
getFirstSample(inputBuffer, buffer, 3),
getFirstSample(inputBuffer, buffer, 4),
getFirstSample(inputBuffer, buffer, 5)
];
if (orientation.some((value, index) => value !== lastOrientation[index])) {
nativeListener.setOrientation(...orientation); // tslint:disable-line:deprecation
lastOrientation = orientation;
}
const positon: [number, number, number] = [
getFirstSample(inputBuffer, buffer, 6),
getFirstSample(inputBuffer, buffer, 7),
getFirstSample(inputBuffer, buffer, 8)
];
if (positon.some((value, index) => value !== lastPosition[index])) {
nativeListener.setPosition(...positon); // tslint:disable-line:deprecation
lastPosition = positon;
}
};
channelMergerNode.connect(scriptProcessorNode);
};
const createSetOrientation = (index: number) => (value: number) => {
if (value !== lastOrientation[index]) {
lastOrientation[index] = value;
nativeListener.setOrientation(...lastOrientation); // tslint:disable-line:deprecation
}
};
const createSetPosition = (index: number) => (value: number) => {
if (value !== lastPosition[index]) {
lastPosition[index] = value;
nativeListener.setPosition(...lastPosition); // tslint:disable-line:deprecation
}
};
const createFakeAudioParam = (input: number, initialValue: number, setValue: (value: number) => void) => {
const constantSourceNode = createNativeConstantSourceNode(nativeContext, {
channelCount: 1,
channelCountMode: 'explicit',
channelInterpretation: 'discrete',
offset: initialValue
});
constantSourceNode.connect(channelMergerNode, 0, input);
// @todo This should be stopped when the context is closed.
constantSourceNode.start();
Object.defineProperty(constantSourceNode.offset, 'defaultValue', {
get(): number {
return initialValue;
}
});
/*
* Bug #62 & #74: Safari does not support ConstantSourceNodes and does not export the correct values for maxValue and
* minValue for GainNodes.
*/
const audioParam = createAudioParam(
<any>{ context },
isOffline,
constantSourceNode.offset,
MOST_POSITIVE_SINGLE_FLOAT,
MOST_NEGATIVE_SINGLE_FLOAT
);
overwriteAccessors(
audioParam,
'value',
(get) => () => get.call(audioParam),
(set) => (value) => {
try {
set.call(audioParam, value);
} catch (err) {
if (err.code !== 9) {
throw err;
}
}
createScriptProcessorNode();
if (isOffline) {
// Bug #117: Using setOrientation() and setPosition() doesn't work with an OfflineAudioContext.
setValue(value);
}
}
);
audioParam.cancelAndHoldAtTime = ((cancelAndHoldAtTime) => {
if (isOffline) {
return () => {
throw createNotSupportedError();
};
}
return (...args: Parameters<IAudioParam['cancelAndHoldAtTime']>) => {
const value = cancelAndHoldAtTime.apply(audioParam, args);
createScriptProcessorNode();
return value;
};
})(audioParam.cancelAndHoldAtTime);
audioParam.cancelScheduledValues = ((cancelScheduledValues) => {
if (isOffline) {
return () => {
throw createNotSupportedError();
};
}
return (...args: Parameters<IAudioParam['cancelScheduledValues']>) => {
const value = cancelScheduledValues.apply(audioParam, args);
createScriptProcessorNode();
return value;
};
})(audioParam.cancelScheduledValues);
audioParam.exponentialRampToValueAtTime = ((exponentialRampToValueAtTime) => {
if (isOffline) {
return () => {
throw createNotSupportedError();
};
}
return (...args: Parameters<IAudioParam['exponentialRampToValueAtTime']>) => {
const value = exponentialRampToValueAtTime.apply(audioParam, args);
createScriptProcessorNode();
return value;
};
})(audioParam.exponentialRampToValueAtTime);
audioParam.linearRampToValueAtTime = ((linearRampToValueAtTime) => {
if (isOffline) {
return () => {
throw createNotSupportedError();
};
}
return (...args: Parameters<IAudioParam['linearRampToValueAtTime']>) => {
const value = linearRampToValueAtTime.apply(audioParam, args);
createScriptProcessorNode();
return value;
};
})(audioParam.linearRampToValueAtTime);
audioParam.setTargetAtTime = ((setTargetAtTime) => {
if (isOffline) {
return () => {
throw createNotSupportedError();
};
}
return (...args: Parameters<IAudioParam['setTargetAtTime']>) => {
const value = setTargetAtTime.apply(audioParam, args);
createScriptProcessorNode();
return value;
};
})(audioParam.setTargetAtTime);
audioParam.setValueAtTime = ((setValueAtTime) => {
if (isOffline) {
return () => {
throw createNotSupportedError();
};
}
return (...args: Parameters<IAudioParam['setValueAtTime']>) => {
const value = setValueAtTime.apply(audioParam, args);
createScriptProcessorNode();
return value;
};
})(audioParam.setValueAtTime);
audioParam.setValueCurveAtTime = ((setValueCurveAtTime) => {
if (isOffline) {
return () => {
throw createNotSupportedError();
};
}
return (...args: Parameters<IAudioParam['setValueCurveAtTime']>) => {
const value = setValueCurveAtTime.apply(audioParam, args);
createScriptProcessorNode();
return value;
};
})(audioParam.setValueCurveAtTime);
return audioParam;
};
return {
forwardX: createFakeAudioParam(0, 0, createSetOrientation(0)),
forwardY: createFakeAudioParam(1, 0, createSetOrientation(1)),
forwardZ: createFakeAudioParam(2, -1, createSetOrientation(2)),
positionX: createFakeAudioParam(6, 0, createSetPosition(0)),
positionY: createFakeAudioParam(7, 0, createSetPosition(1)),
positionZ: createFakeAudioParam(8, 0, createSetPosition(2)),
upX: createFakeAudioParam(3, 0, createSetOrientation(3)),
upY: createFakeAudioParam(4, 1, createSetOrientation(4)),
upZ: createFakeAudioParam(5, 0, createSetOrientation(5))
};
};
const { forwardX, forwardY, forwardZ, positionX, positionY, positionZ, upX, upY, upZ } =
nativeListener.forwardX === undefined ? createFakeAudioParams() : nativeListener;
return {
get forwardX(): IAudioParam {
return forwardX;
},
get forwardY(): IAudioParam {
return forwardY;
},
get forwardZ(): IAudioParam {
return forwardZ;
},
get positionX(): IAudioParam {
return positionX;
},
get positionY(): IAudioParam {
return positionY;
},
get positionZ(): IAudioParam {
return positionZ;
},
get upX(): IAudioParam {
return upX;
},
get upY(): IAudioParam {
return upY;
},
get upZ(): IAudioParam {
return upZ;
}
};
};
}; | the_stack |
declare namespace JQuery {
type TypeOrArray<T> = T | T[];
type Node = Element | Text | Comment | Document | DocumentFragment;
/**
* A string is designated htmlString in jQuery documentation when it is used to represent one or more DOM elements, typically to be created and inserted in the document. When passed as an argument of the jQuery() function, the string is identified as HTML if it starts with <tag ... >) and is parsed as such until the final > character. Prior to jQuery 1.9, a string was considered to be HTML if it contained <tag ... > anywhere within the string.
*/
type htmlString = string;
/**
* A selector is used in jQuery to select DOM elements from a DOM document. That document is, in most cases, the DOM document present in all browsers, but can also be an XML document received via Ajax.
*/
type Selector = string;
/**
* The PlainObject type is a JavaScript object containing zero or more key-value pairs. The plain object is, in other words, an Object object. It is designated "plain" in jQuery documentation to distinguish it from other kinds of JavaScript objects: for example, null, user-defined arrays, and host objects such as document, all of which have a typeof value of "object."
*
* **Note**: The type declaration of PlainObject is imprecise. It includes host objects and user-defined arrays which do not match jQuery's definition.
*/
interface PlainObject<T = any> {
[key: string]: T;
}
interface Selectors extends Sizzle.Selectors {
/**
* @deprecated Deprecated since 3.0. Use \`{@link Selectors#pseudos }\`.
*
* **Cause**: The standard way to add new custom selectors through jQuery is `jQuery.expr.pseudos`. These two other aliases are deprecated, although they still work as of jQuery 3.0.
*
* **Solution**: Rename any of the older usage to `jQuery.expr.pseudos`. The functionality is identical.
*/
':': Sizzle.Selectors.PseudoFunctions;
/**
* @deprecated Deprecated since 3.0. Use \`{@link Selectors#pseudos }\`.
*
* **Cause**: The standard way to add new custom selectors through jQuery is `jQuery.expr.pseudos`. These two other aliases are deprecated, although they still work as of jQuery 3.0.
*
* **Solution**: Rename any of the older usage to `jQuery.expr.pseudos`. The functionality is identical.
*/
filter: Sizzle.Selectors.FilterFunctions;
}
// region Ajax
// #region Ajax
interface AjaxSettings<TContext = any> extends Ajax.AjaxSettingsBase<TContext> {
/**
* A string containing the URL to which the request is sent.
*/
url?: string | undefined;
}
interface UrlAjaxSettings<TContext = any> extends Ajax.AjaxSettingsBase<TContext> {
/**
* A string containing the URL to which the request is sent.
*/
url: string;
}
namespace Ajax {
type SuccessTextStatus = 'success' | 'notmodified' | 'nocontent';
type ErrorTextStatus = 'timeout' | 'error' | 'abort' | 'parsererror';
type TextStatus = SuccessTextStatus | ErrorTextStatus;
type SuccessCallback<TContext> = (this: TContext, data: any, textStatus: SuccessTextStatus, jqXHR: jqXHR) => void;
type ErrorCallback<TContext> = (this: TContext, jqXHR: jqXHR, textStatus: ErrorTextStatus, errorThrown: string) => void;
type CompleteCallback<TContext> = (this: TContext, jqXHR: jqXHR, textStatus: TextStatus) => void;
/**
* @see \`{@link https://api.jquery.com/jquery.ajax/#jQuery-ajax-settings }\`
*/
interface AjaxSettingsBase<TContext> {
/**
* A set of key/value pairs that map a given dataType to its MIME type, which gets sent in the Accept request header. This header tells the server what kind of response it will accept in return.
*/
accepts?: PlainObject<string> | undefined;
/**
* By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done().
*/
async?: boolean | undefined;
/**
* A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless of the type of request.
*/
beforeSend?(this: TContext, jqXHR: jqXHR, settings: this): false | void;
/**
* If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET.
*/
cache?: boolean | undefined;
/**
* A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "nocontent", "error", "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.
*/
complete?: TypeOrArray<CompleteCallback<TContext>> | undefined;
/**
* An object of string/regular-expression pairs that determine how jQuery will parse the response, given its content type.
*/
contents?: PlainObject<RegExp> | undefined;
/**
* When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). As of jQuery 1.6 you can pass false to tell jQuery to not set any content type header. Note: The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. Note: For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server.
*/
contentType?: string | false | undefined;
/**
* This object will be the context of all Ajax-related callbacks. By default, the context is an object that represents the Ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax).
*/
context?: TContext | undefined;
/**
* An object containing dataType-to-dataType converters. Each converter's value is a function that returns the transformed value of the response.
*/
converters?: PlainObject<((value: any) => any) | true> | undefined;
/**
* If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain.
*/
crossDomain?: boolean | undefined;
/**
* Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
*/
data?: PlainObject | string | undefined;
/**
* A function to be used to handle the raw response data of XMLHttpRequest. This is a pre-filtering function to sanitize the response. You should return the sanitized data. The function accepts two arguments: The raw data returned from the server and the 'dataType' parameter.
*/
dataFilter?(data: string, type: string): any;
/**
* The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:
*
* "xml": Returns a XML document that can be processed via jQuery.
*
* "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
*
* "script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, _=[TIMESTAMP], to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.
*
* "json": Evaluates the response as JSON and returns a JavaScript object. Cross-domain "json" requests are converted to "jsonp" unless the request includes jsonp: false in its request options. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)
*
* "jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true.
*
* "text": A plain text string.
*
* multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml". Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.
*/
dataType?: 'xml' | 'html' | 'script' | 'json' | 'jsonp' | 'text' | string | undefined;
/**
* The MIME type of content that is used to submit the form to the server. Possible values are:
*
* "application/x-www-form-urlencoded": The initial default type.
*
* "multipart/form-data": The type that allows file <input> element(s) to upload file data.
*
* "text/plain": A type introduced in HTML5.
*/
enctype?: 'application/x-www-form-urlencoded' | 'multipart/form-data' | 'text/plain' | undefined;
/**
* A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event.
*/
error?: TypeOrArray<ErrorCallback<TContext>> | undefined;
/**
* Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to control various Ajax Events.
*/
global?: boolean | undefined;
/**
* An object of additional header key/value pairs to send along with requests using the XMLHttpRequest transport. The header X-Requested-With: XMLHttpRequest is always added, but its default XMLHttpRequest value can be changed here. Values in the headers setting can also be overwritten from within the beforeSend function.
*/
headers?: PlainObject<string | null | undefined> | undefined;
/**
* Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery 1.4 this technique also checks the 'etag' specified by the server to catch unmodified data.
*/
ifModified?: boolean | undefined;
/**
* Allow the current environment to be recognized as "local," (e.g. the filesystem), even if jQuery does not recognize it as such by default. The following protocols are currently recognized as local: file, *-extension, and widget. If the isLocal setting needs modification, it is recommended to do so once in the $.ajaxSetup() method.
*/
isLocal?: boolean | undefined;
/**
* Override the callback function name in a JSONP request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So {jsonp:'onJSONPLoad'} would result in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the jsonp option to false prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, { jsonp: false, jsonpCallback: "callbackName" }. If you don't trust the target of your Ajax requests, consider setting the jsonp property to false for security reasons.
*/
jsonp?: string | false | undefined;
/**
* Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests. As of jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback is set to the return value of that function.
*/
jsonpCallback?: string | ((this: TContext) => string) | undefined;
/**
* The HTTP method to use for the request (e.g. "POST", "GET", "PUT").
*/
method?: string | undefined;
/**
* A mime type to override the XHR mime type.
*/
mimeType?: string | undefined;
/**
* A password to be used with XMLHttpRequest in response to an HTTP access authentication request.
*/
password?: string | undefined;
/**
* By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
*/
processData?: boolean | undefined;
/**
* Only applies when the "script" transport is used (e.g., cross-domain requests with "jsonp" or "script" dataType and "GET" type). Sets the charset attribute on the script tag used in the request. Used when the character set on the local page is not the same as the one on the remote script.
*/
scriptCharset?: string | undefined;
/**
* An object of numeric HTTP codes and functions to be called when the response has the corresponding code.
*
* If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error (including 3xx redirect), they take the same parameters as the error callback.
*/
statusCode?: StatusCodeCallbacks<TContext> | undefined;
/**
* A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.
*/
success?: TypeOrArray<SuccessCallback<TContext>> | undefined;
/**
* Set a timeout (in milliseconds) for the request. A value of 0 means there will be no timeout. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period.
*/
timeout?: number | undefined;
/**
* Set this to true if you wish to use the traditional style of param serialization.
*/
traditional?: boolean | undefined;
/**
* An alias for method. You should use type if you're using versions of jQuery prior to 1.9.0.
*/
type?: string | undefined;
/**
* A username to be used with XMLHttpRequest in response to an HTTP access authentication request.
*/
username?: string | undefined;
// ActiveXObject requires "lib": ["scripthost"] which consumers would also require
/**
* Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or enhancements to the factory.
*/
xhr?(): XMLHttpRequest;
/**
* An object of fieldName-fieldValue pairs to set on the native XHR object.
*
* In jQuery 1.5, the withCredentials property was not propagated to the native XHR and thus CORS requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ should you require the use of it.
*/
xhrFields?: XHRFields | undefined;
}
// region StatusCodeCallbacks
// #region StatusCodeCallbacks
type StatusCodeCallbacks<TContext> = {
// region Success Status Codes
// #region Success Status Codes
// jQuery treats 2xx and 304 status codes as a success
200?: SuccessCallback<TContext> | undefined;
201?: SuccessCallback<TContext> | undefined;
202?: SuccessCallback<TContext> | undefined;
203?: SuccessCallback<TContext> | undefined;
204?: SuccessCallback<TContext> | undefined;
205?: SuccessCallback<TContext> | undefined;
206?: SuccessCallback<TContext> | undefined;
207?: SuccessCallback<TContext> | undefined;
208?: SuccessCallback<TContext> | undefined;
209?: SuccessCallback<TContext> | undefined;
210?: SuccessCallback<TContext> | undefined;
211?: SuccessCallback<TContext> | undefined;
212?: SuccessCallback<TContext> | undefined;
213?: SuccessCallback<TContext> | undefined;
214?: SuccessCallback<TContext> | undefined;
215?: SuccessCallback<TContext> | undefined;
216?: SuccessCallback<TContext> | undefined;
217?: SuccessCallback<TContext> | undefined;
218?: SuccessCallback<TContext> | undefined;
219?: SuccessCallback<TContext> | undefined;
220?: SuccessCallback<TContext> | undefined;
221?: SuccessCallback<TContext> | undefined;
222?: SuccessCallback<TContext> | undefined;
223?: SuccessCallback<TContext> | undefined;
224?: SuccessCallback<TContext> | undefined;
225?: SuccessCallback<TContext> | undefined;
226?: SuccessCallback<TContext> | undefined;
227?: SuccessCallback<TContext> | undefined;
228?: SuccessCallback<TContext> | undefined;
229?: SuccessCallback<TContext> | undefined;
230?: SuccessCallback<TContext> | undefined;
231?: SuccessCallback<TContext> | undefined;
232?: SuccessCallback<TContext> | undefined;
233?: SuccessCallback<TContext> | undefined;
234?: SuccessCallback<TContext> | undefined;
235?: SuccessCallback<TContext> | undefined;
236?: SuccessCallback<TContext> | undefined;
237?: SuccessCallback<TContext> | undefined;
238?: SuccessCallback<TContext> | undefined;
239?: SuccessCallback<TContext> | undefined;
240?: SuccessCallback<TContext> | undefined;
241?: SuccessCallback<TContext> | undefined;
242?: SuccessCallback<TContext> | undefined;
243?: SuccessCallback<TContext> | undefined;
244?: SuccessCallback<TContext> | undefined;
245?: SuccessCallback<TContext> | undefined;
246?: SuccessCallback<TContext> | undefined;
247?: SuccessCallback<TContext> | undefined;
248?: SuccessCallback<TContext> | undefined;
249?: SuccessCallback<TContext> | undefined;
250?: SuccessCallback<TContext> | undefined;
251?: SuccessCallback<TContext> | undefined;
252?: SuccessCallback<TContext> | undefined;
253?: SuccessCallback<TContext> | undefined;
254?: SuccessCallback<TContext> | undefined;
255?: SuccessCallback<TContext> | undefined;
256?: SuccessCallback<TContext> | undefined;
257?: SuccessCallback<TContext> | undefined;
258?: SuccessCallback<TContext> | undefined;
259?: SuccessCallback<TContext> | undefined;
260?: SuccessCallback<TContext> | undefined;
261?: SuccessCallback<TContext> | undefined;
262?: SuccessCallback<TContext> | undefined;
263?: SuccessCallback<TContext> | undefined;
264?: SuccessCallback<TContext> | undefined;
265?: SuccessCallback<TContext> | undefined;
266?: SuccessCallback<TContext> | undefined;
267?: SuccessCallback<TContext> | undefined;
268?: SuccessCallback<TContext> | undefined;
269?: SuccessCallback<TContext> | undefined;
270?: SuccessCallback<TContext> | undefined;
271?: SuccessCallback<TContext> | undefined;
272?: SuccessCallback<TContext> | undefined;
273?: SuccessCallback<TContext> | undefined;
274?: SuccessCallback<TContext> | undefined;
275?: SuccessCallback<TContext> | undefined;
276?: SuccessCallback<TContext> | undefined;
277?: SuccessCallback<TContext> | undefined;
278?: SuccessCallback<TContext> | undefined;
279?: SuccessCallback<TContext> | undefined;
280?: SuccessCallback<TContext> | undefined;
281?: SuccessCallback<TContext> | undefined;
282?: SuccessCallback<TContext> | undefined;
283?: SuccessCallback<TContext> | undefined;
284?: SuccessCallback<TContext> | undefined;
285?: SuccessCallback<TContext> | undefined;
286?: SuccessCallback<TContext> | undefined;
287?: SuccessCallback<TContext> | undefined;
288?: SuccessCallback<TContext> | undefined;
289?: SuccessCallback<TContext> | undefined;
290?: SuccessCallback<TContext> | undefined;
291?: SuccessCallback<TContext> | undefined;
292?: SuccessCallback<TContext> | undefined;
293?: SuccessCallback<TContext> | undefined;
294?: SuccessCallback<TContext> | undefined;
295?: SuccessCallback<TContext> | undefined;
296?: SuccessCallback<TContext> | undefined;
297?: SuccessCallback<TContext> | undefined;
298?: SuccessCallback<TContext> | undefined;
299?: SuccessCallback<TContext> | undefined;
304?: SuccessCallback<TContext> | undefined;
// #endregion
// region Error Status Codes
// #region Error Status Codes
300?: ErrorCallback<TContext> | undefined;
301?: ErrorCallback<TContext> | undefined;
302?: ErrorCallback<TContext> | undefined;
303?: ErrorCallback<TContext> | undefined;
305?: ErrorCallback<TContext> | undefined;
306?: ErrorCallback<TContext> | undefined;
307?: ErrorCallback<TContext> | undefined;
308?: ErrorCallback<TContext> | undefined;
309?: ErrorCallback<TContext> | undefined;
310?: ErrorCallback<TContext> | undefined;
311?: ErrorCallback<TContext> | undefined;
312?: ErrorCallback<TContext> | undefined;
313?: ErrorCallback<TContext> | undefined;
314?: ErrorCallback<TContext> | undefined;
315?: ErrorCallback<TContext> | undefined;
316?: ErrorCallback<TContext> | undefined;
317?: ErrorCallback<TContext> | undefined;
318?: ErrorCallback<TContext> | undefined;
319?: ErrorCallback<TContext> | undefined;
320?: ErrorCallback<TContext> | undefined;
321?: ErrorCallback<TContext> | undefined;
322?: ErrorCallback<TContext> | undefined;
323?: ErrorCallback<TContext> | undefined;
324?: ErrorCallback<TContext> | undefined;
325?: ErrorCallback<TContext> | undefined;
326?: ErrorCallback<TContext> | undefined;
327?: ErrorCallback<TContext> | undefined;
328?: ErrorCallback<TContext> | undefined;
329?: ErrorCallback<TContext> | undefined;
330?: ErrorCallback<TContext> | undefined;
331?: ErrorCallback<TContext> | undefined;
332?: ErrorCallback<TContext> | undefined;
333?: ErrorCallback<TContext> | undefined;
334?: ErrorCallback<TContext> | undefined;
335?: ErrorCallback<TContext> | undefined;
336?: ErrorCallback<TContext> | undefined;
337?: ErrorCallback<TContext> | undefined;
338?: ErrorCallback<TContext> | undefined;
339?: ErrorCallback<TContext> | undefined;
340?: ErrorCallback<TContext> | undefined;
341?: ErrorCallback<TContext> | undefined;
342?: ErrorCallback<TContext> | undefined;
343?: ErrorCallback<TContext> | undefined;
344?: ErrorCallback<TContext> | undefined;
345?: ErrorCallback<TContext> | undefined;
346?: ErrorCallback<TContext> | undefined;
347?: ErrorCallback<TContext> | undefined;
348?: ErrorCallback<TContext> | undefined;
349?: ErrorCallback<TContext> | undefined;
350?: ErrorCallback<TContext> | undefined;
351?: ErrorCallback<TContext> | undefined;
352?: ErrorCallback<TContext> | undefined;
353?: ErrorCallback<TContext> | undefined;
354?: ErrorCallback<TContext> | undefined;
355?: ErrorCallback<TContext> | undefined;
356?: ErrorCallback<TContext> | undefined;
357?: ErrorCallback<TContext> | undefined;
358?: ErrorCallback<TContext> | undefined;
359?: ErrorCallback<TContext> | undefined;
360?: ErrorCallback<TContext> | undefined;
361?: ErrorCallback<TContext> | undefined;
362?: ErrorCallback<TContext> | undefined;
363?: ErrorCallback<TContext> | undefined;
364?: ErrorCallback<TContext> | undefined;
365?: ErrorCallback<TContext> | undefined;
366?: ErrorCallback<TContext> | undefined;
367?: ErrorCallback<TContext> | undefined;
368?: ErrorCallback<TContext> | undefined;
369?: ErrorCallback<TContext> | undefined;
370?: ErrorCallback<TContext> | undefined;
371?: ErrorCallback<TContext> | undefined;
372?: ErrorCallback<TContext> | undefined;
373?: ErrorCallback<TContext> | undefined;
374?: ErrorCallback<TContext> | undefined;
375?: ErrorCallback<TContext> | undefined;
376?: ErrorCallback<TContext> | undefined;
377?: ErrorCallback<TContext> | undefined;
378?: ErrorCallback<TContext> | undefined;
379?: ErrorCallback<TContext> | undefined;
380?: ErrorCallback<TContext> | undefined;
381?: ErrorCallback<TContext> | undefined;
382?: ErrorCallback<TContext> | undefined;
383?: ErrorCallback<TContext> | undefined;
384?: ErrorCallback<TContext> | undefined;
385?: ErrorCallback<TContext> | undefined;
386?: ErrorCallback<TContext> | undefined;
387?: ErrorCallback<TContext> | undefined;
388?: ErrorCallback<TContext> | undefined;
389?: ErrorCallback<TContext> | undefined;
390?: ErrorCallback<TContext> | undefined;
391?: ErrorCallback<TContext> | undefined;
392?: ErrorCallback<TContext> | undefined;
393?: ErrorCallback<TContext> | undefined;
394?: ErrorCallback<TContext> | undefined;
395?: ErrorCallback<TContext> | undefined;
396?: ErrorCallback<TContext> | undefined;
397?: ErrorCallback<TContext> | undefined;
398?: ErrorCallback<TContext> | undefined;
399?: ErrorCallback<TContext> | undefined;
400?: ErrorCallback<TContext> | undefined;
401?: ErrorCallback<TContext> | undefined;
402?: ErrorCallback<TContext> | undefined;
403?: ErrorCallback<TContext> | undefined;
404?: ErrorCallback<TContext> | undefined;
405?: ErrorCallback<TContext> | undefined;
406?: ErrorCallback<TContext> | undefined;
407?: ErrorCallback<TContext> | undefined;
408?: ErrorCallback<TContext> | undefined;
409?: ErrorCallback<TContext> | undefined;
410?: ErrorCallback<TContext> | undefined;
411?: ErrorCallback<TContext> | undefined;
412?: ErrorCallback<TContext> | undefined;
413?: ErrorCallback<TContext> | undefined;
414?: ErrorCallback<TContext> | undefined;
415?: ErrorCallback<TContext> | undefined;
416?: ErrorCallback<TContext> | undefined;
417?: ErrorCallback<TContext> | undefined;
418?: ErrorCallback<TContext> | undefined;
419?: ErrorCallback<TContext> | undefined;
420?: ErrorCallback<TContext> | undefined;
421?: ErrorCallback<TContext> | undefined;
422?: ErrorCallback<TContext> | undefined;
423?: ErrorCallback<TContext> | undefined;
424?: ErrorCallback<TContext> | undefined;
425?: ErrorCallback<TContext> | undefined;
426?: ErrorCallback<TContext> | undefined;
427?: ErrorCallback<TContext> | undefined;
428?: ErrorCallback<TContext> | undefined;
429?: ErrorCallback<TContext> | undefined;
430?: ErrorCallback<TContext> | undefined;
431?: ErrorCallback<TContext> | undefined;
432?: ErrorCallback<TContext> | undefined;
433?: ErrorCallback<TContext> | undefined;
434?: ErrorCallback<TContext> | undefined;
435?: ErrorCallback<TContext> | undefined;
436?: ErrorCallback<TContext> | undefined;
437?: ErrorCallback<TContext> | undefined;
438?: ErrorCallback<TContext> | undefined;
439?: ErrorCallback<TContext> | undefined;
440?: ErrorCallback<TContext> | undefined;
441?: ErrorCallback<TContext> | undefined;
442?: ErrorCallback<TContext> | undefined;
443?: ErrorCallback<TContext> | undefined;
444?: ErrorCallback<TContext> | undefined;
445?: ErrorCallback<TContext> | undefined;
446?: ErrorCallback<TContext> | undefined;
447?: ErrorCallback<TContext> | undefined;
448?: ErrorCallback<TContext> | undefined;
449?: ErrorCallback<TContext> | undefined;
450?: ErrorCallback<TContext> | undefined;
451?: ErrorCallback<TContext> | undefined;
452?: ErrorCallback<TContext> | undefined;
453?: ErrorCallback<TContext> | undefined;
454?: ErrorCallback<TContext> | undefined;
455?: ErrorCallback<TContext> | undefined;
456?: ErrorCallback<TContext> | undefined;
457?: ErrorCallback<TContext> | undefined;
458?: ErrorCallback<TContext> | undefined;
459?: ErrorCallback<TContext> | undefined;
460?: ErrorCallback<TContext> | undefined;
461?: ErrorCallback<TContext> | undefined;
462?: ErrorCallback<TContext> | undefined;
463?: ErrorCallback<TContext> | undefined;
464?: ErrorCallback<TContext> | undefined;
465?: ErrorCallback<TContext> | undefined;
466?: ErrorCallback<TContext> | undefined;
467?: ErrorCallback<TContext> | undefined;
468?: ErrorCallback<TContext> | undefined;
469?: ErrorCallback<TContext> | undefined;
470?: ErrorCallback<TContext> | undefined;
471?: ErrorCallback<TContext> | undefined;
472?: ErrorCallback<TContext> | undefined;
473?: ErrorCallback<TContext> | undefined;
474?: ErrorCallback<TContext> | undefined;
475?: ErrorCallback<TContext> | undefined;
476?: ErrorCallback<TContext> | undefined;
477?: ErrorCallback<TContext> | undefined;
478?: ErrorCallback<TContext> | undefined;
479?: ErrorCallback<TContext> | undefined;
480?: ErrorCallback<TContext> | undefined;
481?: ErrorCallback<TContext> | undefined;
482?: ErrorCallback<TContext> | undefined;
483?: ErrorCallback<TContext> | undefined;
484?: ErrorCallback<TContext> | undefined;
485?: ErrorCallback<TContext> | undefined;
486?: ErrorCallback<TContext> | undefined;
487?: ErrorCallback<TContext> | undefined;
488?: ErrorCallback<TContext> | undefined;
489?: ErrorCallback<TContext> | undefined;
490?: ErrorCallback<TContext> | undefined;
491?: ErrorCallback<TContext> | undefined;
492?: ErrorCallback<TContext> | undefined;
493?: ErrorCallback<TContext> | undefined;
494?: ErrorCallback<TContext> | undefined;
495?: ErrorCallback<TContext> | undefined;
496?: ErrorCallback<TContext> | undefined;
497?: ErrorCallback<TContext> | undefined;
498?: ErrorCallback<TContext> | undefined;
499?: ErrorCallback<TContext> | undefined;
500?: ErrorCallback<TContext> | undefined;
501?: ErrorCallback<TContext> | undefined;
502?: ErrorCallback<TContext> | undefined;
503?: ErrorCallback<TContext> | undefined;
504?: ErrorCallback<TContext> | undefined;
505?: ErrorCallback<TContext> | undefined;
506?: ErrorCallback<TContext> | undefined;
507?: ErrorCallback<TContext> | undefined;
508?: ErrorCallback<TContext> | undefined;
509?: ErrorCallback<TContext> | undefined;
510?: ErrorCallback<TContext> | undefined;
511?: ErrorCallback<TContext> | undefined;
512?: ErrorCallback<TContext> | undefined;
513?: ErrorCallback<TContext> | undefined;
514?: ErrorCallback<TContext> | undefined;
515?: ErrorCallback<TContext> | undefined;
516?: ErrorCallback<TContext> | undefined;
517?: ErrorCallback<TContext> | undefined;
518?: ErrorCallback<TContext> | undefined;
519?: ErrorCallback<TContext> | undefined;
520?: ErrorCallback<TContext> | undefined;
521?: ErrorCallback<TContext> | undefined;
522?: ErrorCallback<TContext> | undefined;
523?: ErrorCallback<TContext> | undefined;
524?: ErrorCallback<TContext> | undefined;
525?: ErrorCallback<TContext> | undefined;
526?: ErrorCallback<TContext> | undefined;
527?: ErrorCallback<TContext> | undefined;
528?: ErrorCallback<TContext> | undefined;
529?: ErrorCallback<TContext> | undefined;
530?: ErrorCallback<TContext> | undefined;
531?: ErrorCallback<TContext> | undefined;
532?: ErrorCallback<TContext> | undefined;
533?: ErrorCallback<TContext> | undefined;
534?: ErrorCallback<TContext> | undefined;
535?: ErrorCallback<TContext> | undefined;
536?: ErrorCallback<TContext> | undefined;
537?: ErrorCallback<TContext> | undefined;
538?: ErrorCallback<TContext> | undefined;
539?: ErrorCallback<TContext> | undefined;
540?: ErrorCallback<TContext> | undefined;
541?: ErrorCallback<TContext> | undefined;
542?: ErrorCallback<TContext> | undefined;
543?: ErrorCallback<TContext> | undefined;
544?: ErrorCallback<TContext> | undefined;
545?: ErrorCallback<TContext> | undefined;
546?: ErrorCallback<TContext> | undefined;
547?: ErrorCallback<TContext> | undefined;
548?: ErrorCallback<TContext> | undefined;
549?: ErrorCallback<TContext> | undefined;
550?: ErrorCallback<TContext> | undefined;
551?: ErrorCallback<TContext> | undefined;
552?: ErrorCallback<TContext> | undefined;
553?: ErrorCallback<TContext> | undefined;
554?: ErrorCallback<TContext> | undefined;
555?: ErrorCallback<TContext> | undefined;
556?: ErrorCallback<TContext> | undefined;
557?: ErrorCallback<TContext> | undefined;
558?: ErrorCallback<TContext> | undefined;
559?: ErrorCallback<TContext> | undefined;
560?: ErrorCallback<TContext> | undefined;
561?: ErrorCallback<TContext> | undefined;
562?: ErrorCallback<TContext> | undefined;
563?: ErrorCallback<TContext> | undefined;
564?: ErrorCallback<TContext> | undefined;
565?: ErrorCallback<TContext> | undefined;
566?: ErrorCallback<TContext> | undefined;
567?: ErrorCallback<TContext> | undefined;
568?: ErrorCallback<TContext> | undefined;
569?: ErrorCallback<TContext> | undefined;
570?: ErrorCallback<TContext> | undefined;
571?: ErrorCallback<TContext> | undefined;
572?: ErrorCallback<TContext> | undefined;
573?: ErrorCallback<TContext> | undefined;
574?: ErrorCallback<TContext> | undefined;
575?: ErrorCallback<TContext> | undefined;
576?: ErrorCallback<TContext> | undefined;
577?: ErrorCallback<TContext> | undefined;
578?: ErrorCallback<TContext> | undefined;
579?: ErrorCallback<TContext> | undefined;
580?: ErrorCallback<TContext> | undefined;
581?: ErrorCallback<TContext> | undefined;
582?: ErrorCallback<TContext> | undefined;
583?: ErrorCallback<TContext> | undefined;
584?: ErrorCallback<TContext> | undefined;
585?: ErrorCallback<TContext> | undefined;
586?: ErrorCallback<TContext> | undefined;
587?: ErrorCallback<TContext> | undefined;
588?: ErrorCallback<TContext> | undefined;
589?: ErrorCallback<TContext> | undefined;
590?: ErrorCallback<TContext> | undefined;
591?: ErrorCallback<TContext> | undefined;
592?: ErrorCallback<TContext> | undefined;
593?: ErrorCallback<TContext> | undefined;
594?: ErrorCallback<TContext> | undefined;
595?: ErrorCallback<TContext> | undefined;
596?: ErrorCallback<TContext> | undefined;
597?: ErrorCallback<TContext> | undefined;
598?: ErrorCallback<TContext> | undefined;
599?: ErrorCallback<TContext> | undefined;
// #endregion
} & {
// Status codes not listed require type annotations when defining the callback
[index: number]: SuccessCallback<TContext> | ErrorCallback<TContext>;
};
// #endregion
// Writable properties on XMLHttpRequest
interface XHRFields extends Partial<Pick<XMLHttpRequest, 'onreadystatechange' | 'responseType' | 'timeout' | 'withCredentials'>> {
msCaching?: string | undefined;
}
}
interface Transport {
send(headers: PlainObject, completeCallback: Transport.SuccessCallback): void;
abort(): void;
}
namespace Transport {
type SuccessCallback = (status: number, statusText: Ajax.TextStatus, responses?: PlainObject, headers?: string) => void;
}
/**
* @see \`{@link https://api.jquery.com/jquery.ajax/#jqXHR }\`
*/
interface jqXHR<TResolve = any> extends Promise3<TResolve, jqXHR<TResolve>, never,
Ajax.SuccessTextStatus, Ajax.ErrorTextStatus, never,
jqXHR<TResolve>, string, never>,
Pick<XMLHttpRequest, 'abort' | 'getAllResponseHeaders' | 'getResponseHeader' | 'overrideMimeType' | 'readyState' | 'responseText' |
'setRequestHeader' | 'status' | 'statusText'>,
Partial<Pick<XMLHttpRequest, 'responseXML'>> {
responseJSON?: any;
abort(statusText?: string): void;
/**
* Determine the current state of a Deferred object.
* @see \`{@link https://api.jquery.com/deferred.state/ }\`
* @since 1.7
*/
state(): 'pending' | 'resolved' | 'rejected';
statusCode(map: Ajax.StatusCodeCallbacks<any>): void;
}
namespace jqXHR {
interface DoneCallback<TResolve = any, TjqXHR = jqXHR<TResolve>> extends Deferred.Callback3<TResolve, Ajax.SuccessTextStatus, TjqXHR> { }
interface FailCallback<TjqXHR> extends Deferred.Callback3<TjqXHR, Ajax.ErrorTextStatus, string> { }
interface AlwaysCallback<TResolve = any, TjqXHR = jqXHR<TResolve>> extends Deferred.Callback3<TResolve | TjqXHR, Ajax.TextStatus, TjqXHR | string> { }
}
// #endregion
// region Callbacks
// #region Callbacks
interface CallbacksStatic {
/**
* A multi-purpose callbacks list object that provides a powerful way to manage callback lists.
* @param flags An optional list of space-separated flags that change how the callback list behaves.
* @see \`{@link https://api.jquery.com/jQuery.Callbacks/ }\`
* @since 1.7
*/
// tslint:disable-next-line:ban-types no-unnecessary-generics
<T extends Function>(flags?: string): Callbacks<T>;
}
// tslint:disable-next-line:ban-types
interface Callbacks<T extends Function = Function> {
/**
* Add a callback or a collection of callbacks to a callback list.
* @param callback A function, or array of functions, that are to be added to the callback list.
* @param callbacks A function, or array of functions, that are to be added to the callback list.
* @see \`{@link https://api.jquery.com/callbacks.add/ }\`
* @since 1.7
* @example ````Use callbacks.add() to add new callbacks to a callback list:
```javascript
// A sample logging function to be added to a callbacks list
var foo = function( value ) {
console.log( "foo: " + value );
};
// Another function to also be added to the list
var bar = function( value ) {
console.log( "bar: " + value );
};
var callbacks = $.Callbacks();
// Add the function "foo" to the list
callbacks.add( foo );
// Fire the items on the list
callbacks.fire( "hello" );
// Outputs: "foo: hello"
// Add the function "bar" to the list
callbacks.add( bar );
// Fire the items on the list again
callbacks.fire( "world" );
// Outputs:
// "foo: world"
// "bar: world"
```
*/
add(callback: TypeOrArray<T>, ...callbacks: Array<TypeOrArray<T>>): this;
/**
* Disable a callback list from doing anything more.
* @see \`{@link https://api.jquery.com/callbacks.disable/ }\`
* @since 1.7
* @example ````Use callbacks.disable() to disable further calls to a callback list:
```javascript
// A sample logging function to be added to a callbacks list
var foo = function( value ) {
console.log( value );
};
var callbacks = $.Callbacks();
// Add the above function to the list
callbacks.add( foo );
// Fire the items on the list
callbacks.fire( "foo" );
// Outputs: foo
// Disable further calls being possible
callbacks.disable();
// Attempt to fire with "foobar" as an argument
callbacks.fire( "foobar" );
// foobar isn't output
```
*/
disable(): this;
/**
* Determine if the callbacks list has been disabled.
* @see \`{@link https://api.jquery.com/callbacks.disabled/ }\`
* @since 1.7
* @example ````Use callbacks.disabled() to determine if the callbacks list has been disabled:
```javascript
// A sample logging function to be added to a callbacks list
var foo = function( value ) {
console.log( "foo:" + value );
};
var callbacks = $.Callbacks();
// Add the logging function to the callback list
callbacks.add( foo );
// Fire the items on the list, passing an argument
callbacks.fire( "hello" );
// Outputs "foo: hello"
// Disable the callbacks list
callbacks.disable();
// Test the disabled state of the list
console.log ( callbacks.disabled() );
// Outputs: true
```
*/
disabled(): boolean;
/**
* Remove all of the callbacks from a list.
* @see \`{@link https://api.jquery.com/callbacks.empty/ }\`
* @since 1.7
* @example ````Use callbacks.empty() to empty a list of callbacks:
```javascript
// A sample logging function to be added to a callbacks list
var foo = function( value1, value2 ) {
console.log( "foo: " + value1 + "," + value2 );
};
// Another function to also be added to the list
var bar = function( value1, value2 ) {
console.log( "bar: " + value1 + "," + value2 );
};
var callbacks = $.Callbacks();
// Add the two functions
callbacks.add( foo );
callbacks.add( bar );
// Empty the callbacks list
callbacks.empty();
// Check to ensure all callbacks have been removed
console.log( callbacks.has( foo ) );
// false
console.log( callbacks.has( bar ) );
// false
```
*/
empty(): this;
/**
* Call all of the callbacks with the given arguments.
* @param args The argument or list of arguments to pass back to the callback list.
* @see \`{@link https://api.jquery.com/callbacks.fire/ }\`
* @since 1.7
* @example ````Use callbacks.fire() to invoke the callbacks in a list with any arguments that have been passed:
```javascript
// A sample logging function to be added to a callbacks list
var foo = function( value ) {
console.log( "foo:" + value );
};
var callbacks = $.Callbacks();
// Add the function "foo" to the list
callbacks.add( foo );
// Fire the items on the list
callbacks.fire( "hello" ); // Outputs: "foo: hello"
callbacks.fire( "world" ); // Outputs: "foo: world"
// Add another function to the list
var bar = function( value ){
console.log( "bar:" + value );
};
// Add this function to the list
callbacks.add( bar );
// Fire the items on the list again
callbacks.fire( "hello again" );
// Outputs:
// "foo: hello again"
// "bar: hello again"
```
*/
fire(...args: any[]): this;
/**
* Determine if the callbacks have already been called at least once.
* @see \`{@link https://api.jquery.com/callbacks.fired/ }\`
* @since 1.7
* @example ````Use callbacks.fired() to determine if the callbacks in a list have been called at least once:
```javascript
// A sample logging function to be added to a callbacks list
var foo = function( value ) {
console.log( "foo:" + value );
};
var callbacks = $.Callbacks();
// Add the function "foo" to the list
callbacks.add( foo );
// Fire the items on the list
callbacks.fire( "hello" ); // Outputs: "foo: hello"
callbacks.fire( "world" ); // Outputs: "foo: world"
// Test to establish if the callbacks have been called
console.log( callbacks.fired() );
```
*/
fired(): boolean;
/**
* Call all callbacks in a list with the given context and arguments.
* @param context A reference to the context in which the callbacks in the list should be fired.
* @param args An argument, or array of arguments, to pass to the callbacks in the list.
* @see \`{@link https://api.jquery.com/callbacks.fireWith/ }\`
* @since 1.7
* @example ````Use callbacks.fireWith() to fire a list of callbacks with a specific context and an array of arguments:
```javascript
// A sample logging function to be added to a callbacks list
var log = function( value1, value2 ) {
console.log( "Received: " + value1 + "," + value2 );
};
var callbacks = $.Callbacks();
// Add the log method to the callbacks list
callbacks.add( log );
// Fire the callbacks on the list using the context "window"
// and an arguments array
callbacks.fireWith( window, [ "foo","bar" ] );
// Outputs: "Received: foo, bar"
```
*/
fireWith(context: object, args?: ArrayLike<any>): this;
/**
* Determine whether or not the list has any callbacks attached. If a callback is provided as an argument, determine whether it is in a list.
* @param callback The callback to search for.
* @see \`{@link https://api.jquery.com/callbacks.has/ }\`
* @since 1.7
* @example ````Use callbacks.has() to check if a callback list contains a specific callback:
```javascript
// A sample logging function to be added to a callbacks list
var foo = function( value1, value2 ) {
console.log( "Received: " + value1 + "," + value2 );
};
// A second function which will not be added to the list
var bar = function( value1, value2 ) {
console.log( "foobar" );
};
var callbacks = $.Callbacks();
// Add the log method to the callbacks list
callbacks.add( foo );
// Determine which callbacks are in the list
console.log( callbacks.has( foo ) );
// true
console.log( callbacks.has( bar ) );
// false
```
*/
has(callback?: T): boolean;
/**
* Lock a callback list in its current state.
* @see \`{@link https://api.jquery.com/callbacks.lock/ }\`
* @since 1.7
* @example ````Use callbacks.lock() to lock a callback list to avoid further changes being made to the list state:
```javascript
// A sample logging function to be added to a callbacks list
var foo = function( value ) {
console.log( "foo:" + value );
};
var callbacks = $.Callbacks();
// Add the logging function to the callback list
callbacks.add( foo );
// Fire the items on the list, passing an argument
callbacks.fire( "hello" );
// Outputs "foo: hello"
// Lock the callbacks list
callbacks.lock();
// Try firing the items again
callbacks.fire( "world" );
// As the list was locked, no items were called,
// so "world" isn't logged
```
* @example ````Use callbacks.lock() to lock a callback list with "memory," and then resume using the list:
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>callbacks.lock demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<div id="log"></div>
<script>
// Simple function for logging results
var log = function( value ) {
$( "#log" ).append( "<p>" + value + "</p>" );
};
// Two sample functions to be added to a callbacks list
var foo = function( value ) {
log( "foo: " + value );
};
var bar = function( value ) {
log( "bar: " + value );
};
// Create the callbacks object with the "memory" flag
var callbacks = $.Callbacks( "memory" );
// Add the foo logging function to the callback list
callbacks.add( foo );
// Fire the items on the list, passing an argument
callbacks.fire( "hello" );
// Outputs "foo: hello"
// Lock the callbacks list
callbacks.lock();
// Try firing the items again
callbacks.fire( "world" );
// As the list was locked, no items were called,
// so "foo: world" isn't logged
// Add the foo function to the callback list again
callbacks.add( foo );
// Try firing the items again
callbacks.fire( "silentArgument" );
// Outputs "foo: hello" because the argument value was stored in memory
// Add the bar function to the callback list
callbacks.add( bar );
callbacks.fire( "youHadMeAtHello" );
// Outputs "bar: hello" because the list is still locked,
// and the argument value is still stored in memory
</script>
</body>
</html>
```
*/
lock(): this;
/**
* Determine if the callbacks list has been locked.
* @see \`{@link https://api.jquery.com/callbacks.locked/ }\`
* @since 1.7
* @example ````Use callbacks.locked() to determine the lock-state of a callback list:
```javascript
// A sample logging function to be added to a callbacks list
var foo = function( value ) {
console.log( "foo: " + value );
};
var callbacks = $.Callbacks();
// Add the logging function to the callback list
callbacks.add( foo );
// Fire the items on the list, passing an argument
callbacks.fire( "hello" );
// Outputs "foo: hello"
// Lock the callbacks list
callbacks.lock();
// Test the lock-state of the list
console.log ( callbacks.locked() );
// true
```
*/
locked(): boolean;
/**
* Remove a callback or a collection of callbacks from a callback list.
* @param callbacks A function, or array of functions, that are to be removed from the callback list.
* @see \`{@link https://api.jquery.com/callbacks.remove/ }\`
* @since 1.7
* @example ````Use callbacks.remove() to remove callbacks from a callback list:
```javascript
// A sample logging function to be added to a callbacks list
var foo = function( value ) {
console.log( "foo: " + value );
};
var callbacks = $.Callbacks();
// Add the function "foo" to the list
callbacks.add( foo );
// Fire the items on the list
callbacks.fire( "hello" );
// Outputs: "foo: hello"
// Remove "foo" from the callback list
callbacks.remove( foo );
// Fire the items on the list again
callbacks.fire( "world" );
// Nothing output as "foo" is no longer in the list
```
*/
remove(...callbacks: T[]): this;
}
// #endregion
// region CSS hooks
// #region CSS hooks
// Workaround for TypeScript 2.3 which does not have support for weak types handling.
type CSSHook<TElement> =
Partial<_CSSHook<TElement>> & (
Pick<_CSSHook<TElement>, 'get'> |
Pick<_CSSHook<TElement>, 'set'>
);
interface _CSSHook<TElement> {
get(elem: TElement, computed: any, extra: any): any;
set(elem: TElement, value: any): void;
}
interface CSSHooks {
// Set to HTMLElement to minimize breaks but should probably be Element.
[propertyName: string]: CSSHook<HTMLElement>;
}
// #endregion
// region Deferred
// #region Deferred
/**
* Any object that has a then method.
*/
interface Thenable<T> extends PromiseLike<T> { }
// Type parameter guide
// --------------------
// Each type parameter represents a parameter in one of the three possible callbacks.
//
// The first letter indicates which position the parameter is in.
//
// T = A = 1st position
// U = B = 2nd position
// V = C = 3rd position
// S = R = rest position
//
// The second letter indicates which whether it is a [R]esolve, Re[J]ect, or [N]otify value.
//
// The third letter indicates whether the value is returned in the [D]one filter, [F]ail filter, or [P]rogress filter.
/**
* This object provides a subset of the methods of the Deferred object (then, done, fail, always, pipe, progress, state and promise) to prevent users from changing the state of the Deferred.
* @see \`{@link https://api.jquery.com/Types/#Promise }\`
*/
interface PromiseBase<TR, TJ, TN,
UR, UJ, UN,
VR, VJ, VN,
SR, SJ, SN> {
/**
* Add handlers to be called when the Deferred object is either resolved or rejected.
* @param alwaysCallback A function, or array of functions, that is called when the Deferred is resolved or rejected.
* @param alwaysCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected.
* @see \`{@link https://api.jquery.com/deferred.always/ }\`
* @since 1.6
* @example ````Since the jQuery.get() method returns a jqXHR object, which is derived from a Deferred object, we can attach a callback for both success and error using the deferred.always() method.
```javascript
$.get( "test.php" ).always(function() {
alert( "$.get completed with success or error callback arguments" );
});
```
*/
always(alwaysCallback: TypeOrArray<Deferred.CallbackBase<TR | TJ, UR | UJ, VR | VJ, SR | SJ>>,
...alwaysCallbacks: Array<TypeOrArray<Deferred.CallbackBase<TR | TJ, UR | UJ, VR | VJ, SR | SJ>>>): this;
/**
* Add handlers to be called when the Deferred object is resolved.
* @param doneCallback A function, or array of functions, that are called when the Deferred is resolved.
* @param doneCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is resolved.
* @see \`{@link https://api.jquery.com/deferred.done/ }\`
* @since 1.5
* @example ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach a success callback using the .done() method.
```javascript
$.get( "test.php" ).done(function() {
alert( "$.get succeeded" );
});
```
* @example ````Resolve a Deferred object when the user clicks a button, triggering a number of callback functions:
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>deferred.done demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<button>Go</button>
<p>Ready...</p>
<script>
// 3 functions to call when the Deferred object is resolved
function fn1() {
$( "p" ).append( " 1 " );
}
function fn2() {
$( "p" ).append( " 2 " );
}
function fn3( n ) {
$( "p" ).append( n + " 3 " + n );
}
// Create a deferred object
var dfd = $.Deferred();
// Add handlers to be called when dfd is resolved
dfd
// .done() can take any number of functions or arrays of functions
.done( [ fn1, fn2 ], fn3, [ fn2, fn1 ] )
// We can chain done methods, too
.done(function( n ) {
$( "p" ).append( n + " we're done." );
});
// Resolve the Deferred object when the button is clicked
$( "button" ).on( "click", function() {
dfd.resolve( "and" );
});
</script>
</body>
</html>
```
*/
done(doneCallback: TypeOrArray<Deferred.CallbackBase<TR, UR, VR, SR>>,
...doneCallbacks: Array<TypeOrArray<Deferred.CallbackBase<TR, UR, VR, SR>>>): this;
/**
* Add handlers to be called when the Deferred object is rejected.
* @param failCallback A function, or array of functions, that are called when the Deferred is rejected.
* @param failCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is rejected.
* @see \`{@link https://api.jquery.com/deferred.fail/ }\`
* @since 1.5
* @example ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred, you can attach a success and failure callback using the deferred.done() and deferred.fail() methods.
```javascript
$.get( "test.php" )
.done(function() {
alert( "$.get succeeded" );
})
.fail(function() {
alert( "$.get failed!" );
});
```
*/
fail(failCallback: TypeOrArray<Deferred.CallbackBase<TJ, UJ, VJ, SJ>>,
...failCallbacks: Array<TypeOrArray<Deferred.CallbackBase<TJ, UJ, VJ, SJ>>>): this;
/**
* Add handlers to be called when the Deferred object generates progress notifications.
* @param progressCallback A function, or array of functions, to be called when the Deferred generates progress notifications.
* @param progressCallbacks Optional additional functions, or arrays of functions, to be called when the Deferred generates
* progress notifications.
* @see \`{@link https://api.jquery.com/deferred.progress/ }\`
* @since 1.7
*/
progress(progressCallback: TypeOrArray<Deferred.CallbackBase<TN, UN, VN, SN>>,
...progressCallbacks: Array<TypeOrArray<Deferred.CallbackBase<TN, UN, VN, SN>>>): this;
/**
* Return a Deferred's Promise object.
* @param target Object onto which the promise methods have to be attached
* @see \`{@link https://api.jquery.com/deferred.promise/ }\`
* @since 1.5
* @example ````Create a Deferred and set two timer-based functions to either resolve or reject the Deferred after a random interval. Whichever one fires first "wins" and will call one of the callbacks. The second timeout has no effect since the Deferred is already complete (in a resolved or rejected state) from the first timeout action. Also set a timer-based progress notification function, and call a progress handler that adds "working..." to the document body.
```javascript
function asyncEvent() {
var dfd = jQuery.Deferred();
// Resolve after a random interval
setTimeout(function() {
dfd.resolve( "hurray" );
}, Math.floor( 400 + Math.random() * 2000 ) );
// Reject after a random interval
setTimeout(function() {
dfd.reject( "sorry" );
}, Math.floor( 400 + Math.random() * 2000 ) );
// Show a "working..." message every half-second
setTimeout(function working() {
if ( dfd.state() === "pending" ) {
dfd.notify( "working... " );
setTimeout( working, 500 );
}
}, 1 );
// Return the Promise so caller can't change the Deferred
return dfd.promise();
}
// Attach a done, fail, and progress handler for the asyncEvent
$.when( asyncEvent() ).then(
function( status ) {
alert( status + ", things are going well" );
},
function( status ) {
alert( status + ", you fail this time" );
},
function( status ) {
$( "body" ).append( status );
}
);
```
*/
promise<TTarget extends object>(target: TTarget): this & TTarget;
/**
* Return a Deferred's Promise object.
* @see \`{@link https://api.jquery.com/deferred.promise/ }\`
* @since 1.5
* @example ````Use the target argument to promote an existing object to a Promise:
```javascript
// Existing object
var obj = {
hello: function( name ) {
alert( "Hello " + name );
}
},
// Create a Deferred
defer = $.Deferred();
// Set object as a promise
defer.promise( obj );
// Resolve the deferred
defer.resolve( "John" );
// Use the object as a Promise
obj.done(function( name ) {
obj.hello( name ); // Will alert "Hello John"
}).hello( "Karl" ); // Will alert "Hello Karl"
```
*/
promise(): this;
/**
* Determine the current state of a Deferred object.
* @see \`{@link https://api.jquery.com/deferred.state/ }\`
* @since 1.7
*/
state(): 'pending' | 'resolved' | 'rejected';
// region pipe
// #region pipe
/**
* Utility method to filter and/or chain Deferreds.
* @param doneFilter An optional function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.pipe/ }\`
* @since 1.6
* @since 1.7
* @deprecated Deprecated since 1.8. Use \`{@link then }\`.
*
* **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function.
*
* **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0.
* @example ````Filter resolve value:
```javascript
var defer = $.Deferred(),
filtered = defer.pipe(function( value ) {
return value * 2;
});
defer.resolve( 5 );
filtered.done(function( value ) {
alert( "Value is ( 2*5 = ) 10: " + value );
});
```
* @example ````Filter reject value:
```javascript
var defer = $.Deferred(),
filtered = defer.pipe( null, function( value ) {
return value * 3;
});
defer.reject( 6 );
filtered.fail(function( value ) {
alert( "Value is ( 3*6 = ) 18: " + value );
});
```
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.pipe(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
pipe<ARD = never, AJD = never, AND = never,
BRD = never, BJD = never, BND = never,
CRD = never, CJD = never, CND = never,
RRD = never, RJD = never, RND = never,
ARF = never, AJF = never, ANF = never,
BRF = never, BJF = never, BNF = never,
CRF = never, CJF = never, CNF = never,
RRF = never, RJF = never, RNF = never,
ARP = never, AJP = never, ANP = never,
BRP = never, BJP = never, BNP = never,
CRP = never, CJP = never, CNP = never,
RRP = never, RJP = never, RNP = never>(
doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase<ARD, AJD, AND,
BRD, BJD, BND,
CRD, CJD, CND,
RRD, RJD, RND> | Thenable<ARD> | ARD,
failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase<ARF, AJF, ANF,
BRF, BJF, BNF,
CRF, CJF, CNF,
RRF, RJF, RNF> | Thenable<AJF> | AJF,
progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase<ARP, AJP, ANP,
BRP, BJP, BNP,
CRP, CJP, CNP,
RRP, RJP, RNP> | Thenable<ANP> | ANP): PromiseBase<ARD | ARF | ARP, AJD | AJF | AJP, AND | ANF | ANP,
BRD | BRF | BRP, BJD | BJF | BJP, BND | BNF | BNP,
CRD | CRF | CRP, CJD | CJF | CJP, CND | CNF | CNP,
RRD | RRF | RRP, RJD | RJF | RJP, RND | RNF | RNP>;
/**
* Utility method to filter and/or chain Deferreds.
* @param doneFilter An optional function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.pipe/ }\`
* @since 1.6
* @since 1.7
* @deprecated Deprecated since 1.8. Use \`{@link then }\`.
*
* **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function.
*
* **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0.
* @example ````Filter reject value:
```javascript
var defer = $.Deferred(),
filtered = defer.pipe( null, function( value ) {
return value * 3;
});
defer.reject( 6 );
filtered.fail(function( value ) {
alert( "Value is ( 3*6 = ) 18: " + value );
});
```
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.pipe(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
pipe<ARF = never, AJF = never, ANF = never,
BRF = never, BJF = never, BNF = never,
CRF = never, CJF = never, CNF = never,
RRF = never, RJF = never, RNF = never,
ARP = never, AJP = never, ANP = never,
BRP = never, BJP = never, BNP = never,
CRP = never, CJP = never, CNP = never,
RRP = never, RJP = never, RNP = never>(
doneFilter: null,
failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase<ARF, AJF, ANF,
BRF, BJF, BNF,
CRF, CJF, CNF,
RRF, RJF, RNF> | Thenable<AJF> | AJF,
progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase<ARP, AJP, ANP,
BRP, BJP, BNP,
CRP, CJP, CNP,
RRP, RJP, RNP> | Thenable<ANP> | ANP): PromiseBase<ARF | ARP, AJF | AJP, ANF | ANP,
BRF | BRP, BJF | BJP, BNF | BNP,
CRF | CRP, CJF | CJP, CNF | CNP,
RRF | RRP, RJF | RJP, RNF | RNP>;
/**
* Utility method to filter and/or chain Deferreds.
* @param doneFilter An optional function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.pipe/ }\`
* @since 1.6
* @since 1.7
* @deprecated Deprecated since 1.8. Use \`{@link then }\`.
*
* **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function.
*
* **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0.
* @example ````Filter resolve value:
```javascript
var defer = $.Deferred(),
filtered = defer.pipe(function( value ) {
return value * 2;
});
defer.resolve( 5 );
filtered.done(function( value ) {
alert( "Value is ( 2*5 = ) 10: " + value );
});
```
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.pipe(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
pipe<ARD = never, AJD = never, AND = never,
BRD = never, BJD = never, BND = never,
CRD = never, CJD = never, CND = never,
RRD = never, RJD = never, RND = never,
ARP = never, AJP = never, ANP = never,
BRP = never, BJP = never, BNP = never,
CRP = never, CJP = never, CNP = never,
RRP = never, RJP = never, RNP = never>(
doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase<ARD, AJD, AND,
BRD, BJD, BND,
CRD, CJD, CND,
RRD, RJD, RND> | Thenable<ARD> | ARD,
failFilter: null,
progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase<ARP, AJP, ANP,
BRP, BJP, BNP,
CRP, CJP, CNP,
RRP, RJP, RNP> | Thenable<ANP> | ANP): PromiseBase<ARD | ARP, AJD | AJP, AND | ANP,
BRD | BRP, BJD | BJP, BND | BNP,
CRD | CRP, CJD | CJP, CND | CNP,
RRD | RRP, RJD | RJP, RND | RNP>;
/**
* Utility method to filter and/or chain Deferreds.
* @param doneFilter An optional function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.pipe/ }\`
* @since 1.6
* @since 1.7
* @deprecated Deprecated since 1.8. Use \`{@link then }\`.
*
* **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function.
*
* **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0.
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.pipe(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
pipe<ARP = never, AJP = never, ANP = never,
BRP = never, BJP = never, BNP = never,
CRP = never, CJP = never, CNP = never,
RRP = never, RJP = never, RNP = never>(
doneFilter: null,
failFilter: null,
progressFilter?: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase<ARP, AJP, ANP,
BRP, BJP, BNP,
CRP, CJP, CNP,
RRP, RJP, RNP> | Thenable<ANP> | ANP): PromiseBase<ARP, AJP, ANP,
BRP, BJP, BNP,
CRP, CJP, CNP,
RRP, RJP, RNP>;
/**
* Utility method to filter and/or chain Deferreds.
* @param doneFilter An optional function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.pipe/ }\`
* @since 1.6
* @since 1.7
* @deprecated Deprecated since 1.8. Use \`{@link then }\`.
*
* **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function.
*
* **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0.
* @example ````Filter resolve value:
```javascript
var defer = $.Deferred(),
filtered = defer.pipe(function( value ) {
return value * 2;
});
defer.resolve( 5 );
filtered.done(function( value ) {
alert( "Value is ( 2*5 = ) 10: " + value );
});
```
* @example ````Filter reject value:
```javascript
var defer = $.Deferred(),
filtered = defer.pipe( null, function( value ) {
return value * 3;
});
defer.reject( 6 );
filtered.fail(function( value ) {
alert( "Value is ( 3*6 = ) 18: " + value );
});
```
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.pipe(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
pipe<ARD = never, AJD = never, AND = never,
BRD = never, BJD = never, BND = never,
CRD = never, CJD = never, CND = never,
RRD = never, RJD = never, RND = never,
ARF = never, AJF = never, ANF = never,
BRF = never, BJF = never, BNF = never,
CRF = never, CJF = never, CNF = never,
RRF = never, RJF = never, RNF = never>(
doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase<ARD, AJD, AND,
BRD, BJD, BND,
CRD, CJD, CND,
RRD, RJD, RND> | Thenable<ARD> | ARD,
failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase<ARF, AJF, ANF,
BRF, BJF, BNF,
CRF, CJF, CNF,
RRF, RJF, RNF> | Thenable<AJF> | AJF,
progressFilter?: null): PromiseBase<ARD | ARF, AJD | AJF, AND | ANF,
BRD | BRF, BJD | BJF, BND | BNF,
CRD | CRF, CJD | CJF, CND | CNF,
RRD | RRF, RJD | RJF, RND | RNF>;
/**
* Utility method to filter and/or chain Deferreds.
* @param doneFilter An optional function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.pipe/ }\`
* @since 1.6
* @since 1.7
* @deprecated Deprecated since 1.8. Use \`{@link then }\`.
*
* **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function.
*
* **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0.
* @example ````Filter reject value:
```javascript
var defer = $.Deferred(),
filtered = defer.pipe( null, function( value ) {
return value * 3;
});
defer.reject( 6 );
filtered.fail(function( value ) {
alert( "Value is ( 3*6 = ) 18: " + value );
});
```
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.pipe(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
pipe<ARF = never, AJF = never, ANF = never,
BRF = never, BJF = never, BNF = never,
CRF = never, CJF = never, CNF = never,
RRF = never, RJF = never, RNF = never>(
doneFilter: null,
failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase<ARF, AJF, ANF,
BRF, BJF, BNF,
CRF, CJF, CNF,
RRF, RJF, RNF> | Thenable<AJF> | AJF,
progressFilter?: null): PromiseBase<ARF, AJF, ANF,
BRF, BJF, BNF,
CRF, CJF, CNF,
RRF, RJF, RNF>;
/**
* Utility method to filter and/or chain Deferreds.
* @param doneFilter An optional function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.pipe/ }\`
* @since 1.6
* @since 1.7
* @deprecated Deprecated since 1.8. Use \`{@link then }\`.
*
* **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function.
*
* **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0.
* @example ````Filter resolve value:
```javascript
var defer = $.Deferred(),
filtered = defer.pipe(function( value ) {
return value * 2;
});
defer.resolve( 5 );
filtered.done(function( value ) {
alert( "Value is ( 2*5 = ) 10: " + value );
});
```
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.pipe(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
pipe<ARD = never, AJD = never, AND = never,
BRD = never, BJD = never, BND = never,
CRD = never, CJD = never, CND = never,
RRD = never, RJD = never, RND = never>(
doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase<ARD, AJD, AND,
BRD, BJD, BND,
CRD, CJD, CND,
RRD, RJD, RND> | Thenable<ARD> | ARD,
failFilter?: null,
progressFilter?: null): PromiseBase<ARD, AJD, AND,
BRD, BJD, BND,
CRD, CJD, CND,
RRD, RJD, RND>;
// #endregion
// region then
// #region then
/**
* Add handlers to be called when the Deferred object is resolved, rejected, or still in progress.
* @param doneFilter An optional function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.then/ }\`
* @since 1.8
* @example ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach handlers using the .then method.
```javascript
$.get( "test.php" ).then(
function() {
alert( "$.get succeeded" );
}, function() {
alert( "$.get failed!" );
}
);
```
* @example ````Filter the resolve value:
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>deferred.then demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<button>Filter Resolve</button>
<p></p>
<script>
var filterResolve = function() {
var defer = $.Deferred(),
filtered = defer.then(function( value ) {
return value * 2;
});
defer.resolve( 5 );
filtered.done(function( value ) {
$( "p" ).html( "Value is ( 2*5 = ) 10: " + value );
});
};
$( "button" ).on( "click", filterResolve );
</script>
</body>
</html>
```
* @example ````Filter reject value:
```javascript
var defer = $.Deferred(),
filtered = defer.then( null, function( value ) {
return value * 3;
});
defer.reject( 6 );
filtered.fail(function( value ) {
alert( "Value is ( 3*6 = ) 18: " + value );
});
```
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.then(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
then<ARD = never, AJD = never, AND = never,
BRD = never, BJD = never, BND = never,
CRD = never, CJD = never, CND = never,
RRD = never, RJD = never, RND = never,
ARF = never, AJF = never, ANF = never,
BRF = never, BJF = never, BNF = never,
CRF = never, CJF = never, CNF = never,
RRF = never, RJF = never, RNF = never,
ARP = never, AJP = never, ANP = never,
BRP = never, BJP = never, BNP = never,
CRP = never, CJP = never, CNP = never,
RRP = never, RJP = never, RNP = never>(
doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase<ARD, AJD, AND,
BRD, BJD, BND,
CRD, CJD, CND,
RRD, RJD, RND> | Thenable<ARD> | ARD,
failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase<ARF, AJF, ANF,
BRF, BJF, BNF,
CRF, CJF, CNF,
RRF, RJF, RNF> | Thenable<ARF> | ARF,
progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase<ARP, AJP, ANP,
BRP, BJP, BNP,
CRP, CJP, CNP,
RRP, RJP, RNP> | Thenable<ANP> | ANP): PromiseBase<ARD | ARF | ARP, AJD | AJF | AJP, AND | ANF | ANP,
BRD | BRF | BRP, BJD | BJF | BJP, BND | BNF | BNP,
CRD | CRF | CRP, CJD | CJF | CJP, CND | CNF | CNP,
RRD | RRF | RRP, RJD | RJF | RJP, RND | RNF | RNP>;
/**
* Add handlers to be called when the Deferred object is resolved, rejected, or still in progress.
* @param doneFilter An optional function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.then/ }\`
* @since 1.8
* @example ````Filter reject value:
```javascript
var defer = $.Deferred(),
filtered = defer.then( null, function( value ) {
return value * 3;
});
defer.reject( 6 );
filtered.fail(function( value ) {
alert( "Value is ( 3*6 = ) 18: " + value );
});
```
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.then(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
then<ARF = never, AJF = never, ANF = never,
BRF = never, BJF = never, BNF = never,
CRF = never, CJF = never, CNF = never,
RRF = never, RJF = never, RNF = never,
ARP = never, AJP = never, ANP = never,
BRP = never, BJP = never, BNP = never,
CRP = never, CJP = never, CNP = never,
RRP = never, RJP = never, RNP = never>(
doneFilter: null,
failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase<ARF, AJF, ANF,
BRF, BJF, BNF,
CRF, CJF, CNF,
RRF, RJF, RNF> | Thenable<ARF> | ARF,
progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase<ARP, AJP, ANP,
BRP, BJP, BNP,
CRP, CJP, CNP,
RRP, RJP, RNP> | Thenable<ANP> | ANP): PromiseBase<ARF | ARP, AJF | AJP, ANF | ANP,
BRF | BRP, BJF | BJP, BNF | BNP,
CRF | CRP, CJF | CJP, CNF | CNP,
RRF | RRP, RJF | RJP, RNF | RNP>;
/**
* Add handlers to be called when the Deferred object is resolved, rejected, or still in progress.
* @param doneFilter An optional function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.then/ }\`
* @since 1.8
* @example ````Filter the resolve value:
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>deferred.then demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<button>Filter Resolve</button>
<p></p>
<script>
var filterResolve = function() {
var defer = $.Deferred(),
filtered = defer.then(function( value ) {
return value * 2;
});
defer.resolve( 5 );
filtered.done(function( value ) {
$( "p" ).html( "Value is ( 2*5 = ) 10: " + value );
});
};
$( "button" ).on( "click", filterResolve );
</script>
</body>
</html>
```
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.then(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
then<ARD = never, AJD = never, AND = never,
BRD = never, BJD = never, BND = never,
CRD = never, CJD = never, CND = never,
RRD = never, RJD = never, RND = never,
ARP = never, AJP = never, ANP = never,
BRP = never, BJP = never, BNP = never,
CRP = never, CJP = never, CNP = never,
RRP = never, RJP = never, RNP = never>(
doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase<ARD, AJD, AND,
BRD, BJD, BND,
CRD, CJD, CND,
RRD, RJD, RND> | Thenable<ARD> | ARD,
failFilter: null,
progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase<ARP, AJP, ANP,
BRP, BJP, BNP,
CRP, CJP, CNP,
RRP, RJP, RNP> | Thenable<ANP> | ANP): PromiseBase<ARD | ARP, AJD | AJP, AND | ANP,
BRD | BRP, BJD | BJP, BND | BNP,
CRD | CRP, CJD | CJP, CND | CNP,
RRD | RRP, RJD | RJP, RND | RNP>;
/**
* Add handlers to be called when the Deferred object is resolved, rejected, or still in progress.
* @param doneFilter An optional function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.then/ }\`
* @since 1.8
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.then(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
then<ARP = never, AJP = never, ANP = never,
BRP = never, BJP = never, BNP = never,
CRP = never, CJP = never, CNP = never,
RRP = never, RJP = never, RNP = never>(
doneFilter: null,
failFilter: null,
progressFilter?: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase<ARP, AJP, ANP,
BRP, BJP, BNP,
CRP, CJP, CNP,
RRP, RJP, RNP> | Thenable<ANP> | ANP): PromiseBase<ARP, AJP, ANP,
BRP, BJP, BNP,
CRP, CJP, CNP,
RRP, RJP, RNP>;
/**
* Add handlers to be called when the Deferred object is resolved, rejected, or still in progress.
* @param doneFilter An optional function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.then/ }\`
* @since 1.8
* @example ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach handlers using the .then method.
```javascript
$.get( "test.php" ).then(
function() {
alert( "$.get succeeded" );
}, function() {
alert( "$.get failed!" );
}
);
```
* @example ````Filter the resolve value:
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>deferred.then demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<button>Filter Resolve</button>
<p></p>
<script>
var filterResolve = function() {
var defer = $.Deferred(),
filtered = defer.then(function( value ) {
return value * 2;
});
defer.resolve( 5 );
filtered.done(function( value ) {
$( "p" ).html( "Value is ( 2*5 = ) 10: " + value );
});
};
$( "button" ).on( "click", filterResolve );
</script>
</body>
</html>
```
* @example ````Filter reject value:
```javascript
var defer = $.Deferred(),
filtered = defer.then( null, function( value ) {
return value * 3;
});
defer.reject( 6 );
filtered.fail(function( value ) {
alert( "Value is ( 3*6 = ) 18: " + value );
});
```
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.then(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
then<ARD = never, AJD = never, AND = never,
BRD = never, BJD = never, BND = never,
CRD = never, CJD = never, CND = never,
RRD = never, RJD = never, RND = never,
ARF = never, AJF = never, ANF = never,
BRF = never, BJF = never, BNF = never,
CRF = never, CJF = never, CNF = never,
RRF = never, RJF = never, RNF = never>(
doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase<ARD, AJD, AND,
BRD, BJD, BND,
CRD, CJD, CND,
RRD, RJD, RND> | Thenable<ARD> | ARD,
failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase<ARF, AJF, ANF,
BRF, BJF, BNF,
CRF, CJF, CNF,
RRF, RJF, RNF> | Thenable<ARF> | ARF,
progressFilter?: null): PromiseBase<ARD | ARF, AJD | AJF, AND | ANF,
BRD | BRF, BJD | BJF, BND | BNF,
CRD | CRF, CJD | CJF, CND | CNF,
RRD | RRF, RJD | RJF, RND | RNF>;
/**
* Add handlers to be called when the Deferred object is resolved, rejected, or still in progress.
* @param doneFilter An optional function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.then/ }\`
* @since 1.8
* @example ````Filter reject value:
```javascript
var defer = $.Deferred(),
filtered = defer.then( null, function( value ) {
return value * 3;
});
defer.reject( 6 );
filtered.fail(function( value ) {
alert( "Value is ( 3*6 = ) 18: " + value );
});
```
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.then(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
then<ARF = never, AJF = never, ANF = never,
BRF = never, BJF = never, BNF = never,
CRF = never, CJF = never, CNF = never,
RRF = never, RJF = never, RNF = never>(
doneFilter: null,
failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase<ARF, AJF, ANF,
BRF, BJF, BNF,
CRF, CJF, CNF,
RRF, RJF, RNF> | Thenable<ARF> | ARF,
progressFilter?: null): PromiseBase<ARF, AJF, ANF,
BRF, BJF, BNF,
CRF, CJF, CNF,
RRF, RJF, RNF>;
/**
* Add handlers to be called when the Deferred object is resolved, rejected, or still in progress.
* @param doneFilter An optional function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.then/ }\`
* @since 1.8
* @example ````Filter the resolve value:
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>deferred.then demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<button>Filter Resolve</button>
<p></p>
<script>
var filterResolve = function() {
var defer = $.Deferred(),
filtered = defer.then(function( value ) {
return value * 2;
});
defer.resolve( 5 );
filtered.done(function( value ) {
$( "p" ).html( "Value is ( 2*5 = ) 10: " + value );
});
};
$( "button" ).on( "click", filterResolve );
</script>
</body>
</html>
```
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.then(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
then<ARD = never, AJD = never, AND = never,
BRD = never, BJD = never, BND = never,
CRD = never, CJD = never, CND = never,
RRD = never, RJD = never, RND = never>(
doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase<ARD, AJD, AND,
BRD, BJD, BND,
CRD, CJD, CND,
RRD, RJD, RND> | Thenable<ARD> | ARD,
failFilter?: null,
progressFilter?: null): PromiseBase<ARD, AJD, AND,
BRD, BJD, BND,
CRD, CJD, CND,
RRD, RJD, RND>;
// #endregion
/**
* Add handlers to be called when the Deferred object is rejected.
* @param failFilter A function that is called when the Deferred is rejected.
* @see \`{@link https://api.jquery.com/deferred.catch/ }\`
* @since 3.0
* @example ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can rejection handlers using the .catch method.
```javascript
$.get( "test.php" )
.then( function() {
alert( "$.get succeeded" );
} )
.catch( function() {
alert( "$.get failed!" );
} );
```
*/
catch<ARF = never, AJF = never, ANF = never,
BRF = never, BJF = never, BNF = never,
CRF = never, CJF = never, CNF = never,
RRF = never, RJF = never, RNF = never>(
failFilter?: ((t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase<ARF, AJF, ANF,
BRF, BJF, BNF,
CRF, CJF, CNF,
RRF, RJF, RNF> | Thenable<ARF> | ARF) | null): PromiseBase<ARF, AJF, ANF,
BRF, BJF, BNF,
CRF, CJF, CNF,
RRF, RJF, RNF>;
}
/**
* This object provides a subset of the methods of the Deferred object (then, done, fail, always, pipe, progress, state and promise) to prevent users from changing the state of the Deferred.
* @see \`{@link https://api.jquery.com/Types/#Promise }\`
*/
interface Promise3<TR, TJ, TN,
UR, UJ, UN,
VR, VJ, VN> extends PromiseBase<TR, TJ, TN,
UR, UJ, UN,
VR, VJ, VN,
never, never, never> { }
/**
* This object provides a subset of the methods of the Deferred object (then, done, fail, always, pipe, progress, state and promise) to prevent users from changing the state of the Deferred.
* @see \`{@link https://api.jquery.com/Types/#Promise }\`
*/
interface Promise2<TR, TJ, TN,
UR, UJ, UN> extends PromiseBase<TR, TJ, TN,
UR, UJ, UN,
never, never, never,
never, never, never> { }
/**
* This object provides a subset of the methods of the Deferred object (then, done, fail, always, pipe, progress, state and promise) to prevent users from changing the state of the Deferred.
* @see \`{@link https://api.jquery.com/Types/#Promise }\`
*/
interface Promise<TR, TJ = any, TN = any> extends PromiseBase<TR, TJ, TN,
TR, TJ, TN,
TR, TJ, TN,
TR, TJ, TN> { }
interface DeferredStatic {
// https://jquery.com/upgrade-guide/3.0/#callback-exit
exceptionHook: any;
/**
* A factory function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.
* @param beforeStart A function that is called just before the constructor returns.
* @see \`{@link https://api.jquery.com/jQuery.Deferred/ }\`
* @since 1.5
*/
<TR = any, TJ = any, TN = any>(beforeStart?: (this: Deferred<TR, TJ, TN>, deferred: Deferred<TR, TJ, TN>) => void): Deferred<TR, TJ, TN>;
}
interface Deferred<TR, TJ = any, TN = any> {
/**
* Call the progressCallbacks on a Deferred object with the given args.
* @param args Optional arguments that are passed to the progressCallbacks.
* @see \`{@link https://api.jquery.com/deferred.notify/ }\`
* @since 1.7
*/
notify(...args: TN[]): this;
/**
* Call the progressCallbacks on a Deferred object with the given context and args.
* @param context Context passed to the progressCallbacks as the this object.
* @param args An optional array of arguments that are passed to the progressCallbacks.
* @see \`{@link https://api.jquery.com/deferred.notifyWith/ }\`
* @since 1.7
*/
notifyWith(context: object, args?: ArrayLike<TN>): this;
/**
* Reject a Deferred object and call any failCallbacks with the given args.
* @param args Optional arguments that are passed to the failCallbacks.
* @see \`{@link https://api.jquery.com/deferred.reject/ }\`
* @since 1.5
*/
reject(...args: TJ[]): this;
/**
* Reject a Deferred object and call any failCallbacks with the given context and args.
* @param context Context passed to the failCallbacks as the this object.
* @param args An optional array of arguments that are passed to the failCallbacks.
* @see \`{@link https://api.jquery.com/deferred.rejectWith/ }\`
* @since 1.5
*/
rejectWith(context: object, args?: ArrayLike<TJ>): this;
/**
* Resolve a Deferred object and call any doneCallbacks with the given args.
* @param args Optional arguments that are passed to the doneCallbacks.
* @see \`{@link https://api.jquery.com/deferred.resolve/ }\`
* @since 1.5
*/
resolve(...args: TR[]): this;
/**
* Resolve a Deferred object and call any doneCallbacks with the given context and args.
* @param context Context passed to the doneCallbacks as the this object.
* @param args An optional array of arguments that are passed to the doneCallbacks.
* @see \`{@link https://api.jquery.com/deferred.resolveWith/ }\`
* @since 1.5
*/
resolveWith(context: object, args?: ArrayLike<TR>): this;
/**
* Add handlers to be called when the Deferred object is either resolved or rejected.
* @param alwaysCallback A function, or array of functions, that is called when the Deferred is resolved or rejected.
* @param alwaysCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected.
* @see \`{@link https://api.jquery.com/deferred.always/ }\`
* @since 1.6
* @example ````Since the jQuery.get() method returns a jqXHR object, which is derived from a Deferred object, we can attach a callback for both success and error using the deferred.always() method.
```javascript
$.get( "test.php" ).always(function() {
alert( "$.get completed with success or error callback arguments" );
});
```
*/
always(alwaysCallback: TypeOrArray<Deferred.Callback<TR | TJ>>,
...alwaysCallbacks: Array<TypeOrArray<Deferred.Callback<TR | TJ>>>): this;
/**
* Add handlers to be called when the Deferred object is resolved.
* @param doneCallback A function, or array of functions, that are called when the Deferred is resolved.
* @param doneCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is resolved.
* @see \`{@link https://api.jquery.com/deferred.done/ }\`
* @since 1.5
* @example ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach a success callback using the .done() method.
```javascript
$.get( "test.php" ).done(function() {
alert( "$.get succeeded" );
});
```
* @example ````Resolve a Deferred object when the user clicks a button, triggering a number of callback functions:
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>deferred.done demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<button>Go</button>
<p>Ready...</p>
<script>
// 3 functions to call when the Deferred object is resolved
function fn1() {
$( "p" ).append( " 1 " );
}
function fn2() {
$( "p" ).append( " 2 " );
}
function fn3( n ) {
$( "p" ).append( n + " 3 " + n );
}
// Create a deferred object
var dfd = $.Deferred();
// Add handlers to be called when dfd is resolved
dfd
// .done() can take any number of functions or arrays of functions
.done( [ fn1, fn2 ], fn3, [ fn2, fn1 ] )
// We can chain done methods, too
.done(function( n ) {
$( "p" ).append( n + " we're done." );
});
// Resolve the Deferred object when the button is clicked
$( "button" ).on( "click", function() {
dfd.resolve( "and" );
});
</script>
</body>
</html>
```
*/
done(doneCallback: TypeOrArray<Deferred.Callback<TR>>,
...doneCallbacks: Array<TypeOrArray<Deferred.Callback<TR>>>): this;
/**
* Add handlers to be called when the Deferred object is rejected.
* @param failCallback A function, or array of functions, that are called when the Deferred is rejected.
* @param failCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is rejected.
* @see \`{@link https://api.jquery.com/deferred.fail/ }\`
* @since 1.5
* @example ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred, you can attach a success and failure callback using the deferred.done() and deferred.fail() methods.
```javascript
$.get( "test.php" )
.done(function() {
alert( "$.get succeeded" );
})
.fail(function() {
alert( "$.get failed!" );
});
```
*/
fail(failCallback: TypeOrArray<Deferred.Callback<TJ>>,
...failCallbacks: Array<TypeOrArray<Deferred.Callback<TJ>>>): this;
/**
* Add handlers to be called when the Deferred object generates progress notifications.
* @param progressCallback A function, or array of functions, to be called when the Deferred generates progress notifications.
* @param progressCallbacks Optional additional functions, or arrays of functions, to be called when the Deferred generates
* progress notifications.
* @see \`{@link https://api.jquery.com/deferred.progress/ }\`
* @since 1.7
*/
progress(progressCallback: TypeOrArray<Deferred.Callback<TN>>,
...progressCallbacks: Array<TypeOrArray<Deferred.Callback<TN>>>): this;
/**
* Return a Deferred's Promise object.
* @param target Object onto which the promise methods have to be attached
* @see \`{@link https://api.jquery.com/deferred.promise/ }\`
* @since 1.5
* @example ````Use the target argument to promote an existing object to a Promise:
```javascript
// Existing object
var obj = {
hello: function( name ) {
alert( "Hello " + name );
}
},
// Create a Deferred
defer = $.Deferred();
// Set object as a promise
defer.promise( obj );
// Resolve the deferred
defer.resolve( "John" );
// Use the object as a Promise
obj.done(function( name ) {
obj.hello( name ); // Will alert "Hello John"
}).hello( "Karl" ); // Will alert "Hello Karl"
```
*/
promise<TTarget extends object>(target: TTarget): Promise<TR, TJ, TN> & TTarget;
/**
* Return a Deferred's Promise object.
* @see \`{@link https://api.jquery.com/deferred.promise/ }\`
* @since 1.5
* @example ````Create a Deferred and set two timer-based functions to either resolve or reject the Deferred after a random interval. Whichever one fires first "wins" and will call one of the callbacks. The second timeout has no effect since the Deferred is already complete (in a resolved or rejected state) from the first timeout action. Also set a timer-based progress notification function, and call a progress handler that adds "working..." to the document body.
```javascript
function asyncEvent() {
var dfd = jQuery.Deferred();
// Resolve after a random interval
setTimeout(function() {
dfd.resolve( "hurray" );
}, Math.floor( 400 + Math.random() * 2000 ) );
// Reject after a random interval
setTimeout(function() {
dfd.reject( "sorry" );
}, Math.floor( 400 + Math.random() * 2000 ) );
// Show a "working..." message every half-second
setTimeout(function working() {
if ( dfd.state() === "pending" ) {
dfd.notify( "working... " );
setTimeout( working, 500 );
}
}, 1 );
// Return the Promise so caller can't change the Deferred
return dfd.promise();
}
// Attach a done, fail, and progress handler for the asyncEvent
$.when( asyncEvent() ).then(
function( status ) {
alert( status + ", things are going well" );
},
function( status ) {
alert( status + ", you fail this time" );
},
function( status ) {
$( "body" ).append( status );
}
);
```
*/
promise(): Promise<TR, TJ, TN>;
/**
* Determine the current state of a Deferred object.
* @see \`{@link https://api.jquery.com/deferred.state/ }\`
* @since 1.7
*/
state(): 'pending' | 'resolved' | 'rejected';
// region pipe
// #region pipe
/**
* Utility method to filter and/or chain Deferreds.
* @param doneFilter An optional function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.pipe/ }\`
* @since 1.6
* @since 1.7
* @deprecated Deprecated since 1.8. Use \`{@link then }\`.
*
* **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function.
*
* **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0.
* @example ````Filter resolve value:
```javascript
var defer = $.Deferred(),
filtered = defer.pipe(function( value ) {
return value * 2;
});
defer.resolve( 5 );
filtered.done(function( value ) {
alert( "Value is ( 2*5 = ) 10: " + value );
});
```
* @example ````Filter reject value:
```javascript
var defer = $.Deferred(),
filtered = defer.pipe( null, function( value ) {
return value * 3;
});
defer.reject( 6 );
filtered.fail(function( value ) {
alert( "Value is ( 3*6 = ) 18: " + value );
});
```
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.pipe(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
pipe<ARD = never, AJD = never, AND = never,
BRD = never, BJD = never, BND = never,
CRD = never, CJD = never, CND = never,
RRD = never, RJD = never, RND = never,
ARF = never, AJF = never, ANF = never,
BRF = never, BJF = never, BNF = never,
CRF = never, CJF = never, CNF = never,
RRF = never, RJF = never, RNF = never,
ARP = never, AJP = never, ANP = never,
BRP = never, BJP = never, BNP = never,
CRP = never, CJP = never, CNP = never,
RRP = never, RJP = never, RNP = never>(
doneFilter: (...t: TR[]) => PromiseBase<ARD, AJD, AND,
BRD, BJD, BND,
CRD, CJD, CND,
RRD, RJD, RND> | Thenable<ARD> | ARD,
failFilter: (...t: TJ[]) => PromiseBase<ARF, AJF, ANF,
BRF, BJF, BNF,
CRF, CJF, CNF,
RRF, RJF, RNF> | Thenable<AJF> | AJF,
progressFilter: (...t: TN[]) => PromiseBase<ARP, AJP, ANP,
BRP, BJP, BNP,
CRP, CJP, CNP,
RRP, RJP, RNP> | Thenable<ANP> | ANP): PromiseBase<ARD | ARF | ARP, AJD | AJF | AJP, AND | ANF | ANP,
BRD | BRF | BRP, BJD | BJF | BJP, BND | BNF | BNP,
CRD | CRF | CRP, CJD | CJF | CJP, CND | CNF | CNP,
RRD | RRF | RRP, RJD | RJF | RJP, RND | RNF | RNP>;
/**
* Utility method to filter and/or chain Deferreds.
* @param doneFilter An optional function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.pipe/ }\`
* @since 1.6
* @since 1.7
* @deprecated Deprecated since 1.8. Use \`{@link then }\`.
*
* **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function.
*
* **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0.
* @example ````Filter reject value:
```javascript
var defer = $.Deferred(),
filtered = defer.pipe( null, function( value ) {
return value * 3;
});
defer.reject( 6 );
filtered.fail(function( value ) {
alert( "Value is ( 3*6 = ) 18: " + value );
});
```
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.pipe(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
pipe<ARF = never, AJF = never, ANF = never,
BRF = never, BJF = never, BNF = never,
CRF = never, CJF = never, CNF = never,
RRF = never, RJF = never, RNF = never,
ARP = never, AJP = never, ANP = never,
BRP = never, BJP = never, BNP = never,
CRP = never, CJP = never, CNP = never,
RRP = never, RJP = never, RNP = never>(
doneFilter: null,
failFilter: (...t: TJ[]) => PromiseBase<ARF, AJF, ANF,
BRF, BJF, BNF,
CRF, CJF, CNF,
RRF, RJF, RNF> | Thenable<AJF> | AJF,
progressFilter: (...t: TN[]) => PromiseBase<ARP, AJP, ANP,
BRP, BJP, BNP,
CRP, CJP, CNP,
RRP, RJP, RNP> | Thenable<ANP> | ANP): PromiseBase<ARF | ARP, AJF | AJP, ANF | ANP,
BRF | BRP, BJF | BJP, BNF | BNP,
CRF | CRP, CJF | CJP, CNF | CNP,
RRF | RRP, RJF | RJP, RNF | RNP>;
/**
* Utility method to filter and/or chain Deferreds.
* @param doneFilter An optional function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.pipe/ }\`
* @since 1.6
* @since 1.7
* @deprecated Deprecated since 1.8. Use \`{@link then }\`.
*
* **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function.
*
* **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0.
* @example ````Filter resolve value:
```javascript
var defer = $.Deferred(),
filtered = defer.pipe(function( value ) {
return value * 2;
});
defer.resolve( 5 );
filtered.done(function( value ) {
alert( "Value is ( 2*5 = ) 10: " + value );
});
```
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.pipe(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
pipe<ARD = never, AJD = never, AND = never,
BRD = never, BJD = never, BND = never,
CRD = never, CJD = never, CND = never,
RRD = never, RJD = never, RND = never,
ARP = never, AJP = never, ANP = never,
BRP = never, BJP = never, BNP = never,
CRP = never, CJP = never, CNP = never,
RRP = never, RJP = never, RNP = never>(
doneFilter: (...t: TR[]) => PromiseBase<ARD, AJD, AND,
BRD, BJD, BND,
CRD, CJD, CND,
RRD, RJD, RND> | Thenable<ARD> | ARD,
failFilter: null,
progressFilter: (...t: TN[]) => PromiseBase<ARP, AJP, ANP,
BRP, BJP, BNP,
CRP, CJP, CNP,
RRP, RJP, RNP> | Thenable<ANP> | ANP): PromiseBase<ARD | ARP, AJD | AJP, AND | ANP,
BRD | BRP, BJD | BJP, BND | BNP,
CRD | CRP, CJD | CJP, CND | CNP,
RRD | RRP, RJD | RJP, RND | RNP>;
/**
* Utility method to filter and/or chain Deferreds.
* @param doneFilter An optional function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.pipe/ }\`
* @since 1.6
* @since 1.7
* @deprecated Deprecated since 1.8. Use \`{@link then }\`.
*
* **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function.
*
* **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0.
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.pipe(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
pipe<ARP = never, AJP = never, ANP = never,
BRP = never, BJP = never, BNP = never,
CRP = never, CJP = never, CNP = never,
RRP = never, RJP = never, RNP = never>(
doneFilter: null,
failFilter: null,
progressFilter?: (...t: TN[]) => PromiseBase<ARP, AJP, ANP,
BRP, BJP, BNP,
CRP, CJP, CNP,
RRP, RJP, RNP> | Thenable<ANP> | ANP): PromiseBase<ARP, AJP, ANP,
BRP, BJP, BNP,
CRP, CJP, CNP,
RRP, RJP, RNP>;
/**
* Utility method to filter and/or chain Deferreds.
* @param doneFilter An optional function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.pipe/ }\`
* @since 1.6
* @since 1.7
* @deprecated Deprecated since 1.8. Use \`{@link then }\`.
*
* **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function.
*
* **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0.
* @example ````Filter resolve value:
```javascript
var defer = $.Deferred(),
filtered = defer.pipe(function( value ) {
return value * 2;
});
defer.resolve( 5 );
filtered.done(function( value ) {
alert( "Value is ( 2*5 = ) 10: " + value );
});
```
* @example ````Filter reject value:
```javascript
var defer = $.Deferred(),
filtered = defer.pipe( null, function( value ) {
return value * 3;
});
defer.reject( 6 );
filtered.fail(function( value ) {
alert( "Value is ( 3*6 = ) 18: " + value );
});
```
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.pipe(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
pipe<ARD = never, AJD = never, AND = never,
BRD = never, BJD = never, BND = never,
CRD = never, CJD = never, CND = never,
RRD = never, RJD = never, RND = never,
ARF = never, AJF = never, ANF = never,
BRF = never, BJF = never, BNF = never,
CRF = never, CJF = never, CNF = never,
RRF = never, RJF = never, RNF = never>(
doneFilter: (...t: TR[]) => PromiseBase<ARD, AJD, AND,
BRD, BJD, BND,
CRD, CJD, CND,
RRD, RJD, RND> | Thenable<ARD> | ARD,
failFilter: (...t: TJ[]) => PromiseBase<ARF, AJF, ANF,
BRF, BJF, BNF,
CRF, CJF, CNF,
RRF, RJF, RNF> | Thenable<AJF> | AJF,
progressFilter?: null): PromiseBase<ARD | ARF, AJD | AJF, AND | ANF,
BRD | BRF, BJD | BJF, BND | BNF,
CRD | CRF, CJD | CJF, CND | CNF,
RRD | RRF, RJD | RJF, RND | RNF>;
/**
* Utility method to filter and/or chain Deferreds.
* @param doneFilter An optional function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.pipe/ }\`
* @since 1.6
* @since 1.7
* @deprecated Deprecated since 1.8. Use \`{@link then }\`.
*
* **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function.
*
* **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0.
* @example ````Filter reject value:
```javascript
var defer = $.Deferred(),
filtered = defer.pipe( null, function( value ) {
return value * 3;
});
defer.reject( 6 );
filtered.fail(function( value ) {
alert( "Value is ( 3*6 = ) 18: " + value );
});
```
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.pipe(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
pipe<ARF = never, AJF = never, ANF = never,
BRF = never, BJF = never, BNF = never,
CRF = never, CJF = never, CNF = never,
RRF = never, RJF = never, RNF = never>(
doneFilter: null,
failFilter: (...t: TJ[]) => PromiseBase<ARF, AJF, ANF,
BRF, BJF, BNF,
CRF, CJF, CNF,
RRF, RJF, RNF> | Thenable<AJF> | AJF,
progressFilter?: null): PromiseBase<ARF, AJF, ANF,
BRF, BJF, BNF,
CRF, CJF, CNF,
RRF, RJF, RNF>;
/**
* Utility method to filter and/or chain Deferreds.
* @param doneFilter An optional function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.pipe/ }\`
* @since 1.6
* @since 1.7
* @deprecated Deprecated since 1.8. Use \`{@link then }\`.
*
* **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function.
*
* **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0.
* @example ````Filter resolve value:
```javascript
var defer = $.Deferred(),
filtered = defer.pipe(function( value ) {
return value * 2;
});
defer.resolve( 5 );
filtered.done(function( value ) {
alert( "Value is ( 2*5 = ) 10: " + value );
});
```
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.pipe(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
pipe<ARD = never, AJD = never, AND = never,
BRD = never, BJD = never, BND = never,
CRD = never, CJD = never, CND = never,
RRD = never, RJD = never, RND = never>(
doneFilter: (...t: TR[]) => PromiseBase<ARD, AJD, AND,
BRD, BJD, BND,
CRD, CJD, CND,
RRD, RJD, RND> | Thenable<ARD> | ARD,
failFilter?: null,
progressFilter?: null): PromiseBase<ARD, AJD, AND,
BRD, BJD, BND,
CRD, CJD, CND,
RRD, RJD, RND>;
// #endregion
// region then
// #region then
/**
* Add handlers to be called when the Deferred object is resolved, rejected, or still in progress.
* @param doneFilter A function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.then/ }\`
* @since 1.8
* @example ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach handlers using the .then method.
```javascript
$.get( "test.php" ).then(
function() {
alert( "$.get succeeded" );
}, function() {
alert( "$.get failed!" );
}
);
```
* @example ````Filter the resolve value:
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>deferred.then demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<button>Filter Resolve</button>
<p></p>
<script>
var filterResolve = function() {
var defer = $.Deferred(),
filtered = defer.then(function( value ) {
return value * 2;
});
defer.resolve( 5 );
filtered.done(function( value ) {
$( "p" ).html( "Value is ( 2*5 = ) 10: " + value );
});
};
$( "button" ).on( "click", filterResolve );
</script>
</body>
</html>
```
* @example ````Filter reject value:
```javascript
var defer = $.Deferred(),
filtered = defer.then( null, function( value ) {
return value * 3;
});
defer.reject( 6 );
filtered.fail(function( value ) {
alert( "Value is ( 3*6 = ) 18: " + value );
});
```
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.then(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
then<ARD = never, AJD = never, AND = never,
BRD = never, BJD = never, BND = never,
CRD = never, CJD = never, CND = never,
RRD = never, RJD = never, RND = never,
ARF = never, AJF = never, ANF = never,
BRF = never, BJF = never, BNF = never,
CRF = never, CJF = never, CNF = never,
RRF = never, RJF = never, RNF = never,
ARP = never, AJP = never, ANP = never,
BRP = never, BJP = never, BNP = never,
CRP = never, CJP = never, CNP = never,
RRP = never, RJP = never, RNP = never>(
doneFilter: (...t: TR[]) => PromiseBase<ARD, AJD, AND,
BRD, BJD, BND,
CRD, CJD, CND,
RRD, RJD, RND> | Thenable<ARD> | ARD,
failFilter: (...t: TJ[]) => PromiseBase<ARF, AJF, ANF,
BRF, BJF, BNF,
CRF, CJF, CNF,
RRF, RJF, RNF> | Thenable<ARF> | ARF,
progressFilter: (...t: TN[]) => PromiseBase<ARP, AJP, ANP,
BRP, BJP, BNP,
CRP, CJP, CNP,
RRP, RJP, RNP> | Thenable<ANP> | ANP): PromiseBase<ARD | ARF | ARP, AJD | AJF | AJP, AND | ANF | ANP,
BRD | BRF | BRP, BJD | BJF | BJP, BND | BNF | BNP,
CRD | CRF | CRP, CJD | CJF | CJP, CND | CNF | CNP,
RRD | RRF | RRP, RJD | RJF | RJP, RND | RNF | RNP>;
/**
* Add handlers to be called when the Deferred object is resolved, rejected, or still in progress.
* @param doneFilter A function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.then/ }\`
* @since 1.8
* @example ````Filter reject value:
```javascript
var defer = $.Deferred(),
filtered = defer.then( null, function( value ) {
return value * 3;
});
defer.reject( 6 );
filtered.fail(function( value ) {
alert( "Value is ( 3*6 = ) 18: " + value );
});
```
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.then(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
then<ARF = never, AJF = never, ANF = never,
BRF = never, BJF = never, BNF = never,
CRF = never, CJF = never, CNF = never,
RRF = never, RJF = never, RNF = never,
ARP = never, AJP = never, ANP = never,
BRP = never, BJP = never, BNP = never,
CRP = never, CJP = never, CNP = never,
RRP = never, RJP = never, RNP = never>(
doneFilter: null,
failFilter: (...t: TJ[]) => PromiseBase<ARF, AJF, ANF,
BRF, BJF, BNF,
CRF, CJF, CNF,
RRF, RJF, RNF> | Thenable<ARF> | ARF,
progressFilter: (...t: TN[]) => PromiseBase<ARP, AJP, ANP,
BRP, BJP, BNP,
CRP, CJP, CNP,
RRP, RJP, RNP> | Thenable<ANP> | ANP): PromiseBase<ARF | ARP, AJF | AJP, ANF | ANP,
BRF | BRP, BJF | BJP, BNF | BNP,
CRF | CRP, CJF | CJP, CNF | CNP,
RRF | RRP, RJF | RJP, RNF | RNP>;
/**
* Add handlers to be called when the Deferred object is resolved, rejected, or still in progress.
* @param doneFilter A function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.then/ }\`
* @since 1.8
* @example ````Filter the resolve value:
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>deferred.then demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<button>Filter Resolve</button>
<p></p>
<script>
var filterResolve = function() {
var defer = $.Deferred(),
filtered = defer.then(function( value ) {
return value * 2;
});
defer.resolve( 5 );
filtered.done(function( value ) {
$( "p" ).html( "Value is ( 2*5 = ) 10: " + value );
});
};
$( "button" ).on( "click", filterResolve );
</script>
</body>
</html>
```
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.then(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
then<ARD = never, AJD = never, AND = never,
BRD = never, BJD = never, BND = never,
CRD = never, CJD = never, CND = never,
RRD = never, RJD = never, RND = never,
ARP = never, AJP = never, ANP = never,
BRP = never, BJP = never, BNP = never,
CRP = never, CJP = never, CNP = never,
RRP = never, RJP = never, RNP = never>(
doneFilter: (...t: TR[]) => PromiseBase<ARD, AJD, AND,
BRD, BJD, BND,
CRD, CJD, CND,
RRD, RJD, RND> | Thenable<ARD> | ARD,
failFilter: null,
progressFilter: (...t: TN[]) => PromiseBase<ARP, AJP, ANP,
BRP, BJP, BNP,
CRP, CJP, CNP,
RRP, RJP, RNP> | Thenable<ANP> | ANP): PromiseBase<ARD | ARP, AJD | AJP, AND | ANP,
BRD | BRP, BJD | BJP, BND | BNP,
CRD | CRP, CJD | CJP, CND | CNP,
RRD | RRP, RJD | RJP, RND | RNP>;
/**
* Add handlers to be called when the Deferred object is resolved, rejected, or still in progress.
* @param doneFilter A function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.then/ }\`
* @since 1.8
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.then(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
then<ARP = never, AJP = never, ANP = never,
BRP = never, BJP = never, BNP = never,
CRP = never, CJP = never, CNP = never,
RRP = never, RJP = never, RNP = never>(
doneFilter: null,
failFilter: null,
progressFilter?: (...t: TN[]) => PromiseBase<ARP, AJP, ANP,
BRP, BJP, BNP,
CRP, CJP, CNP,
RRP, RJP, RNP> | Thenable<ANP> | ANP): PromiseBase<ARP, AJP, ANP,
BRP, BJP, BNP,
CRP, CJP, CNP,
RRP, RJP, RNP>;
/**
* Add handlers to be called when the Deferred object is resolved, rejected, or still in progress.
* @param doneFilter An optional function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.then/ }\`
* @since 1.8
* @example ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach handlers using the .then method.
```javascript
$.get( "test.php" ).then(
function() {
alert( "$.get succeeded" );
}, function() {
alert( "$.get failed!" );
}
);
```
* @example ````Filter the resolve value:
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>deferred.then demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<button>Filter Resolve</button>
<p></p>
<script>
var filterResolve = function() {
var defer = $.Deferred(),
filtered = defer.then(function( value ) {
return value * 2;
});
defer.resolve( 5 );
filtered.done(function( value ) {
$( "p" ).html( "Value is ( 2*5 = ) 10: " + value );
});
};
$( "button" ).on( "click", filterResolve );
</script>
</body>
</html>
```
* @example ````Filter reject value:
```javascript
var defer = $.Deferred(),
filtered = defer.then( null, function( value ) {
return value * 3;
});
defer.reject( 6 );
filtered.fail(function( value ) {
alert( "Value is ( 3*6 = ) 18: " + value );
});
```
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.then(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
then<ARD = never, AJD = never, AND = never,
BRD = never, BJD = never, BND = never,
CRD = never, CJD = never, CND = never,
RRD = never, RJD = never, RND = never,
ARF = never, AJF = never, ANF = never,
BRF = never, BJF = never, BNF = never,
CRF = never, CJF = never, CNF = never,
RRF = never, RJF = never, RNF = never>(
doneFilter: (...t: TR[]) => PromiseBase<ARD, AJD, AND,
BRD, BJD, BND,
CRD, CJD, CND,
RRD, RJD, RND> | Thenable<ARD> | ARD,
failFilter: (...t: TJ[]) => PromiseBase<ARF, AJF, ANF,
BRF, BJF, BNF,
CRF, CJF, CNF,
RRF, RJF, RNF> | Thenable<ARF> | ARF,
progressFilter?: null): PromiseBase<ARD | ARF, AJD | AJF, AND | ANF,
BRD | BRF, BJD | BJF, BND | BNF,
CRD | CRF, CJD | CJF, CND | CNF,
RRD | RRF, RJD | RJF, RND | RNF>;
/**
* Add handlers to be called when the Deferred object is resolved, rejected, or still in progress.
* @param doneFilter An optional function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.then/ }\`
* @since 1.8
* @example ````Filter reject value:
```javascript
var defer = $.Deferred(),
filtered = defer.then( null, function( value ) {
return value * 3;
});
defer.reject( 6 );
filtered.fail(function( value ) {
alert( "Value is ( 3*6 = ) 18: " + value );
});
```
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.then(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
then<ARF = never, AJF = never, ANF = never,
BRF = never, BJF = never, BNF = never,
CRF = never, CJF = never, CNF = never,
RRF = never, RJF = never, RNF = never>(
doneFilter: null,
failFilter: (...t: TJ[]) => PromiseBase<ARF, AJF, ANF,
BRF, BJF, BNF,
CRF, CJF, CNF,
RRF, RJF, RNF> | Thenable<ARF> | ARF,
progressFilter?: null): PromiseBase<ARF, AJF, ANF,
BRF, BJF, BNF,
CRF, CJF, CNF,
RRF, RJF, RNF>;
/**
* Add handlers to be called when the Deferred object is resolved, rejected, or still in progress.
* @param doneFilter An optional function that is called when the Deferred is resolved.
* @param failFilter An optional function that is called when the Deferred is rejected.
* @param progressFilter An optional function that is called when progress notifications are sent to the Deferred.
* @see \`{@link https://api.jquery.com/deferred.then/ }\`
* @since 1.8
* @example ````Filter the resolve value:
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>deferred.then demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<button>Filter Resolve</button>
<p></p>
<script>
var filterResolve = function() {
var defer = $.Deferred(),
filtered = defer.then(function( value ) {
return value * 2;
});
defer.resolve( 5 );
filtered.done(function( value ) {
$( "p" ).html( "Value is ( 2*5 = ) 10: " + value );
});
};
$( "button" ).on( "click", filterResolve );
</script>
</body>
</html>
```
* @example ````Chain tasks:
```javascript
var request = $.ajax( url, { dataType: "json" } ),
chained = request.then(function( data ) {
return $.ajax( url2, { data: { user: data.userId } } );
});
chained.done(function( data ) {
// data retrieved from url2 as provided by the first request
});
```
*/
then<ARD = never, AJD = never, AND = never,
BRD = never, BJD = never, BND = never,
CRD = never, CJD = never, CND = never,
RRD = never, RJD = never, RND = never>(
doneFilter: (...t: TR[]) => PromiseBase<ARD, AJD, AND,
BRD, BJD, BND,
CRD, CJD, CND,
RRD, RJD, RND> | Thenable<ARD> | ARD,
failFilter?: null,
progressFilter?: null): PromiseBase<ARD, AJD, AND,
BRD, BJD, BND,
CRD, CJD, CND,
RRD, RJD, RND>;
// #endregion
/**
* Add handlers to be called when the Deferred object is rejected.
* @param failFilter A function that is called when the Deferred is rejected.
* @see \`{@link https://api.jquery.com/deferred.catch/ }\`
* @since 3.0
* @example ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can rejection handlers using the .catch method.
```javascript
$.get( "test.php" )
.then( function() {
alert( "$.get succeeded" );
} )
.catch( function() {
alert( "$.get failed!" );
} );
```
*/
catch<ARF = never, AJF = never, ANF = never,
BRF = never, BJF = never, BNF = never,
CRF = never, CJF = never, CNF = never,
RRF = never, RJF = never, RNF = never>(
failFilter?: ((...t: TJ[]) => PromiseBase<ARF, AJF, ANF,
BRF, BJF, BNF,
CRF, CJF, CNF,
RRF, RJF, RNF> | Thenable<ARF> | ARF) | null): PromiseBase<ARF, AJF, ANF,
BRF, BJF, BNF,
CRF, CJF, CNF,
RRF, RJF, RNF>;
}
namespace Deferred {
type CallbackBase<T, U, V, R> = (t: T, u: U, v: V, ...r: R[]) => void;
interface Callback3<T, U, V> extends CallbackBase<T, U, V, never> { }
type Callback<T> = (...args: T[]) => void;
/**
* @deprecated Deprecated. Use \`{@link Callback }\`.
*/
interface DoneCallback<TResolve> extends Callback<TResolve> { }
/**
* @deprecated Deprecated. Use \`{@link Callback }\`.
*/
interface FailCallback<TReject> extends Callback<TReject> { }
/**
* @deprecated Deprecated. Use \`{@link Callback }\`.
*/
interface AlwaysCallback<TResolve, TReject> extends Callback<TResolve | TReject> { }
/**
* @deprecated Deprecated. Use \`{@link Callback }\`.
*/
interface ProgressCallback<TNotify> extends Callback<TNotify> { }
}
// #endregion
// region Effects
// #region Effects
type Duration = number | 'fast' | 'slow';
/**
* @see \`{@link https://api.jquery.com/animate/#animate-properties-options }\`
*/
interface EffectsOptions<TElement> extends PlainObject {
/**
* A function to be called when the animation on an element completes or stops without completing (its Promise object is either resolved or rejected).
*/
always?(this: TElement, animation: Animation<TElement>, jumpedToEnd: boolean): void;
/**
* A function that is called once the animation on an element is complete.
*/
complete?(this: TElement): void;
/**
* A function to be called when the animation on an element completes (its Promise object is resolved).
*/
done?(this: TElement, animation: Animation<TElement>, jumpedToEnd: boolean): void;
/**
* A string or number determining how long the animation will run.
*/
duration?: Duration | undefined;
/**
* A string indicating which easing function to use for the transition.
*/
easing?: string | undefined;
/**
* A function to be called when the animation on an element fails to complete (its Promise object is rejected).
*/
fail?(this: TElement, animation: Animation<TElement>, jumpedToEnd: boolean): void;
/**
* A function to be called after each step of the animation, only once per animated element regardless of the number of animated properties.
*/
progress?(this: TElement, animation: Animation<TElement>, progress: number, remainingMs: number): void;
/**
* A Boolean indicating whether to place the animation in the effects queue. If false, the animation will begin immediately. As of jQuery 1.7, the queue option can also accept a string, in which case the animation is added to the queue represented by that string. When a custom queue name is used the animation does not automatically start; you must call .dequeue("queuename") to start it.
*/
queue?: boolean | string | undefined;
/**
* An object containing one or more of the CSS properties defined by the properties argument and their corresponding easing functions.
*/
specialEasing?: PlainObject<string> | undefined;
/**
* A function to call when the animation on an element begins.
*/
start?(this: TElement, animation: Animation<TElement>): void;
/**
* A function to be called for each animated property of each animated element. This function provides an opportunity to modify the Tween object to change the value of the property before it is set.
*/
step?(this: TElement, now: number, tween: Tween<TElement>): void;
}
// region Animation
// #region Animation
/**
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\`
* @since 1.8
*/
interface AnimationStatic {
/**
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\`
* @since 1.8
*/
<TElement>(element: TElement, props: PlainObject, opts: EffectsOptions<TElement>): Animation<TElement>;
/**
* During the initial setup, `jQuery.Animation` will call any callbacks that have been registered through `jQuery.Animation.prefilter( function( element, props, opts ) )`.
* @param callback The prefilter will have `this` set to an animation object, and you can modify any of the `props` or
* `opts` however you need. The prefilter _may_ return its own promise which also implements `stop()`,
* in which case, processing of prefilters stops. If the prefilter is not trying to override the animation
* entirely, it should return `undefined` or some other falsy value.
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#prefilters }\`
* @since 1.8
*/
prefilter<TElement>(
callback: (this: Animation<TElement>, element: TElement, props: PlainObject, opts: EffectsOptions<TElement>) => Animation<TElement> | _Falsy | void,
prepend?: boolean
): void;
/**
* A "Tweener" is a function responsible for creating a tween object, and you might want to override these if you want to implement complex values ( like a clip/transform array matrix ) in a single property.
*
* You can override the default process for creating a tween in order to provide your own tween object by using `jQuery.Animation.tweener( props, callback( prop, value ) )`.
* @param props A space separated list of properties to be passed to your tweener, or `"*"` if it should be called
* for all properties.
* @param callback The callback will be called with `this` being an `Animation` object. The tweener function will
* generally start with `var tween = this.createTween( prop, value );`, but doesn't nessecarily need to
* use the `jQuery.Tween()` factory.
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweeners }\`
* @since 1.8
*/
tweener(props: string, callback: Tweener<any>): void;
}
/**
* The promise will be resolved when the animation reaches its end, and rejected when terminated early. The context of callbacks attached to the promise will be the element, and the arguments will be the `Animation` object and a boolean `jumpedToEnd` which when true means the animation was stopped with `gotoEnd`, when `undefined` the animation completed naturally.
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\`
* @since 1.8
*/
interface Animation<TElement> extends Promise3<
Animation<TElement>, Animation<TElement>, Animation<TElement>,
true | undefined, false, number,
never, never, number
> {
/**
* The duration specified in ms
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\`
* @since 1.8
*/
duration: number;
/**
* The element being animatied
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\`
* @since 1.8
*/
elem: TElement;
/**
* The final value of each property animating
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\`
* @since 1.8
*/
props: PlainObject;
/**
* The animation options
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\`
* @since 1.8
*/
opts: EffectsOptions<TElement>;
/**
* The original properties before being filtered
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\`
* @since 1.8
*/
originalProps: PlainObject;
/**
* The original options before being filtered
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\`
* @since 1.8
*/
originalOpts: EffectsOptions<TElement>;
/**
* The numeric value of `new Date()` when the animation began
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\`
* @since 1.8
*/
startTime: number;
/**
* The animations tweens.
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\`
* @since 1.8
*/
tweens: Array<Tween<TElement>>;
/**
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\`
* @since 1.8
*/
createTween(propName: string, finalValue: number): Tween<TElement>;
/**
* Stops the animation early, optionally going to the end.
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\`
* @since 1.8
*/
stop(gotoEnd: boolean): this;
}
/**
* A "Tweener" is a function responsible for creating a tween object, and you might want to override these if you want to implement complex values ( like a clip/transform array matrix ) in a single property.
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweeners }\`
* @since 1.8
*/
type Tweener<TElement> = (this: Animation<TElement>, propName: string, finalValue: number) => Tween<TElement>;
/**
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\`
* @since 1.8
*/
interface TweenStatic {
/**
* `jQuery.Tween.propHooks[ prop ]` is a hook point that replaces `jQuery.fx.step[ prop ]` (which is being deprecated.) These hooks are used by the tween to get and set values on elements.
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tween-hooks }\`
* @since 1.8
* @example
```javascript
jQuery.Tween.propHooks[ property ] = {
get: function( tween ) {
// get tween.prop from tween.elem and return it
},
set: function( tween ) {
// set tween.prop on tween.elem to tween.now + tween.unit
}
}
```
*/
propHooks: PropHooks;
/**
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\`
* @since 1.8
*/
<TElement>(elem: TElement, options: EffectsOptions<TElement>, prop: string, end: number, easing?: string, unit?: string): Tween<TElement>;
}
/**
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\`
* @since 1.8
*/
// This should be a class but doesn't work correctly under the JQuery namespace. Tween should be an inner class of jQuery.
interface Tween<TElement> {
/**
* The easing used
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\`
* @since 1.8
*/
easing: string;
/**
* The element being animated
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\`
* @since 1.8
*/
elem: TElement;
/**
* The ending value of the tween
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\`
* @since 1.8
*/
end: number;
/**
* The current value of the tween
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\`
* @since 1.8
*/
now: number;
/**
* A reference to the animation options
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\`
* @since 1.8
*/
options: EffectsOptions<TElement>;
// Undocumented. Is this intended to be public?
pos?: number | undefined;
/**
* The property being animated
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\`
* @since 1.8
*/
prop: string;
/**
* The starting value of the tween
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\`
* @since 1.8
*/
start: number;
/**
* The CSS unit for the tween
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\`
* @since 1.8
*/
unit: string;
/**
* Reads the current value for property from the element
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\`
* @since 1.8
*/
cur(): any;
/**
* Updates the value for the property on the animated elemd.
* @param progress A number from 0 to 1.
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\`
* @since 1.8
*/
run(progress: number): this;
}
/**
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tween-hooks }\`
* @since 1.8
*/
// Workaround for TypeScript 2.3 which does not have support for weak types handling.
type PropHook<TElement> = {
/**
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tween-hooks }\`
* @since 1.8
*/
get(tween: Tween<TElement>): any;
} | {
/**
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tween-hooks }\`
* @since 1.8
*/
set(tween: Tween<TElement>): void;
} | {
[key: string]: never;
};
/**
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tween-hooks }\`
* @since 1.8
*/
interface PropHooks {
[property: string]: PropHook<Node>;
}
// #endregion
// region Easing
// #region Easing
type EasingMethod = (percent: number) => number;
interface Easings {
[name: string]: EasingMethod;
}
// #endregion
// region Effects (fx)
// #region Effects (fx)
interface Effects {
/**
* The rate (in milliseconds) at which animations fire.
* @see \`{@link https://api.jquery.com/jQuery.fx.interval/ }\`
* @since 1.4.3
* @deprecated Deprecated since 3.0. See \`{@link https://api.jquery.com/jQuery.fx.interval/ }\`.
*
* **Cause**: As of jQuery 3.0 the `jQuery.fx.interval` property can be used to change the animation interval only on browsers that do not support the `window.requestAnimationFrame()` method. That is currently only Internet Explorer 9 and the Android Browser. Once support is dropped for these browsers, the property will serve no purpose and it will be removed.
*
* **Solution**: Find and remove code that changes or uses `jQuery.fx.interval`. If the value is being used by code in your page or a plugin, the code may be making assumptions that are no longer valid. The default value of `jQuery.fx.interval` is `13` (milliseconds), which could be used instead of accessing this property.
* @example ````Cause all animations to run with less frames.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.fx.interval demo</title>
<style>
div {
width: 50px;
height: 30px;
margin: 5px;
float: left;
background: green;
}
</style>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<p><input type="button" value="Run"></p>
<div></div>
<script>
jQuery.fx.interval = 100;
$( "input" ).click(function() {
$( "div" ).toggle( 3000 );
});
</script>
</body>
</html>
```
*/
interval: number;
/**
* Globally disable all animations.
* @see \`{@link https://api.jquery.com/jQuery.fx.off/ }\`
* @since 1.3
* @example ````Toggle animation on and off
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.fx.off demo</title>
<style>
div {
width: 50px;
height: 30px;
margin: 5px;
float: left;
background: green;
}
</style>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<input type="button" value="Run">
<button>Toggle fx</button>
<div></div>
<script>
var toggleFx = function() {
$.fx.off = !$.fx.off;
};
toggleFx();
$( "button" ).click( toggleFx );
$( "input" ).click(function() {
$( "div" ).toggle( "slow" );
});
</script>
</body>
</html>
```
*/
off: boolean;
/**
* @deprecated Deprecated since 1.8. Use \`{@link Tween.propHooks jQuery.Tween.propHooks}\`.
*
* `jQuery.fx.step` functions are being replaced by `jQuery.Tween.propHooks` and may eventually be removed, but are still supported via the default tween propHook.
*/
step: PlainObject<AnimationHook<Node>>;
/**
* _overridable_ Clears up the `setInterval`
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#plugging-in-a-different-timer-loop }\`
* @since 1.8
*/
stop(): void;
/**
* Calls `.run()` on each object in the `jQuery.timers` array, removing it from the array if `.run()` returns a falsy value. Calls `jQuery.fx.stop()` whenever there are no timers remaining.
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#plugging-in-a-different-timer-loop }\`
* @since 1.8
*/
tick(): void;
/**
* _overridable_ Creates a `setInterval` if one doesn't already exist, and pushes `tickFunction` to the `jQuery.timers` array. `tickFunction` should also have `anim`, `elem`, and `queue` properties that reference the animation object, animated element, and queue option to facilitate `jQuery.fn.stop()`
*
* By overriding `fx.timer` and `fx.stop` you should be able to implement any animation tick behaviour you desire. (like using `requestAnimationFrame` instead of `setTimeout`.)
*
* There is an example of overriding the timer loop in \`{@link https://github.com/gnarf37/jquery-requestAnimationFrame jquery.requestAnimationFrame}\`
* @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#plugging-in-a-different-timer-loop }\`
* @since 1.8
*/
timer(tickFunction: TickFunction<any>): void;
}
/**
* @deprecated Deprecated since 1.8. Use \`{@link Tween.propHooks jQuery.Tween.propHooks}\`.
*
* `jQuery.fx.step` functions are being replaced by `jQuery.Tween.propHooks` and may eventually be removed, but are still supported via the default tween propHook.
*/
type AnimationHook<TElement> = (fx: Tween<TElement>) => void;
interface TickFunction<TElement> {
anim: Animation<TElement>;
elem: TElement;
queue: boolean | string;
(): any;
}
// #endregion
// region Queue
// #region Queue
// TODO: Is the first element always a string or is that specific to the 'fx' queue?
type Queue<TElement> = { 0: string; } & Array<QueueFunction<TElement>>;
type QueueFunction<TElement> = (this: TElement, next: () => void) => void;
// #endregion
// region Speed
// #region Speed
// Workaround for TypeScript 2.3 which does not have support for weak types handling.
type SpeedSettings<TElement> = {
/**
* A string or number determining how long the animation will run.
*/
duration: Duration;
} | {
/**
* A string indicating which easing function to use for the transition.
*/
easing: string;
} | {
/**
* A function to call once the animation is complete.
*/
complete(this: TElement): void;
} | {
[key: string]: never;
};
// #endregion
// #endregion
// region Events
// #region Events
// region Event
// #region Event
// This should be a class but doesn't work correctly under the JQuery namespace. Event should be an inner class of jQuery.
/**
* jQuery's event system normalizes the event object according to W3C standards. The event object is guaranteed to be passed to the event handler (no checks for window.event required). It normalizes the target, relatedTarget, which, metaKey and pageX/Y properties and provides both stopPropagation() and preventDefault() methods.
*
* Those properties are all documented, and accompanied by examples, on the \`{@link http://api.jquery.com/category/events/event-object/ Event object}\` page.
*
* The standard events in the Document Object Model are: `blur`, `focus`, `load`, `resize`, `scroll`, `unload`, `beforeunload`, `click`, `dblclick`, `mousedown`, `mouseup`, `mousemove`, `mouseover`, `mouseout`, `mouseenter`, `mouseleave`, `change`, `select`, `submit`, `keydown`, `keypress`, and `keyup`. Since the DOM event names have predefined meanings for some elements, using them for other purposes is not recommended. jQuery's event model can trigger an event by any name on an element, and it is propagated up the DOM tree to which that element belongs, if any.
* @see \`{@link https://api.jquery.com/category/events/event-object/ }\`
*/
interface EventStatic {
/**
* The jQuery.Event constructor is exposed and can be used when calling trigger. The new operator is optional.
*
* Check \`{@link https://api.jquery.com/trigger/ trigger}\`'s documentation to see how to combine it with your own event object.
* @see \`{@link https://api.jquery.com/category/events/event-object/ }\`
* @since 1.6
* @example
```javascript
//Create a new jQuery.Event object without the "new" operator.
var e = jQuery.Event( "click" );
// trigger an artificial click event
jQuery( "body" ).trigger( e );
```
* @example
```javascript
// Create a new jQuery.Event object with specified event properties.
var e = jQuery.Event( "keydown", { keyCode: 64 } );
// trigger an artificial keydown event with keyCode 64
jQuery( "body" ).trigger( e );
```
*/
<T extends object>(event: string, properties?: T): Event & T;
/**
* The jQuery.Event constructor is exposed and can be used when calling trigger. The new operator is optional.
*
* Check \`{@link https://api.jquery.com/trigger/ trigger}\`'s documentation to see how to combine it with your own event object.
* @see \`{@link https://api.jquery.com/category/events/event-object/ }\`
* @since 1.6
* @example
```javascript
//Create a new jQuery.Event object without the "new" operator.
var e = jQuery.Event( "click" );
// trigger an artificial click event
jQuery( "body" ).trigger( e );
```
* @example
```javascript
// Create a new jQuery.Event object with specified event properties.
var e = jQuery.Event( "keydown", { keyCode: 64 } );
// trigger an artificial keydown event with keyCode 64
jQuery( "body" ).trigger( e );
```
*/
new <T extends object>(event: string, properties?: T): Event & T;
}
/**
* jQuery's event system normalizes the event object according to W3C standards. The event object is guaranteed to be passed to the event handler (no checks for window.event required). It normalizes the target, relatedTarget, which, metaKey and pageX/Y properties and provides both stopPropagation() and preventDefault() methods.
*
* Those properties are all documented, and accompanied by examples, on the \`{@link http://api.jquery.com/category/events/event-object/ Event object}\` page.
*
* The standard events in the Document Object Model are: `blur`, `focus`, `load`, `resize`, `scroll`, `unload`, `beforeunload`, `click`, `dblclick`, `mousedown`, `mouseup`, `mousemove`, `mouseover`, `mouseout`, `mouseenter`, `mouseleave`, `change`, `select`, `submit`, `keydown`, `keypress`, and `keyup`. Since the DOM event names have predefined meanings for some elements, using them for other purposes is not recommended. jQuery's event model can trigger an event by any name on an element, and it is propagated up the DOM tree to which that element belongs, if any.
* @see \`{@link https://api.jquery.com/category/events/event-object/ }\`
* @see \`{@link TriggeredEvent }\`
*/
interface Event {
// region Copied properties
// #region Copied properties
// Event
bubbles: boolean | undefined;
cancelable: boolean | undefined;
eventPhase: number | undefined;
// UIEvent
detail: number | undefined;
view: Window | undefined;
// MouseEvent
button: number | undefined;
buttons: number | undefined;
clientX: number | undefined;
clientY: number | undefined;
offsetX: number | undefined;
offsetY: number | undefined;
/**
* The mouse position relative to the left edge of the document.
* @see \`{@link https://api.jquery.com/event.pageX/ }\`
* @since 1.0.4
* @example ````Show the mouse position relative to the left and top edges of the document (within this iframe).
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.pageX demo</title>
<style>
body {
background-color: #eef;
}
div {
padding: 20px;
}
</style>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<div id="log"></div>
<script>
$( document ).on( "mousemove", function( event ) {
$( "#log" ).text( "pageX: " + event.pageX + ", pageY: " + event.pageY );
});
</script>
</body>
</html>
```
*/
pageX: number | undefined;
/**
* The mouse position relative to the top edge of the document.
* @see \`{@link https://api.jquery.com/event.pageY/ }\`
* @since 1.0.4
* @example ````Show the mouse position relative to the left and top edges of the document (within this iframe).
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.pageY demo</title>
<style>
body {
background-color: #eef;
}
div {
padding: 20px;
}
</style>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<div id="log"></div>
<script>
$( document ).on( "mousemove", function( event ) {
$( "#log" ).text( "pageX: " + event.pageX + ", pageY: " + event.pageY );
});
</script>
</body>
</html>
```
*/
pageY: number | undefined;
screenX: number | undefined;
screenY: number | undefined;
/** @deprecated */
toElement: Element | undefined;
// PointerEvent
pointerId: number | undefined;
pointerType: string | undefined;
// KeyboardEvent
/** @deprecated */
char: string | undefined;
/** @deprecated */
charCode: number | undefined;
key: string | undefined;
/** @deprecated */
keyCode: number | undefined;
// TouchEvent
changedTouches: TouchList | undefined;
targetTouches: TouchList | undefined;
touches: TouchList | undefined;
// MouseEvent, KeyboardEvent
/**
* For key or mouse events, this property indicates the specific key or button that was pressed.
* @see \`{@link https://api.jquery.com/event.which/ }\`
* @since 1.1.3
* @example ````Log which key was depressed.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.which demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<input id="whichkey" value="type something">
<div id="log"></div>
<script>
$( "#whichkey" ).on( "keydown", function( event ) {
$( "#log" ).html( event.type + ": " + event.which );
});
</script>
</body>
</html>
```
* @example ````Log which mouse button was depressed.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.which demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<input id="whichkey" value="click here">
<div id="log"></div>
<script>
$( "#whichkey" ).on( "mousedown", function( event ) {
$( "#log" ).html( event.type + ": " + event.which );
});
</script>
</body>
</html>
```
*/
which: number | undefined;
// MouseEvent, KeyboardEvent, TouchEvent
altKey: boolean | undefined;
ctrlKey: boolean | undefined;
/**
* Indicates whether the META key was pressed when the event fired.
* @see \`{@link https://api.jquery.com/event.metaKey/ }\`
* @since 1.0.4
* @example ````Determine whether the META key was pressed when the event fired.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.metaKey demo</title>
<style>
body {
background-color: #eef;
}
div {
padding: 20px;
}
</style>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<button value="Test" name="Test" id="checkMetaKey">Click me!</button>
<div id="display"></div>
<script>
$( "#checkMetaKey" ).click(function( event ) {
$( "#display" ).text( event.metaKey );
});
</script>
</body>
</html>
```
*/
metaKey: boolean | undefined;
shiftKey: boolean | undefined;
// #endregion
/**
* The difference in milliseconds between the time the browser created the event and January 1, 1970.
* @see \`{@link https://api.jquery.com/event.timeStamp/ }\`
* @since 1.2.6
* @example ````Display the time since the click handler last executed.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.timeStamp demo</title>
<style>
div {
height: 100px;
width: 300px;
margin: 10px;
background-color: #ffd;
overflow: auto;
}
</style>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<div>Click.</div>
<script>
var last, diff;
$( "div" ).click(function( event ) {
if ( last ) {
diff = event.timeStamp - last;
$( "div" ).append( "time since last event: " + diff + "<br>" );
} else {
$( "div" ).append( "Click again.<br>" );
}
last = event.timeStamp;
});
</script>
</body>
</html>
```
*/
timeStamp: number;
/**
* Describes the nature of the event.
* @see \`{@link https://api.jquery.com/event.type/ }\`
* @since 1.0
* @example ````On all anchor clicks, alert the event type.
```javascript
$( "a" ).click(function( event ) {
alert( event.type ); // "click"
});
```
*/
type: string;
/**
* Returns whether event.preventDefault() was ever called on this event object.
* @see \`{@link https://api.jquery.com/event.isDefaultPrevented/ }\`
* @since 1.3
* @example ````Checks whether event.preventDefault() was called.
```javascript
$( "a" ).click(function( event ) {
alert( event.isDefaultPrevented() ); // false
event.preventDefault();
alert( event.isDefaultPrevented() ); // true
});
```
*/
isDefaultPrevented(): boolean;
/**
* Returns whether event.stopImmediatePropagation() was ever called on this event object.
* @see \`{@link https://api.jquery.com/event.isImmediatePropagationStopped/ }\`
* @since 1.3
* @example ````Checks whether event.stopImmediatePropagation() was called.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.isImmediatePropagationStopped demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<button>click me</button>
<div id="stop-log"></div>
<script>
function immediatePropStopped( event ) {
var msg = "";
if ( event.isImmediatePropagationStopped() ) {
msg = "called";
} else {
msg = "not called";
}
$( "#stop-log" ).append( "<div>" + msg + "</div>" );
}
$( "button" ).click(function( event ) {
immediatePropStopped( event );
event.stopImmediatePropagation();
immediatePropStopped( event );
});
</script>
</body>
</html>
```
*/
isImmediatePropagationStopped(): boolean;
/**
* Returns whether event.stopPropagation() was ever called on this event object.
* @see \`{@link https://api.jquery.com/event.isPropagationStopped/ }\`
* @since 1.3
* @example ````Checks whether event.stopPropagation() was called
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.isPropagationStopped demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<button>click me</button>
<div id="stop-log"></div>
<script>
function propStopped( event ) {
var msg = "";
if ( event.isPropagationStopped() ) {
msg = "called";
} else {
msg = "not called";
}
$( "#stop-log" ).append( "<div>" + msg + "</div>" );
}
$( "button" ).click(function(event) {
propStopped( event );
event.stopPropagation();
propStopped( event );
});
</script>
</body>
</html>
```
*/
isPropagationStopped(): boolean;
/**
* If this method is called, the default action of the event will not be triggered.
* @see \`{@link https://api.jquery.com/event.preventDefault/ }\`
* @since 1.0
* @example ````Cancel the default action (navigation) of the click.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.preventDefault demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<a href="https://jquery.com">default click action is prevented</a>
<div id="log"></div>
<script>
$( "a" ).click(function( event ) {
event.preventDefault();
$( "<div>" )
.append( "default " + event.type + " prevented" )
.appendTo( "#log" );
});
</script>
</body>
</html>
```
*/
preventDefault(): void;
/**
* Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.
* @see \`{@link https://api.jquery.com/event.stopImmediatePropagation/ }\`
* @since 1.3
* @example ````Prevents other event handlers from being called.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.stopImmediatePropagation demo</title>
<style>
p {
height: 30px;
width: 150px;
background-color: #ccf;
}
div {
height: 30px;
width: 150px;
background-color: #cfc;
}
</style>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<p>paragraph</p>
<div>division</div>
<script>
$( "p" ).click(function( event ) {
event.stopImmediatePropagation();
});
$( "p" ).click(function( event ) {
// This function won't be executed
$( this ).css( "background-color", "#f00" );
});
$( "div" ).click(function( event ) {
// This function will be executed
$( this ).css( "background-color", "#f00" );
});
</script>
</body>
</html>
```
*/
stopImmediatePropagation(): void;
/**
* Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
* @see \`{@link https://api.jquery.com/event.stopPropagation/ }\`
* @since 1.0
* @example ````Kill the bubbling on the click event.
```javascript
$( "p" ).click(function( event ) {
event.stopPropagation();
// Do something
});
```
*/
stopPropagation(): void;
}
// #endregion
/**
* Base type for jQuery events that have been triggered (including events triggered on plain objects).
*/
interface TriggeredEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends Event {
/**
* The current DOM element within the event bubbling phase.
* @see \`{@link https://api.jquery.com/event.currentTarget/ }\`
* @since 1.3
* @example ````Alert that currentTarget matches the `this` keyword.
```javascript
$( "p" ).click(function( event ) {
alert( event.currentTarget === this ); // true
});
```
*/
currentTarget: TCurrentTarget;
/**
* The element where the currently-called jQuery event handler was attached.
* @see \`{@link https://api.jquery.com/event.delegateTarget/ }\`
* @since 1.7
* @example ````When a button in any box class is clicked, change the box's background color to red.
```javascript
$( ".box" ).on( "click", "button", function( event ) {
$( event.delegateTarget ).css( "background-color", "red" );
});
```
*/
delegateTarget: TDelegateTarget;
/**
* The DOM element that initiated the event.
* @see \`{@link https://api.jquery.com/event.target/ }\`
* @since 1.0
* @example ````Display the tag's name on click
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.target demo</title>
<style>
span, strong, p {
padding: 8px;
display: block;
border: 1px solid #999;
}
</style>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<div id="log"></div>
<div>
<p>
<strong><span>click</span></strong>
</p>
</div>
<script>
$( "body" ).click(function( event ) {
$( "#log" ).html( "clicked: " + event.target.nodeName );
});
</script>
</body>
</html>
```
* @example ````Implements a simple event delegation: The click handler is added to an unordered list, and the children of its li children are hidden. Clicking one of the li children toggles (see toggle()) their children.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.target demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<ul>
<li>item 1
<ul>
<li>sub item 1-a</li>
<li>sub item 1-b</li>
</ul>
</li>
<li>item 2
<ul>
<li>sub item 2-a</li>
<li>sub item 2-b</li>
</ul>
</li>
</ul>
<script>
function handler( event ) {
var target = $( event.target );
if ( target.is( "li" ) ) {
target.children().toggle();
}
}
$( "ul" ).click( handler ).find( "ul" ).hide();
</script>
</body>
</html>
```
*/
target: TTarget;
/**
* An optional object of data passed to an event method when the current executing handler is bound.
* @see \`{@link https://api.jquery.com/event.data/ }\`
* @since 1.1
* @example ````Within a for loop, pass the value of i to the .on() method so that the current iteration's value is preserved.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.data demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<button> 0 </button>
<button> 1 </button>
<button> 2 </button>
<button> 3 </button>
<button> 4 </button>
<div id="log"></div>
<script>
var logDiv = $( "#log" );
for ( var i = 0; i < 5; i++ ) {
$( "button" ).eq( i ).on( "click", { value: i }, function( event ) {
var msgs = [
"button = " + $( this ).index(),
"event.data.value = " + event.data.value,
"i = " + i
];
logDiv.append( msgs.join( ", " ) + "<br>" );
});
}
</script>
</body>
</html>
```
*/
data: TData;
/**
* The namespace specified when the event was triggered.
* @see \`{@link https://api.jquery.com/event.namespace/ }\`
* @since 1.4.3
* @example ````Determine the event namespace used.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.namespace demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<button>display event.namespace</button>
<p></p>
<script>
$( "p" ).on( "test.something", function( event ) {
alert( event.namespace );
});
$( "button" ).click(function( event ) {
$( "p" ).trigger( "test.something" );
});
</script>
</body>
</html>
```
*/
namespace?: string | undefined;
originalEvent?: _Event | undefined;
/**
* The last value returned by an event handler that was triggered by this event, unless the value was undefined.
* @see \`{@link https://api.jquery.com/event.result/ }\`
* @since 1.3
* @example ````Display previous handler's return value
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.result demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<button>display event.result</button>
<p></p>
<script>
$( "button" ).click(function( event ) {
return "hey";
});
$( "button" ).click(function( event ) {
$( "p" ).html( event.result );
});
</script>
</body>
</html>
```
*/
result?: any;
}
// region Event
// #region Event
interface EventBase<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends TriggeredEvent<TDelegateTarget, TData, TCurrentTarget, TTarget> {
/**
* The other DOM element involved in the event, if any.
* @see \`{@link https://api.jquery.com/event.relatedTarget/ }\`
* @since 1.1.4
* @example ````On mouseout of anchors, alert the element type being entered.
```javascript
$( "a" ).mouseout(function( event ) {
alert( event.relatedTarget.nodeName ); // "DIV"
});
```
*/
relatedTarget?: undefined;
// Event
bubbles: boolean;
cancelable: boolean;
eventPhase: number;
// UIEvent
detail: undefined;
view: undefined;
// MouseEvent
button: undefined;
buttons: undefined;
clientX: undefined;
clientY: undefined;
offsetX: undefined;
offsetY: undefined;
/**
* The mouse position relative to the left edge of the document.
* @see \`{@link https://api.jquery.com/event.pageX/ }\`
* @since 1.0.4
* @example ````Show the mouse position relative to the left and top edges of the document (within this iframe).
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.pageX demo</title>
<style>
body {
background-color: #eef;
}
div {
padding: 20px;
}
</style>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<div id="log"></div>
<script>
$( document ).on( "mousemove", function( event ) {
$( "#log" ).text( "pageX: " + event.pageX + ", pageY: " + event.pageY );
});
</script>
</body>
</html>
```
*/
pageX: undefined;
/**
* The mouse position relative to the top edge of the document.
* @see \`{@link https://api.jquery.com/event.pageY/ }\`
* @since 1.0.4
* @example ````Show the mouse position relative to the left and top edges of the document (within this iframe).
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.pageY demo</title>
<style>
body {
background-color: #eef;
}
div {
padding: 20px;
}
</style>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<div id="log"></div>
<script>
$( document ).on( "mousemove", function( event ) {
$( "#log" ).text( "pageX: " + event.pageX + ", pageY: " + event.pageY );
});
</script>
</body>
</html>
```
*/
pageY: undefined;
screenX: undefined;
screenY: undefined;
/** @deprecated */
toElement: undefined;
// PointerEvent
pointerId: undefined;
pointerType: undefined;
// KeyboardEvent
/** @deprecated */
char: undefined;
/** @deprecated */
charCode: undefined;
key: undefined;
/** @deprecated */
keyCode: undefined;
// TouchEvent
changedTouches: undefined;
targetTouches: undefined;
touches: undefined;
// MouseEvent, KeyboardEvent
/**
* For key or mouse events, this property indicates the specific key or button that was pressed.
* @see \`{@link https://api.jquery.com/event.which/ }\`
* @since 1.1.3
* @deprecated Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`.
* @example ````Log which key was depressed.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.which demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<input id="whichkey" value="type something">
<div id="log"></div>
<script>
$( "#whichkey" ).on( "keydown", function( event ) {
$( "#log" ).html( event.type + ": " + event.which );
});
</script>
</body>
</html>
```
* @example ````Log which mouse button was depressed.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.which demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<input id="whichkey" value="click here">
<div id="log"></div>
<script>
$( "#whichkey" ).on( "mousedown", function( event ) {
$( "#log" ).html( event.type + ": " + event.which );
});
</script>
</body>
</html>
```
*/
which: undefined;
// MouseEvent, KeyboardEvent, TouchEvent
altKey: undefined;
ctrlKey: undefined;
/**
* Indicates whether the META key was pressed when the event fired.
* @see \`{@link https://api.jquery.com/event.metaKey/ }\`
* @since 1.0.4
* @example ````Determine whether the META key was pressed when the event fired.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.metaKey demo</title>
<style>
body {
background-color: #eef;
}
div {
padding: 20px;
}
</style>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<button value="Test" name="Test" id="checkMetaKey">Click me!</button>
<div id="display"></div>
<script>
$( "#checkMetaKey" ).click(function( event ) {
$( "#display" ).text( event.metaKey );
});
</script>
</body>
</html>
```
*/
metaKey: undefined;
shiftKey: undefined;
originalEvent?: _Event | undefined;
}
interface ChangeEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends EventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: 'change';
}
interface ResizeEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends EventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: 'resize';
}
interface ScrollEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends EventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: 'scroll';
}
interface SelectEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends EventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: 'select';
}
interface SubmitEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends EventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: 'submit';
}
// #endregion
// region UIEvent
// #region UIEvent
interface UIEventBase<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends TriggeredEvent<TDelegateTarget, TData, TCurrentTarget, TTarget> {
// Event
bubbles: boolean;
cancelable: boolean;
eventPhase: number;
// UIEvent
detail: number;
view: Window;
originalEvent?: _UIEvent | undefined;
}
// region MouseEvent
// #region MouseEvent
interface MouseEventBase<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends UIEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
/**
* The other DOM element involved in the event, if any.
* @see \`{@link https://api.jquery.com/event.relatedTarget/ }\`
* @since 1.1.4
* @example ````On mouseout of anchors, alert the element type being entered.
```javascript
$( "a" ).mouseout(function( event ) {
alert( event.relatedTarget.nodeName ); // "DIV"
});
```
*/
relatedTarget?: EventTarget | null | undefined;
// MouseEvent
button: number;
buttons: number;
clientX: number;
clientY: number;
offsetX: number;
offsetY: number;
/**
* The mouse position relative to the left edge of the document.
* @see \`{@link https://api.jquery.com/event.pageX/ }\`
* @since 1.0.4
* @example ````Show the mouse position relative to the left and top edges of the document (within this iframe).
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.pageX demo</title>
<style>
body {
background-color: #eef;
}
div {
padding: 20px;
}
</style>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<div id="log"></div>
<script>
$( document ).on( "mousemove", function( event ) {
$( "#log" ).text( "pageX: " + event.pageX + ", pageY: " + event.pageY );
});
</script>
</body>
</html>
```
*/
pageX: number;
/**
* The mouse position relative to the top edge of the document.
* @see \`{@link https://api.jquery.com/event.pageY/ }\`
* @since 1.0.4
* @example ````Show the mouse position relative to the left and top edges of the document (within this iframe).
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.pageY demo</title>
<style>
body {
background-color: #eef;
}
div {
padding: 20px;
}
</style>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<div id="log"></div>
<script>
$( document ).on( "mousemove", function( event ) {
$( "#log" ).text( "pageX: " + event.pageX + ", pageY: " + event.pageY );
});
</script>
</body>
</html>
```
*/
pageY: number;
screenX: number;
screenY: number;
/** @deprecated */
toElement: Element;
// PointerEvent
pointerId: undefined;
pointerType: undefined;
// KeyboardEvent
/** @deprecated */
char: undefined;
/** @deprecated */
charCode: undefined;
key: undefined;
/** @deprecated */
keyCode: undefined;
// TouchEvent
changedTouches: undefined;
targetTouches: undefined;
touches: undefined;
// MouseEvent, KeyboardEvent
/**
* For key or mouse events, this property indicates the specific key or button that was pressed.
* @see \`{@link https://api.jquery.com/event.which/ }\`
* @since 1.1.3
* @deprecated Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`.
* @example ````Log which key was depressed.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.which demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<input id="whichkey" value="type something">
<div id="log"></div>
<script>
$( "#whichkey" ).on( "keydown", function( event ) {
$( "#log" ).html( event.type + ": " + event.which );
});
</script>
</body>
</html>
```
* @example ````Log which mouse button was depressed.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.which demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<input id="whichkey" value="click here">
<div id="log"></div>
<script>
$( "#whichkey" ).on( "mousedown", function( event ) {
$( "#log" ).html( event.type + ": " + event.which );
});
</script>
</body>
</html>
```
*/
which: number;
// MouseEvent, KeyboardEvent, TouchEvent
altKey: boolean;
ctrlKey: boolean;
/**
* Indicates whether the META key was pressed when the event fired.
* @see \`{@link https://api.jquery.com/event.metaKey/ }\`
* @since 1.0.4
* @example ````Determine whether the META key was pressed when the event fired.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.metaKey demo</title>
<style>
body {
background-color: #eef;
}
div {
padding: 20px;
}
</style>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<button value="Test" name="Test" id="checkMetaKey">Click me!</button>
<div id="display"></div>
<script>
$( "#checkMetaKey" ).click(function( event ) {
$( "#display" ).text( event.metaKey );
});
</script>
</body>
</html>
```
*/
metaKey: boolean;
shiftKey: boolean;
originalEvent?: _MouseEvent | undefined;
}
interface ClickEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends MouseEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
/**
* The other DOM element involved in the event, if any.
* @see \`{@link https://api.jquery.com/event.relatedTarget/ }\`
* @since 1.1.4
* @example ````On mouseout of anchors, alert the element type being entered.
```javascript
$( "a" ).mouseout(function( event ) {
alert( event.relatedTarget.nodeName ); // "DIV"
});
```
*/
relatedTarget?: null | undefined;
type: 'click';
}
interface ContextMenuEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends MouseEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
/**
* The other DOM element involved in the event, if any.
* @see \`{@link https://api.jquery.com/event.relatedTarget/ }\`
* @since 1.1.4
* @example ````On mouseout of anchors, alert the element type being entered.
```javascript
$( "a" ).mouseout(function( event ) {
alert( event.relatedTarget.nodeName ); // "DIV"
});
```
*/
relatedTarget?: null | undefined;
type: 'contextmenu';
}
interface DoubleClickEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends MouseEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
/**
* The other DOM element involved in the event, if any.
* @see \`{@link https://api.jquery.com/event.relatedTarget/ }\`
* @since 1.1.4
* @example ````On mouseout of anchors, alert the element type being entered.
```javascript
$( "a" ).mouseout(function( event ) {
alert( event.relatedTarget.nodeName ); // "DIV"
});
```
*/
relatedTarget?: null | undefined;
type: 'dblclick';
}
interface MouseDownEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends MouseEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
/**
* The other DOM element involved in the event, if any.
* @see \`{@link https://api.jquery.com/event.relatedTarget/ }\`
* @since 1.1.4
* @example ````On mouseout of anchors, alert the element type being entered.
```javascript
$( "a" ).mouseout(function( event ) {
alert( event.relatedTarget.nodeName ); // "DIV"
});
```
*/
relatedTarget?: null | undefined;
type: 'mousedown';
}
interface MouseEnterEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends MouseEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
// Special handling by jQuery.
type: 'mouseover';
}
interface MouseLeaveEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends MouseEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
// Special handling by jQuery.
type: 'mouseout';
}
interface MouseMoveEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends MouseEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
/**
* The other DOM element involved in the event, if any.
* @see \`{@link https://api.jquery.com/event.relatedTarget/ }\`
* @since 1.1.4
* @example ````On mouseout of anchors, alert the element type being entered.
```javascript
$( "a" ).mouseout(function( event ) {
alert( event.relatedTarget.nodeName ); // "DIV"
});
```
*/
relatedTarget?: null | undefined;
type: 'mousemove';
}
interface MouseOutEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends MouseEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: 'mouseout';
}
interface MouseOverEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends MouseEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: 'mouseover';
}
interface MouseUpEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends MouseEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
/**
* The other DOM element involved in the event, if any.
* @see \`{@link https://api.jquery.com/event.relatedTarget/ }\`
* @since 1.1.4
* @example ````On mouseout of anchors, alert the element type being entered.
```javascript
$( "a" ).mouseout(function( event ) {
alert( event.relatedTarget.nodeName ); // "DIV"
});
```
*/
relatedTarget?: null | undefined;
type: 'mouseup';
}
// region DragEvent
// #region DragEvent
interface DragEventBase<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends UIEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
originalEvent?: _DragEvent | undefined;
}
interface DragEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends DragEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: 'drag';
}
interface DragEndEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends DragEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: 'dragend';
}
interface DragEnterEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends DragEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: 'dragenter';
}
interface DragExitEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends DragEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: 'dragexit';
}
interface DragLeaveEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends DragEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: 'dragleave';
}
interface DragOverEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends DragEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: 'dragover';
}
interface DragStartEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends DragEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: 'dragstart';
}
interface DropEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends DragEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: 'drop';
}
// #endregion
// #endregion
// region KeyboardEvent
// #region KeyboardEvent
interface KeyboardEventBase<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends UIEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
/**
* The other DOM element involved in the event, if any.
* @see \`{@link https://api.jquery.com/event.relatedTarget/ }\`
* @since 1.1.4
* @example ````On mouseout of anchors, alert the element type being entered.
```javascript
$( "a" ).mouseout(function( event ) {
alert( event.relatedTarget.nodeName ); // "DIV"
});
```
*/
relatedTarget?: undefined;
// MouseEvent
button: undefined;
buttons: undefined;
clientX: undefined;
clientY: undefined;
offsetX: undefined;
offsetY: undefined;
/**
* The mouse position relative to the left edge of the document.
* @see \`{@link https://api.jquery.com/event.pageX/ }\`
* @since 1.0.4
* @example ````Show the mouse position relative to the left and top edges of the document (within this iframe).
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.pageX demo</title>
<style>
body {
background-color: #eef;
}
div {
padding: 20px;
}
</style>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<div id="log"></div>
<script>
$( document ).on( "mousemove", function( event ) {
$( "#log" ).text( "pageX: " + event.pageX + ", pageY: " + event.pageY );
});
</script>
</body>
</html>
```
*/
pageX: undefined;
/**
* The mouse position relative to the top edge of the document.
* @see \`{@link https://api.jquery.com/event.pageY/ }\`
* @since 1.0.4
* @example ````Show the mouse position relative to the left and top edges of the document (within this iframe).
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.pageY demo</title>
<style>
body {
background-color: #eef;
}
div {
padding: 20px;
}
</style>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<div id="log"></div>
<script>
$( document ).on( "mousemove", function( event ) {
$( "#log" ).text( "pageX: " + event.pageX + ", pageY: " + event.pageY );
});
</script>
</body>
</html>
```
*/
pageY: undefined;
screenX: undefined;
screenY: undefined;
/** @deprecated */
toElement: undefined;
// PointerEvent
pointerId: undefined;
pointerType: undefined;
// KeyboardEvent
/** @deprecated */
char: string | undefined;
/** @deprecated */
charCode: number;
code: string;
key: string;
/** @deprecated */
keyCode: number;
// TouchEvent
changedTouches: undefined;
targetTouches: undefined;
touches: undefined;
// MouseEvent, KeyboardEvent
/**
* For key or mouse events, this property indicates the specific key or button that was pressed.
* @see \`{@link https://api.jquery.com/event.which/ }\`
* @since 1.1.3
* @deprecated Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`.
* @example ````Log which key was depressed.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.which demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<input id="whichkey" value="type something">
<div id="log"></div>
<script>
$( "#whichkey" ).on( "keydown", function( event ) {
$( "#log" ).html( event.type + ": " + event.which );
});
</script>
</body>
</html>
```
* @example ````Log which mouse button was depressed.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.which demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<input id="whichkey" value="click here">
<div id="log"></div>
<script>
$( "#whichkey" ).on( "mousedown", function( event ) {
$( "#log" ).html( event.type + ": " + event.which );
});
</script>
</body>
</html>
```
*/
which: number;
// MouseEvent, KeyboardEvent, TouchEvent
altKey: boolean;
ctrlKey: boolean;
/**
* Indicates whether the META key was pressed when the event fired.
* @see \`{@link https://api.jquery.com/event.metaKey/ }\`
* @since 1.0.4
* @example ````Determine whether the META key was pressed when the event fired.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.metaKey demo</title>
<style>
body {
background-color: #eef;
}
div {
padding: 20px;
}
</style>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<button value="Test" name="Test" id="checkMetaKey">Click me!</button>
<div id="display"></div>
<script>
$( "#checkMetaKey" ).click(function( event ) {
$( "#display" ).text( event.metaKey );
});
</script>
</body>
</html>
```
*/
metaKey: boolean;
shiftKey: boolean;
originalEvent?: _KeyboardEvent | undefined;
}
interface KeyDownEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends KeyboardEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: 'keydown';
}
interface KeyPressEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends KeyboardEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: 'keypress';
}
interface KeyUpEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends KeyboardEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: 'keyup';
}
// #endregion
// region TouchEvent
// #region TouchEvent
interface TouchEventBase<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends UIEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
/**
* The other DOM element involved in the event, if any.
* @see \`{@link https://api.jquery.com/event.relatedTarget/ }\`
* @since 1.1.4
* @example ````On mouseout of anchors, alert the element type being entered.
```javascript
$( "a" ).mouseout(function( event ) {
alert( event.relatedTarget.nodeName ); // "DIV"
});
```
*/
relatedTarget?: undefined;
// MouseEvent
button: undefined;
buttons: undefined;
clientX: undefined;
clientY: undefined;
offsetX: undefined;
offsetY: undefined;
/**
* The mouse position relative to the left edge of the document.
* @see \`{@link https://api.jquery.com/event.pageX/ }\`
* @since 1.0.4
* @example ````Show the mouse position relative to the left and top edges of the document (within this iframe).
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.pageX demo</title>
<style>
body {
background-color: #eef;
}
div {
padding: 20px;
}
</style>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<div id="log"></div>
<script>
$( document ).on( "mousemove", function( event ) {
$( "#log" ).text( "pageX: " + event.pageX + ", pageY: " + event.pageY );
});
</script>
</body>
</html>
```
*/
pageX: undefined;
/**
* The mouse position relative to the top edge of the document.
* @see \`{@link https://api.jquery.com/event.pageY/ }\`
* @since 1.0.4
* @example ````Show the mouse position relative to the left and top edges of the document (within this iframe).
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.pageY demo</title>
<style>
body {
background-color: #eef;
}
div {
padding: 20px;
}
</style>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<div id="log"></div>
<script>
$( document ).on( "mousemove", function( event ) {
$( "#log" ).text( "pageX: " + event.pageX + ", pageY: " + event.pageY );
});
</script>
</body>
</html>
```
*/
pageY: undefined;
screenX: undefined;
screenY: undefined;
/** @deprecated */
toElement: undefined;
// PointerEvent
pointerId: undefined;
pointerType: undefined;
// KeyboardEvent
/** @deprecated */
char: undefined;
/** @deprecated */
charCode: undefined;
key: undefined;
/** @deprecated */
keyCode: undefined;
// TouchEvent
changedTouches: TouchList;
targetTouches: TouchList;
touches: TouchList;
// MouseEvent, KeyboardEvent
/**
* For key or mouse events, this property indicates the specific key or button that was pressed.
* @see \`{@link https://api.jquery.com/event.which/ }\`
* @since 1.1.3
* @deprecated Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`.
* @example ````Log which key was depressed.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.which demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<input id="whichkey" value="type something">
<div id="log"></div>
<script>
$( "#whichkey" ).on( "keydown", function( event ) {
$( "#log" ).html( event.type + ": " + event.which );
});
</script>
</body>
</html>
```
* @example ````Log which mouse button was depressed.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.which demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<input id="whichkey" value="click here">
<div id="log"></div>
<script>
$( "#whichkey" ).on( "mousedown", function( event ) {
$( "#log" ).html( event.type + ": " + event.which );
});
</script>
</body>
</html>
```
*/
which: undefined;
// MouseEvent, KeyboardEvent, TouchEvent
altKey: boolean;
ctrlKey: boolean;
/**
* Indicates whether the META key was pressed when the event fired.
* @see \`{@link https://api.jquery.com/event.metaKey/ }\`
* @since 1.0.4
* @example ````Determine whether the META key was pressed when the event fired.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.metaKey demo</title>
<style>
body {
background-color: #eef;
}
div {
padding: 20px;
}
</style>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<button value="Test" name="Test" id="checkMetaKey">Click me!</button>
<div id="display"></div>
<script>
$( "#checkMetaKey" ).click(function( event ) {
$( "#display" ).text( event.metaKey );
});
</script>
</body>
</html>
```
*/
metaKey: boolean;
shiftKey: boolean;
originalEvent?: _TouchEvent | undefined;
}
interface TouchCancelEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends TouchEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: 'touchcancel';
}
interface TouchEndEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends TouchEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: 'touchend';
}
interface TouchMoveEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends TouchEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: 'touchmove';
}
interface TouchStartEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends TouchEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: 'touchstart';
}
// #endregion
// region FocusEvent
// #region FocusEvent
interface FocusEventBase<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends UIEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
/**
* The other DOM element involved in the event, if any.
* @see \`{@link https://api.jquery.com/event.relatedTarget/ }\`
* @since 1.1.4
* @example ````On mouseout of anchors, alert the element type being entered.
```javascript
$( "a" ).mouseout(function( event ) {
alert( event.relatedTarget.nodeName ); // "DIV"
});
```
*/
relatedTarget?: EventTarget | null | undefined;
// MouseEvent
button: undefined;
buttons: undefined;
clientX: undefined;
clientY: undefined;
offsetX: undefined;
offsetY: undefined;
/**
* The mouse position relative to the left edge of the document.
* @see \`{@link https://api.jquery.com/event.pageX/ }\`
* @since 1.0.4
* @example ````Show the mouse position relative to the left and top edges of the document (within this iframe).
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.pageX demo</title>
<style>
body {
background-color: #eef;
}
div {
padding: 20px;
}
</style>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<div id="log"></div>
<script>
$( document ).on( "mousemove", function( event ) {
$( "#log" ).text( "pageX: " + event.pageX + ", pageY: " + event.pageY );
});
</script>
</body>
</html>
```
*/
pageX: undefined;
/**
* The mouse position relative to the top edge of the document.
* @see \`{@link https://api.jquery.com/event.pageY/ }\`
* @since 1.0.4
* @example ````Show the mouse position relative to the left and top edges of the document (within this iframe).
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.pageY demo</title>
<style>
body {
background-color: #eef;
}
div {
padding: 20px;
}
</style>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<div id="log"></div>
<script>
$( document ).on( "mousemove", function( event ) {
$( "#log" ).text( "pageX: " + event.pageX + ", pageY: " + event.pageY );
});
</script>
</body>
</html>
```
*/
pageY: undefined;
screenX: undefined;
screenY: undefined;
/** @deprecated */
toElement: undefined;
// PointerEvent
pointerId: undefined;
pointerType: undefined;
// KeyboardEvent
/** @deprecated */
char: undefined;
/** @deprecated */
charCode: undefined;
key: undefined;
/** @deprecated */
keyCode: undefined;
// TouchEvent
changedTouches: undefined;
targetTouches: undefined;
touches: undefined;
// MouseEvent, KeyboardEvent
/**
* For key or mouse events, this property indicates the specific key or button that was pressed.
* @see \`{@link https://api.jquery.com/event.which/ }\`
* @since 1.1.3
* @deprecated Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`.
* @example ````Log which key was depressed.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.which demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<input id="whichkey" value="type something">
<div id="log"></div>
<script>
$( "#whichkey" ).on( "keydown", function( event ) {
$( "#log" ).html( event.type + ": " + event.which );
});
</script>
</body>
</html>
```
* @example ````Log which mouse button was depressed.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.which demo</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<input id="whichkey" value="click here">
<div id="log"></div>
<script>
$( "#whichkey" ).on( "mousedown", function( event ) {
$( "#log" ).html( event.type + ": " + event.which );
});
</script>
</body>
</html>
```
*/
which: undefined;
// MouseEvent, KeyboardEvent, TouchEvent
altKey: undefined;
ctrlKey: undefined;
/**
* Indicates whether the META key was pressed when the event fired.
* @see \`{@link https://api.jquery.com/event.metaKey/ }\`
* @since 1.0.4
* @example ````Determine whether the META key was pressed when the event fired.
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.metaKey demo</title>
<style>
body {
background-color: #eef;
}
div {
padding: 20px;
}
</style>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<button value="Test" name="Test" id="checkMetaKey">Click me!</button>
<div id="display"></div>
<script>
$( "#checkMetaKey" ).click(function( event ) {
$( "#display" ).text( event.metaKey );
});
</script>
</body>
</html>
```
*/
metaKey: undefined;
shiftKey: undefined;
originalEvent?: _FocusEvent | undefined;
}
interface BlurEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends FocusEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: 'blur';
}
interface FocusEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends FocusEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: 'focus';
}
interface FocusInEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends FocusEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: 'focusin';
}
interface FocusOutEvent<
TDelegateTarget = any,
TData = any,
TCurrentTarget = any,
TTarget = any
> extends FocusEventBase<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: 'focusout';
}
// #endregion
// #endregion
interface TypeToTriggeredEventMap<
TDelegateTarget,
TData,
TCurrentTarget,
TTarget
> {
// Event
change: ChangeEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
resize: ResizeEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
scroll: ScrollEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
select: SelectEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
submit: SubmitEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
// UIEvent
// MouseEvent
click: ClickEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
contextmenu: ContextMenuEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
dblclick: DoubleClickEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
mousedown: MouseDownEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
mouseenter: MouseEnterEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
mouseleave: MouseLeaveEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
mousemove: MouseMoveEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
mouseout: MouseOutEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
mouseover: MouseOverEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
mouseup: MouseUpEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
// DragEvent
drag: DragEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
dragend: DragEndEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
dragenter: DragEnterEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
dragexit: DragExitEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
dragleave: DragLeaveEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
dragover: DragOverEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
dragstart: DragStartEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
drop: DropEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
// KeyboardEvent
keydown: KeyDownEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
keypress: KeyPressEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
keyup: KeyUpEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
// TouchEvent
touchcancel: TouchCancelEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
touchend: TouchEndEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
touchmove: TouchMoveEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
touchstart: TouchStartEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
// FocusEvent
blur: BlurEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
focus: FocusEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
focusin: FocusInEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
focusout: FocusOutEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
[type: string]: TriggeredEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
}
// Extra parameters can be passed from trigger()
type EventHandlerBase<TContext, T> = (this: TContext, t: T, ...args: any[]) => any;
type EventHandler<
TCurrentTarget,
TData = undefined
> = EventHandlerBase<TCurrentTarget, TriggeredEvent<TCurrentTarget, TData>>;
type TypeEventHandler<
TDelegateTarget,
TData,
TCurrentTarget,
TTarget,
TType extends keyof TypeToTriggeredEventMap<TDelegateTarget, TData, TCurrentTarget, TTarget>
> = EventHandlerBase<TCurrentTarget, TypeToTriggeredEventMap<TDelegateTarget, TData, TCurrentTarget, TTarget>[TType]>;
interface TypeEventHandlers<
TDelegateTarget,
TData,
TCurrentTarget,
TTarget
> extends _TypeEventHandlers<TDelegateTarget, TData, TCurrentTarget, TTarget> {
// No idea why it's necessary to include `object` in the union but otherwise TypeScript complains that
// derived types of Event are not assignable to Event.
[type: string]: TypeEventHandler<TDelegateTarget, TData, TCurrentTarget, TTarget, string> |
false |
undefined |
object;
}
type _TypeEventHandlers<
TDelegateTarget,
TData,
TCurrentTarget,
TTarget
> = {
[TType in keyof TypeToTriggeredEventMap<TDelegateTarget, TData, TCurrentTarget, TTarget>]?:
TypeEventHandler<TDelegateTarget, TData, TCurrentTarget, TTarget, TType> |
false |
object;
};
// region Event extensions
// #region Event extensions
interface EventExtensions {
/**
* The jQuery special event hooks are a set of per-event-name functions and properties that allow code to control the behavior of event processing within jQuery. The mechanism is similar to `fixHooks` in that the special event information is stored in `jQuery.event.special.NAME`, where `NAME` is the name of the special event. Event names are case sensitive.
*
* As with `fixHooks`, the special event hooks design assumes it will be very rare that two unrelated pieces of code want to process the same event name. Special event authors who need to modify events with existing hooks will need to take precautions to avoid introducing unwanted side-effects by clobbering those hooks.
* @see \`{@link https://learn.jquery.com/events/event-extensions/#special-event-hooks }\`
*/
special: SpecialEventHooks;
}
// region Special event hooks
// #region Special event hooks
/**
* The jQuery special event hooks are a set of per-event-name functions and properties that allow code to control the behavior of event processing within jQuery. The mechanism is similar to `fixHooks` in that the special event information is stored in `jQuery.event.special.NAME`, where `NAME` is the name of the special event. Event names are case sensitive.
*
* As with `fixHooks`, the special event hooks design assumes it will be very rare that two unrelated pieces of code want to process the same event name. Special event authors who need to modify events with existing hooks will need to take precautions to avoid introducing unwanted side-effects by clobbering those hooks.
* @see \`{@link https://learn.jquery.com/events/event-extensions/#special-event-hooks }\`
*/
// Workaround for TypeScript 2.3 which does not have support for weak types handling.
type SpecialEventHook<TTarget, TData> = {
/**
* Indicates whether this event type should be bubbled when the `.trigger()` method is called; by default it is `false`, meaning that a triggered event will bubble to the element's parents up to the document (if attached to a document) and then to the window. Note that defining `noBubble` on an event will effectively prevent that event from being used for delegated events with `.trigger()`.
* @see \`{@link https://learn.jquery.com/events/event-extensions/#nobubble-boolean }\`
*/
noBubble: boolean;
} | {
/**
* When defined, these string properties specify that a special event should be handled like another event type until the event is delivered. The `bindType` is used if the event is attached directly, and the `delegateType` is used for delegated events. These types are generally DOM event types, and _should not_ be a special event themselves.
* @see \`{@link https://learn.jquery.com/events/event-extensions/#bindtype-string-delegatetype-string }\`
*/
bindType: string;
} | {
/**
* When defined, these string properties specify that a special event should be handled like another event type until the event is delivered. The `bindType` is used if the event is attached directly, and the `delegateType` is used for delegated events. These types are generally DOM event types, and _should not_ be a special event themselves.
* @see \`{@link https://learn.jquery.com/events/event-extensions/#bindtype-string-delegatetype-string }\`
*/
delegateType: string;
} | {
/**
* The setup hook is called the first time an event of a particular type is attached to an element; this provides the hook an opportunity to do processing that will apply to all events of this type on this element. The `this` keyword will be a reference to the element where the event is being attached and `eventHandle` is jQuery's event handler function. In most cases the `namespaces` argument should not be used, since it only represents the namespaces of the _first_ event being attached; subsequent events may not have this same namespaces.
*
* This hook can perform whatever processing it desires, including attaching its own event handlers to the element or to other elements and recording setup information on the element using the `jQuery.data()` method. If the setup hook wants jQuery to add a browser event (via `addEventListener` or `attachEvent`, depending on browser) it should return `false`. In all other cases, jQuery will not add the browser event, but will continue all its other bookkeeping for the event. This would be appropriate, for example, if the event was never fired by the browser but invoked by `.trigger()`. To attach the jQuery event handler in the setup hook, use the `eventHandle` argument.
* @see \`{@link https://learn.jquery.com/events/event-extensions/#setup-function-data-object-namespaces-eventhandle-function }\`
*/
setup(this: TTarget, data: TData, namespaces: string, eventHandle: EventHandler<TTarget, TData>): void | false;
} | {
/**
* The teardown hook is called when the final event of a particular type is removed from an element. The `this` keyword will be a reference to the element where the event is being cleaned up. This hook should return `false` if it wants jQuery to remove the event from the browser's event system (via `removeEventListener` or `detachEvent`). In most cases, the setup and teardown hooks should return the same value.
*
* If the setup hook attached event handlers or added data to an element through a mechanism such as `jQuery.data()`, the teardown hook should reverse the process and remove them. jQuery will generally remove the data and events when an element is totally removed from the document, but failing to remove data or events on teardown will cause a memory leak if the element stays in the document.
* @see \`{@link https://learn.jquery.com/events/event-extensions/#teardown-function }\`
*/
teardown(this: TTarget): void | false;
} | {
/**
* Each time an event handler is added to an element through an API such as `.on()`, jQuery calls this hook. The `this` keyword will be the element to which the event handler is being added, and the `handleObj` argument is as described in the section above. The return value of this hook is ignored.
* @see \`{@link https://learn.jquery.com/events/event-extensions/#add-function-handleobj }\`
*/
add(this: TTarget, handleObj: HandleObject<TTarget, TData>): void;
} | {
/**
* When an event handler is removed from an element using an API such as `.off()`, this hook is called. The `this` keyword will be the element where the handler is being removed, and the `handleObj` argument is as described in the section above. The return value of this hook is ignored.
* @see \`{@link https://learn.jquery.com/events/event-extensions/#remove-function-handleobj }\`
*/
remove(this: TTarget, handleObj: HandleObject<TTarget, TData>): void;
} | {
/**
* Called when the `.trigger()` or `.triggerHandler()` methods are used to trigger an event for the special type from code, as opposed to events that originate from within the browser. The `this` keyword will be the element being triggered, and the event argument will be a `jQuery.Event` object constructed from the caller's input. At minimum, the event type, data, namespace, and target properties are set on the event. The data argument represents additional data passed by `.trigger()` if present.
*
* The trigger hook is called early in the process of triggering an event, just after the `jQuery.Event` object is constructed and before any handlers have been called. It can process the triggered event in any way, for example by calling `event.stopPropagation()` or `event.preventDefault()` before returning. If the hook returns `false`, jQuery does not perform any further event triggering actions and returns immediately. Otherwise, it performs the normal trigger processing, calling any event handlers for the element and bubbling the event (unless propagation is stopped in advance or `noBubble` was specified for the special event) to call event handlers attached to parent elements.
* @see \`{@link https://learn.jquery.com/events/event-extensions/#trigger-function-event-jquery-event-data-object }\`
*/
trigger(this: TTarget, event: Event, data: TData): void | false;
} | {
/**
* When the `.trigger()` method finishes running all the event handlers for an event, it also looks for and runs any method on the target object by the same name unless of the handlers called `event.preventDefault()`. So, `.trigger( "submit" )` will execute the `submit()` method on the element if one exists. When a `_default` hook is specified, the hook is called just prior to checking for and executing the element's default method. If this hook returns the value `false` the element's default method will be called; otherwise it is not.
* @see \`{@link https://learn.jquery.com/events/event-extensions/#_default-function-event-jquery-event-data-object }\`
*/
_default(event: TriggeredEvent<TTarget, TData>, data: TData): void | false;
} | {
/**
* jQuery calls a handle hook when the event has occurred and jQuery would normally call the user's event handler specified by `.on()` or another event binding method. If the hook exists, jQuery calls it _instead_ of that event handler, passing it the event and any data passed from `.trigger()` if it was not a native event. The `this` keyword is the DOM element being handled, and `event.handleObj` property has the detailed event information.
*
* Based in the information it has, the handle hook should decide whether to call the original handler function which is in `event.handleObj.handler`. It can modify information in the event object before calling the original handler, but _must restore_ that data before returning or subsequent unrelated event handlers may act unpredictably. In most cases, the handle hook should return the result of the original handler, but that is at the discretion of the hook. The handle hook is unique in that it is the only special event function hook that is called under its original special event name when the type is mapped using `bindType` and `delegateType`. For that reason, it is almost always an error to have anything other than a handle hook present if the special event defines a `bindType` and `delegateType`, since those other hooks will never be called.
* @see \`{@link https://learn.jquery.com/events/event-extensions/#handle-function-event-jquery-event-data-object }\`
*/
handle(this: TTarget, event: TriggeredEvent<TTarget, TData> & { handleObj: HandleObject<TTarget, TData>; }, ...data: TData[]): void;
} | {
preDispatch(this: TTarget, event: Event): false | void;
} | {
postDispatch(this: TTarget, event: Event): void;
} | {
[key: string]: any;
};
interface SpecialEventHooks {
[event: string]: SpecialEventHook<EventTarget, any>;
}
/**
* Many of the special event hook functions below are passed a `handleObj` object that provides more information about the event, how it was attached, and its current state. This object and its contents should be treated as read-only data, and only the properties below are documented for use by special event handlers.
* @see \`{@link https://learn.jquery.com/events/event-extensions/#the-handleobj-object }\`
*/
interface HandleObject<TTarget, TData> {
/**
* The type of event, such as `"click"`. When special event mapping is used via `bindType` or `delegateType`, this will be the mapped type.
*/
readonly type: string;
/**
* The original type name regardless of whether it was mapped via `bindType` or `delegateType`. So when a "pushy" event is mapped to "click" its `origType` would be "pushy".
*/
readonly origType: string;
/**
* Namespace(s), if any, provided when the event was attached, such as `"myPlugin"`. When multiple namespaces are given, they are separated by periods and sorted in ascending alphabetical order. If no namespaces are provided, this property is an empty string.
*/
readonly namespace: string;
/**
* For delegated events, this is the selector used to filter descendant elements and determine if the handler should be called. For directly bound events, this property is `null`.
*/
readonly selector: string | undefined | null;
/**
* The data, if any, passed to jQuery during event binding, e.g. `{ myData: 42 }`. If the data argument was omitted or `undefined`, this property is `undefined` as well.
*/
readonly data: TData;
/**
* Event handler function passed to jQuery during event binding. If `false` was passed during event binding, the handler refers to a single shared function that simply returns `false`.
*/
readonly handler: EventHandler<TTarget, TData>;
}
// #endregion
// #endregion
// #endregion
interface NameValuePair {
name: string;
value: string;
}
// region Coordinates
// #region Coordinates
interface Coordinates {
left: number;
top: number;
}
// Workaround for TypeScript 2.3 which does not have support for weak types handling.
type CoordinatesPartial =
Pick<Coordinates, 'left'> |
Pick<Coordinates, 'top'> |
{ [key: string]: never; };
// #endregion
// region Val hooks
// #region Val hooks
// Workaround for TypeScript 2.3 which does not have support for weak types handling.
type ValHook<TElement> = {
get(elem: TElement): any;
} | {
set(elem: TElement, value: any): any;
} | {
[key: string]: never;
};
interface ValHooks {
// Set to HTMLElement to minimize breaks but should probably be Element.
[nodeName: string]: ValHook<HTMLElement>;
}
// #endregion
type _Falsy = false | null | undefined | 0 | '' | typeof document.all;
}
declare const jQuery: JQueryStatic;
declare const $: JQueryStatic;
type _Event = Event;
type _UIEvent = UIEvent;
type _MouseEvent = MouseEvent;
type _DragEvent = DragEvent;
type _KeyboardEvent = KeyboardEvent;
type _TouchEvent = TouchEvent;
type _FocusEvent = FocusEvent;
// region ES5 compatibility
// #region ES5 compatibility
// Forward declaration of `Iterable<T>`.
// tslint:disable-next-line:no-empty-interface
interface Iterable<T> { }
interface SymbolConstructor {
/**
* A String value that is used in the creation of the default string description of an object.
* Called by the built-in method Object.prototype.toString.
*/
readonly toStringTag: symbol;
}
declare var Symbol: SymbolConstructor;
// #endregion | the_stack |
import tl = require('azure-pipelines-task-lib/task');
import fs = require('fs');
import os = require('os');
import path = require('path');
import url = require('url');
import request = require('request');
import { JobSearch } from './jobsearch';
import { JobQueue } from './jobqueue';
import { unzip } from './unzip';
import {JobState, checkStateTransitions} from './states';
import * as Util from './util';
export class Job {
public Parent: Job; // if this job is a pipelined job, its parent that started it.
public Children: Job[] = []; // any pipelined jobs
public Joined: Job; // if this job is joined, the main job that is running
public Search: JobSearch;
private queue: JobQueue;
public TaskUrl: string; // URL for the job definition
public State: JobState = JobState.New;
public ExecutableUrl: string; // URL for the executing job instance
public ExecutableNumber: number;
public Name: string;
public Identifier: string; // a job identifier that takes into account folder structure
private jobConsole: string = '';
private jobConsoleOffset: number = 0;
private jobConsoleEnabled: boolean = false;
private working: boolean = true; // initially mark it as working
private workDelay: number = 0;
private retryNumber: number;
public ParsedExecutionResult: {result: string, timestamp: number}; // set during state Finishing
constructor(jobQueue: JobQueue, parent: Job, taskUrl: string, executableUrl: string, executableNumber: number, name: string) {
this.Parent = parent;
this.TaskUrl = taskUrl;
this.ExecutableUrl = executableUrl;
this.ExecutableNumber = executableNumber;
this.Name = name;
if (this.Parent != null) {
this.Parent.Children.push(this);
}
this.queue = jobQueue;
this.retryNumber = 0;
if (this.TaskUrl.startsWith(this.queue.TaskOptions.serverEndpointUrl)) {
// simplest case (jobs run on the same server name as the endpoint)
this.Identifier = this.TaskUrl.substr(this.queue.TaskOptions.serverEndpointUrl.length);
} else {
// backup check in case job is running on a different server name than the endpoint
this.Identifier = url.parse(this.TaskUrl).path.substr(1);
const jobStringIndex: number = this.Identifier.indexOf('job/');
if (jobStringIndex > 0) {
// can fall into here if the jenkins endpoint is not at the server root; e.g. serverUrl/jenkins instead of serverUrl
this.Identifier = this.Identifier.substr(jobStringIndex);
}
}
this.queue.AddJob(this);
this.debug('created');
this.initialize();
}
/**
* All changes to the job state should be routed through here.
* This defines all and validates all state transitions.
*/
private changeState(newState: JobState) {
const currentState: JobState = this.State;
this.debug(`state changed from ${JobState[currentState]} to ${JobState[newState]}`);
const validStateChange: boolean = checkStateTransitions(currentState, newState);
if (!validStateChange) {
Util.fail(`Invalid state change from: ${JobState[currentState]} to: ${JobState[newState]} ${this}`);
}
this.State = newState;
}
public DoWork() {
if (this.working) { // return if already working
return;
} else {
this.working = true;
setTimeout(() => {
switch (this.State) {
case (JobState.New): {
this.initialize();
break;
}
case (JobState.Streaming): {
this.streamConsole();
break;
}
case (JobState.Downloading): {
this.downloadResults();
break;
}
case (JobState.Finishing): {
this.finish();
break;
}
default: {
// usually do not get here, but this can happen if another callback caused this job to be joined
this.stopWork(this.queue.TaskOptions.pollIntervalMillis, null);
break;
}
}
}, this.workDelay);
}
}
private stopWork(delay: number, jobState: JobState) {
if (jobState && jobState !== this.State) {
this.changeState(jobState);
if (!this.IsActive()) {
this.queue.FlushJobConsolesSafely();
}
}
this.workDelay = delay;
this.working = false;
}
private RetryConnection(): void {
this.retryNumber++;
this.consoleLog(`Connection error. Retrying again in ${this.queue.TaskOptions.delayBetweenRetries} seconds. Retry ${this.retryNumber} out of ${this.queue.TaskOptions.retryCount}`);
this.stopWork(this.queue.TaskOptions.delayBetweenRetries*1000, this.State);
}
public IsActive(): boolean {
return this.State === JobState.New ||
this.State === JobState.Locating ||
this.State === JobState.Streaming ||
this.State === JobState.Downloading ||
this.State === JobState.Finishing;
}
private getBlockMessage(message: string): string {
const divider: string = '******************************************************************************';
const blockMessage: string = divider + '\n' + message + ' \n' + divider;
return blockMessage;
}
public SetStreaming(executableNumber: number): void {
// If we aren't waiting for the job to finish then we should end it now
if (!this.queue.TaskOptions.captureConsole) { // transition to Finishing
this.changeState(JobState.Streaming);
this.changeState(JobState.Finishing);
return;
}
if (this.State === JobState.New || this.State === JobState.Locating) {
this.ExecutableNumber = executableNumber;
this.ExecutableUrl = Util.addUrlSegment(this.TaskUrl, this.ExecutableNumber.toString());
this.changeState(JobState.Streaming);
// log the jobs starting block
this.consoleLog(this.getBlockMessage('Jenkins job started: ' + this.Name + '\n' + this.ExecutableUrl));
// log any pending jobs
if (this.queue.FindActiveConsoleJob() == null) {
console.log('Jenkins job pending: ' + this.ExecutableUrl);
}
} else if (this.State === JobState.Joined || this.State === JobState.Cut) {
Util.fail('Can not be set to streaming: ' + this);
}
this.joinOthersToMe();
}
private joinOthersToMe() {
//join all other siblings to this same job (as long as it's not root)
const thisJob: Job = this;
if (thisJob.Parent != null) {
thisJob.Search.DetermineMainJob(thisJob.ExecutableNumber, function (mainJob: Job, secondaryJobs: Job[]) {
if (mainJob != thisJob) {
Util.fail('Illegal call in joinOthersToMe(), job:' + thisJob);
}
for (const i in secondaryJobs) {
const secondaryJob: Job = secondaryJobs[i];
if (secondaryJob.State !== JobState.Cut) {
secondaryJob.SetJoined(thisJob);
}
}
});
}
}
public SetJoined(joinedJob: Job): void {
tl.debug(this + '.setJoined(' + joinedJob + ')');
this.Joined = joinedJob;
this.changeState(JobState.Joined);
if (joinedJob.State === JobState.Joined || joinedJob.State === JobState.Cut) {
Util.fail('Invalid join: ' + this);
}
// recursively cut all children
for (const i in this.Children) {
this.Children[i].Cut();
}
}
public Cut(): void {
this.changeState(JobState.Cut);
for (const i in this.Children) {
this.Children[i].Cut();
}
}
private setParsedExecutionResult(parsedExecutionResult: {result: string, timestamp: number}) {
this.ParsedExecutionResult = parsedExecutionResult;
//log the job's closing block
this.consoleLog(this.getBlockMessage('Jenkins job finished: ' + this.Name + '\n' + this.ExecutableUrl));
}
public GetTaskResult(): number {
if (this.State === JobState.Queued) {
return tl.TaskResult.Succeeded;
} else if (this.State === JobState.Done) {
const resultCode = this.ParsedExecutionResult.result.toUpperCase();
if (resultCode == 'SUCCESS' || (resultCode == 'UNSTABLE' && !this.queue.TaskOptions.failOnUnstableResult)) {
return tl.TaskResult.Succeeded;
} else {
return tl.TaskResult.Failed;
}
}
return tl.TaskResult.Failed;
}
public GetResultString(): string {
if (this.State === JobState.Queued) {
return 'Queued';
} else if (this.State === JobState.Done) {
const resultCode: string = this.ParsedExecutionResult.result.toUpperCase();
// codes map to fields in http://hudson-ci.org/javadoc/hudson/model/Result.html
if (resultCode == 'SUCCESS') {
return tl.loc('succeeded');
} else if (resultCode == 'UNSTABLE') {
return tl.loc('unstable');
} else if (resultCode == 'FAILURE') {
return tl.loc('failed');
} else if (resultCode == 'NOT_BUILT') {
return tl.loc('notbuilt');
} else if (resultCode == 'ABORTED') {
return tl.loc('aborted');
} else {
return resultCode;
}
} else {
return tl.loc('unknown');
}
}
private initialize() {
const thisJob: Job = this;
thisJob.Search.Initialize().then(() => {
if (thisJob.Search.Initialized) {
if (thisJob.queue.TaskOptions.capturePipeline) {
const downstreamProjects = thisJob.Search.ParsedTaskBody.downstreamProjects || [];
downstreamProjects.forEach((project) => {
if (project.color !== 'disabled') {
new Job(thisJob.queue, thisJob, project.url, null, -1, project.name); // will add a new child to the tree
}
});
}
thisJob.Search.ResolveIfKnown(thisJob); // could change state
const newState: JobState = (thisJob.State === JobState.New) ? JobState.Locating : thisJob.State; // another call back could also change state
const nextWorkDelay: number = (newState === JobState.Locating) ? thisJob.queue.TaskOptions.pollIntervalMillis : thisJob.workDelay;
thisJob.stopWork(nextWorkDelay, newState);
} else {
//search not initialized, so try again
thisJob.stopWork(thisJob.queue.TaskOptions.pollIntervalMillis, thisJob.State);
}
}).fail((err) => {
throw err;
});
}
/**
* Checks the success of the job
*
* JobState = Finishing, transition to Downloading, Done, or Queued possible
*/
private finish(): void {
const thisJob: Job = this;
tl.debug('finish()');
if (!thisJob.queue.TaskOptions.captureConsole) { // transition to Queued
thisJob.stopWork(0, JobState.Queued);
} else { // stay in Finishing, or eventually go to Done
const resultUrl: string = Util.addUrlSegment(thisJob.ExecutableUrl, 'api/json?tree=result,timestamp');
thisJob.debug('Tracking completion status of job: ' + resultUrl);
request.get({ url: resultUrl, strictSSL: thisJob.queue.TaskOptions.strictSSL }, function requestCallback(err, httpResponse, body) {
tl.debug('finish().requestCallback()');
if (err) {
Util.handleConnectionResetError(err); // something went bad
thisJob.stopWork(thisJob.queue.TaskOptions.pollIntervalMillis, thisJob.State);
return;
} else if (httpResponse.statusCode !== 200) {
console.error(`Job was killed because of an response with unexpected status code from Jenkins - ${httpResponse.statusCode}`);
Util.failReturnCode(httpResponse, 'Job progress tracking failed to read job result');
thisJob.stopWork(0, JobState.Killed);
} else {
const parsedBody: {result: string, timestamp: number} = JSON.parse(body);
thisJob.debug(`parsedBody for: ${resultUrl} : ${JSON.stringify(parsedBody)}`);
if (parsedBody.result) {
thisJob.setParsedExecutionResult(parsedBody);
if (thisJob.queue.TaskOptions.teamBuildPluginAvailable) {
thisJob.stopWork(0, JobState.Downloading);
} else {
thisJob.stopWork(0, JobState.Done);
}
} else {
// result not updated yet -- keep trying
thisJob.stopWork(thisJob.queue.TaskOptions.pollIntervalMillis, thisJob.State);
}
}
}).auth(thisJob.queue.TaskOptions.username, thisJob.queue.TaskOptions.password, true);
}
}
private downloadResults(): void {
const thisJob: Job = this;
const downloadUrl: string = Util.addUrlSegment(thisJob.ExecutableUrl, 'team-results/zip');
tl.debug('downloadResults(), url:' + downloadUrl);
const downloadRequest = request.get({ url: downloadUrl, strictSSL: thisJob.queue.TaskOptions.strictSSL })
.auth(thisJob.queue.TaskOptions.username, thisJob.queue.TaskOptions.password, true)
.on('error', (err) => {
Util.handleConnectionResetError(err); // something went bad
thisJob.stopWork(thisJob.queue.TaskOptions.pollIntervalMillis, thisJob.State);
})
.on('response', (response) => {
tl.debug('downloadResults(), url:' + downloadUrl + ' , response.statusCode: ' + response.statusCode + ', response.statusMessage: ' + response.statusMessage);
if (response.statusCode == 404) { // expected if there are no results
tl.debug('no results to download');
thisJob.stopWork(0, JobState.Done);
} else if (response.statusCode == 200) { // successfully found results
const destinationFolder: string = path.join(thisJob.queue.TaskOptions.saveResultsTo, thisJob.Name + '/');
const fileName: string = path.join(destinationFolder, 'team-results.zip');
try {
// Create the destination folder if it doesn't exist
if (!tl.exist(destinationFolder)) {
tl.debug('creating results destination folder: ' + destinationFolder);
tl.mkdirP(destinationFolder);
}
tl.debug('downloading results file: ' + fileName);
const file: fs.WriteStream = fs.createWriteStream(fileName);
downloadRequest.pipe(file)
.on('error', (err) => { throw err; })
.on('finish', function fileFinished() {
tl.debug('successfully downloaded results to: ' + fileName);
try {
unzip(fileName, destinationFolder);
thisJob.stopWork(0, JobState.Done);
} catch (e) {
tl.warning('unable to extract results file');
tl.debug(e.message);
process.stderr.write(e + os.EOL);
thisJob.stopWork(0, JobState.Done);
}
});
} catch (err) {
// don't fail the job if the results can not be downloaded successfully
tl.warning('unable to download results to file: ' + fileName + ' for Jenkins Job: ' + thisJob.ExecutableUrl);
tl.warning(err.message);
process.stderr.write(err + os.EOL);
thisJob.stopWork(0, JobState.Done);
}
} else { // an unexepected error with results
try {
const warningMessage: string = (response.statusCode >= 500) ?
'A Jenkins error occurred while retrieving results. Results could not be downloaded.' : // Jenkins server error
'Jenkins results could not be downloaded.'; // Any other error
tl.warning(warningMessage);
const warningStream: any = new Util.StringWritable({ decodeStrings: false });
downloadRequest.pipe(warningStream)
.on('error', (err) => { throw err; })
.on('finish', function finished() {
tl.warning(warningStream);
thisJob.stopWork(0, JobState.Done);
});
} catch (err) {
// don't fail the job if the results can not be downloaded successfully
tl.warning(err.message);
process.stderr.write(err + os.EOL);
thisJob.stopWork(0, JobState.Done);
}
}
});
}
/**
* Streams the Jenkins console.
*
* JobState = Streaming, transition to Finishing possible.
*/
private streamConsole(): void {
const thisJob: Job = this;
const fullUrl: string = Util.addUrlSegment(thisJob.ExecutableUrl, '/logText/progressiveText/?start=' + thisJob.jobConsoleOffset);
thisJob.debug('Tracking progress of job URL: ' + fullUrl);
request.get({ url: fullUrl, strictSSL: thisJob.queue.TaskOptions.strictSSL }, function requestCallback(err, httpResponse, body) {
tl.debug('streamConsole().requestCallback()');
if (err) {
if (thisJob.retryNumber >= thisJob.queue.TaskOptions.retryCount) {
Util.handleConnectionResetError(err); // something went bad
thisJob.stopWork(thisJob.queue.TaskOptions.pollIntervalMillis, thisJob.State);
return;
}
else {
thisJob.RetryConnection();
}
} else if (httpResponse.statusCode === 404) {
// got here too fast, stream not yet available, try again in the future
thisJob.stopWork(thisJob.queue.TaskOptions.pollIntervalMillis, thisJob.State);
} else if (httpResponse.statusCode === 401) {
Util.failReturnCode(httpResponse, 'Job progress tracking failed to read job progress');
thisJob.queue.TaskOptions.captureConsole = false;
thisJob.queue.TaskOptions.capturePipeline = false;
thisJob.queue.TaskOptions.shouldFail = true;
thisJob.queue.TaskOptions.failureMsg = 'Job progress tracking failed to read job progress';
thisJob.stopWork(0, JobState.Finishing);
} else if (httpResponse.statusCode !== 200) {
if (thisJob.retryNumber >= thisJob.queue.TaskOptions.retryCount) {
Util.failReturnCode(httpResponse, 'Job progress tracking failed to read job progress');
thisJob.stopWork(thisJob.queue.TaskOptions.pollIntervalMillis, thisJob.State);
}
else {
thisJob.RetryConnection();
}
} else {
thisJob.consoleLog(body); // redirect Jenkins console to task console
const xMoreData: string = httpResponse.headers['x-more-data'];
if (xMoreData && xMoreData == 'true') {
const offset: string = httpResponse.headers['x-text-size'];
thisJob.jobConsoleOffset = Number.parseInt(offset);
thisJob.stopWork(thisJob.queue.TaskOptions.pollIntervalMillis, thisJob.State);
} else { // no more console, move to Finishing
thisJob.stopWork(0, JobState.Finishing);
}
}
}).auth(thisJob.queue.TaskOptions.username, thisJob.queue.TaskOptions.password, true)
.on('error', (err) => {
if (thisJob.retryNumber >= thisJob.queue.TaskOptions.retryCount) {
throw err;
}
else {
thisJob.consoleLog(err);
}
});
}
public EnableConsole() {
const thisJob: Job = this;
if (thisJob.queue.TaskOptions.captureConsole) {
if (!this.jobConsoleEnabled) {
if (this.jobConsole != '') { // flush any queued output
console.log(this.jobConsole);
}
this.jobConsoleEnabled = true;
}
}
}
public IsConsoleEnabled() {
return this.jobConsoleEnabled;
}
private consoleLog(message: string) {
if (this.jobConsoleEnabled) {
//only log it if the console is enabled.
console.log(message);
}
this.jobConsole += message;
}
private debug(message: string) {
const fullMessage: string = this.toString() + ' debug: ' + message;
tl.debug(fullMessage);
}
private toString() {
let fullMessage: string = '(' + this.State + ':' + this.Name + ':' + this.ExecutableNumber;
if (this.Parent != null) {
fullMessage += ', p:' + this.Parent;
}
if (this.Joined != null) {
fullMessage += ', j:' + this.Joined;
}
fullMessage += ')';
return fullMessage;
}
} | the_stack |
import { Injectable } from '@angular/core';
import { Location } from '@angular/common';
import { Params, QueryParamsHandling } from '@angular/router';
import { Observable, BehaviorSubject, ReplaySubject, Subject } from 'rxjs';
import { share } from 'rxjs/operators';
import { isFragmentContain, isFragmentEqual, isUrlPathContain, isUrlPathEqual } from './url-matching-helpers';
import { NbIconConfig } from '../icon/icon.component';
import { NbBadge } from '../badge/badge.component';
export interface NbMenuBag { tag: string; item: NbMenuItem }
const itemClick$ = new Subject<NbMenuBag>();
const addItems$ = new ReplaySubject<{ tag: string; items: NbMenuItem[] }>(1);
const navigateHome$ = new ReplaySubject<{ tag: string }>(1);
const getSelectedItem$
= new ReplaySubject<{ tag: string; listener: BehaviorSubject<NbMenuBag> }>(1);
const itemSelect$ = new ReplaySubject<NbMenuBag>(1);
const itemHover$ = new ReplaySubject<NbMenuBag>(1);
const submenuToggle$ = new ReplaySubject<NbMenuBag>(1);
const collapseAll$ = new ReplaySubject<{ tag: string }>(1);
export type NbMenuBadgeConfig = Omit<NbBadge, 'position'>;
// TODO: check if we need both URL and LINK
/**
*
*
* Menu Item options example
* @stacked-example(Menu Link Parameters, menu/menu-link-params.component)
*
*
*/
export class NbMenuItem {
/**
* Item Title
* @type {string}
*/
title: string;
/**
* Item relative link (for routerLink)
* @type {string}
*/
link?: string;
/**
* Item URL (absolute)
* @type {string}
*/
url?: string;
/**
* Icon class name or icon config object
* @type {string | NbIconConfig}
*/
icon?: string | NbIconConfig;
/**
* Expanded by default
* @type {boolean}
*/
expanded?: boolean;
/**
* Badge component
* @type {boolean}
*/
badge?: NbMenuBadgeConfig;
/**
* Children items
* @type {List<NbMenuItem>}
*/
children?: NbMenuItem[];
/**
* HTML Link target
* @type {string}
*/
target?: string;
/**
* Hidden Item
* @type {boolean}
*/
hidden?: boolean;
/**
* Item is selected when partly or fully equal to the current url
* @type {string}
*/
pathMatch?: 'full' | 'prefix' = 'full';
/**
* Where this is a home item
* @type {boolean}
*/
home?: boolean;
/**
* Whether the item is just a group (non-clickable)
* @type {boolean}
*/
group?: boolean;
/** Whether the item skipLocationChange is true or false
*@type {boolean}
*/
skipLocationChange?: boolean;
/** Map of query parameters
*@type {Params}
*/
queryParams?: Params;
queryParamsHandling?: QueryParamsHandling;
parent?: NbMenuItem;
selected?: boolean;
data?: any;
fragment?: string;
preserveFragment?: boolean;
/**
* @returns item parents in top-down order
*/
static getParents(item: NbMenuItem): NbMenuItem[] {
const parents = [];
let parent = item.parent;
while (parent) {
parents.unshift(parent);
parent = parent.parent;
}
return parents;
}
static isParent(item: NbMenuItem, possibleChild: NbMenuItem): boolean {
return possibleChild.parent
? possibleChild.parent === item || this.isParent(item, possibleChild.parent)
: false;
}
}
// TODO: map select events to router change events
// TODO: review the interface
/**
*
*
* Menu Service. Allows you to listen to menu events, or to interact with a menu.
* @stacked-example(Menu Service, menu/menu-service.component)
*
*
*/
@Injectable()
export class NbMenuService {
/**
* Add items to the end of the menu items list
* @param {List<NbMenuItem>} items
* @param {string} tag
*/
addItems(items: NbMenuItem[], tag?: string) {
addItems$.next({ tag, items });
}
/**
* Collapses all menu items
* @param {string} tag
*/
collapseAll(tag?: string) {
collapseAll$.next({ tag });
}
/**
* Navigate to the home menu item
* @param {string} tag
*/
navigateHome(tag?: string) {
navigateHome$.next({ tag });
}
/**
* Returns currently selected item. Won't subscribe to the future events.
* @param {string} tag
* @returns {Observable<{tag: string; item: NbMenuItem}>}
*/
getSelectedItem(tag?: string): Observable<NbMenuBag> {
const listener = new BehaviorSubject<NbMenuBag>(null);
getSelectedItem$.next({ tag, listener });
return listener.asObservable();
}
onItemClick(): Observable<NbMenuBag> {
return itemClick$.pipe(share());
}
onItemSelect(): Observable<NbMenuBag> {
return itemSelect$.pipe(share());
}
onItemHover(): Observable<NbMenuBag> {
return itemHover$.pipe(share());
}
onSubmenuToggle(): Observable<NbMenuBag> {
return submenuToggle$.pipe(share());
}
}
@Injectable()
export class NbMenuInternalService {
constructor(private location: Location) {}
prepareItems(items: NbMenuItem[]) {
const defaultItem = new NbMenuItem();
items.forEach(i => {
this.applyDefaults(i, defaultItem);
this.setParent(i);
});
}
selectFromUrl(items: NbMenuItem[], tag: string, collapseOther: boolean = false) {
const selectedItem = this.findItemByUrl(items);
if (selectedItem) {
this.selectItem(selectedItem, items, collapseOther, tag);
}
}
selectItem(item: NbMenuItem, items: NbMenuItem[], collapseOther: boolean = false, tag: string) {
const unselectedItems = this.resetSelection(items);
const collapsedItems = collapseOther ? this.collapseItems(items) : [];
for (const parent of NbMenuItem.getParents(item)) {
parent.selected = true;
// emit event only for items that weren't selected before ('unselectedItems' contains items that were selected)
if (!unselectedItems.includes(parent)) {
this.itemSelect(parent, tag);
}
const wasNotExpanded = !parent.expanded;
parent.expanded = true;
const i = collapsedItems.indexOf(parent);
// emit event only for items that weren't expanded before.
// 'collapsedItems' contains items that were expanded, so no need to emit event.
// in case 'collapseOther' is false, 'collapsedItems' will be empty,
// so also check if item isn't expanded already ('wasNotExpanded').
if (i === -1 && wasNotExpanded) {
this.submenuToggle(parent, tag);
} else {
collapsedItems.splice(i, 1);
}
}
item.selected = true;
// emit event only for items that weren't selected before ('unselectedItems' contains items that were selected)
if (!unselectedItems.includes(item)) {
this.itemSelect(item, tag);
}
// remaining items which wasn't expanded back after expanding all currently selected items
for (const collapsedItem of collapsedItems) {
this.submenuToggle(collapsedItem, tag);
}
}
collapseAll(items: NbMenuItem[], tag: string, except?: NbMenuItem) {
const collapsedItems = this.collapseItems(items, except);
for (const item of collapsedItems) {
this.submenuToggle(item, tag);
}
}
onAddItem(): Observable<{ tag: string; items: NbMenuItem[] }> {
return addItems$.pipe(share());
}
onNavigateHome(): Observable<{ tag: string }> {
return navigateHome$.pipe(share());
}
onCollapseAll(): Observable<{ tag: string }> {
return collapseAll$.pipe(share());
}
onGetSelectedItem(): Observable<{ tag: string; listener: BehaviorSubject<NbMenuBag> }> {
return getSelectedItem$.pipe(share());
}
itemHover(item: NbMenuItem, tag?: string) {
itemHover$.next({tag, item});
}
submenuToggle(item: NbMenuItem, tag?: string) {
submenuToggle$.next({tag, item});
}
itemSelect(item: NbMenuItem, tag?: string) {
itemSelect$.next({tag, item});
}
itemClick(item: NbMenuItem, tag?: string) {
itemClick$.next({tag, item});
}
/**
* Unselect all given items deeply.
* @param items array of items to unselect.
* @returns items which selected value was changed.
*/
private resetSelection(items: NbMenuItem[]): NbMenuItem[] {
const unselectedItems = [];
for (const item of items) {
if (item.selected) {
unselectedItems.push(item);
}
item.selected = false;
if (item.children) {
unselectedItems.push(...this.resetSelection(item.children));
}
}
return unselectedItems;
}
/**
* Collapse all given items deeply.
* @param items array of items to collapse.
* @param except menu item which shouldn't be collapsed, also disables collapsing for parents of this item.
* @returns items which expanded value was changed.
*/
private collapseItems(items: NbMenuItem[], except?: NbMenuItem): NbMenuItem[] {
const collapsedItems = [];
for (const item of items) {
if (except && (item === except || NbMenuItem.isParent(item, except))) {
continue;
}
if (item.expanded) {
collapsedItems.push(item)
}
item.expanded = false;
if (item.children) {
collapsedItems.push(...this.collapseItems(item.children));
}
}
return collapsedItems;
}
private applyDefaults(item, defaultItem) {
const menuItem = {...item};
Object.assign(item, defaultItem, menuItem);
item.children && item.children.forEach(child => {
this.applyDefaults(child, defaultItem);
});
}
private setParent(item: NbMenuItem) {
item.children && item.children.forEach(child => {
child.parent = item;
this.setParent(child);
});
}
/**
* Find deepest item which link matches current URL path.
* @param items array of items to search in.
* @returns found item of undefined.
*/
private findItemByUrl(items: NbMenuItem[]): NbMenuItem | undefined {
let selectedItem;
items.some(item => {
if (item.children) {
selectedItem = this.findItemByUrl(item.children);
}
if (!selectedItem && this.isSelectedInUrl(item)) {
selectedItem = item;
}
return selectedItem;
});
return selectedItem;
}
private isSelectedInUrl(item: NbMenuItem): boolean {
const exact: boolean = item.pathMatch === 'full';
const link: string = item.link;
const isSelectedInPath = exact
? isUrlPathEqual(this.location.path(), link)
: isUrlPathContain(this.location.path(), link);
if (isSelectedInPath && item.fragment != null) {
return exact
? isFragmentEqual(this.location.path(true), item.fragment)
: isFragmentContain(this.location.path(true), item.fragment);
}
return isSelectedInPath;
}
} | the_stack |
import {
IAppSettings,
IBookmark,
IClusterAuthProviderAWS,
IClusterAuthProviderAzure,
IClusterAuthProviderDigitalOcean,
IClusterAuthProviderGoogle,
IClusterAuthProviderOIDC,
IClusterAuthProviderRancher,
IClusters,
TAuthProvider,
} from '../declarations';
import {
DEFAULT_SETTINGS,
STORAGE_BOOKMARKS,
STORAGE_CLUSTER,
STORAGE_CLUSTERS,
STORAGE_SETTINGS,
STORAGE_TEMPORARY_CREDENTIALS,
} from './constants';
// readBookmarks returns the saved bookmarks of a user from localStorage.
export const readBookmarks = (): IBookmark[] => {
const bookmarks = localStorage.getItem(STORAGE_BOOKMARKS);
if (bookmarks === null) {
return [];
}
return JSON.parse(bookmarks);
};
// readCluster returns the saved active cluster from localStorage. If there is no value in the localStorage or the saved
// active cluster is not in the saved cluster, undefined is returned.
export const readCluster = (): string | undefined => {
const clusters = readClusters();
return localStorage.getItem(STORAGE_CLUSTER) !== null && localStorage.getItem(STORAGE_CLUSTER) !== ''
? (localStorage.getItem(STORAGE_CLUSTER) as string)
: clusters && Object.keys(clusters).length > 0
? Object.keys(clusters)[0]
: undefined;
};
// readClusters returns the saved clusters from localStorage. If there are no saved clusters, undefined is returned.
export const readClusters = (): IClusters | undefined => {
// return localStorage.getItem(STORAGE_CLUSTERS) !== null && localStorage.getItem(STORAGE_CLUSTERS) !== ''
// ? (JSON.parse(localStorage.getItem(STORAGE_CLUSTERS) as string) as IClusters)
// : undefined;
// DEPRECATED: Migrate old clusters to the new structure. This can be removed in one of the next version.
const clusters =
localStorage.getItem(STORAGE_CLUSTERS) !== null && localStorage.getItem(STORAGE_CLUSTERS) !== ''
? (JSON.parse(localStorage.getItem(STORAGE_CLUSTERS) as string) as IClusters)
: undefined;
if (clusters === undefined || localStorage.getItem('migrated') === 'true') {
return clusters;
}
const azureCredentials = localStorage.getItem('azure');
const awsCredentials = localStorage.getItem('aws');
const googleCredentials = localStorage.getItem('google');
const rancherCredentials = localStorage.getItem('rancher');
const googleClientID = localStorage.getItem('google_clientid');
const oidcCredentials = localStorage.getItem('oidc');
for (const id in clusters) {
if (clusters[id].authProvider === '') {
clusters[id].authProvider = 'kubeconfig';
} else if (clusters[id].authProvider === 'aws') {
if (awsCredentials !== null) {
const parsed = JSON.parse(awsCredentials);
const parts = id.split('_');
if (parts.length >= 3) {
if (parsed.hasOwnProperty(parts[1])) {
clusters[id].authProviderAWS = {
clusterID: parts.slice(2, parts.length).join('_'),
accessKeyID: parsed[parts[1]].accessKeyID,
region: parts[1],
secretKey: parsed[parts[1]].secretKey,
};
}
}
}
} else if (clusters[id].authProvider === 'google') {
if (googleCredentials !== null && googleClientID !== null) {
const parsed = JSON.parse(googleCredentials);
clusters[id].authProviderGoogle = {
accessToken: parsed.access_token,
clientID: googleClientID,
expires: 0,
idToken: parsed.id_token,
refreshToken: parsed.refresh_token,
tokenType: parsed.token_type,
};
}
} else if (clusters[id].authProvider === 'rancher') {
if (rancherCredentials !== null) {
const parsed = JSON.parse(rancherCredentials);
clusters[id].authProviderRancher = {
rancherHost: parsed.rancherHost,
rancherPort: parsed.rancherPort,
secure: parsed.secure,
username: parsed.username,
password: parsed.password,
bearerToken: parsed.bearerToken,
expires: parsed.expires,
};
}
} else if (clusters[id].authProvider === 'azure') {
if (azureCredentials !== null) {
clusters[id].authProviderAzure = JSON.parse(azureCredentials) as IClusterAuthProviderAzure;
}
} else if (clusters[id].authProvider.startsWith('oidc__')) {
if (oidcCredentials !== null) {
const authProvider = clusters[id].authProvider.replace('oidc__', '');
const oidc = JSON.parse(oidcCredentials);
clusters[id].authProvider = 'oidc';
if (oidc.hasOwnProperty(authProvider)) {
clusters[id].authProviderOIDC = {
clientID: oidc[authProvider].clientID,
clientSecret: oidc[authProvider].clientSecret,
idToken: oidc[authProvider].idToken,
idpIssuerURL: oidc[authProvider].idpIssuerURL,
refreshToken: oidc[authProvider].refreshToken,
certificateAuthority: oidc[authProvider].certificateAuthority,
accessToken: oidc[authProvider].accessToken,
expiry: oidc[authProvider].expiry,
};
}
}
}
}
localStorage.setItem(STORAGE_CLUSTERS, JSON.stringify(clusters));
localStorage.setItem('migrated', 'true');
localStorage.removeItem('aws');
localStorage.removeItem('azure');
localStorage.removeItem('google_clientid');
localStorage.removeItem('google');
localStorage.removeItem('rancher');
localStorage.removeItem('oidc');
localStorage.removeItem('oidc_last');
return clusters;
};
// readSettings returns the settings set by the user. If the user had not modified the settings yet, return the default
// settings. We have to check the parsed settings from localStorage key by key, because on older version it is possible,
// that a key is missing.
export const readSettings = (): IAppSettings => {
const settingsFromStorage = localStorage.getItem(STORAGE_SETTINGS);
if (settingsFromStorage) {
const settings = JSON.parse(settingsFromStorage);
return {
theme: settings.theme ? settings.theme : DEFAULT_SETTINGS.theme,
authenticationEnabled: settings.hasOwnProperty('authenticationEnabled')
? settings.authenticationEnabled
: DEFAULT_SETTINGS.authenticationEnabled,
timeout: settings.timeout ? settings.timeout : DEFAULT_SETTINGS.timeout,
terminalFontSize: settings.terminalFontSize ? settings.terminalFontSize : DEFAULT_SETTINGS.terminalFontSize,
terminalScrollback: settings.terminalScrollback
? settings.terminalScrollback
: DEFAULT_SETTINGS.terminalScrollback,
editorFormat: settings.editorFormat ? settings.editorFormat : DEFAULT_SETTINGS.editorFormat,
enablePodMetrics: settings.hasOwnProperty('enablePodMetrics')
? settings.enablePodMetrics
: DEFAULT_SETTINGS.enablePodMetrics,
queryLimit: settings.queryLimit ? settings.queryLimit : DEFAULT_SETTINGS.queryLimit,
queryRefetchInterval: settings.queryRefetchInterval
? settings.queryRefetchInterval
: DEFAULT_SETTINGS.queryRefetchInterval,
queryConfig: DEFAULT_SETTINGS.queryConfig,
sshKey: settings.sshKey ? settings.sshKey : DEFAULT_SETTINGS.sshKey,
sshPort: settings.sshPort ? settings.sshPort : DEFAULT_SETTINGS.sshPort,
sshUser: settings.sshUser ? settings.sshUser : DEFAULT_SETTINGS.sshUser,
prometheusEnabled: settings.hasOwnProperty('prometheusEnabled')
? settings.prometheusEnabled
: DEFAULT_SETTINGS.prometheusEnabled,
prometheusNamespace: settings.prometheusNamespace
? settings.prometheusNamespace
: DEFAULT_SETTINGS.prometheusNamespace,
prometheusSelector: settings.prometheusSelector
? settings.prometheusSelector
: DEFAULT_SETTINGS.prometheusSelector,
prometheusPort: settings.prometheusPort ? settings.prometheusPort : DEFAULT_SETTINGS.prometheusPort,
prometheusUsername: settings.prometheusUsername
? settings.prometheusUsername
: DEFAULT_SETTINGS.prometheusUsername,
prometheusPassword: settings.prometheusPassword
? settings.prometheusPassword
: DEFAULT_SETTINGS.prometheusPassword,
prometheusAddress: '',
prometheusDashboardsNamespace: settings.prometheusDashboardsNamespace
? settings.prometheusDashboardsNamespace
: DEFAULT_SETTINGS.prometheusDashboardsNamespace,
elasticsearchEnabled: settings.hasOwnProperty('elasticsearchEnabled')
? settings.elasticsearchEnabled
: DEFAULT_SETTINGS.elasticsearchEnabled,
elasticsearchNamespace: settings.elasticsearchNamespace
? settings.elasticsearchNamespace
: DEFAULT_SETTINGS.elasticsearchNamespace,
elasticsearchSelector: settings.elasticsearchSelector
? settings.elasticsearchSelector
: DEFAULT_SETTINGS.elasticsearchSelector,
elasticsearchPort: settings.elasticsearchPort ? settings.elasticsearchPort : DEFAULT_SETTINGS.elasticsearchPort,
elasticsearchUsername: settings.elasticsearchUsername
? settings.elasticsearchUsername
: DEFAULT_SETTINGS.elasticsearchUsername,
elasticsearchPassword: settings.elasticsearchPassword
? settings.elasticsearchPassword
: DEFAULT_SETTINGS.elasticsearchPassword,
elasticsearchAddress: '',
jaegerEnabled: settings.hasOwnProperty('jaegerEnabled') ? settings.jaegerEnabled : DEFAULT_SETTINGS.jaegerEnabled,
jaegerNamespace: settings.jaegerNamespace ? settings.jaegerNamespace : DEFAULT_SETTINGS.jaegerNamespace,
jaegerSelector: settings.jaegerSelector ? settings.jaegerSelector : DEFAULT_SETTINGS.jaegerSelector,
jaegerPort: settings.jaegerPort ? settings.jaegerPort : DEFAULT_SETTINGS.jaegerPort,
jaegerUsername: settings.jaegerUsername ? settings.jaegerUsername : DEFAULT_SETTINGS.jaegerUsername,
jaegerPassword: settings.jaegerPassword ? settings.jaegerPassword : DEFAULT_SETTINGS.jaegerPassword,
jaegerQueryBasePath: settings.jaegerQueryBasePath
? settings.jaegerQueryBasePath
: DEFAULT_SETTINGS.jaegerQueryBasePath,
jaegerAddress: '',
proxyEnabled: settings.hasOwnProperty('proxyEnabled') ? settings.proxyEnabled : DEFAULT_SETTINGS.proxyEnabled,
proxyAddress: settings.proxyAddress ? settings.proxyAddress : DEFAULT_SETTINGS.proxyAddress,
helmShowAllVersions: settings.hasOwnProperty('helmShowAllVersions')
? settings.helmShowAllVersions
: DEFAULT_SETTINGS.helmShowAllVersions,
};
}
return DEFAULT_SETTINGS;
};
// readTemporaryCredentials returns the temporary stored creedentials for a cloud provider or ODIC from localStorage.
export const readTemporaryCredentials = (
authProvider: TAuthProvider,
):
| undefined
| IClusterAuthProviderAWS
| IClusterAuthProviderAzure
| IClusterAuthProviderDigitalOcean
| IClusterAuthProviderGoogle
| IClusterAuthProviderRancher
| IClusterAuthProviderOIDC => {
const credentials = localStorage.getItem(STORAGE_TEMPORARY_CREDENTIALS);
if (credentials === null) {
return undefined;
} else if (authProvider === 'aws') {
return JSON.parse(credentials) as IClusterAuthProviderAWS;
} else if (authProvider === 'azure') {
return JSON.parse(credentials) as IClusterAuthProviderAzure;
} else if (authProvider === 'digitalocean') {
return JSON.parse(credentials) as IClusterAuthProviderDigitalOcean;
} else if (authProvider === 'google') {
return JSON.parse(credentials) as IClusterAuthProviderGoogle;
} else if (authProvider === 'rancher') {
return JSON.parse(credentials) as IClusterAuthProviderRancher;
} else if (authProvider === 'oidc') {
return JSON.parse(credentials) as IClusterAuthProviderOIDC;
} else {
return undefined;
}
};
// removeCluster removes the saved cluster from localStorage.
export const removeCluster = (): void => {
localStorage.removeItem(STORAGE_CLUSTER);
};
// removeClusters removes the saved clusters from localStorage.
export const removeClusters = (): void => {
localStorage.removeItem(STORAGE_CLUSTERS);
};
// removeTemporaryCredentials removes the temporary saved credentials from localStorage.
export const removeTemporaryCredentials = (): void => {
localStorage.removeItem(STORAGE_TEMPORARY_CREDENTIALS);
};
// saveBookmarks saves the given bookmarks to localStorage.
export const saveBookmarks = (bookmarks: IBookmark[]): void => {
localStorage.setItem(STORAGE_BOOKMARKS, JSON.stringify(bookmarks));
};
// saveCluster saves the given cluster id to localStorage.
export const saveCluster = (cluster: string): void => {
localStorage.setItem(STORAGE_CLUSTER, cluster);
};
// saveClusters saves the given clusters object to localStorage.
export const saveClusters = (clusters: IClusters): void => {
localStorage.setItem(STORAGE_CLUSTERS, JSON.stringify(clusters));
};
// saveSettings saves the users settings to the localStorage.
export const saveSettings = (settings: IAppSettings): void => {
localStorage.setItem(STORAGE_SETTINGS, JSON.stringify(settings));
};
// saveTemporaryCredentials saves the credentials for a cloud provider or OIDC temporary to the localStorage.
export const saveTemporaryCredentials = (
credentials:
| IClusterAuthProviderAWS
| IClusterAuthProviderAzure
| IClusterAuthProviderDigitalOcean
| IClusterAuthProviderGoogle
| IClusterAuthProviderRancher
| IClusterAuthProviderOIDC,
): void => {
localStorage.setItem(STORAGE_TEMPORARY_CREDENTIALS, JSON.stringify(credentials));
}; | the_stack |
import * as anchor from '@project-serum/anchor';
import { Program, Provider } from '@project-serum/anchor';
import {
AccountLayout,
MintLayout,
Token,
TOKEN_PROGRAM_ID,
} from '@solana/spl-token';
import {
Keypair,
PublicKey,
sendAndConfirmTransaction,
SystemProgram,
Transaction,
TransactionSignature,
} from '@solana/web3.js';
import { assert } from 'chai';
import buffer from 'buffer';
import { BN } from '../sdk';
import { ClearingHouse, ClearingHouseUser } from '../sdk/src';
export async function mockOracle(
price: number = 50 * 10e7,
expo = -7
): Promise<PublicKey> {
// default: create a $50 coin oracle
const program = anchor.workspace.Pyth;
anchor.setProvider(
anchor.AnchorProvider.local(undefined, {
commitment: 'confirmed',
preflightCommitment: 'confirmed',
})
);
const priceFeedAddress = await createPriceFeed({
oracleProgram: program,
initPrice: price,
expo: expo,
});
const feedData = await getFeedData(program, priceFeedAddress);
if (feedData.price !== price) {
console.log('mockOracle precision error:', feedData.price, '!=', price);
}
assert.ok(Math.abs(feedData.price - price) < 1e-10);
return priceFeedAddress;
}
export async function mockUSDCMint(provider: Provider): Promise<Keypair> {
const fakeUSDCMint = anchor.web3.Keypair.generate();
const createUSDCMintAccountIx = SystemProgram.createAccount({
fromPubkey: provider.wallet.publicKey,
newAccountPubkey: fakeUSDCMint.publicKey,
lamports: await Token.getMinBalanceRentForExemptMint(provider.connection),
space: MintLayout.span,
programId: TOKEN_PROGRAM_ID,
});
const initCollateralMintIx = Token.createInitMintInstruction(
TOKEN_PROGRAM_ID,
fakeUSDCMint.publicKey,
6,
provider.wallet.publicKey,
null
);
const fakeUSDCTx = new Transaction();
fakeUSDCTx.add(createUSDCMintAccountIx);
fakeUSDCTx.add(initCollateralMintIx);
await sendAndConfirmTransaction(
provider.connection,
fakeUSDCTx,
// @ts-ignore
[provider.wallet.payer, fakeUSDCMint],
{
skipPreflight: false,
commitment: 'recent',
preflightCommitment: 'recent',
}
);
return fakeUSDCMint;
}
export async function mockUserUSDCAccount(
fakeUSDCMint: Keypair,
usdcMintAmount: BN,
provider: Provider,
owner?: PublicKey
): Promise<Keypair> {
const userUSDCAccount = anchor.web3.Keypair.generate();
const fakeUSDCTx = new Transaction();
if (owner === undefined) {
owner = provider.wallet.publicKey;
}
const createUSDCTokenAccountIx = SystemProgram.createAccount({
fromPubkey: provider.wallet.publicKey,
newAccountPubkey: userUSDCAccount.publicKey,
lamports: await Token.getMinBalanceRentForExemptAccount(
provider.connection
),
space: AccountLayout.span,
programId: TOKEN_PROGRAM_ID,
});
fakeUSDCTx.add(createUSDCTokenAccountIx);
const initUSDCTokenAccountIx = Token.createInitAccountInstruction(
TOKEN_PROGRAM_ID,
fakeUSDCMint.publicKey,
userUSDCAccount.publicKey,
owner
);
fakeUSDCTx.add(initUSDCTokenAccountIx);
const mintToUserAccountTx = await Token.createMintToInstruction(
TOKEN_PROGRAM_ID,
fakeUSDCMint.publicKey,
userUSDCAccount.publicKey,
provider.wallet.publicKey,
[],
usdcMintAmount.toNumber()
);
fakeUSDCTx.add(mintToUserAccountTx);
const _fakeUSDCTxResult = await sendAndConfirmTransaction(
provider.connection,
fakeUSDCTx,
// @ts-ignore
[provider.wallet.payer, userUSDCAccount],
{
skipPreflight: false,
commitment: 'recent',
preflightCommitment: 'recent',
}
);
return userUSDCAccount;
}
export async function mintToInsuranceFund(
chInsuranceAccount: Keypair,
fakeUSDCMint: Keypair,
amount: BN,
provider: Provider
): Promise<TransactionSignature> {
const mintToUserAccountTx = await Token.createMintToInstruction(
TOKEN_PROGRAM_ID,
fakeUSDCMint.publicKey,
chInsuranceAccount.publicKey,
provider.wallet.publicKey,
[],
amount.toNumber()
);
const fakeUSDCTx = new Transaction();
fakeUSDCTx.add(mintToUserAccountTx);
return await sendAndConfirmTransaction(
provider.connection,
fakeUSDCTx,
// @ts-ignore
[provider.wallet.payer],
{
skipPreflight: false,
commitment: 'recent',
preflightCommitment: 'recent',
}
);
}
export async function initUserAccounts(
NUM_USERS: number,
usdcMint: Keypair,
usdcAmount: BN,
provider: Provider
) {
const user_keys = [];
const userUSDCAccounts = [];
const clearingHouses = [];
const userAccountInfos = [];
let userAccountPublicKey: PublicKey;
for (let i = 0; i < NUM_USERS; i++) {
console.log('user', i, 'initialize');
const owner = anchor.web3.Keypair.generate();
const ownerWallet = new anchor.Wallet(owner);
await provider.connection.requestAirdrop(ownerWallet.publicKey, 100000000);
const newUserAcct = await mockUserUSDCAccount(
usdcMint,
usdcAmount,
provider,
ownerWallet.publicKey
);
const chProgram = anchor.workspace.ClearingHouse as anchor.Program; // this.program-ify
const clearingHouse1 = ClearingHouse.from(
provider.connection,
//@ts-ignore
ownerWallet,
chProgram.programId,
{
commitment: 'confirmed',
}
);
// await clearingHouse1.initialize(usdcMint.publicKey, false);
await clearingHouse1.subscribe();
userUSDCAccounts.push(newUserAcct);
clearingHouses.push(clearingHouse1);
// var last_idx = userUSDCAccounts.length - 1;
// try {
[, userAccountPublicKey] =
await clearingHouse1.initializeUserAccountAndDepositCollateral(
// marketPublicKey,
usdcAmount,
newUserAcct.publicKey
);
// const userAccount = 0;
const userAccount = ClearingHouseUser.from(
clearingHouse1,
ownerWallet.publicKey
);
await userAccount.subscribe();
userAccountInfos.push(userAccount);
// } catch (e) {
// assert(true);
// }
user_keys.push(userAccountPublicKey);
}
return [userUSDCAccounts, user_keys, clearingHouses, userAccountInfos];
}
const empty32Buffer = buffer.Buffer.alloc(32);
const PKorNull = (data) =>
data.equals(empty32Buffer) ? null : new anchor.web3.PublicKey(data);
export const createPriceFeed = async ({
oracleProgram,
initPrice,
confidence = undefined,
expo = -4,
}: {
oracleProgram: Program;
initPrice: number;
confidence?: number;
expo?: number;
}): Promise<PublicKey> => {
const conf = confidence || new BN((initPrice / 10) * 10 ** -expo);
const collateralTokenFeed = new anchor.web3.Account();
await oracleProgram.rpc.initialize(
new BN(initPrice * 10 ** -expo),
expo,
conf,
{
accounts: { price: collateralTokenFeed.publicKey },
signers: [collateralTokenFeed],
instructions: [
anchor.web3.SystemProgram.createAccount({
fromPubkey: oracleProgram.provider.wallet.publicKey,
newAccountPubkey: collateralTokenFeed.publicKey,
space: 3312,
lamports:
await oracleProgram.provider.connection.getMinimumBalanceForRentExemption(
3312
),
programId: oracleProgram.programId,
}),
],
}
);
return collateralTokenFeed.publicKey;
};
export const setFeedPrice = async (
oracleProgram: Program,
newPrice: number,
priceFeed: PublicKey
) => {
const info = await oracleProgram.provider.connection.getAccountInfo(
priceFeed
);
const data = parsePriceData(info.data);
await oracleProgram.rpc.setPrice(new BN(newPrice * 10 ** -data.exponent), {
accounts: { price: priceFeed },
});
};
export const setFeedTwap = async (
oracleProgram: Program,
newTwap: number,
priceFeed: PublicKey
) => {
const info = await oracleProgram.provider.connection.getAccountInfo(
priceFeed
);
const data = parsePriceData(info.data);
await oracleProgram.rpc.setTwap(new BN(newTwap * 10 ** -data.exponent), {
accounts: { price: priceFeed },
});
};
export const getFeedData = async (
oracleProgram: Program,
priceFeed: PublicKey
) => {
const info = await oracleProgram.provider.connection.getAccountInfo(
priceFeed
);
return parsePriceData(info.data);
};
// https://github.com/nodejs/node/blob/v14.17.0/lib/internal/errors.js#L758
const ERR_BUFFER_OUT_OF_BOUNDS = () =>
new Error('Attempt to access memory outside buffer bounds');
// https://github.com/nodejs/node/blob/v14.17.0/lib/internal/errors.js#L968
const ERR_INVALID_ARG_TYPE = (name, expected, actual) =>
new Error(
`The "${name}" argument must be of type ${expected}. Received ${actual}`
);
// https://github.com/nodejs/node/blob/v14.17.0/lib/internal/errors.js#L1262
const ERR_OUT_OF_RANGE = (str, range, received) =>
new Error(
`The value of "${str} is out of range. It must be ${range}. Received ${received}`
);
// https://github.com/nodejs/node/blob/v14.17.0/lib/internal/validators.js#L127-L130
function validateNumber(value, name) {
if (typeof value !== 'number')
throw ERR_INVALID_ARG_TYPE(name, 'number', value);
}
// https://github.com/nodejs/node/blob/v14.17.0/lib/internal/buffer.js#L68-L80
function boundsError(value, length) {
if (Math.floor(value) !== value) {
validateNumber(value, 'offset');
throw ERR_OUT_OF_RANGE('offset', 'an integer', value);
}
if (length < 0) throw ERR_BUFFER_OUT_OF_BOUNDS();
throw ERR_OUT_OF_RANGE('offset', `>= 0 and <= ${length}`, value);
}
function readBigInt64LE(buffer, offset = 0) {
validateNumber(offset, 'offset');
const first = buffer[offset];
const last = buffer[offset + 7];
if (first === undefined || last === undefined)
boundsError(offset, buffer.length - 8);
const val =
buffer[offset + 4] +
buffer[offset + 5] * 2 ** 8 +
buffer[offset + 6] * 2 ** 16 +
(last << 24); // Overflow
return (
(BigInt(val) << BigInt(32)) +
BigInt(
first +
buffer[++offset] * 2 ** 8 +
buffer[++offset] * 2 ** 16 +
buffer[++offset] * 2 ** 24
)
);
}
// https://github.com/nodejs/node/blob/v14.17.0/lib/internal/buffer.js#L89-L107
function readBigUInt64LE(buffer, offset = 0) {
validateNumber(offset, 'offset');
const first = buffer[offset];
const last = buffer[offset + 7];
if (first === undefined || last === undefined)
boundsError(offset, buffer.length - 8);
const lo =
first +
buffer[++offset] * 2 ** 8 +
buffer[++offset] * 2 ** 16 +
buffer[++offset] * 2 ** 24;
const hi =
buffer[++offset] +
buffer[++offset] * 2 ** 8 +
buffer[++offset] * 2 ** 16 +
last * 2 ** 24;
return BigInt(lo) + (BigInt(hi) << BigInt(32)); // tslint:disable-line:no-bitwise
}
const parsePriceData = (data) => {
// Pyth magic number.
const magic = data.readUInt32LE(0);
// Program version.
const version = data.readUInt32LE(4);
// Account type.
const type = data.readUInt32LE(8);
// Price account size.
const size = data.readUInt32LE(12);
// Price or calculation type.
const priceType = data.readUInt32LE(16);
// Price exponent.
const exponent = data.readInt32LE(20);
// Number of component prices.
const numComponentPrices = data.readUInt32LE(24);
// unused
// const unused = accountInfo.data.readUInt32LE(28)
// Currently accumulating price slot.
const currentSlot = readBigUInt64LE(data, 32);
// Valid on-chain slot of aggregate price.
const validSlot = readBigUInt64LE(data, 40);
// Time-weighted average price.
const twapComponent = readBigInt64LE(data, 48);
const twap = Number(twapComponent) * 10 ** exponent;
// Annualized price volatility.
const avolComponent = readBigUInt64LE(data, 56);
const avol = Number(avolComponent) * 10 ** exponent;
// Space for future derived values.
const drv0Component = readBigInt64LE(data, 64);
const drv0 = Number(drv0Component) * 10 ** exponent;
const drv1Component = readBigInt64LE(data, 72);
const drv1 = Number(drv1Component) * 10 ** exponent;
const drv2Component = readBigInt64LE(data, 80);
const drv2 = Number(drv2Component) * 10 ** exponent;
const drv3Component = readBigInt64LE(data, 88);
const drv3 = Number(drv3Component) * 10 ** exponent;
const drv4Component = readBigInt64LE(data, 96);
const drv4 = Number(drv4Component) * 10 ** exponent;
const drv5Component = readBigInt64LE(data, 104);
const drv5 = Number(drv5Component) * 10 ** exponent;
// Product id / reference account.
const productAccountKey = new anchor.web3.PublicKey(data.slice(112, 144));
// Next price account in list.
const nextPriceAccountKey = PKorNull(data.slice(144, 176));
// Aggregate price updater.
const aggregatePriceUpdaterAccountKey = new anchor.web3.PublicKey(
data.slice(176, 208)
);
const aggregatePriceInfo = parsePriceInfo(data.slice(208, 240), exponent);
// Price components - up to 32.
const priceComponents = [];
let offset = 240;
let shouldContinue = true;
while (offset < data.length && shouldContinue) {
const publisher = PKorNull(data.slice(offset, offset + 32));
offset += 32;
if (publisher) {
const aggregate = parsePriceInfo(
data.slice(offset, offset + 32),
exponent
);
offset += 32;
const latest = parsePriceInfo(data.slice(offset, offset + 32), exponent);
offset += 32;
priceComponents.push({ publisher, aggregate, latest });
} else {
shouldContinue = false;
}
}
return Object.assign(
Object.assign(
{
magic,
version,
type,
size,
priceType,
exponent,
numComponentPrices,
currentSlot,
validSlot,
twapComponent,
twap,
avolComponent,
avol,
drv0Component,
drv0,
drv1Component,
drv1,
drv2Component,
drv2,
drv3Component,
drv3,
drv4Component,
drv4,
drv5Component,
drv5,
productAccountKey,
nextPriceAccountKey,
aggregatePriceUpdaterAccountKey,
},
aggregatePriceInfo
),
{ priceComponents }
);
};
const _parseProductData = (data) => {
// Pyth magic number.
const magic = data.readUInt32LE(0);
// Program version.
const version = data.readUInt32LE(4);
// Account type.
const type = data.readUInt32LE(8);
// Price account size.
const size = data.readUInt32LE(12);
// First price account in list.
const priceAccountBytes = data.slice(16, 48);
const priceAccountKey = new anchor.web3.PublicKey(priceAccountBytes);
const product = {};
let idx = 48;
while (idx < data.length) {
const keyLength = data[idx];
idx++;
if (keyLength) {
const key = data.slice(idx, idx + keyLength).toString();
idx += keyLength;
const valueLength = data[idx];
idx++;
const value = data.slice(idx, idx + valueLength).toString();
idx += valueLength;
product[key] = value;
}
}
return { magic, version, type, size, priceAccountKey, product };
};
const parsePriceInfo = (data, exponent) => {
// Aggregate price.
const priceComponent = data.readBigUInt64LE(0);
const price = Number(priceComponent) * 10 ** exponent;
// Aggregate confidence.
const confidenceComponent = data.readBigUInt64LE(8);
const confidence = Number(confidenceComponent) * 10 ** exponent;
// Aggregate status.
const status = data.readUInt32LE(16);
// Aggregate corporate action.
const corporateAction = data.readUInt32LE(20);
// Aggregate publish slot.
const publishSlot = data.readBigUInt64LE(24);
return {
priceComponent,
price,
confidenceComponent,
confidence,
status,
corporateAction,
publishSlot,
};
}; | the_stack |
import {saveAs} from 'file-saver';
import React, {FormEvent, useEffect, useRef, useState} from "react";
import {BrowserQRCodeReader, IScannerControls} from "@zxing/browser";
import {Result} from "@zxing/library";
import {useTranslation} from 'next-i18next';
import Card from "./Card";
import Alert from "./Alert";
import Check from './Check';
import {PayloadBody} from "../src/payload";
import {getPayloadBodyFromFile, processSHCCode} from "../src/process";
import {PassData} from "../src/pass";
import {Photo} from "../src/photo";
import {isIOS, isMacOs, isAndroid, isSafari, osVersion, getUA, browserName, browserVersion} from 'react-device-detect';
import * as Sentry from '@sentry/react';
import Bullet from './Bullet';
import { GPayData } from '../src/gpay';
import Dropdown from './Dropdown';
import { debug } from 'webpack';
const getTheme = () => {
if (typeof window !== 'undefined' &&
window.localStorage) {
const storedPrefs =
window.localStorage.getItem('color-theme')
if (typeof storedPrefs === 'string') {
return storedPrefs
}
const userMedia =
window.matchMedia('(prefers-color-scheme: dark)')
if (userMedia.matches) {
return 'dark'
}
}
// If you want to use light theme as the default,
// return "light" instead
return 'light'
}
const options = [
{ label: 'Alberta', value: 'https://covidrecords.alberta.ca/form'},
{ label: 'British Columbia', value: 'https://www.healthgateway.gov.bc.ca/vaccinecard'},
{ label: 'Canadian Armed Forces', value: 'https://www.canada.ca/en/department-national-defence/campaigns/covid-19/covid-19-vaccines-for-canadian-armed-forces-members.html#proof'},
{ label: 'Manitoba', value: 'https://www.gov.mb.ca/covid19/vaccine/immunizationrecord/residents.html'},
{ label: 'New Brunswick', value: 'https://myhealth.gnb.ca/'},
{ label: 'Newfoundland and Labrador', value: 'https://vaccineportal.nlchi.nl.ca/'},
{ label: 'Northwest Territories', value: 'https://www.gov.nt.ca/covid-19/en/request/proof-vaccination'},
{ label: 'Nunavut', value: 'https://gov.nu.ca/sites/default/files/covid_proof_of_vaccination_qa_for_nunavut_october_14_2021.pdf'},
{ label: 'Nova Scotia', value: 'https://novascotia.flow.canimmunize.ca/en/portal'},
{ label: 'Ontario', value: 'https://covid19.ontariohealth.ca'},
{ label: 'Prince Edward Island', value: 'https://pei.flow.canimmunize.ca/en/portal'},
{ label: 'Québec', value: 'https://covid19.quebec.ca/PreuveVaccinale'},
{ label: 'Saskatchewan', value: 'https://services.saskatchewan.ca/#/login'},
{ label: 'Yukon', value: 'https://service.yukon.ca/forms/en/get-covid19-proof-of-vaccination'},
]
function Form(): JSX.Element {
const {t} = useTranslation(['index', 'errors', 'common']);
// Whether camera is open or not
const [isCameraOpen, setIsCameraOpen] = useState<boolean>(false);
// Currently selected dose
const [selectedDose, setSelectedDose] = useState<number>(2);
// Global camera controls
const [globalControls, setGlobalControls] = useState<IScannerControls>(undefined);
// Currently selected QR Code / File. Only one of them is set.
const [qrCode, setQrCode] = useState<Result>(undefined);
const [file, setFile] = useState<File>(undefined);
const [file2, setFile2] = useState<File>(undefined);
const [payloadBody, setPayloadBody] = useState<PayloadBody>(undefined);
const [saveLoading, setSaveLoading] = useState<boolean>(false);
const [fileLoading, setFileLoading] = useState<boolean>(false);
const [file2Loading, setFile2Loading] = useState<boolean>(false);
const [generated, setGenerated] = useState<boolean>(false); // this flag represents the file has been used to generate a pass
const [isDisabledAppleWallet, setIsDisabledAppleWallet] = useState<boolean>(false);
const [isDisabledGooglePay, setIsDisabledGooglePay] = useState<boolean>(false);
const [isDisabledFastLink, setIsDisabledFastLink] = useState<boolean>(true);
const [addErrorMessages, _setAddErrorMessages] = useState<Array<string>>([]);
const [fileErrorMessages, _setFileErrorMessages] = useState<Array<string>>([]);
const [showDoseOption, setShowDoseOption] = useState<boolean>(false);
// const [warningMessages, _setWarningMessages] = useState<Array<string>>([]);
const hitcountHost = 'https://stats.vaccine-ontario.ca';
// Check if there is a translation and replace message accordingly
const setAddErrorMessage = (message: string) => {
if (!message) {
return;
}
const translation = t('errors:'.concat(message));
_setAddErrorMessages(Array.from(new Set([...addErrorMessages, translation !== message ? translation : message])));
};
const setFileErrorMessage = (message: string) => {
if (!message) {
return;
}
const translation = t('errors:'.concat(message));
_setFileErrorMessages(Array.from(new Set([...addErrorMessages, translation !== message ? translation : message])));
};
const deleteAddErrorMessage = (message: string) =>{
_setAddErrorMessages(addErrorMessages.filter(item => item !== message))
}
// File Input ref
const inputFile = useRef<HTMLInputElement>(undefined)
const inputFile2 = useRef<HTMLInputElement>(undefined)
// Add event listener to listen for file change events
useEffect(() => {
let payloadBody;
if (inputFile && inputFile.current) {
inputFile.current.addEventListener('change', async () => {
let selectedFile = inputFile.current.files[0];
if (selectedFile) {
setFileLoading(true);
setQrCode(undefined);
setPayloadBody(undefined);
setFile(undefined);
setShowDoseOption(false);
setGenerated(false);
deleteAddErrorMessage(t('errors:'.concat('noFileOrQrCode')));
_setFileErrorMessages([]);
checkBrowserType();
payloadBody = await getPayload(selectedFile);
await renderPhoto(payloadBody);
}
});
}
if (inputFile2 && inputFile2.current) {
inputFile2.current.addEventListener('change', async () => {
let selectedFile2 = inputFile2.current.files[0];
if (selectedFile2) {
setFile2Loading(true);
setFile2(selectedFile2);
await storeFileToLocalStorageBase64('extra', selectedFile2);
payloadBody.extraUrl = 'extra';
setFile2Loading(false);
}
});
}
checkBrowserType();
}, [inputFile, inputFile2])
async function storeFileToLocalStorageBase64(key: string, file: File) {
if (window.localStorage && file.type.includes('application/pdf')) {
// https://stackoverflow.com/a/56738510/2789065
console.log('storing buffer ' + file.type);
const buffer = Buffer.from(await new Response(file).arrayBuffer());
let dataUrl = `data:${file.type};base64,${buffer.toString("base64")}`;
localStorage.setItem(key, dataUrl);
}
}
async function getPayload(file) : Promise<PayloadBody> {
try {
const payload = await getPayloadBodyFromFile(file);
if (file2) {
payload.extraUrl = file2.name;
}
setPayloadBody(payload);
setFileLoading(false);
setFile(file);
if (payload.rawData.length == 0) {
if (Object.keys(payload.receipts).length === 1) {
setSelectedDose(parseInt(Object.keys(payload.receipts)[0]));
} else {
setShowDoseOption(true);
}
}
return Promise.resolve(payload);
} catch (e) {
setFile(file);
setFileLoading(false);
if (e) {
console.error(e);
// Don't report known errors to Sentry
if (!e.message.includes('invalidFileType') &&
!e.message.includes('No SHC QR code found')) {
Sentry.captureException(e);
}
if (e.message != undefined) {
setFileErrorMessage(e.message);
} else {
setFileErrorMessage('unableToContinue');
}
} else {
setFileErrorMessage('unexpected');
}
}
}
// Show file Dialog
async function showFileDialog() {
hideCameraView();
// Clear out any currently-selected files
inputFile.current.value = '';
// Hide our existing pass image
document.getElementById('shc-pass-image').hidden = true;
document.getElementById('shc-image-header').hidden = true;
inputFile.current.click();
}
async function showFile2Dialog() {
inputFile2.current.click();
}
async function goToFAQ(e : any) {
e.preventDefault();
window.location.href = '/faq';
}
// Hide camera view
async function hideCameraView() {
if (globalControls) {
globalControls.stop();
}
setIsCameraOpen(false);
_setFileErrorMessages([]);
}
// Show camera view
async function showCameraView() {
// Create new QR Code Reader
const codeReader = new BrowserQRCodeReader();
// Needs to be called before any camera can be accessed
let deviceList: MediaDeviceInfo[];
try {
deviceList = await BrowserQRCodeReader.listVideoInputDevices();
} catch (e) {
setFileErrorMessage('noCameraAccess');
return;
}
// Check if camera device is present
if (deviceList.length == 0) {
setFileErrorMessage("noCameraFound");
return;
}
// Get preview Element to show camera stream
const previewElem: HTMLVideoElement = document.querySelector('#cameraPreview');
// Set Global controls
setGlobalControls(
// Start decoding from video device
await codeReader.decodeFromVideoDevice(undefined,
previewElem,
async (result, error, controls) => {
if (result) {
const qrCode = result.getText();
// Check if this was a valid SHC QR code - if it was not, display an error
if (!qrCode.startsWith('shc:/')) {
setFileErrorMessage(t('invalidSHC'));
} else {
_setFileErrorMessages([]);
setQrCode(result);
setFile(undefined);
setPayloadBody(undefined);
setShowDoseOption(false);
setGenerated(false);
checkBrowserType();
const payloadBody = await processSHCCode(qrCode);
setPayloadBody(payloadBody);
controls.stop();
// Reset
setGlobalControls(undefined);
setIsCameraOpen(false);
await renderPhoto(payloadBody);
}
}
if (error) {
setFileErrorMessage(error.message);
}
}
)
);
// Hide our existing pass image
document.getElementById('shc-pass-image').hidden = true;
document.getElementById('shc-image-header').hidden = true;
setQrCode(undefined);
setPayloadBody(undefined);
setFile(undefined);
setShowDoseOption(false);
setGenerated(false);
_setFileErrorMessages([]);
setIsCameraOpen(true);
}
async function incrementCount() {
try {
if (typeof generated == undefined || !generated) {
const request = `${hitcountHost}/count?url=pass.vaccine-ontario.ca`;
//console.log(request);
let response = await fetch(request);
//console.log(response);
setGenerated(true);
}
} catch (e) {
// Fail silently - we shouldn't blow up receipt processing because we couldn't increment our counter
console.error(e);
//return Promise.reject(e);
}
}
// Add Pass to wallet
async function addToWallet(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setSaveLoading(true);
if (!file && !qrCode) {
setAddErrorMessage('noFileOrQrCode')
setSaveLoading(false);
return;
}
try {
if (payloadBody) {
const selectedReceipt = payloadBody.shcReceipt;
const filenameDetails = selectedReceipt.cardOrigin.replace(' ', '-');
const passName = selectedReceipt.name.replace(' ', '-');
const covidPassFilename = `grassroots-receipt-${passName}-${filenameDetails}.pkpass`;
const pass = await PassData.generatePass(payloadBody, selectedDose);
const passBlob = new Blob([pass], {type: "application/vnd.apple.pkpass"});
await incrementCount();
if (isIOS && isSafari) {
try {
localStorage.setItem(`receipt-${payloadBody.serialNumber}`, payloadBody.dataUrl);
console.log(`receipt-${payloadBody.serialNumber} saved`);
} catch (e) {
// clear old receipts and retry
console.info('clearing old receipts');
localStorage.clear();
localStorage.setItem(`receipt-${payloadBody.serialNumber}`, payloadBody.dataUrl);
}
}
saveAs(passBlob, covidPassFilename);
setSaveLoading(false);
}
} catch (e) {
if (e) {
console.error(e);
Sentry.captureException(e);
if (e.message) {
setAddErrorMessage(e.message);
} else {
setAddErrorMessage('unableToContinue');
}
} else {
setAddErrorMessage('unexpected');
}
setSaveLoading(false);
}
}
// Add Pass to Google Pay
async function addToGooglePay(e : any) {
e.preventDefault();
setSaveLoading(true);
if (!file && !qrCode) {
setAddErrorMessage('noFileOrQrCode')
setSaveLoading(false);
return;
}
try {
if (payloadBody) {
console.log('> increment count');
await incrementCount();
console.log('> generatePass');
const jwt = await GPayData.generatePass(payloadBody, selectedDose);
if (payloadBody.dataUrl) {
try {
localStorage.setItem(`receipt-${payloadBody.serialNumber}`, payloadBody.dataUrl);
console.log(`receipt-${payloadBody.serialNumber} saved`);
} catch (e) {
if (e.message.includes('quota')) {
// clear old receipts and retry
console.info('clearing old receipts');
localStorage.clear();
localStorage.setItem(`receipt-${payloadBody.serialNumber}`, payloadBody.dataUrl);
}
}
}
const newUrl = `https://pay.google.com/gp/v/save/${jwt}`;
console.log('> redirect to save Google Pass');
setSaveLoading(false);
window.location.href = newUrl;
}
} catch (e) {
if (e) {
console.error(e);
Sentry.captureException(e);
if (e.message) {
setAddErrorMessage(e.message);
} else {
setAddErrorMessage("Unable to continue.");
}
} else {
setAddErrorMessage("Unexpected error. Sorry.");
}
setSaveLoading(false);
}
}
async function renderPhoto(payloadBody : PayloadBody, shouldRegister = true) {
console.log('renderPhoto');
if (!payloadBody) {
console.log('no payload body');
setAddErrorMessage('noFileOrQrCode');
return;
}
try {
console.log('beginning render');
if (payloadBody.rawData.length > 0) {
// This is an SHC receipt, so do our SHC thing
// need to clean up first
if (document.getElementById('shc-qrcode').hasChildNodes()) {
document.getElementById('shc-qrcode').firstChild.remove();
}
document.getElementById('shc-pass-image').hidden = false;
document.getElementById('shc-image-header').hidden = false;
console.log('made canvas visible');
await Photo.generateSHCPass(payloadBody, shouldRegister);
console.log('generated blob');
}
console.log('done photo render');
} catch (e) {
Sentry.captureException(e);
setAddErrorMessage(e.message);
}
}
async function refreshPhoto() {
await renderPhoto(payloadBody, false);
}
const setDose = (e : any) => {
setSelectedDose(e.target.value);
}
function checkBrowserType() {
// if (isIPad13) {
// setAddErrorMessage('Sorry. Apple does not support the use of Wallet on iPad. Please use iPhone/Safari.');
// setIsDisabledAppleWallet(true);
// }
// if (!isSafari && !isChrome) {
// setAddErrorMessage('Sorry. Apple Wallet pass can be added using Safari or Chrome only.');
// setIsDisabledAppleWallet(true);
// }
const uaIsiOS15 = getUA.includes('15_');
if (isIOS && ((!osVersion.startsWith('15')) && !uaIsiOS15)) {
const message = `Not iOS15 error: osVersion=${osVersion} UA=${getUA}`;
console.warn(message);
Sentry.captureMessage(message);
setAddErrorMessage(`Sorry, iOS 15+ is needed for the Apple Wallet functionality to work with Smart Health Card (detected iOS ${osVersion}, browser ${browserName} ${browserVersion})`);
setIsDisabledAppleWallet(true);
return;
}
//TODO: feature flagging
// if (isIOS || isMacOs) {
// setIsDisabledFastLink(false);
// }
console.log(osVersion);
if (isMacOs) {
setAddErrorMessage('iOSReminder')
return;
}
if (isIOS && !isSafari) {
setAddErrorMessage('safariSupportOnly');
setIsDisabledAppleWallet(true);
return;
}
if (isAndroid) {
const majorVersion = parseInt(osVersion.split('.')[0]);
console.log(`majorVersion=${majorVersion}`);
if (majorVersion >= 8) {
setIsDisabledGooglePay(false);
} else {
setAddErrorMessage('androidVersionError')
setIsDisabledGooglePay(true);
}
} else {
if (window.location.hostname !== 'localhost') {
setIsDisabledGooglePay(true);
}
}
}
return (
<div>
<form className="space-y-5" id="form" onSubmit={addToWallet}>
<Card step="1" heading={t('index:downloadReceipt')} content={
<div className="space-y-5">
<p>{t('index:visit')}</p>
<p><b>{t('index:reminderNotToRepeat')}</b></p>
<Dropdown label="Select Your Province" options={options} />
</div>
}/>
<Card step="2" heading={t('index:selectCertificate')} content={
<div className="space-y-5">
<p>{t('index:selectCertificateDescription')}</p>
<div className="grid grid-cols-1 md:grid-cols-2 gap-5 items-center justify-start">
<button
type="button"
onClick={showFileDialog}
className="h-20 bg-green-600 hover:bg-gray-700 text-white font-semibold rounded-md">
{t('index:openFile')}
</button>
<button
type="button"
onClick={isCameraOpen ? hideCameraView : showCameraView}
className="h-20 bg-green-600 hover:bg-gray-700 text-white font-semibold rounded-md">
{isCameraOpen ? t('index:stopCamera') : t('index:startCamera')}
</button>
<div id="spin" className={fileLoading ? undefined : "hidden"}>
<svg className="animate-spin h-5 w-5 ml-4" viewBox="0 0 24 24">
<circle className="opacity-0" cx="12" cy="12" r="10" stroke="currentColor"
strokeWidth="4"/>
<path className="opacity-75" fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"/>
</svg>
</div>
</div>
<video id="cameraPreview"
className={`${isCameraOpen ? undefined : "hidden"} rounded-md w-full`}/>
<input type='file'
id='file'
accept="application/pdf,.png,.jpg,.jpeg,.gif,.webp"
ref={inputFile}
style={{display: 'none'}}
/>
{(qrCode || file) &&
<div className="flex items-center space-x-1">
<svg className="h-4 w-4 text-green-600" fill="none" viewBox="0 0 24 24"
stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 5l7 7-7 7"/>
</svg>
<span className="w-full truncate">
{
qrCode && t('index:foundQrCode')
}
{
file && file.name
}
</span>
</div>
}
{fileErrorMessages.map((message, i) =>
<Alert message={message} key={'error-' + i} type="error" />
)}
</div>
}/>
{!isDisabledFastLink && <Card step="3" heading='(Optional) Link a photo to your wallet pass' content={
<div className="space-y-5">
<p>The photo will be saved in your browser (as local & private storage). Your wallet pass will have a link to it for quick showing.</p>
<div className="grid grid-cols-1 md:grid-cols-2 gap-5 items-center justify-start">
<button
type="button"
onClick={showFile2Dialog}
className="h-20 bg-green-600 hover:bg-gray-700 text-white font-semibold rounded-md">
{t('index:openFile')}
</button>
<div id="spin2" className={file2Loading ? undefined : "hidden"}>
<svg className="animate-spin h-5 w-5 ml-4" viewBox="0 0 24 24">
<circle className="opacity-0" cx="12" cy="12" r="10" stroke="currentColor"
strokeWidth="4"/>
<path className="opacity-75" fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"/>
</svg>
</div>
</div>
<input type='file'
id='file2'
accept="application/pdf,.png,.jpg,.jpeg,.gif,.webp"
ref={inputFile2}
style={{display: 'none'}}
/>
{(file2) &&
<div className="flex items-center space-x-1">
<svg className="h-4 w-4 text-green-600" fill="none" viewBox="0 0 24 24"
stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 5l7 7-7 7"/>
</svg>
<span className="w-full truncate">
{
file2 && file2.name
}
</span>
</div>
}
{fileErrorMessages.map((message, i) =>
<Alert message={message} key={'error-' + i} type="error" />
)}
</div>
}/>
}
{showDoseOption && <Card step={isDisabledFastLink ? '4': '3'} heading={'Choose dose number'} content={
<div className="space-y-5">
<p>
{t('index:formatChange')}
<br /><br />
{t('index:saveMultiple')}
</p>
<link href="https://cdn.jsdelivr.net/npm/@tailwindcss/custom-forms@0.2.1/dist/custom-forms.css" rel="stylesheet"/>
<div className="block">
<div className="mt-2">
{payloadBody && Object.keys(payloadBody.receipts).map(key =>
<div key={key}>
<label className="inline-flex items-center">
<input onChange={setDose} type="radio" className="form-radio" name="radio" value={key} checked={parseInt(key) == selectedDose} />
<span className="ml-2">Dose {key}</span>
</label>
</div>
)}
</div>
</div>
</div>
} />}
<Card step={showDoseOption ? (!isDisabledFastLink ? '5' : '4') : (!isDisabledFastLink ? '4': '3')} heading={t('index:addToWalletHeader')} content={
<div className="space-y-5">
<div>
<ul className="list-none">
<Check text={t('createdOnDevice')}/>
<Check text={t('piiNotSent')}/>
<Check text={t('openSourceTransparent')}/>
</ul>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-5 items-center justify-items-stretch">
<button disabled={saveLoading || isDisabledAppleWallet} id="download" type="submit" value='applewallet' name='action'
className={'outline-apple rounded-md ' + ((!payloadBody || saveLoading || isDisabledAppleWallet)? 'bg-gray-300 cursor-not-allowed':'bg-black cursor-pointer')}>
<div className="flex justify-center">
<img style={{height: 40}} src="apple_wallet.svg" alt={t('index:addToWallet')}/>
</div>
</button>
<button id="addToGooglePay" type="button" disabled={saveLoading || isDisabledGooglePay} value='gpay' name='action' onClick={addToGooglePay}
className={'rounded-md ' + ((!payloadBody || saveLoading || isDisabledGooglePay)? 'bg-gray-300 cursor-not-allowed':'bg-black cursor-pointer')}>
<div className="flex justify-center">
<img style={{height: 40}} src="gpay_light.svg" alt={t('index:addToGooglePay')}/>
</div>
</button>
<div id="spin" className={saveLoading ? undefined : "hidden"}>
<svg className="animate-spin h-5 w-5 ml-4" viewBox="0 0 24 24">
<circle className="opacity-0" cx="12" cy="12" r="10" stroke="currentColor"
strokeWidth="4"/>
<path className="opacity-75" fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"/>
</svg>
</div>
</div>
{addErrorMessages.map((message, i) =>
<Alert message={message} key={'error-' + i} type="error" />
)}
<div id="shc-image-header" hidden>
<p><b>{t('index:saveVaccineCard')}</b></p>
<p>{t('index:refreshNote')}</p>
<br />
<button id="renderPhoto" type="button" disabled={saveLoading || !payloadBody} value='renderPhoto' name='action' onClick={refreshPhoto}
className=" bg-green-600 py-2 px-3 text-white font-semibold rounded-md disabled:bg-gray-400">
{t('index:refreshButton')}
</button>
</div>
<div id="shc-pass-image" style={{backgroundColor: "white", color: "black", fontFamily: 'Arial', fontSize: 10, width: '350px', padding: '10px', border: '1px solid', margin: '0px'}} hidden>
<table style={{verticalAlign: "middle"}}>
<tbody>
<tr>
<td><img src='shield-black.svg' width='50' height='50' /></td>
<td style={{fontSize: 20, width: 280}}>
<span style={{marginLeft: '11px', whiteSpace: 'nowrap'}}><b>COVID-19 Vaccination Card</b></span><br/>
<span style={{marginLeft: '11px'}}><b id='shc-card-origin'></b></span>
</td>
</tr>
</tbody>
</table>
<br/>
<div style={{fontSize:14, textAlign: 'center'}}>
<span id='shc-card-name' ></span> (<span id='shc-card-dob'></span>)
</div>
<br/>
<table style={{textAlign: "center", width: "100%"}}>
<tbody>
<tr>
<td id='shc-card-vaccine-name-1'></td> <td id='shc-card-vaccine-name-2'></td>
</tr>
<tr>
<td id='shc-card-vaccine-date-1'></td> <td id='shc-card-vaccine-date-2'></td>
</tr>
<tr id='extraRow1a' hidden>
<td id='shc-card-vaccine-name-3'></td> <td id='shc-card-vaccine-name-4'></td>
</tr>
<tr id='extraRow1b' hidden>
<td id='shc-card-vaccine-date-3'></td> <td id='shc-card-vaccine-date-4'></td>
</tr>
</tbody>
</table>
<br/>
<div id='shc-card-vaccine' style={{width:'63%', display:'block', marginLeft: 'auto', marginRight: 'auto'}}></div>
<div id='shc-qrcode' style={{width:'63%', display:'block', marginLeft: 'auto', marginRight: 'auto'}}></div>
<br/>
</div>{<a id="shc-pass-img-link" download="vaccination-card.png"><img id="shc-pass-img"/></a>}
</div>
}/>
<Card step="?" heading={t('index:questions')} content={
<div className="space-y-5">
<p>{t('index:questionsNote')}</p>
<div>
<ul>
<Bullet text={t('index:question1')}/>
<Bullet text={t('index:question2')}/>
<Bullet text={t('index:question3')}/>
</ul>
</div>
<div className="flex flex-row items-center justify-start">
<button id="faq-redirect" onClick={goToFAQ}
className=" bg-green-600 py-2 px-3 text-white font-semibold rounded-md disabled:bg-gray-400">
{t('index:visitFAQ')}
</button>
</div>
</div>
}/>
</form>
</div>
)
}
export default Form; | the_stack |
import { VxeEvent } from '../component'
import { VxeTableDefines, VxeTableConstructor, VxeTablePrivateMethods } from '../table'
import { VxeGridConstructor, VxeGridPrivateMethods } from '../grid'
export interface VxeTableProMethods {
/**
* 用于 mouse-config.area,用于获取鼠标选择的区域
*/
getCellAreas(): VxeTableProDefines.MouseCellArea[]
/**
* 用于 mouse-config.area,用于获取区域中的活动单元格
*/
getActiveCellArea(): VxeTableProDefines.MouseActiveCellArea | null
/**
* @deprecated
*/
getCopyCellArea(): VxeTableProDefines.MouseCellArea | null
/**
* 用于 mouse-config.area,用于获取标记为复制粘贴的区域
*/
getCopyCellAreas(): VxeTableProDefines.MouseCellArea[]
/**
* 用于 mouse-config.area,复制指定区域,返回转换后的文本
*/
copyCellArea(): { text: string, html: string }
/**
* 用于 mouse-config.area,剪贴指定区域,返回转换后的文本
*/
cutCellArea(): { text: string, html: string }
/**
* 用于 mouse-config.area,粘贴从表格中被复制的数据,如果不是从表格中操作,则无法粘贴
*/
pasteCellArea(): Promise<any>
/**
* 用于 mouse-config.area,用于清除鼠标选择的区域,可以指定清除的区域
*/
clearCellAreas(area?: number | VxeTableProDefines.MouseCellArea): Promise<any>
/**
* 用于 mouse-config.area,手动清除标记为复制粘贴的区域
*/
clearCopyCellArea(): Promise<any>
/**
* 用于 mouse-config.area,选取指定区域的单元格
* @param areaConfigs 指定区域
*/
setCellAreas(areaConfigs: VxeTableProDefines.CellAreaConfig[], activeArea?: {
area?: number | VxeTableProDefines.CellAreaConfig
column?: number | VxeTableDefines.ColumnInfo
row?: any
}): Promise<any>
/**
* 用于 mouse-config.area,设置活动的区域的单元格
* @param activeArea
*/
setActiveCellArea(activeArea: VxeTableProDefines.ActiveCellAreaConfig): Promise<any>
/**
* 打开单元格查找窗口
*/
openFind(): Promise<any>
/**
* 打开单元格替换窗口
*/
openReplace(): Promise<any>
/**
* 手动关闭查找与替换窗口
*/
closeFNR(): Promise<any>
}
export interface VxeProPluginMethods extends VxeTableProMethods { }
export interface VxeTableProPrivateMethods {
handleKeyboardEvent(evnt: KeyboardEvent): void
handleHeaderCellAreaEvent(evnt: KeyboardEvent, params: VxeTableDefines.HeaderCellClickEventParams): void
handleCellAreaEvent(evnt: MouseEvent, params: VxeTableDefines.CellClickEventParams): void
handleUpdateCellAreas(): void
handleCopyCellAreaEvent(evnt: ClipboardEvent): void
handlePasteCellAreaEvent(evnt: ClipboardEvent): void
handleCutCellAreaEvent(evnt: ClipboardEvent): void
triggerCellExtendMousedownEvent(evnt: MouseEvent, params: any): void
triggerCopyCellAreaEvent(evnt: MouseEvent): void
triggerCutCellAreaEvent(evnt: MouseEvent): void
triggerPasteCellAreaEvent(evnt: MouseEvent): void
triggerFNROpenEvent(evnt: MouseEvent, tab: 'find' | 'replace'): void
}
export interface VxeProPluginPrivateMethods extends VxeTableProPrivateMethods { }
declare module '../table' {
interface VxeTableMethods extends VxeTableProMethods { }
interface VxeTablePrivateMethods extends VxeTableProPrivateMethods { }
}
declare module '../grid' {
interface VxeGridMethods extends VxeTableProMethods { }
interface VxeGridPrivateMethods extends VxeTableProPrivateMethods { }
}
export interface VXETableProClipboard {
text?: string
html?: string
[key: string]: any
}
declare module '../vxe-table' {
interface VXETableConfig {
clipboard?: VXETableProClipboard
}
}
export namespace VxeTableProDefines {
export interface CellAreaParams {
cols: VxeTableDefines.ColumnInfo[]
rows: any
}
export interface FNRTab {
value: string
label: string
}
export interface FNRSearch {
seq: number
row: number
col: number
isActived: boolean
value: string
}
export interface MouseActiveCellArea {
el?: HTMLElement | null
type: CELL_AREA_TYPE
area: MouseCellArea
row: any
column: VxeTableDefines.ColumnInfo
top: number
left: number
width: number
height: number
}
export interface MouseCellArea {
el?: HTMLElement | null
leftEl?: HTMLElement | null
rightEl?: HTMLElement | null
type: CELL_AREA_TYPE
rows: any[]
cols: VxeTableDefines.ColumnInfo[]
top: number
left: number
width: number
height: number
}
export type CELL_AREA_TYPE = 'main' | 'copy' | 'extend' | 'multi' | 'active'
export interface CellAreaConfig {
type?: CELL_AREA_TYPE
startColumn: VxeTableDefines.ColumnInfo | number
endColumn: VxeTableDefines.ColumnInfo | number
startRow: any
endRow: any
}
export interface ActiveCellAreaConfig {
area: VxeTableProDefines.MouseCellArea | number
column: VxeTableDefines.ColumnInfo | number
row: any
}
export type ExtendCellAreaDirection = 'up' | 'down' | 'left' | 'right'
export interface ExtendCellAreaCalcBaseParams {
rows: any[]
cols: VxeTableDefines.ColumnInfo[]
targetValues: any[][]
targetRows: any[]
targetCols: VxeTableDefines.ColumnInfo[]
extendRows: any[]
extendCols: VxeTableDefines.ColumnInfo[]
direction: ExtendCellAreaDirection
$table: VxeTableConstructor & VxeTablePrivateMethods
$grid: VxeGridConstructor | null | undefined
}
interface EventParams extends VxeEvent {
$table: VxeTableConstructor & VxeTablePrivateMethods
$grid: VxeGridConstructor | null | undefined
}
type FnrTab = 'find' | 'replace'
export interface OpenFnrParams {
tab: FnrTab
}
export interface OpenFnrEventParams extends EventParams, OpenFnrParams { }
export interface FnrChangeParams extends OpenFnrParams { }
export interface FnrChangeEventParams extends EventParams, FnrChangeParams { }
export interface FnrFindParams {
findValue: string
row: any
column: VxeTableDefines.ColumnInfo
}
export interface FnrFindEventParams extends FnrFindParams { }
export interface FindAndReplaceResult {
row: any
_rowIndex: number
column: VxeTableDefines.ColumnInfo
_columnIndex: number
}
export interface FnrFindAllParams {
findValue: string
result: FindAndReplaceResult[]
}
export interface FnrFindAllEventParams extends FnrFindAllParams { }
export interface FnrReplaceParams {
findValue: string
replaceValue: string
row: any
column: VxeTableDefines.ColumnInfo
}
export interface FnrReplaceEventParams extends FnrReplaceParams { }
export interface FnrReplaceAllParams {
findValue: string
replaceValue: string
result: FindAndReplaceResult[]
}
export interface FnrReplaceAllEventParams extends FnrReplaceAllParams { }
export interface CellAreaCopyParams {
status: boolean
targetAreas: VxeTableProDefines.CellAreaParams[]
cellValues: string[][]
}
export interface CellAreaCopyEventParams extends EventParams, CellAreaCopyParams { }
export interface CellAreaCutParams {
status: boolean
targetAreas: VxeTableProDefines.CellAreaParams[]
cellValues: string[][]
}
export interface CellAreaCutEventParams extends EventParams, CellAreaCutParams { }
export interface CellAreaPasteParams {
status: boolean
targetAreas: VxeTableProDefines.CellAreaParams[]
}
export interface CellAreaPasteEventParams extends EventParams, CellAreaPasteParams { }
export interface CellAreaMergeParams {
status: boolean
targetAreas: VxeTableProDefines.CellAreaParams[]
}
export interface CellAreaMergeEventParams extends EventParams, CellAreaMergeParams { }
export interface ClearCellAreaMergeParams {
mergeCells: VxeTableDefines.MergeInfo[]
}
export interface ClearCellAreaMergeEventParams extends EventParams, ClearCellAreaMergeParams { }
export interface HeaderCellAreaSelectionParams {
targetRows: any[]
targetCols: VxeTableDefines.ColumnInfo[]
column: VxeTableDefines.ColumnInfo
_columnIndex: number
}
export interface HeaderCellAreaSelectionEventParams extends EventParams, HeaderCellAreaSelectionParams { }
export interface CellAreaSelectionStartParams {
row: any
_rowIndex: number
$rowIndex: number
column: VxeTableDefines.ColumnInfo
_columnIndex: number
$columnIndex: number
cell: HTMLElement
}
export interface CellAreaSelectionStartEventParams extends EventParams, CellAreaSelectionStartParams { }
export interface CellAreaSelectionDragParams {
rows: any[]
cols: VxeTableDefines.ColumnInfo[]
}
export interface CellAreaSelectionDragEventParams extends EventParams, CellAreaSelectionDragParams { }
export interface CellAreaSelectionEndParams {
rows: any[]
cols: VxeTableDefines.ColumnInfo[]
}
export interface CellAreaSelectionEndEventParams extends EventParams, CellAreaSelectionEndParams { }
export interface CellAreaExtensionStartParams extends CellAreaSelectionStartParams {}
export interface CellAreaExtensionStartEventParams extends EventParams, CellAreaExtensionStartParams { }
export interface CellAreaExtensionDragParams {
rows: any[]
cols: VxeTableDefines.ColumnInfo[]
targetRows: any[]
targetCols: VxeTableDefines.ColumnInfo[]
}
export interface CellAreaExtensionDragEventParams extends EventParams, CellAreaExtensionDragParams { }
export interface CellAreaExtensionEndParams {
rows: any[]
cols: VxeTableDefines.ColumnInfo[]
targetRows: any[]
targetCols: VxeTableDefines.ColumnInfo[]
}
export interface CellAreaExtensionEndEventParams extends EventParams, CellAreaExtensionEndParams { }
export interface CellAreaArrowsStartParams {
rows: any[]
cols: VxeTableDefines.ColumnInfo[]
isLeft: boolean
isUp: boolean
isRight: boolean
isDown: boolean
}
export interface CellAreaArrowsStartEventParams extends EventParams, CellAreaArrowsStartParams { }
export interface CellAreaArrowsEndParams extends CellAreaArrowsStartParams {
targetRows: any[]
targetCols: VxeTableDefines.ColumnInfo[]
}
export interface CellAreaArrowsEndEventParams extends EventParams, CellAreaArrowsEndParams { }
export interface ActiveCellChangeStartParams {
activeArea: VxeTableProDefines.MouseCellArea
row: any
column: VxeTableDefines.ColumnInfo
isTab: boolean
isEnter: boolean
isLeft: boolean
isUp: boolean
isRight: boolean
isDown: boolean
}
export interface ActiveCellChangeStartEventParams extends EventParams, ActiveCellChangeStartParams { }
export interface ActiveCellChangeEndParams extends ActiveCellChangeStartParams {
beforeActiveArea: VxeTableProDefines.MouseCellArea
}
export interface ActiveCellChangeEndEventParams extends EventParams, ActiveCellChangeEndParams { }
}
export type VxeTableProEmits = [
'change-fnr', // 废弃
'open-fnr',
'fnr-change',
'fnr-find',
'fnr-find-all',
'fnr-replace',
'fnr-replace-all',
'cell-area-copy',
'cell-area-cut',
'cell-area-paste',
'cell-area-merge',
'clear-cell-area-merge',
'header-cell-area-selection',
'cell-area-selection-start',
'cell-area-selection-drag',
'cell-area-selection-end',
'cell-area-extension-start',
'cell-area-extension-drag',
'cell-area-extension-end',
'cell-area-arrows-start',
'cell-area-arrows-end',
'active-cell-change-start',
'active-cell-change-end'
]
declare module '../table' {
interface VxeTableEventProps {
onOpenFnr?: VxeTableEvents.OpenFnr
onFnrChange?: VxeTableEvents.FnrChange
onFnrFind?: VxeTableEvents.FnrFind
onFnrFindAll?: VxeTableEvents.FnrFindAll
onFnrReplace?: VxeTableEvents.FnrReplace
onFnrReplaceAll?: VxeTableEvents.FnrReplaceAll
onCellAreaCopy?: VxeTableEvents.CellAreaCopy
onCellAreaCut?: VxeTableEvents.CellAreaCut
onCellAreaPaste?: VxeTableEvents.CellAreaPaste
onCellAreaMerge?: VxeTableEvents.CellAreaMerge
onClearCellAreaMerge?: VxeTableEvents.ClearCellAreaMerge
onHeaderCellAreaSelection?: VxeTableEvents.HeaderCellAreaSelection
onCellAreaSelectionStart?: VxeTableEvents.CellAreaSelectionStart
onCellAreaSelectionDrag?: VxeTableEvents.CellAreaSelectionDrag
onCellAreaSelectionEnd?: VxeTableEvents.CellAreaSelectionEnd
onCellAreaExtensionStart?: VxeTableEvents.CellAreaExtensionStart
onCellAreaExtensionDrag?: VxeTableEvents.CellAreaExtensionDrag
onCellAreaExtensionEnd?: VxeTableEvents.CellAreaExtensionEnd
onCellAreaArrowsStart?: VxeTableEvents.CellAreaArrowsStart
onCellAreaArrowsEnd?: VxeTableEvents.CellAreaArrowsEnd
onActiveCellChangeStart?: VxeTableEvents.ActiveCellChangeStart
onActiveCellChangeEnd?: VxeTableEvents.ActiveCellChangeEnd
}
interface VxeTableListeners {
openFnr?: VxeTableEvents.OpenFnr
fnrChange?: VxeTableEvents.FnrChange
fnrFind?: VxeTableEvents.FnrFind
fnrFindAll?: VxeTableEvents.FnrFindAll
fnrReplace?: VxeTableEvents.FnrReplace
fnrReplaceAll?: VxeTableEvents.FnrReplaceAll
cellAreaCopy?: VxeTableEvents.CellAreaCopy
cellAreaCut?: VxeTableEvents.CellAreaCut
cellAreaPaste?: VxeTableEvents.CellAreaPaste
cellAreaMerge?: VxeTableEvents.CellAreaMerge
clearCellAreaMerge?: VxeTableEvents.ClearCellAreaMerge
headerCellAreaSelection?: VxeTableEvents.HeaderCellAreaSelection
cellAreaSelectionStart?: VxeTableEvents.CellAreaSelectionStart
cellAreaSelectionDrag?: VxeTableEvents.CellAreaSelectionDrag
cellAreaSelectionEnd?: VxeTableEvents.CellAreaSelectionEnd
cellAreaExtensionStart?: VxeTableEvents.CellAreaExtensionStart
cellAreaExtensionDrag?: VxeTableEvents.CellAreaExtensionDrag
cellAreaExtensionEnd?: VxeTableEvents.CellAreaExtensionEnd
cellAreaArrowsStart?: VxeTableEvents.CellAreaArrowsStart
cellAreaArrowsEnd?: VxeTableEvents.CellAreaArrowsEnd
activeCellChangeStart?: VxeTableEvents.ActiveCellChangeStart
activeCellChangeEnd?: VxeTableEvents.ActiveCellChangeEnd
}
namespace VxeTableEvents {
export type OpenFnr = (params: VxeTableProDefines.OpenFnrParams) => void
export type FnrChange = (params: VxeTableProDefines.FnrChangeParams) => void
export type FnrFind = (params: VxeTableProDefines.FnrFindParams) => void
export type FnrFindAll = (params: VxeTableProDefines.FnrFindAllParams) => void
export type FnrReplace = (params: VxeTableProDefines.FnrReplaceParams) => void
export type FnrReplaceAll = (params: VxeTableProDefines.FnrReplaceAllParams) => void
export type CellAreaCopy = (params: VxeTableProDefines.CellAreaCopyParams) => void
export type CellAreaCut = (params: VxeTableProDefines.CellAreaCutParams) => void
export type CellAreaPaste = (params: VxeTableProDefines.CellAreaPasteParams) => void
export type CellAreaMerge = (params: VxeTableProDefines.CellAreaMergeEventParams) => void
export type ClearCellAreaMerge = (params: VxeTableProDefines.ClearCellAreaMergeEventParams) => void
export type HeaderCellAreaSelection = (params: VxeTableProDefines.HeaderCellAreaSelectionEventParams) => void
export type CellAreaSelectionStart = (params: VxeTableProDefines.CellAreaSelectionStartEventParams) => void
export type CellAreaSelectionDrag = (params: VxeTableProDefines.CellAreaSelectionDragEventParams) => void
export type CellAreaSelectionEnd = (params: VxeTableProDefines.CellAreaSelectionEndEventParams) => void
export type CellAreaExtensionStart = (params: VxeTableProDefines.CellAreaExtensionStartEventParams) => void
export type CellAreaExtensionDrag = (params: VxeTableProDefines.CellAreaExtensionDragEventParams) => void
export type CellAreaExtensionEnd = (params: VxeTableProDefines.CellAreaExtensionEndEventParams) => void
export type CellAreaArrowsStart = (params: VxeTableProDefines.CellAreaArrowsStartEventParams) => void
export type CellAreaArrowsEnd = (params: VxeTableProDefines.CellAreaArrowsEndEventParams) => void
export type ActiveCellChangeStart = (params: VxeTableProDefines.ActiveCellChangeStartEventParams) => void
export type ActiveCellChangeEnd = (params: VxeTableProDefines.ActiveCellChangeEndEventParams) => void
}
}
declare module '../grid' {
interface VxeGridEventProps {
onOpenFnr?: VxeGridEvents.OpenFnr
onFnrChange?: VxeGridEvents.FnrChange
onFnrFind?: VxeGridEvents.FnrFind
onFnrFindAll?: VxeGridEvents.FnrFindAll
onFnrReplace?: VxeGridEvents.FnrReplace
onFnrReplaceAll?: VxeGridEvents.FnrReplaceAll
onCellAreaCopy?: VxeGridEvents.CellAreaCopy
onCellAreaCut?: VxeGridEvents.CellAreaCut
onCellAreaPaste?: VxeGridEvents.CellAreaPaste
onCellAreaMerge?: VxeGridEvents.CellAreaMerge
onClearCellAreaMerge?: VxeGridEvents.ClearCellAreaMerge
onHeaderCellAreaSelection?: VxeGridEvents.HeaderCellAreaSelection
onCellAreaSelectionStart?: VxeGridEvents.CellAreaSelectionStart
onCellAreaSelectionDrag?: VxeGridEvents.CellAreaSelectionDrag
onCellAreaSelectionEnd?: VxeGridEvents.CellAreaSelectionEnd
onCellAreaExtensionStart?: VxeGridEvents.CellAreaExtensionStart
onCellAreaExtensionDrag?: VxeGridEvents.CellAreaExtensionDrag
onCellAreaExtensionEnd?: VxeGridEvents.CellAreaExtensionEnd
onCellAreaArrowsStart?: VxeGridEvents.CellAreaArrowsStart
onCellAreaArrowsEnd?: VxeGridEvents.CellAreaArrowsEnd
onActiveCellChangeStart?: VxeGridEvents.ActiveCellChangeStart
onActiveCellChangeEnd?: VxeGridEvents.ActiveCellChangeEnd
}
interface VxeGridListeners {
openFnr?: VxeGridEvents.OpenFnr
changeFnr?: VxeGridEvents.FnrChange
fnrFind?: VxeGridEvents.FnrFind
fnrFindAll?: VxeGridEvents.FnrFindAll
fnrReplace?: VxeGridEvents.FnrReplace
fnrReplaceAll?: VxeGridEvents.FnrReplaceAll
cellAreaCopy?: VxeGridEvents.CellAreaCopy
cellAreaCut?: VxeGridEvents.CellAreaCut
cellAreaMerge?: VxeGridEvents.CellAreaMerge
clearCellAreaMerge?: VxeGridEvents.ClearCellAreaMerge
headerCellAreaSelection?: VxeGridEvents.HeaderCellAreaSelection
cellAreaSelectionStart?: VxeGridEvents.CellAreaSelectionStart
cellAreaSelectionDrag?: VxeGridEvents.CellAreaSelectionDrag
cellAreaSelectionEnd?: VxeGridEvents.CellAreaSelectionEnd
cellAreaExtensionStart?: VxeGridEvents.CellAreaExtensionStart
cellAreaExtensionDrag?: VxeGridEvents.CellAreaExtensionDrag
cellAreaExtensionEnd?: VxeGridEvents.CellAreaExtensionEnd
cellAreaArrowsStart?: VxeGridEvents.CellAreaArrowsStart
cellAreaArrowsEnd?: VxeGridEvents.CellAreaArrowsEnd
ActiveCellChangeStart?: VxeGridEvents.ActiveCellChangeStart
ActiveCellChangeEnd?: VxeGridEvents.ActiveCellChangeEnd
}
namespace VxeGridEvents {
export type OpenFnr = (params: VxeTableProDefines.OpenFnrParams) => void
export type FnrChange = (params: VxeTableProDefines.FnrChangeParams) => void
export type FnrFind = (params: VxeTableProDefines.FnrFindParams) => void
export type FnrFindAll = (params: VxeTableProDefines.FnrFindAllParams) => void
export type FnrReplace = (params: VxeTableProDefines.FnrReplaceParams) => void
export type FnrReplaceAll = (params: VxeTableProDefines.FnrReplaceAllParams) => void
export type CellAreaCopy = (params: VxeTableProDefines.CellAreaCopyParams) => void
export type CellAreaCut = (params: VxeTableProDefines.CellAreaCutParams) => void
export type CellAreaPaste = (params: VxeTableProDefines.CellAreaPasteParams) => void
export type CellAreaMerge = (params: VxeTableProDefines.CellAreaMergeParams) => void
export type ClearCellAreaMerge = (params: VxeTableProDefines.ClearCellAreaMergeParams) => void
export type HeaderCellAreaSelection = (params: VxeTableProDefines.HeaderCellAreaSelectionParams) => void
export type CellAreaSelectionStart = (params: VxeTableProDefines.CellAreaSelectionStartEventParams) => void
export type CellAreaSelectionDrag = (params: VxeTableProDefines.CellAreaSelectionDragEventParams) => void
export type CellAreaSelectionEnd = (params: VxeTableProDefines.CellAreaSelectionEndEventParams) => void
export type CellAreaExtensionStart = (params: VxeTableProDefines.CellAreaExtensionStartEventParams) => void
export type CellAreaExtensionDrag = (params: VxeTableProDefines.CellAreaExtensionDragEventParams) => void
export type CellAreaExtensionEnd = (params: VxeTableProDefines.CellAreaExtensionEndEventParams) => void
export type CellAreaArrowsStart = (params: VxeTableProDefines.CellAreaArrowsStartEventParams) => void
export type CellAreaArrowsEnd = (params: VxeTableProDefines.CellAreaArrowsEndEventParams) => void
export type ActiveCellChangeStart = (params: VxeTableProDefines.ActiveCellChangeStartEventParams) => void
export type ActiveCellChangeEnd = (params: VxeTableProDefines.ActiveCellChangeEndEventParams) => void
}
} | the_stack |
import { Game } from '.';
import { Resource } from '../Resource';
import { Unit } from '../Unit';
import { LuxMatchConfigs } from '../types';
import { GameMap } from '../GameMap';
import seedrandom from 'seedrandom';
import { Position } from '../GameMap/position';
const mapSizes = [12, 16, 24, 32];
export const generateGame = (
matchconfigs: Partial<LuxMatchConfigs> = {}
): Game => {
const configs = {
...matchconfigs,
};
const seed = configs.seed;
const rng = seedrandom(`gen_${seed}`);
const size = mapSizes[Math.floor(rng() * mapSizes.length)];
if (configs.width === undefined) {
// TODO: use rng to get width and heights
configs.width = size;
}
if (configs.height === undefined) {
configs.height = size;
}
const game = new Game(configs);
const map = game.map;
const width = map.width;
const height = map.height;
if (configs.mapType === GameMap.Types.DEBUG) {
// for testing, hardcode wood and coal
const woodCoords = [
[3, 3],
[3, 4],
[4, 3],
[5, 6],
[1, 1],
[1, 2],
[1, 3],
[2, 5],
[2, 14],
[2, 13],
[4, 13],
[5, 13],
[5, 12],
[5, 14],
];
for (const c of woodCoords) {
map.addResource(c[0], c[1], Resource.Types.WOOD, 1500);
map.addResource(width - c[0] - 1, c[1], Resource.Types.WOOD, 1500);
}
const coalCoords = [
[5, 5],
[6, 5],
[9, 4],
];
for (const c of coalCoords) {
map.addResource(c[0], c[1], Resource.Types.COAL, 300);
map.addResource(width - c[0] - 1, c[1], Resource.Types.COAL, 300);
}
const uCoords = [
[9, 7],
[7, 8],
];
for (const c of uCoords) {
map.addResource(c[0], c[1], Resource.Types.URANIUM, 30);
map.addResource(width - c[0] - 1, c[1], Resource.Types.URANIUM, 30);
}
// hardcode initial city tiles
game.spawnCityTile(Unit.TEAM.A, 2, 1);
game.spawnCityTile(Unit.TEAM.B, width - 3, 1);
game.spawnWorker(Unit.TEAM.A, 2, 2);
game.spawnWorker(Unit.TEAM.B, width - 3, 2);
game.spawnCart(Unit.TEAM.A, 1, 2);
game.spawnCart(Unit.TEAM.B, width - 2, 2);
} else if (configs.mapType === GameMap.Types.EMPTY) {
return game;
} else {
let symmetry = SYMMETRY.HORIZONTAL;
let halfWidth = width;
let halfHeight = height;
if (rng() < 0.5) {
symmetry = SYMMETRY.VERTICAL;
halfWidth = width / 2;
} else {
halfHeight = height / 2;
}
let resourcesMap = generateAllResources(
rng,
symmetry,
width,
height,
halfWidth,
halfHeight
);
let retries = 0;
while (!validateResourcesMap(resourcesMap)) {
retries += 1;
resourcesMap = generateAllResources(
rng,
symmetry,
width,
height,
halfWidth,
halfHeight
);
}
resourcesMap.forEach((row, y) => {
row.forEach((val, x) => {
if (val !== null) {
map.addResource(x, y, val.type, val.amt);
}
});
});
let spawnX = Math.floor(rng() * (halfWidth - 1)) + 1;
let spawnY = Math.floor(rng() * (halfHeight - 1)) + 1;
while (map.getCell(spawnX, spawnY).hasResource()) {
spawnX = Math.floor(rng() * (halfWidth - 1)) + 1;
spawnY = Math.floor(rng() * (halfHeight - 1)) + 1;
}
game.spawnWorker(Unit.TEAM.A, spawnX, spawnY);
game.spawnCityTile(Unit.TEAM.A, spawnX, spawnY);
if (symmetry === SYMMETRY.HORIZONTAL) {
game.spawnWorker(Unit.TEAM.B, spawnX, height - spawnY - 1);
game.spawnCityTile(Unit.TEAM.B, spawnX, height - spawnY - 1);
} else {
game.spawnWorker(Unit.TEAM.B, width - spawnX - 1, spawnY);
game.spawnCityTile(Unit.TEAM.B, width - spawnX - 1, spawnY);
}
// add at least 3 wood deposits near spawns
const deltaIndex = Math.floor(rng() * MOVE_DELTAS.length);
const woodSpawnsDeltas = [
MOVE_DELTAS[deltaIndex],
MOVE_DELTAS[(deltaIndex + 1) % MOVE_DELTAS.length],
MOVE_DELTAS[(deltaIndex + 2) % MOVE_DELTAS.length],
MOVE_DELTAS[(deltaIndex + 3) % MOVE_DELTAS.length],
MOVE_DELTAS[(deltaIndex + 4) % MOVE_DELTAS.length],
MOVE_DELTAS[(deltaIndex + 5) % MOVE_DELTAS.length],
MOVE_DELTAS[(deltaIndex + 6) % MOVE_DELTAS.length]
];
let count = 0
for (const delta of woodSpawnsDeltas) {
const nx = spawnX + delta[0];
const ny = spawnY + delta[1];
let nx2 = nx;
let ny2 = ny;
if (symmetry === SYMMETRY.HORIZONTAL) {
ny2 = height - ny - 1;
} else {
nx2 = width - nx - 1;
}
if (
!map.inMap(new Position(nx, ny)) ||
!map.inMap(new Position(nx2, ny2))
) {
continue;
}
if (
!map.getCell(nx, ny).hasResource() &&
map.getCell(nx, ny).citytile === null
) {
count += 1;
map.addResource(nx, ny, Resource.Types.WOOD, 800);
}
if (
!map.getCell(nx2, ny2).hasResource() &&
map.getCell(nx2, ny2).citytile === null
) {
count += 1;
map.addResource(nx2, ny2, Resource.Types.WOOD, 800);
}
if (count == 6) break;
}
return game;
}
return game;
};
enum SYMMETRY {
HORIZONTAL,
VERTICAL,
}
const validateResourcesMap = (
resourcesMap: Array<{ amt: number; type: Resource.Types } | any>
) => {
const data = { wood: 0, coal: 0, uranium: 0 };
resourcesMap.forEach((row, y) => {
row.forEach((val, x) => {
if (val !== null) {
data[resourcesMap[y][x].type] += resourcesMap[y][x].amt;
}
});
});
if (data.wood < 2000) return false;
if (data.coal < 1500) return false;
if (data.uranium < 300) return false;
return true;
};
const generateAllResources = (
rng: seedrandom.prng,
symmetry: SYMMETRY,
width: number,
height: number,
halfWidth: number,
halfHeight: number
) => {
let resourcesMap: Array<{ amt: number; type: Resource.Types } | any> = [];
for (let i = 0; i < height; i++) {
resourcesMap.push([]);
for (let j = 0; j < width; j++) {
resourcesMap[i].push(null);
}
}
const woodResourcesMap = generateResourceMap(
rng,
0.21,
0.01,
halfWidth,
halfHeight,
{ deathLimit: 2, birthLimit: 4 }
);
woodResourcesMap.forEach((row, y) => {
row.forEach((val, x) => {
if (val === 1) {
const amt = Math.min(300 + Math.floor(rng() * 100), 500);
resourcesMap[y][x] = { type: Resource.Types.WOOD, amt };
}
});
});
const coalResourcesMap = generateResourceMap(
rng,
0.11,
0.02,
halfWidth,
halfHeight,
{ deathLimit: 2, birthLimit: 4 }
);
coalResourcesMap.forEach((row, y) => {
row.forEach((val, x) => {
if (val === 1) {
const amt = 350 + Math.floor(rng() * 75);
resourcesMap[y][x] = { type: Resource.Types.COAL, amt };
}
});
});
const uraniumResourcesMap = generateResourceMap(
rng,
0.055,
0.04,
halfWidth,
halfHeight,
{ deathLimit: 1, birthLimit: 6 }
);
uraniumResourcesMap.forEach((row, y) => {
row.forEach((val, x) => {
if (val === 1) {
const amt = 300 + Math.floor(rng() * 50);
resourcesMap[y][x] = { type: Resource.Types.URANIUM, amt };
}
});
});
for (let i = 0; i < 10; i++) {
resourcesMap = gravitateResources(resourcesMap);
}
// perturb resources
for (let y = 0; y < halfHeight; y++) {
for (let x = 0; x < halfWidth; x++) {
const resource = resourcesMap[y][x];
if (resource === null) continue;
for (const d of MOVE_DELTAS) {
const nx = x + d[0];
const ny = y + d[1];
if (nx < 0 || ny < 0 || nx >= halfHeight || ny >= halfWidth) continue;
if (rng() < 0.05) {
let amt = 300 + Math.floor(rng() * 50);
if (resource.type === 'coal') {
amt = 350 + Math.floor(rng() * 75);
}
if (resource.type === 'wood') {
amt = Math.min(300 + Math.floor(rng() * 100), 500);
}
resourcesMap[ny][nx] = { type: resource.type, amt };
}
}
}
}
for (let y = 0; y < halfHeight; y++) {
for (let x = 0; x < halfWidth; x++) {
const resource = resourcesMap[y][x];
if (symmetry === SYMMETRY.VERTICAL) {
resourcesMap[y][width - x - 1] = resource;
} else {
resourcesMap[height - y - 1][x] = resource;
}
}
}
return resourcesMap;
};
const generateResourceMap = (
rng: seedrandom.prng,
density,
densityRange,
width,
height,
golOptions: GOLOptions = { deathLimit: 2, birthLimit: 4 }
): number[][] => {
// width, height should represent half of the map
const DENSITY = density - densityRange / 2 + densityRange * rng();
const arr = [];
for (let y = 0; y < height; y++) {
arr.push([]);
for (let x = 0; x < width; x++) {
let type = 0;
if (rng() < DENSITY) {
type = 1;
}
arr[y].push(type);
}
}
// simulate GOL for 2 rounds
for (let i = 0; i < 2; i++) {
simulateGOL(arr, golOptions);
}
return arr;
};
const MOVE_DELTAS = [
[0, 1],
[-1, 1],
[-1, 0],
[-1, -1],
[0, -1],
[1, -1],
[1, 0],
[1, 1],
];
type GOLOptions = {
deathLimit: number;
birthLimit: number;
};
const simulateGOL = (arr: Array<Array<number>>, options: GOLOptions) => {
// high birthlimit = unlikely to deviate from initial random spots
// high deathlimit = lots of patches die
const padding = 1;
const deathLimit = options.deathLimit;
const birthLimit = options.birthLimit;
for (let i = padding; i < arr.length - padding; i++) {
for (let j = padding; j < arr[0].length - padding; j++) {
let alive = 0;
for (let k = 0; k < MOVE_DELTAS.length; k++) {
const delta = MOVE_DELTAS[k];
const ny = i + delta[1];
const nx = j + delta[0];
if (arr[ny][nx] === 1) {
alive++;
}
}
if (arr[i][j] == 1) {
if (alive < deathLimit) {
arr[i][j] = 0;
} else {
arr[i][j] = 1;
}
} else {
if (alive > birthLimit) {
arr[i][j] = 1;
} else {
arr[i][j] = 0;
}
}
}
}
};
const kernelForce = (resourcesMap: any[], rx: number, ry: number) => {
const force = [0, 0];
const resource = resourcesMap[ry][rx];
const kernelSize = 5;
for (let y = ry - kernelSize; y < ry + kernelSize; y++) {
for (let x = rx - kernelSize; x < rx + kernelSize; x++) {
if (x < 0 || y < 0 || x >= resourcesMap[0].length || y >= resourcesMap.length) continue;
const r2 = resourcesMap[y][x]
if (r2 !== null) {
const dx = rx - x;
const dy = ry - y;
const mdist = Math.abs(dx) + Math.abs(dy);
if (r2.type !== resource.type) {
if (dx !== 0) force[0] += Math.pow(dx/mdist, 2) * Math.sign(dx);
if (dy !== 0) force[1] += Math.pow(dy/mdist, 2) * Math.sign(dy);
} else {
if (dx !== 0) force[0] -= Math.pow(dx/mdist, 2) * Math.sign(dx);
if (dy !== 0) force[1] -= Math.pow(dy/mdist, 2) * Math.sign(dy);
}
}
}
}
return force;
}
/**
* Gravitate like to like, push different resources away from each other.
*
* Add's a force direction to each cell.
*/
const gravitateResources = (resourcesMap) => {
const newResourcesMap = [];
for (let y = 0; y < resourcesMap.length; y++) {
newResourcesMap.push([]);
for (let x = 0; x < resourcesMap[y].length; x++) {
newResourcesMap[y].push(null);
const res = resourcesMap[y][x];
if (res !== null) {
const f = kernelForce(resourcesMap, x, y);
resourcesMap[y][x].force = f;
}
}
}
for (let y = 0; y < resourcesMap.length; y++) {
for (let x = 0; x < resourcesMap[y].length; x++) {
const res = resourcesMap[y][x];
if (res !== null) {
let nx = x + Math.sign(res.force[0])*1;
let ny = y + Math.sign(res.force[1])*1;
if (nx < 0) nx = 0;
if (ny < 0) ny = 0;
if (nx >= resourcesMap[0].length) nx = resourcesMap[0].length-1;
if (ny >= resourcesMap.length) ny = resourcesMap.length- 1;
if (newResourcesMap[ny][nx] === null) {
newResourcesMap[ny][nx] = res;
} else {
newResourcesMap[y][x] = res;
}
}
}
}
return newResourcesMap;
}
export interface GenerationConfigs {
width: number;
height: number;
seed: number;
}
const printMap = (resourcesMap) => {
for (let y = 0; y < resourcesMap.length; y++) {
let str = '';
for (let x = 0; x < resourcesMap[y].length; x++) {
const res = resourcesMap[y][x];
if (res === null) {
str +="0 ".grey
} else {
switch(res.type) {
case 'wood':
str += "X ".yellow
break;
case 'coal':
str += "X ".black
break;
case 'uranium':
str += "X ".magenta
break;
}
}
}
console.log(str)
}
}
// const rng = seedrandom(`gen_${23122929}`);
// const size = mapSizes[Math.floor(rng() * mapSizes.length)];
// let halfWidth = size;
// let halfHeight = size;
// let symmetry = SYMMETRY.HORIZONTAL;
// if (rng() < 0.5) {
// symmetry = SYMMETRY.VERTICAL;
// halfWidth = size / 2;
// } else {
// halfHeight = size / 2;
// }
// let resourcesMap = generateAllResources(
// rng,
// symmetry,
// size,
// size,
// halfWidth,
// halfHeight
// );
// console.log("Initial Resource Half Map")
// printMap(resourcesMap)
// for (let i = 0; i < 10; i++) {
// // console.log(resourcesMap[4][0])
// // console.log("gravitating")
// if (i %2 == 0) {
// console.log(`Resource Half Map after ${i + 1} gravitation steps`)
// resourcesMap = gravitateResources(resourcesMap)
// printMap(resourcesMap)
// }
// } | the_stack |
/// <reference types="node" />
/**
* This is a native SNMP library for Node.js. The purpose is to provide enough
* functionality to perform large scale monitoring of network equipment.
*
* It's optimized for polling tens of thousands of counters on hundreds or
* thousands of hosts in a parallell manner. This is known to work (although
* performance might be limited by less than optimal SNMP agent implementations
* in random network gear).
*
* @example
* import * as snmp from 'snmp-native';
*/
export const defaultOptions: SessionOptions;
export const DataTypes: DataTypes;
export const PduTypes: PduTypes;
export const Versions: Versions;
export const Errors: Errors;
/**
* @internal
* export const Versions: Version;
*/
/**
* Create a Session. The Session constructor can take an options object.
* The options passed to the Session will be the defaults for any
* subsequent function calls on that session, but can be overridden as
* needed. Useful parameters here are host, port and family.
*
* For optimum performance when polling many hosts, create a session
* without specifying the host. Reuse this session for all hosts and
* specify the host on each get, getAll, etc.
*
* @example
* // Create a session with default settings.
* const session = new snmp.Session();
* @example
* // Create a Session with explicit default host, port, and community.
* const session = new snmp.Session({
* host: 'device.example.com',
* port: 161,
* community: 'special',
* });
* @example
* // Create an IPv6 Session.
* const session = new snmp.Session({
* host: '2001:db8::42',
* family: 'udp6',
* community: 'private',
* });
*/
export class Session {
options: SessionOptions;
/**
* @internal
* socket: Socket;
* @internal
* reqs: {
* [key: number]: {
* callback: callback;
* }
* };
*/
constructor(options?: SessionOptions);
/**
* Perform a simple GetRequest.
*
* The callback is called with an error object or an array of varbinds.
*
* @param options.oid The OID to get
*
* @example
* const oid = [ 1, 3, 6, 1, 4, 1, 42, 1, 0 ];
*
* session.get( { oid, }, (err, varbinds) => {
* if( err ){
* console.error( 'Failed' );
* } else {
* const varbind = varbinds[0];
* console.log( `${varbind.oid} = ${varbind.value}` );
* }
* } );
*
* @example
* // Specify host and community explicitly:
* const host = 'example.host.com';
* const community = 'private';
*
* session.get( { oid, host, community, }, (err, varbinds) => {
* const varbind = varbinds[0];
* console.log( `${varbind.oid} = ${varbind.value}` );
* } );
*/
get(
options: {
oid: OID;
} & Options,
callback: ResponseCallback
): void;
/**
* Perform a simple GetNextRequest.
*
* The callback is called with an error object or an array of varbinds.
*
* @param options.oid The OID to get
*
* @example
* const oid = [ 1, 3, 6, 1, 4, 1, 42, 1, 0 ];
*
* session.getNext( { oid, }, (err, varbinds) => {
* if( err ){
* console.error( 'Failed' );
* } else {
* const varbind = varbinds[0];
* console.log( `${varbind.oid} = ${varbind.value}` );
* }
* } );
*/
getNext(
options: {
oid: OID;
} & Options,
callback: ResponseCallback
): void;
/**
* Perform repeated GetRequests to fetch all the required values.
* Multiple OIDs will get packed into as few GetRequest packets as
* possible to minimize roundtrip delays. Gets will be issued serially
* (not in parallell) to avoid flooding hosts.
*
* The callback is called with an error object or an array of varbinds.
* If abortOnError is false (default) any variables that couldn't be
* fetched will simply be omitted from the results. If it is true,
* the callback is called with an error object on any failure. If the
* combinedTimeout is triggered, the callback is called with an error
* and the partial results.
*
* @param options.oids An array of OIDs to get.
* @param options.abortOnError Whether to stop or continue when an
* error is encountered. Default: false.
* @param options.combinedTimeout Timeout in milliseconds that the
* getAll() may take. Default: no timeout.
*
* @example
* const oids = [
* [ 1, 3, 6, 1, 4, 1, 42, 1, 0 ],
* [ 1, 3, 6, 1, 4, 1, 42, 2, 0 ],
* ];
*
* session.getAll( { oids, }, (err, varbinds) => {
* if( err && !varbinds ){
* console.error( 'Failed' );
* } else {
* if( err ){
* console.log( 'Partial results' );
* }
* varbinds.forEach( varbind => {
* console.log( `${varbind.oid} = ${varbind.value}` );
* } );
* }
* } );
*/
getAll(
options: {
oids: OID[];
abortOnError?: boolean | undefined;
combinedTimeout?: number | undefined;
} & Options,
callback: ResponseCallback
): void;
/**
* Perform repeated GetNextRequests to fetch all values in the
* specified tree.
*
* The callback is called with an error object or an array of
* varbinds. If the combinedTimeout is triggered, the callback
* is called with an error and the partial results.
*
* @param options.oid The OID to get.
* @param options.combinedTimeout Timeout in milliseconds that the
* getAll() may take. Default: no timeout.
*
* @example
* const oid = [ 1, 3, 6, 1, 4, 1, 42, 1, 0 ];
*
* session.getSubtree( { oids, }, (err, varbinds) => {
* if( err && !varbinds ){
* console.error( 'Failed' );
* } else {
* if( err ){
* console.log( 'Partial results' );
* }
* varbinds.forEach( varbind => {
* console.log( `${varbind.oid} = ${varbind.value}` );
* } );
* }
* } );
*/
getSubtree(
options: {
oid: OID;
combinedTimeout?: number | undefined;
} & Options,
callback: ResponseCallback
): void;
/**
* Perform a simple SetRequest.
*
* @param options.oid The OID to set.
* @param options.value The value to set.
* @param options.type The type of the value. Supported data types are:
* * Integer (2);
* * Gague (66);
* * IpAddress (64);
* * OctetString (4); and
* * Null (5).
*
* @example
* const oid = [ 1, 3, 6, 1, 4, 1, 42, 1, 0 ];
* const type = snmp.DataTypes.Integer; // => 2
*
* session.set( { oid, type, value: 42, }, (err, varbinds) => {
* if( err ){
* console.error( 'Failed' );
* } else {
* const varbind = varbinds[0];
* console.log( 'Set completed' );
* console.log( `${varbind.oid} = ${varbind.value}` );
* }
* } );
*/
set(
options: {
oid: OID;
type?: DataTypes[keyof DataTypes] | null | undefined,
value?: any;
} & Options,
callback?: ResponseCallback
): void;
/**
* Cancels all outstanding requests and frees used OS resources.
* Outstanding requests will call their callback with the
* "Cancelled" error set.
*/
close(): void;
}
/**
* Create an ASN.1 BER encoding of a Packet structure. This is suitable
* for transmission on a UDP socket.
*
* @param pkt Packet to encode
*/
export function encode(pkt: Packet): Buffer;
/**
* Parse an SNMP packet into its component fields. We don't do a lot of
* validation so a malformed packet will probably just make us blow up.
*
* @param buf Input buffer
*/
export function parse(buf: Buffer): Packet;
/**
* Compare two OIDs and return -1, 0 or +1 depending on the relation
* between them.
*
* @param oidA An OID
* @param oidB An OID
*/
export function compareOids(oidA?: OID, oidB?: OID): -1 | 0 | 1;
/**
* @internal
* export type Version = {
* SNMPv1: number;
* SNMPv2c: number;
* };
*/
export interface SessionOptions extends Options {
/**
* The UDP port used to bind the socket locally, or 0 to use a
* random port.
*/
bindPort?: number | undefined;
/**
* Address family to bind to. This is only used by the Session
* constructor since that is when the bind is done.
*/
family?: 'udp4' | 'udp6' | undefined;
/**
* Function responsible for handling incoming messages and sending UDP
* responses back. If nothing is given here, the default implementation
* is used. This is useful if you want to implement custom logic in
* your application.
*/
msgReceived?(message: Buffer, rinfo: ResponseInfo): void;
/**
* @internal
* version?: number;
*/
}
export interface Options {
/**
* The host to send the request to. Any resolvable name is allowed in
* addition to IP addresses.
*/
host?: string | undefined;
/**
* The UDP port number to send the request to.
*/
port?: number | undefined;
/**
* The SNMP community name.
*/
community?: string | undefined;
/**
* An array of timeout values. Values are times in milliseconds, the
* length of the array is the total number of transmissions that will
* occur. Defaults to four attempts with five seconds between each.
*
* Re-transmissions can be disabled by providing a single timeout
* value.
*
*
* @example
* [ 5000 ] // Disable re-transmission
*
*/
timeouts?: number[] | undefined;
}
/**
* Object Identifier (OID) in array or string form. The string form will
* be parsed into an array.
*
* @example [ 1, 3, 6, 1, 4, 1, 1, 2, 3, 4 ]
* @example '.1.3.6.1.4.1.1.2.3.4'
*/
export type OID = string | number[];
/**
* VarBind object
*/
export type ResponseCallback = (err: Error | null, varbinds: VarBind[]) => void;
export interface ResponseInfo {
address: string;
family: 'IPv4' | 'IPv6';
port: number;
size: number;
}
export interface VarBind {
/**
* The integer type code for the returned value.
*/
type: DataTypes[keyof DataTypes];
/**
* The value, in decoded form. This will be an integer for integer,
* gauge, counter and timetick types, a string for an octet string
* value, an array for array or IP number types.
*/
value: any;
/**
* The represented OID (in array form).
*/
oid: number[];
/**
* For octet string values, this is a raw Buffer representing the string.
*/
valueRaw: Buffer;
/**
* For octet string values, this is a hex string representation of the value.
*/
valueHex?: string | undefined;
/**
* The timestamp (in milliseconds) when the response was received.
*/
receiveStamp: number;
/**
* The timestamp (in milliseconds) when the request was transmitted.
*/
sendStamp: number;
/**
* @internal
* requestId: number;
*/
}
export interface PDU {
type: number;
reqid: number;
error: number;
errorIndex: number;
varbinds: VarBind[];
}
export interface Packet {
version: 0 | 1;
community: string;
pdu: PDU;
}
export interface DataTypes {
readonly Integer: 0x02;
readonly OctetString: 0x04;
readonly Null: 0x05;
readonly ObjectIdentifier: 0x06;
readonly Sequence: 0x30;
readonly IpAddress: 0x40;
readonly Counter: 0x41;
readonly Gauge: 0x42;
readonly TimeTicks: 0x43;
readonly Opaque: 0x44;
readonly NsapAddress: 0x45;
readonly Counter64: 0x46;
readonly NoSuchObject: 0x80;
readonly NoSuchInstance: 0x81;
readonly EndOfMibView: 0x82;
readonly PDUBase: 0xA0;
}
export interface PduTypes {
readonly GetRequestPDU: 0x00;
readonly GetNextRequestPDU: 0x01;
readonly GetResponsePDU: 0x02;
readonly SetRequestPDU: 0x03;
}
export interface Errors {
readonly NoError: 0;
readonly TooBig: 1;
readonly NoSuchName: 2;
readonly BadValue: 3;
readonly ReadOnly: 4;
readonly GenErr: 5;
readonly NoAccess: 6;
readonly WrongType: 7;
readonly WrongLength: 8;
readonly WrongEncoding: 9;
readonly WrongValue: 10;
readonly NoCreation: 11;
readonly InconsistentValue: 12;
readonly ResourceUnavailable: 13;
readonly CommitFailed: 14;
readonly UndoFailed: 15;
readonly AuthorizationError: 16;
readonly NotWritable: 17;
readonly InconsistentName: 18;
}
export interface Versions {
readonly SNMPv1: 0;
readonly SNMPv2c: 1;
} | the_stack |
import traverse, { NodePath, Visitor } from '@babel/traverse'
import * as t from '@babel/types'
import type { StaticConfigParsed, TamaguiInternalConfig } from '@tamagui/core'
import * as CoreNode from '@tamagui/core-node'
import { stylePropsTransform } from '@tamagui/helpers'
import { difference, pick } from 'lodash'
import { ExtractedAttr, ExtractedAttrAttr, ExtractorParseProps, Ternary } from '../types'
import { createEvaluator, createSafeEvaluator } from './createEvaluator'
import { evaluateAstNode } from './evaluateAstNode'
import { attrStr, findComponentName, isInsideTamagui, isPresent, objToStr } from './extractHelpers'
import { findTopmostFunction } from './findTopmostFunction'
import { getStaticBindingsForScope } from './getStaticBindingsForScope'
import { literalToAst } from './literalToAst'
import { loadTamagui } from './loadTamagui'
import { logLines } from './logLines'
import { normalizeTernaries } from './normalizeTernaries'
import { removeUnusedHooks } from './removeUnusedHooks'
const { mediaQueryConfig, postProcessStyles, pseudos } = CoreNode
export const FAILED_EVAL = Symbol('failed_style_eval')
const UNTOUCHED_PROPS = {
key: true,
style: true,
className: true,
}
const isAttr = (x: ExtractedAttr): x is ExtractedAttrAttr => x.type === 'attr'
const validHooks = {
useMedia: true,
useTheme: true,
}
export type Extractor = ReturnType<typeof createExtractor>
const createTernary = (x: Ternary) => x
export function createExtractor() {
const shouldAddDebugProp =
// really basic disable this for next.js because it messes with ssr
!process.env.npm_package_dependencies_next &&
process.env.TAMAGUI_TARGET !== 'native' &&
process.env.IDENTIFY_TAGS !== 'false' &&
(process.env.NODE_ENV === 'development' || process.env.DEBUG || process.env.IDENTIFY_TAGS)
// ts imports
require('esbuild-register/dist/node').register({
target: 'es2019',
format: 'cjs',
})
let loadedTamaguiConfig: TamaguiInternalConfig
let hasLogged = false
return {
getTamagui() {
return loadedTamaguiConfig
},
parse: (
fileOrPath: NodePath<t.Program> | t.File,
{
config = 'tamagui.config.ts',
importsWhitelist = ['constants.js'],
evaluateVars = true,
shouldPrintDebug = false,
sourcePath = '',
onExtractTag,
getFlattenedNode,
disableExtraction,
disableExtractInlineMedia,
disableExtractVariables,
disableDebugAttr,
...props
}: ExtractorParseProps
) => {
if (sourcePath === '') {
throw new Error(`Must provide a source file name`)
}
if (!Array.isArray(props.components)) {
throw new Error(`Must provide components array with list of Tamagui component modules`)
}
// we require it after parse because we need to set some global/env stuff before importing
// otherwise we'd import `rnw` and cause it to evaluate react-native-web which causes errors
const { components, tamaguiConfig } = loadTamagui({
config,
components: props.components || ['tamagui'],
})
loadedTamaguiConfig = tamaguiConfig
const defaultTheme = tamaguiConfig.themes[Object.keys(tamaguiConfig.themes)[0]]
const body = fileOrPath.type === 'Program' ? fileOrPath.get('body') : fileOrPath.program.body
/**
* Step 1: Determine if importing any statically extractable components
*/
const isInternalImport = (importStr: string) => {
return isInsideTamagui(sourcePath) && importStr[0] === '.'
}
const validComponents: { [key: string]: any } = Object.keys(components)
// check if uppercase to avoid hitting media query proxy before init
.filter((key) => key[0].toUpperCase() === key[0] && !!components[key]?.staticConfig)
.reduce((obj, name) => {
obj[name] = components[name]
return obj
}, {})
let doesUseValidImport = false
for (const bodyPath of body) {
if (bodyPath.type !== 'ImportDeclaration') continue
const node = ('node' in bodyPath ? bodyPath.node : bodyPath) as any
const from = node.source.value
if (props.components.includes(from) || isInternalImport(from)) {
if (
node.specifiers.some((specifier) => {
const name = specifier.local.name
return validComponents[name] || validHooks[name]
})
) {
doesUseValidImport = true
break
}
}
}
if (shouldPrintDebug) {
console.log(sourcePath, { doesUseValidImport })
}
if (!doesUseValidImport) {
return null
}
let couldntParse = false
const modifiedComponents = new Set<NodePath<any>>()
// only keeping a cache around per-file, reset it if it changes
const bindingCache: Record<string, string | null> = {}
const callTraverse = (a: Visitor<{}>) => {
return fileOrPath.type === 'File' ? traverse(fileOrPath, a) : fileOrPath.traverse(a)
}
/**
* Step 2: Statically extract from JSX < /> nodes
*/
let programPath: NodePath<t.Program>
const res = {
flattened: 0,
optimized: 0,
modified: 0,
}
callTraverse({
Program: {
enter(path) {
programPath = path
},
},
JSXElement(traversePath) {
const node = traversePath.node.openingElement
const ogAttributes = node.attributes
const componentName = findComponentName(traversePath.scope)
const closingElement = traversePath.node.closingElement
// skip non-identifier opening elements (member expressions, etc.)
if (t.isJSXMemberExpression(closingElement?.name) || !t.isJSXIdentifier(node.name)) {
return
}
// validate its a proper import from tamagui (or internally inside tamagui)
const binding = traversePath.scope.getBinding(node.name.name)
if (binding) {
if (!t.isImportDeclaration(binding.path.parent)) {
return
}
const source = binding.path.parent.source
if (!props.components.includes(source.value) && !isInternalImport(source.value)) {
return
}
if (!validComponents[binding.identifier.name]) {
return
}
}
const component = validComponents[node.name.name] as { staticConfig?: StaticConfigParsed }
if (!component || !component.staticConfig) {
return
}
const originalNodeName = node.name.name
if (shouldPrintDebug) {
console.log(`\n<${originalNodeName} />`)
}
const filePath = sourcePath.replace(process.cwd(), '.')
const lineNumbers = node.loc
? node.loc.start.line +
(node.loc.start.line !== node.loc.end.line ? `-${node.loc.end.line}` : '')
: ''
// add data-is
if (shouldAddDebugProp && !disableDebugAttr) {
const preName = componentName ? `${componentName}:` : ''
res.modified++
node.attributes.unshift(
t.jsxAttribute(
t.jsxIdentifier('data-is'),
t.stringLiteral(
` ${preName}${node.name.name} ${filePath.replace('./', '')}:${lineNumbers} `
)
)
)
}
if (disableExtraction) {
if (!hasLogged) {
console.log('🥚 Tamagui disableExtraction set: no CSS or optimizations will be run')
hasLogged = true
}
return
}
const { staticConfig } = component
const isTextView = staticConfig.isText || false
const validStyles = staticConfig?.validStyles ?? {}
// find tag="a" tag="main" etc dom indicators
let tagName = staticConfig.defaultProps?.tag ?? (isTextView ? 'span' : 'div')
traversePath
.get('openingElement')
.get('attributes')
.forEach((path) => {
const attr = path.node
if (t.isJSXSpreadAttribute(attr)) return
if (attr.name.name !== 'tag') return
const val = attr.value
if (!t.isStringLiteral(val)) return
tagName = val.value
})
const flatNode = getFlattenedNode({ isTextView, tag: tagName })
const deoptProps = new Set([
...(props.deoptProps ?? []),
...(staticConfig.deoptProps ?? []),
])
const excludeProps = new Set(props.excludeProps ?? [])
const isExcludedProp = (name: string) => {
const res = excludeProps.has(name)
if (res && shouldPrintDebug) console.log(` excluding ${name}`)
return res
}
const isDeoptedProp = (name: string) => {
const res = deoptProps.has(name)
if (res && shouldPrintDebug) console.log(` deopting ${name}`)
return res
}
// Generate scope object at this level
const staticNamespace = getStaticBindingsForScope(
traversePath.scope,
importsWhitelist,
sourcePath,
bindingCache,
shouldPrintDebug
)
const attemptEval = !evaluateVars
? evaluateAstNode
: createEvaluator({
tamaguiConfig,
staticNamespace,
sourcePath,
traversePath,
shouldPrintDebug,
})
const attemptEvalSafe = createSafeEvaluator(attemptEval)
if (shouldPrintDebug) {
console.log(' staticNamespace', Object.keys(staticNamespace).join(', '))
}
//
// SPREADS SETUP
//
// TODO restore
const hasDeopt = (obj: Object) => {
return Object.keys(obj).some(isDeoptedProp)
}
// flatten any easily evaluatable spreads
const flattenedAttrs: (t.JSXAttribute | t.JSXSpreadAttribute)[] = []
traversePath
.get('openingElement')
.get('attributes')
.forEach((path) => {
const attr = path.node
if (!t.isJSXSpreadAttribute(attr)) {
flattenedAttrs.push(attr)
return
}
let arg: any
try {
arg = attemptEval(attr.argument)
} catch (e: any) {
if (shouldPrintDebug) {
console.log(' couldnt parse spread', e.message)
}
flattenedAttrs.push(attr)
return
}
if (typeof arg !== 'undefined') {
try {
if (typeof arg !== 'object' || arg == null) {
if (shouldPrintDebug) {
console.log(' non object or null arg', arg)
}
flattenedAttrs.push(attr)
} else {
for (const k in arg) {
const value = arg[k]
// this is a null prop:
if (!value && typeof value === 'object') {
console.log('shouldnt we handle this?', k, value, arg)
continue
}
flattenedAttrs.push(
t.jsxAttribute(
t.jsxIdentifier(k),
t.jsxExpressionContainer(literalToAst(value))
)
)
}
}
} catch (err) {
console.warn('cant parse spread, caught err', err)
couldntParse = true
}
}
})
if (couldntParse) {
return
}
// set flattened
node.attributes = flattenedAttrs
// add in default props
if (staticConfig.defaultProps) {
for (const key in staticConfig.defaultProps) {
const serialize = require('babel-literal-to-ast')
const val = staticConfig.defaultProps[key]
node.attributes.unshift(
t.jsxAttribute(
t.jsxIdentifier(key),
typeof val === 'string'
? t.stringLiteral(val)
: t.jsxExpressionContainer(serialize(val))
)
)
}
}
let attrs: ExtractedAttr[] = []
let shouldDeopt = false
let inlinePropCount = 0
let isFlattened = false
// RUN first pass
// normalize all conditionals so we can evaluate away easier later
// at the same time lets normalize shorthand media queries into spreads:
// that way we can parse them with the same logic later on
//
// {...media.sm && { color: x ? 'red' : 'blue' }}
// => {...media.sm && x && { color: 'red' }}
// => {...media.sm && !x && { color: 'blue' }}
//
// $sm={{ color: 'red' }}
// => {...media.sm && { color: 'red' }}
//
// $sm={{ color: x ? 'red' : 'blue' }}
// => {...media.sm && x && { color: 'red' }}
// => {...media.sm && !x && { color: 'blue' }}
attrs = traversePath
.get('openingElement')
.get('attributes')
.flatMap((path) => {
try {
const res = evaluateAttribute(path)
if (!res) {
path.remove()
}
return res
} catch (err: any) {
console.log('Error extracting attribute', err.message, err.stack)
console.log('node', path.node)
return {
type: 'attr',
value: path.node,
} as const
}
})
.flat(4)
.filter(isPresent)
function isStaticAttributeName(name: string) {
return !!(
!!validStyles[name] ||
staticConfig.validPropsExtra?.[name] ||
!!pseudos[name] ||
staticConfig.variants?.[name] ||
tamaguiConfig.shorthands[name] ||
(name[0] === '$' ? !!mediaQueryConfig[name.slice(1)] : false)
)
}
function isExtractable(obj: t.Node): obj is t.ObjectExpression {
return (
t.isObjectExpression(obj) &&
obj.properties.every((prop) => {
if (!t.isObjectProperty(prop)) {
console.log('not object prop', prop)
return false
}
const propName = prop.key['name']
if (!isStaticAttributeName(propName) && propName !== 'tag') {
if (shouldPrintDebug) {
console.log(' not a valid style prop!', propName)
}
return false
}
return true
})
)
}
// side <= { color: 'red', background: x ? 'red' : 'green' }
// | => Ternary<test, { color: 'red' }, null>
// | => Ternary<test && x, { background: 'red' }, null>
// | => Ternary<test && !x, { background: 'green' }, null>
function createTernariesFromObjectProperties(
test: t.Expression,
side: t.Expression | null,
ternaryPartial: Partial<Ternary> = {}
): null | Ternary[] {
if (!side) {
return null
}
if (!isExtractable(side)) {
throw new Error('not extractable')
}
return side.properties.flatMap((property) => {
if (!t.isObjectProperty(property)) {
throw new Error('expected object property')
}
// this could be a recurse here if we want to get fancy
if (t.isConditionalExpression(property.value)) {
// merge up into the parent conditional, split into two
const [truthy, falsy] = [
t.objectExpression([t.objectProperty(property.key, property.value.consequent)]),
t.objectExpression([t.objectProperty(property.key, property.value.alternate)]),
].map((x) => attemptEval(x))
return [
createTernary({
remove() {},
...ternaryPartial,
test: t.logicalExpression('&&', test, property.value.test),
consequent: truthy,
alternate: null,
}),
createTernary({
...ternaryPartial,
test: t.logicalExpression(
'&&',
test,
t.unaryExpression('!', property.value.test)
),
consequent: falsy,
alternate: null,
remove() {},
}),
]
}
const obj = t.objectExpression([t.objectProperty(property.key, property.value)])
const consequent = attemptEval(obj)
return createTernary({
remove() {},
...ternaryPartial,
test,
consequent,
alternate: null,
})
})
}
// START function evaluateAttribute
function evaluateAttribute(
path: NodePath<t.JSXAttribute | t.JSXSpreadAttribute>
): ExtractedAttr | ExtractedAttr[] | null {
const attribute = path.node
const attr: ExtractedAttr = { type: 'attr', value: attribute }
// ...spreads
if (t.isJSXSpreadAttribute(attribute)) {
const arg = attribute.argument
const conditional = t.isConditionalExpression(arg)
? // <YStack {...isSmall ? { color: 'red } : { color: 'blue }}
([arg.test, arg.consequent, arg.alternate] as const)
: t.isLogicalExpression(arg) && arg.operator === '&&'
? // <YStack {...isSmall && { color: 'red }}
([arg.left, arg.right, null] as const)
: null
if (conditional) {
const [test, alt, cons] = conditional
if (!test) throw new Error(`no test`)
if ([alt, cons].some((side) => side && !isExtractable(side))) {
if (shouldPrintDebug) {
console.log('not extractable', alt, cons)
}
return attr
}
// split into individual ternaries per object property
return [
...(createTernariesFromObjectProperties(test, alt) || []),
...((cons &&
createTernariesFromObjectProperties(t.unaryExpression('!', test), cons)) ||
[]),
].map((ternary) => ({
type: 'ternary',
value: ternary,
}))
}
}
// END ...spreads
// directly keep these
// couldn't evaluate spread, undefined name, or name is not string
if (
t.isJSXSpreadAttribute(attribute) ||
!attribute.name ||
typeof attribute.name.name !== 'string'
) {
inlinePropCount++
return attr
}
const name = attribute.name.name
if (isExcludedProp(name)) {
return null
}
// can still optimize the object... see hoverStyle on native
if (isDeoptedProp(name)) {
if (shouldPrintDebug) {
console.log(' ! inlining, deopt prop', name)
}
inlinePropCount++
return attr
}
// pass className, key, and style props through untouched
if (UNTOUCHED_PROPS[name]) {
return attr
}
// shorthand media queries
if (name[0] === '$' && t.isJSXExpressionContainer(attribute?.value)) {
// allow disabling this extraction
if (disableExtractInlineMedia) {
return attr
}
const shortname = name.slice(1)
if (mediaQueryConfig[shortname]) {
const expression = attribute.value.expression
if (!t.isJSXEmptyExpression(expression)) {
const ternaries = createTernariesFromObjectProperties(
t.stringLiteral(shortname),
expression,
{
inlineMediaQuery: shortname,
}
)
if (ternaries) {
return ternaries.map((value) => ({
type: 'ternary',
value,
}))
}
}
}
}
const [value, valuePath] = (() => {
if (t.isJSXExpressionContainer(attribute?.value)) {
return [attribute.value.expression!, path.get('value')!] as const
} else {
return [attribute.value!, path.get('value')!] as const
}
})()
const remove = () => {
Array.isArray(valuePath) ? valuePath.map((p) => p.remove()) : valuePath.remove()
}
if (name === 'ref') {
if (shouldPrintDebug) {
console.log(' ! inlining, ref', name)
}
inlinePropCount++
return attr
}
if (name === 'tag') {
return {
type: 'attr',
value: path.node,
}
}
// native shouldn't extract variables
if (disableExtractVariables) {
if (value) {
if (value.type === 'StringLiteral' && value.value[0] === '$') {
if (shouldPrintDebug) {
console.log(' native, disable extract var', value.value)
}
inlinePropCount++
return attr
}
}
}
// if value can be evaluated, extract it and filter it out
const styleValue = attemptEvalSafe(value)
// never flatten if a prop isn't a valid static attribute
// only post prop-mapping
if (!isStaticAttributeName(name)) {
let keys = [name]
if (staticConfig.propMapper) {
// for now passing empty props {}, a bit odd, need to at least document
// for now we don't expose custom components so just noting behavior
const out = staticConfig.propMapper(
name,
styleValue,
defaultTheme,
staticConfig.defaultProps
)
if (out) {
keys = Object.keys(out)
}
}
if (keys.some((k) => !isStaticAttributeName(k) && k !== 'tag')) {
if (shouldPrintDebug) {
console.log(' ! inlining, not static attribute name', name)
}
inlinePropCount++
return attr
}
}
// FAILED = dynamic or ternary, keep going
if (styleValue !== FAILED_EVAL) {
return {
type: 'style',
value: { [name]: styleValue },
name,
attr: path.node,
}
}
// ternaries!
// binary ternary, we can eventually make this smarter but step 1
// basically for the common use case of:
// opacity={(conditional ? 0 : 1) * scale}
if (t.isBinaryExpression(value)) {
const { operator, left, right } = value
// if one side is a ternary, and the other side is evaluatable, we can maybe extract
const lVal = attemptEvalSafe(left)
const rVal = attemptEvalSafe(right)
if (shouldPrintDebug) {
console.log(` evalBinaryExpression lVal ${String(lVal)}, rVal ${String(rVal)}`)
}
if (lVal !== FAILED_EVAL && t.isConditionalExpression(right)) {
const ternary = addBinaryConditional(operator, left, right)
if (ternary) return ternary
}
if (rVal !== FAILED_EVAL && t.isConditionalExpression(left)) {
const ternary = addBinaryConditional(operator, right, left)
if (ternary) return ternary
}
if (shouldPrintDebug) {
console.log(` evalBinaryExpression cant extract`)
}
inlinePropCount++
return attr
}
const staticConditional = getStaticConditional(value)
if (staticConditional) {
return { type: 'ternary', value: staticConditional }
}
const staticLogical = getStaticLogical(value)
if (staticLogical) {
return { type: 'ternary', value: staticLogical }
}
if (shouldPrintDebug) {
console.log(' ! inline prop via no match', name, value.type)
}
// if we've made it this far, the prop stays inline
inlinePropCount++
//
// RETURN ATTR
//
return attr
// attr helpers:
function addBinaryConditional(
operator: any,
staticExpr: any,
cond: t.ConditionalExpression
): ExtractedAttr | null {
if (getStaticConditional(cond)) {
const alt = attemptEval(t.binaryExpression(operator, staticExpr, cond.alternate))
const cons = attemptEval(t.binaryExpression(operator, staticExpr, cond.consequent))
if (shouldPrintDebug) {
console.log(' binaryConditional', cond.test, cons, alt)
}
return {
type: 'ternary',
value: {
test: cond.test,
remove,
alternate: { [name]: alt },
consequent: { [name]: cons },
},
}
}
return null
}
function getStaticConditional(value: t.Node): Ternary | null {
if (t.isConditionalExpression(value)) {
try {
if (shouldPrintDebug) {
console.log('attempt', value.alternate, value.consequent)
}
const aVal = attemptEval(value.alternate)
const cVal = attemptEval(value.consequent)
if (shouldPrintDebug) {
const type = value.test.type
console.log(' static ternary', type, cVal, aVal)
}
return {
test: value.test,
remove,
consequent: { [name]: cVal },
alternate: { [name]: aVal },
}
} catch (err: any) {
if (shouldPrintDebug) {
console.log(' cant eval ternary', err.message)
}
}
}
return null
}
function getStaticLogical(value: t.Node): Ternary | null {
if (t.isLogicalExpression(value)) {
if (value.operator === '&&') {
try {
const val = attemptEval(value.right)
if (shouldPrintDebug) {
console.log(' staticLogical', value.left, name, val)
}
return {
test: value.left,
remove,
consequent: { [name]: val },
alternate: null,
}
} catch (err) {
if (shouldPrintDebug) {
console.log(' cant static eval logical', err)
}
}
}
}
return null
}
} // END function evaluateAttribute
// see if we can filter them
if (shouldPrintDebug) {
console.log(' - attrs (before):\n', logLines(attrs.map(attrStr).join(', ')))
}
// now update to new values
node.attributes = attrs.filter(isAttr).map((x) => x.value)
if (couldntParse) {
if (shouldPrintDebug) {
console.log(` cancel:`, { couldntParse, shouldDeopt })
}
node.attributes = ogAttributes
return
}
// before deopt, can still optimize
const parentFn = findTopmostFunction(traversePath)
if (parentFn) {
modifiedComponents.add(parentFn)
}
// combine ternaries
let ternaries: Ternary[] = []
attrs = attrs
.reduce<(ExtractedAttr | ExtractedAttr[])[]>((out, cur) => {
const next = attrs[attrs.indexOf(cur) + 1]
if (cur.type === 'ternary') {
ternaries.push(cur.value)
}
if ((!next || next.type !== 'ternary') && ternaries.length) {
// finish, process
const normalized = normalizeTernaries(ternaries).map(
({ alternate, consequent, ...rest }) => {
return {
type: 'ternary' as const,
value: {
...rest,
alternate: alternate || null,
consequent: consequent || null,
},
}
}
)
try {
return [...out, ...normalized]
} finally {
if (shouldPrintDebug) {
console.log(
` normalizeTernaries (${ternaries.length} => ${normalized.length})`
)
}
ternaries = []
}
}
if (cur.type === 'ternary') {
return out
}
out.push(cur)
return out
}, [])
.flat()
// evaluates all static attributes into a simple object
const completeStaticProps = {
...Object.keys(attrs).reduce((acc, index) => {
const cur = attrs[index] as ExtractedAttr
if (cur.type === 'style') {
Object.assign(acc, cur.value)
}
if (cur.type === 'attr') {
if (t.isJSXSpreadAttribute(cur.value)) {
return acc
}
if (!t.isJSXIdentifier(cur.value.name)) {
return acc
}
const key = cur.value.name.name
// undefined = boolean true
const value = attemptEvalSafe(cur.value.value || t.booleanLiteral(true))
if (value === FAILED_EVAL) {
return acc
}
acc[key] = value
}
return acc
}, {}),
}
// flatten logic!
// fairly simple check to see if all children are text
const hasSpread = node.attributes.some((x) => t.isJSXSpreadAttribute(x))
const hasOnlyStringChildren =
!hasSpread &&
(node.selfClosing ||
(traversePath.node.children &&
traversePath.node.children.every((x) => x.type === 'JSXText')))
const shouldFlatten =
!shouldDeopt &&
inlinePropCount === 0 &&
!hasSpread &&
staticConfig.neverFlatten !== true &&
(staticConfig.neverFlatten === 'jsx' ? hasOnlyStringChildren : true)
// insert overrides - this inserts null props for things that are set in classNames
// only when not flattening, so the downstream component can skip applying those styles
if (!shouldFlatten) {
attrs = attrs.reduce<ExtractedAttr[]>((acc, cur) => {
if (cur.type === 'style') {
// TODO need to loop over initial props not just style props
for (const key in cur.value) {
const shouldEnsureOverridden = !!staticConfig.ensureOverriddenProp?.[key]
const isSetInAttrsAlready = attrs.some(
(x) =>
x.type === 'attr' &&
x.value.type === 'JSXAttribute' &&
x.value.name.name === key
)
if (!isSetInAttrsAlready) {
const isVariant = !!staticConfig.variants?.[cur.name || '']
if (isVariant || shouldEnsureOverridden) {
acc.push({
type: 'attr',
value:
cur.attr ||
t.jsxAttribute(
t.jsxIdentifier(key),
t.jsxExpressionContainer(t.nullLiteral())
),
})
}
}
}
}
acc.push(cur)
return acc
}, [])
}
if (shouldPrintDebug) {
console.log(' - attrs (flattened): \n', logLines(attrs.map(attrStr).join(', ')))
}
// evaluate away purely style props
attrs = attrs.reduce<ExtractedAttr[]>((acc, cur) => {
if (
cur.type !== 'attr' ||
!t.isJSXAttribute(cur.value) ||
typeof cur.value.name.name !== 'string'
) {
if (cur.type === 'style') {
const key = Object.keys(cur.value)[0]
if (!validStyles[key] && !pseudos[key]) {
if (shouldPrintDebug) {
console.log(' ❌ excluding', key)
}
// we've already expanded shorthands, now we can remove them
return acc
}
}
}
acc.push(cur)
return acc
}, [])
if (shouldPrintDebug) {
console.log(' - attrs (evaluated styles): \n', logLines(attrs.map(attrStr).join(', ')))
}
// combine styles, leave undefined values
let prev: ExtractedAttr | null = null
attrs = attrs.reduce<ExtractedAttr[]>((acc, cur) => {
if (cur.type === 'style') {
if (prev?.type === 'style') {
Object.assign(prev.value, cur.value)
return acc
}
}
acc.push(cur)
prev = cur
return acc
}, [])
if (shouldPrintDebug) {
console.log(' - attrs (combined 🔀): \n', logLines(attrs.map(attrStr).join(', ')))
}
// post process
const getStyles = (props: Object | null) => {
if (!props) return
if (!!excludeProps.size) {
for (const key in props) {
if (isExcludedProp(key)) delete props[key]
}
}
const out = postProcessStyles(props, staticConfig, defaultTheme)
const next = out?.style ?? props
if (shouldPrintDebug) {
console.log(' getStyles props >>\n', logLines(objToStr(props)))
console.log(' getStyles next >>\n', logLines(objToStr(next)))
console.log(' getStyles style >>\n', logLines(objToStr(out.style)))
console.log(' getStyles viewp >>\n', logLines(objToStr(out.viewProps)))
}
if (staticConfig.validStyles) {
for (const key in next) {
if (!staticConfig.validStyles[key] && !pseudos[key]) {
delete next[key]
}
}
}
return next
}
// used to ensure we pass the entire prop bundle to getStyles
const completeStylesProcessed = getStyles({
...staticConfig.defaultProps,
...completeStaticProps,
})
// any extra styles added in postprocess should be added to first group as they wont be overriden
const stylesToAddToInitialGroup = difference(
Object.keys(completeStylesProcessed),
Object.keys(completeStaticProps)
)
if (stylesToAddToInitialGroup.length) {
const toAdd = pick(completeStylesProcessed, ...stylesToAddToInitialGroup)
const firstGroup = attrs.find((x) => x.type === 'style')
if (shouldPrintDebug) {
console.log(' stylesToAddToInitialGroup', stylesToAddToInitialGroup.join(', '))
console.log(' toAdd', objToStr(toAdd))
}
if (!firstGroup) {
attrs.unshift({ type: 'style', value: toAdd })
} else {
Object.assign(firstGroup.value, toAdd)
}
}
if (shouldPrintDebug) {
// prettier-ignore
console.log(' completeStaticProps\n', logLines(objToStr(completeStaticProps)))
// prettier-ignore
console.log(' completeStylesProcessed\n', logLines(objToStr(completeStylesProcessed)))
}
for (const attr of attrs) {
try {
switch (attr.type) {
case 'ternary':
const a = getStyles(attr.value.alternate)
const c = getStyles(attr.value.consequent)
attr.value.alternate = a
attr.value.consequent = c
if (shouldPrintDebug) {
console.log(' => tern ', attrStr(attr))
}
break
case 'style':
const next = {}
for (const key in attr.value) {
if (key in stylePropsTransform) {
// TODO this logic needs to be a bit more right, because could have spread in between transforms...
next['transform'] = completeStylesProcessed['transform']
} else {
next[key] = completeStylesProcessed[key] ?? attr.value[key]
}
}
attr.value = next
break
}
} catch (err) {
// any error de-opt
if (shouldPrintDebug) {
console.log(' postprocessing error, deopt', err)
node.attributes = ogAttributes
return node
}
}
}
if (shouldPrintDebug) {
console.log(' - attrs (after):\n', logLines(attrs.map(attrStr).join(', ')))
}
if (shouldFlatten) {
// DO FLATTEN
if (shouldPrintDebug) {
console.log(' [✅] flattening', originalNodeName, flatNode)
}
isFlattened = true
node.name.name = flatNode
res.flattened++
if (closingElement) {
closingElement.name.name = flatNode
}
}
if (shouldPrintDebug) {
// prettier-ignore
console.log(' [❊] inline props ', inlinePropCount, shouldDeopt ? ' deopted' : '', hasSpread ? ' spread' : '', '!flatten', staticConfig.neverFlatten)
console.log(' - attrs (end):\n', logLines(attrs.map(attrStr).join(', ')))
}
res.optimized++
onExtractTag({
attrs,
node,
lineNumbers,
filePath,
attemptEval,
jsxPath: traversePath,
originalNodeName,
isFlattened,
programPath,
})
},
})
/**
* Step 3: Remove dead code from removed media query / theme hooks
*/
if (modifiedComponents.size) {
const all = Array.from(modifiedComponents)
if (shouldPrintDebug) {
console.log(' [🪝] hook check', all.length)
}
for (const comp of all) {
removeUnusedHooks(comp, shouldPrintDebug)
}
}
return res
},
}
} | the_stack |
import BaseTokenizer from '../../i18n/tokenizer/base';
import { uniform, coin } from '../../utils/random';
import * as TemplateGrammar from './grammar';
interface LanguagePack {
locale : string,
getTokenizer() : BaseTokenizer;
}
/**
* Natural language template language that supports grammar-based constraints
* to handle agreement in number, tense, gender, etc.
*
*/
type FlagValue = string|number;
/**
* The result of replacing placeholders in a template.
*
* This is a tree of strings or choices, each associated with flags.
*/
export abstract class ReplacedResult {
static EMPTY : ReplacedResult;
/**
* Apply a flag constraint to this tree.
*
* Returns a constrained tree, or null if no possible set of choices
* is valid.
*
*/
abstract constrain(flag : string, value : FlagValue) : ReplacedResult|null;
abstract chooseSample(rng : () => number) : string;
abstract chooseBest() : string;
}
class EmptyReplacement extends ReplacedResult {
constrain(flag : string, value : FlagValue) {
return this;
}
chooseSample(rng : () => number) {
return '';
}
chooseBest() {
return '';
}
}
ReplacedResult.EMPTY = new EmptyReplacement();
function whitespaceJoin(iterable : Iterable<unknown>, joiner = '') {
joiner = joiner.trim();
let buf = '';
for (const element of iterable) {
const string = (typeof element === 'string' ? element : String(element)).trim();
if (!string)
continue;
if (buf) {
buf += ' ';
if (joiner) {
buf += joiner;
buf += ' ';
}
}
buf += string;
}
return buf;
}
export class ReplacedConcatenation extends ReplacedResult {
constructor(public text : Array<string|ReplacedResult>,
public constFlags : Record<string, FlagValue>,
public refFlags : Record<string, [number, string]>) {
super();
}
toString() {
const buf = this.text.map((t) => '{' + t + '}').join(' ');
const flags = [];
for (const flag in this.constFlags)
flags.push(`${flag}=${this.constFlags[flag]}`);
for (const flag in this.refFlags)
flags.push(`${flag}=${this.refFlags[flag][0]}[${this.refFlags[flag][1]}]`);
if (flags.length > 0)
return buf + ` [${flags.join(',')}]`;
else
return buf;
}
constrain(flag : string, value : FlagValue) : ReplacedResult|null {
if (flag in this.constFlags) {
const ourValue = this.constFlags[flag];
if (ourValue === value)
return this;
else
return null;
}
if (flag in this.refFlags) {
const [index, subflag] = this.refFlags[flag];
const toConstrain = this.text[index];
if (!(toConstrain instanceof ReplacedResult))
return this;
const constrained = toConstrain.constrain(subflag, value);
if (constrained === null)
return null;
const newText = this.text.slice(0, index);
newText.push(constrained);
newText.push(...this.text.slice(index+1));
const newFlags : Record<string, FlagValue> = {};
Object.assign(newFlags, this.constFlags);
newFlags[flag] = value;
const newRefFlags : Record<string, [number, string]> = {};
Object.assign(newRefFlags, this.refFlags);
delete newRefFlags[flag];
return new ReplacedConcatenation(newText, newFlags, newRefFlags);
}
// no constraint at all
return this;
}
chooseSample(rng : () => number) {
const text = this.text.map((t) => typeof t === 'string' ? t : t.chooseSample(rng));
return whitespaceJoin(text);
}
chooseBest() {
const text = this.text.map((t) => typeof t === 'string' ? t : t.chooseBest());
return whitespaceJoin(text);
}
}
export class ReplacedChoice extends ReplacedResult {
constructor(public choices : ReplacedResult[]) {
super();
}
toString() {
return `{${this.choices.join('|')}}`;
}
constrain(flag : string, value : FlagValue) : ReplacedResult|null {
const constrained = this.choices.map((c) => c.constrain(flag, value))
.filter((x) : x is ReplacedResult => x !== null);
if (constrained.length === 0)
return null;
if (constrained.length === 1)
return constrained[0];
return new ReplacedChoice(constrained);
}
chooseSample(rng : () => number) {
return uniform(this.choices, rng).chooseSample(rng);
}
chooseBest() {
return this.choices[0].chooseBest();
}
}
type ListFormatPart = {
type : 'literal',
value : string
} | {
type : 'element',
value : string
};
export class ReplacedList extends ReplacedResult {
constructor(public elements : ReplacedResult[],
public locale : string,
public listType : string|undefined) {
super();
}
get length() {
return this.elements.length;
}
private _makeList(elements : unknown[], listType : string) : string {
if (listType === 'disjunction' ||
listType === 'conjunction') {
const strings = elements.map((el) => String(el));
const formatted = new (Intl as any).ListFormat(this.locale, { type: listType })
.formatToParts(strings);
return whitespaceJoin(formatted.map((el : ListFormatPart) => el.type === 'literal' ? el.value.trim() : el.value));
}
return whitespaceJoin(elements, this.listType);
}
toString() {
return this._makeList(this.elements, 'conjunction');
}
constrain(flag : string, value : FlagValue) : ReplacedResult|null {
const mapped : ReplacedResult[] = [];
for (const el of this.elements) {
const constrained = el.constrain(flag, value);
if (constrained === null)
return null;
mapped.push(el);
}
if (flag === 'list_type') {
if (this.listType === undefined)
return new ReplacedList(mapped, this.locale, String(value));
else if (this.listType !== value)
return null;
}
return new ReplacedList(mapped, this.locale, this.listType);
}
chooseSample(rng : () => number) {
const listType = this.listType === undefined ?
(coin(0.5, rng) ? 'conjunction' : 'disjunction') : this.listType;
return this._makeList(this.elements.map((el) => el.chooseSample(rng)), listType);
}
chooseBest() {
return this._makeList(this.elements.map((el) => el.chooseBest()),
this.listType ?? 'conjunction');
}
}
/**
* An object that represents the value with which to replace a placeholder.
*/
export interface PlaceholderReplacement {
value : any;
text : ReplacedResult;
}
type PlaceholderConstraints = Record<number, Record<string, FlagValue>>;
// AST objects (representations of a parsed template)
interface ReplacementContext {
replacements : Record<number, PlaceholderReplacement|undefined>;
constraints : PlaceholderConstraints;
}
export abstract class Replaceable {
private static _cache = new Map<string, Replaceable>();
static EMPTY : Replaceable;
/**
* Parse a template string into a replaceable object.
*/
static parse(template : string) : Replaceable {
return TemplateGrammar.parse(template);
}
/**
* Parse a template string into a replaceable object, and preprocess
* it immediately.
*
* This method differs from {@link Replaceable.parse} because it will
* cache the result so it is fast to call multiple times for the same string.
*/
static get(template : string, langPack : LanguagePack, names : string[]) {
const cacheKey = langPack.locale + '/' + template;
const cached = Replaceable._cache.get(cacheKey);
if (cached)
return cached;
const parsed : Replaceable = TemplateGrammar.parse(template);
parsed.preprocess(langPack, names);
Replaceable._cache.set(cacheKey, parsed);
return parsed;
}
abstract visit(cb : (repl : Replaceable) => boolean) : void;
abstract preprocess(langPack : LanguagePack, placeholders : string[]) : this;
abstract optimize(constraints : PlaceholderConstraints) : Replaceable|null;
abstract replace(ctx : ReplacementContext) : ReplacedResult|null;
}
/**
* A named placeholder.
*
* A placeholder can be followed by an option. The meaning of the option is not
* defined at this level.
*/
export class Placeholder extends Replaceable {
private _index : number|undefined = undefined;
constructor(public param : string,
public key : string[] = [],
public option : string = '') {
super();
}
toString() {
return `\${${this.param}${this.key.length > 0 ? '.' + this.key.join('.') : ''}`
+ (this.option ? `:${this.option}` : '') + '}';
}
visit(cb : (repl : Replaceable) => boolean) {
cb(this);
}
preprocess(langPack : LanguagePack, placeholders : string[]) {
this._index = getPlaceholderIndex(placeholders, this.param);
return this;
}
optimize() {
return this;
}
replace(ctx : ReplacementContext) : ReplacedResult|null {
const param = ctx.replacements[this._index!];
if (!param)
return null;
if (this.key.length > 0) {
const replacement = get(param.value, this.key);
if (replacement === null || replacement === undefined)
return null;
return new ReplacedConcatenation([String(replacement)], {}, {});
} else {
let replacement = param.text;
const paramConstraints = ctx.constraints[this._index!] || {};
for (const flag in paramConstraints) {
const value = paramConstraints[flag];
const maybeReplacement = replacement.constrain(flag, value);
if (maybeReplacement === null)
return null;
replacement = maybeReplacement;
}
return replacement;
}
}
}
/**
* A phrase that is already expressed as a replaced result.
*
* This is a Replaceable that does not contain any placeholder.
*/
export class ReplacedPhrase extends Replaceable {
constructor(public text : ReplacedResult) {
super();
}
clone() {
return new ReplacedPhrase(this.text);
}
toString() {
return this.text.toString();
}
visit(cb : (repl : Replaceable) => boolean) {
cb(this);
}
preprocess(langPack : LanguagePack, placeholders : string[]) {
return this;
}
optimize() {
return this;
}
replace(ctx : ReplacementContext) : ReplacedResult|null {
return this.text;
}
}
Replaceable.EMPTY = new ReplacedPhrase(ReplacedResult.EMPTY);
function templateEscape(str : string) {
return str.replace(/[${}|[\]\\]/g, '\\$0');
}
/**
* A piece of text with flags such as gender, number, tense, etc.
*
* In syntax, they are represented by free text followed by `[flag=value]`.
* Examples:
*
* `actor [gender=masculine]`
* `restaurants [plural=other]`
*/
export class Phrase extends Replaceable {
constructor(public text : string,
public flags : Record<string, string> = {}) {
super();
}
clone() {
const flags : Record<string, string> = {};
Object.assign(flags, this.flags);
return new Phrase(this.text, flags);
}
toString() {
const text = templateEscape(this.text);
const flags = [];
for (const flag in this.flags)
flags.push(`${flag}=${this.flags[flag]}`);
if (flags.length > 0)
return `${text} [${flags.join(',')}]`;
else
return text;
}
toReplaced() {
return new ReplacedConcatenation([this.text], this.flags, {});
}
visit(cb : (repl : Replaceable) => boolean) {
cb(this);
}
preprocess(langPack : LanguagePack, placeholders : string[]) {
const tokenizer = langPack.getTokenizer();
this.text = tokenizer.tokenize(this.text).rawTokens.join(' ');
return this;
}
optimize() {
return this;
}
replace(ctx : ReplacementContext) : ReplacedResult|null {
return new ReplacedConcatenation([this.text], this.flags, {});
}
}
function mergeConstraints(into : PlaceholderConstraints, newConstraints : PlaceholderConstraints) {
for (const placeholder in newConstraints) {
if (!(placeholder in into))
into[placeholder] = {};
for (const flag in newConstraints[placeholder])
into[placeholder][flag] = newConstraints[placeholder][flag];
}
}
/**
* Concatenation of multiple replaceable elements.
*
* The concatenation does not propagate the flags of the elements, but
* it has its own set of flags.
*/
export class Concatenation extends Replaceable {
private _computedRefFlags : Record<string, [number, string]> = {};
private _hasAnyFlag : boolean;
constructor(public children : Replaceable[],
public flags : Record<string, FlagValue>,
public refFlags : Record<string, [string|number, string]>) {
super();
this._hasAnyFlag = Object.keys(flags).length + Object.keys(refFlags).length > 0;
}
toString() {
const buf = this.children.join(' ');
const flags = [];
for (const flag in this.flags)
flags.push(`${flag}=${this.flags[flag]}`);
for (const flag in this.refFlags)
flags.push(`${flag}=${this.refFlags[flag][0]}[${this.refFlags[flag][1]}]`);
if (flags.length > 0)
return buf + ` [${flags.join(',')}]`;
else
return buf;
}
visit(cb : (repl : Replaceable) => boolean) {
if (!cb(this))
return;
for (const c of this.children)
c.visit(cb);
}
optimize(constraints : PlaceholderConstraints) {
const optimized = [];
let anyChange = false;
for (const c of this.children) {
const copt = c.optimize(constraints);
if (copt === null)
return null;
optimized.push(copt);
anyChange = anyChange || c !== copt;
}
if (!anyChange)
return this;
const optconcat = new Concatenation(optimized, this.flags, this.refFlags);
optconcat._computedRefFlags = this._computedRefFlags;
return optconcat;
}
preprocess(langPack : LanguagePack, placeholders : string[]) {
for (const c of this.children)
c.preprocess(langPack, placeholders);
for (const ourFlag in this.refFlags) {
const [placeholder, theirFlag] = this.refFlags[ourFlag];
if (typeof placeholder === 'number') {
if (placeholder < 0 || placeholder >= this.children.length)
throw new Error(`Invalid ref-flag [${ourFlag}=${placeholder}[${theirFlag}]]`);
this._computedRefFlags[ourFlag] = [placeholder, theirFlag];
} else {
let found = -1;
for (let i = 0; i < this.children.length; i++) {
const c = this.children[i];
if (c instanceof Placeholder && c.param === placeholder) {
found = i;
break;
}
}
if (found < 0)
throw new Error(`Invalid ref-flag [${ourFlag}=${placeholder}[${theirFlag}]], must refer to a placeholder immediately used in the same concatenation expression`);
this._computedRefFlags[ourFlag] = [found, theirFlag];
}
}
return this;
}
replace(ctx : ReplacementContext) : ReplacedResult|null {
const replaced : Array<string|ReplacedResult> = [];
for (const child of this.children) {
const childReplacement = child.replace(ctx);
if (childReplacement === null)
return null;
// if we don't have any flags, we can flatten the replacement
// if we do have flags, we cannot because it will change the meaning of the ref flags
if (!this._hasAnyFlag && childReplacement instanceof ReplacedConcatenation)
replaced.push(...childReplacement.text);
else
replaced.push(childReplacement);
}
return new ReplacedConcatenation(replaced, this.flags, this._computedRefFlags);
}
}
/**
* A phrase that has multiple equivalent variants.
*
* Different variants can set different flags, to account for gender,
* plural, case, tense, mood, etc.
*/
export class Choice implements Replaceable {
constructor(public variants : Replaceable[]) {
}
toString() {
return `{${this.variants.join('|')}}`;
}
preprocess(langPack : LanguagePack, placeholders : string[]) {
for (const v of this.variants)
v.preprocess(langPack, placeholders);
return this;
}
optimize(constraints : PlaceholderConstraints) : Replaceable|null {
const optimized = [];
let anyChange = false;
for (const v of this.variants) {
const vopt = v.optimize(constraints);
if (vopt === null) {
anyChange = true;
continue;
}
optimized.push(vopt);
anyChange = anyChange || v !== vopt;
}
if (optimized.length === 0)
return null;
else if (optimized.length === 1)
return optimized[0];
if (!anyChange)
return this;
return new Choice(optimized);
}
visit(cb : (repl : Replaceable) => boolean) {
if (!cb(this))
return;
for (const v of this.variants)
v.visit(cb);
}
replace(ctx : ReplacementContext) : ReplacedResult|null {
const variants : ReplacedResult[] = [];
for (const v of this.variants) {
const replaced = v.replace(ctx);
if (replaced === null)
continue;
variants.push(replaced);
}
if (variants.length === 0)
return null;
else if (variants.length === 1)
return variants[0];
else
return new ReplacedChoice(variants);
}
}
function get(value : any, keys : string[]) : unknown {
for (const key of keys) {
value = value[key];
if (value === null || value === undefined)
return value;
}
return value;
}
function getPlaceholderIndex(placeholders : string[], toFind : string) {
const index = placeholders.indexOf(toFind);
if (index < 0)
throw new TypeError(`Invalid placeholder \${${toFind}}, allowed placeholders are: ${placeholders.join(', ')}`);
return index;
}
/**
* A phrase that depends on a numeric value.
*
* The syntax is:
* ```
* ${param.key:plural:
* pluralname{variant}
* ...
* }
* ```
*
* Example:
* ```
* ${results.length:plural:
* one{restaurant}
* other{restaurants}
* }
*/
export class Plural implements Replaceable {
private _index : number|undefined = undefined;
private _rules : Intl.PluralRules|undefined = undefined;
constructor(public param : string,
public key : string[],
public type : Intl.PluralRuleType,
public variants : Record<string|number, Replaceable>) {
}
toString() {
let buf = `\${${this.param}${this.key.length > 0 ? '.' + this.key.join('.') : ''}:${this.type === 'cardinal' ? 'plural' : this.type}:`;
for (const variant in this.variants)
buf += `${typeof variant === 'number' ? '=' + variant : variant}{${this.variants[variant]}}`;
buf += `}`;
return buf;
}
visit(cb : (repl : Replaceable) => boolean) {
if (!cb(this))
return;
for (const v in this.variants)
this.variants[v].visit(cb);
}
optimize(constraints : PlaceholderConstraints) {
const optimized : Record<string|number, Replaceable> = {};
let anyVariant = false;
let anyChange = false;
for (const v in this.variants) {
const vopt = this.variants[v].optimize(constraints);
if (vopt === null) {
anyChange = true;
continue;
}
optimized[v] = vopt;
anyVariant = true;
anyChange = anyChange || this.variants[v] !== vopt;
}
if (!anyVariant)
return null;
if (!anyChange)
return this;
const optthis = new Plural(this.param, this.key, this.type, optimized);
optthis._index = this._index;
optthis._rules = this._rules;
return optthis;
}
preprocess(langPack : LanguagePack, placeholders : string[]) {
for (const v in this.variants)
this.variants[v].preprocess(langPack, placeholders);
this._index = getPlaceholderIndex(placeholders, this.param);
this._rules = new Intl.PluralRules(langPack.locale, { type: this.type });
return this;
}
replace(ctx : ReplacementContext) : ReplacedResult|null {
const param = ctx.replacements[this._index!];
if (!param)
return null;
const value = get(param.value, this.key);
if (value === null || value === undefined)
return null;
const number = Number(value);
if (number in this.variants)
return this.variants[number].replace(ctx);
const variant = this._rules!.select(number);
if (variant in this.variants)
return this.variants[variant].replace(ctx);
else
return null;
}
}
/**
* A phrase that depends on an enumerated value.
*
* The syntax is:
* ```
* ${param.key:select:
* v1{variant}
* v2{variant}
* ...
* }
* ```
*
* Example:
*
* ```
* ${status.value:select:
* sunny{The sun is shining}
* cloudy{The sun is covered by clouds}
* }
* ```
*/
export class ValueSelect implements Replaceable {
private _index : number|undefined = undefined;
constructor(public param : string,
public key : string[],
public variants : Record<string, Replaceable>) {
}
toString() {
let buf = `\${${this.param}${this.key.length > 0 ? '.' + this.key.join('.') : ''}:select:`;
for (const variant in this.variants)
buf += `${variant}{${this.variants[variant]}}`;
buf += `}`;
return buf;
}
visit(cb : (repl : Replaceable) => boolean) {
if (!cb(this))
return;
for (const v in this.variants)
this.variants[v].visit(cb);
}
optimize(constraints : PlaceholderConstraints) {
const optimized : Record<string|number, Replaceable> = {};
let anyVariant = false;
let anyChange = false;
for (const v in this.variants) {
const vopt = this.variants[v].optimize(constraints);
if (vopt === null) {
anyChange = true;
continue;
}
optimized[v] = vopt;
anyVariant = true;
anyChange = anyChange || this.variants[v] !== vopt;
}
if (!anyVariant)
return null;
if (!anyChange)
return this;
const optthis = new ValueSelect(this.param, this.key, optimized);
optthis._index = this._index;
return optthis;
}
preprocess(langPack : LanguagePack, placeholders : string[]) {
for (const v in this.variants)
this.variants[v].preprocess(langPack, placeholders);
this._index = getPlaceholderIndex(placeholders, this.param);
return this;
}
replace(ctx : ReplacementContext) : ReplacedResult|null {
const param = ctx.replacements[this._index!];
if (!param)
return null;
const value = String(get(param.value, this.key));
if (value in this.variants)
return this.variants[value].replace(ctx);
else if ('_' in this.variants)
return this.variants['_'].replace(ctx);
else
return null;
}
}
/**
* A phrase that depends on a flag.
*
* The syntax is:
* ```
* ${param[key]:select:
* v1{variant}
* v2{variant}
* ...
* }
* ```
* (which depends on a flag of the parameter)
*
* Example:
*
* ```
* ${table[gender]:select:
* masculine{his}
* feminine{her}
* }
* ```
*/
export class FlagSelect implements Replaceable {
private _index : number|undefined = undefined;
constructor(public param : string,
public flag : string,
public variants : Record<string, Replaceable>) {
}
toString() {
let buf = `\${${this.param}[${this.flag}]:select:`;
for (const variant in this.variants)
buf += `${variant}{${this.variants[variant]}}`;
buf += `}`;
return buf;
}
visit(cb : (repl : Replaceable) => boolean) {
if (!cb(this))
return;
for (const v in this.variants)
this.variants[v].visit(cb);
}
optimize(constraints : PlaceholderConstraints) : Replaceable|null {
// check if we already have a constraint on this param
if (constraints[this._index!] && this.flag in constraints[this._index!]) {
const constraint = constraints[this._index!][this.flag];
if (!this.variants[constraint])
return null;
return this.variants[constraint].optimize(constraints);
}
const optimized : Record<string, Replaceable> = {};
let anyVariant = false;
for (const v in this.variants) {
// make a new replacement context with the added constraint on this
// placeholder
// the constraint will be propagated down to where this placeholder is
// used, and will be applied to the replacement of the placeholder
const newConstraints : PlaceholderConstraints = {};
mergeConstraints(newConstraints, constraints);
mergeConstraints(newConstraints, { [this._index!]: { [this.flag]: v } });
const vopt = this.variants[v].optimize(newConstraints);
if (vopt === null)
continue;
optimized[v] = vopt;
anyVariant = true;
}
if (!anyVariant)
return null;
const optthis = new FlagSelect(this.param, this.flag, optimized);
optthis._index = this._index;
return optthis;
}
preprocess(langPack : LanguagePack, placeholders : string[]) {
for (const v in this.variants)
this.variants[v].preprocess(langPack, placeholders);
this._index = getPlaceholderIndex(placeholders, this.param);
return this;
}
replace(ctx : ReplacementContext) : ReplacedResult|null {
// check if we already have a constraint on this param
if (ctx.constraints[this._index!] && this.flag in ctx.constraints[this._index!]) {
const constraint = ctx.constraints[this._index!][this.flag];
if (!this.variants[constraint])
return null;
return this.variants[constraint].replace(ctx);
}
const variants : ReplacedResult[] = [];
for (const v in this.variants) {
// make a new replacement context with the added constraint on this
// placeholder
// the constraint will be propagated down to where this placeholder is
// used, and will be applied to the replacement of the placeholder
const newCtx : ReplacementContext = {
replacements: ctx.replacements,
constraints: {}
};
mergeConstraints(newCtx.constraints, ctx.constraints);
mergeConstraints(newCtx.constraints, { [this._index!]: { [this.flag]: v } });
const replaced = this.variants[v].replace(newCtx);
if (replaced === null)
continue;
variants.push(replaced);
}
if (variants.length === 0)
return null;
else if (variants.length === 1)
return variants[0];
else
return new ReplacedChoice(variants);
}
} | the_stack |
* @module Metadata
*/
import { FormatProps } from "../Deserialization/JsonProps";
import { XmlSerializationUtils } from "../Deserialization/XmlSerializationUtils";
import { SchemaItemType } from "../ECObjects";
import { ECObjectsError, ECObjectsStatus } from "../Exception";
import { BaseFormat, DecimalPrecision, FormatTraits, formatTraitsToArray, FormatType, formatTypeToString, FractionalPrecision,
ScientificType, scientificTypeToString, ShowSignOption, showSignOptionToString} from "@itwin/core-quantity";
import { InvertedUnit } from "./InvertedUnit";
import { Schema } from "./Schema";
import { SchemaItem } from "./SchemaItem";
import { Unit } from "./Unit";
/**
* @beta
*/
export class Format extends SchemaItem {
public override readonly schemaItemType!: SchemaItemType.Format; // eslint-disable-line
protected _base: BaseFormat;
protected _units?: Array<[Unit | InvertedUnit, string | undefined]>;
constructor(schema: Schema, name: string) {
super(schema, name);
this.schemaItemType = SchemaItemType.Format;
this._base = new BaseFormat(name);
}
public get roundFactor(): number { return this._base.roundFactor; }
public get type(): FormatType { return this._base.type; }
public get precision(): DecimalPrecision | FractionalPrecision { return this._base.precision; }
public get minWidth(): number | undefined { return this._base.minWidth; }
public get scientificType(): ScientificType | undefined { return this._base.scientificType; }
public get showSignOption(): ShowSignOption { return this._base.showSignOption; }
public get decimalSeparator(): string { return this._base.decimalSeparator; }
public get thousandSeparator(): string { return this._base.thousandSeparator; }
public get uomSeparator(): string { return this._base.uomSeparator; }
public get stationSeparator(): string { return this._base.stationSeparator; }
public get stationOffsetSize(): number | undefined { return this._base.stationOffsetSize; }
public get formatTraits(): FormatTraits { return this._base.formatTraits; }
public get spacer(): string | undefined { return this._base.spacer; }
public get includeZero(): boolean | undefined { return this._base.includeZero; }
public get units(): Array<[Unit | InvertedUnit, string | undefined]> | undefined { return this._units; }
private parseFormatTraits(formatTraitsFromJson: string | string[]) {
return this._base.parseFormatTraits(formatTraitsFromJson);
}
public hasFormatTrait(formatTrait: FormatTraits) {
return this._base.hasFormatTraitSet(formatTrait);
}
/**
* Adds a Unit, or InvertedUnit, with an optional label override.
* @param unit The Unit, or InvertedUnit, to add to this Format.
* @param label A label that overrides the label defined within the Unit when a value is formatted.
*/
protected addUnit(unit: Unit | InvertedUnit, label?: string) {
if (undefined === this._units)
this._units = [];
else { // Validate that a duplicate is not added.
for (const existingUnit of this._units) {
if (unit.fullName.toLowerCase() === existingUnit[0].fullName.toLowerCase())
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this.fullName} has duplicate units, '${unit.fullName}'.`); // TODO: Validation - this should be a validation error not a hard failure.
}
}
this._units.push([unit, label]);
}
protected setPrecision(precision: number) { this._base.precision = precision; }
private typecheck(formatProps: FormatProps) {
this._base.loadFormatProperties(formatProps);
if (undefined !== formatProps.composite) { // TODO: This is duplicated below when the units need to be processed...
if (undefined !== formatProps.composite.includeZero)
this._base.includeZero = formatProps.composite.includeZero;
if (undefined !== formatProps.composite.spacer) {
if (formatProps.composite.spacer.length > 1)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this.fullName} has a composite with an invalid 'spacer' attribute. It should be an empty or one character string.`);
this._base.spacer = formatProps.composite.spacer;
}
// Composite requires 1-4 units
if (formatProps.composite.units.length <= 0 || formatProps.composite.units.length > 4)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, `The Format ${this.fullName} has an invalid 'Composite' attribute. It should have 1-4 units.`);
}
}
public override fromJSONSync(formatProps: FormatProps) {
super.fromJSONSync(formatProps);
this.typecheck(formatProps);
if (undefined === formatProps.composite)
return;
// Units are separated from the rest of the deserialization because of the need to have separate sync and async implementation
for (const unit of formatProps.composite.units) {
const newUnit = this.schema.lookupItemSync<Unit | InvertedUnit>(unit.name);
if (undefined === newUnit)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, ``);
this.addUnit(newUnit, unit.label);
}
}
public override async fromJSON(formatProps: FormatProps) {
await super.fromJSON(formatProps);
this.typecheck(formatProps);
if (undefined === formatProps.composite)
return;
// Units are separated from the rest of the deserialization because of the need to have separate sync and async implementation
for (const unit of formatProps.composite.units) {
const newUnit = await this.schema.lookupItem<Unit | InvertedUnit>(unit.name);
if (undefined === newUnit)
throw new ECObjectsError(ECObjectsStatus.InvalidECJson, ``);
this.addUnit(newUnit, unit.label);
}
}
/**
* Save this Format's properties to an object for serializing to JSON.
* @param standalone Serialization includes only this object (as opposed to the full schema).
* @param includeSchemaVersion Include the Schema's version information in the serialized object.
*/
public override toJSON(standalone: boolean = false, includeSchemaVersion: boolean = false): FormatProps {
const schemaJson = super.toJSON(standalone, includeSchemaVersion) as any;
schemaJson.type = formatTypeToString(this.type);
schemaJson.precision = this.precision;
// this._spacer = " ";
// this._includeZero = true;
// Serialize the minimal amount of information needed so anything that is the same as the default, do not serialize.
if (0.0 !== this.roundFactor) schemaJson.roundFactor = this.roundFactor;
if (ShowSignOption.OnlyNegative !== this.showSignOption) schemaJson.showSignOption = showSignOptionToString(this.showSignOption);
if (FormatTraits.Uninitialized !== this.formatTraits) schemaJson.formatTraits = formatTraitsToArray(this.formatTraits);
if ("." !== this.decimalSeparator) schemaJson.decimalSeparator = this.decimalSeparator;
if ("," !== this.thousandSeparator) schemaJson.thousandSeparator = this.thousandSeparator;
if (" " !== this.uomSeparator) schemaJson.uomSeparator = this.uomSeparator;
if (undefined !== this.minWidth) schemaJson.minWidth = this.minWidth;
if (FormatType.Scientific === this.type && undefined !== this.scientificType)
schemaJson.scientificType = scientificTypeToString(this.scientificType);
if (FormatType.Station === this.type) {
if (undefined !== this.stationOffsetSize)
schemaJson.stationOffsetSize = this.stationOffsetSize;
if (" " !== this.stationSeparator)
schemaJson.stationSeparator = this.stationSeparator;
}
if (undefined === this.units)
return schemaJson;
schemaJson.composite = {};
if (" " !== this.spacer) schemaJson.composite.spacer = this.spacer;
if (true !== this.includeZero) schemaJson.composite.includeZero = this.includeZero;
schemaJson.composite.units = [];
for (const unit of this.units) {
schemaJson.composite.units.push({
name: unit[0].fullName,
label: unit[1],
});
}
return schemaJson;
}
/** @internal */
public override async toXml(schemaXml: Document): Promise<Element> {
const itemElement = await super.toXml(schemaXml);
itemElement.setAttribute("type", formatTypeToString(this.type).toLowerCase());
itemElement.setAttribute("precision", this.precision.toString());
itemElement.setAttribute("roundFactor", this.roundFactor.toString());
itemElement.setAttribute("showSignOption", showSignOptionToString(this.showSignOption));
itemElement.setAttribute("decimalSeparator", this.decimalSeparator);
itemElement.setAttribute("thousandSeparator", this.thousandSeparator);
itemElement.setAttribute("uomSeparator", this.uomSeparator);
itemElement.setAttribute("stationSeparator", this.stationSeparator);
if (undefined !== this.minWidth)
itemElement.setAttribute("minWidth", this.minWidth.toString());
if (undefined !== this.scientificType)
itemElement.setAttribute("scientificType", scientificTypeToString(this.scientificType));
if (undefined !== this.stationOffsetSize)
itemElement.setAttribute("stationOffsetSize", this.stationOffsetSize.toString());
const formatTraits = formatTraitsToArray(this.formatTraits);
if (formatTraits.length > 0)
itemElement.setAttribute("formatTraits", formatTraits.join("|"));
if (undefined !== this.units) {
const compositeElement = schemaXml.createElement("Composite");
if (undefined !== this.spacer)
compositeElement.setAttribute("spacer", this.spacer);
if (undefined !== this.includeZero)
compositeElement.setAttribute("includeZero", this.includeZero.toString());
this.units.forEach(([unit, label]) => {
const unitElement = schemaXml.createElement("Unit");
if (undefined !== label)
unitElement.setAttribute("label", label);
const unitName = XmlSerializationUtils.createXmlTypedName(this.schema, unit.schema, unit.name);
unitElement.textContent = unitName;
compositeElement.appendChild(unitElement);
});
itemElement.appendChild(compositeElement);
}
return itemElement;
}
/**
* @alpha Used in schema editing.
*/
protected setFormatType(formatType: FormatType) {
this._base.type = formatType;
}
/**
* @alpha Used in schema editing.
*/
protected setRoundFactor(roundFactor: number) {
this._base.roundFactor = roundFactor;
}
/**
* @alpha Used in schema editing.
*/
protected setShowSignOption(signOption: ShowSignOption) {
this._base.showSignOption = signOption;
}
/**
* @alpha Used in schema editing.
*/
protected setDecimalSeparator(separator: string) {
this._base.decimalSeparator = separator;
}
/**
* @alpha Used in schema editing.
*/
protected setThousandSeparator(separator: string) {
this._base.thousandSeparator = separator;
}
/**
* @alpha Used in schema editing.
*/
protected setUomSeparator(separator: string) {
this._base.uomSeparator = separator;
}
/**
* @alpha Used in schema editing.
*/
protected setStationSeparator(separator: string) {
this._base.stationSeparator = separator;
}
}
/**
* @internal
* An abstract class used for schema editing.
*/
export abstract class MutableFormat extends Format {
public abstract override addUnit(unit: Unit | InvertedUnit, label?: string): void;
public abstract override setPrecision(precision: number): void;
public abstract override setFormatType(formatType: FormatType): void;
public abstract override setRoundFactor(roundFactor: number): void;
public abstract override setShowSignOption(signOption: ShowSignOption): void;
public abstract override setDecimalSeparator(separator: string): void;
public abstract override setThousandSeparator(separator: string): void;
public abstract override setUomSeparator(separator: string): void;
public abstract override setStationSeparator(separator: string): void;
public abstract override setDisplayLabel(displayLabel: string): void;
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/storageSyncServicesMappers";
import * as Parameters from "../models/parameters";
import { StorageSyncManagementClientContext } from "../storageSyncManagementClientContext";
/** Class representing a StorageSyncServices. */
export class StorageSyncServices {
private readonly client: StorageSyncManagementClientContext;
/**
* Create a StorageSyncServices.
* @param {StorageSyncManagementClientContext} client Reference to the service client.
*/
constructor(client: StorageSyncManagementClientContext) {
this.client = client;
}
/**
* Check the give namespace name availability.
* @param locationName The desired region for the name check.
* @param parameters Parameters to check availability of the given namespace name
* @param [options] The optional parameters
* @returns Promise<Models.StorageSyncServicesCheckNameAvailabilityResponse>
*/
checkNameAvailability(locationName: string, parameters: Models.CheckNameAvailabilityParameters, options?: msRest.RequestOptionsBase): Promise<Models.StorageSyncServicesCheckNameAvailabilityResponse>;
/**
* @param locationName The desired region for the name check.
* @param parameters Parameters to check availability of the given namespace name
* @param callback The callback
*/
checkNameAvailability(locationName: string, parameters: Models.CheckNameAvailabilityParameters, callback: msRest.ServiceCallback<Models.CheckNameAvailabilityResult>): void;
/**
* @param locationName The desired region for the name check.
* @param parameters Parameters to check availability of the given namespace name
* @param options The optional parameters
* @param callback The callback
*/
checkNameAvailability(locationName: string, parameters: Models.CheckNameAvailabilityParameters, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.CheckNameAvailabilityResult>): void;
checkNameAvailability(locationName: string, parameters: Models.CheckNameAvailabilityParameters, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.CheckNameAvailabilityResult>, callback?: msRest.ServiceCallback<Models.CheckNameAvailabilityResult>): Promise<Models.StorageSyncServicesCheckNameAvailabilityResponse> {
return this.client.sendOperationRequest(
{
locationName,
parameters,
options
},
checkNameAvailabilityOperationSpec,
callback) as Promise<Models.StorageSyncServicesCheckNameAvailabilityResponse>;
}
/**
* Create a new StorageSyncService.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param storageSyncServiceName Name of Storage Sync Service resource.
* @param parameters Storage Sync Service resource name.
* @param [options] The optional parameters
* @returns Promise<Models.StorageSyncServicesCreateResponse>
*/
create(resourceGroupName: string, storageSyncServiceName: string, parameters: Models.StorageSyncServiceCreateParameters, options?: msRest.RequestOptionsBase): Promise<Models.StorageSyncServicesCreateResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param storageSyncServiceName Name of Storage Sync Service resource.
* @param parameters Storage Sync Service resource name.
* @param callback The callback
*/
create(resourceGroupName: string, storageSyncServiceName: string, parameters: Models.StorageSyncServiceCreateParameters, callback: msRest.ServiceCallback<Models.StorageSyncService>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param storageSyncServiceName Name of Storage Sync Service resource.
* @param parameters Storage Sync Service resource name.
* @param options The optional parameters
* @param callback The callback
*/
create(resourceGroupName: string, storageSyncServiceName: string, parameters: Models.StorageSyncServiceCreateParameters, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.StorageSyncService>): void;
create(resourceGroupName: string, storageSyncServiceName: string, parameters: Models.StorageSyncServiceCreateParameters, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.StorageSyncService>, callback?: msRest.ServiceCallback<Models.StorageSyncService>): Promise<Models.StorageSyncServicesCreateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
storageSyncServiceName,
parameters,
options
},
createOperationSpec,
callback) as Promise<Models.StorageSyncServicesCreateResponse>;
}
/**
* Get a given StorageSyncService.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param storageSyncServiceName Name of Storage Sync Service resource.
* @param [options] The optional parameters
* @returns Promise<Models.StorageSyncServicesGetResponse>
*/
get(resourceGroupName: string, storageSyncServiceName: string, options?: msRest.RequestOptionsBase): Promise<Models.StorageSyncServicesGetResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param storageSyncServiceName Name of Storage Sync Service resource.
* @param callback The callback
*/
get(resourceGroupName: string, storageSyncServiceName: string, callback: msRest.ServiceCallback<Models.StorageSyncService>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param storageSyncServiceName Name of Storage Sync Service resource.
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, storageSyncServiceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.StorageSyncService>): void;
get(resourceGroupName: string, storageSyncServiceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.StorageSyncService>, callback?: msRest.ServiceCallback<Models.StorageSyncService>): Promise<Models.StorageSyncServicesGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
storageSyncServiceName,
options
},
getOperationSpec,
callback) as Promise<Models.StorageSyncServicesGetResponse>;
}
/**
* Patch a given StorageSyncService.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param storageSyncServiceName Name of Storage Sync Service resource.
* @param [options] The optional parameters
* @returns Promise<Models.StorageSyncServicesUpdateResponse>
*/
update(resourceGroupName: string, storageSyncServiceName: string, options?: Models.StorageSyncServicesUpdateOptionalParams): Promise<Models.StorageSyncServicesUpdateResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param storageSyncServiceName Name of Storage Sync Service resource.
* @param callback The callback
*/
update(resourceGroupName: string, storageSyncServiceName: string, callback: msRest.ServiceCallback<Models.StorageSyncService>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param storageSyncServiceName Name of Storage Sync Service resource.
* @param options The optional parameters
* @param callback The callback
*/
update(resourceGroupName: string, storageSyncServiceName: string, options: Models.StorageSyncServicesUpdateOptionalParams, callback: msRest.ServiceCallback<Models.StorageSyncService>): void;
update(resourceGroupName: string, storageSyncServiceName: string, options?: Models.StorageSyncServicesUpdateOptionalParams | msRest.ServiceCallback<Models.StorageSyncService>, callback?: msRest.ServiceCallback<Models.StorageSyncService>): Promise<Models.StorageSyncServicesUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
storageSyncServiceName,
options
},
updateOperationSpec,
callback) as Promise<Models.StorageSyncServicesUpdateResponse>;
}
/**
* Delete a given StorageSyncService.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param storageSyncServiceName Name of Storage Sync Service resource.
* @param [options] The optional parameters
* @returns Promise<Models.StorageSyncServicesDeleteResponse>
*/
deleteMethod(resourceGroupName: string, storageSyncServiceName: string, options?: msRest.RequestOptionsBase): Promise<Models.StorageSyncServicesDeleteResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param storageSyncServiceName Name of Storage Sync Service resource.
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, storageSyncServiceName: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param storageSyncServiceName Name of Storage Sync Service resource.
* @param options The optional parameters
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, storageSyncServiceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, storageSyncServiceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<Models.StorageSyncServicesDeleteResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
storageSyncServiceName,
options
},
deleteMethodOperationSpec,
callback) as Promise<Models.StorageSyncServicesDeleteResponse>;
}
/**
* Get a StorageSyncService list by Resource group name.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param [options] The optional parameters
* @returns Promise<Models.StorageSyncServicesListByResourceGroupResponse>
*/
listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.StorageSyncServicesListByResourceGroupResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.StorageSyncServiceArray>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.StorageSyncServiceArray>): void;
listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.StorageSyncServiceArray>, callback?: msRest.ServiceCallback<Models.StorageSyncServiceArray>): Promise<Models.StorageSyncServicesListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
options
},
listByResourceGroupOperationSpec,
callback) as Promise<Models.StorageSyncServicesListByResourceGroupResponse>;
}
/**
* Get a StorageSyncService list by subscription.
* @param [options] The optional parameters
* @returns Promise<Models.StorageSyncServicesListBySubscriptionResponse>
*/
listBySubscription(options?: msRest.RequestOptionsBase): Promise<Models.StorageSyncServicesListBySubscriptionResponse>;
/**
* @param callback The callback
*/
listBySubscription(callback: msRest.ServiceCallback<Models.StorageSyncServiceArray>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
listBySubscription(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.StorageSyncServiceArray>): void;
listBySubscription(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.StorageSyncServiceArray>, callback?: msRest.ServiceCallback<Models.StorageSyncServiceArray>): Promise<Models.StorageSyncServicesListBySubscriptionResponse> {
return this.client.sendOperationRequest(
{
options
},
listBySubscriptionOperationSpec,
callback) as Promise<Models.StorageSyncServicesListBySubscriptionResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const checkNameAvailabilityOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/providers/Microsoft.StorageSync/locations/{locationName}/checkNameAvailability",
urlParameters: [
Parameters.locationName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.CheckNameAvailabilityParameters,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.CheckNameAvailabilityResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const createOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorageSync/storageSyncServices/{storageSyncServiceName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.storageSyncServiceName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.StorageSyncServiceCreateParameters,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.StorageSyncService
},
default: {
bodyMapper: Mappers.StorageSyncError
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorageSync/storageSyncServices/{storageSyncServiceName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.storageSyncServiceName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.StorageSyncService,
headersMapper: Mappers.StorageSyncServicesGetHeaders
},
default: {
bodyMapper: Mappers.StorageSyncError
}
},
serializer
};
const updateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorageSync/storageSyncServices/{storageSyncServiceName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.storageSyncServiceName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: [
"options",
"parameters"
],
mapper: Mappers.StorageSyncServiceUpdateParameters
},
responses: {
200: {
bodyMapper: Mappers.StorageSyncService,
headersMapper: Mappers.StorageSyncServicesUpdateHeaders
},
default: {
bodyMapper: Mappers.StorageSyncError
}
},
serializer
};
const deleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorageSync/storageSyncServices/{storageSyncServiceName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.storageSyncServiceName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
headersMapper: Mappers.StorageSyncServicesDeleteHeaders
},
204: {
headersMapper: Mappers.StorageSyncServicesDeleteHeaders
},
default: {
bodyMapper: Mappers.StorageSyncError
}
},
serializer
};
const listByResourceGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorageSync/storageSyncServices",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.StorageSyncServiceArray,
headersMapper: Mappers.StorageSyncServicesListByResourceGroupHeaders
},
default: {
bodyMapper: Mappers.StorageSyncError
}
},
serializer
};
const listBySubscriptionOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.StorageSync/storageSyncServices",
urlParameters: [
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.StorageSyncServiceArray,
headersMapper: Mappers.StorageSyncServicesListBySubscriptionHeaders
},
default: {
bodyMapper: Mappers.StorageSyncError
}
},
serializer
}; | the_stack |
'use strict';
import { inject, injectable } from 'inversify';
import { cloneDeep } from 'lodash';
import * as path from 'path';
import { QuickPick, QuickPickItem, QuickPickItemKind } from 'vscode';
import * as nls from 'vscode-nls';
import { IApplicationShell, ICommandManager, IWorkspaceService } from '../../../../common/application/types';
import { Commands, Octicons } from '../../../../common/constants';
import { isParentPath } from '../../../../common/platform/fs-paths';
import { IPlatformService } from '../../../../common/platform/types';
import { IConfigurationService, IPathUtils, Resource } from '../../../../common/types';
import { getIcon } from '../../../../common/utils/icons';
import { Common, InterpreterQuickPickList } from '../../../../common/utils/localize';
import {
IMultiStepInput,
IMultiStepInputFactory,
InputStep,
IQuickPickParameters,
} from '../../../../common/utils/multiStepInput';
import { SystemVariables } from '../../../../common/variables/systemVariables';
import { REFRESH_BUTTON_ICON } from '../../../../debugger/extension/attachQuickPick/types';
import { EnvironmentType } from '../../../../pythonEnvironments/info';
import { captureTelemetry, sendTelemetryEvent } from '../../../../telemetry';
import { EventName } from '../../../../telemetry/constants';
import { IInterpreterService, PythonEnvironmentsChangedEvent } from '../../../contracts';
import {
IInterpreterQuickPickItem,
IInterpreterSelector,
IPythonPathUpdaterServiceManager,
ISpecialQuickPickItem,
} from '../../types';
import { BaseInterpreterSelectorCommand } from './base';
const localize: nls.LocalizeFunc = nls.loadMessageBundle();
const untildify = require('untildify');
export type InterpreterStateArgs = { path?: string; workspace: Resource };
type QuickPickType = IInterpreterQuickPickItem | ISpecialQuickPickItem | QuickPickItem;
function isInterpreterQuickPickItem(item: QuickPickType): item is IInterpreterQuickPickItem {
return 'interpreter' in item;
}
function isSpecialQuickPickItem(item: QuickPickType): item is ISpecialQuickPickItem {
return 'alwaysShow' in item;
}
function isSeparatorItem(item: QuickPickType): item is QuickPickItem {
return 'kind' in item && item.kind === QuickPickItemKind.Separator;
}
// eslint-disable-next-line @typescript-eslint/no-namespace
export namespace EnvGroups {
export const Workspace = InterpreterQuickPickList.workspaceGroupName;
export const Conda = 'Conda';
export const Global = InterpreterQuickPickList.globalGroupName;
export const VirtualEnv = 'VirtualEnv';
export const PipEnv = 'PipEnv';
export const Pyenv = 'Pyenv';
export const Venv = 'Venv';
export const Poetry = 'Poetry';
export const VirtualEnvWrapper = 'VirtualEnvWrapper';
export const Recommended = Common.recommended;
}
@injectable()
export class SetInterpreterCommand extends BaseInterpreterSelectorCommand {
private readonly manualEntrySuggestion: ISpecialQuickPickItem = {
label: `${Octicons.Add} ${InterpreterQuickPickList.enterPath.label}`,
alwaysShow: true,
};
constructor(
@inject(IApplicationShell) applicationShell: IApplicationShell,
@inject(IPathUtils) pathUtils: IPathUtils,
@inject(IPythonPathUpdaterServiceManager)
pythonPathUpdaterService: IPythonPathUpdaterServiceManager,
@inject(IConfigurationService) configurationService: IConfigurationService,
@inject(ICommandManager) commandManager: ICommandManager,
@inject(IMultiStepInputFactory) private readonly multiStepFactory: IMultiStepInputFactory,
@inject(IPlatformService) private readonly platformService: IPlatformService,
@inject(IInterpreterSelector) private readonly interpreterSelector: IInterpreterSelector,
@inject(IWorkspaceService) workspaceService: IWorkspaceService,
@inject(IInterpreterService) private readonly interpreterService: IInterpreterService,
) {
super(
pythonPathUpdaterService,
commandManager,
applicationShell,
workspaceService,
pathUtils,
configurationService,
);
}
public async activate(): Promise<void> {
this.disposables.push(
this.commandManager.registerCommand(Commands.Set_Interpreter, this.setInterpreter.bind(this)),
);
}
public async _pickInterpreter(
input: IMultiStepInput<InterpreterStateArgs>,
state: InterpreterStateArgs,
): Promise<void | InputStep<InterpreterStateArgs>> {
// If the list is refreshing, it's crucial to maintain sorting order at all
// times so that the visible items do not change.
const preserveOrderWhenFiltering = !!this.interpreterService.refreshPromise;
const suggestions = this.getItems(state.workspace);
// Discovery is no longer guranteed to be auto-triggered on extension load, so trigger it when
// user interacts with the interpreter picker but only once per session. Users can rely on the
// refresh button if they want to trigger it more than once.
this.interpreterService.triggerRefresh(undefined, { ifNotTriggerredAlready: true }).ignoreErrors();
state.path = undefined;
const currentInterpreterPathDisplay = this.pathUtils.getDisplayName(
this.configurationService.getSettings(state.workspace).pythonPath,
state.workspace ? state.workspace.fsPath : undefined,
);
const selection = await input.showQuickPick<QuickPickType, IQuickPickParameters<QuickPickType>>({
placeholder: localize(
'InterpreterQuickPickList.quickPickListPlaceholder',
'Selected Interpreter: {0}',
currentInterpreterPathDisplay,
),
items: suggestions,
sortByLabel: !preserveOrderWhenFiltering,
keepScrollPosition: true,
activeItem: await this.getActiveItem(state.workspace, suggestions),
matchOnDetail: true,
matchOnDescription: true,
title: InterpreterQuickPickList.browsePath.openButtonLabel,
customButtonSetup: {
button: {
iconPath: getIcon(REFRESH_BUTTON_ICON),
tooltip: InterpreterQuickPickList.refreshInterpreterList,
},
callback: () => this.interpreterService.triggerRefresh().ignoreErrors(),
},
onChangeItem: {
event: this.interpreterService.onDidChangeInterpreters,
// It's essential that each callback is handled synchronously, as result of the previous
// callback influences the input for the next one. Input here is the quickpick itself.
callback: (event: PythonEnvironmentsChangedEvent, quickPick) => {
if (this.interpreterService.refreshPromise) {
quickPick.busy = true;
this.interpreterService.refreshPromise.then(() => {
// Items are in the final state as all previous callbacks have finished executing.
quickPick.busy = false;
// Ensure we set a recommended item after refresh has finished.
this.updateQuickPickItems(quickPick, {}, state.workspace);
});
}
this.updateQuickPickItems(quickPick, event, state.workspace);
},
},
});
if (selection === undefined) {
sendTelemetryEvent(EventName.SELECT_INTERPRETER_SELECTED, undefined, { action: 'escape' });
} else if (selection.label === this.manualEntrySuggestion.label) {
sendTelemetryEvent(EventName.SELECT_INTERPRETER_ENTER_OR_FIND);
return this._enterOrBrowseInterpreterPath(input, state, suggestions);
} else {
sendTelemetryEvent(EventName.SELECT_INTERPRETER_SELECTED, undefined, { action: 'selected' });
state.path = (selection as IInterpreterQuickPickItem).path;
}
return undefined;
}
private getItems(resource: Resource) {
const suggestions: QuickPickType[] = [this.manualEntrySuggestion];
const defaultInterpreterPathSuggestion = this.getDefaultInterpreterPathSuggestion(resource);
if (defaultInterpreterPathSuggestion) {
suggestions.push(defaultInterpreterPathSuggestion);
}
const interpreterSuggestions = this.getSuggestions(resource);
this.setRecommendedItem(interpreterSuggestions, resource);
suggestions.push(...interpreterSuggestions);
return suggestions;
}
private getSuggestions(resource: Resource): QuickPickType[] {
const workspaceFolder = this.workspaceService.getWorkspaceFolder(resource);
const items = this.interpreterSelector.getSuggestions(resource, !!this.interpreterService.refreshPromise);
if (this.interpreterService.refreshPromise) {
// We cannot put items in groups while the list is loading as group of an item can change.
return items;
}
const itemsWithFullName = this.interpreterSelector.getSuggestions(resource, true);
const recommended = this.interpreterSelector.getRecommendedSuggestion(
itemsWithFullName,
this.workspaceService.getWorkspaceFolder(resource)?.uri,
);
if (recommended && items[0].interpreter.id === recommended.interpreter.id) {
items.shift();
}
return getGroupedQuickPickItems(items, recommended, workspaceFolder?.uri.fsPath);
}
private async getActiveItem(resource: Resource, suggestions: QuickPickType[]) {
const interpreter = await this.interpreterService.getActiveInterpreter(resource);
const activeInterpreterItem = suggestions.find(
(i) => isInterpreterQuickPickItem(i) && i.interpreter.id === interpreter?.id,
);
if (activeInterpreterItem) {
return activeInterpreterItem;
}
const firstInterpreterSuggestion = suggestions.find((s) => isInterpreterQuickPickItem(s));
if (firstInterpreterSuggestion) {
return firstInterpreterSuggestion;
}
return suggestions[0];
}
private getDefaultInterpreterPathSuggestion(resource: Resource): ISpecialQuickPickItem | undefined {
const config = this.workspaceService.getConfiguration('python', resource);
const systemVariables = new SystemVariables(resource, undefined, this.workspaceService);
const defaultInterpreterPathValue = systemVariables.resolveAny(config.get<string>('defaultInterpreterPath'));
if (defaultInterpreterPathValue && defaultInterpreterPathValue !== 'python') {
return {
label: `${Octicons.Gear} ${InterpreterQuickPickList.defaultInterpreterPath.label}`,
description: this.pathUtils.getDisplayName(
defaultInterpreterPathValue,
resource ? resource.fsPath : undefined,
),
path: defaultInterpreterPathValue,
alwaysShow: true,
};
}
return undefined;
}
/**
* Updates quickpick using the change event received.
*/
private updateQuickPickItems(
quickPick: QuickPick<QuickPickType>,
event: PythonEnvironmentsChangedEvent,
resource: Resource,
) {
// Active items are reset once we replace the current list with updated items, so save it.
const activeItemBeforeUpdate = quickPick.activeItems.length > 0 ? quickPick.activeItems[0] : undefined;
quickPick.items = this.getUpdatedItems(quickPick.items, event, resource);
// Ensure we maintain the same active item as before.
const activeItem = activeItemBeforeUpdate
? quickPick.items.find((item) => {
if (isInterpreterQuickPickItem(item) && isInterpreterQuickPickItem(activeItemBeforeUpdate)) {
return item.interpreter.id === activeItemBeforeUpdate.interpreter.id;
}
if (isSpecialQuickPickItem(item) && isSpecialQuickPickItem(activeItemBeforeUpdate)) {
// 'label' is a constant here instead of 'path'.
return item.label === activeItemBeforeUpdate.label;
}
return false;
})
: undefined;
quickPick.activeItems = activeItem ? [activeItem] : [];
}
/**
* Prepare updated items to replace the quickpick list with.
*/
private getUpdatedItems(
items: readonly QuickPickType[],
event: PythonEnvironmentsChangedEvent,
resource: Resource,
): QuickPickType[] {
const updatedItems = [...items.values()];
const areItemsGrouped = items.find((item) => isSeparatorItem(item));
const env = event.old ?? event.new;
let envIndex = -1;
if (env) {
envIndex = updatedItems.findIndex(
(item) => isInterpreterQuickPickItem(item) && item.interpreter.id === env.id,
);
}
if (event.new) {
const newSuggestion = this.interpreterSelector.suggestionToQuickPickItem(
event.new,
resource,
!areItemsGrouped,
);
if (envIndex === -1) {
if (areItemsGrouped) {
addSeparatorIfApplicable(
updatedItems,
newSuggestion,
this.workspaceService.getWorkspaceFolder(resource)?.uri.fsPath,
);
}
updatedItems.push(newSuggestion);
} else {
updatedItems[envIndex] = newSuggestion;
}
}
if (envIndex !== -1 && event.new === undefined) {
updatedItems.splice(envIndex, 1);
}
this.setRecommendedItem(updatedItems, resource);
return updatedItems;
}
private setRecommendedItem(items: QuickPickType[], resource: Resource) {
const interpreterSuggestions = this.interpreterSelector.getSuggestions(resource, true);
if (!this.interpreterService.refreshPromise && interpreterSuggestions.length > 0) {
const suggestion = this.interpreterSelector.getRecommendedSuggestion(
interpreterSuggestions,
this.workspaceService.getWorkspaceFolder(resource)?.uri,
);
if (!suggestion) {
return;
}
const areItemsGrouped = items.find((item) => isSeparatorItem(item) && item.label === EnvGroups.Recommended);
const recommended = cloneDeep(suggestion);
recommended.label = `${Octicons.Star} ${recommended.label}`;
recommended.description = areItemsGrouped
? // No need to add a tag as "Recommended" group already exists.
recommended.description
: `${recommended.description ?? ''} - ${Common.recommended}`;
const index = items.findIndex(
(item) => isInterpreterQuickPickItem(item) && item.interpreter.id === recommended.interpreter.id,
);
if (index !== -1) {
items[index] = recommended;
}
}
}
@captureTelemetry(EventName.SELECT_INTERPRETER_ENTER_BUTTON)
public async _enterOrBrowseInterpreterPath(
input: IMultiStepInput<InterpreterStateArgs>,
state: InterpreterStateArgs,
suggestions: QuickPickType[],
): Promise<void | InputStep<InterpreterStateArgs>> {
const items: QuickPickItem[] = [
{
label: InterpreterQuickPickList.browsePath.label,
detail: InterpreterQuickPickList.browsePath.detail,
},
];
const selection = await input.showQuickPick({
placeholder: InterpreterQuickPickList.enterPath.placeholder,
items,
acceptFilterBoxTextAsSelection: true,
});
if (typeof selection === 'string') {
// User entered text in the filter box to enter path to python, store it
sendTelemetryEvent(EventName.SELECT_INTERPRETER_ENTER_CHOICE, undefined, { choice: 'enter' });
state.path = selection;
this.sendInterpreterEntryTelemetry(selection, state.workspace, suggestions);
} else if (selection && selection.label === InterpreterQuickPickList.browsePath.label) {
sendTelemetryEvent(EventName.SELECT_INTERPRETER_ENTER_CHOICE, undefined, { choice: 'browse' });
const filtersKey = 'Executables';
const filtersObject: { [name: string]: string[] } = {};
filtersObject[filtersKey] = ['exe'];
const uris = await this.applicationShell.showOpenDialog({
filters: this.platformService.isWindows ? filtersObject : undefined,
openLabel: InterpreterQuickPickList.browsePath.openButtonLabel,
canSelectMany: false,
title: InterpreterQuickPickList.browsePath.title,
});
if (uris && uris.length > 0) {
state.path = uris[0].fsPath;
this.sendInterpreterEntryTelemetry(state.path!, state.workspace, suggestions);
}
}
}
@captureTelemetry(EventName.SELECT_INTERPRETER)
public async setInterpreter(): Promise<void> {
const targetConfig = await this.getConfigTargets();
if (!targetConfig) {
return;
}
const { configTarget } = targetConfig[0];
const wkspace = targetConfig[0].folderUri;
const interpreterState: InterpreterStateArgs = { path: undefined, workspace: wkspace };
const multiStep = this.multiStepFactory.create<InterpreterStateArgs>();
await multiStep.run((input, s) => this._pickInterpreter(input, s), interpreterState);
if (interpreterState.path !== undefined) {
// User may choose to have an empty string stored, so variable `interpreterState.path` may be
// an empty string, in which case we should update.
// Having the value `undefined` means user cancelled the quickpick, so we update nothing in that case.
await this.pythonPathUpdaterService.updatePythonPath(interpreterState.path, configTarget, 'ui', wkspace);
}
}
/**
* Check if the interpreter that was entered exists in the list of suggestions.
* If it does, it means that it had already been discovered,
* and we didn't do a good job of surfacing it.
*
* @param selection Intepreter path that was either entered manually or picked by browsing through the filesystem.
*/
// eslint-disable-next-line class-methods-use-this
private sendInterpreterEntryTelemetry(selection: string, workspace: Resource, suggestions: QuickPickType[]): void {
let interpreterPath = path.normalize(untildify(selection));
if (!path.isAbsolute(interpreterPath)) {
interpreterPath = path.resolve(workspace?.fsPath || '', selection);
}
const expandedPaths = suggestions.map((s) => {
const suggestionPath = isInterpreterQuickPickItem(s) ? s.interpreter.path : '';
let expandedPath = path.normalize(untildify(suggestionPath));
if (!path.isAbsolute(suggestionPath)) {
expandedPath = path.resolve(workspace?.fsPath || '', suggestionPath);
}
return expandedPath;
});
const discovered = expandedPaths.includes(interpreterPath);
sendTelemetryEvent(EventName.SELECT_INTERPRETER_ENTERED_EXISTS, undefined, { discovered });
return undefined;
}
}
function getGroupedQuickPickItems(
items: IInterpreterQuickPickItem[],
recommended: IInterpreterQuickPickItem | undefined,
workspacePath?: string,
): QuickPickType[] {
const updatedItems: QuickPickType[] = [];
if (recommended) {
updatedItems.push({ label: EnvGroups.Recommended, kind: QuickPickItemKind.Separator }, recommended);
}
let previousGroup = EnvGroups.Recommended;
for (const item of items) {
previousGroup = addSeparatorIfApplicable(updatedItems, item, workspacePath, previousGroup);
updatedItems.push(item);
}
return updatedItems;
}
function addSeparatorIfApplicable(
items: QuickPickType[],
newItem: IInterpreterQuickPickItem,
workspacePath?: string,
previousGroup?: string | undefined,
) {
if (!previousGroup) {
const lastItem = items.length ? items[items.length - 1] : undefined;
previousGroup =
lastItem && isInterpreterQuickPickItem(lastItem) ? getGroup(lastItem, workspacePath) : undefined;
}
const currentGroup = getGroup(newItem, workspacePath);
if (!previousGroup || currentGroup !== previousGroup) {
const separatorItem: QuickPickItem = { label: currentGroup, kind: QuickPickItemKind.Separator };
items.push(separatorItem);
previousGroup = currentGroup;
}
return previousGroup;
}
function getGroup(item: IInterpreterQuickPickItem, workspacePath?: string) {
if (workspacePath && isParentPath(item.path, workspacePath)) {
return EnvGroups.Workspace;
}
switch (item.interpreter.envType) {
case EnvironmentType.Global:
case EnvironmentType.System:
case EnvironmentType.Unknown:
case EnvironmentType.WindowsStore:
return EnvGroups.Global;
default:
return EnvGroups[item.interpreter.envType];
}
} | the_stack |
import { EventEmitter } from 'events';
import { DeadlineClient } from '../deadline-client';
jest.mock('http');
jest.mock('https');
describe('DeadlineClient', () => {
let deadlineClient: DeadlineClient;
class MockResponse extends EventEmitter {
public statusCode: number;
public statusMessage: string = 'status message';
public constructor(statusCode: number) {
super();
this.statusCode = statusCode;
}
}
class MockRequest extends EventEmitter {
public end() {}
public write(_data: string) {}
}
let consoleLogMock: jest.SpyInstance<any, any>;
let request: MockRequest;
let response: MockResponse;
/**
* Mock implementation of the request
*
* @param _url The URL of the request
* @param callback The callback to call when a response is available
*/
function httpRequestMock(_url: string, callback: (_request: any) => void) {
if (callback) {
callback(response);
}
return request;
}
describe('successful responses', () => {
beforeEach(() => {
consoleLogMock = jest.spyOn(console, 'log').mockReturnValue(undefined);
request = new MockRequest();
jest.requireMock('http').request.mockReset();
jest.requireMock('https').request.mockReset();
(jest.requireMock('https').Agent as jest.Mock).mockClear();
response = new MockResponse(200);
});
test('successful http get request', async () => {
// GIVEN
jest.requireMock('http').request.mockImplementation(httpRequestMock);
deadlineClient = new DeadlineClient({
host: 'hostname',
port: 8080,
protocol: 'HTTP',
});
const responseData = {
test: true,
};
// WHEN
const promise = deadlineClient.GetRequest('/get/version/test');
response.emit('data', Buffer.from(JSON.stringify(responseData), 'utf8'));
response.emit('end');
const result = await promise;
// THEN
// should make an HTTP request
expect(jest.requireMock('http').request)
.toBeCalledWith(
{
agent: undefined,
method: 'GET',
port: 8080,
host: 'hostname',
path: '/get/version/test',
},
expect.any(Function),
);
expect(result.data).toEqual(responseData);
});
test('successful http get request with options', async () => {
// GIVEN
jest.requireMock('http').request.mockImplementation(httpRequestMock);
deadlineClient = new DeadlineClient({
host: 'hostname',
port: 8080,
protocol: 'HTTP',
});
const responseData = {
test: true,
};
// WHEN
const promise = deadlineClient.GetRequest('/get/version/test', {
headers: {
'Content-Type': 'application/json',
},
});
response.emit('data', Buffer.from(JSON.stringify(responseData), 'utf8'));
response.emit('end');
const result = await promise;
// THEN
// should make an HTTP request
expect(jest.requireMock('http').request)
.toBeCalledWith(
{
agent: undefined,
headers: {
'Content-Type': 'application/json',
},
method: 'GET',
port: 8080,
host: 'hostname',
path: '/get/version/test',
},
expect.any(Function),
);
expect(result.data).toEqual(responseData);
});
test('successful https get request', async () => {
// GIVEN
jest.requireMock('https').request.mockImplementation(httpRequestMock);
deadlineClient = new DeadlineClient({
host: 'hostname',
port: 4433,
protocol: 'HTTPS',
});
const responseData = {
test: true,
};
// WHEN
const promise = deadlineClient.GetRequest('/get/version/test');
response.emit('data', Buffer.from(JSON.stringify(responseData), 'utf8'));
response.emit('end');
const result = await promise;
// THEN
const agentMock = jest.requireMock('https').Agent as jest.Mock;
expect(agentMock).toHaveBeenCalledTimes(1);
expect(agentMock).toBeCalledWith(expect.not.objectContaining({ ca: expect.any(String) }));
expect(agentMock).toBeCalledWith(expect.not.objectContaining({ pfx: expect.any(String) }));
expect(agentMock).toBeCalledWith(expect.not.objectContaining({ passphrase: expect.any(String) }));
// should make an HTTPS request
expect(jest.requireMock('https').request)
.toBeCalledWith(
{
agent: agentMock.mock.instances[0],
method: 'GET',
port: 4433,
host: 'hostname',
path: '/get/version/test',
},
expect.any(Function),
);
expect(result.data).toEqual(responseData);
});
test('successful https get request with tls', async () => {
// GIVEN
jest.requireMock('https').request.mockImplementation(httpRequestMock);
deadlineClient = new DeadlineClient({
host: 'hostname',
port: 4433,
protocol: 'HTTPS',
tls: {
ca: 'cacontent',
pfx: 'pfxcontent',
passphrase: 'passphrasecontent',
},
});
const responseData = {
test: true,
};
// WHEN
const promise = deadlineClient.GetRequest('/get/version/test');
response.emit('data', Buffer.from(JSON.stringify(responseData), 'utf8'));
response.emit('end');
const result = await promise;
// THEN
const agentMock = jest.requireMock('https').Agent as jest.Mock;
expect(agentMock).toHaveBeenCalledTimes(1);
expect(agentMock).toBeCalledWith(
expect.objectContaining({
ca: 'cacontent',
pfx: 'pfxcontent',
passphrase: 'passphrasecontent',
}),
);
// should make an HTTPS request
expect(jest.requireMock('https').request)
.toBeCalledWith(
{
agent: agentMock.mock.instances[0],
method: 'GET',
port: 4433,
host: 'hostname',
path: '/get/version/test',
},
expect.any(Function),
);
expect(result.data).toEqual(responseData);
});
test('successful http post request', async () => {
// GIVEN
jest.requireMock('http').request.mockImplementation(httpRequestMock);
deadlineClient = new DeadlineClient({
host: 'hostname',
port: 8080,
protocol: 'HTTP',
});
const responseData = {
test: true,
};
// WHEN
const promise = deadlineClient.PostRequest('/save/version/test', 'anydata');
response.emit('data', Buffer.from(JSON.stringify(responseData), 'utf8'));
response.emit('end');
const result = await promise;
// THEN
// should make an HTTP request
expect(jest.requireMock('http').request)
.toBeCalledWith(
{
agent: undefined,
method: 'POST',
port: 8080,
host: 'hostname',
path: '/save/version/test',
},
expect.any(Function),
);
expect(result.data).toEqual(responseData);
});
test('successful https post request', async () => {
// GIVEN
jest.requireMock('https').request.mockImplementation(httpRequestMock);
deadlineClient = new DeadlineClient({
host: 'hostname',
port: 4433,
protocol: 'HTTPS',
});
const responseData = {
test: true,
};
// WHEN
const promise = deadlineClient.PostRequest('/save/version/test', 'anydata');
response.emit('data', Buffer.from(JSON.stringify(responseData), 'utf8'));
response.emit('end');
const result = await promise;
// THEN
const agentMock = jest.requireMock('https').Agent as jest.Mock;
expect(agentMock).toHaveBeenCalledTimes(1);
expect(agentMock).toBeCalledWith(expect.not.objectContaining({ ca: expect.any(String) }));
expect(agentMock).toBeCalledWith(expect.not.objectContaining({ pfx: expect.any(String) }));
expect(agentMock).toBeCalledWith(expect.not.objectContaining({ passphrase: expect.any(String) }));
// should make an HTTP request
expect(jest.requireMock('https').request)
.toBeCalledWith(
{
agent: agentMock.mock.instances[0],
method: 'POST',
port: 4433,
host: 'hostname',
path: '/save/version/test',
},
expect.any(Function),
);
expect(result.data).toEqual(responseData);
});
test('successful https post request with tls', async () => {
// GIVEN
jest.requireMock('https').request.mockImplementation(httpRequestMock);
deadlineClient = new DeadlineClient({
host: 'hostname',
port: 4433,
protocol: 'HTTPS',
tls: {
ca: 'cacontent',
pfx: 'pfxcontent',
passphrase: 'passphrasecontent',
},
});
const responseData = {
test: true,
};
// WHEN
const promise = deadlineClient.PostRequest('/save/version/test', 'anydata');
response.emit('data', Buffer.from(JSON.stringify(responseData), 'utf8'));
response.emit('end');
const result = await promise;
// THEN
const agentMock = jest.requireMock('https').Agent as jest.Mock;
expect(agentMock).toHaveBeenCalledTimes(1);
expect(agentMock).toBeCalledWith(
expect.objectContaining({
ca: 'cacontent',
pfx: 'pfxcontent',
passphrase: 'passphrasecontent',
}),
);
// should make an HTTPS request
expect(jest.requireMock('https').request)
.toBeCalledWith(
{
agent: agentMock.mock.instances[0],
method: 'POST',
port: 4433,
host: 'hostname',
path: '/save/version/test',
},
expect.any(Function),
);
expect(result.data).toEqual(responseData);
});
});
describe('failed responses', () => {
beforeEach(() => {
consoleLogMock = jest.spyOn(console, 'log').mockReturnValue(undefined);
request = new MockRequest();
jest.requireMock('http').request.mockImplementation(httpRequestMock);
jest.requireMock('https').request.mockImplementation(httpRequestMock);
});
afterEach(() => {
jest.clearAllMocks();
jest.requireMock('http').request.mockReset();
jest.requireMock('https').request.mockReset();
});
describe('returns a rejected promise on 400 responses', () => {
test.each([
['HTTP', 'GET'],
['HTTP', 'POST'],
['HTTPS', 'GET'],
['HTTPS', 'POST'],
])('for %p %p', async (protocol: string, requestType: string) => {
// GIVEN
response = new MockResponse(400);
deadlineClient = new DeadlineClient({
host: 'hostname',
port: 0,
protocol: protocol,
});
// WHEN
function performRequest() {
if (requestType === 'GET') { return deadlineClient.GetRequest('anypath'); }
return deadlineClient.PostRequest('anypath', 'anydata');
}
const promise = performRequest();
// THEN
await expect(promise)
.rejects
.toEqual(response.statusMessage);
expect(consoleLogMock.mock.calls.length).toBe(0);
});
});
describe('retries on 503 responses', () => {
test.each([
['HTTP', 'GET'],
['HTTP', 'POST'],
['HTTPS', 'GET'],
['HTTPS', 'POST'],
])('for %p %p', async (protocol: string, requestType: string) => {
// GIVEN
response = new MockResponse(503);
const retries = 3;
deadlineClient = new DeadlineClient({
host: 'hostname',
port: 0,
protocol: protocol,
retries,
retryWaitMs: 0,
});
// WHEN
function performRequest() {
if (requestType === 'GET') { return deadlineClient.GetRequest('anypath'); }
return deadlineClient.PostRequest('anypath', 'anydata');
}
const promise = performRequest();
// THEN
await expect(promise)
.rejects
.toEqual(response.statusMessage);
expect(consoleLogMock.mock.calls.length).toBe(retries * 2);
expect(consoleLogMock.mock.calls[0][0]).toMatch(/Request failed with/);
expect(consoleLogMock.mock.calls[1][0]).toMatch(/Retries left:/);
});
});
});
}); | the_stack |
import { BuildCtx, figplugDir } from './ctx'
import { Lib, StdLib, UserLib, LibProps, Product, IncrementalBuildProcess } from './pkgbuild'
import * as os from 'os'
import { existsSync, watch as watchFile } from 'fs'
import * as Html from 'html'
import { jsonfmt, rpath, fmtDuration, parseQueryString } from './util'
import { readfile, writefile, isFile } from './fs'
import postcssNesting from 'postcss-nesting'
import { Manifest } from './manifest'
import * as Path from 'path'
import {
join as pjoin,
dirname,
basename,
parse as parsePath,
resolve as presolve,
} from 'path'
import { AssetBundler, AssetInfo } from './asset'
const domTSLib = new StdLib("dom")
let _figplugLib :Lib|null = null
function getFigplugLib() :Lib {
return _figplugLib || (_figplugLib = new Lib({
dfile: pjoin(figplugDir, 'lib', 'figplug.d.ts'),
jsfile: pjoin(figplugDir, 'lib', 'figplug.js'),
cachedir: pjoin(os.tmpdir(), 'figplug'),
}))
}
let figmaPluginLibCache = new Map<string,Lib>() // by version
function getFigmaPluginLib(apiVersion? :string) :Lib {
let v :string = FIGMA_API_VERSIONS[0] // latest version
if (apiVersion && apiVersion != "latest") {
v = apiVersion
}
let lib = figmaPluginLibCache.get(v)
if (!lib) {
let dfile = pjoin(figplugDir, 'lib', `figma-plugin-${v}.d.ts`)
if (!existsSync(dfile)) {
console.warn(
`warning: unknown Figma API version ${apiVersion}.`+
` Using type definitions for latest known version.`
)
dfile = pjoin(figplugDir, 'lib', `figma-plugin.d.ts`)
}
lib = new Lib(dfile)
figmaPluginLibCache.set(v, lib)
}
return lib
}
async function setLibPropsFiles(input: string, fn :string, props :LibProps) {
if (fn.endsWith(".d.ts")) {
// provided foo.d.ts
// =? foo.js
// == foo.d.ts
if (props.dfile) {
throw new Error(`duplicate .d.ts file provided for -lib=${repr(input)}`)
}
props.dfile = fn
} else if (fn.endsWith(".js")) {
// provided foo.js
// == foo.js
// =? foo.d.ts
if (props.jsfile) {
throw new Error(`duplicate .js file provided for -lib=${repr(input)}`)
}
props.jsfile = fn
} else {
// assume fn lacks extension -- look for both fn.js and fn.d.ts
let jsfn = fn + ".js"
let dtsfn = fn + ".d.ts"
let hasJS = props.jsfile ? Promise.resolve(false) : isFile(jsfn)
let hasDTS = props.dfile ? Promise.resolve(false) : isFile(dtsfn)
if (await hasJS) {
props.jsfile = jsfn
}
if (await hasDTS) {
props.dfile = dtsfn
}
}
}
async function getUserLib(filename :string, basedir :string, cachedir :string) :Promise<UserLib> {
let props = {} as LibProps
let names = filename.split(":").map(fn => Path.isAbsolute(fn) ? fn : Path.resolve(basedir, fn))
if (names.length > 1) {
// foo.js:foo.d.ts
if (names.length > 2) {
throw new Error(`too many filenames provided for -lib=${repr(filename)}`)
}
for (let fn of names) {
fn = Path.resolve(fn)
await setLibPropsFiles(filename, fn, props)
}
} else {
let fn = Path.resolve(names[0])
await setLibPropsFiles(filename, fn, props)
}
if (!props.dfile && !props.jsfile) {
throw new Error(`library not found ${filename} (${names.join(", ")})`)
}
if (!props.jsfile) {
// .d.ts file was set -- try to discover matching .js file
let jsfn = props.dfile!.substr(0, props.dfile!.length - ".d.ts".length) + ".js"
if (await isFile(jsfn)) {
props.jsfile = jsfn
}
} else if (!props.dfile) {
// .js file was set -- try to discover matching .d.ts file
let dtsfn = props.jsfile!.substr(0, props.jsfile!.length - ".js".length) + ".d.ts"
if (await isFile(dtsfn)) {
props.dfile = dtsfn
}
}
if (props.jsfile) {
props.cachedir = cachedir
}
// Note: It probably doesn't help much to cache these, so we don't and keep
// this code a little simpler.
return new UserLib(props)
}
function stripFileExt(filename :string) :string {
let ext = Path.extname(filename)
return ext ? filename.substr(0, filename.length - ext.length) : filename
}
interface UserLibSpec {
fn :string // possibly-relative filename
basedir :string // absolute base dir
}
export class PluginTarget {
readonly manifest :Manifest
readonly basedir :string // root of plugin; dirname of manifest.json
readonly srcdir :string
readonly outdir :string
readonly cachedir :string // == pjoin(this.outdir, ".figplug-cache")
readonly name :string // e.g. "Foo Bar" from manifest.props.name
readonly pluginProduct :Product
readonly uiProduct :Product|null = null
// user lib specs provided with constructor and manifest
readonly pUserLibs :UserLibSpec[] = []
readonly uiUserLibs :UserLibSpec[] = []
needLoadUserLibs :bool = false // true when loadUserLibs needs to be called by build()
// output files
readonly pluginOutFile :string
readonly htmlOutFile :string = "" // non-empty when uiProduct is set
readonly htmlInFile :string = "" // non-empty when uiProduct is set
readonly cssInFile :string = "" // non-empty when uiProduct is set
// incremental build promises
pluginIncrBuildProcess :IncrementalBuildProcess|null = null
uiIncrBuildProcess :IncrementalBuildProcess|null = null
constructor(manifest :Manifest, c :BuildCtx) {
this.manifest = manifest
this.basedir = dirname(manifest.file)
let pluginSrcFile = presolve(this.basedir, manifest.props.main)
this.srcdir = dirname(pluginSrcFile)
this.outdir = c.outdir || pjoin(this.srcdir, "build")
this.cachedir = pjoin(this.outdir, ".figplug-cache")
this.name = manifest.props.name
let customModuleId = manifest.props.figplug && manifest.props.figplug.moduleId
let moduleId = customModuleId || stripFileExt(manifest.props.main)
this.pluginOutFile = pjoin(
this.outdir,
(customModuleId || parsePath(pluginSrcFile).name) + '.js'
)
// setup libs
let figplugLib = getFigplugLib()
let figmaPluginLib = getFigmaPluginLib(manifest.props.api)
// setup user libs
this.initUserLibs(c.libs, c.uilibs)
// setup plugin product
this.pluginProduct = new Product({
version: c.version,
id: moduleId,
entry: pluginSrcFile,
outfile: this.pluginOutFile,
basedir: this.basedir,
cachedir: this.cachedir,
libs: [ figplugLib, figmaPluginLib ],
targetESVersion: 8, // Figma's JS VM supports ES2017
mapfile: (
c.externalSourceMap ? (this.pluginOutFile + '.map') :
pjoin(this.cachedir, this.pluginOutFile.replace(/[^A-Za-z0-9_\-]+/g, ".") + '.map')
),
})
// setup ui product
if (manifest.props.ui) {
let uisrcFile = pjoin(this.basedir, manifest.props.ui)
let uisrcFilePath = parsePath(uisrcFile)
let ext = uisrcFilePath.ext.toLowerCase()
let uisrcDir = uisrcFilePath.dir
let uisrcName = pjoin(uisrcDir, uisrcFilePath.name)
this.htmlInFile = uisrcName + '.html'
this.cssInFile = uisrcName + '.css'
this.htmlOutFile = pjoin(this.outdir, uisrcFilePath.name + '.html')
if (!uisrcFile.endsWith(".html")) {
this.uiProduct = new Product({
version: this.pluginProduct.version,
id: stripFileExt(manifest.props.ui),
entry: uisrcFile,
outfile: pjoin(this.cachedir, 'ui.js'),
basedir: this.basedir,
cachedir: this.cachedir,
libs: [ figplugLib, domTSLib ],
jsx: (ext == ".tsx" || ext == ".jsx") ? "react" : "",
targetESVersion: this.pluginProduct.targetESVersion,
})
} // else: HTML-only UI
}
}
initUserLibs(pUserLibs :string[], uiUserLibs :string[]) {
let mp = this.manifest.props
// sets used to avoid duplicate entries. Values are absolute paths.
let seenp = new Set<string>()
let seenui = new Set<string>()
let add = (seen :Set<string>, v :UserLibSpec[], basedir :string, fn :string) => {
let path = presolve(basedir, fn)
if (!seen.has(path)) {
seen.add(path)
v.push({ fn, basedir })
}
}
// Add libs from config/CLI.
// libs defined on command line are relative to current working directory
let basedir = process.cwd()
for (let fn of pUserLibs) {
add(seenp, this.pUserLibs, basedir, fn)
}
if (mp.ui) for (let fn of uiUserLibs) {
add(seenui, this.uiUserLibs, basedir, fn)
}
// Add libs from manifest
if (mp.figplug) {
let basedir = this.srcdir // plugin libs defined in manifest are relative to srcdir
if (mp.figplug.libs) for (let fn of mp.figplug.libs) {
add(seenp, this.pUserLibs, basedir, fn)
}
if (mp.ui && mp.figplug.uilibs) for (let fn of mp.figplug.uilibs) {
add(seenui, this.uiUserLibs, basedir, fn)
}
}
// set load flag if there are any user libs
this.needLoadUserLibs = (this.pUserLibs.length + this.uiUserLibs.length) > 0
}
async loadUserLibs(c :BuildCtx) :Promise<void> {
assert(this.needLoadUserLibs)
this.needLoadUserLibs = false
// dedup libs to make sure we only have once UserLib instance per actual lib file
let loadLibs = new Map<string,UserLibSpec>()
let libPaths :string[] = []
for (let ls of this.pUserLibs.concat(this.uiUserLibs)) {
let path = presolve(ls.basedir, ls.fn)
loadLibs.set(path, ls)
libPaths.push(path)
}
// load and await all
if (c.verbose2) {
print(`[${this.name}] load libs:\n ` + Array.from(loadLibs.keys()).join("\n "))
}
let loadedLibs = new Map<string,UserLib>()
await Promise.all(Array.from(loadLibs).map(([path, ls]) =>
getUserLib(ls.fn, ls.basedir, this.cachedir).then(lib => {
loadedLibs.set(path, lib)
})
))
// add libs to products
let libs = libPaths.map(path => loadedLibs.get(path)!)
let i = 0
for (; i < this.pUserLibs.length; i++) {
if (c.verbose) { print(`add plugin ${libs[i]}`) }
this.pluginProduct.libs.push(libs[i])
}
// remainder of libs are ui libs
for (; i < libs.length; i++) {
assert(this.uiProduct)
if (c.verbose) { print(`add UI ${libs[i]}`) }
this.uiProduct!.libs.push(libs[i])
}
}
async build(c :BuildCtx, onbuild? :()=>void) :Promise<void> {
// TODO: if there's a package.json file in this.basedir then read the
// version from it and assign it to this.version
if (this.needLoadUserLibs) {
await this.loadUserLibs(c)
}
// sanity-check input and output files
if (this.pluginProduct.entry == this.pluginProduct.outfile) {
throw "plugin input file is same as output file: " +
repr(this.pluginProduct.entry)
}
if (this.htmlInFile && this.htmlInFile == this.htmlOutFile) {
throw `html input file is same as output file: ` + repr(this.htmlInFile)
}
if (this.uiProduct && this.uiProduct.entry == this.uiProduct.outfile) {
throw "ui input file is same as output file: " +
repr(this.uiProduct.entry)
}
// setup string subs for ui
if (this.uiProduct) {
this.uiProduct.subs = [
["process.env.NODE_ENV", c.debug ? "'development'" : "'production'"],
]
}
// reporting
let onStartBuild = () => {}
let onEndBuild = onbuild ? onbuild : (()=>{})
if (c.verbose || c.watch) {
let info = (
"plugin " + repr(this.name) +
" at " + rpath(this.srcdir) +
" -> " + rpath(this.outdir)
)
let startTime = 0
onStartBuild = () => {
startTime = Date.now()
print(`building ${info}`)
}
onEndBuild = () => {
let time = fmtDuration(Date.now() - startTime)
print(`built ${info} in ${time}`)
onbuild && onbuild()
}
}
// build once or incrementally depending on c.watch
return Promise.all([
this.writeManifestFile(c, this.manifest),
c.watch ?
this.buildIncr(c, onStartBuild, onEndBuild) :
this.buildOnce(c, onStartBuild, onEndBuild)
]).then(() => {})
}
async buildIncr(c :BuildCtx, onStartBuild :()=>void, onEndBuild :(e? :Error)=>void) :Promise<void> {
// TODO: return cancelable promise, like we do for
// Product.buildIncrementally.
if (this.pluginIncrBuildProcess || this.uiIncrBuildProcess) {
throw new Error(`already has incr build process`)
}
// reload manifest on change
watchFile(this.manifest.file, {}, async () => {
try {
let manifest2 = await Manifest.loadFile(this.manifest.file)
if (this.manifest.props.main != manifest2.props.main ||
this.manifest.props.ui != manifest2.props.ui)
{
// source changed -- need to restart build process
// TODO: automate restarting the build
console.error(
'\n' +
`Warning: Need to restart program -- ` +
'source files in manifest changed.' +
'\n'
)
} else {
this.writeManifestFile(c, manifest2)
}
} catch (err) {
console.error(err.message)
}
})
let onStartBuildHtml = () => {}
const buildHtml = () => {
onStartBuildHtml()
return this.buildHTML(c)
}
// watch HTML and CSS source files for changes
if (this.htmlInFile && existsSync(this.htmlInFile)) {
watchFile(this.htmlInFile, {}, buildHtml)
}
if (this.cssInFile && existsSync(this.cssInFile)) {
watchFile(this.cssInFile, {}, buildHtml)
}
// Watch user libraries
let isRestartingPluginBuild = false
const rebuildPlugin = () => {
if (this.pluginIncrBuildProcess && !isRestartingPluginBuild) {
isRestartingPluginBuild = true
this.pluginIncrBuildProcess.restart().then(() => { isRestartingPluginBuild = false })
}
}
for (let lib of this.pluginProduct.libs) {
if (lib instanceof UserLib) {
if (lib.jsfile) { watchFile(lib.jsfile, {}, rebuildPlugin) }
if (lib.dfile) { watchFile(lib.dfile, {}, rebuildPlugin) }
}
}
if (this.uiProduct) {
let isRestartingUIBuild = false
const rebuildUI = () => {
if (this.uiIncrBuildProcess && !isRestartingUIBuild) {
isRestartingUIBuild = true
this.uiIncrBuildProcess.restart().then(() => { isRestartingUIBuild = false })
}
}
for (let lib of this.uiProduct.libs) {
if (lib instanceof UserLib) {
if (lib.jsfile) { watchFile(lib.jsfile, {}, rebuildUI) }
if (lib.dfile) { watchFile(lib.dfile, {}, rebuildUI) }
}
}
}
// have UI?
if (this.uiProduct || this.htmlInFile) {
let buildCounter = 0
let onstart = () => {
if (buildCounter++ == 0) {
onStartBuild()
}
}
let onend = (err? :Error) => {
if (--buildCounter == 0) {
onEndBuild(err)
}
}
this.pluginIncrBuildProcess = this.pluginProduct.buildIncrementally(c, onstart, onend)
if (this.uiProduct) {
// TS UI
this.uiIncrBuildProcess = this.uiProduct.buildIncrementally(
c,
onstart,
err => err ? null
: buildHtml().then(() => onend()).catch(onend)
)
return Promise.all([
this.pluginIncrBuildProcess,
this.uiIncrBuildProcess,
]).then(() => {})
}
if (this.htmlInFile) {
// HTML-only UI
onStartBuildHtml = onstart
return Promise.all([
this.pluginIncrBuildProcess,
buildHtml().then(() => onend()).catch(onend),
]).then(() => {})
}
} else {
// no UI
return this.pluginIncrBuildProcess = this.pluginProduct.buildIncrementally(
c,
onStartBuild,
onEndBuild,
)
}
}
buildOnce(c :BuildCtx, onStartBuild :()=>void, onEndBuild :()=>void) :Promise<void> {
onStartBuild()
if (this.uiProduct) {
// TS UI
return Promise.all([
this.pluginProduct.build(c),
this.uiProduct.build(c).then(() => this.buildHTML(c)),
]).then(onEndBuild)
}
if (this.htmlInFile) {
// HTML-only UI
return Promise.all([
this.pluginProduct.build(c),
this.buildHTML(c),
]).then(onEndBuild)
}
// no UI
return this.pluginProduct.build(c).then(onEndBuild)
}
async buildHTML(c :BuildCtx) :Promise<void> {
const defaultHtml = (
"<html><head></head><body><div id=\"root\"></div></body></html>"
)
let startTime = 0
if (c.verbose) {
startTime = Date.now()
print(`build module ${repr(rpath(this.htmlOutFile))}`)
}
// read contents of HTML and CSS files
let [html, css] = await Promise.all([
readfile(this.htmlInFile, 'utf8').catch(err => {
if (err.code != 'ENOENT') { throw err }
return defaultHtml
}),
readfile(this.cssInFile, 'utf8').catch(err => {
if (err.code != 'ENOENT') { throw err }
return ""
}),
])
// Static includes
html = await this.processInlineFiles(c, html)
// HTML head and tail
let head = ""
let tail = ""
if (this.uiProduct) {
let js = this.uiProduct.output.js
tail += '<script>\n' + js + '\n</script>'
}
// process CSS if any was loaded
if (css.trim() != "") {
css = await this.processCss(css, this.cssInFile)
head = '<style>\n' + css + '\n</style>'
}
// find best offset in html text to insert HTML head content
let htmlOut = ""
let tailInsertPos = Html.findTailIndex(html)
if (head.length) {
let headInsertPos = Html.findHeadIndex(html)
htmlOut = (
html.substr(0, headInsertPos) +
head +
html.substring(headInsertPos, tailInsertPos) +
tail +
html.substr(tailInsertPos)
)
} else {
htmlOut = (
html.substr(0, tailInsertPos) +
tail +
html.substr(tailInsertPos)
)
}
if (c.verbose) {
let time = fmtDuration(Date.now() - startTime)
print(`built module ${repr(rpath(this.htmlOutFile))} in ${time}`)
}
return writefile(this.htmlOutFile, htmlOut, 'utf8')
}
// processInlineFiles finds, parses and inlines files referenced by `html`.
//
// This function acts on two different kinds of information:
//
// - HTML elements like img with a src attribute.
// The src attribute value is replaced with a data url and width and height attributes
// are added (unless specified)
//
// - Explicit <?include "filename" ?> directives.
// This entire directive is replaced by the contents of the file.
//
// Filenames are relative to dirname(this.htmlInFile).
//
// An optional query string parameter "?as=" can be provided with the filename
// to <?include?> directives, which controls what the output will be.
// The values for "as=" are:
//
// as=bytearray
// Inserts a comma-separated sequence of bytes of the file in decimal form.
// e.g. 69,120,97,109,112,108,101 for the ASCII data "Example"
//
// as=jsobj
// Inserts a JavaScript literal object with the following interface:
// {
// mimeType :string // File type. Empty if unknown.
// width? :number // for images, the width of the image
// height? :number // for images, the height of the image
// }
//
// Absence of as= query parameters means that the contents of the file is inserted as text.
//
// Note: File loads are deduplicated, so there's really no performance penalty for including
// the same file multiple times. For instance:
//
// <img src="foo.png">
// <script>
// const fooData = new Uint8Array([<?include "foo.png?as=bytearray"?>])
// const fooInfo = <?include "foo.png?as=jsobj"?>
// </script>
//
// This would only cause foo.png to be read once.
//
async processInlineFiles(c :BuildCtx, html :string) :Promise<string> {
interface InlineFile {
type :"html"|"include"
filename :string
mimeType :string
index :number
params :Record<string,string[]>
loadp :Promise<void>
assetInfo :AssetInfo|null // non-null when loadp is loaded
loadErr :Error|null // non-null on load error (assetInfo will be null)
// defined for type=="html"
tagname :string
prefix :string
suffix :string
}
const re = /<([^\s>]+)([^>]+)src=(?:"([^"]+)"|'([^']+)')([^>]*)>|<\?\s*include\s+(?:"([^"]+)"|'([^']+)')\s*\?>/mig
const reGroupCount = 7 // used for index of "index" in args to replace callback
// Find
let inlineFiles :InlineFile[] = [] // indexed by character offset in html
let errors :string[] = [] // error messages indexed by character offset in html
let htmlInFileDir = dirname(this.htmlInFile)
html.replace(re, (substr :string, ...m :any[]) => {
let f = {
index: m[reGroupCount],
params: {},
mimeType: "",
} as InlineFile
if (m[0]) {
let srcval = m[2] || m[3]
if (srcval.indexOf(":") != -1) {
// skip URLs
return substr
}
f.type = "html"
f.filename = pjoin(htmlInFileDir, srcval)
f.tagname = m[0].toLowerCase()
f.prefix = "<" + m[0] + m[1]
f.suffix = m[4].trimRight() + ">"
} else {
// <?include ... ?>
let srcval = m[5]
if (srcval.indexOf(":") != -1) {
// URLs not supported in ?include?
let error = `invalid file path`
console.error(
`error in ${rpath(this.htmlInFile)}: ${error} in directive: ${substr} -- ignoring`
)
errors[f.index] = error
return ""
}
f.type = "include"
f.filename = pjoin(htmlInFileDir, m[5])
}
inlineFiles[f.index] = f
return substr
})
if (inlineFiles.length == 0) {
// nothing found -- nothing to do
return html
}
// Load data files
let fileLoaders = new Map<string,Promise<AssetInfo>>() // filename => AssetInfo
let assetBundler = new AssetBundler()
for (let k in inlineFiles) {
let f = inlineFiles[k]
// parse filename and update f
let [filename, mimeType, queryString] = assetBundler.parseFilename(f.filename)
f.params = parseQueryString(queryString)
f.filename = filename
f.mimeType = mimeType || ""
// start loading file
let loadp = fileLoaders.get(filename)
if (!loadp) {
loadp = assetBundler.loadAssetInfo(filename, f.mimeType)
fileLoaders.set(filename, loadp)
}
f.loadp = loadp.then(assetInfo => {
f.assetInfo = assetInfo
}).catch(err => {
let errmsg = String(err).replace(
filename,
Path.relative(dirname(this.htmlInFile), filename)
)
console.error(`error in ${rpath(this.htmlInFile)}: ${errmsg}`)
f.loadErr = err
})
}
// await file loaders, ignoring errors
await Promise.all(Array.from(fileLoaders.values()).map(p => p.catch(err => {})))
// Replace in html
html = html.replace(re, (substr :string, ...m :any[]) => {
let index = m[reGroupCount]
let f = inlineFiles[index]
if (!f) {
let error = errors[index]
if (error) {
return `<!--${substr.replace(/^<\?|\?>$/g, "").trim()} [error: ${error}] -->`
}
// unmodified
return substr
}
if (!f.assetInfo) {
return substr
}
if (f.type == "html") {
// Note: f.tagname is lower-cased
if (f.tagname == "script") {
// special case for <script src="foo.js"></script> -> <script>...</script>
let s = f.prefix.trim() + (f.suffix == ">" ? ">" : " " + f.suffix.trimLeft())
let text = f.assetInfo.getTextData()
if (s.endsWith("/>")) {
// <script src="foo.js"/> -> <script>...</script>
s = s.substr(0, s.length - 2) + ">" + text + "</script>"
} else {
s += text
}
return s
}
const sizeTagNames = {"svg":1,"img":1}
let s = f.prefix + `src='${f.assetInfo!.url}'`
if (f.tagname in sizeTagNames && typeof f.assetInfo.attrs.width == "number") {
let width = f.assetInfo.attrs.width as number
let height = f.assetInfo.attrs.height as number
if (width > 0 && height > 0) {
let wm = substr.match(/width=(?:"([^"]+)"|'([^"]+)')/i)
let hm = substr.match(/height=(?:"([^"]+)"|'([^"]+)')/i)
if (wm && !hm) {
// width set but not height -- set height based on width and aspect ratio
let w = parseInt(wm[1] || wm[2])
if (!isNaN(w) && w > 0) {
s += ` height="${(w * (height / width)).toFixed(0)}" `
}
} else if (!wm && hm) {
// height set but not width -- set width based on height and aspect ratio
let h = parseInt(hm[1] || hm[2])
if (!isNaN(h) && h > 0) {
s += ` width="${(h * (width / height)).toFixed(0)}" `
}
} else if (!wm && !hm) {
// set width & height
s += ` width="${width}" height="${height}" `
}
}
}
return s + f.suffix
}
let asType = "as" in f.params ? (f.params["as"][0]||"").toLowerCase() : ""
if (asType == "bytearray") {
return Array.from(f.assetInfo.getData()).join(",")
}
let text = f.assetInfo.getTextData()
if (asType == "jsobj") {
return JSON.stringify(Object.assign({
mimeType: f.assetInfo.mimeType,
}, f.assetInfo.attrs), null, 2)
}
return text
})
return html
}
processCss(css :string, filename :string) :Promise<string> {
return postcssNesting.process(css, {
from: filename,
}, {
features: {
'nesting-rules': true,
},
}).then(r => r.toString()) as Promise<string>
}
writeManifestFile(c :BuildCtx, manifest :Manifest) :Promise<void> {
if (c.noGenManifest) {
c.verbose2 && print(`[${this.name}] skip writing manifest.json`)
return Promise.resolve()
}
let props = manifest.propMap()
// override source file names
props.set("main", basename(this.pluginProduct.outfile))
if (this.htmlOutFile) {
props.set("ui", basename(this.htmlOutFile))
} else {
props.delete("ui")
}
// generate JSON
let json = jsonfmt(props)
// write file
let file = pjoin(this.outdir, 'manifest.json')
c.verbose2 && print(`write ${rpath(file)}`)
return writefile(file, json, 'utf8')
}
toString() :string {
let name = JSON.stringify(this.manifest.props.name)
let dir = JSON.stringify(
rpath(this.srcdir) || basename(process.cwd())
)
return `Plugin(${name} at ${dir})`
}
} | the_stack |
import { default as TarjanGraphConstructor, Graph as TarjanGraph } from "tarjan-graph";
import { encode64 } from "df/common/protos";
import { JSONObjectStringifier, StringifiedMap } from "df/common/strings/stringifier";
import * as adapters from "df/core/adapters";
import { AContextable, Assertion, AssertionContext, IAssertionConfig } from "df/core/assertion";
import { Contextable, ICommonContext, Resolvable } from "df/core/common";
import { Declaration, IDeclarationConfig } from "df/core/declaration";
import { IOperationConfig, Operation, OperationContext } from "df/core/operation";
import {
DistStyleType,
ITableConfig,
ITableContext,
SortStyleType,
Table,
TableContext,
TableType
} from "df/core/table";
import * as test from "df/core/test";
import * as utils from "df/core/utils";
import { toResolvable } from "df/core/utils";
import { version as dataformCoreVersion } from "df/core/version";
import { dataform } from "df/protos/ts";
const SQL_DATA_WAREHOUSE_DIST_HASH_REGEXP = new RegExp("HASH\\s*\\(\\s*\\w*\\s*\\)\\s*");
const DEFAULT_CONFIG = {
defaultSchema: "dataform",
assertionSchema: "dataform_assertions"
};
/**
* @hidden
*/
export interface IActionProto {
name?: string;
fileName?: string;
dependencyTargets?: dataform.ITarget[];
dependencies?: string[];
hermeticity?: dataform.ActionHermeticity;
target?: dataform.ITarget;
canonicalTarget?: dataform.ITarget;
parentAction?: dataform.ITarget;
}
type SqlxConfig = (
| (ITableConfig & { type: TableType })
| (IAssertionConfig & { type: "assertion" })
| (IOperationConfig & { type: "operations" })
| (IDeclarationConfig & { type: "declaration" })
| (test.ITestConfig & { type: "test" })
) & { name: string };
/**
* @hidden
*/
export class Session {
public rootDir: string;
public config: dataform.IProjectConfig;
public canonicalConfig: dataform.IProjectConfig;
public actions: Array<Table | Operation | Assertion | Declaration>;
public tests: { [name: string]: test.Test };
public graphErrors: dataform.IGraphErrors;
constructor(
rootDir?: string,
projectConfig?: dataform.IProjectConfig,
originalProjectConfig?: dataform.IProjectConfig
) {
this.init(rootDir, projectConfig, originalProjectConfig);
}
public init(
rootDir: string,
projectConfig?: dataform.IProjectConfig,
originalProjectConfig?: dataform.IProjectConfig
) {
this.rootDir = rootDir;
this.config = projectConfig || DEFAULT_CONFIG;
this.canonicalConfig = getCanonicalProjectConfig(
originalProjectConfig || projectConfig || DEFAULT_CONFIG
);
this.actions = [];
this.tests = {};
this.graphErrors = { compilationErrors: [] };
}
public get projectConfig(): Pick<
dataform.IProjectConfig,
| "warehouse"
| "defaultDatabase"
| "defaultSchema"
| "assertionSchema"
| "databaseSuffix"
| "schemaSuffix"
| "tablePrefix"
| "vars"
> {
return Object.freeze({
warehouse: this.config.warehouse,
defaultDatabase: this.config.defaultDatabase,
defaultSchema: this.config.defaultSchema,
assertionSchema: this.config.assertionSchema,
databaseSuffix: this.config.databaseSuffix,
schemaSuffix: this.config.schemaSuffix,
tablePrefix: this.config.tablePrefix,
vars: Object.freeze({ ...this.config.vars })
});
}
public adapter(): adapters.IAdapter {
return adapters.create(this.config, dataformCoreVersion);
}
public sqlxAction(actionOptions: {
sqlxConfig: SqlxConfig;
sqlStatementCount: number;
sqlContextable: (
ctx: TableContext | AssertionContext | OperationContext | ICommonContext
) => string[];
incrementalWhereContextable: (ctx: ITableContext) => string;
preOperationsContextable: (ctx: ITableContext) => string[];
postOperationsContextable: (ctx: ITableContext) => string[];
inputContextables: [
{
refName: string[];
contextable: (ctx: ICommonContext) => string;
}
];
}) {
const { sqlxConfig } = actionOptions;
if (actionOptions.sqlStatementCount > 1 && sqlxConfig.type !== "operations") {
this.compileError(
"Actions may only contain more than one SQL statement if they are of type 'operations'."
);
}
if (sqlxConfig.hasOwnProperty("protected") && sqlxConfig.type !== "incremental") {
this.compileError(
"Actions may only specify 'protected: true' if they are of type 'incremental'."
);
}
if (actionOptions.incrementalWhereContextable && sqlxConfig.type !== "incremental") {
this.compileError(
"Actions may only include incremental_where if they are of type 'incremental'."
);
}
if (!sqlxConfig.hasOwnProperty("schema") && sqlxConfig.type === "declaration") {
this.compileError("Actions of type 'declaration' must specify a value for 'schema'.");
}
if (actionOptions.inputContextables.length > 0 && sqlxConfig.type !== "test") {
this.compileError("Actions may only include input blocks if they are of type 'test'.");
}
if (actionOptions.preOperationsContextable && !definesDataset(sqlxConfig.type)) {
this.compileError("Actions may only include pre_operations if they create a dataset.");
}
if (actionOptions.postOperationsContextable && !definesDataset(sqlxConfig.type)) {
this.compileError("Actions may only include post_operations if they create a dataset.");
}
if (
!!sqlxConfig.hasOwnProperty("sqldatawarehouse") &&
!["bigquery", "snowflake"].includes(this.config.warehouse)
) {
this.compileError(
"Actions may only specify 'database' in projects whose warehouse is 'BigQuery' or 'Snowflake'."
);
}
switch (sqlxConfig.type) {
case "view":
case "table":
case "inline":
case "incremental":
const table = this.publish(sqlxConfig.name)
.config(sqlxConfig)
.query(ctx => actionOptions.sqlContextable(ctx)[0]);
if (actionOptions.incrementalWhereContextable) {
table.where(actionOptions.incrementalWhereContextable);
}
if (actionOptions.preOperationsContextable) {
table.preOps(actionOptions.preOperationsContextable);
}
if (actionOptions.postOperationsContextable) {
table.postOps(actionOptions.postOperationsContextable);
}
break;
case "assertion":
this.assert(sqlxConfig.name)
.config(sqlxConfig)
.query(ctx => actionOptions.sqlContextable(ctx)[0]);
break;
case "operations":
this.operate(sqlxConfig.name)
.config(sqlxConfig)
.queries(actionOptions.sqlContextable);
break;
case "declaration":
this.declare({
database: sqlxConfig.database,
schema: sqlxConfig.schema,
name: sqlxConfig.name
}).config(sqlxConfig);
break;
case "test":
const testCase = this.test(sqlxConfig.name)
.config(sqlxConfig)
.expect(ctx => actionOptions.sqlContextable(ctx)[0]);
actionOptions.inputContextables.forEach(({ refName, contextable }) => {
testCase.input(refName, contextable);
});
break;
default:
throw new Error(`Unrecognized action type: ${(sqlxConfig as SqlxConfig).type}`);
}
}
public resolve(ref: Resolvable | string[], ...rest: string[]): string {
ref = toResolvable(ref, rest);
const allResolved = this.findActions(utils.resolvableAsTarget(ref));
if (allResolved.length > 1) {
this.compileError(new Error(utils.ambiguousActionNameMsg(ref, allResolved)));
}
const resolved = allResolved.length > 0 ? allResolved[0] : undefined;
if (resolved && resolved instanceof Table && resolved.proto.type === "inline") {
// TODO: Pretty sure this is broken as the proto.query value may not
// be set yet as it happens during compilation. We should evalute the query here.
return `(${resolved.proto.query})`;
}
if (resolved && resolved instanceof Operation && !resolved.proto.hasOutput) {
this.compileError(
new Error("Actions cannot resolve operations which do not produce output.")
);
}
if (resolved) {
if (resolved instanceof Declaration) {
return this.adapter().resolveTarget(resolved.proto.target);
}
return this.adapter().resolveTarget({
...resolved.proto.target,
database:
resolved.proto.target.database &&
this.adapter().normalizeIdentifier(
`${resolved.proto.target.database}${this.getDatabaseSuffixWithUnderscore()}`
),
schema: this.adapter().normalizeIdentifier(
`${resolved.proto.target.schema}${this.getSchemaSuffixWithUnderscore()}`
),
name: this.adapter().normalizeIdentifier(
`${this.getTablePrefixWithUnderscore()}${resolved.proto.target.name}`
)
});
}
// TODO: Here we allow 'ref' to go unresolved. This is for backwards compatibility with projects
// that use .sql files. In these projects, this session may not know about all actions (yet), and
// thus we need to fall back to assuming that the target *will* exist in the future. Once we break
// backwards compatibility with .sql files, we should remove the below code, and append a compile
// error instead.
if (typeof ref === "string") {
return this.adapter().resolveTarget(
utils.target(
this.adapter(),
this.config,
this.adapter().normalizeIdentifier(`${this.getTablePrefixWithUnderscore()}${ref}`),
this.adapter().normalizeIdentifier(
`${this.config.defaultSchema}${this.getSchemaSuffixWithUnderscore()}`
),
this.config.defaultDatabase &&
this.adapter().normalizeIdentifier(
`${this.config.defaultDatabase}${this.getDatabaseSuffixWithUnderscore()}`
)
)
);
}
return this.adapter().resolveTarget(
utils.target(
this.adapter(),
this.config,
this.adapter().normalizeIdentifier(`${this.getTablePrefixWithUnderscore()}${ref.name}`),
this.adapter().normalizeIdentifier(`${ref.schema}${this.getSchemaSuffixWithUnderscore()}`),
ref.database &&
this.adapter().normalizeIdentifier(
`${ref.database}${this.getDatabaseSuffixWithUnderscore()}`
)
)
);
}
public operate(
name: string,
queries?: Contextable<ICommonContext, string | string[]>
): Operation {
const operation = new Operation();
operation.session = this;
utils.setNameAndTarget(this, operation.proto, name);
if (queries) {
operation.queries(queries);
}
operation.proto.fileName = utils.getCallerFile(this.rootDir);
this.actions.push(operation);
return operation;
}
public publish(
name: string,
queryOrConfig?: Contextable<ITableContext, string> | ITableConfig
): Table {
const newTable = new Table();
newTable.session = this;
utils.setNameAndTarget(this, newTable.proto, name);
if (!!queryOrConfig) {
if (typeof queryOrConfig === "object") {
newTable.config(queryOrConfig);
} else {
newTable.query(queryOrConfig);
}
}
newTable.proto.fileName = utils.getCallerFile(this.rootDir);
this.actions.push(newTable);
return newTable;
}
public assert(name: string, query?: AContextable<string>): Assertion {
const assertion = new Assertion();
assertion.session = this;
utils.setNameAndTarget(this, assertion.proto, name, this.config.assertionSchema);
if (query) {
assertion.query(query);
}
assertion.proto.fileName = utils.getCallerFile(this.rootDir);
this.actions.push(assertion);
return assertion;
}
public declare(dataset: dataform.ITarget): Declaration {
const declaration = new Declaration();
declaration.session = this;
utils.setNameAndTarget(this, declaration.proto, dataset.name, dataset.schema, dataset.database);
declaration.proto.fileName = utils.getCallerFile(this.rootDir);
this.actions.push(declaration);
return declaration;
}
public test(name: string): test.Test {
const newTest = new test.Test();
newTest.session = this;
newTest.proto.name = name;
newTest.proto.fileName = utils.getCallerFile(this.rootDir);
// Add it to global index.
this.tests[name] = newTest;
return newTest;
}
public compileError(err: Error | string, path?: string, actionName?: string) {
const fileName = path || utils.getCallerFile(this.rootDir) || __filename;
const compileError = dataform.CompilationError.create({
fileName,
actionName
});
if (typeof err === "string") {
compileError.message = err;
} else {
compileError.message = err.message;
compileError.stack = err.stack;
}
this.graphErrors.compilationErrors.push(compileError);
}
public compile(): dataform.CompiledGraph {
const compiledGraph = dataform.CompiledGraph.create({
projectConfig: this.config,
tables: this.compileGraphChunk(
this.actions.filter(action => action instanceof Table),
dataform.Table.verify
),
operations: this.compileGraphChunk(
this.actions.filter(action => action instanceof Operation),
dataform.Operation.verify
),
assertions: this.compileGraphChunk(
this.actions.filter(action => action instanceof Assertion),
dataform.Assertion.verify
),
declarations: this.compileGraphChunk(
this.actions.filter(action => action instanceof Declaration),
dataform.Declaration.verify
),
tests: this.compileGraphChunk(Object.values(this.tests), dataform.Test.verify),
graphErrors: this.graphErrors,
dataformCoreVersion,
targets: this.actions.map(action => action.proto.target)
});
this.fullyQualifyDependencies(
[].concat(compiledGraph.tables, compiledGraph.assertions, compiledGraph.operations)
);
this.alterActionName(
[].concat(compiledGraph.tables, compiledGraph.assertions, compiledGraph.operations),
[].concat(compiledGraph.declarations.map(declaration => declaration.target))
);
const standardActions = [].concat(
compiledGraph.tables,
compiledGraph.assertions,
compiledGraph.operations,
compiledGraph.declarations
);
this.checkActionNameUniqueness(standardActions);
this.checkTestNameUniqueness(compiledGraph.tests);
this.checkCanonicalTargetUniqueness(standardActions);
this.checkTableConfigValidity(compiledGraph.tables);
this.checkCircularity(
[].concat(compiledGraph.tables, compiledGraph.assertions, compiledGraph.operations)
);
if (this.config.useRunCache) {
this.checkRunCachingCorrectness(
[].concat(
compiledGraph.tables,
compiledGraph.assertions,
compiledGraph.operations.filter(operation => operation.hasOutput)
)
);
}
utils.throwIfInvalid(compiledGraph, dataform.CompiledGraph.verify);
return compiledGraph;
}
public compileToBase64() {
return encode64(dataform.CompiledGraph, this.compile());
}
public findActions(target: dataform.ITarget) {
const adapter = this.adapter();
return this.actions.filter(action => {
if (
!!target.database &&
action.proto.target.database !== adapter.normalizeIdentifier(target.database)
) {
return false;
}
if (
!!target.schema &&
action.proto.target.schema !== adapter.normalizeIdentifier(target.schema)
) {
return false;
}
return action.proto.target.name === adapter.normalizeIdentifier(target.name);
});
}
private getDatabaseSuffixWithUnderscore() {
return !!this.config.databaseSuffix ? `_${this.config.databaseSuffix}` : "";
}
private getSchemaSuffixWithUnderscore() {
return !!this.config.schemaSuffix ? `_${this.config.schemaSuffix}` : "";
}
private getTablePrefixWithUnderscore() {
return !!this.config.tablePrefix ? `${this.config.tablePrefix}_` : "";
}
private compileGraphChunk<T>(
actions: Array<{ proto: IActionProto; compile(): T }>,
verify: (proto: T) => string
): T[] {
const compiledChunks: T[] = [];
actions.forEach(action => {
try {
const compiledChunk = action.compile();
utils.throwIfInvalid(compiledChunk, verify);
compiledChunks.push(compiledChunk);
} catch (e) {
this.compileError(e, action.proto.fileName, action.proto.name);
}
});
return compiledChunks;
}
private fullyQualifyDependencies(actions: IActionProto[]) {
actions.forEach(action => {
const fullyQualifiedDependencies: { [name: string]: dataform.ITarget } = {};
for (const dependency of action.dependencyTargets) {
const possibleDeps = this.findActions(dependency);
if (possibleDeps.length === 0) {
// We couldn't find a matching target.
this.compileError(
new Error(
`Missing dependency detected: Action "${
action.name
}" depends on "${utils.stringifyResolvable(dependency)}" which does not exist`
),
action.fileName,
action.name
);
} else if (possibleDeps.length === 1) {
// We found a single matching target, and fully-qualify it if it's a normal dependency,
// or add all of its dependencies to ours if it's an 'inline' table.
const protoDep = possibleDeps[0].proto;
if (protoDep instanceof dataform.Table && protoDep.type === "inline") {
protoDep.dependencyTargets.forEach(inlineDep =>
action.dependencyTargets.push(inlineDep)
);
} else {
fullyQualifiedDependencies[protoDep.name] = protoDep.target;
}
} else {
// Too many targets matched the dependency.
this.compileError(
new Error(utils.ambiguousActionNameMsg(dependency, possibleDeps)),
action.fileName,
action.name
);
}
}
action.dependencies = Object.keys(fullyQualifiedDependencies);
action.dependencyTargets = Object.values(fullyQualifiedDependencies);
});
}
private alterActionName(actions: IActionProto[], declarationTargets: dataform.ITarget[]) {
const { tablePrefix, schemaSuffix, databaseSuffix } = this.config;
if (!tablePrefix && !schemaSuffix && !databaseSuffix) {
return;
}
const newTargetByOriginalTarget = new StringifiedMap<dataform.ITarget, dataform.ITarget>(
JSONObjectStringifier.create()
);
declarationTargets.forEach(declarationTarget =>
newTargetByOriginalTarget.set(declarationTarget, declarationTarget)
);
actions.forEach(action => {
newTargetByOriginalTarget.set(action.target, {
...action.target,
database:
action.target.database &&
this.adapter().normalizeIdentifier(
`${action.target.database}${this.getDatabaseSuffixWithUnderscore()}`
),
schema: this.adapter().normalizeIdentifier(
`${action.target.schema}${this.getSchemaSuffixWithUnderscore()}`
),
name: this.adapter().normalizeIdentifier(
`${this.getTablePrefixWithUnderscore()}${action.target.name}`
)
});
action.target = newTargetByOriginalTarget.get(action.target);
action.name = utils.targetToName(action.target);
});
// Fix up dependencies in case those dependencies' names have changed.
const getUpdatedTarget = (originalTarget: dataform.ITarget) => {
// It's possible that we don't have a new Target for a dependency that failed to compile,
// so fall back to the original Target.
if (!newTargetByOriginalTarget.has(originalTarget)) {
return originalTarget;
}
return newTargetByOriginalTarget.get(originalTarget);
};
actions.forEach(action => {
action.dependencyTargets = (action.dependencyTargets || []).map(getUpdatedTarget);
action.dependencies = (action.dependencyTargets || []).map(dependencyTarget =>
utils.targetToName(dependencyTarget)
);
if (!!action.parentAction) {
action.parentAction = getUpdatedTarget(action.parentAction);
}
});
}
private checkActionNameUniqueness(actions: IActionProto[]) {
const allNames: string[] = [];
actions.forEach(action => {
if (allNames.includes(action.name)) {
this.compileError(
new Error(
`Duplicate action name detected. Names within a schema must be unique across tables, declarations, assertions, and operations`
),
action.fileName,
action.name
);
}
allNames.push(action.name);
});
}
private checkCanonicalTargetUniqueness(actions: IActionProto[]) {
const allCanonicalTargets = new StringifiedMap<dataform.ITarget, boolean>(
JSONObjectStringifier.create()
);
actions.forEach(action => {
if (allCanonicalTargets.has(action.canonicalTarget)) {
this.compileError(
new Error(
`Duplicate canonical target detected. Canonical targets must be unique across tables, declarations, assertions, and operations:\n"${JSON.stringify(
action.canonicalTarget
)}"`
),
action.fileName,
action.name
);
}
allCanonicalTargets.set(action.canonicalTarget, true);
});
}
private checkTableConfigValidity(tables: dataform.ITable[]) {
tables.forEach(table => {
// type
if (!!table.type && !TableType.includes(table.type as TableType)) {
this.compileError(
`Wrong type of table detected. Should only use predefined types: ${joinQuoted(
TableType
)}`,
table.fileName,
table.name
);
}
// snowflake config
if (!!table.snowflake) {
if (table.snowflake.secure && table.type !== "view") {
this.compileError(
new Error(`The 'secure' option is only valid for Snowflake views`),
table.fileName,
table.name
);
}
if (table.snowflake.transient && table.type !== "table") {
this.compileError(
new Error(`The 'transient' option is only valid for Snowflake tables`),
table.fileName,
table.name
);
}
if (
table.snowflake.clusterBy?.length > 0 &&
table.type !== "table" &&
table.type !== "incremental"
) {
this.compileError(
new Error(`The 'clusterBy' option is only valid for Snowflake tables`),
table.fileName,
table.name
);
}
}
// sqldatawarehouse config
if (!!table.sqlDataWarehouse) {
if (!!table.uniqueKey && table.uniqueKey.length > 0) {
this.compileError(
new Error(
`Merging using unique keys for SQLDataWarehouse has not yet been implemented`
),
table.fileName,
table.name
);
}
if (table.sqlDataWarehouse.distribution) {
const distribution = table.sqlDataWarehouse.distribution.toUpperCase();
if (
distribution !== "REPLICATE" &&
distribution !== "ROUND_ROBIN" &&
!SQL_DATA_WAREHOUSE_DIST_HASH_REGEXP.test(distribution)
) {
this.compileError(
new Error(`Invalid value for sqldatawarehouse distribution: ${distribution}`),
table.fileName,
table.name
);
}
}
}
// Redshift config
if (!!table.redshift) {
const validatePropertyDefined = (
opts: dataform.IRedshiftOptions,
prop: keyof dataform.IRedshiftOptions
) => {
const value = opts[prop];
if (!opts.hasOwnProperty(prop)) {
this.compileError(`Property "${prop}" is not defined`, table.fileName, table.name);
} else if (value instanceof Array) {
if (value.length === 0) {
this.compileError(`Property "${prop}" is not defined`, table.fileName, table.name);
}
}
};
const validatePropertiesDefined = (
opts: dataform.IRedshiftOptions,
props: Array<keyof dataform.IRedshiftOptions>
) => props.forEach(prop => validatePropertyDefined(opts, prop));
const validatePropertyValueInValues = (
opts: dataform.IRedshiftOptions,
prop: keyof dataform.IRedshiftOptions & ("distStyle" | "sortStyle"),
values: readonly string[]
) => {
if (!!opts[prop] && !values.includes(opts[prop])) {
this.compileError(
`Wrong value of "${prop}" property. Should only use predefined values: ${joinQuoted(
values
)}`,
table.fileName,
table.name
);
}
};
if (table.redshift.distStyle || table.redshift.distKey) {
validatePropertiesDefined(table.redshift, ["distStyle", "distKey"]);
validatePropertyValueInValues(table.redshift, "distStyle", DistStyleType);
}
if (
table.redshift.sortStyle ||
(table.redshift.sortKeys && table.redshift.sortKeys.length)
) {
validatePropertiesDefined(table.redshift, ["sortStyle", "sortKeys"]);
validatePropertyValueInValues(table.redshift, "sortStyle", SortStyleType);
}
}
// BigQuery config
if (!!table.bigquery) {
if (
(table.bigquery.partitionBy || table.bigquery.clusterBy?.length) &&
table.type === "view"
) {
this.compileError(
`partitionBy/clusterBy are not valid for BigQuery views; they are only valid for tables`,
table.fileName,
table.name
);
}
}
// Ignored properties
if (!!Table.IGNORED_PROPS[table.type]) {
Table.IGNORED_PROPS[table.type].forEach(ignoredProp => {
if (objectExistsOrIsNonEmpty(table[ignoredProp])) {
this.compileError(
`Unused property was detected: "${ignoredProp}". This property is not used for tables with type "${table.type}" and will be ignored`,
table.fileName,
table.name
);
}
});
}
});
}
private checkTestNameUniqueness(tests: dataform.ITest[]) {
const allNames: string[] = [];
tests.forEach(testProto => {
if (allNames.includes(testProto.name)) {
this.compileError(
new Error(`Duplicate test name detected: "${testProto.name}"`),
testProto.fileName,
testProto.name
);
}
allNames.push(testProto.name);
});
}
private checkCircularity(actions: IActionProto[]) {
const allActionsByName = keyByName(actions);
// Type exports for tarjan-graph are unfortunately wrong, so we have to do this minor hack.
const tarjanGraph: TarjanGraph = new (TarjanGraphConstructor as any)();
actions.forEach(action => {
const cleanedDependencies = (action.dependencies || []).filter(
dependency => !!allActionsByName[dependency]
);
tarjanGraph.add(action.name, cleanedDependencies);
});
const cycles = tarjanGraph.getCycles();
cycles.forEach(cycle => {
const firstActionInCycle = allActionsByName[cycle[0].name];
const message = `Circular dependency detected in chain: [${cycle
.map(vertex => vertex.name)
.join(" > ")} > ${firstActionInCycle.name}]`;
this.compileError(new Error(message), firstActionInCycle.fileName);
});
}
private checkRunCachingCorrectness(actionsWithOutput: IActionProto[]) {
actionsWithOutput.forEach(action => {
if (action.dependencies?.length > 0) {
return;
}
if (
[dataform.ActionHermeticity.HERMETIC, dataform.ActionHermeticity.NON_HERMETIC].includes(
action.hermeticity
)
) {
return;
}
this.compileError(
new Error(
"Zero-dependency actions which create datasets are required to explicitly declare 'hermetic: (true|false)' when run caching is turned on."
),
action.fileName,
action.name
);
});
}
}
function declaresDataset(type: string, hasOutput?: boolean) {
return definesDataset(type) || type === "declaration" || hasOutput;
}
function definesDataset(type: string) {
return type === "view" || type === "table" || type === "inline" || type === "incremental";
}
function keyByName(actions: IActionProto[]) {
const actionsByName: { [name: string]: IActionProto } = {};
actions.forEach(action => (actionsByName[action.name] = action));
return actionsByName;
}
function getCanonicalProjectConfig(originalProjectConfig: dataform.IProjectConfig) {
return {
warehouse: originalProjectConfig.warehouse,
defaultSchema: originalProjectConfig.defaultSchema,
defaultDatabase: originalProjectConfig.defaultDatabase,
assertionSchema: originalProjectConfig.assertionSchema
};
}
function joinQuoted(values: readonly string[]) {
return values.map((value: string) => `"${value}"`).join(" | ");
}
function objectExistsOrIsNonEmpty(prop: any): boolean {
if (!prop) {
return false;
}
return (
(Array.isArray(prop) && !!prop.length) ||
(!Array.isArray(prop) && typeof prop === "object" && !!Object.keys(prop).length) ||
typeof prop !== "object"
);
} | the_stack |
import { useId } from '@reach/auto-id';
import { setStatus } from 'a11y-status';
import type { DependencyList, Dispatch, EffectCallback, MutableRefObject } from 'react';
import { useEffect, useReducer, useRef } from 'react';
import useEffectOnce from 'react-use/lib/useEffectOnce';
import useShallowCompareEffect from 'react-use/lib/useShallowCompareEffect';
import { isEmptyArray } from '@remirror/core-helpers';
import { multishiftReducer } from './multishift-reducer';
import type {
A11yStatusMessageProps,
GetA11yStatusMessage,
ItemsToString,
MultishiftA11yIdProps,
MultishiftProps,
MultishiftRootActions,
MultishiftState,
} from './multishift-types';
import {
callChangeHandlers,
defaultItemsToString,
GetElementIds,
getElementIds,
getInitialStateProps,
isOrContainsNode,
} from './multishift-utils';
/**
* Creates the reducer for managing the multishift internal state.
*/
export function useMultishiftReducer<Item = any>(
props: MultishiftProps<Item>,
): [MultishiftState<Item>, Dispatch<MultishiftRootActions<Item>>] {
const { stateReducer, ...rest } = props;
const initialState = getInitialStateProps<Item>(rest);
return useReducer((prevState: MultishiftState<Item>, action: MultishiftRootActions<Item>) => {
const [state, changes] = multishiftReducer(prevState, action, rest);
const changeset = { changes, state, prevState };
callChangeHandlers(rest, changeset);
if (stateReducer) {
return stateReducer(changeset, action, rest);
}
return state;
}, initialState);
}
/**
* Creates the ids for identifying the elements in the app.
*/
export function useElementIds(props: MultishiftA11yIdProps): GetElementIds {
const defaultId = useId();
return getElementIds(defaultId ?? '', props);
}
interface UseElementRefs {
toggleButton: MutableRefObject<HTMLElement | undefined>;
input: MutableRefObject<HTMLElement | undefined>;
menu: MutableRefObject<HTMLElement | undefined>;
comboBox: MutableRefObject<HTMLElement | undefined>;
items: MutableRefObject<HTMLElement[]>;
ignored: MutableRefObject<HTMLElement[]>;
}
/**
* Get the element references.
*/
export function useElementRefs(): UseElementRefs {
const items = useRef<HTMLElement[]>([]);
const ignored = useRef<HTMLElement[]>([]);
const toggleButton = useRef<HTMLElement>();
const input = useRef<HTMLElement>();
const menu = useRef<HTMLElement>();
const comboBox = useRef<HTMLElement>();
// Reset the items ref nodes on each call render.
items.current = [];
ignored.current = [];
return useRef({ toggleButton, input, menu, comboBox, items, ignored }).current;
}
/**
* A default getA11yStatusMessage function is provided that will check `items.current.length`
* and return "No results." or if there are results but no item is highlighted,
* "resultCount results are available, use up and down arrow keys to navigate."
* If items are highlighted it will run `itemToString(highlightedItem)` and display
* the value of the `highlightedItem`.
*/
const defaultGetA11yStatusMessage = <Item = any>({
items,
state: { selectedItems, isOpen },
itemsToString = defaultItemsToString,
}: A11yStatusMessageProps<Item>) => {
if (!isEmptyArray(selectedItems)) {
return `${itemsToString(selectedItems)} has been selected.`;
}
if (isEmptyArray(items)) {
return '';
}
const resultCount = items.length;
if (isOpen) {
if (resultCount === 0) {
return 'No results are available';
}
return `${resultCount} result${
resultCount === 1 ? ' is' : 's are'
} available, use up and down arrow keys to navigate. Press Enter key to select.`;
}
return '';
};
interface UseSetA11yProps<Item = any> {
state: MultishiftState<Item>;
items: Item[];
itemsToString?: ItemsToString<Item>;
getA11yStatusMessage?: GetA11yStatusMessage<Item>;
customA11yStatusMessage?: string;
}
export function useSetA11y<Item = any>(props: UseSetA11yProps<Item>): void {
const {
state,
items,
itemsToString = defaultItemsToString,
getA11yStatusMessage = defaultGetA11yStatusMessage,
customA11yStatusMessage = '',
} = props;
const automaticMessage = getA11yStatusMessage({
state,
items,
itemsToString,
});
// Sets a11y status message on changes to relevant state values.
useEffectOnUpdate(() => {
setStatus(automaticMessage);
}, [state.isOpen, state.selectedItems]);
// Sets a11y status message on changes in customA11yStatusMessage
useEffect(() => {
if (customA11yStatusMessage) {
setStatus(customA11yStatusMessage);
}
}, [customA11yStatusMessage]);
}
/**
* This is a hook that listens for events mouse and touch events.
*
* When something does occur outside of the registered elements it will dispatch
* the relevant action.
*/
export function useOuterEventListener<Item = any>(
refs: ReturnType<typeof useElementRefs>,
state: MultishiftState<Item>,
{ outerMouseUp, outerTouchEnd }: { outerMouseUp: () => void; outerTouchEnd: () => void },
): MutableRefObject<{
isMouseDown: boolean;
isTouchMove: boolean;
lastBlurred: HTMLElement | undefined;
}> {
const context = useRef({
isMouseDown: false,
isTouchMove: false,
lastBlurred: undefined as HTMLElement | undefined,
});
const isOpen = useRef(state.isOpen);
isOpen.current = state.isOpen;
const targetWithinMultishift = (target: Node | null, checkActiveElement = true) => {
return [
refs.comboBox.current,
refs.menu.current,
refs.toggleButton.current,
refs.input.current,
...refs.ignored.current,
...refs.items.current,
].some((node) => {
return (
node &&
(isOrContainsNode(node, target) ||
(checkActiveElement && isOrContainsNode(node, window.document.activeElement)))
);
});
};
useEffectOnce(() => {
// Borrowed from `downshift`
// context.current.isMouseDown helps us track whether the mouse is currently held down.
// This is useful when the user clicks on an item in the list, but holds the mouse
// down long enough for the list to disappear (because the blur event fires on the input)
// context.current.isMouseDown is used in the blur handler on the input to determine whether the blur event should
// trigger hiding the menu.
const onMouseDown = () => {
context.current.isMouseDown = true;
};
const onMouseUp = (event: MouseEvent) => {
context.current.isMouseDown = false;
// if the target element or the activeElement is within a multishift node
// then we don't want to reset multishift
const contextWithinMultishift = targetWithinMultishift(event.target as Node);
if (!contextWithinMultishift && isOpen.current) {
outerMouseUp();
}
};
// Borrowed from `downshift`
// Touching an element in iOS gives focus and hover states, but touching out of
// the element will remove hover, and persist the focus state, resulting in the
// blur event not being triggered.
// context.current.isTouchMove helps us track whether the user is tapping or swiping on a touch screen.
// If the user taps outside of Multishift, the component should be reset,
// but not if the user is swiping
const onTouchStart = () => {
context.current.isTouchMove = false;
};
const onTouchMove = () => {
context.current.isTouchMove = true;
};
const onTouchEnd = (event: TouchEvent) => {
const contextWithinMultishift = targetWithinMultishift(event.target as Node, false);
if (!context.current.isTouchMove && !contextWithinMultishift && isOpen.current) {
outerTouchEnd();
}
};
window.addEventListener('mousedown', onMouseDown);
window.addEventListener('mouseup', onMouseUp);
window.addEventListener('touchstart', onTouchStart);
window.addEventListener('touchmove', onTouchMove);
window.addEventListener('touchend', onTouchEnd);
return () => {
window.removeEventListener('mousedown', onMouseDown);
window.removeEventListener('mouseup', onMouseUp);
window.removeEventListener('touchstart', onTouchStart);
window.removeEventListener('touchmove', onTouchMove);
window.removeEventListener('touchend', onTouchEnd);
};
});
return context;
}
/**
* A hook for managing multiple timeouts.
*
* @remarks
*
* All timeouts are automatically cleared when un-mounting.
*/
export function useTimeouts(): Readonly<[(fn: () => void, time?: number) => void, () => void]> {
const timeoutIds = useRef<any[]>([]);
const setHookTimeout = (fn: () => void, time = 1) => {
const id = setTimeout(() => {
timeoutIds.current = timeoutIds.current.filter((timeoutId) => timeoutId !== id);
fn();
}, time);
timeoutIds.current.push(id);
};
const clearHookTimeouts = () => {
timeoutIds.current.forEach((id) => {
clearTimeout(id);
});
timeoutIds.current = [];
};
// Clear the timeouts on dismount
useEffectOnce(() => clearHookTimeouts);
return [setHookTimeout, clearHookTimeouts] as const;
}
/**
* React effect hook that ignores the first invocation (e.g. on mount).
*
* @remarks
*
* The signature is exactly the same as the useEffect hook.
*
* ```tsx
* import React from 'react'
* import { useEffectOnUpdate } from 'react-use';
*
* const Demo = () => {
* const [count, setCount] = React.useState(0);
*
* React.useEffect(() => {
* const interval = setInterval(() => {
* setCount(count => count + 1)
* }, 1000)
*
* return () => {
* clearInterval(interval)
* }
* }, [])
*
* useEffectOnUpdate(() => {
* log('count', count) // will only show 1 and beyond
*
* return () => { // *OPTIONAL*
* // do something on unmount
* }
* }) // you can include deps array if necessary
*
* return <div>Count: {count}</div>
* };
* ```
*/
export function useEffectOnUpdate(effect: EffectCallback, dependencies: DependencyList): void {
const isInitialMount = useRef(true);
useShallowCompareEffect(() => {
if (isInitialMount.current) {
isInitialMount.current = false;
} else {
return effect();
}
}, [dependencies]);
}
/**
* React lifecycle hook that calls a function when the component will unmount.
*
* @remarks
*
* Try `useEffectOnce` if you need both a mount and unmount function.
*
* ```jsx
* import {useUnmount} from 'react-use';
*
* const Demo = () => {
* useUnmount(() => log('UNMOUNTED'));
* return null;
* };
* ```
*/
export function useUnmount(fn: () => void | undefined): void {
useEffectOnce(() => fn);
} | the_stack |
import { Component, h, RenderableProps } from 'preact';
import { getDeviceInfo, setMnemonicPassphraseEnabled } from '../../../api/bitbox02';
import { translate, TranslateProps } from '../../../decorators/translate';
import { SimpleMarkup } from '../../../utils/simplemarkup';
import { Button, Checkbox } from '../../../components/forms';
import { alertUser } from '../../../components/alert/Alert';
import { SettingsButton } from '../../../components/settingsButton/settingsButton';
import { Dialog, DialogButtons } from '../../../components/dialog/dialog';
import { WaitDialog } from '../../../components/wait-dialog/wait-dialog';
import { Message } from '../../../components/message/message';
interface MnemonicPassphraseButtonProps {
deviceID: string;
passphraseEnabled: boolean;
}
interface State {
infoStep: number;
passphraseEnabled: boolean;
status: 'idle' | 'info' | 'progress' | 'success';
understood: boolean;
}
type Props = MnemonicPassphraseButtonProps & TranslateProps;
class MnemonicPassphraseButton extends Component<Props, State> {
public readonly state: State = {
infoStep: 5,
status: 'idle',
passphraseEnabled: this.props.passphraseEnabled,
understood: false,
}
private togglePassphrase = () => {
const { t } = this.props;
const enable = !this.state.passphraseEnabled;
this.setState({ status: 'progress' });
setMnemonicPassphraseEnabled(this.props.deviceID, enable)
.then(() => getDeviceInfo(this.props.deviceID))
.then(({ mnemonicPassphraseEnabled }) => {
this.setState({
passphraseEnabled: mnemonicPassphraseEnabled,
status: 'success',
});
})
.catch((e) => {
this.setState({ status: 'idle' });
alertUser(t(`passphrase.error.e${e.code}`, {
defaultValue: e.message || t('genericError'),
}));
});
}
private startInfo = () => {
const { passphraseEnabled } = this.state;
this.setState({
// before enabling/disabling we show 1 or more pages to inform about the feature
// each page has a continue button that jumps to the next or finally toggles passphrase
// infoStep counts down in decreasing order
infoStep: passphraseEnabled
? 0 // disabling passphrase shows only 1 info dialog
: 5, // enabling has 6 dialogs with information
status: 'info',
understood: false,
});
}
private stopInfo = () => this.setState({ status: 'idle' })
private continueInfo = () => {
if (this.state.infoStep === 0) {
this.togglePassphrase();
return;
}
this.setState(({ infoStep }) => ({ infoStep: infoStep - 1 }));
}
private renderEnableInfo = () => {
const { infoStep, understood } = this.state;
const { t } = this.props;
switch (infoStep) {
case 5:
return (
<Dialog key="step-intro" medium title={t('passphrase.intro.title')} onClose={this.stopInfo}>
{this.renderMultiLine(t('passphrase.intro.message'))}
<DialogButtons>
<Button primary onClick={this.continueInfo}>
{t('passphrase.what.button')}
</Button>
<Button transparent onClick={this.stopInfo}>
{t('button.back')}
</Button>
</DialogButtons>
</Dialog>
);
case 4:
return (
<Dialog key="step-what" medium title={t('passphrase.what.title')} onClose={this.stopInfo}>
{this.renderMultiLine(t('passphrase.what.message'))}
<DialogButtons>
<Button primary onClick={this.continueInfo}>
{t('passphrase.why.button')}
</Button>
<Button transparent onClick={this.stopInfo}>
{t('button.back')}
</Button>
</DialogButtons>
</Dialog>
);
case 3:
return (
<Dialog key="step-why" medium title={t('passphrase.why.title')} onClose={this.stopInfo}>
{this.renderMultiLine(t('passphrase.why.message'))}
<DialogButtons>
<Button primary onClick={this.continueInfo}>
{t('passphrase.considerations.button')}
</Button>
<Button transparent onClick={this.stopInfo}>
{t('button.back')}
</Button>
</DialogButtons>
</Dialog>
);
case 2:
return (
<Dialog key="step-considerations" medium title={t('passphrase.considerations.title')} onClose={this.stopInfo}>
{this.renderMultiLine(t('passphrase.considerations.message'))}
<DialogButtons>
<Button primary onClick={this.continueInfo}>
{t('passphrase.how.button')}
</Button>
<Button transparent onClick={this.stopInfo}>
{t('button.back')}
</Button>
</DialogButtons>
</Dialog>
);
case 1:
return (
<Dialog key="step-how" medium title={t('passphrase.how.title')} onClose={this.stopInfo}>
{this.renderMultiLine(t('passphrase.how.message'))}
<DialogButtons>
<Button primary onClick={this.continueInfo}>
{t('passphrase.summary.button')}
</Button>
<Button transparent onClick={this.stopInfo}>
{t('button.back')}
</Button>
</DialogButtons>
</Dialog>
);
case 0:
return (
<Dialog key="step-summary" medium title={t('passphrase.summary.title')} onClose={this.stopInfo}>
<ul style="padding-left: var(--space-default);">
<SimpleMarkup key="info-1" tagName="li" markup={t('passphrase.summary.understandList.0')} />
<SimpleMarkup key="info-2" tagName="li" markup={t('passphrase.summary.understandList.1')} />
<SimpleMarkup key="info-3" tagName="li" markup={t('passphrase.summary.understandList.2')} />
</ul>
<Message type="message">
<Checkbox
onChange={e => this.setState({ understood: (e.target as HTMLInputElement)?.checked })}
id="understood"
checked={understood}
label={t('passphrase.summary.understand')} />
</Message>
<DialogButtons>
<Button primary onClick={this.continueInfo} disabled={!understood}>
{t('passphrase.enable')}
</Button>
<Button transparent onClick={this.stopInfo}>
{t('button.back')}
</Button>
</DialogButtons>
</Dialog>
);
default:
console.error(`invalid infoStep ${infoStep}`);
return;
}
}
private renderMultiLine = text => text.split('\n').map((line: string, i: number) => (
<SimpleMarkup key={`${line}-${i}`} tagName="p" markup={line} />
))
private renderDisableInfo = () => {
const { t } = this.props;
return (
<Dialog key="step-disable-info1" medium title={t('passphrase.disable')} onClose={this.stopInfo}>
{this.renderMultiLine(t('passphrase.disableInfo.message'))}
<DialogButtons>
<Button primary onClick={this.continueInfo}>
{t('passphrase.disableInfo.button')}
</Button>
<Button transparent onClick={this.stopInfo}>
{t('button.back')}
</Button>
</DialogButtons>
</Dialog>
);
}
public render(
{ t }: RenderableProps<Props>,
{ passphraseEnabled, status }: State,
) {
return (
<div>
<SettingsButton onClick={this.startInfo}>
{passphraseEnabled
? t('passphrase.disable')
: t('passphrase.enable')}
</SettingsButton>
{status === 'info' && (
passphraseEnabled
? this.renderDisableInfo()
: this.renderEnableInfo()
)}
{status === 'progress' && (
<WaitDialog
title={t(passphraseEnabled
? 'passphrase.progressDisable.title'
: 'passphrase.progressEnable.title')}>
{t(passphraseEnabled
? 'passphrase.progressDisable.message'
: 'passphrase.progressEnable.message')}
</WaitDialog>
)}
{status === 'success' && (
<WaitDialog
title={t(passphraseEnabled
? 'passphrase.successDisabled.title'
: 'passphrase.successEnabled.title')} >
{this.renderMultiLine(
t(passphraseEnabled
? 'passphrase.successDisabled.message'
: 'passphrase.successEnabled.message')
)}
</WaitDialog>
)}
</div>
);
}
}
const HOC = translate<MnemonicPassphraseButtonProps>()(MnemonicPassphraseButton );
export { HOC as MnemonicPassphraseButton }; | the_stack |
import { expect } from 'chai';
import { SortedMap, LLRBNode } from '../src/core/util/SortedMap';
import { shuffle } from './helpers/util';
// Many of these were adapted from the mugs source code.
// http://mads379.github.com/mugs/
describe('SortedMap Tests', () => {
const defaultCmp = function (a, b) {
if (a === b) {
return 0;
} else if (a < b) {
return -1;
} else {
return 1;
}
};
it('Create node', () => {
const map = new SortedMap(defaultCmp).insert('key', 'value');
expect((map as any).root_.left.isEmpty()).to.equal(true);
expect((map as any).root_.right.isEmpty()).to.equal(true);
});
it('You can search a map for a specific key', () => {
const map = new SortedMap(defaultCmp).insert(1, 1).insert(2, 2);
expect(map.get(1)).to.equal(1);
expect(map.get(2)).to.equal(2);
expect(map.get(3)).to.equal(null);
});
it('You can insert a new key/value pair into the tree', () => {
const map = new SortedMap(defaultCmp).insert(1, 1).insert(2, 2);
expect((map as any).root_.key).to.equal(2);
expect((map as any).root_.left.key).to.equal(1);
});
it('You can remove a key/value pair from the map', () => {
const map = new SortedMap(defaultCmp).insert(1, 1).insert(2, 2);
const newMap = map.remove(1);
expect(newMap.get(2)).to.equal(2);
expect(newMap.get(1)).to.equal(null);
});
it('More removals', () => {
const map = new SortedMap(defaultCmp)
.insert(1, 1)
.insert(50, 50)
.insert(3, 3)
.insert(4, 4)
.insert(7, 7)
.insert(9, 9)
.insert(20, 20)
.insert(18, 18)
.insert(2, 2)
.insert(71, 71)
.insert(42, 42)
.insert(88, 88);
const m1 = map.remove(7);
const m2 = m1.remove(3);
const m3 = m2.remove(1);
expect(m3.count()).to.equal(9);
expect(m3.get(1)).to.equal(null);
expect(m3.get(3)).to.equal(null);
expect(m3.get(7)).to.equal(null);
expect(m3.get(20)).to.equal(20);
});
it('Removal bug', () => {
const map = new SortedMap(defaultCmp)
.insert(1, 1)
.insert(2, 2)
.insert(3, 3);
const m1 = map.remove(2);
expect(m1.get(1)).to.equal(1);
expect(m1.get(3)).to.equal(3);
});
it('Test increasing', () => {
const total = 100;
let item;
let map = new SortedMap(defaultCmp).insert(1, 1);
for (item = 2; item < total; item++) {
map = map.insert(item, item);
}
expect((map as any).root_.checkMaxDepth_()).to.equal(true);
for (item = 2; item < total; item++) {
map = map.remove(item);
}
expect((map as any).root_.checkMaxDepth_()).to.equal(true);
});
it('The structure should be valid after insertion (1)', () => {
const map = new SortedMap(defaultCmp)
.insert(1, 1)
.insert(2, 2)
.insert(3, 3);
expect((map as any).root_.key).to.equal(2);
expect((map as any).root_.left.key).to.equal(1);
expect((map as any).root_.right.key).to.equal(3);
});
it('The structure should be valid after insertion (2)', () => {
const map = new SortedMap(defaultCmp)
.insert(1, 1)
.insert(2, 2)
.insert(3, 3)
.insert(4, 4)
.insert(5, 5)
.insert(6, 6)
.insert(7, 7)
.insert(8, 8)
.insert(9, 9)
.insert(10, 10)
.insert(11, 11)
.insert(12, 12);
expect(map.count()).to.equal(12);
expect((map as any).root_.checkMaxDepth_()).to.equal(true);
});
it('Rotate left leaves the tree in a valid state', () => {
const node = new LLRBNode(
4,
4,
false,
new LLRBNode(2, 2, false, null, null),
new LLRBNode(
7,
7,
true,
new LLRBNode(5, 5, false, null, null),
new LLRBNode(8, 8, false, null, null)
)
);
const node2 = (node as any).rotateLeft_();
expect(node2.count()).to.equal(5);
expect(node2.checkMaxDepth_()).to.equal(true);
});
it('Rotate right leaves the tree in a valid state', () => {
const node = new LLRBNode(
7,
7,
false,
new LLRBNode(
4,
4,
true,
new LLRBNode(2, 2, false, null, null),
new LLRBNode(5, 5, false, null, null)
),
new LLRBNode(8, 8, false, null, null)
);
const node2 = (node as any).rotateRight_();
expect(node2.count()).to.equal(5);
expect(node2.key).to.equal(4);
expect(node2.left.key).to.equal(2);
expect(node2.right.key).to.equal(7);
expect(node2.right.left.key).to.equal(5);
expect(node2.right.right.key).to.equal(8);
});
it('The structure should be valid after insertion (3)', () => {
const map = new SortedMap(defaultCmp)
.insert(1, 1)
.insert(50, 50)
.insert(3, 3)
.insert(4, 4)
.insert(7, 7)
.insert(9, 9);
expect(map.count()).to.equal(6);
expect((map as any).root_.checkMaxDepth_()).to.equal(true);
const m2 = map.insert(20, 20).insert(18, 18).insert(2, 2);
expect(m2.count()).to.equal(9);
expect((m2 as any).root_.checkMaxDepth_()).to.equal(true);
const m3 = m2.insert(71, 71).insert(42, 42).insert(88, 88);
expect(m3.count()).to.equal(12);
expect((m3 as any).root_.checkMaxDepth_()).to.equal(true);
});
it('you can overwrite a value', () => {
const map = new SortedMap(defaultCmp).insert(10, 10).insert(10, 8);
expect(map.get(10)).to.equal(8);
});
it('removing the last element returns an empty map', () => {
const map = new SortedMap(defaultCmp).insert(10, 10).remove(10);
expect(map.isEmpty()).to.equal(true);
});
it('empty .get()', () => {
const empty = new SortedMap(defaultCmp);
expect(empty.get('something')).to.equal(null);
});
it('empty .count()', () => {
const empty = new SortedMap(defaultCmp);
expect(empty.count()).to.equal(0);
});
it('empty .remove()', () => {
const empty = new SortedMap(defaultCmp);
expect(empty.remove('something').count()).to.equal(0);
});
it('.reverseTraversal() works.', () => {
const map = new SortedMap(defaultCmp)
.insert(1, 1)
.insert(5, 5)
.insert(3, 3)
.insert(2, 2)
.insert(4, 4);
let next = 5;
map.reverseTraversal((key, value) => {
expect(key).to.equal(next);
next--;
});
expect(next).to.equal(0);
});
it('insertion and removal of 100 items in random order.', () => {
const N = 100;
const toInsert = [],
toRemove = [];
for (let i = 0; i < N; i++) {
toInsert.push(i);
toRemove.push(i);
}
shuffle(toInsert);
shuffle(toRemove);
let map = new SortedMap(defaultCmp);
for (let i = 0; i < N; i++) {
map = map.insert(toInsert[i], toInsert[i]);
expect((map as any).root_.checkMaxDepth_()).to.equal(true);
}
expect(map.count()).to.equal(N);
// Ensure order is correct.
let next = 0;
map.inorderTraversal((key, value) => {
expect(key).to.equal(next);
expect(value).to.equal(next);
next++;
});
expect(next).to.equal(N);
for (let i = 0; i < N; i++) {
expect((map as any).root_.checkMaxDepth_()).to.equal(true);
map = map.remove(toRemove[i]);
}
expect(map.count()).to.equal(0);
});
// A little perf test for convenient benchmarking.
xit('Perf', () => {
for (let j = 0; j < 5; j++) {
let map = new SortedMap(defaultCmp);
const start = new Date().getTime();
for (let i = 0; i < 50000; i++) {
map = map.insert(i, i);
}
for (let i = 0; i < 50000; i++) {
map = map.remove(i);
}
const end = new Date().getTime();
// console.log(end-start);
}
});
xit('Perf: Insertion and removal with various # of items.', () => {
const verifyTraversal = function (map, max) {
let next = 0;
map.inorderTraversal((key, value) => {
expect(key).to.equal(next);
expect(value).to.equal(next);
next++;
});
expect(next).to.equal(max);
};
for (let N = 10; N <= 100000; N *= 10) {
const toInsert = [],
toRemove = [];
for (let i = 0; i < N; i++) {
toInsert.push(i);
toRemove.push(i);
}
shuffle(toInsert);
shuffle(toRemove);
let map = new SortedMap(defaultCmp);
const start = new Date().getTime();
for (let i = 0; i < N; i++) {
map = map.insert(toInsert[i], toInsert[i]);
}
// Ensure order is correct.
verifyTraversal(map, N);
for (let i = 0; i < N; i++) {
map = map.remove(toRemove[i]);
}
const elapsed = new Date().getTime() - start;
// console.log(N + ": " +elapsed);
}
});
xit('Perf: Comparison with {}: Insertion and removal with various # of items.', () => {
const verifyTraversal = function (tree, max) {
const keys = [];
for (const k of Object.keys(tree)) {
keys.push(k);
}
keys.sort();
expect(keys.length).to.equal(max);
for (let i = 0; i < max; i++) {
expect(tree[i]).to.equal(i);
}
};
for (let N = 10; N <= 100000; N *= 10) {
const toInsert = [],
toRemove = [];
for (let i = 0; i < N; i++) {
toInsert.push(i);
toRemove.push(i);
}
shuffle(toInsert);
shuffle(toRemove);
const tree = {};
const start = new Date().getTime();
for (let i = 0; i < N; i++) {
tree[i] = i;
}
// Ensure order is correct.
//verifyTraversal(tree, N);
for (let i = 0; i < N; i++) {
delete tree[i];
}
const elapsed = new Date().getTime() - start;
// console.log(N + ": " +elapsed);
}
});
it('SortedMapIterator empty test.', () => {
const map = new SortedMap(defaultCmp);
const iterator = map.getIterator();
expect(iterator.getNext()).to.equal(null);
});
it('SortedMapIterator test with 10 items.', () => {
const items = [];
for (let i = 0; i < 10; i++) {
items.push(i);
}
shuffle(items);
let map = new SortedMap(defaultCmp);
for (let i = 0; i < 10; i++) {
map = map.insert(items[i], items[i]);
}
const iterator = map.getIterator();
let n = iterator.getNext() as any,
expected = 0;
while (n !== null) {
expect(n.key).to.equal(expected);
expect(n.value).to.equal(expected);
expected++;
n = iterator.getNext();
}
expect(expected).to.equal(10);
});
it('SortedMap.getPredecessorKey works.', () => {
const map = new SortedMap(defaultCmp)
.insert(1, 1)
.insert(50, 50)
.insert(3, 3)
.insert(4, 4)
.insert(7, 7)
.insert(9, 9);
expect(map.getPredecessorKey(1)).to.equal(null);
expect(map.getPredecessorKey(3)).to.equal(1);
expect(map.getPredecessorKey(4)).to.equal(3);
expect(map.getPredecessorKey(7)).to.equal(4);
expect(map.getPredecessorKey(9)).to.equal(7);
expect(map.getPredecessorKey(50)).to.equal(9);
});
}); | the_stack |
import minimist from 'yargs-parser'
import Debug from 'debug'
const debug = Debug('core/repl')
const debugCommandErrors = Debug('core/repl/errors')
import { v4 as uuid } from 'uuid'
import isError from './error'
import encodeComponent from './encode'
import { splitIntoPipeStages } from './pipe-stages'
import { split, patterns, semiSplit } from './split'
import { RawContent, RawResponse, isRawResponse, MixedResponse, MixedResponsePart } from '../models/entity'
import { getHistoryForTab } from '../models/history'
import { Executor, ReplEval, DirectReplEval } from './types'
import { isMultiModalResponse } from '../models/mmr/is'
import { isNavResponse } from '../models/NavResponse'
import expandHomeDir from '../util/home'
import { CommandStartEvent, CommandCompleteEvent } from './events'
import {
CommandLine,
CommandTreeResolution,
CommandHandlerWithEvents,
EvaluatorArgs as Arguments,
ExecType,
KResponse,
ParsedOptions,
YargsParserFlags
} from '../models/command'
import REPL from '../models/repl'
import { ExecOptions, ExecOptionsWithUUID, DefaultExecOptions, DefaultExecOptionsForTab } from '../models/execOptions'
import eventChannelUnsafe, { eventBus } from '../core/events'
import { CodedError } from '../models/errors'
import { UsageModel, UsageRow } from '../core/usage-error'
import { isHeadless, hasLocalAccess } from '../core/capabilities'
import { promiseEach } from '../util/async'
import SymbolTable from '../core/symbol-table'
import { getModel } from '../commands/tree'
import { isSuccessfulCommandResolution } from '../commands/resolution'
import { Tab, getCurrentTab, getTabId, splitFor } from '../webapp/tab'
import { Block } from '../webapp/models/block'
import { Stream, Streamable } from '../models/streamable'
import enforceUsage from './enforce-usage'
import { isXtermResponse } from '../models/XtermResponse'
let currentEvaluatorImpl: ReplEval = new DirectReplEval()
export const setEvaluatorImpl = (impl: ReplEval): void => {
debug('setting evaluator impl', impl.name)
currentEvaluatorImpl = impl
}
/** trim the optional suffix e.g. --last [actionName] */
const stripTrailer = (str: string) => str && str.replace(/\s+.*$/, '')
/** turn --foo into foo and -f into f */
const unflag = (opt: string) => opt && stripTrailer(opt.replace(/^[-]+/, ''))
const emptyExecOptions = (): ExecOptions => new DefaultExecOptions()
function okIf404(err: CodedError) {
if (err.code === 404) {
return false
} else {
throw err
}
}
/**
* Find a matching command evaluator
*
*/
async function lookupCommandEvaluator<T extends KResponse, O extends ParsedOptions>(
argv: string[],
execOptions: ExecOptions
): Promise<CommandTreeResolution<T, O>> {
// first try treating options as binary
const tryCatchalls = false
const argvNoOptions = argv.filter((_, idx, A) => _.charAt(0) !== '-' && (idx === 0 || A[idx - 1].charAt(0) !== '-'))
const evaluator = await getModel()
.read<T, O>(argvNoOptions, execOptions, tryCatchalls)
.catch(okIf404)
if (!isSuccessfulCommandResolution(evaluator)) {
// then try treating options as unary
const tryCatchalls2 = false
const argvNoOptions2 = argv.filter(_ => _.charAt(0) !== '-')
const evaluator2 = await getModel()
.read<T, O>(argvNoOptions2, execOptions, tryCatchalls2)
.catch(okIf404)
if (isSuccessfulCommandResolution(evaluator2)) {
return evaluator2
} else {
const tryCatchalls3 = true
const evaluator3 = await getModel().read<T, O>(argvNoOptions, execOptions, tryCatchalls3)
if (isSuccessfulCommandResolution(evaluator3)) {
return evaluator3
}
}
}
return evaluator
}
interface CommandEvaluationError extends CodedError {
kind: 'commandresolution'
}
/**
* Execute the given command-line directly in this process
*
*/
class InProcessExecutor implements Executor {
public name = 'InProcessExecutor'
private loadSymbolTable(tab: Tab, execOptions: ExecOptions) {
if (!isHeadless()) {
const curDic = SymbolTable.read(tab)
if (typeof curDic !== 'undefined') {
if (!execOptions.env) {
execOptions.env = {}
}
execOptions.env = Object.assign({}, execOptions.env, curDic)
}
}
}
/** Add a history entry */
private pushHistory(command: string, execOptions: ExecOptions, tab: Tab): number | void {
if (!execOptions || !execOptions.noHistory) {
if (!execOptions || !execOptions.quiet) {
if (!execOptions || execOptions.type !== ExecType.Nested) {
const historyModel = getHistoryForTab(tab.uuid)
return (execOptions.history = historyModel.add({
raw: command
}))
}
}
}
}
/** Update a history entry with the response */
/* private updateHistory(cursor: number, endEvent: CommandCompleteEvent) {
getHistoryForTab(endEvent.tab.uuid).update(cursor, async line => {
const resp = await endEvent.response
if (!isHTML(resp) && !isReactResponse(resp)) {
try {
JSON.stringify(resp)
line.response = resp
line.execUUID = endEvent.execUUID
line.historyIdx = endEvent.historyIdx
line.responseType = endEvent.responseType
} catch (err) {
debug('non-serializable response', resp)
}
}
})
} */
/** Notify the world that a command execution has begun */
private emitStartEvent(startEvent: CommandStartEvent) {
eventBus.emitCommandStart(startEvent)
}
/** Notify the world that a command execution has finished */
private emitCompletionEvent<T extends KResponse, O extends ParsedOptions>(
presponse: T | Promise<T>,
endEvent: Omit<CommandCompleteEvent, 'response' | 'responseType' | 'historyIdx'>,
historyIdx?: number
) {
return Promise.resolve(presponse).then(response => {
const responseType = isMultiModalResponse(response)
? ('MultiModalResponse' as const)
: isNavResponse(response)
? ('NavResponse' as const)
: ('ScalarResponse' as const)
const fullEvent = Object.assign(endEvent, { response, responseType, historyIdx })
eventBus.emitCommandComplete(fullEvent)
/* if (historyIdx) {
this.updateHistory(historyIdx, fullEvent)
} */
})
}
/**
* Split an `argv` into a pair of `argvNoOptions` and `ParsedOptions`.
*
*/
private parseOptions<T extends KResponse, O extends ParsedOptions>(
argv: string[],
evaluator: CommandHandlerWithEvents<T, O>
): { argvNoOptions: string[]; parsedOptions: O } {
/* interface ArgCount {
[key: string]: number
} */
//
// fetch the usage model for the command
//
const _usage: UsageModel = evaluator.options && evaluator.options.usage
const usage: UsageModel = _usage && _usage.fn ? _usage.fn(_usage.command) : _usage
// debug('usage', usage)
/* if (execOptions && execOptions.failWithUsage && !usage) {
debug('caller needs usage model, but none exists for this command', evaluator)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (false as any) as T
} */
const builtInOptions: UsageRow[] = [{ name: '--quiet', alias: '-q', hidden: true, boolean: true }]
if (!usage || !usage.noHelp) {
// usage might tell us not to add help, or not to add the -h help alias
const help: { name: string; hidden: boolean; boolean: boolean; alias?: string } = {
name: '--help',
hidden: true,
boolean: true
}
if (!usage || !usage.noHelpAlias) {
help.alias = '-h'
}
builtInOptions.push(help)
}
// here, we encode some common aliases, and then overlay any flags from the command
// narg: any flags that take more than one argument e.g. -p key value would have { narg: { p: 2 } }
const commandFlags: YargsParserFlags =
(evaluator.options && evaluator.options.flags) ||
(evaluator.options &&
evaluator.options.synonymFor &&
evaluator.options.synonymFor.options &&
evaluator.options.synonymFor.options.flags) ||
({} as YargsParserFlags)
const optional = builtInOptions.concat(
(evaluator.options && evaluator.options.usage && evaluator.options.usage.optional) || []
)
const optionalBooleans = optional && optional.filter(({ boolean }) => boolean).map(_ => unflag(_.name))
interface CanonicalArgs {
[key: string]: string
}
const optionalAliases =
optional &&
optional
.filter(({ alias }) => alias)
.reduce((M: CanonicalArgs, { name, alias }) => {
M[unflag(alias)] = unflag(name)
return M
}, {})
const allFlags = {
configuration: Object.assign(
{ 'camel-case-expansion': false },
(evaluator.options && evaluator.options.flags && evaluator.options.flags.configuration) ||
(usage && usage.configuration) ||
{}
),
string: commandFlags.string || [],
array: commandFlags.array || [],
boolean: (commandFlags.boolean || []).concat(optionalBooleans || []),
alias: Object.assign({}, commandFlags.alias || {}, optionalAliases || {}),
narg: Object.assign(
{},
commandFlags.narg || {}, // narg from registrar.listen(route, handler, { flags: { narg: ... }})
(optional &&
optional.reduce((N, { name, alias, narg }) => {
// narg from listen(route, handler, { usage: { optional: [...] }})
if (narg) {
N[unflag(name)] = narg
N[unflag(alias)] = narg
}
return N
}, {} as Record<string, number>)) ||
{}
)
}
const parsedOptions = (minimist(argv, allFlags) as any) as O
const argvNoOptions: string[] = parsedOptions._
return { argvNoOptions, parsedOptions }
}
private async execUnsafe<T extends KResponse, O extends ParsedOptions>(
commandUntrimmed: string,
execOptions = emptyExecOptions()
): Promise<T | CodedError<number> | HTMLElement | MixedResponse | CommandEvaluationError> {
const startTime = Date.now()
const tab = execOptions.tab || getCurrentTab()
const execType = (execOptions && execOptions.type) || ExecType.TopLevel
const REPL = tab.REPL || getImpl(tab)
// trim suffix comments, e.g. "kubectl get pods # comments start here"
// insert whitespace for whitespace-free prefix comments, e.g. "#comments" -> "# comments"
let command = (commandUntrimmed || '')
.trim()
.replace(patterns.suffixComments, '$1')
.replace(patterns.prefixComments, '# $1')
const argv = split(command)
// pipeline splits, e.g. if command='a b|c', the pipeStages=[['a','b'],'c']
const pipeStages = splitIntoPipeStages(command)
// debug('command', commandUntrimmed)
const evaluator = await lookupCommandEvaluator<T, O>(argv, execOptions)
if (isSuccessfulCommandResolution(evaluator)) {
// If core handles redirect, argv and command shouldn't contain the redirect part;
// otherwise, controllers may use argv and command incorrectly e.g. kuiecho hi > file will print "hi > file" instead of "hi"
const noCoreRedirect = execOptions.noCoreRedirect || (evaluator.options && evaluator.options.noCoreRedirect)
// are we asked to redirect the output to a file?
let redirectDesired = !noCoreRedirect && !!pipeStages.redirect && !/\/dev/.test(pipeStages.redirect)
const originalCommand = command
if (redirectDesired && pipeStages.redirect) {
argv.splice(argv.indexOf(pipeStages.redirector), 2)
command = command.replace(new RegExp(`\\s*${pipeStages.redirector}\\s*${pipeStages.redirect}\\s*$`), '')
}
const { argvNoOptions, parsedOptions } = this.parseOptions(argv, evaluator)
if (evaluator.options && evaluator.options.requiresLocal && !hasLocalAccess()) {
debug('command does not work in a browser', originalCommand)
const err = new Error('Command requires local access') as CommandEvaluationError
err.code = 406 // http not acceptable
err.kind = 'commandresolution'
return err
}
// if we don't have a head (yet), but this command requires one,
// then ask for a head and try again. note that we ignore this
// needsUI constraint if the user is asking for help
if (
isHeadless() &&
!parsedOptions.cli &&
!(parsedOptions.h || parsedOptions.help) &&
((process.env.DEFAULT_TO_UI && !parsedOptions.cli) || (evaluator.options && evaluator.options.needsUI))
) {
import('../main/headless').then(({ createWindow }) =>
createWindow(argv, evaluator.options.fullscreen, evaluator.options, true)
)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (true as any) as T
}
const execUUID = execOptions.execUUID || uuid()
execOptions.execUUID = execUUID
const evaluatorOptions = evaluator.options
this.emitStartEvent({
tab,
route: evaluator.route,
startTime,
command: commandUntrimmed,
redirectDesired,
pipeStages,
evaluatorOptions,
execType,
execUUID,
execOptions,
echo: execOptions.echo
})
if (command.length === 0) {
// blank line (after stripping off comments)
this.emitCompletionEvent(true, {
tab,
execType,
completeTime: Date.now(),
command: commandUntrimmed,
argvNoOptions,
parsedOptions,
pipeStages,
execOptions,
execUUID,
cancelled: true,
echo: execOptions.echo,
evaluatorOptions
})
return
}
const historyIdx = isHeadless() ? -1 : this.pushHistory(originalCommand, execOptions, tab)
try {
if (!/(&&|\|\|)/.test(commandUntrimmed)) {
enforceUsage(argv, evaluator, execOptions)
}
} catch (err) {
debug('usage enforcement failure', err, execType === ExecType.Nested)
this.emitCompletionEvent(
err,
{
tab,
execType,
completeTime: Date.now(),
command: commandUntrimmed,
argvNoOptions,
parsedOptions,
pipeStages,
execOptions,
cancelled: false,
echo: execOptions.echo,
execUUID,
evaluatorOptions
},
historyIdx || -1
)
if (execOptions.type === ExecType.Nested) {
throw err
} else {
return
}
}
this.loadSymbolTable(tab, execOptions)
const args: Arguments<O> = {
tab,
REPL,
block: execOptions.block,
nextBlock: undefined,
argv,
command,
execOptions,
argvNoOptions,
pipeStages,
parsedOptions: parsedOptions as O,
createErrorStream: execOptions.createErrorStream || (() => this.makeStream(getTabId(tab), execUUID, 'stderr')),
createOutputStream: execOptions.createOutputStream || (() => this.makeStream(getTabId(tab), execUUID, 'stdout'))
}
// COMMAND EXECUTION ABOUT TO COMMENCE. This is where we
// actually execute the command line and populate this
// `response` variable:
let response: T | Promise<T> | MixedResponse
const commands = evaluatorOptions.semiExpand === false ? [] : semiSplit(command)
if (commands.length > 1) {
// e.g. "a ; b ; c"
response = await semicolonInvoke(commands, execOptions)
redirectDesired = false // any redirects will be handled in the respective semi invoke
} else {
// e.g. just "a" or "a > /tmp/foo"
try {
response = await Promise.resolve(
currentEvaluatorImpl.apply<T, O>(commandUntrimmed, execOptions, evaluator, args)
).then(response => {
// indicate that the command was successfuly completed
evaluator.success({
tab,
type: (execOptions && execOptions.type) || ExecType.TopLevel,
isDrilldown: execOptions.isDrilldown,
command,
parsedOptions
})
return response
})
} catch (err) {
debugCommandErrors(err)
evaluator.error(command, tab, execType, err)
if (execType === ExecType.Nested || execOptions.rethrowErrors) {
throw err
}
response = err
}
if (evaluator.options.viewTransformer && execType !== ExecType.Nested) {
response = await Promise.resolve(response)
.then(async _ => {
const maybeAView = await evaluator.options.viewTransformer(args, _)
return maybeAView || _
})
.catch(err => {
// view transformer failed; treat this as the response to the user
return err
})
}
// the || true part is a safeguard for cases where typescript
// didn't catch a command handler returning nothing; it
// shouldn't happen, but probably isn't a sign of a dire
// problem. issue a debug warning, in any case
if (!response) {
debug('warning: command handler returned nothing', commandUntrimmed)
}
}
// Here is where we handle redirecting the response to a file
if (redirectDesired && !isError(await response)) {
try {
await redirectResponse(response, pipeStages.redirect, pipeStages.redirector)
// mimic "no response", now that we've successfully
// redirected the response to a file
response = true as T
} catch (err) {
response = err
}
}
this.emitCompletionEvent(
response || true,
{
tab,
execType,
completeTime: Date.now(),
command: commandUntrimmed,
argvNoOptions,
parsedOptions,
pipeStages,
execUUID,
cancelled: false,
echo: execOptions.echo,
evaluatorOptions,
execOptions
},
historyIdx || -1
)
return response
} else {
const err = new Error('Command not found') as CommandEvaluationError
err.code = 404 // http not acceptable
err.kind = 'commandresolution'
return err
}
}
public async exec<T extends KResponse, O extends ParsedOptions>(
commandUntrimmed: string,
execOptions = emptyExecOptions()
): Promise<T | CodedError<number> | HTMLElement | MixedResponse | CommandEvaluationError> {
try {
return await this.execUnsafe(commandUntrimmed, execOptions)
} catch (err) {
if (execOptions.type !== ExecType.Nested && !execOptions.rethrowErrors) {
console.error('Internal Error: uncaught exception in exec', err)
return err
} else {
throw err
}
}
}
private async makeStream(tabUUID: string, execUUID: string, which: 'stdout' | 'stderr'): Promise<Stream> {
if (isHeadless()) {
const { streamTo: headlessStreamTo } = await import('../main/headless-support')
return headlessStreamTo(which)
} else {
const stream = (response: Streamable) =>
new Promise<void>(resolve => {
eventChannelUnsafe.once(`/command/stdout/done/${tabUUID}/${execUUID}`, () => {
resolve()
})
eventChannelUnsafe.emit(`/command/stdout/${tabUUID}/${execUUID}`, response)
})
return Promise.resolve(stream)
}
}
} /* InProcessExecutor */
/**
* Execute the given command-line. This function operates by
* delegation to the IExecutor impl.
*
*/
let currentExecutorImpl: Executor = new InProcessExecutor()
export const exec = (commandUntrimmed: string, execOptions = emptyExecOptions()) => {
return currentExecutorImpl.exec(commandUntrimmed, execOptions)
}
/**
* User hit enter in the REPL
*
* @param execUUID for command re-execution
*
*/
export const doEval = (_tab: Tab, block: Block, command: string, execUUID?: string) => {
const tab = splitFor(_tab)
const defaultExecOptions = new DefaultExecOptionsForTab(tab, block, execUUID)
const execOptions: ExecOptions = !execUUID
? defaultExecOptions
: Object.assign(defaultExecOptions, { type: ExecType.Rerun })
return exec(command, execOptions)
}
/**
* If, while evaluating a command, it needs to evaluate a sub-command...
*
*/
export const qexec = <T extends KResponse>(
command: string,
block?: HTMLElement | boolean,
contextChangeOK?: boolean,
execOptions?: ExecOptions,
nextBlock?: HTMLElement
): Promise<T> => {
return exec(
command,
Object.assign(
{
block,
nextBlock,
noHistory: true,
contextChangeOK
},
execOptions,
{
type: ExecType.Nested
}
)
) as Promise<T>
}
export const qfexec = (
command: string,
block?: HTMLElement,
nextBlock?: HTMLElement,
execOptions?: ExecOptions
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): Promise<any> => {
// context change ok, final exec in a chain of nested execs
return qexec(command, block, true, execOptions, nextBlock)
}
/**
* "raw" exec, where we want the data model back directly
*
*/
export const rexec = async <Raw extends RawContent>(
command: string,
execOptions = emptyExecOptions()
): Promise<RawResponse<Raw>> => {
const content = await qexec<Raw | RawResponse<Raw>>(
command,
undefined,
undefined,
Object.assign({ raw: true }, execOptions)
)
if (isRawResponse(content)) {
return content
} else {
// bad actors may return a string; adapt this to RawResponse
return {
mode: 'raw',
content
}
}
}
/**
* Evaluate a command and place the result in the current active view for the given tab
*
*/
export const reexec = <T extends KResponse>(command: string, execOptions: ExecOptionsWithUUID): Promise<T> => {
return exec(command, Object.assign({ echo: true, type: ExecType.Rerun }, execOptions)) as Promise<T>
}
/**
* Programmatic exec, as opposed to human typing and hitting enter
*
*/
export const pexec = <T extends KResponse>(command: string, execOptions?: ExecOptions): Promise<T> => {
return exec(command, Object.assign({ echo: true, type: ExecType.ClickHandler }, execOptions)) as Promise<T>
}
/**
* Execute a command in response to an in-view click
*
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars,@typescript-eslint/no-empty-function
export async function click(command: string | (() => Promise<string>), evt: MouseEvent): Promise<void> {}
/**
* Update the executor impl
*
*/
export const setExecutorImpl = (impl: Executor): void => {
currentExecutorImpl = impl
}
/**
* If the command is semicolon-separated, invoke each element of the
* split separately
*
*/
async function semicolonInvoke(commands: string[], execOptions: ExecOptions): Promise<MixedResponse> {
debug('semicolonInvoke', commands)
const nonEmptyCommands = commands.filter(_ => _)
const result: MixedResponse = await promiseEach(nonEmptyCommands, async command => {
try {
const entity = await qexec<MixedResponsePart | true>(
command,
undefined,
undefined,
Object.assign({}, execOptions, { quiet: false, /* block, */ execUUID: execOptions.execUUID })
)
if (entity === true) {
// pty output
return ''
} else {
return entity
}
} catch (err) {
return err
}
})
return result
}
/**
* @return an instance that obeys the REPL interface
*
*/
export function getImpl(tab: Tab): REPL {
const impl = { qexec, rexec, pexec, reexec, click, encodeComponent, split } as REPL
tab.REPL = impl
return impl
}
/**
* redirect a string response
*
*/
async function redirectResponse<T extends KResponse>(
_response: MixedResponse | T | Promise<T>,
filepath: string,
redirector: CommandLine['pipeStages']['redirector']
) {
const response = await _response
if (response === true) {
// probably a mis-parsing of the redirect
} else if (Buffer.isBuffer(response) || typeof response === 'string' || isXtermResponse(response)) {
try {
const data = isXtermResponse(response) ? response.rows.map(i => i.map(j => j.innerText)).join(' ') : response
const writeOptions = redirector === '>>' ? '--append' : ''
await rexec<{ data: string }>(`vfs fwrite ${encodeComponent(expandHomeDir(filepath))} ${writeOptions}`, { data })
debug(`redirected response to ${filepath}`, response)
} catch (err) {
console.error(err)
throw new Error(`Error in redirect: ${err.message}`)
}
} else {
debug('Unsupported redirect response', response)
throw new Error('Error: unsupported redirect response')
}
} | the_stack |
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types";
import {
CloneReceiptRuleSetCommand,
CloneReceiptRuleSetCommandInput,
CloneReceiptRuleSetCommandOutput,
} from "./commands/CloneReceiptRuleSetCommand";
import {
CreateConfigurationSetCommand,
CreateConfigurationSetCommandInput,
CreateConfigurationSetCommandOutput,
} from "./commands/CreateConfigurationSetCommand";
import {
CreateConfigurationSetEventDestinationCommand,
CreateConfigurationSetEventDestinationCommandInput,
CreateConfigurationSetEventDestinationCommandOutput,
} from "./commands/CreateConfigurationSetEventDestinationCommand";
import {
CreateConfigurationSetTrackingOptionsCommand,
CreateConfigurationSetTrackingOptionsCommandInput,
CreateConfigurationSetTrackingOptionsCommandOutput,
} from "./commands/CreateConfigurationSetTrackingOptionsCommand";
import {
CreateCustomVerificationEmailTemplateCommand,
CreateCustomVerificationEmailTemplateCommandInput,
CreateCustomVerificationEmailTemplateCommandOutput,
} from "./commands/CreateCustomVerificationEmailTemplateCommand";
import {
CreateReceiptFilterCommand,
CreateReceiptFilterCommandInput,
CreateReceiptFilterCommandOutput,
} from "./commands/CreateReceiptFilterCommand";
import {
CreateReceiptRuleCommand,
CreateReceiptRuleCommandInput,
CreateReceiptRuleCommandOutput,
} from "./commands/CreateReceiptRuleCommand";
import {
CreateReceiptRuleSetCommand,
CreateReceiptRuleSetCommandInput,
CreateReceiptRuleSetCommandOutput,
} from "./commands/CreateReceiptRuleSetCommand";
import {
CreateTemplateCommand,
CreateTemplateCommandInput,
CreateTemplateCommandOutput,
} from "./commands/CreateTemplateCommand";
import {
DeleteConfigurationSetCommand,
DeleteConfigurationSetCommandInput,
DeleteConfigurationSetCommandOutput,
} from "./commands/DeleteConfigurationSetCommand";
import {
DeleteConfigurationSetEventDestinationCommand,
DeleteConfigurationSetEventDestinationCommandInput,
DeleteConfigurationSetEventDestinationCommandOutput,
} from "./commands/DeleteConfigurationSetEventDestinationCommand";
import {
DeleteConfigurationSetTrackingOptionsCommand,
DeleteConfigurationSetTrackingOptionsCommandInput,
DeleteConfigurationSetTrackingOptionsCommandOutput,
} from "./commands/DeleteConfigurationSetTrackingOptionsCommand";
import {
DeleteCustomVerificationEmailTemplateCommand,
DeleteCustomVerificationEmailTemplateCommandInput,
DeleteCustomVerificationEmailTemplateCommandOutput,
} from "./commands/DeleteCustomVerificationEmailTemplateCommand";
import {
DeleteIdentityCommand,
DeleteIdentityCommandInput,
DeleteIdentityCommandOutput,
} from "./commands/DeleteIdentityCommand";
import {
DeleteIdentityPolicyCommand,
DeleteIdentityPolicyCommandInput,
DeleteIdentityPolicyCommandOutput,
} from "./commands/DeleteIdentityPolicyCommand";
import {
DeleteReceiptFilterCommand,
DeleteReceiptFilterCommandInput,
DeleteReceiptFilterCommandOutput,
} from "./commands/DeleteReceiptFilterCommand";
import {
DeleteReceiptRuleCommand,
DeleteReceiptRuleCommandInput,
DeleteReceiptRuleCommandOutput,
} from "./commands/DeleteReceiptRuleCommand";
import {
DeleteReceiptRuleSetCommand,
DeleteReceiptRuleSetCommandInput,
DeleteReceiptRuleSetCommandOutput,
} from "./commands/DeleteReceiptRuleSetCommand";
import {
DeleteTemplateCommand,
DeleteTemplateCommandInput,
DeleteTemplateCommandOutput,
} from "./commands/DeleteTemplateCommand";
import {
DeleteVerifiedEmailAddressCommand,
DeleteVerifiedEmailAddressCommandInput,
DeleteVerifiedEmailAddressCommandOutput,
} from "./commands/DeleteVerifiedEmailAddressCommand";
import {
DescribeActiveReceiptRuleSetCommand,
DescribeActiveReceiptRuleSetCommandInput,
DescribeActiveReceiptRuleSetCommandOutput,
} from "./commands/DescribeActiveReceiptRuleSetCommand";
import {
DescribeConfigurationSetCommand,
DescribeConfigurationSetCommandInput,
DescribeConfigurationSetCommandOutput,
} from "./commands/DescribeConfigurationSetCommand";
import {
DescribeReceiptRuleCommand,
DescribeReceiptRuleCommandInput,
DescribeReceiptRuleCommandOutput,
} from "./commands/DescribeReceiptRuleCommand";
import {
DescribeReceiptRuleSetCommand,
DescribeReceiptRuleSetCommandInput,
DescribeReceiptRuleSetCommandOutput,
} from "./commands/DescribeReceiptRuleSetCommand";
import {
GetAccountSendingEnabledCommand,
GetAccountSendingEnabledCommandInput,
GetAccountSendingEnabledCommandOutput,
} from "./commands/GetAccountSendingEnabledCommand";
import {
GetCustomVerificationEmailTemplateCommand,
GetCustomVerificationEmailTemplateCommandInput,
GetCustomVerificationEmailTemplateCommandOutput,
} from "./commands/GetCustomVerificationEmailTemplateCommand";
import {
GetIdentityDkimAttributesCommand,
GetIdentityDkimAttributesCommandInput,
GetIdentityDkimAttributesCommandOutput,
} from "./commands/GetIdentityDkimAttributesCommand";
import {
GetIdentityMailFromDomainAttributesCommand,
GetIdentityMailFromDomainAttributesCommandInput,
GetIdentityMailFromDomainAttributesCommandOutput,
} from "./commands/GetIdentityMailFromDomainAttributesCommand";
import {
GetIdentityNotificationAttributesCommand,
GetIdentityNotificationAttributesCommandInput,
GetIdentityNotificationAttributesCommandOutput,
} from "./commands/GetIdentityNotificationAttributesCommand";
import {
GetIdentityPoliciesCommand,
GetIdentityPoliciesCommandInput,
GetIdentityPoliciesCommandOutput,
} from "./commands/GetIdentityPoliciesCommand";
import {
GetIdentityVerificationAttributesCommand,
GetIdentityVerificationAttributesCommandInput,
GetIdentityVerificationAttributesCommandOutput,
} from "./commands/GetIdentityVerificationAttributesCommand";
import {
GetSendQuotaCommand,
GetSendQuotaCommandInput,
GetSendQuotaCommandOutput,
} from "./commands/GetSendQuotaCommand";
import {
GetSendStatisticsCommand,
GetSendStatisticsCommandInput,
GetSendStatisticsCommandOutput,
} from "./commands/GetSendStatisticsCommand";
import { GetTemplateCommand, GetTemplateCommandInput, GetTemplateCommandOutput } from "./commands/GetTemplateCommand";
import {
ListConfigurationSetsCommand,
ListConfigurationSetsCommandInput,
ListConfigurationSetsCommandOutput,
} from "./commands/ListConfigurationSetsCommand";
import {
ListCustomVerificationEmailTemplatesCommand,
ListCustomVerificationEmailTemplatesCommandInput,
ListCustomVerificationEmailTemplatesCommandOutput,
} from "./commands/ListCustomVerificationEmailTemplatesCommand";
import {
ListIdentitiesCommand,
ListIdentitiesCommandInput,
ListIdentitiesCommandOutput,
} from "./commands/ListIdentitiesCommand";
import {
ListIdentityPoliciesCommand,
ListIdentityPoliciesCommandInput,
ListIdentityPoliciesCommandOutput,
} from "./commands/ListIdentityPoliciesCommand";
import {
ListReceiptFiltersCommand,
ListReceiptFiltersCommandInput,
ListReceiptFiltersCommandOutput,
} from "./commands/ListReceiptFiltersCommand";
import {
ListReceiptRuleSetsCommand,
ListReceiptRuleSetsCommandInput,
ListReceiptRuleSetsCommandOutput,
} from "./commands/ListReceiptRuleSetsCommand";
import {
ListTemplatesCommand,
ListTemplatesCommandInput,
ListTemplatesCommandOutput,
} from "./commands/ListTemplatesCommand";
import {
ListVerifiedEmailAddressesCommand,
ListVerifiedEmailAddressesCommandInput,
ListVerifiedEmailAddressesCommandOutput,
} from "./commands/ListVerifiedEmailAddressesCommand";
import {
PutConfigurationSetDeliveryOptionsCommand,
PutConfigurationSetDeliveryOptionsCommandInput,
PutConfigurationSetDeliveryOptionsCommandOutput,
} from "./commands/PutConfigurationSetDeliveryOptionsCommand";
import {
PutIdentityPolicyCommand,
PutIdentityPolicyCommandInput,
PutIdentityPolicyCommandOutput,
} from "./commands/PutIdentityPolicyCommand";
import {
ReorderReceiptRuleSetCommand,
ReorderReceiptRuleSetCommandInput,
ReorderReceiptRuleSetCommandOutput,
} from "./commands/ReorderReceiptRuleSetCommand";
import { SendBounceCommand, SendBounceCommandInput, SendBounceCommandOutput } from "./commands/SendBounceCommand";
import {
SendBulkTemplatedEmailCommand,
SendBulkTemplatedEmailCommandInput,
SendBulkTemplatedEmailCommandOutput,
} from "./commands/SendBulkTemplatedEmailCommand";
import {
SendCustomVerificationEmailCommand,
SendCustomVerificationEmailCommandInput,
SendCustomVerificationEmailCommandOutput,
} from "./commands/SendCustomVerificationEmailCommand";
import { SendEmailCommand, SendEmailCommandInput, SendEmailCommandOutput } from "./commands/SendEmailCommand";
import {
SendRawEmailCommand,
SendRawEmailCommandInput,
SendRawEmailCommandOutput,
} from "./commands/SendRawEmailCommand";
import {
SendTemplatedEmailCommand,
SendTemplatedEmailCommandInput,
SendTemplatedEmailCommandOutput,
} from "./commands/SendTemplatedEmailCommand";
import {
SetActiveReceiptRuleSetCommand,
SetActiveReceiptRuleSetCommandInput,
SetActiveReceiptRuleSetCommandOutput,
} from "./commands/SetActiveReceiptRuleSetCommand";
import {
SetIdentityDkimEnabledCommand,
SetIdentityDkimEnabledCommandInput,
SetIdentityDkimEnabledCommandOutput,
} from "./commands/SetIdentityDkimEnabledCommand";
import {
SetIdentityFeedbackForwardingEnabledCommand,
SetIdentityFeedbackForwardingEnabledCommandInput,
SetIdentityFeedbackForwardingEnabledCommandOutput,
} from "./commands/SetIdentityFeedbackForwardingEnabledCommand";
import {
SetIdentityHeadersInNotificationsEnabledCommand,
SetIdentityHeadersInNotificationsEnabledCommandInput,
SetIdentityHeadersInNotificationsEnabledCommandOutput,
} from "./commands/SetIdentityHeadersInNotificationsEnabledCommand";
import {
SetIdentityMailFromDomainCommand,
SetIdentityMailFromDomainCommandInput,
SetIdentityMailFromDomainCommandOutput,
} from "./commands/SetIdentityMailFromDomainCommand";
import {
SetIdentityNotificationTopicCommand,
SetIdentityNotificationTopicCommandInput,
SetIdentityNotificationTopicCommandOutput,
} from "./commands/SetIdentityNotificationTopicCommand";
import {
SetReceiptRulePositionCommand,
SetReceiptRulePositionCommandInput,
SetReceiptRulePositionCommandOutput,
} from "./commands/SetReceiptRulePositionCommand";
import {
TestRenderTemplateCommand,
TestRenderTemplateCommandInput,
TestRenderTemplateCommandOutput,
} from "./commands/TestRenderTemplateCommand";
import {
UpdateAccountSendingEnabledCommand,
UpdateAccountSendingEnabledCommandInput,
UpdateAccountSendingEnabledCommandOutput,
} from "./commands/UpdateAccountSendingEnabledCommand";
import {
UpdateConfigurationSetEventDestinationCommand,
UpdateConfigurationSetEventDestinationCommandInput,
UpdateConfigurationSetEventDestinationCommandOutput,
} from "./commands/UpdateConfigurationSetEventDestinationCommand";
import {
UpdateConfigurationSetReputationMetricsEnabledCommand,
UpdateConfigurationSetReputationMetricsEnabledCommandInput,
UpdateConfigurationSetReputationMetricsEnabledCommandOutput,
} from "./commands/UpdateConfigurationSetReputationMetricsEnabledCommand";
import {
UpdateConfigurationSetSendingEnabledCommand,
UpdateConfigurationSetSendingEnabledCommandInput,
UpdateConfigurationSetSendingEnabledCommandOutput,
} from "./commands/UpdateConfigurationSetSendingEnabledCommand";
import {
UpdateConfigurationSetTrackingOptionsCommand,
UpdateConfigurationSetTrackingOptionsCommandInput,
UpdateConfigurationSetTrackingOptionsCommandOutput,
} from "./commands/UpdateConfigurationSetTrackingOptionsCommand";
import {
UpdateCustomVerificationEmailTemplateCommand,
UpdateCustomVerificationEmailTemplateCommandInput,
UpdateCustomVerificationEmailTemplateCommandOutput,
} from "./commands/UpdateCustomVerificationEmailTemplateCommand";
import {
UpdateReceiptRuleCommand,
UpdateReceiptRuleCommandInput,
UpdateReceiptRuleCommandOutput,
} from "./commands/UpdateReceiptRuleCommand";
import {
UpdateTemplateCommand,
UpdateTemplateCommandInput,
UpdateTemplateCommandOutput,
} from "./commands/UpdateTemplateCommand";
import {
VerifyDomainDkimCommand,
VerifyDomainDkimCommandInput,
VerifyDomainDkimCommandOutput,
} from "./commands/VerifyDomainDkimCommand";
import {
VerifyDomainIdentityCommand,
VerifyDomainIdentityCommandInput,
VerifyDomainIdentityCommandOutput,
} from "./commands/VerifyDomainIdentityCommand";
import {
VerifyEmailAddressCommand,
VerifyEmailAddressCommandInput,
VerifyEmailAddressCommandOutput,
} from "./commands/VerifyEmailAddressCommand";
import {
VerifyEmailIdentityCommand,
VerifyEmailIdentityCommandInput,
VerifyEmailIdentityCommandOutput,
} from "./commands/VerifyEmailIdentityCommand";
import { SESClient } from "./SESClient";
/**
* <fullname>Amazon Simple Email Service</fullname>
* <p> This document contains reference information for the <a href="https://aws.amazon.com/ses/">Amazon Simple Email Service</a> (Amazon SES) API, version
* 2010-12-01. This document is best used in conjunction with the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/Welcome.html">Amazon SES Developer
* Guide</a>. </p>
* <note>
* <p> For a list of Amazon SES endpoints to use in service requests, see <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/regions.html">Regions and
* Amazon SES</a> in the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/Welcome.html">Amazon SES Developer
* Guide</a>.</p>
* </note>
*/
export class SES extends SESClient {
/**
* <p>Creates a receipt rule set by cloning an existing one. All receipt rules and
* configurations are copied to the new receipt rule set and are completely independent of
* the source rule set.</p>
* <p>For information about setting up rule sets, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-receipt-rule-set.html">Amazon SES
* Developer Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public cloneReceiptRuleSet(
args: CloneReceiptRuleSetCommandInput,
options?: __HttpHandlerOptions
): Promise<CloneReceiptRuleSetCommandOutput>;
public cloneReceiptRuleSet(
args: CloneReceiptRuleSetCommandInput,
cb: (err: any, data?: CloneReceiptRuleSetCommandOutput) => void
): void;
public cloneReceiptRuleSet(
args: CloneReceiptRuleSetCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CloneReceiptRuleSetCommandOutput) => void
): void;
public cloneReceiptRuleSet(
args: CloneReceiptRuleSetCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CloneReceiptRuleSetCommandOutput) => void),
cb?: (err: any, data?: CloneReceiptRuleSetCommandOutput) => void
): Promise<CloneReceiptRuleSetCommandOutput> | void {
const command = new CloneReceiptRuleSetCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Creates a configuration set.</p>
* <p>Configuration sets enable you to publish email sending events. For information about
* using configuration sets, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/monitor-sending-activity.html">Amazon SES Developer
* Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public createConfigurationSet(
args: CreateConfigurationSetCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateConfigurationSetCommandOutput>;
public createConfigurationSet(
args: CreateConfigurationSetCommandInput,
cb: (err: any, data?: CreateConfigurationSetCommandOutput) => void
): void;
public createConfigurationSet(
args: CreateConfigurationSetCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateConfigurationSetCommandOutput) => void
): void;
public createConfigurationSet(
args: CreateConfigurationSetCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateConfigurationSetCommandOutput) => void),
cb?: (err: any, data?: CreateConfigurationSetCommandOutput) => void
): Promise<CreateConfigurationSetCommandOutput> | void {
const command = new CreateConfigurationSetCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Creates a configuration set event destination.</p>
* <note>
* <p>When you create or update an event destination, you must provide one, and only
* one, destination. The destination can be CloudWatch, Amazon Kinesis Firehose, or Amazon Simple Notification Service (Amazon SNS).</p>
* </note>
* <p>An event destination is the AWS service to which Amazon SES publishes the email sending
* events associated with a configuration set. For information about using configuration
* sets, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/monitor-sending-activity.html">Amazon SES Developer
* Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public createConfigurationSetEventDestination(
args: CreateConfigurationSetEventDestinationCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateConfigurationSetEventDestinationCommandOutput>;
public createConfigurationSetEventDestination(
args: CreateConfigurationSetEventDestinationCommandInput,
cb: (err: any, data?: CreateConfigurationSetEventDestinationCommandOutput) => void
): void;
public createConfigurationSetEventDestination(
args: CreateConfigurationSetEventDestinationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateConfigurationSetEventDestinationCommandOutput) => void
): void;
public createConfigurationSetEventDestination(
args: CreateConfigurationSetEventDestinationCommandInput,
optionsOrCb?:
| __HttpHandlerOptions
| ((err: any, data?: CreateConfigurationSetEventDestinationCommandOutput) => void),
cb?: (err: any, data?: CreateConfigurationSetEventDestinationCommandOutput) => void
): Promise<CreateConfigurationSetEventDestinationCommandOutput> | void {
const command = new CreateConfigurationSetEventDestinationCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Creates an association between a configuration set and a custom domain for open and
* click event tracking. </p>
* <p>By default, images and links used for tracking open and click events are hosted on
* domains operated by Amazon SES. You can configure a subdomain of your own to handle these
* events. For information about using custom domains, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/configure-custom-open-click-domains.html">Amazon SES Developer Guide</a>.</p>
*/
public createConfigurationSetTrackingOptions(
args: CreateConfigurationSetTrackingOptionsCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateConfigurationSetTrackingOptionsCommandOutput>;
public createConfigurationSetTrackingOptions(
args: CreateConfigurationSetTrackingOptionsCommandInput,
cb: (err: any, data?: CreateConfigurationSetTrackingOptionsCommandOutput) => void
): void;
public createConfigurationSetTrackingOptions(
args: CreateConfigurationSetTrackingOptionsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateConfigurationSetTrackingOptionsCommandOutput) => void
): void;
public createConfigurationSetTrackingOptions(
args: CreateConfigurationSetTrackingOptionsCommandInput,
optionsOrCb?:
| __HttpHandlerOptions
| ((err: any, data?: CreateConfigurationSetTrackingOptionsCommandOutput) => void),
cb?: (err: any, data?: CreateConfigurationSetTrackingOptionsCommandOutput) => void
): Promise<CreateConfigurationSetTrackingOptionsCommandOutput> | void {
const command = new CreateConfigurationSetTrackingOptionsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Creates a new custom verification email template.</p>
* <p>For more information about custom verification email templates, see <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/custom-verification-emails.html">Using Custom Verification Email Templates</a> in the <i>Amazon SES Developer
* Guide</i>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public createCustomVerificationEmailTemplate(
args: CreateCustomVerificationEmailTemplateCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateCustomVerificationEmailTemplateCommandOutput>;
public createCustomVerificationEmailTemplate(
args: CreateCustomVerificationEmailTemplateCommandInput,
cb: (err: any, data?: CreateCustomVerificationEmailTemplateCommandOutput) => void
): void;
public createCustomVerificationEmailTemplate(
args: CreateCustomVerificationEmailTemplateCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateCustomVerificationEmailTemplateCommandOutput) => void
): void;
public createCustomVerificationEmailTemplate(
args: CreateCustomVerificationEmailTemplateCommandInput,
optionsOrCb?:
| __HttpHandlerOptions
| ((err: any, data?: CreateCustomVerificationEmailTemplateCommandOutput) => void),
cb?: (err: any, data?: CreateCustomVerificationEmailTemplateCommandOutput) => void
): Promise<CreateCustomVerificationEmailTemplateCommandOutput> | void {
const command = new CreateCustomVerificationEmailTemplateCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Creates a new IP address filter.</p>
* <p>For information about setting up IP address filters, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-ip-filters.html">Amazon SES Developer Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public createReceiptFilter(
args: CreateReceiptFilterCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateReceiptFilterCommandOutput>;
public createReceiptFilter(
args: CreateReceiptFilterCommandInput,
cb: (err: any, data?: CreateReceiptFilterCommandOutput) => void
): void;
public createReceiptFilter(
args: CreateReceiptFilterCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateReceiptFilterCommandOutput) => void
): void;
public createReceiptFilter(
args: CreateReceiptFilterCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateReceiptFilterCommandOutput) => void),
cb?: (err: any, data?: CreateReceiptFilterCommandOutput) => void
): Promise<CreateReceiptFilterCommandOutput> | void {
const command = new CreateReceiptFilterCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Creates a receipt rule.</p>
* <p>For information about setting up receipt rules, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-receipt-rules.html">Amazon SES Developer
* Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public createReceiptRule(
args: CreateReceiptRuleCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateReceiptRuleCommandOutput>;
public createReceiptRule(
args: CreateReceiptRuleCommandInput,
cb: (err: any, data?: CreateReceiptRuleCommandOutput) => void
): void;
public createReceiptRule(
args: CreateReceiptRuleCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateReceiptRuleCommandOutput) => void
): void;
public createReceiptRule(
args: CreateReceiptRuleCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateReceiptRuleCommandOutput) => void),
cb?: (err: any, data?: CreateReceiptRuleCommandOutput) => void
): Promise<CreateReceiptRuleCommandOutput> | void {
const command = new CreateReceiptRuleCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Creates an empty receipt rule set.</p>
* <p>For information about setting up receipt rule sets, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-receipt-rule-set.html">Amazon SES
* Developer Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public createReceiptRuleSet(
args: CreateReceiptRuleSetCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateReceiptRuleSetCommandOutput>;
public createReceiptRuleSet(
args: CreateReceiptRuleSetCommandInput,
cb: (err: any, data?: CreateReceiptRuleSetCommandOutput) => void
): void;
public createReceiptRuleSet(
args: CreateReceiptRuleSetCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateReceiptRuleSetCommandOutput) => void
): void;
public createReceiptRuleSet(
args: CreateReceiptRuleSetCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateReceiptRuleSetCommandOutput) => void),
cb?: (err: any, data?: CreateReceiptRuleSetCommandOutput) => void
): Promise<CreateReceiptRuleSetCommandOutput> | void {
const command = new CreateReceiptRuleSetCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Creates an email template. Email templates enable you to send personalized email to
* one or more destinations in a single API operation. For more information, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-personalized-email-api.html">Amazon SES Developer
* Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public createTemplate(
args: CreateTemplateCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateTemplateCommandOutput>;
public createTemplate(
args: CreateTemplateCommandInput,
cb: (err: any, data?: CreateTemplateCommandOutput) => void
): void;
public createTemplate(
args: CreateTemplateCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateTemplateCommandOutput) => void
): void;
public createTemplate(
args: CreateTemplateCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateTemplateCommandOutput) => void),
cb?: (err: any, data?: CreateTemplateCommandOutput) => void
): Promise<CreateTemplateCommandOutput> | void {
const command = new CreateTemplateCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes a configuration set. Configuration sets enable you to publish email sending
* events. For information about using configuration sets, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/monitor-sending-activity.html">Amazon SES Developer Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public deleteConfigurationSet(
args: DeleteConfigurationSetCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteConfigurationSetCommandOutput>;
public deleteConfigurationSet(
args: DeleteConfigurationSetCommandInput,
cb: (err: any, data?: DeleteConfigurationSetCommandOutput) => void
): void;
public deleteConfigurationSet(
args: DeleteConfigurationSetCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteConfigurationSetCommandOutput) => void
): void;
public deleteConfigurationSet(
args: DeleteConfigurationSetCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteConfigurationSetCommandOutput) => void),
cb?: (err: any, data?: DeleteConfigurationSetCommandOutput) => void
): Promise<DeleteConfigurationSetCommandOutput> | void {
const command = new DeleteConfigurationSetCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes a configuration set event destination. Configuration set event destinations
* are associated with configuration sets, which enable you to publish email sending
* events. For information about using configuration sets, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/monitor-sending-activity.html">Amazon SES Developer Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public deleteConfigurationSetEventDestination(
args: DeleteConfigurationSetEventDestinationCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteConfigurationSetEventDestinationCommandOutput>;
public deleteConfigurationSetEventDestination(
args: DeleteConfigurationSetEventDestinationCommandInput,
cb: (err: any, data?: DeleteConfigurationSetEventDestinationCommandOutput) => void
): void;
public deleteConfigurationSetEventDestination(
args: DeleteConfigurationSetEventDestinationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteConfigurationSetEventDestinationCommandOutput) => void
): void;
public deleteConfigurationSetEventDestination(
args: DeleteConfigurationSetEventDestinationCommandInput,
optionsOrCb?:
| __HttpHandlerOptions
| ((err: any, data?: DeleteConfigurationSetEventDestinationCommandOutput) => void),
cb?: (err: any, data?: DeleteConfigurationSetEventDestinationCommandOutput) => void
): Promise<DeleteConfigurationSetEventDestinationCommandOutput> | void {
const command = new DeleteConfigurationSetEventDestinationCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes an association between a configuration set and a custom domain for open and
* click event tracking.</p>
* <p>By default, images and links used for tracking open and click events are hosted on
* domains operated by Amazon SES. You can configure a subdomain of your own to handle these
* events. For information about using custom domains, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/configure-custom-open-click-domains.html">Amazon SES Developer Guide</a>.</p>
* <note>
* <p>Deleting this kind of association will result in emails sent using the specified
* configuration set to capture open and click events using the standard,
* Amazon SES-operated domains.</p>
* </note>
*/
public deleteConfigurationSetTrackingOptions(
args: DeleteConfigurationSetTrackingOptionsCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteConfigurationSetTrackingOptionsCommandOutput>;
public deleteConfigurationSetTrackingOptions(
args: DeleteConfigurationSetTrackingOptionsCommandInput,
cb: (err: any, data?: DeleteConfigurationSetTrackingOptionsCommandOutput) => void
): void;
public deleteConfigurationSetTrackingOptions(
args: DeleteConfigurationSetTrackingOptionsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteConfigurationSetTrackingOptionsCommandOutput) => void
): void;
public deleteConfigurationSetTrackingOptions(
args: DeleteConfigurationSetTrackingOptionsCommandInput,
optionsOrCb?:
| __HttpHandlerOptions
| ((err: any, data?: DeleteConfigurationSetTrackingOptionsCommandOutput) => void),
cb?: (err: any, data?: DeleteConfigurationSetTrackingOptionsCommandOutput) => void
): Promise<DeleteConfigurationSetTrackingOptionsCommandOutput> | void {
const command = new DeleteConfigurationSetTrackingOptionsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes an existing custom verification email template. </p>
* <p>For more information about custom verification email templates, see <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/custom-verification-emails.html">Using Custom Verification Email Templates</a> in the <i>Amazon SES Developer
* Guide</i>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public deleteCustomVerificationEmailTemplate(
args: DeleteCustomVerificationEmailTemplateCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteCustomVerificationEmailTemplateCommandOutput>;
public deleteCustomVerificationEmailTemplate(
args: DeleteCustomVerificationEmailTemplateCommandInput,
cb: (err: any, data?: DeleteCustomVerificationEmailTemplateCommandOutput) => void
): void;
public deleteCustomVerificationEmailTemplate(
args: DeleteCustomVerificationEmailTemplateCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteCustomVerificationEmailTemplateCommandOutput) => void
): void;
public deleteCustomVerificationEmailTemplate(
args: DeleteCustomVerificationEmailTemplateCommandInput,
optionsOrCb?:
| __HttpHandlerOptions
| ((err: any, data?: DeleteCustomVerificationEmailTemplateCommandOutput) => void),
cb?: (err: any, data?: DeleteCustomVerificationEmailTemplateCommandOutput) => void
): Promise<DeleteCustomVerificationEmailTemplateCommandOutput> | void {
const command = new DeleteCustomVerificationEmailTemplateCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes the specified identity (an email address or a domain) from the list of
* verified identities.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public deleteIdentity(
args: DeleteIdentityCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteIdentityCommandOutput>;
public deleteIdentity(
args: DeleteIdentityCommandInput,
cb: (err: any, data?: DeleteIdentityCommandOutput) => void
): void;
public deleteIdentity(
args: DeleteIdentityCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteIdentityCommandOutput) => void
): void;
public deleteIdentity(
args: DeleteIdentityCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteIdentityCommandOutput) => void),
cb?: (err: any, data?: DeleteIdentityCommandOutput) => void
): Promise<DeleteIdentityCommandOutput> | void {
const command = new DeleteIdentityCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes the specified sending authorization policy for the given identity (an email
* address or a domain). This API returns successfully even if a policy with the specified
* name does not exist.</p>
* <note>
* <p>This API is for the identity owner only. If you have not verified the identity,
* this API will return an error.</p>
* </note>
* <p>Sending authorization is a feature that enables an identity owner to authorize other
* senders to use its identities. For information about using sending authorization, see
* the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html">Amazon SES Developer
* Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public deleteIdentityPolicy(
args: DeleteIdentityPolicyCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteIdentityPolicyCommandOutput>;
public deleteIdentityPolicy(
args: DeleteIdentityPolicyCommandInput,
cb: (err: any, data?: DeleteIdentityPolicyCommandOutput) => void
): void;
public deleteIdentityPolicy(
args: DeleteIdentityPolicyCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteIdentityPolicyCommandOutput) => void
): void;
public deleteIdentityPolicy(
args: DeleteIdentityPolicyCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteIdentityPolicyCommandOutput) => void),
cb?: (err: any, data?: DeleteIdentityPolicyCommandOutput) => void
): Promise<DeleteIdentityPolicyCommandOutput> | void {
const command = new DeleteIdentityPolicyCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes the specified IP address filter.</p>
* <p>For information about managing IP address filters, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-managing-ip-filters.html">Amazon SES
* Developer Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public deleteReceiptFilter(
args: DeleteReceiptFilterCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteReceiptFilterCommandOutput>;
public deleteReceiptFilter(
args: DeleteReceiptFilterCommandInput,
cb: (err: any, data?: DeleteReceiptFilterCommandOutput) => void
): void;
public deleteReceiptFilter(
args: DeleteReceiptFilterCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteReceiptFilterCommandOutput) => void
): void;
public deleteReceiptFilter(
args: DeleteReceiptFilterCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteReceiptFilterCommandOutput) => void),
cb?: (err: any, data?: DeleteReceiptFilterCommandOutput) => void
): Promise<DeleteReceiptFilterCommandOutput> | void {
const command = new DeleteReceiptFilterCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes the specified receipt rule.</p>
* <p>For information about managing receipt rules, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-managing-receipt-rules.html">Amazon SES
* Developer Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public deleteReceiptRule(
args: DeleteReceiptRuleCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteReceiptRuleCommandOutput>;
public deleteReceiptRule(
args: DeleteReceiptRuleCommandInput,
cb: (err: any, data?: DeleteReceiptRuleCommandOutput) => void
): void;
public deleteReceiptRule(
args: DeleteReceiptRuleCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteReceiptRuleCommandOutput) => void
): void;
public deleteReceiptRule(
args: DeleteReceiptRuleCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteReceiptRuleCommandOutput) => void),
cb?: (err: any, data?: DeleteReceiptRuleCommandOutput) => void
): Promise<DeleteReceiptRuleCommandOutput> | void {
const command = new DeleteReceiptRuleCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes the specified receipt rule set and all of the receipt rules it
* contains.</p>
* <note>
* <p>The currently active rule set cannot be deleted.</p>
* </note>
* <p>For information about managing receipt rule sets, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-managing-receipt-rule-sets.html">Amazon SES Developer Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public deleteReceiptRuleSet(
args: DeleteReceiptRuleSetCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteReceiptRuleSetCommandOutput>;
public deleteReceiptRuleSet(
args: DeleteReceiptRuleSetCommandInput,
cb: (err: any, data?: DeleteReceiptRuleSetCommandOutput) => void
): void;
public deleteReceiptRuleSet(
args: DeleteReceiptRuleSetCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteReceiptRuleSetCommandOutput) => void
): void;
public deleteReceiptRuleSet(
args: DeleteReceiptRuleSetCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteReceiptRuleSetCommandOutput) => void),
cb?: (err: any, data?: DeleteReceiptRuleSetCommandOutput) => void
): Promise<DeleteReceiptRuleSetCommandOutput> | void {
const command = new DeleteReceiptRuleSetCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deletes an email template.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public deleteTemplate(
args: DeleteTemplateCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteTemplateCommandOutput>;
public deleteTemplate(
args: DeleteTemplateCommandInput,
cb: (err: any, data?: DeleteTemplateCommandOutput) => void
): void;
public deleteTemplate(
args: DeleteTemplateCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteTemplateCommandOutput) => void
): void;
public deleteTemplate(
args: DeleteTemplateCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteTemplateCommandOutput) => void),
cb?: (err: any, data?: DeleteTemplateCommandOutput) => void
): Promise<DeleteTemplateCommandOutput> | void {
const command = new DeleteTemplateCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deprecated. Use the <code>DeleteIdentity</code> operation to delete email addresses
* and domains.</p>
*/
public deleteVerifiedEmailAddress(
args: DeleteVerifiedEmailAddressCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteVerifiedEmailAddressCommandOutput>;
public deleteVerifiedEmailAddress(
args: DeleteVerifiedEmailAddressCommandInput,
cb: (err: any, data?: DeleteVerifiedEmailAddressCommandOutput) => void
): void;
public deleteVerifiedEmailAddress(
args: DeleteVerifiedEmailAddressCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteVerifiedEmailAddressCommandOutput) => void
): void;
public deleteVerifiedEmailAddress(
args: DeleteVerifiedEmailAddressCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteVerifiedEmailAddressCommandOutput) => void),
cb?: (err: any, data?: DeleteVerifiedEmailAddressCommandOutput) => void
): Promise<DeleteVerifiedEmailAddressCommandOutput> | void {
const command = new DeleteVerifiedEmailAddressCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Returns the metadata and receipt rules for the receipt rule set that is currently
* active.</p>
* <p>For information about setting up receipt rule sets, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-receipt-rule-set.html">Amazon SES
* Developer Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public describeActiveReceiptRuleSet(
args: DescribeActiveReceiptRuleSetCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeActiveReceiptRuleSetCommandOutput>;
public describeActiveReceiptRuleSet(
args: DescribeActiveReceiptRuleSetCommandInput,
cb: (err: any, data?: DescribeActiveReceiptRuleSetCommandOutput) => void
): void;
public describeActiveReceiptRuleSet(
args: DescribeActiveReceiptRuleSetCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeActiveReceiptRuleSetCommandOutput) => void
): void;
public describeActiveReceiptRuleSet(
args: DescribeActiveReceiptRuleSetCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeActiveReceiptRuleSetCommandOutput) => void),
cb?: (err: any, data?: DescribeActiveReceiptRuleSetCommandOutput) => void
): Promise<DescribeActiveReceiptRuleSetCommandOutput> | void {
const command = new DescribeActiveReceiptRuleSetCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Returns the details of the specified configuration set. For information about using
* configuration sets, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/monitor-sending-activity.html">Amazon SES Developer
* Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public describeConfigurationSet(
args: DescribeConfigurationSetCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeConfigurationSetCommandOutput>;
public describeConfigurationSet(
args: DescribeConfigurationSetCommandInput,
cb: (err: any, data?: DescribeConfigurationSetCommandOutput) => void
): void;
public describeConfigurationSet(
args: DescribeConfigurationSetCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeConfigurationSetCommandOutput) => void
): void;
public describeConfigurationSet(
args: DescribeConfigurationSetCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeConfigurationSetCommandOutput) => void),
cb?: (err: any, data?: DescribeConfigurationSetCommandOutput) => void
): Promise<DescribeConfigurationSetCommandOutput> | void {
const command = new DescribeConfigurationSetCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Returns the details of the specified receipt rule.</p>
* <p>For information about setting up receipt rules, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-receipt-rules.html">Amazon SES Developer
* Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public describeReceiptRule(
args: DescribeReceiptRuleCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeReceiptRuleCommandOutput>;
public describeReceiptRule(
args: DescribeReceiptRuleCommandInput,
cb: (err: any, data?: DescribeReceiptRuleCommandOutput) => void
): void;
public describeReceiptRule(
args: DescribeReceiptRuleCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeReceiptRuleCommandOutput) => void
): void;
public describeReceiptRule(
args: DescribeReceiptRuleCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeReceiptRuleCommandOutput) => void),
cb?: (err: any, data?: DescribeReceiptRuleCommandOutput) => void
): Promise<DescribeReceiptRuleCommandOutput> | void {
const command = new DescribeReceiptRuleCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Returns the details of the specified receipt rule set.</p>
* <p>For information about managing receipt rule sets, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-managing-receipt-rule-sets.html">Amazon SES Developer Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public describeReceiptRuleSet(
args: DescribeReceiptRuleSetCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeReceiptRuleSetCommandOutput>;
public describeReceiptRuleSet(
args: DescribeReceiptRuleSetCommandInput,
cb: (err: any, data?: DescribeReceiptRuleSetCommandOutput) => void
): void;
public describeReceiptRuleSet(
args: DescribeReceiptRuleSetCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeReceiptRuleSetCommandOutput) => void
): void;
public describeReceiptRuleSet(
args: DescribeReceiptRuleSetCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeReceiptRuleSetCommandOutput) => void),
cb?: (err: any, data?: DescribeReceiptRuleSetCommandOutput) => void
): Promise<DescribeReceiptRuleSetCommandOutput> | void {
const command = new DescribeReceiptRuleSetCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Returns the email sending status of the Amazon SES account for the current region.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public getAccountSendingEnabled(
args: GetAccountSendingEnabledCommandInput,
options?: __HttpHandlerOptions
): Promise<GetAccountSendingEnabledCommandOutput>;
public getAccountSendingEnabled(
args: GetAccountSendingEnabledCommandInput,
cb: (err: any, data?: GetAccountSendingEnabledCommandOutput) => void
): void;
public getAccountSendingEnabled(
args: GetAccountSendingEnabledCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetAccountSendingEnabledCommandOutput) => void
): void;
public getAccountSendingEnabled(
args: GetAccountSendingEnabledCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetAccountSendingEnabledCommandOutput) => void),
cb?: (err: any, data?: GetAccountSendingEnabledCommandOutput) => void
): Promise<GetAccountSendingEnabledCommandOutput> | void {
const command = new GetAccountSendingEnabledCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Returns the custom email verification template for the template name you
* specify.</p>
* <p>For more information about custom verification email templates, see <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/custom-verification-emails.html">Using Custom Verification Email Templates</a> in the <i>Amazon SES Developer
* Guide</i>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public getCustomVerificationEmailTemplate(
args: GetCustomVerificationEmailTemplateCommandInput,
options?: __HttpHandlerOptions
): Promise<GetCustomVerificationEmailTemplateCommandOutput>;
public getCustomVerificationEmailTemplate(
args: GetCustomVerificationEmailTemplateCommandInput,
cb: (err: any, data?: GetCustomVerificationEmailTemplateCommandOutput) => void
): void;
public getCustomVerificationEmailTemplate(
args: GetCustomVerificationEmailTemplateCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetCustomVerificationEmailTemplateCommandOutput) => void
): void;
public getCustomVerificationEmailTemplate(
args: GetCustomVerificationEmailTemplateCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetCustomVerificationEmailTemplateCommandOutput) => void),
cb?: (err: any, data?: GetCustomVerificationEmailTemplateCommandOutput) => void
): Promise<GetCustomVerificationEmailTemplateCommandOutput> | void {
const command = new GetCustomVerificationEmailTemplateCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Returns the current status of Easy DKIM signing for an entity. For domain name
* identities, this operation also returns the DKIM tokens that are required for Easy DKIM
* signing, and whether Amazon SES has successfully verified that these tokens have been
* published.</p>
* <p>This operation takes a list of identities as input and returns the following
* information for each:</p>
* <ul>
* <li>
* <p>Whether Easy DKIM signing is enabled or disabled.</p>
* </li>
* <li>
* <p>A set of DKIM tokens that represent the identity. If the identity is an email
* address, the tokens represent the domain of that address.</p>
* </li>
* <li>
* <p>Whether Amazon SES has successfully verified the DKIM tokens published in the
* domain's DNS. This information is only returned for domain name identities, not
* for email addresses.</p>
* </li>
* </ul>
* <p>This operation is throttled at one request per second and can only get DKIM attributes
* for up to 100 identities at a time.</p>
* <p>For more information about creating DNS records using DKIM tokens, go to the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/easy-dkim-dns-records.html">Amazon SES Developer Guide</a>.</p>
*/
public getIdentityDkimAttributes(
args: GetIdentityDkimAttributesCommandInput,
options?: __HttpHandlerOptions
): Promise<GetIdentityDkimAttributesCommandOutput>;
public getIdentityDkimAttributes(
args: GetIdentityDkimAttributesCommandInput,
cb: (err: any, data?: GetIdentityDkimAttributesCommandOutput) => void
): void;
public getIdentityDkimAttributes(
args: GetIdentityDkimAttributesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetIdentityDkimAttributesCommandOutput) => void
): void;
public getIdentityDkimAttributes(
args: GetIdentityDkimAttributesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetIdentityDkimAttributesCommandOutput) => void),
cb?: (err: any, data?: GetIdentityDkimAttributesCommandOutput) => void
): Promise<GetIdentityDkimAttributesCommandOutput> | void {
const command = new GetIdentityDkimAttributesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Returns the custom MAIL FROM attributes for a list of identities (email addresses :
* domains).</p>
* <p>This operation is throttled at one request per second and can only get custom MAIL
* FROM attributes for up to 100 identities at a time.</p>
*/
public getIdentityMailFromDomainAttributes(
args: GetIdentityMailFromDomainAttributesCommandInput,
options?: __HttpHandlerOptions
): Promise<GetIdentityMailFromDomainAttributesCommandOutput>;
public getIdentityMailFromDomainAttributes(
args: GetIdentityMailFromDomainAttributesCommandInput,
cb: (err: any, data?: GetIdentityMailFromDomainAttributesCommandOutput) => void
): void;
public getIdentityMailFromDomainAttributes(
args: GetIdentityMailFromDomainAttributesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetIdentityMailFromDomainAttributesCommandOutput) => void
): void;
public getIdentityMailFromDomainAttributes(
args: GetIdentityMailFromDomainAttributesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetIdentityMailFromDomainAttributesCommandOutput) => void),
cb?: (err: any, data?: GetIdentityMailFromDomainAttributesCommandOutput) => void
): Promise<GetIdentityMailFromDomainAttributesCommandOutput> | void {
const command = new GetIdentityMailFromDomainAttributesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Given a list of verified identities (email addresses and/or domains), returns a
* structure describing identity notification attributes.</p>
* <p>This operation is throttled at one request per second and can only get notification
* attributes for up to 100 identities at a time.</p>
* <p>For more information about using notifications with Amazon SES, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/notifications.html">Amazon SES
* Developer Guide</a>.</p>
*/
public getIdentityNotificationAttributes(
args: GetIdentityNotificationAttributesCommandInput,
options?: __HttpHandlerOptions
): Promise<GetIdentityNotificationAttributesCommandOutput>;
public getIdentityNotificationAttributes(
args: GetIdentityNotificationAttributesCommandInput,
cb: (err: any, data?: GetIdentityNotificationAttributesCommandOutput) => void
): void;
public getIdentityNotificationAttributes(
args: GetIdentityNotificationAttributesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetIdentityNotificationAttributesCommandOutput) => void
): void;
public getIdentityNotificationAttributes(
args: GetIdentityNotificationAttributesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetIdentityNotificationAttributesCommandOutput) => void),
cb?: (err: any, data?: GetIdentityNotificationAttributesCommandOutput) => void
): Promise<GetIdentityNotificationAttributesCommandOutput> | void {
const command = new GetIdentityNotificationAttributesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Returns the requested sending authorization policies for the given identity (an email
* address or a domain). The policies are returned as a map of policy names to policy
* contents. You can retrieve a maximum of 20 policies at a time.</p>
* <note>
* <p>This API is for the identity owner only. If you have not verified the identity,
* this API will return an error.</p>
* </note>
* <p>Sending authorization is a feature that enables an identity owner to authorize other
* senders to use its identities. For information about using sending authorization, see
* the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html">Amazon SES Developer
* Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public getIdentityPolicies(
args: GetIdentityPoliciesCommandInput,
options?: __HttpHandlerOptions
): Promise<GetIdentityPoliciesCommandOutput>;
public getIdentityPolicies(
args: GetIdentityPoliciesCommandInput,
cb: (err: any, data?: GetIdentityPoliciesCommandOutput) => void
): void;
public getIdentityPolicies(
args: GetIdentityPoliciesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetIdentityPoliciesCommandOutput) => void
): void;
public getIdentityPolicies(
args: GetIdentityPoliciesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetIdentityPoliciesCommandOutput) => void),
cb?: (err: any, data?: GetIdentityPoliciesCommandOutput) => void
): Promise<GetIdentityPoliciesCommandOutput> | void {
const command = new GetIdentityPoliciesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Given a list of identities (email addresses and/or domains), returns the verification
* status and (for domain identities) the verification token for each identity.</p>
* <p>The verification status of an email address is "Pending" until the email address owner
* clicks the link within the verification email that Amazon SES sent to that address. If the
* email address owner clicks the link within 24 hours, the verification status of the
* email address changes to "Success". If the link is not clicked within 24 hours, the
* verification status changes to "Failed." In that case, if you still want to verify the
* email address, you must restart the verification process from the beginning.</p>
* <p>For domain identities, the domain's verification status is "Pending" as Amazon SES searches
* for the required TXT record in the DNS settings of the domain. When Amazon SES detects the
* record, the domain's verification status changes to "Success". If Amazon SES is unable to
* detect the record within 72 hours, the domain's verification status changes to "Failed."
* In that case, if you still want to verify the domain, you must restart the verification
* process from the beginning.</p>
* <p>This operation is throttled at one request per second and can only get verification
* attributes for up to 100 identities at a time.</p>
*/
public getIdentityVerificationAttributes(
args: GetIdentityVerificationAttributesCommandInput,
options?: __HttpHandlerOptions
): Promise<GetIdentityVerificationAttributesCommandOutput>;
public getIdentityVerificationAttributes(
args: GetIdentityVerificationAttributesCommandInput,
cb: (err: any, data?: GetIdentityVerificationAttributesCommandOutput) => void
): void;
public getIdentityVerificationAttributes(
args: GetIdentityVerificationAttributesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetIdentityVerificationAttributesCommandOutput) => void
): void;
public getIdentityVerificationAttributes(
args: GetIdentityVerificationAttributesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetIdentityVerificationAttributesCommandOutput) => void),
cb?: (err: any, data?: GetIdentityVerificationAttributesCommandOutput) => void
): Promise<GetIdentityVerificationAttributesCommandOutput> | void {
const command = new GetIdentityVerificationAttributesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Provides the sending limits for the Amazon SES account. </p>
* <p>You can execute this operation no more than once per second.</p>
*/
public getSendQuota(
args: GetSendQuotaCommandInput,
options?: __HttpHandlerOptions
): Promise<GetSendQuotaCommandOutput>;
public getSendQuota(args: GetSendQuotaCommandInput, cb: (err: any, data?: GetSendQuotaCommandOutput) => void): void;
public getSendQuota(
args: GetSendQuotaCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetSendQuotaCommandOutput) => void
): void;
public getSendQuota(
args: GetSendQuotaCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetSendQuotaCommandOutput) => void),
cb?: (err: any, data?: GetSendQuotaCommandOutput) => void
): Promise<GetSendQuotaCommandOutput> | void {
const command = new GetSendQuotaCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Provides sending statistics for the current AWS Region. The result is a list of data
* points, representing the last two weeks of sending activity. Each data point in the list
* contains statistics for a 15-minute period of time.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public getSendStatistics(
args: GetSendStatisticsCommandInput,
options?: __HttpHandlerOptions
): Promise<GetSendStatisticsCommandOutput>;
public getSendStatistics(
args: GetSendStatisticsCommandInput,
cb: (err: any, data?: GetSendStatisticsCommandOutput) => void
): void;
public getSendStatistics(
args: GetSendStatisticsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetSendStatisticsCommandOutput) => void
): void;
public getSendStatistics(
args: GetSendStatisticsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetSendStatisticsCommandOutput) => void),
cb?: (err: any, data?: GetSendStatisticsCommandOutput) => void
): Promise<GetSendStatisticsCommandOutput> | void {
const command = new GetSendStatisticsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Displays the template object (which includes the Subject line, HTML part and text
* part) for the template you specify.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public getTemplate(args: GetTemplateCommandInput, options?: __HttpHandlerOptions): Promise<GetTemplateCommandOutput>;
public getTemplate(args: GetTemplateCommandInput, cb: (err: any, data?: GetTemplateCommandOutput) => void): void;
public getTemplate(
args: GetTemplateCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetTemplateCommandOutput) => void
): void;
public getTemplate(
args: GetTemplateCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetTemplateCommandOutput) => void),
cb?: (err: any, data?: GetTemplateCommandOutput) => void
): Promise<GetTemplateCommandOutput> | void {
const command = new GetTemplateCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Provides a list of the configuration sets associated with your Amazon SES account in the
* current AWS Region. For information about using configuration sets, see <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/monitor-sending-activity.html">Monitoring Your Amazon SES Sending Activity</a> in the <i>Amazon SES Developer
* Guide.</i>
* </p>
* <p>You can execute this operation no more than once per second. This operation will
* return up to 1,000 configuration sets each time it is run. If your Amazon SES account has
* more than 1,000 configuration sets, this operation will also return a NextToken element.
* You can then execute the <code>ListConfigurationSets</code> operation again, passing the
* <code>NextToken</code> parameter and the value of the NextToken element to retrieve
* additional results.</p>
*/
public listConfigurationSets(
args: ListConfigurationSetsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListConfigurationSetsCommandOutput>;
public listConfigurationSets(
args: ListConfigurationSetsCommandInput,
cb: (err: any, data?: ListConfigurationSetsCommandOutput) => void
): void;
public listConfigurationSets(
args: ListConfigurationSetsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListConfigurationSetsCommandOutput) => void
): void;
public listConfigurationSets(
args: ListConfigurationSetsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListConfigurationSetsCommandOutput) => void),
cb?: (err: any, data?: ListConfigurationSetsCommandOutput) => void
): Promise<ListConfigurationSetsCommandOutput> | void {
const command = new ListConfigurationSetsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Lists the existing custom verification email templates for your account in the current
* AWS Region.</p>
* <p>For more information about custom verification email templates, see <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/custom-verification-emails.html">Using Custom Verification Email Templates</a> in the <i>Amazon SES Developer
* Guide</i>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public listCustomVerificationEmailTemplates(
args: ListCustomVerificationEmailTemplatesCommandInput,
options?: __HttpHandlerOptions
): Promise<ListCustomVerificationEmailTemplatesCommandOutput>;
public listCustomVerificationEmailTemplates(
args: ListCustomVerificationEmailTemplatesCommandInput,
cb: (err: any, data?: ListCustomVerificationEmailTemplatesCommandOutput) => void
): void;
public listCustomVerificationEmailTemplates(
args: ListCustomVerificationEmailTemplatesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListCustomVerificationEmailTemplatesCommandOutput) => void
): void;
public listCustomVerificationEmailTemplates(
args: ListCustomVerificationEmailTemplatesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListCustomVerificationEmailTemplatesCommandOutput) => void),
cb?: (err: any, data?: ListCustomVerificationEmailTemplatesCommandOutput) => void
): Promise<ListCustomVerificationEmailTemplatesCommandOutput> | void {
const command = new ListCustomVerificationEmailTemplatesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Returns a list containing all of the identities (email addresses and domains) for your
* AWS account in the current AWS Region, regardless of verification status.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public listIdentities(
args: ListIdentitiesCommandInput,
options?: __HttpHandlerOptions
): Promise<ListIdentitiesCommandOutput>;
public listIdentities(
args: ListIdentitiesCommandInput,
cb: (err: any, data?: ListIdentitiesCommandOutput) => void
): void;
public listIdentities(
args: ListIdentitiesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListIdentitiesCommandOutput) => void
): void;
public listIdentities(
args: ListIdentitiesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListIdentitiesCommandOutput) => void),
cb?: (err: any, data?: ListIdentitiesCommandOutput) => void
): Promise<ListIdentitiesCommandOutput> | void {
const command = new ListIdentitiesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Returns a list of sending authorization policies that are attached to the given
* identity (an email address or a domain). This API returns only a list. If you want the
* actual policy content, you can use <code>GetIdentityPolicies</code>.</p>
* <note>
* <p>This API is for the identity owner only. If you have not verified the identity,
* this API will return an error.</p>
* </note>
* <p>Sending authorization is a feature that enables an identity owner to authorize other
* senders to use its identities. For information about using sending authorization, see
* the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html">Amazon SES Developer
* Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public listIdentityPolicies(
args: ListIdentityPoliciesCommandInput,
options?: __HttpHandlerOptions
): Promise<ListIdentityPoliciesCommandOutput>;
public listIdentityPolicies(
args: ListIdentityPoliciesCommandInput,
cb: (err: any, data?: ListIdentityPoliciesCommandOutput) => void
): void;
public listIdentityPolicies(
args: ListIdentityPoliciesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListIdentityPoliciesCommandOutput) => void
): void;
public listIdentityPolicies(
args: ListIdentityPoliciesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListIdentityPoliciesCommandOutput) => void),
cb?: (err: any, data?: ListIdentityPoliciesCommandOutput) => void
): Promise<ListIdentityPoliciesCommandOutput> | void {
const command = new ListIdentityPoliciesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Lists the IP address filters associated with your AWS account in the current AWS
* Region.</p>
* <p>For information about managing IP address filters, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-managing-ip-filters.html">Amazon SES
* Developer Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public listReceiptFilters(
args: ListReceiptFiltersCommandInput,
options?: __HttpHandlerOptions
): Promise<ListReceiptFiltersCommandOutput>;
public listReceiptFilters(
args: ListReceiptFiltersCommandInput,
cb: (err: any, data?: ListReceiptFiltersCommandOutput) => void
): void;
public listReceiptFilters(
args: ListReceiptFiltersCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListReceiptFiltersCommandOutput) => void
): void;
public listReceiptFilters(
args: ListReceiptFiltersCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListReceiptFiltersCommandOutput) => void),
cb?: (err: any, data?: ListReceiptFiltersCommandOutput) => void
): Promise<ListReceiptFiltersCommandOutput> | void {
const command = new ListReceiptFiltersCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Lists the receipt rule sets that exist under your AWS account in the current AWS
* Region. If there are additional receipt rule sets to be retrieved, you will receive a
* <code>NextToken</code> that you can provide to the next call to
* <code>ListReceiptRuleSets</code> to retrieve the additional entries.</p>
* <p>For information about managing receipt rule sets, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-managing-receipt-rule-sets.html">Amazon SES Developer Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public listReceiptRuleSets(
args: ListReceiptRuleSetsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListReceiptRuleSetsCommandOutput>;
public listReceiptRuleSets(
args: ListReceiptRuleSetsCommandInput,
cb: (err: any, data?: ListReceiptRuleSetsCommandOutput) => void
): void;
public listReceiptRuleSets(
args: ListReceiptRuleSetsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListReceiptRuleSetsCommandOutput) => void
): void;
public listReceiptRuleSets(
args: ListReceiptRuleSetsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListReceiptRuleSetsCommandOutput) => void),
cb?: (err: any, data?: ListReceiptRuleSetsCommandOutput) => void
): Promise<ListReceiptRuleSetsCommandOutput> | void {
const command = new ListReceiptRuleSetsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Lists the email templates present in your Amazon SES account in the current AWS
* Region.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public listTemplates(
args: ListTemplatesCommandInput,
options?: __HttpHandlerOptions
): Promise<ListTemplatesCommandOutput>;
public listTemplates(
args: ListTemplatesCommandInput,
cb: (err: any, data?: ListTemplatesCommandOutput) => void
): void;
public listTemplates(
args: ListTemplatesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListTemplatesCommandOutput) => void
): void;
public listTemplates(
args: ListTemplatesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTemplatesCommandOutput) => void),
cb?: (err: any, data?: ListTemplatesCommandOutput) => void
): Promise<ListTemplatesCommandOutput> | void {
const command = new ListTemplatesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deprecated. Use the <code>ListIdentities</code> operation to list the email addresses
* and domains associated with your account.</p>
*/
public listVerifiedEmailAddresses(
args: ListVerifiedEmailAddressesCommandInput,
options?: __HttpHandlerOptions
): Promise<ListVerifiedEmailAddressesCommandOutput>;
public listVerifiedEmailAddresses(
args: ListVerifiedEmailAddressesCommandInput,
cb: (err: any, data?: ListVerifiedEmailAddressesCommandOutput) => void
): void;
public listVerifiedEmailAddresses(
args: ListVerifiedEmailAddressesCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListVerifiedEmailAddressesCommandOutput) => void
): void;
public listVerifiedEmailAddresses(
args: ListVerifiedEmailAddressesCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListVerifiedEmailAddressesCommandOutput) => void),
cb?: (err: any, data?: ListVerifiedEmailAddressesCommandOutput) => void
): Promise<ListVerifiedEmailAddressesCommandOutput> | void {
const command = new ListVerifiedEmailAddressesCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Adds or updates the delivery options for a configuration set.</p>
*/
public putConfigurationSetDeliveryOptions(
args: PutConfigurationSetDeliveryOptionsCommandInput,
options?: __HttpHandlerOptions
): Promise<PutConfigurationSetDeliveryOptionsCommandOutput>;
public putConfigurationSetDeliveryOptions(
args: PutConfigurationSetDeliveryOptionsCommandInput,
cb: (err: any, data?: PutConfigurationSetDeliveryOptionsCommandOutput) => void
): void;
public putConfigurationSetDeliveryOptions(
args: PutConfigurationSetDeliveryOptionsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: PutConfigurationSetDeliveryOptionsCommandOutput) => void
): void;
public putConfigurationSetDeliveryOptions(
args: PutConfigurationSetDeliveryOptionsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutConfigurationSetDeliveryOptionsCommandOutput) => void),
cb?: (err: any, data?: PutConfigurationSetDeliveryOptionsCommandOutput) => void
): Promise<PutConfigurationSetDeliveryOptionsCommandOutput> | void {
const command = new PutConfigurationSetDeliveryOptionsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Adds or updates a sending authorization policy for the specified identity (an email
* address or a domain).</p>
* <note>
* <p>This API is for the identity owner only. If you have not verified the identity,
* this API will return an error.</p>
* </note>
* <p>Sending authorization is a feature that enables an identity owner to authorize other
* senders to use its identities. For information about using sending authorization, see
* the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html">Amazon SES Developer
* Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public putIdentityPolicy(
args: PutIdentityPolicyCommandInput,
options?: __HttpHandlerOptions
): Promise<PutIdentityPolicyCommandOutput>;
public putIdentityPolicy(
args: PutIdentityPolicyCommandInput,
cb: (err: any, data?: PutIdentityPolicyCommandOutput) => void
): void;
public putIdentityPolicy(
args: PutIdentityPolicyCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: PutIdentityPolicyCommandOutput) => void
): void;
public putIdentityPolicy(
args: PutIdentityPolicyCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutIdentityPolicyCommandOutput) => void),
cb?: (err: any, data?: PutIdentityPolicyCommandOutput) => void
): Promise<PutIdentityPolicyCommandOutput> | void {
const command = new PutIdentityPolicyCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Reorders the receipt rules within a receipt rule set.</p>
* <note>
* <p>All of the rules in the rule set must be represented in this request. That is,
* this API will return an error if the reorder request doesn't explicitly position all
* of the rules.</p>
* </note>
* <p>For information about managing receipt rule sets, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-managing-receipt-rule-sets.html">Amazon SES Developer Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public reorderReceiptRuleSet(
args: ReorderReceiptRuleSetCommandInput,
options?: __HttpHandlerOptions
): Promise<ReorderReceiptRuleSetCommandOutput>;
public reorderReceiptRuleSet(
args: ReorderReceiptRuleSetCommandInput,
cb: (err: any, data?: ReorderReceiptRuleSetCommandOutput) => void
): void;
public reorderReceiptRuleSet(
args: ReorderReceiptRuleSetCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ReorderReceiptRuleSetCommandOutput) => void
): void;
public reorderReceiptRuleSet(
args: ReorderReceiptRuleSetCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ReorderReceiptRuleSetCommandOutput) => void),
cb?: (err: any, data?: ReorderReceiptRuleSetCommandOutput) => void
): Promise<ReorderReceiptRuleSetCommandOutput> | void {
const command = new ReorderReceiptRuleSetCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Generates and sends a bounce message to the sender of an email you received through
* Amazon SES. You can only use this API on an email up to 24 hours after you receive it.</p>
* <note>
* <p>You cannot use this API to send generic bounces for mail that was not received by
* Amazon SES.</p>
* </note>
* <p>For information about receiving email through Amazon SES, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email.html">Amazon SES
* Developer Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public sendBounce(args: SendBounceCommandInput, options?: __HttpHandlerOptions): Promise<SendBounceCommandOutput>;
public sendBounce(args: SendBounceCommandInput, cb: (err: any, data?: SendBounceCommandOutput) => void): void;
public sendBounce(
args: SendBounceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: SendBounceCommandOutput) => void
): void;
public sendBounce(
args: SendBounceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: SendBounceCommandOutput) => void),
cb?: (err: any, data?: SendBounceCommandOutput) => void
): Promise<SendBounceCommandOutput> | void {
const command = new SendBounceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Composes an email message to multiple destinations. The message body is created using
* an email template.</p>
* <p>In order to send email using the <code>SendBulkTemplatedEmail</code> operation, your
* call to the API must meet the following requirements:</p>
* <ul>
* <li>
* <p>The call must refer to an existing email template. You can create email
* templates using the <a>CreateTemplate</a> operation.</p>
* </li>
* <li>
* <p>The message must be sent from a verified email address or domain.</p>
* </li>
* <li>
* <p>If your account is still in the Amazon SES sandbox, you may only send to verified
* addresses or domains, or to email addresses associated with the Amazon SES Mailbox
* Simulator. For more information, see <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-addresses-and-domains.html">Verifying
* Email Addresses and Domains</a> in the <i>Amazon SES Developer
* Guide.</i>
* </p>
* </li>
* <li>
* <p>The maximum message size is 10 MB.</p>
* </li>
* <li>
* <p>Each <code>Destination</code> parameter must include at least one recipient
* email address. The recipient address can be a To: address, a CC: address, or a
* BCC: address. If a recipient email address is invalid (that is, it is not in the
* format <i>UserName@[SubDomain.]Domain.TopLevelDomain</i>), the
* entire message will be rejected, even if the message contains other recipients
* that are valid.</p>
* </li>
* <li>
* <p>The message may not include more than 50 recipients, across the To:, CC: and
* BCC: fields. If you need to send an email message to a larger audience, you can
* divide your recipient list into groups of 50 or fewer, and then call the
* <code>SendBulkTemplatedEmail</code> operation several times to send the
* message to each group.</p>
* </li>
* <li>
* <p>The number of destinations you can contact in a single call to the API may be
* limited by your account's maximum sending rate.</p>
* </li>
* </ul>
*/
public sendBulkTemplatedEmail(
args: SendBulkTemplatedEmailCommandInput,
options?: __HttpHandlerOptions
): Promise<SendBulkTemplatedEmailCommandOutput>;
public sendBulkTemplatedEmail(
args: SendBulkTemplatedEmailCommandInput,
cb: (err: any, data?: SendBulkTemplatedEmailCommandOutput) => void
): void;
public sendBulkTemplatedEmail(
args: SendBulkTemplatedEmailCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: SendBulkTemplatedEmailCommandOutput) => void
): void;
public sendBulkTemplatedEmail(
args: SendBulkTemplatedEmailCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: SendBulkTemplatedEmailCommandOutput) => void),
cb?: (err: any, data?: SendBulkTemplatedEmailCommandOutput) => void
): Promise<SendBulkTemplatedEmailCommandOutput> | void {
const command = new SendBulkTemplatedEmailCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Adds an email address to the list of identities for your Amazon SES account in the current
* AWS Region and attempts to verify it. As a result of executing this operation, a
* customized verification email is sent to the specified address.</p>
* <p>To use this operation, you must first create a custom verification email template. For
* more information about creating and using custom verification email templates, see
* <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/custom-verification-emails.html">Using Custom
* Verification Email Templates</a> in the <i>Amazon SES Developer
* Guide</i>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public sendCustomVerificationEmail(
args: SendCustomVerificationEmailCommandInput,
options?: __HttpHandlerOptions
): Promise<SendCustomVerificationEmailCommandOutput>;
public sendCustomVerificationEmail(
args: SendCustomVerificationEmailCommandInput,
cb: (err: any, data?: SendCustomVerificationEmailCommandOutput) => void
): void;
public sendCustomVerificationEmail(
args: SendCustomVerificationEmailCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: SendCustomVerificationEmailCommandOutput) => void
): void;
public sendCustomVerificationEmail(
args: SendCustomVerificationEmailCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: SendCustomVerificationEmailCommandOutput) => void),
cb?: (err: any, data?: SendCustomVerificationEmailCommandOutput) => void
): Promise<SendCustomVerificationEmailCommandOutput> | void {
const command = new SendCustomVerificationEmailCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Composes an email message and immediately queues it for sending. In order to send
* email using the <code>SendEmail</code> operation, your message must meet the following
* requirements:</p>
*
* <ul>
* <li>
* <p>The message must be sent from a verified email address or domain. If you
* attempt to send email using a non-verified address or domain, the operation will
* result in an "Email address not verified" error. </p>
* </li>
* <li>
* <p>If your account is still in the Amazon SES sandbox, you may only send to verified
* addresses or domains, or to email addresses associated with the Amazon SES Mailbox
* Simulator. For more information, see <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-addresses-and-domains.html">Verifying
* Email Addresses and Domains</a> in the <i>Amazon SES Developer
* Guide.</i>
* </p>
* </li>
* <li>
* <p>The maximum message size is 10 MB.</p>
* </li>
* <li>
* <p>The message must include at least one recipient email address. The recipient
* address can be a To: address, a CC: address, or a BCC: address. If a recipient
* email address is invalid (that is, it is not in the format
* <i>UserName@[SubDomain.]Domain.TopLevelDomain</i>), the entire
* message will be rejected, even if the message contains other recipients that are
* valid.</p>
* </li>
* <li>
* <p>The message may not include more than 50 recipients, across the To:, CC: and
* BCC: fields. If you need to send an email message to a larger audience, you can
* divide your recipient list into groups of 50 or fewer, and then call the
* <code>SendEmail</code> operation several times to send the message to each
* group.</p>
* </li>
* </ul>
* <important>
* <p>For every message that you send, the total number of recipients (including each
* recipient in the To:, CC: and BCC: fields) is counted against the maximum number of
* emails you can send in a 24-hour period (your <i>sending quota</i>).
* For more information about sending quotas in Amazon SES, see <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/manage-sending-limits.html">Managing Your Amazon SES
* Sending Limits</a> in the <i>Amazon SES Developer Guide.</i>
* </p>
* </important>
*/
public sendEmail(args: SendEmailCommandInput, options?: __HttpHandlerOptions): Promise<SendEmailCommandOutput>;
public sendEmail(args: SendEmailCommandInput, cb: (err: any, data?: SendEmailCommandOutput) => void): void;
public sendEmail(
args: SendEmailCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: SendEmailCommandOutput) => void
): void;
public sendEmail(
args: SendEmailCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: SendEmailCommandOutput) => void),
cb?: (err: any, data?: SendEmailCommandOutput) => void
): Promise<SendEmailCommandOutput> | void {
const command = new SendEmailCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Composes an email message and immediately queues it for sending.</p>
*
* <p>This operation is more flexible than the <code>SendEmail</code> API operation. When
* you use the <code>SendRawEmail</code> operation, you can specify the headers of the
* message as well as its content. This flexibility is useful, for example, when you want
* to send a multipart MIME email (such a message that contains both a text and an HTML
* version). You can also use this operation to send messages that include
* attachments.</p>
* <p>The <code>SendRawEmail</code> operation has the following requirements:</p>
* <ul>
* <li>
* <p>You can only send email from <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-addresses-and-domains.html">verified email addresses or domains</a>. If you try
* to send email from an address that isn't verified, the operation results in an
* "Email address not verified" error.</p>
* </li>
* <li>
* <p>If your account is still in the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/request-production-access.html">Amazon SES sandbox</a>, you can only send email to other
* verified addresses in your account, or to addresses that are associated with the
* <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/mailbox-simulator.html">Amazon SES mailbox simulator</a>.</p>
* </li>
* <li>
* <p>The maximum message size, including attachments, is 10 MB.</p>
* </li>
* <li>
* <p>Each message has to include at least one recipient address. A recipient
* address includes any address on the To:, CC:, or BCC: lines.</p>
* </li>
* <li>
* <p>If you send a single message to more than one recipient address, and one of
* the recipient addresses isn't in a valid format (that is, it's not in the format
* <i>UserName@[SubDomain.]Domain.TopLevelDomain</i>), Amazon SES
* rejects the entire message, even if the other addresses are valid.</p>
* </li>
* <li>
* <p>Each message can include up to 50 recipient addresses across the To:, CC:, or
* BCC: lines. If you need to send a single message to more than 50 recipients, you
* have to split the list of recipient addresses into groups of less than 50
* recipients, and send separate messages to each group.</p>
* </li>
* <li>
* <p>Amazon SES allows you to specify 8-bit Content-Transfer-Encoding for MIME message
* parts. However, if Amazon SES has to modify the contents of your message (for
* example, if you use open and click tracking), 8-bit content isn't preserved. For
* this reason, we highly recommend that you encode all content that isn't 7-bit
* ASCII. For more information, see <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-raw.html#send-email-mime-encoding">MIME Encoding</a> in the <i>Amazon SES Developer
* Guide</i>.</p>
* </li>
* </ul>
*
*
*
* <p>Additionally, keep the following considerations in mind when using the
* <code>SendRawEmail</code> operation:</p>
*
* <ul>
* <li>
* <p>Although you can customize the message headers when using the
* <code>SendRawEmail</code> operation, Amazon SES will automatically apply its own
* <code>Message-ID</code> and <code>Date</code> headers; if you passed these
* headers when creating the message, they will be overwritten by the values that
* Amazon SES provides.</p>
* </li>
* <li>
* <p>If you are using sending authorization to send on behalf of another user,
* <code>SendRawEmail</code> enables you to specify the cross-account identity
* for the email's Source, From, and Return-Path parameters in one of two ways: you
* can pass optional parameters <code>SourceArn</code>, <code>FromArn</code>,
* and/or <code>ReturnPathArn</code> to the API, or you can include the following
* X-headers in the header of your raw email:</p>
* <ul>
* <li>
* <p>
* <code>X-SES-SOURCE-ARN</code>
* </p>
* </li>
* <li>
* <p>
* <code>X-SES-FROM-ARN</code>
* </p>
* </li>
* <li>
* <p>
* <code>X-SES-RETURN-PATH-ARN</code>
* </p>
* </li>
* </ul>
* <important>
* <p>Don't include these X-headers in the DKIM signature. Amazon SES removes these
* before it sends the email.</p>
* </important>
* <p>If you only specify the <code>SourceIdentityArn</code> parameter, Amazon SES sets
* the From and Return-Path addresses to the same identity that you
* specified.</p>
* <p>For more information about sending authorization, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html">Using Sending
* Authorization with Amazon SES</a> in the <i>Amazon SES Developer
* Guide.</i>
* </p>
* </li>
* <li>
* <p>For every message that you send, the total number of recipients (including
* each recipient in the To:, CC: and BCC: fields) is counted against the maximum
* number of emails you can send in a 24-hour period (your <i>sending
* quota</i>). For more information about sending quotas in Amazon SES, see
* <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/manage-sending-limits.html">Managing Your
* Amazon SES Sending Limits</a> in the <i>Amazon SES Developer
* Guide.</i>
* </p>
* </li>
* </ul>
*/
public sendRawEmail(
args: SendRawEmailCommandInput,
options?: __HttpHandlerOptions
): Promise<SendRawEmailCommandOutput>;
public sendRawEmail(args: SendRawEmailCommandInput, cb: (err: any, data?: SendRawEmailCommandOutput) => void): void;
public sendRawEmail(
args: SendRawEmailCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: SendRawEmailCommandOutput) => void
): void;
public sendRawEmail(
args: SendRawEmailCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: SendRawEmailCommandOutput) => void),
cb?: (err: any, data?: SendRawEmailCommandOutput) => void
): Promise<SendRawEmailCommandOutput> | void {
const command = new SendRawEmailCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Composes an email message using an email template and immediately queues it for
* sending.</p>
* <p>In order to send email using the <code>SendTemplatedEmail</code> operation, your call
* to the API must meet the following requirements:</p>
* <ul>
* <li>
* <p>The call must refer to an existing email template. You can create email
* templates using the <a>CreateTemplate</a> operation.</p>
* </li>
* <li>
* <p>The message must be sent from a verified email address or domain.</p>
* </li>
* <li>
* <p>If your account is still in the Amazon SES sandbox, you may only send to verified
* addresses or domains, or to email addresses associated with the Amazon SES Mailbox
* Simulator. For more information, see <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-addresses-and-domains.html">Verifying
* Email Addresses and Domains</a> in the <i>Amazon SES Developer
* Guide.</i>
* </p>
* </li>
* <li>
* <p>The maximum message size is 10 MB.</p>
* </li>
* <li>
* <p>Calls to the <code>SendTemplatedEmail</code> operation may only include one
* <code>Destination</code> parameter. A destination is a set of recipients who
* will receive the same version of the email. The <code>Destination</code>
* parameter can include up to 50 recipients, across the To:, CC: and BCC:
* fields.</p>
* </li>
* <li>
* <p>The <code>Destination</code> parameter must include at least one recipient
* email address. The recipient address can be a To: address, a CC: address, or a
* BCC: address. If a recipient email address is invalid (that is, it is not in the
* format <i>UserName@[SubDomain.]Domain.TopLevelDomain</i>), the
* entire message will be rejected, even if the message contains other recipients
* that are valid.</p>
* </li>
* </ul>
* <important>
* <p>If your call to the <code>SendTemplatedEmail</code> operation includes all of the
* required parameters, Amazon SES accepts it and returns a Message ID. However, if Amazon SES
* can't render the email because the template contains errors, it doesn't send the
* email. Additionally, because it already accepted the message, Amazon SES doesn't return a
* message stating that it was unable to send the email.</p>
* <p>For these reasons, we highly recommend that you set up Amazon SES to send you
* notifications when Rendering Failure events occur. For more information, see <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-personalized-email-api.html">Sending
* Personalized Email Using the Amazon SES API</a> in the <i>Amazon Simple Email Service
* Developer Guide</i>.</p>
* </important>
*/
public sendTemplatedEmail(
args: SendTemplatedEmailCommandInput,
options?: __HttpHandlerOptions
): Promise<SendTemplatedEmailCommandOutput>;
public sendTemplatedEmail(
args: SendTemplatedEmailCommandInput,
cb: (err: any, data?: SendTemplatedEmailCommandOutput) => void
): void;
public sendTemplatedEmail(
args: SendTemplatedEmailCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: SendTemplatedEmailCommandOutput) => void
): void;
public sendTemplatedEmail(
args: SendTemplatedEmailCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: SendTemplatedEmailCommandOutput) => void),
cb?: (err: any, data?: SendTemplatedEmailCommandOutput) => void
): Promise<SendTemplatedEmailCommandOutput> | void {
const command = new SendTemplatedEmailCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Sets the specified receipt rule set as the active receipt rule set.</p>
* <note>
* <p>To disable your email-receiving through Amazon SES completely, you can call this API
* with RuleSetName set to null.</p>
* </note>
* <p>For information about managing receipt rule sets, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-managing-receipt-rule-sets.html">Amazon SES Developer Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public setActiveReceiptRuleSet(
args: SetActiveReceiptRuleSetCommandInput,
options?: __HttpHandlerOptions
): Promise<SetActiveReceiptRuleSetCommandOutput>;
public setActiveReceiptRuleSet(
args: SetActiveReceiptRuleSetCommandInput,
cb: (err: any, data?: SetActiveReceiptRuleSetCommandOutput) => void
): void;
public setActiveReceiptRuleSet(
args: SetActiveReceiptRuleSetCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: SetActiveReceiptRuleSetCommandOutput) => void
): void;
public setActiveReceiptRuleSet(
args: SetActiveReceiptRuleSetCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: SetActiveReceiptRuleSetCommandOutput) => void),
cb?: (err: any, data?: SetActiveReceiptRuleSetCommandOutput) => void
): Promise<SetActiveReceiptRuleSetCommandOutput> | void {
const command = new SetActiveReceiptRuleSetCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Enables or disables Easy DKIM signing of email sent from an identity. If Easy DKIM
* signing is enabled for a domain, then Amazon SES uses DKIM to sign all email that it sends
* from addresses on that domain. If Easy DKIM signing is enabled for an email address,
* then Amazon SES uses DKIM to sign all email it sends from that address.</p>
* <note>
* <p>For email addresses (for example, <code>user@example.com</code>), you can only
* enable DKIM signing if the corresponding domain (in this case,
* <code>example.com</code>) has been set up to use Easy DKIM.</p>
* </note>
* <p>You can enable DKIM signing for an identity at any time after you start the
* verification process for the identity, even if the verification process isn't complete. </p>
* <p>You can execute this operation no more than once per second.</p>
* <p>For more information about Easy DKIM signing, go to the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/easy-dkim.html">Amazon SES Developer Guide</a>.</p>
*/
public setIdentityDkimEnabled(
args: SetIdentityDkimEnabledCommandInput,
options?: __HttpHandlerOptions
): Promise<SetIdentityDkimEnabledCommandOutput>;
public setIdentityDkimEnabled(
args: SetIdentityDkimEnabledCommandInput,
cb: (err: any, data?: SetIdentityDkimEnabledCommandOutput) => void
): void;
public setIdentityDkimEnabled(
args: SetIdentityDkimEnabledCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: SetIdentityDkimEnabledCommandOutput) => void
): void;
public setIdentityDkimEnabled(
args: SetIdentityDkimEnabledCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: SetIdentityDkimEnabledCommandOutput) => void),
cb?: (err: any, data?: SetIdentityDkimEnabledCommandOutput) => void
): Promise<SetIdentityDkimEnabledCommandOutput> | void {
const command = new SetIdentityDkimEnabledCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Given an identity (an email address or a domain), enables or disables whether Amazon SES
* forwards bounce and complaint notifications as email. Feedback forwarding can only be
* disabled when Amazon Simple Notification Service (Amazon SNS) topics are specified for both bounces and
* complaints.</p>
* <note>
* <p>Feedback forwarding does not apply to delivery notifications. Delivery
* notifications are only available through Amazon SNS.</p>
* </note>
* <p>You can execute this operation no more than once per second.</p>
* <p>For more information about using notifications with Amazon SES, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/notifications.html">Amazon SES
* Developer Guide</a>.</p>
*/
public setIdentityFeedbackForwardingEnabled(
args: SetIdentityFeedbackForwardingEnabledCommandInput,
options?: __HttpHandlerOptions
): Promise<SetIdentityFeedbackForwardingEnabledCommandOutput>;
public setIdentityFeedbackForwardingEnabled(
args: SetIdentityFeedbackForwardingEnabledCommandInput,
cb: (err: any, data?: SetIdentityFeedbackForwardingEnabledCommandOutput) => void
): void;
public setIdentityFeedbackForwardingEnabled(
args: SetIdentityFeedbackForwardingEnabledCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: SetIdentityFeedbackForwardingEnabledCommandOutput) => void
): void;
public setIdentityFeedbackForwardingEnabled(
args: SetIdentityFeedbackForwardingEnabledCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: SetIdentityFeedbackForwardingEnabledCommandOutput) => void),
cb?: (err: any, data?: SetIdentityFeedbackForwardingEnabledCommandOutput) => void
): Promise<SetIdentityFeedbackForwardingEnabledCommandOutput> | void {
const command = new SetIdentityFeedbackForwardingEnabledCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Given an identity (an email address or a domain), sets whether Amazon SES includes the
* original email headers in the Amazon Simple Notification Service (Amazon SNS) notifications of a specified
* type.</p>
* <p>You can execute this operation no more than once per second.</p>
* <p>For more information about using notifications with Amazon SES, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/notifications.html">Amazon SES
* Developer Guide</a>.</p>
*/
public setIdentityHeadersInNotificationsEnabled(
args: SetIdentityHeadersInNotificationsEnabledCommandInput,
options?: __HttpHandlerOptions
): Promise<SetIdentityHeadersInNotificationsEnabledCommandOutput>;
public setIdentityHeadersInNotificationsEnabled(
args: SetIdentityHeadersInNotificationsEnabledCommandInput,
cb: (err: any, data?: SetIdentityHeadersInNotificationsEnabledCommandOutput) => void
): void;
public setIdentityHeadersInNotificationsEnabled(
args: SetIdentityHeadersInNotificationsEnabledCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: SetIdentityHeadersInNotificationsEnabledCommandOutput) => void
): void;
public setIdentityHeadersInNotificationsEnabled(
args: SetIdentityHeadersInNotificationsEnabledCommandInput,
optionsOrCb?:
| __HttpHandlerOptions
| ((err: any, data?: SetIdentityHeadersInNotificationsEnabledCommandOutput) => void),
cb?: (err: any, data?: SetIdentityHeadersInNotificationsEnabledCommandOutput) => void
): Promise<SetIdentityHeadersInNotificationsEnabledCommandOutput> | void {
const command = new SetIdentityHeadersInNotificationsEnabledCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Enables or disables the custom MAIL FROM domain setup for a verified identity (an
* email address or a domain).</p>
* <important>
* <p>To send emails using the specified MAIL FROM domain, you must add an MX record to
* your MAIL FROM domain's DNS settings. If you want your emails to pass Sender Policy
* Framework (SPF) checks, you must also add or update an SPF record. For more
* information, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/mail-from-set.html">Amazon SES Developer
* Guide</a>.</p>
* </important>
* <p>You can execute this operation no more than once per second.</p>
*/
public setIdentityMailFromDomain(
args: SetIdentityMailFromDomainCommandInput,
options?: __HttpHandlerOptions
): Promise<SetIdentityMailFromDomainCommandOutput>;
public setIdentityMailFromDomain(
args: SetIdentityMailFromDomainCommandInput,
cb: (err: any, data?: SetIdentityMailFromDomainCommandOutput) => void
): void;
public setIdentityMailFromDomain(
args: SetIdentityMailFromDomainCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: SetIdentityMailFromDomainCommandOutput) => void
): void;
public setIdentityMailFromDomain(
args: SetIdentityMailFromDomainCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: SetIdentityMailFromDomainCommandOutput) => void),
cb?: (err: any, data?: SetIdentityMailFromDomainCommandOutput) => void
): Promise<SetIdentityMailFromDomainCommandOutput> | void {
const command = new SetIdentityMailFromDomainCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Sets an Amazon Simple Notification Service (Amazon SNS) topic to use when delivering notifications. When you use
* this operation, you specify a verified identity, such as an email address or domain.
* When you send an email that uses the chosen identity in the Source field, Amazon SES sends
* notifications to the topic you specified. You can send bounce, complaint, or delivery
* notifications (or any combination of the three) to the Amazon SNS topic that you
* specify.</p>
* <p>You can execute this operation no more than once per second.</p>
* <p>For more information about feedback notification, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/notifications.html">Amazon SES Developer
* Guide</a>.</p>
*/
public setIdentityNotificationTopic(
args: SetIdentityNotificationTopicCommandInput,
options?: __HttpHandlerOptions
): Promise<SetIdentityNotificationTopicCommandOutput>;
public setIdentityNotificationTopic(
args: SetIdentityNotificationTopicCommandInput,
cb: (err: any, data?: SetIdentityNotificationTopicCommandOutput) => void
): void;
public setIdentityNotificationTopic(
args: SetIdentityNotificationTopicCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: SetIdentityNotificationTopicCommandOutput) => void
): void;
public setIdentityNotificationTopic(
args: SetIdentityNotificationTopicCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: SetIdentityNotificationTopicCommandOutput) => void),
cb?: (err: any, data?: SetIdentityNotificationTopicCommandOutput) => void
): Promise<SetIdentityNotificationTopicCommandOutput> | void {
const command = new SetIdentityNotificationTopicCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Sets the position of the specified receipt rule in the receipt rule set.</p>
* <p>For information about managing receipt rules, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-managing-receipt-rules.html">Amazon SES
* Developer Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public setReceiptRulePosition(
args: SetReceiptRulePositionCommandInput,
options?: __HttpHandlerOptions
): Promise<SetReceiptRulePositionCommandOutput>;
public setReceiptRulePosition(
args: SetReceiptRulePositionCommandInput,
cb: (err: any, data?: SetReceiptRulePositionCommandOutput) => void
): void;
public setReceiptRulePosition(
args: SetReceiptRulePositionCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: SetReceiptRulePositionCommandOutput) => void
): void;
public setReceiptRulePosition(
args: SetReceiptRulePositionCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: SetReceiptRulePositionCommandOutput) => void),
cb?: (err: any, data?: SetReceiptRulePositionCommandOutput) => void
): Promise<SetReceiptRulePositionCommandOutput> | void {
const command = new SetReceiptRulePositionCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Creates a preview of the MIME content of an email when provided with a template and a
* set of replacement data.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public testRenderTemplate(
args: TestRenderTemplateCommandInput,
options?: __HttpHandlerOptions
): Promise<TestRenderTemplateCommandOutput>;
public testRenderTemplate(
args: TestRenderTemplateCommandInput,
cb: (err: any, data?: TestRenderTemplateCommandOutput) => void
): void;
public testRenderTemplate(
args: TestRenderTemplateCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: TestRenderTemplateCommandOutput) => void
): void;
public testRenderTemplate(
args: TestRenderTemplateCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: TestRenderTemplateCommandOutput) => void),
cb?: (err: any, data?: TestRenderTemplateCommandOutput) => void
): Promise<TestRenderTemplateCommandOutput> | void {
const command = new TestRenderTemplateCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Enables or disables email sending across your entire Amazon SES account in the current
* AWS Region. You can use this operation in conjunction with Amazon CloudWatch alarms to
* temporarily pause email sending across your Amazon SES account in a given AWS Region when
* reputation metrics (such as your bounce or complaint rates) reach certain
* thresholds.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public updateAccountSendingEnabled(
args: UpdateAccountSendingEnabledCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateAccountSendingEnabledCommandOutput>;
public updateAccountSendingEnabled(
args: UpdateAccountSendingEnabledCommandInput,
cb: (err: any, data?: UpdateAccountSendingEnabledCommandOutput) => void
): void;
public updateAccountSendingEnabled(
args: UpdateAccountSendingEnabledCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateAccountSendingEnabledCommandOutput) => void
): void;
public updateAccountSendingEnabled(
args: UpdateAccountSendingEnabledCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateAccountSendingEnabledCommandOutput) => void),
cb?: (err: any, data?: UpdateAccountSendingEnabledCommandOutput) => void
): Promise<UpdateAccountSendingEnabledCommandOutput> | void {
const command = new UpdateAccountSendingEnabledCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Updates the event destination of a configuration set. Event destinations are
* associated with configuration sets, which enable you to publish email sending events to
* Amazon CloudWatch, Amazon Kinesis Firehose, or Amazon Simple Notification Service (Amazon SNS). For information about using configuration sets,
* see <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/monitor-sending-activity.html">Monitoring Your Amazon SES
* Sending Activity</a> in the <i>Amazon SES Developer Guide.</i>
* </p>
* <note>
* <p>When you create or update an event destination, you must provide one, and only
* one, destination. The destination can be Amazon CloudWatch, Amazon Kinesis Firehose, or Amazon Simple Notification Service
* (Amazon SNS).</p>
* </note>
* <p>You can execute this operation no more than once per second.</p>
*/
public updateConfigurationSetEventDestination(
args: UpdateConfigurationSetEventDestinationCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateConfigurationSetEventDestinationCommandOutput>;
public updateConfigurationSetEventDestination(
args: UpdateConfigurationSetEventDestinationCommandInput,
cb: (err: any, data?: UpdateConfigurationSetEventDestinationCommandOutput) => void
): void;
public updateConfigurationSetEventDestination(
args: UpdateConfigurationSetEventDestinationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateConfigurationSetEventDestinationCommandOutput) => void
): void;
public updateConfigurationSetEventDestination(
args: UpdateConfigurationSetEventDestinationCommandInput,
optionsOrCb?:
| __HttpHandlerOptions
| ((err: any, data?: UpdateConfigurationSetEventDestinationCommandOutput) => void),
cb?: (err: any, data?: UpdateConfigurationSetEventDestinationCommandOutput) => void
): Promise<UpdateConfigurationSetEventDestinationCommandOutput> | void {
const command = new UpdateConfigurationSetEventDestinationCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Enables or disables the publishing of reputation metrics for emails sent using a
* specific configuration set in a given AWS Region. Reputation metrics include bounce
* and complaint rates. These metrics are published to Amazon CloudWatch. By using CloudWatch, you can
* create alarms when bounce or complaint rates exceed certain thresholds.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public updateConfigurationSetReputationMetricsEnabled(
args: UpdateConfigurationSetReputationMetricsEnabledCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateConfigurationSetReputationMetricsEnabledCommandOutput>;
public updateConfigurationSetReputationMetricsEnabled(
args: UpdateConfigurationSetReputationMetricsEnabledCommandInput,
cb: (err: any, data?: UpdateConfigurationSetReputationMetricsEnabledCommandOutput) => void
): void;
public updateConfigurationSetReputationMetricsEnabled(
args: UpdateConfigurationSetReputationMetricsEnabledCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateConfigurationSetReputationMetricsEnabledCommandOutput) => void
): void;
public updateConfigurationSetReputationMetricsEnabled(
args: UpdateConfigurationSetReputationMetricsEnabledCommandInput,
optionsOrCb?:
| __HttpHandlerOptions
| ((err: any, data?: UpdateConfigurationSetReputationMetricsEnabledCommandOutput) => void),
cb?: (err: any, data?: UpdateConfigurationSetReputationMetricsEnabledCommandOutput) => void
): Promise<UpdateConfigurationSetReputationMetricsEnabledCommandOutput> | void {
const command = new UpdateConfigurationSetReputationMetricsEnabledCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Enables or disables email sending for messages sent using a specific configuration set
* in a given AWS Region. You can use this operation in conjunction with Amazon CloudWatch alarms
* to temporarily pause email sending for a configuration set when the reputation metrics
* for that configuration set (such as your bounce on complaint rate) exceed certain
* thresholds.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public updateConfigurationSetSendingEnabled(
args: UpdateConfigurationSetSendingEnabledCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateConfigurationSetSendingEnabledCommandOutput>;
public updateConfigurationSetSendingEnabled(
args: UpdateConfigurationSetSendingEnabledCommandInput,
cb: (err: any, data?: UpdateConfigurationSetSendingEnabledCommandOutput) => void
): void;
public updateConfigurationSetSendingEnabled(
args: UpdateConfigurationSetSendingEnabledCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateConfigurationSetSendingEnabledCommandOutput) => void
): void;
public updateConfigurationSetSendingEnabled(
args: UpdateConfigurationSetSendingEnabledCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateConfigurationSetSendingEnabledCommandOutput) => void),
cb?: (err: any, data?: UpdateConfigurationSetSendingEnabledCommandOutput) => void
): Promise<UpdateConfigurationSetSendingEnabledCommandOutput> | void {
const command = new UpdateConfigurationSetSendingEnabledCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Modifies an association between a configuration set and a custom domain for open and
* click event tracking. </p>
* <p>By default, images and links used for tracking open and click events are hosted on
* domains operated by Amazon SES. You can configure a subdomain of your own to handle these
* events. For information about using custom domains, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/configure-custom-open-click-domains.html">Amazon SES Developer Guide</a>.</p>
*/
public updateConfigurationSetTrackingOptions(
args: UpdateConfigurationSetTrackingOptionsCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateConfigurationSetTrackingOptionsCommandOutput>;
public updateConfigurationSetTrackingOptions(
args: UpdateConfigurationSetTrackingOptionsCommandInput,
cb: (err: any, data?: UpdateConfigurationSetTrackingOptionsCommandOutput) => void
): void;
public updateConfigurationSetTrackingOptions(
args: UpdateConfigurationSetTrackingOptionsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateConfigurationSetTrackingOptionsCommandOutput) => void
): void;
public updateConfigurationSetTrackingOptions(
args: UpdateConfigurationSetTrackingOptionsCommandInput,
optionsOrCb?:
| __HttpHandlerOptions
| ((err: any, data?: UpdateConfigurationSetTrackingOptionsCommandOutput) => void),
cb?: (err: any, data?: UpdateConfigurationSetTrackingOptionsCommandOutput) => void
): Promise<UpdateConfigurationSetTrackingOptionsCommandOutput> | void {
const command = new UpdateConfigurationSetTrackingOptionsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Updates an existing custom verification email template.</p>
* <p>For more information about custom verification email templates, see <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/custom-verification-emails.html">Using Custom Verification Email Templates</a> in the <i>Amazon SES Developer
* Guide</i>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public updateCustomVerificationEmailTemplate(
args: UpdateCustomVerificationEmailTemplateCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateCustomVerificationEmailTemplateCommandOutput>;
public updateCustomVerificationEmailTemplate(
args: UpdateCustomVerificationEmailTemplateCommandInput,
cb: (err: any, data?: UpdateCustomVerificationEmailTemplateCommandOutput) => void
): void;
public updateCustomVerificationEmailTemplate(
args: UpdateCustomVerificationEmailTemplateCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateCustomVerificationEmailTemplateCommandOutput) => void
): void;
public updateCustomVerificationEmailTemplate(
args: UpdateCustomVerificationEmailTemplateCommandInput,
optionsOrCb?:
| __HttpHandlerOptions
| ((err: any, data?: UpdateCustomVerificationEmailTemplateCommandOutput) => void),
cb?: (err: any, data?: UpdateCustomVerificationEmailTemplateCommandOutput) => void
): Promise<UpdateCustomVerificationEmailTemplateCommandOutput> | void {
const command = new UpdateCustomVerificationEmailTemplateCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Updates a receipt rule.</p>
* <p>For information about managing receipt rules, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-managing-receipt-rules.html">Amazon SES
* Developer Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public updateReceiptRule(
args: UpdateReceiptRuleCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateReceiptRuleCommandOutput>;
public updateReceiptRule(
args: UpdateReceiptRuleCommandInput,
cb: (err: any, data?: UpdateReceiptRuleCommandOutput) => void
): void;
public updateReceiptRule(
args: UpdateReceiptRuleCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateReceiptRuleCommandOutput) => void
): void;
public updateReceiptRule(
args: UpdateReceiptRuleCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateReceiptRuleCommandOutput) => void),
cb?: (err: any, data?: UpdateReceiptRuleCommandOutput) => void
): Promise<UpdateReceiptRuleCommandOutput> | void {
const command = new UpdateReceiptRuleCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Updates an email template. Email templates enable you to send personalized email to
* one or more destinations in a single API operation. For more information, see the <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-personalized-email-api.html">Amazon SES Developer
* Guide</a>.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public updateTemplate(
args: UpdateTemplateCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateTemplateCommandOutput>;
public updateTemplate(
args: UpdateTemplateCommandInput,
cb: (err: any, data?: UpdateTemplateCommandOutput) => void
): void;
public updateTemplate(
args: UpdateTemplateCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateTemplateCommandOutput) => void
): void;
public updateTemplate(
args: UpdateTemplateCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateTemplateCommandOutput) => void),
cb?: (err: any, data?: UpdateTemplateCommandOutput) => void
): Promise<UpdateTemplateCommandOutput> | void {
const command = new UpdateTemplateCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Returns a set of DKIM tokens for a domain identity.</p>
* <important>
* <p>When you execute the <code>VerifyDomainDkim</code> operation, the domain that you
* specify is added to the list of identities that are associated with your account.
* This is true even if you haven't already associated the domain with your account by
* using the <code>VerifyDomainIdentity</code> operation. However, you can't send email
* from the domain until you either successfully <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-domains.html">verify it</a> or you
* successfully <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/easy-dkim.html">set up DKIM for
* it</a>.</p>
* </important>
* <p>You use the tokens that are generated by this operation to create CNAME records. When
* Amazon SES detects that you've added these records to the DNS configuration for a domain, you
* can start sending email from that domain. You can start sending email even if you
* haven't added the TXT record provided by the VerifyDomainIdentity operation to the DNS
* configuration for your domain. All email that you send from the domain is authenticated
* using DKIM.</p>
* <p>To create the CNAME records for DKIM authentication, use the following values:</p>
* <ul>
* <li>
* <p>
* <b>Name</b>:
* <i>token</i>._domainkey.<i>example.com</i>
* </p>
* </li>
* <li>
* <p>
* <b>Type</b>: CNAME</p>
* </li>
* <li>
* <p>
* <b>Value</b>:
* <i>token</i>.dkim.amazonses.com</p>
* </li>
* </ul>
* <p>In the preceding example, replace <i>token</i> with one of the tokens
* that are generated when you execute this operation. Replace
* <i>example.com</i> with your domain. Repeat this process for each
* token that's generated by this operation.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public verifyDomainDkim(
args: VerifyDomainDkimCommandInput,
options?: __HttpHandlerOptions
): Promise<VerifyDomainDkimCommandOutput>;
public verifyDomainDkim(
args: VerifyDomainDkimCommandInput,
cb: (err: any, data?: VerifyDomainDkimCommandOutput) => void
): void;
public verifyDomainDkim(
args: VerifyDomainDkimCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: VerifyDomainDkimCommandOutput) => void
): void;
public verifyDomainDkim(
args: VerifyDomainDkimCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: VerifyDomainDkimCommandOutput) => void),
cb?: (err: any, data?: VerifyDomainDkimCommandOutput) => void
): Promise<VerifyDomainDkimCommandOutput> | void {
const command = new VerifyDomainDkimCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Adds a domain to the list of identities for your Amazon SES account in the current AWS
* Region and attempts to verify it. For more information about verifying domains, see
* <a href="https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-addresses-and-domains.html">Verifying Email
* Addresses and Domains</a> in the <i>Amazon SES Developer
* Guide.</i>
* </p>
* <p>You can execute this operation no more than once per second.</p>
*/
public verifyDomainIdentity(
args: VerifyDomainIdentityCommandInput,
options?: __HttpHandlerOptions
): Promise<VerifyDomainIdentityCommandOutput>;
public verifyDomainIdentity(
args: VerifyDomainIdentityCommandInput,
cb: (err: any, data?: VerifyDomainIdentityCommandOutput) => void
): void;
public verifyDomainIdentity(
args: VerifyDomainIdentityCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: VerifyDomainIdentityCommandOutput) => void
): void;
public verifyDomainIdentity(
args: VerifyDomainIdentityCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: VerifyDomainIdentityCommandOutput) => void),
cb?: (err: any, data?: VerifyDomainIdentityCommandOutput) => void
): Promise<VerifyDomainIdentityCommandOutput> | void {
const command = new VerifyDomainIdentityCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Deprecated. Use the <code>VerifyEmailIdentity</code> operation to verify a new email
* address.</p>
*/
public verifyEmailAddress(
args: VerifyEmailAddressCommandInput,
options?: __HttpHandlerOptions
): Promise<VerifyEmailAddressCommandOutput>;
public verifyEmailAddress(
args: VerifyEmailAddressCommandInput,
cb: (err: any, data?: VerifyEmailAddressCommandOutput) => void
): void;
public verifyEmailAddress(
args: VerifyEmailAddressCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: VerifyEmailAddressCommandOutput) => void
): void;
public verifyEmailAddress(
args: VerifyEmailAddressCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: VerifyEmailAddressCommandOutput) => void),
cb?: (err: any, data?: VerifyEmailAddressCommandOutput) => void
): Promise<VerifyEmailAddressCommandOutput> | void {
const command = new VerifyEmailAddressCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Adds an email address to the list of identities for your Amazon SES account in the current
* AWS region and attempts to verify it. As a result of executing this operation, a
* verification email is sent to the specified address.</p>
* <p>You can execute this operation no more than once per second.</p>
*/
public verifyEmailIdentity(
args: VerifyEmailIdentityCommandInput,
options?: __HttpHandlerOptions
): Promise<VerifyEmailIdentityCommandOutput>;
public verifyEmailIdentity(
args: VerifyEmailIdentityCommandInput,
cb: (err: any, data?: VerifyEmailIdentityCommandOutput) => void
): void;
public verifyEmailIdentity(
args: VerifyEmailIdentityCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: VerifyEmailIdentityCommandOutput) => void
): void;
public verifyEmailIdentity(
args: VerifyEmailIdentityCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: VerifyEmailIdentityCommandOutput) => void),
cb?: (err: any, data?: VerifyEmailIdentityCommandOutput) => void
): Promise<VerifyEmailIdentityCommandOutput> | void {
const command = new VerifyEmailIdentityCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
} | the_stack |
import * as coreClient from "@azure/core-client";
import * as Parameters from "./models/parameters";
import * as Mappers from "./models/mappers";
import {
ModelFlatteningClientOptionalParams,
PutArrayOptionalParams,
GetArrayOptionalParams,
GetArrayResponse,
PutWrappedArrayOptionalParams,
GetWrappedArrayOptionalParams,
GetWrappedArrayResponse,
PutDictionaryOptionalParams,
GetDictionaryOptionalParams,
GetDictionaryResponse,
PutResourceCollectionOptionalParams,
GetResourceCollectionOptionalParams,
GetResourceCollectionResponse,
PutSimpleProductOptionalParams,
PutSimpleProductResponse,
PostFlattenedSimpleProductOptionalParams,
PostFlattenedSimpleProductResponse,
FlattenParameterGroup,
PutSimpleProductWithGroupingOptionalParams,
PutSimpleProductWithGroupingResponse
} from "./models";
export class ModelFlatteningClient extends coreClient.ServiceClient {
$host: string;
/**
* Initializes a new instance of the ModelFlatteningClient class.
* @param options The parameter options
*/
constructor(options?: ModelFlatteningClientOptionalParams) {
// Initializing default values for options
if (!options) {
options = {};
}
const defaults: ModelFlatteningClientOptionalParams = {
requestContentType: "application/json; charset=utf-8"
};
const packageDetails = `azsdk-js-model-flattening/1.0.0-preview1`;
const userAgentPrefix =
options.userAgentOptions && options.userAgentOptions.userAgentPrefix
? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}`
: `${packageDetails}`;
const optionsWithDefaults = {
...defaults,
...options,
userAgentOptions: {
userAgentPrefix
},
baseUri: options.endpoint || "http://localhost:3000"
};
super(optionsWithDefaults);
// Assigning values to Constant parameters
this.$host = options.$host || "http://localhost:3000";
}
/**
* Put External Resource as an Array
* @param options The options parameters.
*/
putArray(options?: PutArrayOptionalParams): Promise<void> {
return this.sendOperationRequest({ options }, putArrayOperationSpec);
}
/**
* Get External Resource as an Array
* @param options The options parameters.
*/
getArray(options?: GetArrayOptionalParams): Promise<GetArrayResponse> {
return this.sendOperationRequest({ options }, getArrayOperationSpec);
}
/**
* No need to have a route in Express server for this operation. Used to verify the type flattened is
* not removed if it's referenced in an array
* @param options The options parameters.
*/
putWrappedArray(options?: PutWrappedArrayOptionalParams): Promise<void> {
return this.sendOperationRequest({ options }, putWrappedArrayOperationSpec);
}
/**
* No need to have a route in Express server for this operation. Used to verify the type flattened is
* not removed if it's referenced in an array
* @param options The options parameters.
*/
getWrappedArray(
options?: GetWrappedArrayOptionalParams
): Promise<GetWrappedArrayResponse> {
return this.sendOperationRequest({ options }, getWrappedArrayOperationSpec);
}
/**
* Put External Resource as a Dictionary
* @param options The options parameters.
*/
putDictionary(options?: PutDictionaryOptionalParams): Promise<void> {
return this.sendOperationRequest({ options }, putDictionaryOperationSpec);
}
/**
* Get External Resource as a Dictionary
* @param options The options parameters.
*/
getDictionary(
options?: GetDictionaryOptionalParams
): Promise<GetDictionaryResponse> {
return this.sendOperationRequest({ options }, getDictionaryOperationSpec);
}
/**
* Put External Resource as a ResourceCollection
* @param options The options parameters.
*/
putResourceCollection(
options?: PutResourceCollectionOptionalParams
): Promise<void> {
return this.sendOperationRequest(
{ options },
putResourceCollectionOperationSpec
);
}
/**
* Get External Resource as a ResourceCollection
* @param options The options parameters.
*/
getResourceCollection(
options?: GetResourceCollectionOptionalParams
): Promise<GetResourceCollectionResponse> {
return this.sendOperationRequest(
{ options },
getResourceCollectionOperationSpec
);
}
/**
* Put Simple Product with client flattening true on the model
* @param options The options parameters.
*/
putSimpleProduct(
options?: PutSimpleProductOptionalParams
): Promise<PutSimpleProductResponse> {
return this.sendOperationRequest(
{ options },
putSimpleProductOperationSpec
);
}
/**
* Put Flattened Simple Product with client flattening true on the parameter
* @param productId Unique identifier representing a specific product for a given latitude & longitude.
* For example, uberX in San Francisco will have a different product_id than uberX in Los Angeles.
* @param options The options parameters.
*/
postFlattenedSimpleProduct(
productId: string,
options?: PostFlattenedSimpleProductOptionalParams
): Promise<PostFlattenedSimpleProductResponse> {
return this.sendOperationRequest(
{ productId, options },
postFlattenedSimpleProductOperationSpec
);
}
/**
* Put Simple Product with client flattening true on the model
* @param flattenParameterGroup Parameter group
* @param options The options parameters.
*/
putSimpleProductWithGrouping(
flattenParameterGroup: FlattenParameterGroup,
options?: PutSimpleProductWithGroupingOptionalParams
): Promise<PutSimpleProductWithGroupingResponse> {
return this.sendOperationRequest(
{ flattenParameterGroup, options },
putSimpleProductWithGroupingOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const putArrayOperationSpec: coreClient.OperationSpec = {
path: "/model-flatten/array",
httpMethod: "PUT",
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
requestBody: Parameters.resourceArray,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const getArrayOperationSpec: coreClient.OperationSpec = {
path: "/model-flatten/array",
httpMethod: "GET",
responses: {
200: {
bodyMapper: {
type: {
name: "Sequence",
element: {
type: { name: "Composite", className: "FlattenedProduct" }
}
}
}
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const putWrappedArrayOperationSpec: coreClient.OperationSpec = {
path: "/model-flatten/wrappedarray",
httpMethod: "PUT",
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
requestBody: Parameters.resourceArray1,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const getWrappedArrayOperationSpec: coreClient.OperationSpec = {
path: "/model-flatten/wrappedarray",
httpMethod: "GET",
responses: {
200: {
bodyMapper: {
type: {
name: "Sequence",
element: { type: { name: "Composite", className: "ProductWrapper" } }
}
}
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const putDictionaryOperationSpec: coreClient.OperationSpec = {
path: "/model-flatten/dictionary",
httpMethod: "PUT",
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
requestBody: Parameters.resourceDictionary,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const getDictionaryOperationSpec: coreClient.OperationSpec = {
path: "/model-flatten/dictionary",
httpMethod: "GET",
responses: {
200: {
bodyMapper: {
type: {
name: "Dictionary",
value: { type: { name: "Composite", className: "FlattenedProduct" } }
}
}
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const putResourceCollectionOperationSpec: coreClient.OperationSpec = {
path: "/model-flatten/resourcecollection",
httpMethod: "PUT",
responses: {
200: {},
default: {
bodyMapper: Mappers.ErrorModel
}
},
requestBody: Parameters.resourceComplexObject,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const getResourceCollectionOperationSpec: coreClient.OperationSpec = {
path: "/model-flatten/resourcecollection",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.ResourceCollection
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.accept],
serializer
};
const putSimpleProductOperationSpec: coreClient.OperationSpec = {
path: "/model-flatten/customFlattening",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.SimpleProduct
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
requestBody: Parameters.simpleBodyProduct,
urlParameters: [Parameters.$host],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const postFlattenedSimpleProductOperationSpec: coreClient.OperationSpec = {
path: "/model-flatten/customFlattening",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.SimpleProduct
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
requestBody: {
parameterPath: {
productId: ["productId"],
description: ["options", "description"],
maxProductDisplayName: ["options", "maxProductDisplayName"],
capacity: ["options", "capacity"],
genericValue: ["options", "genericValue"],
odataValue: ["options", "odataValue"]
},
mapper: { ...Mappers.SimpleProduct, required: true }
},
urlParameters: [Parameters.$host],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const putSimpleProductWithGroupingOperationSpec: coreClient.OperationSpec = {
path: "/model-flatten/customFlattening/parametergrouping/{name}/",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.SimpleProduct
},
default: {
bodyMapper: Mappers.ErrorModel
}
},
requestBody: {
parameterPath: {
productId: ["flattenParameterGroup", "productId"],
description: ["flattenParameterGroup", "description"],
maxProductDisplayName: ["flattenParameterGroup", "maxProductDisplayName"],
capacity: ["flattenParameterGroup", "capacity"],
genericValue: ["flattenParameterGroup", "genericValue"],
odataValue: ["flattenParameterGroup", "odataValue"]
},
mapper: { ...Mappers.SimpleProduct, required: true }
},
urlParameters: [Parameters.$host, Parameters.name],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
}; | the_stack |
namespace ts {
export enum LogLevel {
Off,
Error,
Warning,
Info,
Verbose
}
export interface LoggingHost {
log(level: LogLevel, s: string): void;
}
export interface DeprecationOptions {
message?: string;
error?: boolean;
since?: Version | string;
warnAfter?: Version | string;
errorAfter?: Version | string;
typeScriptVersion?: Version | string;
}
export namespace Debug {
let typeScriptVersion: Version | undefined;
/* eslint-disable prefer-const */
let currentAssertionLevel = AssertionLevel.None;
export let currentLogLevel = LogLevel.Warning;
export let isDebugging = false;
export let loggingHost: LoggingHost | undefined;
/* eslint-enable prefer-const */
type AssertionKeys = MatchingKeys<typeof Debug, AnyFunction>;
export function getTypeScriptVersion() {
return typeScriptVersion ?? (typeScriptVersion = new Version(version));
}
export function shouldLog(level: LogLevel): boolean {
return currentLogLevel <= level;
}
function logMessage(level: LogLevel, s: string): void {
if (loggingHost && shouldLog(level)) {
loggingHost.log(level, s);
}
}
export function log(s: string): void {
logMessage(LogLevel.Info, s);
}
export namespace log {
export function error(s: string): void {
logMessage(LogLevel.Error, s);
}
export function warn(s: string): void {
logMessage(LogLevel.Warning, s);
}
export function log(s: string): void {
logMessage(LogLevel.Info, s);
}
export function trace(s: string): void {
logMessage(LogLevel.Verbose, s);
}
}
const assertionCache: Partial<Record<AssertionKeys, { level: AssertionLevel, assertion: AnyFunction }>> = {};
export function getAssertionLevel() {
return currentAssertionLevel;
}
export function setAssertionLevel(level: AssertionLevel) {
const prevAssertionLevel = currentAssertionLevel;
currentAssertionLevel = level;
if (level > prevAssertionLevel) {
// restore assertion functions for the current assertion level (see `shouldAssertFunction`).
for (const key of getOwnKeys(assertionCache) as AssertionKeys[]) {
const cachedFunc = assertionCache[key];
if (cachedFunc !== undefined && Debug[key] !== cachedFunc.assertion && level >= cachedFunc.level) {
(Debug as any)[key] = cachedFunc;
assertionCache[key] = undefined;
}
}
}
}
export function shouldAssert(level: AssertionLevel): boolean {
return currentAssertionLevel >= level;
}
/**
* Tests whether an assertion function should be executed. If it shouldn't, it is cached and replaced with `ts.noop`.
* Replaced assertion functions are restored when `Debug.setAssertionLevel` is set to a high enough level.
* @param level The minimum assertion level required.
* @param name The name of the current assertion function.
*/
function shouldAssertFunction<K extends AssertionKeys>(level: AssertionLevel, name: K): boolean {
if (!shouldAssert(level)) {
assertionCache[name] = { level, assertion: Debug[name] };
(Debug as any)[name] = noop;
return false;
}
return true;
}
export function fail(message?: string, stackCrawlMark?: AnyFunction): never {
debugger;
const e = new Error(message ? `Debug Failure. ${message}` : "Debug Failure.");
if ((Error as any).captureStackTrace) {
(Error as any).captureStackTrace(e, stackCrawlMark || fail);
}
throw e;
}
export function failBadSyntaxKind(node: Node, message?: string, stackCrawlMark?: AnyFunction): never {
return fail(
`${message || "Unexpected node."}\r\nNode ${formatSyntaxKind(node.kind)} was unexpected.`,
stackCrawlMark || failBadSyntaxKind);
}
export function assert(expression: unknown, message?: string, verboseDebugInfo?: string | (() => string), stackCrawlMark?: AnyFunction): asserts expression {
if (!expression) {
message = message ? `False expression: ${message}` : "False expression.";
if (verboseDebugInfo) {
message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo());
}
fail(message, stackCrawlMark || assert);
}
}
export function assertEqual<T>(a: T, b: T, msg?: string, msg2?: string, stackCrawlMark?: AnyFunction): void {
if (a !== b) {
const message = msg ? msg2 ? `${msg} ${msg2}` : msg : "";
fail(`Expected ${a} === ${b}. ${message}`, stackCrawlMark || assertEqual);
}
}
export function assertLessThan(a: number, b: number, msg?: string, stackCrawlMark?: AnyFunction): void {
if (a >= b) {
fail(`Expected ${a} < ${b}. ${msg || ""}`, stackCrawlMark || assertLessThan);
}
}
export function assertLessThanOrEqual(a: number, b: number, stackCrawlMark?: AnyFunction): void {
if (a > b) {
fail(`Expected ${a} <= ${b}`, stackCrawlMark || assertLessThanOrEqual);
}
}
export function assertGreaterThanOrEqual(a: number, b: number, stackCrawlMark?: AnyFunction): void {
if (a < b) {
fail(`Expected ${a} >= ${b}`, stackCrawlMark || assertGreaterThanOrEqual);
}
}
export function assertIsDefined<T>(value: T, message?: string, stackCrawlMark?: AnyFunction): asserts value is NonNullable<T> {
// eslint-disable-next-line no-null/no-null
if (value === undefined || value === null) {
fail(message, stackCrawlMark || assertIsDefined);
}
}
export function checkDefined<T>(value: T | null | undefined, message?: string, stackCrawlMark?: AnyFunction): T {
assertIsDefined(value, message, stackCrawlMark || checkDefined);
return value;
}
export function assertEachIsDefined<T extends Node>(value: NodeArray<T>, message?: string, stackCrawlMark?: AnyFunction): asserts value is NodeArray<T>;
export function assertEachIsDefined<T>(value: readonly T[], message?: string, stackCrawlMark?: AnyFunction): asserts value is readonly NonNullable<T>[];
export function assertEachIsDefined<T>(value: readonly T[], message?: string, stackCrawlMark?: AnyFunction) {
for (const v of value) {
assertIsDefined(v, message, stackCrawlMark || assertEachIsDefined);
}
}
export function checkEachDefined<T, A extends readonly T[]>(value: A, message?: string, stackCrawlMark?: AnyFunction): A {
assertEachIsDefined(value, message, stackCrawlMark || checkEachDefined);
return value;
}
export function assertNever(member: never, message = "Illegal value:", stackCrawlMark?: AnyFunction): never {
const detail = typeof member === "object" && hasProperty(member, "kind") && hasProperty(member, "pos") && formatSyntaxKind ? "SyntaxKind: " + formatSyntaxKind((member as Node).kind) : JSON.stringify(member);
return fail(`${message} ${detail}`, stackCrawlMark || assertNever);
}
export function assertEachNode<T extends Node, U extends T>(nodes: NodeArray<T>, test: (node: T) => node is U, message?: string, stackCrawlMark?: AnyFunction): asserts nodes is NodeArray<U>;
export function assertEachNode<T extends Node, U extends T>(nodes: readonly T[], test: (node: T) => node is U, message?: string, stackCrawlMark?: AnyFunction): asserts nodes is readonly U[];
export function assertEachNode(nodes: readonly Node[], test: (node: Node) => boolean, message?: string, stackCrawlMark?: AnyFunction): void;
export function assertEachNode(nodes: readonly Node[], test: (node: Node) => boolean, message?: string, stackCrawlMark?: AnyFunction) {
if (shouldAssertFunction(AssertionLevel.Normal, "assertEachNode")) {
assert(
test === undefined || every(nodes, test),
message || "Unexpected node.",
() => `Node array did not pass test '${getFunctionName(test)}'.`,
stackCrawlMark || assertEachNode);
}
}
export function assertNode<T extends Node, U extends T>(node: T | undefined, test: (node: T) => node is U, message?: string, stackCrawlMark?: AnyFunction): asserts node is U;
export function assertNode(node: Node | undefined, test: ((node: Node) => boolean) | undefined, message?: string, stackCrawlMark?: AnyFunction): void;
export function assertNode(node: Node | undefined, test: ((node: Node) => boolean) | undefined, message?: string, stackCrawlMark?: AnyFunction) {
if (shouldAssertFunction(AssertionLevel.Normal, "assertNode")) {
assert(
node !== undefined && (test === undefined || test(node)),
message || "Unexpected node.",
() => `Node ${formatSyntaxKind(node?.kind)} did not pass test '${getFunctionName(test!)}'.`,
stackCrawlMark || assertNode);
}
}
export function assertNotNode<T extends Node, U extends T>(node: T | undefined, test: (node: Node) => node is U, message?: string, stackCrawlMark?: AnyFunction): asserts node is Exclude<T, U>;
export function assertNotNode(node: Node | undefined, test: ((node: Node) => boolean) | undefined, message?: string, stackCrawlMark?: AnyFunction): void;
export function assertNotNode(node: Node | undefined, test: ((node: Node) => boolean) | undefined, message?: string, stackCrawlMark?: AnyFunction) {
if (shouldAssertFunction(AssertionLevel.Normal, "assertNotNode")) {
assert(
node === undefined || test === undefined || !test(node),
message || "Unexpected node.",
() => `Node ${formatSyntaxKind(node!.kind)} should not have passed test '${getFunctionName(test!)}'.`,
stackCrawlMark || assertNotNode);
}
}
export function assertOptionalNode<T extends Node, U extends T>(node: T, test: (node: T) => node is U, message?: string, stackCrawlMark?: AnyFunction): asserts node is U;
export function assertOptionalNode<T extends Node, U extends T>(node: T | undefined, test: (node: T) => node is U, message?: string, stackCrawlMark?: AnyFunction): asserts node is U | undefined;
export function assertOptionalNode(node: Node | undefined, test: ((node: Node) => boolean) | undefined, message?: string, stackCrawlMark?: AnyFunction): void;
export function assertOptionalNode(node: Node | undefined, test: ((node: Node) => boolean) | undefined, message?: string, stackCrawlMark?: AnyFunction) {
if (shouldAssertFunction(AssertionLevel.Normal, "assertOptionalNode")) {
assert(
test === undefined || node === undefined || test(node),
message || "Unexpected node.",
() => `Node ${formatSyntaxKind(node?.kind)} did not pass test '${getFunctionName(test!)}'.`,
stackCrawlMark || assertOptionalNode);
}
}
export function assertOptionalToken<T extends Node, K extends SyntaxKind>(node: T, kind: K, message?: string, stackCrawlMark?: AnyFunction): asserts node is Extract<T, { readonly kind: K }>;
export function assertOptionalToken<T extends Node, K extends SyntaxKind>(node: T | undefined, kind: K, message?: string, stackCrawlMark?: AnyFunction): asserts node is Extract<T, { readonly kind: K }> | undefined;
export function assertOptionalToken(node: Node | undefined, kind: SyntaxKind | undefined, message?: string, stackCrawlMark?: AnyFunction): void;
export function assertOptionalToken(node: Node | undefined, kind: SyntaxKind | undefined, message?: string, stackCrawlMark?: AnyFunction) {
if (shouldAssertFunction(AssertionLevel.Normal, "assertOptionalToken")) {
assert(
kind === undefined || node === undefined || node.kind === kind,
message || "Unexpected node.",
() => `Node ${formatSyntaxKind(node?.kind)} was not a '${formatSyntaxKind(kind)}' token.`,
stackCrawlMark || assertOptionalToken);
}
}
export function assertMissingNode(node: Node | undefined, message?: string, stackCrawlMark?: AnyFunction): asserts node is undefined;
export function assertMissingNode(node: Node | undefined, message?: string, stackCrawlMark?: AnyFunction) {
if (shouldAssertFunction(AssertionLevel.Normal, "assertMissingNode")) {
assert(
node === undefined,
message || "Unexpected node.",
() => `Node ${formatSyntaxKind(node!.kind)} was unexpected'.`,
stackCrawlMark || assertMissingNode);
}
}
/**
* Asserts a value has the specified type in typespace only (does not perform a runtime assertion).
* This is useful in cases where we switch on `node.kind` and can be reasonably sure the type is accurate, and
* as a result can reduce the number of unnecessary casts.
*/
export function type<T>(value: unknown): asserts value is T;
export function type(_value: unknown) { }
export function getFunctionName(func: AnyFunction) {
if (typeof func !== "function") {
return "";
}
else if (func.hasOwnProperty("name")) {
return (func as any).name;
}
else {
const text = Function.prototype.toString.call(func);
const match = /^function\s+([\w\$]+)\s*\(/.exec(text);
return match ? match[1] : "";
}
}
export function formatSymbol(symbol: Symbol): string {
return `{ name: ${unescapeLeadingUnderscores(symbol.escapedName)}; flags: ${formatSymbolFlags(symbol.flags)}; declarations: ${map(symbol.declarations, node => formatSyntaxKind(node.kind))} }`;
}
/**
* Formats an enum value as a string for debugging and debug assertions.
*/
export function formatEnum(value = 0, enumObject: any, isFlags?: boolean) {
const members = getEnumMembers(enumObject);
if (value === 0) {
return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0";
}
if (isFlags) {
let result = "";
let remainingFlags = value;
for (const [enumValue, enumName] of members) {
if (enumValue > value) {
break;
}
if (enumValue !== 0 && enumValue & value) {
result = `${result}${result ? "|" : ""}${enumName}`;
remainingFlags &= ~enumValue;
}
}
if (remainingFlags === 0) {
return result;
}
}
else {
for (const [enumValue, enumName] of members) {
if (enumValue === value) {
return enumName;
}
}
}
return value.toString();
}
function getEnumMembers(enumObject: any) {
const result: [number, string][] = [];
for (const name in enumObject) {
const value = enumObject[name];
if (typeof value === "number") {
result.push([value, name]);
}
}
return stableSort<[number, string]>(result, (x, y) => compareValues(x[0], y[0]));
}
export function formatSyntaxKind(kind: SyntaxKind | undefined): string {
return formatEnum(kind, (ts as any).SyntaxKind, /*isFlags*/ false);
}
export function formatSnippetKind(kind: SnippetKind | undefined): string {
return formatEnum(kind, (ts as any).SnippetKind, /*isFlags*/ false);
}
export function formatNodeFlags(flags: NodeFlags | undefined): string {
return formatEnum(flags, (ts as any).NodeFlags, /*isFlags*/ true);
}
export function formatModifierFlags(flags: ModifierFlags | undefined): string {
return formatEnum(flags, (ts as any).ModifierFlags, /*isFlags*/ true);
}
export function formatTransformFlags(flags: TransformFlags | undefined): string {
return formatEnum(flags, (ts as any).TransformFlags, /*isFlags*/ true);
}
export function formatEmitFlags(flags: EmitFlags | undefined): string {
return formatEnum(flags, (ts as any).EmitFlags, /*isFlags*/ true);
}
export function formatSymbolFlags(flags: SymbolFlags | undefined): string {
return formatEnum(flags, (ts as any).SymbolFlags, /*isFlags*/ true);
}
export function formatTypeFlags(flags: TypeFlags | undefined): string {
return formatEnum(flags, (ts as any).TypeFlags, /*isFlags*/ true);
}
export function formatSignatureFlags(flags: SignatureFlags | undefined): string {
return formatEnum(flags, (ts as any).SignatureFlags, /*isFlags*/ true);
}
export function formatObjectFlags(flags: ObjectFlags | undefined): string {
return formatEnum(flags, (ts as any).ObjectFlags, /*isFlags*/ true);
}
export function formatFlowFlags(flags: FlowFlags | undefined): string {
return formatEnum(flags, (ts as any).FlowFlags, /*isFlags*/ true);
}
let isDebugInfoEnabled = false;
interface ExtendedDebugModule {
init(_ts: typeof ts): void;
formatControlFlowGraph(flowNode: FlowNode): string;
}
let extendedDebugModule: ExtendedDebugModule | undefined;
function extendedDebug() {
enableDebugInfo();
if (!extendedDebugModule) {
throw new Error("Debugging helpers could not be loaded.");
}
return extendedDebugModule;
}
export function printControlFlowGraph(flowNode: FlowNode) {
return console.log(formatControlFlowGraph(flowNode));
}
export function formatControlFlowGraph(flowNode: FlowNode) {
return extendedDebug().formatControlFlowGraph(flowNode);
}
let flowNodeProto: FlowNodeBase | undefined;
function attachFlowNodeDebugInfoWorker(flowNode: FlowNodeBase) {
if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line no-in-operator
Object.defineProperties(flowNode, {
// for use with vscode-js-debug's new customDescriptionGenerator in launch.json
__tsDebuggerDisplay: {
value(this: FlowNodeBase) {
const flowHeader =
this.flags & FlowFlags.Start ? "FlowStart" :
this.flags & FlowFlags.BranchLabel ? "FlowBranchLabel" :
this.flags & FlowFlags.LoopLabel ? "FlowLoopLabel" :
this.flags & FlowFlags.Assignment ? "FlowAssignment" :
this.flags & FlowFlags.TrueCondition ? "FlowTrueCondition" :
this.flags & FlowFlags.FalseCondition ? "FlowFalseCondition" :
this.flags & FlowFlags.SwitchClause ? "FlowSwitchClause" :
this.flags & FlowFlags.ArrayMutation ? "FlowArrayMutation" :
this.flags & FlowFlags.Call ? "FlowCall" :
this.flags & FlowFlags.ReduceLabel ? "FlowReduceLabel" :
this.flags & FlowFlags.Unreachable ? "FlowUnreachable" :
"UnknownFlow";
const remainingFlags = this.flags & ~(FlowFlags.Referenced - 1);
return `${flowHeader}${remainingFlags ? ` (${formatFlowFlags(remainingFlags)})`: ""}`;
}
},
__debugFlowFlags: { get(this: FlowNodeBase) { return formatEnum(this.flags, (ts as any).FlowFlags, /*isFlags*/ true); } },
__debugToString: { value(this: FlowNodeBase) { return formatControlFlowGraph(this); } }
});
}
}
export function attachFlowNodeDebugInfo(flowNode: FlowNodeBase) {
if (isDebugInfoEnabled) {
if (typeof Object.setPrototypeOf === "function") {
// if we're in es2015, attach the method to a shared prototype for `FlowNode`
// so the method doesn't show up in the watch window.
if (!flowNodeProto) {
flowNodeProto = Object.create(Object.prototype) as FlowNodeBase;
attachFlowNodeDebugInfoWorker(flowNodeProto);
}
Object.setPrototypeOf(flowNode, flowNodeProto);
}
else {
// not running in an es2015 environment, attach the method directly.
attachFlowNodeDebugInfoWorker(flowNode);
}
}
}
let nodeArrayProto: NodeArray<Node> | undefined;
function attachNodeArrayDebugInfoWorker(array: NodeArray<Node>) {
if (!("__tsDebuggerDisplay" in array)) { // eslint-disable-line no-in-operator
Object.defineProperties(array, {
__tsDebuggerDisplay: {
value(this: NodeArray<Node>, defaultValue: string) {
// An `Array` with extra properties is rendered as `[A, B, prop1: 1, prop2: 2]`. Most of
// these aren't immediately useful so we trim off the `prop1: ..., prop2: ...` part from the
// formatted string.
// This regex can trigger slow backtracking because of overlapping potential captures.
// We don't care, this is debug code that's only enabled with a debugger attached -
// we're just taking note of it for anyone checking regex performance in the future.
defaultValue = String(defaultValue).replace(/(?:,[\s\w\d_]+:[^,]+)+\]$/, "]");
return `NodeArray ${defaultValue}`;
}
}
});
}
}
export function attachNodeArrayDebugInfo(array: NodeArray<Node>) {
if (isDebugInfoEnabled) {
if (typeof Object.setPrototypeOf === "function") {
// if we're in es2015, attach the method to a shared prototype for `NodeArray`
// so the method doesn't show up in the watch window.
if (!nodeArrayProto) {
nodeArrayProto = Object.create(Array.prototype) as NodeArray<Node>;
attachNodeArrayDebugInfoWorker(nodeArrayProto);
}
Object.setPrototypeOf(array, nodeArrayProto);
}
else {
// not running in an es2015 environment, attach the method directly.
attachNodeArrayDebugInfoWorker(array);
}
}
}
/**
* Injects debug information into frequently used types.
*/
export function enableDebugInfo() {
if (isDebugInfoEnabled) return;
// avoid recomputing
let weakTypeTextMap: WeakMap<Type, string> | undefined;
let weakNodeTextMap: WeakMap<Node, string> | undefined;
function getWeakTypeTextMap() {
if (weakTypeTextMap === undefined) {
if (typeof WeakMap === "function") weakTypeTextMap = new WeakMap();
}
return weakTypeTextMap;
}
function getWeakNodeTextMap() {
if (weakNodeTextMap === undefined) {
if (typeof WeakMap === "function") weakNodeTextMap = new WeakMap();
}
return weakNodeTextMap;
}
// Add additional properties in debug mode to assist with debugging.
Object.defineProperties(objectAllocator.getSymbolConstructor().prototype, {
// for use with vscode-js-debug's new customDescriptionGenerator in launch.json
__tsDebuggerDisplay: {
value(this: Symbol) {
const symbolHeader =
this.flags & SymbolFlags.Transient ? "TransientSymbol" :
"Symbol";
const remainingSymbolFlags = this.flags & ~SymbolFlags.Transient;
return `${symbolHeader} '${symbolName(this)}'${remainingSymbolFlags ? ` (${formatSymbolFlags(remainingSymbolFlags)})` : ""}`;
}
},
__debugFlags: { get(this: Symbol) { return formatSymbolFlags(this.flags); } }
});
Object.defineProperties(objectAllocator.getTypeConstructor().prototype, {
// for use with vscode-js-debug's new customDescriptionGenerator in launch.json
__tsDebuggerDisplay: {
value(this: Type) {
const typeHeader =
this.flags & TypeFlags.Nullable ? "NullableType" :
this.flags & TypeFlags.StringOrNumberLiteral ? `LiteralType ${JSON.stringify((this as LiteralType).value)}` :
this.flags & TypeFlags.BigIntLiteral ? `LiteralType ${(this as BigIntLiteralType).value.negative ? "-" : ""}${(this as BigIntLiteralType).value.base10Value}n` :
this.flags & TypeFlags.UniqueESSymbol ? "UniqueESSymbolType" :
this.flags & TypeFlags.Enum ? "EnumType" :
this.flags & TypeFlags.Intrinsic ? `IntrinsicType ${(this as IntrinsicType).intrinsicName}` :
this.flags & TypeFlags.Union ? "UnionType" :
this.flags & TypeFlags.Intersection ? "IntersectionType" :
this.flags & TypeFlags.Index ? "IndexType" :
this.flags & TypeFlags.IndexedAccess ? "IndexedAccessType" :
this.flags & TypeFlags.Conditional ? "ConditionalType" :
this.flags & TypeFlags.Substitution ? "SubstitutionType" :
this.flags & TypeFlags.TypeParameter ? "TypeParameter" :
this.flags & TypeFlags.Object ?
(this as ObjectType).objectFlags & ObjectFlags.ClassOrInterface ? "InterfaceType" :
(this as ObjectType).objectFlags & ObjectFlags.Reference ? "TypeReference" :
(this as ObjectType).objectFlags & ObjectFlags.Tuple ? "TupleType" :
(this as ObjectType).objectFlags & ObjectFlags.Anonymous ? "AnonymousType" :
(this as ObjectType).objectFlags & ObjectFlags.Mapped ? "MappedType" :
(this as ObjectType).objectFlags & ObjectFlags.ReverseMapped ? "ReverseMappedType" :
(this as ObjectType).objectFlags & ObjectFlags.EvolvingArray ? "EvolvingArrayType" :
"ObjectType" :
"Type";
const remainingObjectFlags = this.flags & TypeFlags.Object ? (this as ObjectType).objectFlags & ~ObjectFlags.ObjectTypeKindMask : 0;
return `${typeHeader}${this.symbol ? ` '${symbolName(this.symbol)}'` : ""}${remainingObjectFlags ? ` (${formatObjectFlags(remainingObjectFlags)})` : ""}`;
}
},
__debugFlags: { get(this: Type) { return formatTypeFlags(this.flags); } },
__debugObjectFlags: { get(this: Type) { return this.flags & TypeFlags.Object ? formatObjectFlags((this as ObjectType).objectFlags) : ""; } },
__debugTypeToString: {
value(this: Type) {
// avoid recomputing
const map = getWeakTypeTextMap();
let text = map?.get(this);
if (text === undefined) {
text = this.checker.typeToString(this);
map?.set(this, text);
}
return text;
}
},
});
Object.defineProperties(objectAllocator.getSignatureConstructor().prototype, {
__debugFlags: { get(this: Signature) { return formatSignatureFlags(this.flags); } },
__debugSignatureToString: { value(this: Signature) { return this.checker?.signatureToString(this); } }
});
const nodeConstructors = [
objectAllocator.getNodeConstructor(),
objectAllocator.getIdentifierConstructor(),
objectAllocator.getTokenConstructor(),
objectAllocator.getSourceFileConstructor()
];
for (const ctor of nodeConstructors) {
if (!ctor.prototype.hasOwnProperty("__debugKind")) {
Object.defineProperties(ctor.prototype, {
// for use with vscode-js-debug's new customDescriptionGenerator in launch.json
__tsDebuggerDisplay: {
value(this: Node) {
const nodeHeader =
isGeneratedIdentifier(this) ? "GeneratedIdentifier" :
isIdentifier(this) ? `Identifier '${idText(this)}'` :
isPrivateIdentifier(this) ? `PrivateIdentifier '${idText(this)}'` :
isStringLiteral(this) ? `StringLiteral ${JSON.stringify(this.text.length < 10 ? this.text : this.text.slice(10) + "...")}` :
isNumericLiteral(this) ? `NumericLiteral ${this.text}` :
isBigIntLiteral(this) ? `BigIntLiteral ${this.text}n` :
isTypeParameterDeclaration(this) ? "TypeParameterDeclaration" :
isParameter(this) ? "ParameterDeclaration" :
isConstructorDeclaration(this) ? "ConstructorDeclaration" :
isGetAccessorDeclaration(this) ? "GetAccessorDeclaration" :
isSetAccessorDeclaration(this) ? "SetAccessorDeclaration" :
isCallSignatureDeclaration(this) ? "CallSignatureDeclaration" :
isConstructSignatureDeclaration(this) ? "ConstructSignatureDeclaration" :
isIndexSignatureDeclaration(this) ? "IndexSignatureDeclaration" :
isTypePredicateNode(this) ? "TypePredicateNode" :
isTypeReferenceNode(this) ? "TypeReferenceNode" :
isFunctionTypeNode(this) ? "FunctionTypeNode" :
isConstructorTypeNode(this) ? "ConstructorTypeNode" :
isTypeQueryNode(this) ? "TypeQueryNode" :
isTypeLiteralNode(this) ? "TypeLiteralNode" :
isArrayTypeNode(this) ? "ArrayTypeNode" :
isTupleTypeNode(this) ? "TupleTypeNode" :
isOptionalTypeNode(this) ? "OptionalTypeNode" :
isRestTypeNode(this) ? "RestTypeNode" :
isUnionTypeNode(this) ? "UnionTypeNode" :
isIntersectionTypeNode(this) ? "IntersectionTypeNode" :
isConditionalTypeNode(this) ? "ConditionalTypeNode" :
isInferTypeNode(this) ? "InferTypeNode" :
isParenthesizedTypeNode(this) ? "ParenthesizedTypeNode" :
isThisTypeNode(this) ? "ThisTypeNode" :
isTypeOperatorNode(this) ? "TypeOperatorNode" :
isIndexedAccessTypeNode(this) ? "IndexedAccessTypeNode" :
isMappedTypeNode(this) ? "MappedTypeNode" :
isLiteralTypeNode(this) ? "LiteralTypeNode" :
isNamedTupleMember(this) ? "NamedTupleMember" :
isImportTypeNode(this) ? "ImportTypeNode" :
formatSyntaxKind(this.kind);
return `${nodeHeader}${this.flags ? ` (${formatNodeFlags(this.flags)})` : ""}`;
}
},
__debugKind: { get(this: Node) { return formatSyntaxKind(this.kind); } },
__debugNodeFlags: { get(this: Node) { return formatNodeFlags(this.flags); } },
__debugModifierFlags: { get(this: Node) { return formatModifierFlags(getEffectiveModifierFlagsNoCache(this)); } },
__debugTransformFlags: { get(this: Node) { return formatTransformFlags(this.transformFlags); } },
__debugIsParseTreeNode: { get(this: Node) { return isParseTreeNode(this); } },
__debugEmitFlags: { get(this: Node) { return formatEmitFlags(getEmitFlags(this)); } },
__debugGetText: {
value(this: Node, includeTrivia?: boolean) {
if (nodeIsSynthesized(this)) return "";
// avoid recomputing
const map = getWeakNodeTextMap();
let text = map?.get(this);
if (text === undefined) {
const parseNode = getParseTreeNode(this);
const sourceFile = parseNode && getSourceFileOfNode(parseNode);
text = sourceFile ? getSourceTextOfNodeFromSourceFile(sourceFile, parseNode!, includeTrivia) : "";
map?.set(this, text);
}
return text;
}
}
});
}
}
// attempt to load extended debugging information
try {
if (sys && sys.require) {
const basePath = getDirectoryPath(resolvePath(sys.getExecutingFilePath()));
const result = sys.require(basePath, "./compiler-debug") as RequireResult<ExtendedDebugModule>;
if (!result.error) {
result.module.init(ts);
extendedDebugModule = result.module;
}
}
}
catch {
// do nothing
}
isDebugInfoEnabled = true;
}
function formatDeprecationMessage(name: string, error: boolean | undefined, errorAfter: Version | undefined, since: Version | undefined, message: string | undefined) {
let deprecationMessage = error ? "DeprecationError: " : "DeprecationWarning: ";
deprecationMessage += `'${name}' `;
deprecationMessage += since ? `has been deprecated since v${since}` : "is deprecated";
deprecationMessage += error ? " and can no longer be used." : errorAfter ? ` and will no longer be usable after v${errorAfter}.` : ".";
deprecationMessage += message ? ` ${formatStringFromArgs(message, [name], 0)}` : "";
return deprecationMessage;
}
function createErrorDeprecation(name: string, errorAfter: Version | undefined, since: Version | undefined, message: string | undefined) {
const deprecationMessage = formatDeprecationMessage(name, /*error*/ true, errorAfter, since, message);
return () => {
throw new TypeError(deprecationMessage);
};
}
function createWarningDeprecation(name: string, errorAfter: Version | undefined, since: Version | undefined, message: string | undefined) {
let hasWrittenDeprecation = false;
return () => {
if (!hasWrittenDeprecation) {
log.warn(formatDeprecationMessage(name, /*error*/ false, errorAfter, since, message));
hasWrittenDeprecation = true;
}
};
}
function createDeprecation(name: string, options: DeprecationOptions & { error: true }): () => never;
function createDeprecation(name: string, options?: DeprecationOptions): () => void;
function createDeprecation(name: string, options: DeprecationOptions = {}) {
const version = typeof options.typeScriptVersion === "string" ? new Version(options.typeScriptVersion) : options.typeScriptVersion ?? getTypeScriptVersion();
const errorAfter = typeof options.errorAfter === "string" ? new Version(options.errorAfter) : options.errorAfter;
const warnAfter = typeof options.warnAfter === "string" ? new Version(options.warnAfter) : options.warnAfter;
const since = typeof options.since === "string" ? new Version(options.since) : options.since ?? warnAfter;
const error = options.error || errorAfter && version.compareTo(errorAfter) <= 0;
const warn = !warnAfter || version.compareTo(warnAfter) >= 0;
return error ? createErrorDeprecation(name, errorAfter, since, options.message) :
warn ? createWarningDeprecation(name, errorAfter, since, options.message) :
noop;
}
function wrapFunction<F extends (...args: any[]) => any>(deprecation: () => void, func: F): F {
return function (this: unknown) {
deprecation();
return func.apply(this, arguments);
} as F;
}
export function deprecate<F extends (...args: any[]) => any>(func: F, options?: DeprecationOptions): F {
const deprecation = createDeprecation(getFunctionName(func), options);
return wrapFunction(deprecation, func);
}
}
} | the_stack |
import { EventEmitter } from "events";
import { Server } from "http";
import { HubConfig, RemoteClientConfig, BrowserSpec, BenchmarkRuntimeConfig, BestAgentState, BenchmarkUpdateState } from "@best/types";
import { normalizeClientConfig , normalizeSpecs } from '@best/utils';
import socketIO, { Server as SocketIoServer, Socket } from "socket.io";
import { BEST_RPC } from "@best/shared";
import { RemoteClient } from "@best/agent";
import { matchSpecs } from "@best/utils";
import RemoteAgent from "./remote-agent";
import { validateConfig, validateToken } from './utils/validate';
export class Hub extends EventEmitter {
private hubConfig: HubConfig;
private clientsSocketServer: SocketIoServer;
private agentsSocketServer: SocketIoServer;
private connectedClients = new Set<RemoteClient>();
private connectedAgents = new Set<RemoteAgent>();
private activeClients: Map<RemoteClient, RemoteAgent> = new Map();
constructor(server: Server, hubConfig: HubConfig) {
super();
this.hubConfig = hubConfig;
this.clientsSocketServer = socketIO(server, { path: '/best' });
this.clientsSocketServer.on('connect', this.onClientConnect.bind(this));
this.agentsSocketServer = socketIO(server, { path: '/agents' });
this.agentsSocketServer.on('connect', this.onAgentConnect.bind(this));
}
// -- Client lifecycle ---------------------------------------------------------------
onClientConnect(clientSocket: Socket) {
const query = clientSocket.handshake.query;
const config = normalizeClientConfig(query);
const invalidConfig = validateConfig(config, this.hubConfig, this.getAgentSpecs(), clientSocket.id);
if (invalidConfig) {
clientSocket.emit(BEST_RPC.AGENT_REJECTION, invalidConfig);
return clientSocket.disconnect(true);
}
const remoteClient = this.setupNewClient(clientSocket, config);
console.log(`[HUB] Connected clients: ${this.connectedClients.size}`);
if (this.idleAgentMatchingSpecs(remoteClient)) {
this.runBenchmarks(remoteClient);
} else {
remoteClient.log(`Client enqueued. Waiting for an agent to be free...`);
this.emit(BEST_RPC.AGENT_QUEUED_CLIENT, { clientId: remoteClient.getId(), jobs: config.jobs, specs: config.specs });
}
}
setupNewClient(socketClient: Socket, clientConfig: RemoteClientConfig): RemoteClient {
// Create and new RemoteClient and add it to the pool
const remoteClient = new RemoteClient(socketClient, clientConfig);
this.connectedClients.add(remoteClient);
console.log(`[HUB] New client ${remoteClient.getId()} connected. Jobs requested ${clientConfig.jobs} | specs: ${JSON.stringify(clientConfig.specs)}`);
this.emit(BEST_RPC.AGENT_CONNECTED_CLIENT, { clientId: remoteClient.getId(), jobs: clientConfig.jobs, specs: remoteClient.getSpecs() });
// Make sure we remove it from an agent's perspective if the client is disconnected
remoteClient.on(BEST_RPC.DISCONNECT, () => {
console.log(`[HUB] Disconnected client ${remoteClient.getId()}`);
this.emit(BEST_RPC.AGENT_DISCONNECTED_CLIENT, remoteClient.getId());
this.connectedClients.delete(remoteClient);
console.log(`[HUB] Connected clients: ${this.connectedClients.size}`);
// If the client is actively running something we need to kill it
if (this.activeClients.has(remoteClient)) {
const remoteAgent = this.activeClients.get(remoteClient);
if (remoteAgent && remoteAgent.isBusy()) {
remoteAgent.interruptRunner();
}
this.activeClients.delete(remoteClient);
}
});
remoteClient.on(BEST_RPC.BENCHMARK_START, (benchmarkId: string) => {
const agent = this.activeClients.get(remoteClient);
this.emit(BEST_RPC.BENCHMARK_START, { agentId: agent && agent.getId(), clientId: remoteClient.getId(), benchmarkId });
});
remoteClient.on(BEST_RPC.BENCHMARK_END, (benchmarkId: string) => {
const agent = this.activeClients.get(remoteClient);
this.emit(BEST_RPC.BENCHMARK_END, { agentId: agent && agent.getId(), clientId: remoteClient.getId(), benchmarkId });
});
remoteClient.on(BEST_RPC.BENCHMARK_UPDATE, (benchmarkId: string, state: BenchmarkUpdateState, opts: BenchmarkRuntimeConfig) => {
const agent = this.activeClients.get(remoteClient);
this.emit(BEST_RPC.BENCHMARK_UPDATE, { agentId: agent && agent.getId(), clientId: remoteClient.getId(), benchmarkId, state, opts });
});
// If we are done with the job, make sure after a short time the client gets removed
remoteClient.on(BEST_RPC.REMOTE_CLIENT_EMPTY_QUEUE, () => {
console.log(`[HUB] Remote client ${remoteClient.getId()} is done. Scheduling a force disconnect.`);
setTimeout(() => {
if (this.connectedClients.has(remoteClient)) {
console.log(`[HUB] Force client disconnect (${remoteClient.getId()}): With no more jobs to run an agent must disconnect`);
remoteClient.disconnectClient(`Forced disconnect: With no more jobs client should have disconnected`);
}
}, 10000);
});
return remoteClient;
}
// -- Agent lifecycle ---------------------------------------------------------------
onAgentConnect(agentSocket: Socket) {
const query = agentSocket.handshake.query;
const specs = normalizeSpecs(query);
const validToken = validateToken(query.authToken, this.hubConfig.authToken);
const hasSpecs = specs.length > 0;
if (!validToken) {
agentSocket.emit(BEST_RPC.AGENT_REJECTION, 'Invalid Token');
return agentSocket.disconnect(true);
}
if (!hasSpecs) {
agentSocket.emit(BEST_RPC.AGENT_REJECTION, 'An agent must provide specs');
return agentSocket.disconnect(true);
}
if (!query.agentUri) {
agentSocket.emit(BEST_RPC.AGENT_REJECTION, 'An agent must provide a URI');
return agentSocket.disconnect(true);
}
const remoteAgent = this.setupNewAgent(agentSocket, specs, { agentUri: query.agentUri, agentToken: query.agentAuthToken });
if (remoteAgent) {
// If queued jobs with those specs, run them...
}
}
setupNewAgent(socketAgent: Socket, specs: BrowserSpec[], { agentUri, agentToken }: any): RemoteAgent {
// Create and new RemoteAgent and add it to the pool
const remoteAgent = new RemoteAgent(socketAgent, { uri: agentUri, token: agentToken, specs });
this.connectedAgents.add(remoteAgent);
console.log(`[HUB] New Agent ${remoteAgent.getId()} connected with specs: ${JSON.stringify(remoteAgent.getSpecs())}`);
this.emit(BEST_RPC.HUB_CONNECTED_AGENT, { agentId: remoteAgent.getId(), specs: remoteAgent.getSpecs(), uri: remoteAgent.getUri()});
// Make sure we remove it from an agent's perspective if the client is disconnected
remoteAgent.on(BEST_RPC.DISCONNECT, () => {
console.log(`[HUB] Disconnected Agent ${remoteAgent.getId()}`);
this.emit(BEST_RPC.HUB_DISCONNECTED_AGENT, { agentId: remoteAgent.getId() });
this.connectedAgents.delete(remoteAgent);
if (remoteAgent.isBusy()) {
remoteAgent.interruptRunner();
}
});
return remoteAgent;
}
// -- Private methods ---------------------------------------------------------------
async runBenchmarks(remoteClient: RemoteClient) {
// New agent setup
if (!this.activeClients.has(remoteClient)) {
const matchingAgents = this.findAgentMatchingSpecs(remoteClient, { ignoreBusy: true });
if (matchingAgents.length > 0) {
const remoteAgent = matchingAgents[0];
this.activeClients.set(remoteClient, remoteAgent);
this.emit(BEST_RPC.AGENT_RUNNING_CLIENT, { clientId: remoteClient.getId(), agentId: remoteAgent.getId(), jobs: remoteClient.getPendingBenchmarks() });
try {
await remoteAgent.runBenchmarks(remoteClient);
} catch(err) {
console.log(`[HUB] Error running benchmark for remote client ${remoteClient.getId()}`);
remoteClient.disconnectClient(`Error running benchmark ${err}`); // make sure we disconnect the agent
} finally {
this.activeClients.delete(remoteClient);
queueMicrotask(() => this.runQueuedBenchmarks());
}
} else {
console.log('[HUB] All agents are busy at this moment...');
}
} else {
console.log(`[HUB] Client ${remoteClient.getId()} is actively running already`)
}
}
runQueuedBenchmarks() {
Array.from(this.connectedClients).forEach((remoteClient) => {
if (!this.activeClients.has(remoteClient)) {
if (this.idleAgentMatchingSpecs(remoteClient) && remoteClient.getPendingBenchmarks() > 0) {
console.log(`[HUB] Running benchmark: "${remoteClient.getId()}" has ${remoteClient.getPendingBenchmarks()} to run`);
this.runBenchmarks(remoteClient);
} else {
console.log(`[HUB] All matching agents still busy for ${remoteClient.getId()}`);
}
}
});
}
getAgentSpecs(): BrowserSpec[] {
const specs: BrowserSpec[] = [];
for (const agent of this.connectedAgents) {
specs.push(...agent.getSpecs());
}
return specs;
}
idleAgentMatchingSpecs(remoteClient: RemoteClient): boolean {
return this.findAgentMatchingSpecs(remoteClient, { ignoreBusy: true }).length > 0;
}
findAgentMatchingSpecs(remoteClient: RemoteClient, { ignoreBusy }: { ignoreBusy?: boolean } = {}): RemoteAgent[] {
const specs = remoteClient.getSpecs();
const agents: RemoteAgent[] = [];
if (specs) {
for (const agent of this.connectedAgents) {
const matchesSpecs = matchSpecs(specs, agent.getSpecs() || []);
const matchesFilterCriteria = ignoreBusy ? !agent.isBusy(): true;
if (matchesSpecs && matchesFilterCriteria) {
agents.push(agent);
}
}
}
return agents;
}
// -- Public API ---------------------------------------------------------------
getState(): BestAgentState {
const connectedClients = Array.from(this.connectedClients).map((client) => client.getState());
const connectedAgents = Array.from(this.connectedAgents).map(agent => agent.getState());
const activeClients = Array.from(this.activeClients).map(([rc, ra]) => ({ clientId: rc.getId(), agentId: ra.getId() }));
return {
connectedClients,
connectedAgents,
activeClients
};
}
} | the_stack |
import React, { PureComponent } from 'react';
import { SelectableValue, QueryEditorProps, dateTime } from '@grafana/data';
import { InlineField, InlineFormLabel, InlineSwitch, MultiSelect, Select } from '@grafana/ui';
import {
StravaQuery,
StravaQueryType,
StravaActivityStat,
StravaQueryFormat,
StravaActivityType,
StravaJsonData,
StravaQueryInterval,
StravaActivityStream,
StravaActivityData,
StravaSplitStat,
StravaAthlete,
} from '../types';
import StravaDatasource from '../datasource';
import { AthleteLabel } from './AthleteLabel';
import { getTemplateSrv } from '@grafana/runtime';
const ACTIVITY_DATE_FORMAT = 'YYYY-MM-DD HH:mm';
const stravaQueryTypeOptions: Array<SelectableValue<StravaQueryType>> = [
{
value: StravaQueryType.Activities,
label: 'Activities',
description: 'Athlete Activities',
},
{
value: StravaQueryType.Activity,
label: 'Activity',
description: 'Individual activity',
},
];
const stravaActivityStatOptions: Array<SelectableValue<StravaActivityStat>> = [
{ value: StravaActivityStat.Distance, label: 'Distance' },
{ value: StravaActivityStat.ElapsedTime, label: 'Elapsed Time' },
{ value: StravaActivityStat.MovingTime, label: 'Moving Time' },
{ value: StravaActivityStat.ElevationGain, label: 'Elevation Gain' },
{ value: StravaActivityStat.AveragePower, label: 'Average Power' },
{ value: StravaActivityStat.AverageHeartRate, label: 'Average Heart Rate' },
];
const stravaActivityTypeOptions: Array<SelectableValue<StravaActivityType>> = [
{ value: null, label: 'All' },
{ value: 'Run', label: 'Run' },
{ value: 'Ride', label: 'Ride' },
{ value: 'Other', label: 'Other' },
];
const stravaActivityDataOptions: Array<SelectableValue<StravaActivityData>> = [
{ value: StravaActivityData.Graph, label: 'Graph' },
{ value: StravaActivityData.Splits, label: 'Splits' },
{ value: StravaActivityData.Stats, label: 'Stats' },
];
const stravaActivityGraphOptions: Array<SelectableValue<StravaActivityStream>> = [
// { value: StravaActivityStream.Distance, label: 'Distance' },
{ value: StravaActivityStream.HeartRate, label: 'Heart Rate' },
{ value: StravaActivityStream.Velocity, label: 'Speed' },
{ value: StravaActivityStream.Pace, label: 'Pace' },
{ value: StravaActivityStream.WattsCalc, label: 'Est Power' },
{ value: StravaActivityStream.Watts, label: 'Watts' },
{ value: StravaActivityStream.Cadence, label: 'Cadence' },
{ value: StravaActivityStream.Altitude, label: 'Altitude' },
{ value: StravaActivityStream.GradeSmooth, label: 'Gradient' },
// { value: StravaActivityStream.GradeAdjustedDistance, label: 'Gradient (adjusted)' },
// { value: StravaActivityStream.Temp, label: 'Temp' },
];
const stravaActivitySplitOptions: Array<SelectableValue<StravaSplitStat>> = [
{ value: StravaSplitStat.HeartRate, label: 'Heart Rate' },
{ value: StravaSplitStat.Speed, label: 'Speed' },
{ value: StravaSplitStat.ElapsedTime, label: 'Elapsed Time' },
{ value: StravaSplitStat.MovingTime, label: 'Moving Time' },
];
const FORMAT_OPTIONS: Array<SelectableValue<StravaQueryFormat>> = [
{ label: 'Time series', value: StravaQueryFormat.TimeSeries },
{ label: 'Table', value: StravaQueryFormat.Table },
{ label: 'World Map', value: StravaQueryFormat.WorldMap },
];
const INTERVAL_OPTIONS: Array<SelectableValue<StravaQueryInterval>> = [
{ label: 'Auto', value: StravaQueryInterval.Auto },
{ label: 'No', value: StravaQueryInterval.No },
{ label: 'Hour', value: StravaQueryInterval.Hour },
{ label: 'Day', value: StravaQueryInterval.Day },
{ label: 'Week', value: StravaQueryInterval.Week },
{ label: 'Month', value: StravaQueryInterval.Month },
];
const extendedStatsOptions: Array<SelectableValue<string>> = [
{ label: 'achievement_count', value: 'achievement_count' },
{ label: 'average_speed', value: 'average_speed' },
{ label: 'average_watts', value: 'average_watts' },
{ label: 'comment_count', value: 'comment_count' },
{ label: 'commute', value: 'commute' },
{ label: 'device_watts', value: 'device_watts' },
{ label: 'elev_high', value: 'elev_high' },
{ label: 'elev_low', value: 'elev_low' },
{ label: 'gear_id', value: 'gear_id' },
{ label: 'has_kudoed', value: 'has_kudoed' },
{ label: 'kudos_count', value: 'kudos_count' },
{ label: 'location_city', value: 'location_city' },
{ label: 'location_country', value: 'location_country' },
{ label: 'location_state', value: 'location_state' },
{ label: 'manual', value: 'manual' },
{ label: 'max_heartrate', value: 'max_heartrate' },
{ label: 'max_speed', value: 'max_speed' },
{ label: 'pr_count', value: 'pr_count' },
{ label: 'start_date', value: 'start_date' },
{ label: 'start_date_local', value: 'start_date_local' },
{ label: 'start_latitude', value: 'start_latitude' },
{ label: 'start_longitude', value: 'start_longitude' },
{ label: 'trainer', value: 'trainer' },
{ label: 'workout_type', value: 'workout_type' },
];
const baseStatsOptions: Array<SelectableValue<string>> = [
{ label: 'start_date', value: 'start_date' },
{ label: 'name', value: 'name' },
{ label: 'distance', value: 'distance' },
{ label: 'moving_time', value: 'moving_time' },
{ label: 'elapsed_time', value: 'elapsed_time' },
{ label: 'average_heartrate', value: 'average_heartrate' },
{ label: 'total_elevation_gain', value: 'total_elevation_gain' },
{ label: 'kilojoules', value: 'kilojoules' },
{ label: 'type', value: 'type' },
{ label: 'id', value: 'id' },
];
const stravaStatsOptions = baseStatsOptions.concat(extendedStatsOptions);
export const DefaultTarget: State = {
refId: '',
athlete: {} as StravaAthlete,
queryType: StravaQueryType.Activities,
activityType: null,
activitiesOptions: [],
activityStat: StravaActivityStat.Distance,
format: StravaQueryFormat.TimeSeries,
interval: StravaQueryInterval.Auto,
activityData: StravaActivityData.Graph,
activityGraph: StravaActivityStream.HeartRate,
extendedStats: [],
singleActivityStat: '',
};
export interface Props extends QueryEditorProps<StravaDatasource, StravaQuery, StravaJsonData> {}
interface State extends StravaQuery {
athlete: StravaAthlete;
selectedActivity?: SelectableValue<number>;
activitiesOptions: Array<SelectableValue<number>>;
}
export class QueryEditor extends PureComponent<Props, State> {
state: State = DefaultTarget;
async componentDidMount() {
const athlete = await this.props.datasource.stravaApi.getAuthenticatedAthlete();
const activitiesOptions = await this.getActivitiesOptions(this.props.query.activityType);
this.setState({ athlete, activitiesOptions });
}
getSelectedQueryType = () => {
return stravaQueryTypeOptions.find((v) => v.value === this.props.query.queryType);
};
getSelectedActivityStat = () => {
return stravaActivityStatOptions.find((v) => v.value === this.props.query.activityStat);
};
getSelectedActivityType = () => {
return stravaActivityTypeOptions.find((v) => v.value === this.props.query.activityType);
};
getSelectedActivityData = () => {
return stravaActivityDataOptions.find((v) => v.value === this.props.query.activityData);
};
getSelectedActivityGraph = () => {
return stravaActivityGraphOptions.find((v) => v.value === this.props.query.activityGraph);
};
getSelectedActivitySplit = () => {
return stravaActivitySplitOptions.find((v) => v.value === this.props.query.splitStat);
};
getSelectedSingleActivityStat = () => {
return stravaStatsOptions.find((v) => v.value === this.props.query.singleActivityStat);
};
getFormatOption = () => {
return FORMAT_OPTIONS.find((v) => v.value === this.props.query.format);
};
getIntervalOption = () => {
return INTERVAL_OPTIONS.find((v) => v.value === this.props.query.interval);
};
getSelectedActivityOption = () => {
return this.props.query.selectedActivity;
};
getActivitiesOptions = async (activityType: StravaActivityType): Promise<Array<SelectableValue<number>>> => {
const { datasource } = this.props;
let activities = await datasource.stravaApi.getActivities({ limit: 100 });
activities = datasource.filterActivities(activities, activityType);
let options: Array<SelectableValue<number>> = activities.map((a) => ({
value: a.id,
label: a.name,
description: `${dateTime(a.start_date_local).format(ACTIVITY_DATE_FORMAT)} (${a.type})`,
}));
const variables: SelectableValue[] = getTemplateSrv()
.getVariables()
.map((v) => ({
value: `$${v.name}`,
label: `$${v.name}`,
description: 'Variable',
}));
options = variables.concat(options);
return options;
};
onQueryTypeChanged = (option: SelectableValue<StravaQueryType>) => {
const { query } = this.props;
if (option.value) {
this.onChange({ ...query, queryType: option.value });
}
};
onActivityStatChanged = (option: SelectableValue<StravaActivityStat>) => {
const { query } = this.props;
if (option.value) {
this.onChange({ ...query, activityStat: option.value });
}
};
onActivityDataChanged = (option: SelectableValue<StravaActivityData>) => {
const { query } = this.props;
if (option.value) {
this.onChange({ ...query, activityData: option.value });
}
};
onActivityGraphChanged = (option: SelectableValue<StravaActivityStream>) => {
const { query } = this.props;
if (option.value) {
this.onChange({ ...query, activityGraph: option.value });
}
};
onActivitySplitChanged = (option: SelectableValue<StravaSplitStat>) => {
const { query } = this.props;
if (option.value) {
this.onChange({ ...query, splitStat: option.value });
}
};
onActivityTypeChanged = async (option: SelectableValue<StravaActivityType>) => {
const { query } = this.props;
if (option.value !== undefined) {
this.onChange({ ...query, activityType: option.value });
const activitiesOptions = await this.getActivitiesOptions(option.value);
this.setState({ activitiesOptions });
}
};
onFitToRangeChanged = (event: React.FormEvent<HTMLInputElement>) => {
const { query } = this.props;
this.onChange({ ...query, fitToTimeRange: !query.fitToTimeRange });
};
onFormatChange = (option: SelectableValue<StravaQueryFormat>) => {
const { query } = this.props;
if (option.value) {
this.onChange({ ...query, format: option.value });
}
};
onIntervalChange = (option: SelectableValue<StravaQueryInterval>) => {
const { query } = this.props;
if (option.value) {
this.onChange({ ...query, interval: option.value });
}
};
onActivityChanged = (option: SelectableValue<number>) => {
const { query } = this.props;
if (option.value !== undefined) {
this.onChange({ ...query, activityId: option.value, selectedActivity: option });
}
};
onExtendedStatsChanged = (options: Array<SelectableValue<string>>) => {
const { query } = this.props;
console.log(options);
if (options) {
const values: string[] = [];
options.forEach((option) => option.value && values.push(option.value));
this.onChange({ ...query, extendedStats: values });
}
};
onSingleActivityStatChanged = (option: SelectableValue<string>) => {
const { query } = this.props;
if (option.value) {
this.onChange({ ...query, singleActivityStat: option.value });
}
};
onChange(query: StravaQuery) {
const { onChange, onRunQuery } = this.props;
onChange(query);
onRunQuery();
}
renderActivitiesEditor() {
const { query } = this.props;
return (
<>
<div className="gf-form-inline">
<InlineFormLabel width={12}> </InlineFormLabel>
<InlineFormLabel width={5}>Stat</InlineFormLabel>
<Select
isSearchable={false}
width={16}
value={this.getSelectedActivityStat()}
options={stravaActivityStatOptions}
onChange={this.onActivityStatChanged}
/>
<InlineFormLabel width={8}>Format</InlineFormLabel>
<Select
isSearchable={false}
width={16}
options={FORMAT_OPTIONS}
onChange={this.onFormatChange}
value={this.getFormatOption()}
/>
<InlineFormLabel width={5}>Interval</InlineFormLabel>
<Select
isSearchable={false}
width={16}
options={INTERVAL_OPTIONS}
onChange={this.onIntervalChange}
value={this.getIntervalOption()}
/>
<div className="gf-form gf-form--grow">
<div className="gf-form-label gf-form-label--grow" />
</div>
</div>
{query.format === StravaQueryFormat.Table && (
<div className="gf-form-inline">
<InlineFormLabel width={12}> </InlineFormLabel>
<InlineField label="Extended Stats" labelWidth={14}>
<MultiSelect
isSearchable
isClearable
value={query.extendedStats}
options={extendedStatsOptions}
onChange={this.onExtendedStatsChanged}
/>
</InlineField>
<div className="gf-form gf-form--grow">
<div className="gf-form-label gf-form-label--grow" />
</div>
</div>
)}
</>
);
}
renderActivityEditor() {
const { query } = this.props;
const { activitiesOptions } = this.state;
return (
<>
<div className="gf-form-inline">
<InlineFormLabel width={12}> </InlineFormLabel>
<InlineFormLabel width={5}>Activity</InlineFormLabel>
<Select
isSearchable={true}
width={33}
value={this.getSelectedActivityOption()}
options={activitiesOptions}
onChange={this.onActivityChanged}
/>
<InlineField label="Data" labelWidth={10}>
<Select
isSearchable={false}
width={16}
value={this.getSelectedActivityData()}
options={stravaActivityDataOptions}
onChange={this.onActivityDataChanged}
/>
</InlineField>
{query.activityData === StravaActivityData.Graph && (
<Select
isSearchable={false}
width={16}
value={this.getSelectedActivityGraph()}
options={stravaActivityGraphOptions}
onChange={this.onActivityGraphChanged}
/>
)}
{query.activityData === StravaActivityData.Splits && (
<Select
isSearchable={false}
width={16}
value={this.getSelectedActivitySplit()}
options={stravaActivitySplitOptions}
onChange={this.onActivitySplitChanged}
/>
)}
{query.activityData === StravaActivityData.Stats && (
<Select
isSearchable={true}
width={20}
value={this.getSelectedSingleActivityStat()}
options={stravaStatsOptions}
onChange={this.onSingleActivityStatChanged}
/>
)}
<InlineFormLabel width={5}>Fit to range</InlineFormLabel>
<InlineSwitch css="" value={query.fitToTimeRange || false} onChange={this.onFitToRangeChanged}></InlineSwitch>
<div className="gf-form gf-form--grow">
<div className="gf-form-label gf-form-label--grow" />
</div>
</div>
</>
);
}
render() {
const { athlete } = this.state;
const queryType = this.getSelectedQueryType();
return (
<>
<div className="gf-form-inline">
<AthleteLabel athlete={athlete} />
<InlineFormLabel width={5}>Query</InlineFormLabel>
<Select
isSearchable={false}
width={16}
value={this.getSelectedQueryType()}
options={stravaQueryTypeOptions}
onChange={this.onQueryTypeChanged}
/>
<InlineFormLabel width={8}>Activity type</InlineFormLabel>
<Select
isSearchable={false}
width={16}
value={this.getSelectedActivityType()}
options={stravaActivityTypeOptions}
onChange={this.onActivityTypeChanged}
/>
<div className="gf-form gf-form--grow">
<div className="gf-form-label gf-form-label--grow" />
</div>
</div>
{queryType?.value === StravaQueryType.Activities && this.renderActivitiesEditor()}
{queryType?.value === StravaQueryType.Activity && this.renderActivityEditor()}
</>
);
}
} | the_stack |
import {AbstractComponent} from '@common/component/abstract.component';
import {Component, ElementRef, Injector, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {SubscribeArg} from '@common/domain/subscribe-arg';
import {Modal} from '@common/domain/modal';
import {PopupService} from '@common/service/popup.service';
import {DeleteModalComponent} from '@common/component/modal/delete/delete.component';
import {LineageService} from './service/lineage.service';
import {LineageEdge} from '@domain/meta-data-management/lineage';
import {EditLineagePopupComponent} from './component/edit-lineage-popup.component';
import {PeriodComponent, PeriodType} from '@common/component/period/period.component';
import {Alert} from '@common/util/alert.util';
import {ActivatedRoute} from '@angular/router';
import * as _ from 'lodash';
import {PeriodData} from '@common/value/period.data.value';
@Component({
selector: 'app-lineage',
templateUrl: './lineage.component.html',
})
export class LineageComponent extends AbstractComponent implements OnInit, OnDestroy {
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
@ViewChild(EditLineagePopupComponent)
private editLineagePopup: EditLineagePopupComponent;
// 삭제 컴포넌트
@ViewChild(DeleteModalComponent)
private _deleteComp: DeleteModalComponent;
// date
private _selectedDate: PeriodData;
// 검색 파라메터
private _searchParams: { [key: string]: string };
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// popup status
public step: string;
// period component
@ViewChild(PeriodComponent)
public periodComponent: PeriodComponent;
public lineageList: LineageEdge[];
public searchText: string;
public selectedContentSort: Order = new Order();
public selectedType: PeriodType;
public defaultDate: PeriodData;
// popup status
public isCreatingLineage: boolean = false;
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Constructor
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
constructor(
private _lineageService: LineageService,
private _activatedRoute: ActivatedRoute,
private popupService: PopupService,
protected element: ElementRef,
protected injector: Injector) {
super(element, injector);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Override Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
public ngOnInit() {
super.ngOnInit();
this._initView();
// After creating dataset
this.subscriptions.push(
this.popupService.view$.subscribe((data: SubscribeArg) => {
this.step = data.name;
if (this.step === 'complete-lineage-create') {
this.reloadPage(true);
}
})
);
// Get query param from url
this.subscriptions.push(
this._activatedRoute.queryParams.subscribe((params) => {
if (!_.isEmpty(params)) {
if (!this.isNullOrUndefined(params['size'])) {
this.page.size = params['size'];
}
if (!this.isNullOrUndefined(params['page'])) {
this.page.page = params['page'];
}
if (!this.isNullOrUndefined(params['descContains'])) {
this.searchText = params['descContains'];
}
const sort = params['sort'];
if (!this.isNullOrUndefined(sort)) {
const sortInfo = decodeURIComponent(sort).split(',');
this.selectedContentSort.key = sortInfo[0];
this.selectedContentSort.sort = sortInfo[1];
}
const from = params['from'];
const to = params['to'];
this._selectedDate = new PeriodData();
this._selectedDate.startDate = from;
this._selectedDate.endDate = to;
this._selectedDate.startDateStr = decodeURIComponent(from);
this._selectedDate.endDateStr = decodeURIComponent(to);
this._selectedDate.type = params['type'];
this.defaultDate = this._selectedDate;
this.safelyDetectChanges();
}
this._getLineageList();
})
);
}
public ngOnDestroy() {
super.ngOnDestroy();
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* 리니지 제거
* @param {Modal} modal
*/
public deleteLineageEdge(modal: Modal): void {
this.loadingShow();
this._lineageService.deleteLineage(modal['edgeId']).then(() => {
this.loadingHide();
Alert.success(this.translateService.instant('msg.metadata.ui.lineage.delete.edge.success', {value: modal['description']}));
if (this.page.page > 0 && this.lineageList.length === 1) {
this.page.page = this.page.page - 1;
}
this.reloadPage();
}).catch((error) => {
this.loadingHide();
this.commonExceptionHandler(error);
});
}
/**
* 컨텐츠 총 갯수
* @returns {number}
*/
public get getTotalContentsCount(): number {
return this.pageResult.totalElements;
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method - event
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
public onChangedSearchKeyword(keyword: string): void {
// set search keyword
this.searchText = keyword;
// reload page
this.reloadPage(true);
}
public onClickEditLineage(): void {
this.editLineagePopup.init({
name: 'edit'
});
}
public onClickCreateLineage(): void {
this.step = 'upload-file';
}
/**
* 리니지 상세정보 클릭 이벤트
* @param {string} lineageId
*/
public onClickDetailLineage(lineageId: string): void {
// 상세화면으로 이동
this.router.navigate(['management/metadata/lineage', lineageId]).then();
}
/**
* 리니지 삭제 클릭 이벤트
* @param event
* @param {LineageEdge} lineageEdge
*/
public onClickDeleteLineage(event, lineageEdge: LineageEdge): void {
event.stopPropagation();
const modal = new Modal();
modal.description = lineageEdge.desc;
modal.name = this.translateService.instant('msg.metadata.ui.lineage.delete.edge');
modal.btnName = this.translateService.instant('msg.comm.btn.modal.done');
modal['edgeId'] = lineageEdge.edgeId;
this._deleteComp.init(modal);
}
/**
* 필터링 초기화 버튼 클릭 이벤트
*/
public onClickResetFilters(): void {
// 정렬
this.selectedContentSort = new Order();
// create date 초기화
this._selectedDate = null;
// date 필터 created update 설정 default created로 설정
this.periodComponent.selectedDate = 'CREATED';
// 검색조건 초기화
this.searchText = '';
// 페이지 초기화
this.pageResult.number = 0;
// date 필터 init
this.periodComponent.setAll();
this.reloadPage();
}
/**
* 정렬 버튼 클릭
* @param {string} key
*/
public onClickSort(key: string): void {
// 초기화
this.selectedContentSort.sort = this.selectedContentSort.key !== key ? 'default' : this.selectedContentSort.sort;
// 정렬 정보 저장
this.selectedContentSort.key = key;
if (this.selectedContentSort.key === key) {
// asc, desc
switch (this.selectedContentSort.sort) {
case 'asc':
this.selectedContentSort.sort = 'desc';
break;
case 'desc':
this.selectedContentSort.sort = 'asc';
break;
case 'default':
this.selectedContentSort.sort = 'desc';
break;
}
}
// 페이지 초기화 후 재조회
this.reloadPage();
}
/**
* 코드 테이블 이름 검색
*/
public onSearchText(): void {
this._searchText(this.searchText);
}
/**
* 코드 테이블 이름 초기화 후 검색
*/
public onSearchTextInit(): void {
this._searchText('');
}
/**
* 캘린더 선택 이벤트
* @param event
*/
public onChangeData(event): void {
// 선택한 날짜
this._selectedDate = event;
// 재조회
this.reloadPage();
}
/**
* 페이지 변경
* @param data
*/
public changePage(data: { page: number, size: number }) {
if (data) {
this.page.page = data.page;
this.page.size = data.size;
this.reloadPage(false);
}
} // function - changePage
/**
* 페이지를 새로 불러온다.
* @param {boolean} isFirstPage
*/
public reloadPage(isFirstPage: boolean = true) {
(isFirstPage) && (this.page.page = 0);
this._searchParams = this._getLineageListParams();
this.router.routeReuseStrategy.shouldReuseRoute = () => false;
this.router.navigate(
[this.router.url.replace(/\?.*/gi, '')],
{queryParams: this._searchParams, replaceUrl: true}
).then();
} // function - reloadPage
public isEmptyList(): boolean {
return this.lineageList.length === 0;
}
public getLineageType(lineage: LineageEdge) {
if (lineage.frColName && lineage.toColName) {
return 'column';
}
return 'metadata';
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* ui init
* @private
*/
private _initView(): void {
// 리스트 초기화
this.lineageList = [];
// 검색어 초기화
this.searchText = '';
// 정렬 초기화
this.selectedContentSort = new Order();
// 페이지당 갯수 10
this.page.size = 10;
}
/**
* 검색어로 코드 테이블 이름 검색
* @param {string} keyword
* @private
*/
private _searchText(keyword: string): void {
this.searchText = keyword;
// 페이지 초기화 후 재조회
this.reloadPage();
}
/**
* After creating code table
*/
public onCreateComplete() {
this.loadingHide();
this.reloadPage();
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Method - getter
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* 코드 테이블 리스트 조회
* @private
*/
private _getLineageList(): void {
this.loadingShow();
const params = this._getLineageListParams();
this.lineageList = [];
this._lineageService.getLineageList(params).then((result) => {
// 현재 페이지에 아이템이 없다면 전 페이지를 불러온다.
if (this.page.page > 0 &&
this.isNullOrUndefined(result['_embedded']) ||
(!this.isNullOrUndefined(result['_embedded']) && result['_embedded'].lineageedges.length === 0)) {
this.page.page = result.page.number - 1;
this._getLineageList();
}
this._searchParams = params;
this.pageResult = result.page;
this.lineageList = result['_embedded'] ? this.lineageList.concat(result['_embedded'].lineageedges) : [];
this.loadingHide();
}).catch((error) => {
this.loadingHide();
this.commonExceptionHandler(error);
});
}
/**
* 코드 테이블 목록 조회 파라메터
* @returns {Object}
* @private
*/
private _getLineageListParams(): any {
const params = {
size: this.page.size,
page: this.page.page
};
if (!this.isNullOrUndefined(this.searchText) && this.searchText.trim() !== '') {
params['descContains'] = this.searchText.trim();
}
return params;
}
}
class Order {
key: string = 'name';
sort: string = 'asc';
} | the_stack |
import {
Box,
Button,
ButtonProps,
Fade,
FormHelperText,
Theme,
Typography,
useTheme,
} from "@material-ui/core";
import { makeStyles, styled } from "@material-ui/core/styles";
import AccountBalanceWalletIcon from "@material-ui/icons/AccountBalanceWallet";
import { WalletPickerProps } from "@renproject/multiwallet-ui";
import classNames from "classnames";
import React, { FunctionComponent, useCallback, useState } from "react";
import { TFunction, Trans, useTranslation } from "react-i18next";
import { useDispatch } from "react-redux";
import { useTimeout } from "react-use";
import {
ActionButton,
ActionButtonWrapper,
SecondaryActionButton,
} from "../../../components/buttons/Buttons";
import { WalletIcon } from "../../../components/icons/RenIcons";
import {
PaperContent,
SpacedPaperContent,
} from "../../../components/layout/Paper";
import { Link } from "../../../components/links/Links";
import { BridgeModalTitle } from "../../../components/modals/BridgeModal";
import {
ProgressWithContent,
ProgressWrapper,
} from "../../../components/progress/ProgressHelpers";
import { Debug } from "../../../components/utils/Debug";
import {
WalletConnectionStatusType,
WalletStatus,
} from "../../../components/utils/types";
import { createPulseAnimation } from "../../../theme/animationUtils";
import { defaultShadow } from "../../../theme/other";
import {
BridgeWallet,
getChainConfigByRentxName,
getNetworkConfigByRentxName,
getWalletConfig,
getWalletConfigByRentxName,
} from "../../../utils/assetConfigs";
import { trimAddress } from "../../../utils/strings";
import { useSubNetworkName } from "../../ui/uiHooks";
import { useSelectedChainWallet, useSwitchChainHelpers } from "../walletHooks";
import { setWalletPickerOpened } from "../walletSlice";
export const useWalletPickerStyles = makeStyles((theme) => ({
root: {
width: 400,
minHeight: 441,
},
body: {
padding: 24,
},
header: {
display: "flex",
justifyContent: "space-between",
alignItems: "stretch",
borderBottom: `1px solid ${theme.palette.divider}`,
padding: `16px 16px 14px`,
},
headerTitle: {
flexGrow: 2,
paddingLeft: 16,
textAlign: "center",
lineHeight: 2,
},
headerCloseIcon: {
fontSize: 16,
},
button: {
border: `1px solid ${theme.palette.divider}`,
},
chainTitle: {
textTransform: "capitalize",
fontSize: 14,
},
}));
const useWalletEntryButtonStyles = makeStyles({
root: {
marginTop: 20,
fontSize: 16,
padding: "11px 20px 11px 20px",
},
label: {
display: "flex",
justifyContent: "space-between",
alignContent: "center",
},
icon: {
fontSize: 36,
display: "inline-flex",
},
});
export const WalletEntryButton: WalletPickerProps<
any,
any
>["WalletEntryButton"] = ({ onClick, name, logo }) => {
const { icon: iconClassName, ...classes } = useWalletEntryButtonStyles();
const walletConfig = getWalletConfigByRentxName(name);
const { MainIcon } = walletConfig;
return (
<Button
classes={classes}
variant="outlined"
size="large"
fullWidth
onClick={onClick}
>
<span>{walletConfig.full}</span>{" "}
<span className={iconClassName}>
<MainIcon fontSize="inherit" />
</span>
</Button>
);
};
export const WalletChainLabel: WalletPickerProps<
any,
any
>["WalletChainLabel"] = ({ chain }) => {
const chainConfig = getChainConfigByRentxName(chain);
return <span>{chainConfig.full}</span>;
};
export const WalletConnectingInfo: WalletPickerProps<
any,
any
>["ConnectingInfo"] = ({ chain, onClose }) => {
const { t } = useTranslation();
const theme = useTheme();
const chainConfig = getChainConfigByRentxName(chain);
// TODO: There should be better mapping.
const walletSymbol: BridgeWallet = {
ethereum: BridgeWallet.METAMASKW,
bsc: BridgeWallet.BINANCESMARTW,
fantom: BridgeWallet.METAMASKW,
polygon: BridgeWallet.METAMASKW,
avalanche: BridgeWallet.METAMASKW,
solana: BridgeWallet.SOLLETW,
arbitrum: BridgeWallet.METAMASKW,
}[
chain as
| "ethereum"
| "bsc"
| "fantom"
| "polygon"
| "avalanche"
| "solana"
| "arbitrum"
];
const walletConfig = getWalletConfig(walletSymbol);
const { MainIcon } = walletConfig;
const [isPassed] = useTimeout(3000);
const passed = isPassed();
return (
<>
<Debug it={{ chainConfig }} />
<BridgeModalTitle
title={
passed
? t("wallet.action-required", {
wallet: walletConfig.short,
})
: t("wallet.action-connecting")
}
onClose={onClose}
/>
<PaperContent bottomPadding>
<ProgressWrapper>
<ProgressWithContent
size={128}
color={theme.customColors.skyBlueLight}
fontSize="big"
processing
>
<MainIcon fontSize="inherit" />
</ProgressWithContent>
</ProgressWrapper>
<Typography variant="h6" align="center">
{passed
? t("wallet.action-connect-message", {
wallet: walletConfig.full,
})
: t("wallet.action-connecting-to", {
chain: chainConfig.full,
})}
</Typography>
</PaperContent>
</>
);
};
const useWalletConnectionProgressStyles = makeStyles((theme) => ({
iconWrapper: {
borderRadius: "50%",
padding: 13,
backgroundColor: theme.palette.divider,
display: "flex",
justifyContent: "center",
alignItems: "center",
fontSize: 44,
},
}));
export const WalletConnectionProgress: FunctionComponent = () => {
const theme = useTheme();
const styles = useWalletConnectionProgressStyles();
return (
<ProgressWithContent color={theme.customColors.redLighter} size={128}>
<div className={styles.iconWrapper}>
<WalletIcon fontSize="inherit" color="secondary" />
</div>
</ProgressWithContent>
);
};
export const WalletWrongNetworkInfo: WalletPickerProps<
any,
any
>["WrongNetworkInfo"] = ({ chain, targetNetwork, onClose }) => {
const { t } = useTranslation();
const theme = useTheme();
const subNetworkName = useSubNetworkName();
const chainConfig = getChainConfigByRentxName(chain);
const networkName = getNetworkConfigByRentxName(targetNetwork).full;
const { provider } = useSelectedChainWallet();
const [pending, setPending] = useState(false);
const [error, setError] = useState<any>(false);
const { addOrSwitchChain } = useSwitchChainHelpers(
chainConfig.symbol,
targetNetwork,
provider
);
const [success, setSuccess] = useState(false);
const handleSwitch = useCallback(() => {
if (addOrSwitchChain !== null) {
setError(false);
setPending(true);
addOrSwitchChain()
.then(() => {
setError(false);
setSuccess(true);
})
.catch((error) => {
setError(error);
})
.finally(() => {
setPending(false);
});
}
}, [addOrSwitchChain]);
return (
<>
<BridgeModalTitle
title={t("wallet.wrong-network-title")}
onClose={onClose}
/>
<PaperContent bottomPadding>
<ProgressWrapper>
<ProgressWithContent
size={128}
color={theme.customColors.redLighter}
fontSize="big"
>
<AccountBalanceWalletIcon fontSize="inherit" color="secondary" />
</ProgressWithContent>
</ProgressWrapper>
<Typography variant="h5" align="center" gutterBottom>
{t("wallet.network-switch-label")} {chainConfig.full} {networkName}
{subNetworkName && <span> ({subNetworkName})</span>}
</Typography>
<Typography variant="body1" align="center" color="textSecondary">
{t("wallet.network-switch-description")} {chainConfig.full}{" "}
{networkName} {subNetworkName}
</Typography>
<Box mt={2}>
{addOrSwitchChain !== null && (
<div>
<Box minHeight={19}>
<Fade in={pending || Boolean(error)} timeout={{ enter: 2000 }}>
<Box textAlign="center">
{pending && (
<CenteredFormHelperText>
{t("wallet.network-switching-message", {
wallet: "MetaMask",
})}
</CenteredFormHelperText>
)}
{Boolean(error) && (
<CenteredFormHelperText error>
{error.code === 4001 &&
t("wallet.operation-safely-rejected-message")}
{error.code === -32002 &&
t("wallet.operation-not-finished-message")}
</CenteredFormHelperText>
)}
</Box>
</Fade>
</Box>
<ActionButton
onClick={handleSwitch}
disabled={pending || success}
>
{pending || success
? t("wallet.network-switching-label", {
network: subNetworkName || networkName,
wallet: "MetaMask",
})
: t("wallet.network-switch-label", {
network: subNetworkName || networkName,
})}
</ActionButton>
</div>
)}
</Box>
</PaperContent>
</>
);
};
const CenteredFormHelperText = styled(FormHelperText)({
textAlign: "center",
});
export const createIndicatorClass = (className: string, color: string) => {
const { pulsingStyles, pulsingKeyframes } = createPulseAnimation(
color,
3,
className
);
return {
...pulsingKeyframes,
[className]: {
...pulsingStyles,
backgroundColor: color,
},
};
};
type WalletConnectionIndicatorStyles = Record<
"root" | "connected" | "disconnected" | "wrongNetwork" | "connecting",
string
>;
const useWalletConnectionIndicatorStyles = makeStyles((theme) => {
return {
root: {
width: 8,
height: 8,
borderRadius: 4,
backgroundColor: theme.palette.divider,
},
...createIndicatorClass("connected", theme.palette.success.main),
...createIndicatorClass("disconnected", theme.palette.error.main),
...createIndicatorClass("connecting", theme.palette.info.main),
...createIndicatorClass("wrongNetwork", theme.palette.warning.main),
};
});
type WalletConnectionIndicatorProps = {
status?: WalletConnectionStatusType;
className?: string; // TODO: find a better way
};
export const WalletConnectionIndicator: FunctionComponent<WalletConnectionIndicatorProps> = ({
status,
className: classNameProp,
}) => {
const styles = useWalletConnectionIndicatorStyles() as WalletConnectionIndicatorStyles;
const className = classNames(styles.root, classNameProp, {
[styles.connected]: status === WalletStatus.CONNECTED,
[styles.wrongNetwork]: status === WalletStatus.WRONG_NETWORK,
[styles.disconnected]: status === WalletStatus.DISCONNECTED,
[styles.connecting]: status === WalletStatus.CONNECTING,
});
return <div className={className} />;
};
const getWalletConnectionLabel = (
status: WalletConnectionStatusType,
t: TFunction
) => {
switch (status) {
case "disconnected":
return t("wallet.connect-wallet");
case "connecting":
return t("wallet.connecting");
case "connected":
return t("wallet.connected");
case "wrong_network":
return t("wallet.wrong-network");
}
};
const useWalletConnectionStatusButtonStyles = makeStyles<Theme>((theme) => ({
root: {
backgroundColor: theme.palette.common.white,
borderColor: theme.palette.divider,
boxShadow: defaultShadow,
"&:hover": {
borderColor: theme.palette.divider,
backgroundColor: theme.palette.divider,
},
},
hoisted: {
zIndex: theme.zIndex.tooltip,
},
indicator: {
marginRight: 10,
},
indicatorMobile: {
marginLeft: 16,
marginRight: 30,
},
account: { marginLeft: 20 },
}));
type WalletConnectionStatusButtonProps = ButtonProps & {
status: WalletConnectionStatusType;
wallet: BridgeWallet;
hoisted?: boolean;
account?: string;
mobile?: boolean;
};
export const WalletConnectionStatusButton: FunctionComponent<WalletConnectionStatusButtonProps> = ({
status,
account,
wallet,
hoisted,
className,
mobile,
...rest
}) => {
const { t } = useTranslation();
const {
indicator: indicatorClassName,
indicatorMobile: indicatorMobileClassName,
account: accountClassName,
hoisted: hoistedClassName,
...classes
} = useWalletConnectionStatusButtonStyles();
const label =
status === WalletStatus.CONNECTED
? getWalletConfig(wallet).short
: getWalletConnectionLabel(status, t);
const trimmedAddress = trimAddress(account);
const resolvedClassName = classNames(className, {
[hoistedClassName]: hoisted,
});
const buttonProps: any = mobile
? {}
: {
variant: "outlined",
color: "secondary",
classes,
};
return (
<Button className={resolvedClassName} {...buttonProps} {...rest}>
<WalletConnectionIndicator
status={status}
className={mobile ? indicatorMobileClassName : indicatorClassName}
/>
<span>{label}</span>
{trimmedAddress && (
<span className={accountClassName}>{trimmedAddress}</span>
)}
</Button>
);
};
const useBackToWalletPicker = (onClose: () => void) => {
const dispatch = useDispatch();
const handleBackToWalletPicker = useCallback(() => {
onClose();
setTimeout(() => {
dispatch(setWalletPickerOpened(true));
}, 1);
}, [dispatch, onClose]);
return handleBackToWalletPicker;
};
type AbstractConnectorInfoProps = {
wallet: string;
network: string;
link: string;
onBack: () => void;
onClose: () => void;
acknowledge: () => void;
};
const AbstractConnectorInfo: FunctionComponent<AbstractConnectorInfoProps> = ({
wallet,
network,
link,
onBack,
onClose,
acknowledge,
}) => {
const { t } = useTranslation();
return (
<>
<BridgeModalTitle title=" " onClose={onClose} onPrev={onBack} />
<SpacedPaperContent topPadding bottomPadding>
<Typography variant="h5" align="center" gutterBottom>
{t("wallet.connect-network-with-wallet-message", {
wallet,
network,
})}
</Typography>
<Typography
variant="body1"
align="center"
color="textSecondary"
gutterBottom
>
<Trans
i18nKey="wallet.ensure-network-added-message"
values={{
network,
wallet,
}}
components={[<Link href={link} external />]}
/>
</Typography>
</SpacedPaperContent>
<PaperContent bottomPadding>
<ActionButtonWrapper>
<Button variant="text" color="primary" onClick={onBack}>
{t("wallet.use-another-wallet-label")}
</Button>
</ActionButtonWrapper>
<ActionButtonWrapper>
<ActionButton onClick={acknowledge}>
{t("wallet.continue-with-wallet-label", { wallet })}
</ActionButton>
</ActionButtonWrapper>
</PaperContent>
</>
);
};
const getBscMmLink = (lang: string) => {
return `https://academy.binance.com/${lang}/articles/connecting-metamask-to-binance-smart-chain`;
};
export const BinanceMetamaskConnectorInfo: WalletPickerProps<
any,
any
>["DefaultInfo"] = ({ acknowledge, onClose }) => {
//TODO: not very elegant solution, Dialog should be extended with onBack/onPrev action
const { t, i18n } = useTranslation();
const handleBack = useBackToWalletPicker(onClose);
const wallet = "MetaMask";
return (
<>
<BridgeModalTitle title=" " onClose={onClose} onPrev={handleBack} />
<SpacedPaperContent topPadding bottomPadding>
<Typography variant="h5" align="center" gutterBottom>
{t("wallet.bsc-mm-connect-message")}
</Typography>
<Typography
variant="body1"
align="center"
color="textSecondary"
gutterBottom
>
{t("wallet.bsc-mm-connect-description")}{" "}
<Link href={getBscMmLink(i18n.language)} external>
{t("common.here")}
</Link>
</Typography>
</SpacedPaperContent>
<PaperContent bottomPadding>
<ActionButtonWrapper>
<Button variant="text" color="primary" onClick={handleBack}>
{t("wallet.use-another-wallet-label")}
</Button>
</ActionButtonWrapper>
<ActionButtonWrapper>
<ActionButton onClick={acknowledge}>
{t("wallet.continue-with-wallet-label", { wallet })}
</ActionButton>
</ActionButtonWrapper>
</PaperContent>
</>
);
};
export const AvalancheMetamaskConnectorInfo: WalletPickerProps<
any,
any
>["DefaultInfo"] = ({ acknowledge, onClose }) => {
const handleBack = useBackToWalletPicker(onClose);
const wallet = "MetaMask";
const network = "Avalanche";
const link =
"https://support.avax.network/en/articles/4626956-how-do-i-set-up-metamask-on-avalanche";
return (
<AbstractConnectorInfo
network={network}
wallet={wallet}
onBack={handleBack}
onClose={onClose}
acknowledge={acknowledge}
link={link}
/>
);
};
export const FantomMetamaskConnectorInfo: WalletPickerProps<
any,
any
>["DefaultInfo"] = ({ acknowledge, onClose }) => {
const handleBack = useBackToWalletPicker(onClose);
const wallet = "MetaMask";
const network = "Fantom";
const link = "https://docs.fantom.foundation/tutorials/set-up-metamask";
return (
<AbstractConnectorInfo
network={network}
wallet={wallet}
onBack={handleBack}
onClose={onClose}
acknowledge={acknowledge}
link={link}
/>
);
};
export const PolygonMetamaskConnectorInfo: WalletPickerProps<
any,
any
>["DefaultInfo"] = ({ acknowledge, onClose }) => {
const handleBack = useBackToWalletPicker(onClose);
const wallet = "MetaMask";
const network = "Polygon";
const link = "https://docs.matic.network/docs/develop/metamask/config-matic/";
return (
<AbstractConnectorInfo
network={network}
wallet={wallet}
onBack={handleBack}
onClose={onClose}
acknowledge={acknowledge}
link={link}
/>
);
};
export const ArbitrumMetamaskConnectorInfo: WalletPickerProps<
any,
any
>["DefaultInfo"] = ({ acknowledge, onClose }) => {
const handleBack = useBackToWalletPicker(onClose);
const wallet = "MetaMask";
const network = "Arbitrum";
// TODO: Update link once mainnet instructions are published.
const link = "https://developer.offchainlabs.com/docs/public_testnet";
return (
<AbstractConnectorInfo
network={network}
wallet={wallet}
onBack={handleBack}
onClose={onClose}
acknowledge={acknowledge}
link={link}
/>
);
};
type AddTokenButtonProps = {
onAddToken: (() => Promise<unknown>) | null;
wallet: string;
currency: string;
};
export const AddTokenButton: FunctionComponent<AddTokenButtonProps> = ({
onAddToken,
wallet,
currency,
}) => {
const { t } = useTranslation();
const [pending, setPending] = useState(false);
const handleAddToken = useCallback(() => {
if (onAddToken !== null) {
setPending(true);
onAddToken().finally(() => {
setPending(false);
});
}
}, [onAddToken]);
const show = onAddToken !== null;
const params = {
wallet: wallet,
currency: currency,
};
return (
<Fade in={show}>
<SecondaryActionButton disabled={pending} onClick={handleAddToken}>
{pending
? t("wallet.add-token-button-pending-label", params)
: t("wallet.add-token-button-label", params)}
</SecondaryActionButton>
</Fade>
);
}; | the_stack |
import { basename } from 'path'
import { FORM_ERROR } from 'final-form'
import * as R from 'ramda'
import * as React from 'react'
import type * as RF from 'react-final-form'
import * as redux from 'react-redux'
import * as M from '@material-ui/core'
import * as authSelectors from 'containers/Auth/selectors'
import { useData } from 'utils/Data'
import * as APIConnector from 'utils/APIConnector'
import * as AWS from 'utils/AWS'
import * as Sentry from 'utils/Sentry'
import { JsonSchema, makeSchemaValidator } from 'utils/json-schema'
import * as packageHandleUtils from 'utils/packageHandle'
import * as s3paths from 'utils/s3paths'
import * as workflows from 'utils/workflows'
import * as requests from '../requests'
import SelectWorkflow from './SelectWorkflow'
export const MAX_UPLOAD_SIZE = 20 * 1000 * 1000 * 1000 // 20GB
export const MAX_S3_SIZE = 50 * 1000 * 1000 * 1000 // 50GB
export const MAX_FILE_COUNT = 1000
export const ERROR_MESSAGES = {
UPLOAD: 'Error uploading files',
MANIFEST: 'Error creating manifest',
}
export const getNormalizedPath = (f: { path?: string; name: string }) => {
const p = f.path || f.name
return p.startsWith('/') ? p.substring(1) : p
}
export async function hashFile(file: File) {
if (!window.crypto?.subtle?.digest) throw new Error('Crypto API unavailable')
const buf = await file.arrayBuffer()
// XXX: consider using hashwasm for stream-based hashing to support larger files
const hashBuf = await window.crypto.subtle.digest('SHA-256', buf)
return Array.from(new Uint8Array(hashBuf))
.map((b) => b.toString(16).padStart(2, '0'))
.join('')
}
function cacheDebounce<I extends [any, ...any[]], O, K extends string | number | symbol>(
fn: (...args: I) => Promise<O>,
wait: number,
getKey: (...args: I) => K = R.identity as unknown as (...args: I) => K,
) {
type Resolver = (result: Promise<O>) => void
const cache = {} as Record<K, Promise<O>>
let timer: null | ReturnType<typeof setTimeout>
let resolveList: Resolver[] = []
return (...args: I) => {
const key = getKey(...args)
if (key in cache) return cache[key]
return new Promise((resolveNew: Resolver) => {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
timer = null
const result = fn(...args)
cache[key] = result
resolveList.forEach((resolve) => resolve(result))
resolveList = []
}, wait)
resolveList.push(resolveNew)
})
}
}
interface ApiRequest {
<O>(opts: {
endpoint: string
method?: 'GET' | 'PUT' | 'POST' | 'DELETE' | 'HEAD'
body?: {}
}): Promise<O>
}
const validateName = (req: ApiRequest) =>
cacheDebounce(async (name: string) => {
if (name) {
const res = await req<{ valid: boolean }>({
endpoint: '/package_name_valid',
method: 'POST',
body: { name },
})
if (!res.valid) return 'invalid'
}
return undefined
}, 200)
export function useNameValidator(workflow?: workflows.Workflow) {
const req: ApiRequest = APIConnector.use()
const [counter, setCounter] = React.useState(0)
const [processing, setProcessing] = React.useState(false)
const inc = React.useCallback(() => setCounter(R.inc), [setCounter])
const validator = React.useMemo(() => validateName(req), [req])
const validate = React.useCallback(
async (name: string) => {
if (workflow?.packageNamePattern?.test(name) === false) {
return 'pattern'
}
setProcessing(true)
try {
const error = await validator(name)
setProcessing(false)
return error
} catch (e) {
setProcessing(false)
return e instanceof Error ? (e.message as string) : ''
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[counter, validator, workflow?.packageNamePattern],
)
return React.useMemo(() => ({ validate, processing, inc }), [validate, processing, inc])
}
export function useNameExistence(bucket: string) {
const [counter, setCounter] = React.useState(0)
const inc = React.useCallback(() => setCounter(R.inc), [setCounter])
const s3 = AWS.S3.use()
// eslint-disable-next-line react-hooks/exhaustive-deps
const validate = React.useCallback(
cacheDebounce(async (name: string) => {
if (name) {
const packageExists = await requests.ensurePackageIsPresent({
s3,
bucket,
name,
})
if (packageExists) return 'exists'
}
return undefined
}, 200),
[bucket, counter, s3],
)
return React.useMemo(() => ({ validate, inc }), [validate, inc])
}
export function mkMetaValidator(schema?: JsonSchema) {
// TODO: move schema validation to utils/validators
// but don't forget that validation depends on library.
// Maybe we should split validators to files at first
const schemaValidator = makeSchemaValidator(schema)
return function validateMeta(value: object | null) {
const jsonObjectErr = value && !R.is(Object, value)
if (jsonObjectErr) {
return new Error('Metadata must be a valid JSON object')
}
if (schema) {
const errors = schemaValidator(value || {})
if (errors.length) return errors
}
return undefined
}
}
export type MetaValidator = ReturnType<typeof mkMetaValidator>
interface FieldProps {
error?: string
helperText?: React.ReactNode
validating?: boolean
}
const useFieldInputStyles = M.makeStyles({
root: {
// It hides M.CircularProgress (spinning square) overflow
overflow: 'hidden',
},
})
export function Field({
error,
helperText,
validating,
...rest
}: FieldProps & M.TextFieldProps) {
const inputClasses = useFieldInputStyles()
const props = {
InputLabelProps: { shrink: true },
InputProps: {
endAdornment: validating && <M.CircularProgress size={20} />,
classes: inputClasses,
},
error: !!error,
helperText: error || helperText,
...rest,
}
return <M.TextField {...props} />
}
interface PackageNameInputOwnProps {
errors: Record<string, React.ReactNode>
input: RF.FieldInputProps<string>
directory?: string
meta: RF.FieldMetaState<string>
validating: boolean
workflow: { packageName: packageHandleUtils.NameTemplates }
}
type PackageNameInputProps = PackageNameInputOwnProps &
Omit<Parameters<typeof Field>[0], keyof PackageNameInputOwnProps>
export function PackageNameInput({
errors,
input: { value, onChange },
meta,
workflow,
directory,
validating,
...rest
}: PackageNameInputProps) {
const readyForValidation = (value && meta.modified) || meta.submitFailed
const errorCode = readyForValidation && meta.error
const error = errorCode ? errors[errorCode] || errorCode : ''
const [modified, setModified] = React.useState(!!(meta.modified || value))
const handleChange = React.useCallback(
(event) => {
setModified(true)
onChange(event)
},
[onChange, setModified],
)
const props = {
disabled: meta.submitting || meta.submitSucceeded,
error,
fullWidth: true,
label: 'Name',
margin: 'normal' as const,
onChange: handleChange,
placeholder: 'e.g. user/package',
// NOTE: react-form doesn't change `FormState.validating` on async validation when field loses focus
validating,
value,
...rest,
}
const username = redux.useSelector(authSelectors.username)
React.useEffect(() => {
if (modified) return
const packageName = getDefaultPackageName(workflow, {
username,
directory,
})
if (!packageName) return
onChange({
target: {
value: packageName,
},
})
}, [directory, workflow, modified, onChange, username])
return <Field {...props} />
}
interface CommitMessageInputOwnProps {
errors: Record<string, React.ReactNode>
input: RF.FieldInputProps<string>
meta: RF.FieldMetaState<string>
}
type CommitMessageInputProps = CommitMessageInputOwnProps &
Omit<Parameters<typeof Field>[0], keyof CommitMessageInputOwnProps>
export function CommitMessageInput({
errors,
input,
meta,
...rest
}: CommitMessageInputProps) {
const errorCode = meta.submitFailed && meta.error
const error = errorCode ? errors[errorCode] || errorCode : ''
const props = {
disabled: meta.submitting || meta.submitSucceeded,
error,
fullWidth: true,
label: 'Commit message',
margin: 'normal' as const,
placeholder: 'Enter a commit message',
validating: meta.submitFailed && meta.validating,
...input,
...rest,
}
return <Field {...props} />
}
interface WorkflowInputProps {
input: RF.FieldInputProps<workflows.Workflow>
meta: RF.FieldMetaState<workflows.Workflow>
workflowsConfig?: workflows.WorkflowsConfig
errors?: Record<string, React.ReactNode>
}
export function WorkflowInput({
input,
meta,
workflowsConfig,
errors = {},
}: WorkflowInputProps) {
const disabled = meta.submitting || meta.submitSucceeded
const errorKey = meta.submitFailed && meta.error
return (
<SelectWorkflow
items={workflowsConfig ? workflowsConfig.workflows : []}
onChange={input.onChange}
value={input.value}
disabled={disabled}
error={errorKey ? errors[errorKey] || errorKey : undefined}
/>
)
}
export const defaultWorkflowFromConfig = (cfg?: workflows.WorkflowsConfig) =>
cfg && cfg.workflows.find((item) => item.isDefault)
export function useWorkflowValidator(workflowsConfig?: workflows.WorkflowsConfig) {
return React.useMemo(
() => (workflow?: workflows.Workflow) => {
if (!workflowsConfig?.isWorkflowRequired) return undefined
if (workflow && workflow.slug !== workflows.notSelected) return undefined
return 'required'
},
[workflowsConfig?.isWorkflowRequired],
)
}
export interface SchemaFetcherRenderPropsLoading {
responseError: undefined
schema: undefined
schemaLoading: true
selectedWorkflow: workflows.Workflow | undefined
validate: MetaValidator
}
export interface SchemaFetcherRenderPropsSuccess {
responseError: undefined
schema?: JsonSchema
schemaLoading: false
selectedWorkflow: workflows.Workflow | undefined
validate: MetaValidator
}
export interface SchemaFetcherRenderPropsError {
responseError: Error
schema: undefined
schemaLoading: false
selectedWorkflow: workflows.Workflow | undefined
validate: MetaValidator
}
export type SchemaFetcherRenderProps =
| SchemaFetcherRenderPropsLoading
| SchemaFetcherRenderPropsSuccess
| SchemaFetcherRenderPropsError
const noopValidator: MetaValidator = () => undefined
interface SchemaFetcherProps {
manifest?: {
workflow?: {
id?: string
}
}
workflow?: workflows.Workflow
workflowsConfig: workflows.WorkflowsConfig
children: (props: SchemaFetcherRenderProps) => React.ReactElement
}
export function SchemaFetcher({
manifest,
workflow,
workflowsConfig,
children,
}: SchemaFetcherProps) {
const s3 = AWS.S3.use()
const sentry = Sentry.use()
const slug = manifest?.workflow?.id
const initialWorkflow = React.useMemo(() => {
// reuse workflow from previous revision if it's still present in the config
if (slug) {
const w = workflowsConfig.workflows.find(R.propEq('slug', slug))
if (w) return w
}
return defaultWorkflowFromConfig(workflowsConfig)
}, [slug, workflowsConfig])
const selectedWorkflow = workflow || initialWorkflow
if (!selectedWorkflow) {
const error = new Error(`"default_workflow" or "workflow.id" doesn't exist`)
sentry('captureException', error)
// eslint-disable-next-line no-console
console.error(error)
}
const schemaUrl = R.pathOr('', ['schema', 'url'], selectedWorkflow)
const data = useData(requests.metadataSchema, { s3, schemaUrl })
const res: SchemaFetcherRenderProps = React.useMemo(
() =>
data.case({
Ok: (schema?: JsonSchema) =>
({
schema,
schemaLoading: false,
selectedWorkflow,
validate: mkMetaValidator(schema),
} as SchemaFetcherRenderPropsSuccess),
Err: (responseError: Error) =>
({
responseError,
schemaLoading: false,
selectedWorkflow,
validate: mkMetaValidator(),
} as SchemaFetcherRenderPropsError),
_: () =>
({
schemaLoading: true,
selectedWorkflow,
validate: noopValidator,
} as SchemaFetcherRenderPropsLoading),
}),
[data, selectedWorkflow],
)
return children(res)
}
export function useCryptoApiValidation() {
return React.useCallback(() => {
const isCryptoApiAvailable =
window.crypto && window.crypto.subtle && window.crypto.subtle.digest
return {
[FORM_ERROR]: !isCryptoApiAvailable
? 'Quilt requires the Web Cryptography API. Please try another browser.'
: undefined,
}
}, [])
}
export function calcDialogHeight(windowHeight: number, metaHeight: number): number {
const neededSpace = 345 /* space to fit other inputs */ + metaHeight
const availableSpace = windowHeight - 200 /* free space for headers */
const minimalSpace = 420 /* minimal height */
if (availableSpace < minimalSpace) return minimalSpace
return R.clamp(minimalSpace, availableSpace, neededSpace)
}
export const useContentStyles = M.makeStyles({
root: {
height: ({ metaHeight }: { metaHeight: number }) =>
calcDialogHeight(window.innerHeight, metaHeight),
paddingTop: 0,
},
})
export function getUsernamePrefix(username?: string | null) {
if (!username) return ''
const name = username.includes('@') ? username.split('@')[0] : username
// see PACKAGE_NAME_FORMAT at quilt3/util.py
const validParts = name.match(/\w+/g)
return validParts ? `${validParts.join('')}/` : ''
}
const getDefaultPackageName = (
workflow: { packageName: packageHandleUtils.NameTemplates },
{ directory, username }: { directory?: string; username: string },
) => {
const usernamePrefix = getUsernamePrefix(username)
const templateBasedName =
typeof directory === 'string'
? packageHandleUtils.execTemplate(workflow?.packageName, 'files', {
directory: basename(directory),
username: s3paths.ensureNoSlash(usernamePrefix),
})
: packageHandleUtils.execTemplate(workflow?.packageName, 'packages', {
username: s3paths.ensureNoSlash(usernamePrefix),
})
return typeof templateBasedName === 'string' ? templateBasedName : usernamePrefix
}
const usePackageNameWarningStyles = M.makeStyles({
root: {
marginRight: '4px',
verticalAlign: '-5px',
},
})
interface PackageNameWarningProps {
exists?: boolean
}
export const PackageNameWarning = ({ exists }: PackageNameWarningProps) => {
const classes = usePackageNameWarningStyles()
return (
<>
<M.Icon className={classes.root} fontSize="small">
info_outlined
</M.Icon>
{exists ? 'Existing package' : 'New package'}
</>
)
}
interface DialogWrapperProps {
exited: boolean
}
export function DialogWrapper({
exited,
...props
}: DialogWrapperProps & React.ComponentProps<typeof M.Dialog>) {
const refProps = { exited, onExited: props.onExited }
const ref = React.useRef<typeof refProps>()
ref.current = refProps
React.useEffect(
() => () => {
// call onExited on unmount if it has not been called yet
if (!ref.current!.exited && ref.current!.onExited)
(ref.current!.onExited as () => void)()
},
[],
)
return <M.Dialog {...props} />
}
export function useEntriesValidator(workflow?: workflows.Workflow) {
const s3 = AWS.S3.use()
return React.useCallback(
async (entries: $TSFixMe) => {
const schemaUrl = workflow?.entriesSchema
if (!schemaUrl) return undefined
const entriesSchema = await requests.objectSchema({ s3, schemaUrl })
// TODO: Show error if there is network error
if (!entriesSchema) return undefined
return makeSchemaValidator(entriesSchema)(entries)
},
[workflow, s3],
)
} | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace FormRecurring_Appointment {
interface Header extends DevKit.Controls.IHeader {
/** Enter the user or team who is assigned to manage the record. This field is updated every time the record is assigned to a different user. */
OwnerId: DevKit.Controls.Lookup;
/** Select the priority so that preferred customers or critical issues are handled quickly. */
PriorityCode: DevKit.Controls.OptionSet;
/** Shows whether the recurring appointment is open, scheduled, completed, or canceled. Completed and canceled appointments are read-only and can't be edited. */
StateCode: DevKit.Controls.OptionSet;
}
interface tab_SUMMARY_TAB_Sections {
appointment_description: DevKit.Controls.Section;
general_information: DevKit.Controls.Section;
tab_2_section_2: DevKit.Controls.Section;
}
interface tab_SUMMARY_TAB extends DevKit.Controls.ITab {
Section: tab_SUMMARY_TAB_Sections;
}
interface Tabs {
SUMMARY_TAB: tab_SUMMARY_TAB;
}
interface Body {
Tab: Tabs;
/** Type additional information to describe the recurring appointment, such as key talking points or objectives. */
Description: DevKit.Controls.String;
/** Type the location where the recurring appointment will take place, such as a conference room or customer office. */
Location: DevKit.Controls.String;
/** Enter the account, contact, lead, user, or other equipment resources that are not needed at the recurring appointment, but can optionally attend. */
OptionalAttendees: DevKit.Controls.Lookup;
/** Choose the record that the recurring appointment series relates to. */
RegardingObjectId: DevKit.Controls.Lookup;
/** Enter the account, contact, lead, user, or other equipment resources that are required to attend the recurring appointment. */
RequiredAttendees: DevKit.Controls.Lookup;
/** Type a short description about the objective or primary topic of the recurring appointment. */
Subject: DevKit.Controls.String;
}
}
class FormRecurring_Appointment extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Recurring_Appointment
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form Recurring_Appointment */
Body: DevKit.FormRecurring_Appointment.Body;
/** The Header section of form Recurring_Appointment */
Header: DevKit.FormRecurring_Appointment.Header;
}
class RecurringAppointmentMasterApi {
/**
* DynamicsCrm.DevKit RecurringAppointmentMasterApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Unique identifier of the recurring appointment series. */
ActivityId: DevKit.WebApi.GuidValue;
/** Type a category to identify the recurring appointment type, such as status meeting or service call, to tie the appointment to a business group or function. */
Category: DevKit.WebApi.StringValue;
/** Shows who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who created the record on behalf of another user. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** The day of the month on which the recurring appointment occurs. */
DayOfMonth: DevKit.WebApi.IntegerValue;
/** Bitmask that represents the days of the week on which the recurring appointment occurs. */
DaysOfWeekMask: DevKit.WebApi.IntegerValue;
/** List of deleted instances of the recurring appointment series. */
DeletedExceptionsList: DevKit.WebApi.StringValueReadonly;
/** Type additional information to describe the recurring appointment, such as key talking points or objectives. */
Description: DevKit.WebApi.StringValue;
/** Duration of the recurring appointment series in minutes. */
Duration: DevKit.WebApi.IntegerValue;
/** Actual end date of the recurring appointment series based on the specified end date and recurrence pattern. */
EffectiveEndDate_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Actual start date of the recurring appointment series based on the specified start date and recurrence pattern. */
EffectiveStartDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** End time of the associated activity. */
EndTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Shows the conversion rate of the record's currency. The exchange rate is used to convert all money fields in the record from the local currency to the system's default currency. */
ExchangeRate: DevKit.WebApi.DecimalValueReadonly;
/** State code to indicate whether the recurring appointment series is expanded fully or partially. */
ExpansionStateCode: DevKit.WebApi.OptionSetValueReadonly;
/** First day of week for the recurrence pattern. */
FirstDayOfWeek: DevKit.WebApi.IntegerValue;
/** Unique Outlook identifier to correlate recurring appointment series across Exchange mailboxes. */
GlobalObjectId: DevKit.WebApi.StringValue;
/** Unique identifier of the recurring appointment series for which the recurrence information was updated. */
GroupId: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the data import or data migration that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Specifies the recurring appointment series to occur on every Nth day of a month. Valid for monthly and yearly recurrence patterns only. */
Instance: DevKit.WebApi.OptionSetValue;
/** Type of instance of a recurring appointment series. */
InstanceTypeCode: DevKit.WebApi.OptionSetValueReadonly;
/** Number of units of a given recurrence type between occurrences. */
Interval: DevKit.WebApi.IntegerValue;
/** Select whether the recurring appointment is an all-day event to make sure that the required resources are scheduled for the full day. */
IsAllDayEvent: DevKit.WebApi.BooleanValue;
/** Indicates whether the recurring appointment series was billed as part of resolving a case. */
IsBilled: DevKit.WebApi.BooleanValue;
/** For internal use only. */
IsMapiPrivate: DevKit.WebApi.BooleanValue;
/** Indicates whether the recurring appointment series should occur after every N months. Valid for monthly recurrence pattern only. */
IsNthMonthly: DevKit.WebApi.BooleanValue;
/** Indicates whether the recurring appointment series should occur after every N years. Valid for yearly recurrence pattern only. */
IsNthYearly: DevKit.WebApi.BooleanValue;
/** For internal use only. */
IsRegenerate: DevKit.WebApi.BooleanValue;
/** Indicates whether the activity is a regular activity type or event type. */
IsRegularActivity: DevKit.WebApi.BooleanValueReadonly;
/** For internal use only. */
IsUnsafe: DevKit.WebApi.IntegerValueReadonly;
/** Indicates whether the weekly recurrence pattern is a daily weekday pattern. Valid for weekly recurrence pattern only. */
IsWeekDayPattern: DevKit.WebApi.BooleanValue;
/** Indicates whether the recurring appointment series was created from a workflow rule. */
IsWorkflowCreated: DevKit.WebApi.BooleanValue;
/** Date of last expanded instance of a recurring appointment series. */
LastExpandedInstanceDate_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Type the location where the recurring appointment will take place, such as a conference room or customer office. */
Location: DevKit.WebApi.StringValue;
/** Shows who last updated the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Shows who last updated the record on behalf of another user. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Indicates the month of the year for the recurrence pattern. */
MonthOfYear: DevKit.WebApi.OptionSetValue;
/** Date of the next expanded instance of a recurring appointment series. */
NextExpansionInstanceDate_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Number of appointment occurrences in a recurring appointment series. */
Occurrences: DevKit.WebApi.IntegerValue;
/** Unique identifier of the Microsoft Office Outlook recurring appointment series owner that correlates to the PR_OWNER_APPT_ID MAPI property. */
OutlookOwnerApptId: DevKit.WebApi.IntegerValue;
/** Date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValue;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValue;
/** Unique identifier of the business unit that owns the recurring appointment series. */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the team who owns the recurring appointment series. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the user who owns the recurring appointment series. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** End date of the recurrence range. */
PatternEndDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Select the type of end date for the recurring appointment, such as no end date or the number of occurrences. */
PatternEndType: DevKit.WebApi.OptionSetValue;
/** Start date of the recurrence range. */
PatternStartDate_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Select the priority so that preferred customers or critical issues are handled quickly. */
PriorityCode: DevKit.WebApi.OptionSetValue;
/** Shows the ID of the process. */
ProcessId: DevKit.WebApi.GuidValue;
/** Select the pattern type for the recurring appointment to indicate whether the appointment occurs daily, weekly, monthly, or yearly. */
RecurrencePatternType: DevKit.WebApi.OptionSetValue;
/** Choose the record that the recurring appointment series relates to. */
regardingobjectid_account_recurringappointmentmaster: DevKit.WebApi.LookupValue;
/** Choose the record that the recurring appointment series relates to. */
regardingobjectid_contact_recurringappointmentmaster: DevKit.WebApi.LookupValue;
/** Choose the record that the recurring appointment series relates to. */
regardingobjectid_knowledgearticle_recurringappointmentmaster: DevKit.WebApi.LookupValue;
/** Choose the record that the recurring appointment series relates to. */
regardingobjectid_knowledgebaserecord_recurringappointmentmaster: DevKit.WebApi.LookupValue;
/** Unique identifier of the recurrence rule that is associated with the recurring appointment series. */
RuleId: DevKit.WebApi.LookupValueReadonly;
/** Safe body text of the recurring appointment. */
SafeDescription: DevKit.WebApi.StringValueReadonly;
/** Scheduled end time of the recurring appointment series. */
ScheduledEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Scheduled start time of the recurring appointment series. */
ScheduledStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Indicates whether the recurring appointment series is active or inactive. */
SeriesStatus: DevKit.WebApi.BooleanValue;
/** Shows the date and time by which the activities are sorted. */
SortDate_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Shows the ID of the stage. */
StageId: DevKit.WebApi.GuidValue;
/** Start time of the recurring appointment series. */
StartTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Shows whether the recurring appointment is open, scheduled, completed, or canceled. Completed and canceled appointments are read-only and can't be edited. */
StateCode: DevKit.WebApi.OptionSetValue;
/** Select the recurring appointment's status. */
StatusCode: DevKit.WebApi.OptionSetValue;
/** Type a subcategory to identify the recurring appointment type and relate the activity to a specific product, sales region, business group, or other function. */
Subcategory: DevKit.WebApi.StringValue;
/** Type a short description about the objective or primary topic of the recurring appointment. */
Subject: DevKit.WebApi.StringValue;
/** For internal use only. */
SubscriptionId: DevKit.WebApi.GuidValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Choose the local currency for the record to make sure budgets are reported in the correct currency. */
TransactionCurrencyId: DevKit.WebApi.LookupValue;
/** For internal use only. */
TraversedPath: DevKit.WebApi.StringValue;
/** Time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
/** The array of object that can cast object to ActivityPartyApi class */
ActivityParties: Array<any>;
}
}
declare namespace OptionSet {
namespace RecurringAppointmentMaster {
enum ExpansionStateCode {
/** 2 */
Full,
/** 1 */
Partial,
/** 0 */
Unexpanded
}
enum Instance {
/** 1 */
First,
/** 4 */
Fourth,
/** 5 */
Last,
/** 2 */
Second,
/** 3 */
Third
}
enum InstanceTypeCode {
/** 0 */
Not_Recurring,
/** 3 */
Recurring_Exception,
/** 4 */
Recurring_Future_Exception,
/** 2 */
Recurring_Instance,
/** 1 */
Recurring_Master
}
enum MonthOfYear {
/** 4 */
April,
/** 8 */
August,
/** 12 */
December,
/** 2 */
February,
/** 0 */
Invalid_Month_Of_Year,
/** 1 */
January,
/** 7 */
July,
/** 6 */
June,
/** 3 */
March,
/** 5 */
May,
/** 11 */
November,
/** 10 */
October,
/** 9 */
September
}
enum PatternEndType {
/** 1 */
No_End_Date,
/** 2 */
Occurrences,
/** 3 */
Pattern_End_Date
}
enum PriorityCode {
/** 2 */
High,
/** 0 */
Low,
/** 1 */
Normal
}
enum RecurrencePatternType {
/** 0 */
Daily,
/** 2 */
Monthly,
/** 1 */
Weekly,
/** 3 */
Yearly
}
enum StateCode {
/** 2 */
Canceled,
/** 1 */
Completed,
/** 0 */
Open,
/** 3 */
Scheduled
}
enum StatusCode {
/** 5 */
Busy,
/** 4 */
Canceled,
/** 3 */
Completed,
/** 1 */
Free,
/** 6 */
Out_of_Office,
/** 2 */
Tentative
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Recurring Appointment'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import { Assert, AITestClass } from "@microsoft/ai-test-framework";
import { AppInsightsCore } from "../../../src/JavaScriptSDK/AppInsightsCore";
import { IChannelControls } from "../../../src/JavaScriptSDK.Interfaces/IChannelControls";
import { _InternalMessageId, LoggingSeverity } from "../../../src/JavaScriptSDK.Enums/LoggingEnums";
import { _InternalLogMessage, DiagnosticLogger } from "../../../src/JavaScriptSDK/DiagnosticLogger";
import { IConfiguration } from "../../../src/JavaScriptSDK.Interfaces/IConfiguration";
import { IPlugin, ITelemetryPlugin } from "../../../src/JavaScriptSDK.Interfaces/ITelemetryPlugin";
import { ITelemetryItem } from "../../../src/JavaScriptSDK.Interfaces/ITelemetryItem";
import { BaseTelemetryPlugin } from "../../../src/JavaScriptSDK/BaseTelemetryPlugin";
import { IAppInsightsCore } from "../../../src/JavaScriptSDK.Interfaces/IAppInsightsCore";
import { ITelemetryPluginChain } from "../../../src/JavaScriptSDK.Interfaces/ITelemetryPluginChain";
import { IProcessTelemetryContext } from "../../../src/JavaScriptSDK.Interfaces/IProcessTelemetryContext";
const AIInternalMessagePrefix = "AITR_";
const MaxInt32 = 0xFFFFFFFF;
export class DynamicTests extends AITestClass {
public testInitialize() {
super.testInitialize();
}
public testCleanup() {
super.testCleanup();
}
public registerTests() {
this.testCase({
name: "Dynamic disable: Initialization with plugins and disable shared trackPlugin",
test: () => {
const coreChannelPlugin = new TestChannelPlugin();
const sharedChannelPlugin = new TestChannelPlugin();
const trackPlugin = new TrackPlugin();
const appInsightsCore = new AppInsightsCore();
const appInsightsSharedCore = new AppInsightsCore();
const config: IConfiguration = {
instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41"
};
try {
appInsightsCore.initialize(config, [coreChannelPlugin, new TestPlugin(), trackPlugin, new TestSamplingPlugin()]);
} catch (error) {
Assert.ok(false, "Everything should be initialized");
}
Assert.equal(1, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal(0, coreChannelPlugin.events[0].data.trackPlugin);
Assert.equal(true, coreChannelPlugin.events[0].data.sampled);
try {
appInsightsSharedCore.initialize(config, [sharedChannelPlugin, new TestPlugin(), trackPlugin, new TestSamplingPlugin()]);
} catch (error) {
Assert.ok(false, "Everything should be initialized");
}
// The 2nd usage of the trackPlugin doesn't call initialize so we won't have any additional event (from the initialize of trackPlugin)
Assert.equal(0, sharedChannelPlugin.events.length, "We should have a track call");
let testTrackPlugin = appInsightsCore.getPlugin(trackPlugin.identifier);
Assert.ok(testTrackPlugin != null, "Track plugin should be returned");
Assert.equal(trackPlugin, testTrackPlugin.plugin, "The returned plugin should be the same instance");
let testSharedTrackPlugin = appInsightsSharedCore.getPlugin(trackPlugin.identifier);
Assert.ok(testSharedTrackPlugin != null, "Shared Track plugin should be returned");
Assert.equal(trackPlugin, testSharedTrackPlugin.plugin, "The returned Shared plugin should be the same instance");
appInsightsCore.track({
name: "MyCustomEvent"
});
appInsightsSharedCore.track({
name: "MySharedCustomEvent"
});
Assert.equal(2, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal("MyCustomEvent", coreChannelPlugin.events[1].name);
Assert.equal(1, coreChannelPlugin.events[1].data.trackPlugin);
Assert.equal(true, coreChannelPlugin.events[1].data.sampled);
Assert.equal(1, sharedChannelPlugin.events.length, "We should have a track call");
Assert.equal("MySharedCustomEvent", sharedChannelPlugin.events[0].name);
Assert.equal(2, sharedChannelPlugin.events[0].data.trackPlugin);
Assert.equal(true, sharedChannelPlugin.events[0].data.sampled);
// Disable the shared instance track plugin
appInsightsSharedCore.getPlugin(trackPlugin.identifier).setEnabled(false);
appInsightsCore.track({
name: "MyCustomEvent2"
});
appInsightsSharedCore.track({
name: "MySharedCustomEvent2"
});
Assert.equal(3, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal("MyCustomEvent2", coreChannelPlugin.events[2].name);
Assert.equal(undefined, (coreChannelPlugin.events[2].data || {}).trackPlugin);
Assert.equal(true, coreChannelPlugin.events[2].data.sampled);
Assert.equal(2, sharedChannelPlugin.events.length, "We should have a track call");
Assert.equal("MySharedCustomEvent2", sharedChannelPlugin.events[1].name);
Assert.equal(undefined, (sharedChannelPlugin.events[1].data || {}).trackPlugin, "The track plugin should not have been applied to the shared instance");
Assert.equal(true, sharedChannelPlugin.events[1].data.sampled);
}
});
this.testCase({
name: "Dynamic disable: Initialization with plugins and disable core but not trackPlugin",
test: () => {
const coreChannelPlugin = new TestChannelPlugin();
const sharedChannelPlugin = new TestChannelPlugin();
const trackPlugin = new TrackPlugin();
const appInsightsCore = new AppInsightsCore();
const appInsightsSharedCore = new AppInsightsCore();
const config: IConfiguration = {
instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41"
};
try {
appInsightsCore.initialize(config, [coreChannelPlugin, new TestPlugin(), trackPlugin, new TestSamplingPlugin()]);
} catch (error) {
Assert.ok(false, "Everything should be initialized");
}
Assert.equal(1, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal(0, coreChannelPlugin.events[0].data.trackPlugin);
Assert.equal(true, coreChannelPlugin.events[0].data.sampled);
try {
appInsightsSharedCore.initialize(config, [sharedChannelPlugin, new TestPlugin(), trackPlugin, new TestSamplingPlugin()]);
} catch (error) {
Assert.ok(false, "Everything should be initialized");
}
// The 2nd usage of the trackPlugin doesn't call initialize so we won't have any additional event (from the initialize of trackPlugin)
Assert.equal(0, sharedChannelPlugin.events.length, "We should have a track call");
let testTrackPlugin = appInsightsCore.getPlugin(trackPlugin.identifier);
Assert.ok(testTrackPlugin != null, "Track plugin should be returned");
Assert.equal(trackPlugin, testTrackPlugin.plugin, "The returned plugin should be the same instance");
let testSharedTrackPlugin = appInsightsSharedCore.getPlugin(trackPlugin.identifier);
Assert.ok(testSharedTrackPlugin != null, "Shared Track plugin should be returned");
Assert.equal(trackPlugin, testSharedTrackPlugin.plugin, "The returned Shared plugin should be the same instance");
appInsightsCore.track({
name: "MyCustomEvent"
});
appInsightsSharedCore.track({
name: "MySharedCustomEvent"
});
Assert.equal(2, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal("MyCustomEvent", coreChannelPlugin.events[1].name);
Assert.equal(1, coreChannelPlugin.events[1].data.trackPlugin);
Assert.equal(true, coreChannelPlugin.events[1].data.sampled);
Assert.equal(1, sharedChannelPlugin.events.length, "We should have a track call");
Assert.equal("MySharedCustomEvent", sharedChannelPlugin.events[0].name);
Assert.equal(2, sharedChannelPlugin.events[0].data.trackPlugin);
Assert.equal(true, sharedChannelPlugin.events[0].data.sampled);
appInsightsCore.getPlugin(trackPlugin.identifier).setEnabled(false);
appInsightsCore.track({
name: "MyCustomEvent2"
});
appInsightsSharedCore.track({
name: "MySharedCustomEvent2"
});
Assert.equal(3, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal("MyCustomEvent2", coreChannelPlugin.events[2].name);
Assert.equal(undefined, (coreChannelPlugin.events[2].data || {}).trackPlugin);
Assert.equal(true, coreChannelPlugin.events[2].data.sampled);
Assert.equal(2, sharedChannelPlugin.events.length, "We should have a track call");
Assert.equal("MySharedCustomEvent2", sharedChannelPlugin.events[1].name);
Assert.equal(undefined, (sharedChannelPlugin.events[1].data || {}).trackPlugin, "The track plugin should not have been applied to the shared instance");
Assert.equal(true, sharedChannelPlugin.events[1].data.sampled);
}
});
this.testCase({
name: "Dynamic disable: Initialization with plugins and disable shared old trackPlugin",
test: () => {
const coreChannelPlugin = new TestChannelPlugin();
const sharedChannelPlugin = new TestChannelPlugin();
const oldTrackPlugin = new OldTrackPlugin();
const appInsightsCore = new AppInsightsCore();
const appInsightsSharedCore = new AppInsightsCore();
const config: IConfiguration = {
instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41"
};
try {
appInsightsCore.initialize(config, [coreChannelPlugin, new TestPlugin(), oldTrackPlugin, new TestSamplingPlugin()]);
} catch (error) {
Assert.ok(false, "Everything should be initialized");
}
Assert.equal(1, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal(0, coreChannelPlugin.events[0].data.trackPlugin);
Assert.equal(true, coreChannelPlugin.events[0].data.sampled);
try {
appInsightsSharedCore.initialize(config, [sharedChannelPlugin, new TestPlugin(), oldTrackPlugin, new TestSamplingPlugin()]);
} catch (error) {
Assert.ok(false, "Everything should be initialized");
}
// The 2nd usage of the trackPlugin doesn't call initialize so we won't have any additional event (from the initialize of trackPlugin)
Assert.equal(0, sharedChannelPlugin.events.length, "We should have a track call");
let testTrackPlugin = appInsightsCore.getPlugin(oldTrackPlugin.identifier);
Assert.ok(testTrackPlugin != null, "Track plugin should be returned");
Assert.equal(oldTrackPlugin, testTrackPlugin.plugin, "The returned plugin should be the same instance");
let testSharedTrackPlugin = appInsightsSharedCore.getPlugin(oldTrackPlugin.identifier);
Assert.ok(testSharedTrackPlugin != null, "Shared Track plugin should be returned");
Assert.equal(oldTrackPlugin, testSharedTrackPlugin.plugin, "The returned Shared plugin should be the same instance");
appInsightsCore.track({
name: "MyCustomEvent"
});
appInsightsSharedCore.track({
name: "MySharedCustomEvent"
});
Assert.equal(2, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal("MyCustomEvent", coreChannelPlugin.events[1].name);
Assert.equal(1, coreChannelPlugin.events[1].data.trackPlugin);
Assert.equal(true, coreChannelPlugin.events[1].data.sampled);
Assert.equal(1, sharedChannelPlugin.events.length, "We should have a track call");
Assert.equal("MySharedCustomEvent", sharedChannelPlugin.events[0].name);
Assert.equal(2, sharedChannelPlugin.events[0].data.trackPlugin);
Assert.equal(true, sharedChannelPlugin.events[0].data.sampled);
appInsightsSharedCore.getPlugin(oldTrackPlugin.identifier).setEnabled(false);
appInsightsCore.track({
name: "MyCustomEvent2"
});
appInsightsSharedCore.track({
name: "MySharedCustomEvent2"
});
Assert.equal(3, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal("MyCustomEvent2", coreChannelPlugin.events[2].name);
Assert.equal(undefined, (coreChannelPlugin.events[2].data || {}).trackPlugin);
Assert.equal(true, coreChannelPlugin.events[2].data.sampled);
Assert.equal(2, sharedChannelPlugin.events.length, "We should have a track call");
Assert.equal("MySharedCustomEvent2", sharedChannelPlugin.events[1].name);
Assert.equal(undefined, (sharedChannelPlugin.events[1].data || {}).trackPlugin, "The track plugin should not have been applied to the shared instance");
Assert.equal(true, sharedChannelPlugin.events[1].data.sampled);
}
});
this.testCase({
name: "Dynamic disable: Initialization with plugins and disable core but not old trackPlugin",
test: () => {
const coreChannelPlugin = new TestChannelPlugin();
const sharedChannelPlugin = new TestChannelPlugin();
const oldTrackPlugin = new OldTrackPlugin();
const appInsightsCore = new AppInsightsCore();
const appInsightsSharedCore = new AppInsightsCore();
const config: IConfiguration = {
instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41"
};
try {
appInsightsCore.initialize(config, [coreChannelPlugin, new TestPlugin(), oldTrackPlugin, new TestSamplingPlugin()]);
} catch (error) {
Assert.ok(false, "Everything should be initialized");
}
Assert.equal(1, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal(0, coreChannelPlugin.events[0].data.trackPlugin);
Assert.equal(true, coreChannelPlugin.events[0].data.sampled);
try {
appInsightsSharedCore.initialize(config, [sharedChannelPlugin, new TestPlugin(), oldTrackPlugin, new TestSamplingPlugin()]);
} catch (error) {
Assert.ok(false, "Everything should be initialized");
}
// The 2nd usage of the trackPlugin doesn't call initialize so we won't have any additional event (from the initialize of trackPlugin)
Assert.equal(0, sharedChannelPlugin.events.length, "We should have a track call");
let testTrackPlugin = appInsightsCore.getPlugin(oldTrackPlugin.identifier);
Assert.ok(testTrackPlugin != null, "Track plugin should be returned");
Assert.equal(oldTrackPlugin, testTrackPlugin.plugin, "The returned plugin should be the same instance");
let testSharedTrackPlugin = appInsightsSharedCore.getPlugin(oldTrackPlugin.identifier);
Assert.ok(testSharedTrackPlugin != null, "Shared Track plugin should be returned");
Assert.equal(oldTrackPlugin, testSharedTrackPlugin.plugin, "The returned Shared plugin should be the same instance");
appInsightsCore.track({
name: "MyCustomEvent"
});
appInsightsSharedCore.track({
name: "MySharedCustomEvent"
});
Assert.equal(2, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal("MyCustomEvent", coreChannelPlugin.events[1].name);
Assert.equal(1, coreChannelPlugin.events[1].data.trackPlugin);
Assert.equal(true, coreChannelPlugin.events[1].data.sampled);
Assert.equal(1, sharedChannelPlugin.events.length, "We should have a track call");
Assert.equal("MySharedCustomEvent", sharedChannelPlugin.events[0].name);
Assert.equal(2, sharedChannelPlugin.events[0].data.trackPlugin);
Assert.equal(true, sharedChannelPlugin.events[0].data.sampled);
appInsightsCore.getPlugin(oldTrackPlugin.identifier).setEnabled(false);
appInsightsCore.track({
name: "MyCustomEvent2"
});
appInsightsSharedCore.track({
name: "MySharedCustomEvent2"
});
Assert.equal(3, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal("MyCustomEvent2", coreChannelPlugin.events[2].name);
Assert.equal(undefined, (coreChannelPlugin.events[2].data || {}).trackPlugin);
Assert.equal(true, coreChannelPlugin.events[2].data.sampled);
Assert.equal(2, sharedChannelPlugin.events.length, "We should have a track call");
Assert.equal("MySharedCustomEvent2", sharedChannelPlugin.events[1].name);
Assert.equal(undefined, (sharedChannelPlugin.events[1].data || {}).trackPlugin, "The track plugin should not have been applied to the shared instance");
Assert.equal(true, sharedChannelPlugin.events[1].data.sampled);
}
});
this.testCase({
name: "Dynamic unload: Initialization and unload with Channel",
test: () => {
const samplingPlugin = new TestSamplingPlugin();
const channelPlugin = new TestChannelPlugin();
const appInsightsCore = new AppInsightsCore();
const config: IConfiguration = {
instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41"
};
try {
appInsightsCore.initialize(config, [channelPlugin]);
} catch (error) {
Assert.ok(false, "Everything should be initialized");
}
let testSender = appInsightsCore.getPlugin("TestSender");
Assert.ok(testSender != null, "Sender should be returned");
Assert.equal(channelPlugin, testSender.plugin, "The returned plugin should be the instance we passed in");
let unloadComplete = false;
appInsightsCore.unload(false, () => {
unloadComplete = true;
});
Assert.equal(true, unloadComplete, "Unload should have been completed synchronously");
Assert.equal(true, channelPlugin.isTearDownInvoked, "Teardown should have been called");
Assert.equal(false, appInsightsCore.isInitialized(), "Core should be no longer initialized");
Assert.equal(null, appInsightsCore.getPlugin("TestSender"), "Sender should no longer be loaded");
}
});
this.testCase({
name: "Dynamic unload: Initialization and unload with plugins",
test: () => {
const samplingPlugin = new TestSamplingPlugin();
const channelPlugin = new TestChannelPlugin();
const testPlugin = new TestPlugin();
const trackPlugin = new TrackPlugin();
const appInsightsCore = new AppInsightsCore();
const config: IConfiguration = {
instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41"
};
try {
appInsightsCore.initialize(config, [channelPlugin, testPlugin, trackPlugin, samplingPlugin]);
} catch (error) {
Assert.ok(false, "Everything should be initialized");
}
let testSender = appInsightsCore.getPlugin("TestSender");
Assert.ok(testSender != null, "Sender should be returned");
Assert.equal(channelPlugin, testSender.plugin, "The returned plugin should be the instance we passed in");
Assert.equal(samplingPlugin, appInsightsCore.getPlugin(samplingPlugin.identifier).plugin, "Sampling Plugin");
Assert.equal(testPlugin, appInsightsCore.getPlugin(testPlugin.identifier).plugin, "testPlugin Plugin");
Assert.equal(trackPlugin, appInsightsCore.getPlugin(trackPlugin.identifier).plugin, "trackPlugin Plugin");
let unloadComplete = false;
appInsightsCore.unload(false, () => {
unloadComplete = true;
});
Assert.equal(true, unloadComplete, "Unload should have been completed synchronously");
Assert.equal(true, channelPlugin.isTearDownInvoked, "Teardown should have been called");
Assert.equal(false, appInsightsCore.isInitialized(), "Core should be no longer initialized");
Assert.equal(false, trackPlugin.isInitialized(), "trackPlugin should be no longer initialized");
Assert.equal(null, appInsightsCore.getPlugin(channelPlugin.identifier), "Sender should no longer be loaded");
Assert.equal(null, appInsightsCore.getPlugin(samplingPlugin.identifier), "Sampling Plugin");
Assert.equal(null, appInsightsCore.getPlugin(testPlugin.identifier), "testPlugin Plugin");
Assert.equal(null, appInsightsCore.getPlugin(trackPlugin.identifier), "trackPlugin Plugin");
}
});
this.testCase({
name: "Dynamic remove/unload: Initialization with plugins and unload trackPlugin",
test: () => {
const samplingPlugin = new TestSamplingPlugin();
const channelPlugin = new TestChannelPlugin();
const testPlugin = new TestPlugin();
const trackPlugin = new TrackPlugin();
const appInsightsCore = new AppInsightsCore();
const config: IConfiguration = {
instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41",
loggingLevelConsole: 2
};
try {
appInsightsCore.initialize(config, [channelPlugin, testPlugin, trackPlugin, samplingPlugin]);
} catch (error) {
Assert.ok(false, "Everything should be initialized");
}
let testSender = appInsightsCore.getPlugin("TestSender");
Assert.ok(testSender != null, "Sender should be returned");
Assert.equal(channelPlugin, testSender.plugin, "The returned plugin should be the instance we passed in");
Assert.equal(samplingPlugin, appInsightsCore.getPlugin(samplingPlugin.identifier).plugin, "Sampling Plugin");
Assert.equal(testPlugin, appInsightsCore.getPlugin(testPlugin.identifier).plugin, "testPlugin Plugin");
Assert.equal(trackPlugin, appInsightsCore.getPlugin(trackPlugin.identifier).plugin, "trackPlugin Plugin");
Assert.equal(1, channelPlugin.events.length, "We should have a track call");
Assert.equal(0, channelPlugin.events[0].data.trackPlugin);
Assert.equal(true, channelPlugin.events[0].data.sampled);
appInsightsCore.track({
name: "MyCustomEvent"
});
Assert.equal(2, channelPlugin.events.length, "We should have a track call");
Assert.equal(1, channelPlugin.events[1].data.trackPlugin);
Assert.equal(true, channelPlugin.events[1].data.sampled);
// Unload the track plugin
let removed = false;
appInsightsCore.getPlugin(trackPlugin.identifier).remove(false, () => {
removed = true;
});
Assert.equal(true, removed, "Track Plugin should have been removed");
// Configuration should not have changed
Assert.equal(2, appInsightsCore.logger.consoleLoggingLevel(), "Validate the Console Logging Level")
appInsightsCore.track({
name: "MyCustomEvent2"
});
Assert.equal(3, channelPlugin.events.length, "We should have a track call");
Assert.equal(undefined, (channelPlugin.events[2].data ||{}).trackPlugin);
Assert.equal(null, appInsightsCore.getPlugin(trackPlugin.identifier), "trackPlugin Plugin");
Assert.equal(true, channelPlugin.events[2].data.sampled);
let unloadComplete = false;
appInsightsCore.unload(false, () => {
unloadComplete = true;
});
Assert.equal(true, unloadComplete, "Unload should have been completed synchronously");
Assert.equal(true, channelPlugin.isTearDownInvoked, "Teardown should have been called");
Assert.equal(false, appInsightsCore.isInitialized(), "Core should be no longer initialized");
Assert.equal(false, trackPlugin.isInitialized(), "trackPlugin should be no longer initialized");
Assert.equal(null, appInsightsCore.getPlugin(channelPlugin.identifier), "Sender should no longer be loaded");
Assert.equal(null, appInsightsCore.getPlugin(samplingPlugin.identifier), "Sampling Plugin");
Assert.equal(null, appInsightsCore.getPlugin(testPlugin.identifier), "testPlugin Plugin");
Assert.equal(null, appInsightsCore.getPlugin(trackPlugin.identifier), "trackPlugin Plugin");
}
});
this.testCase({
name: "Dynamic remove/add/unload: Initialization with plugins and unload and reload samplingPlugin",
test: () => {
const samplingPlugin = new TestSamplingPlugin();
const channelPlugin = new TestChannelPlugin();
const testPlugin = new TestPlugin();
const trackPlugin = new TrackPlugin();
const appInsightsCore = new AppInsightsCore();
const config: IConfiguration = {
instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41"
};
try {
appInsightsCore.initialize(config, [channelPlugin, testPlugin, trackPlugin, samplingPlugin]);
} catch (error) {
Assert.ok(false, "Everything should be initialized");
}
let testSender = appInsightsCore.getPlugin("TestSender");
Assert.ok(testSender != null, "Sender should be returned");
Assert.equal(channelPlugin, testSender.plugin, "The returned plugin should be the instance we passed in");
Assert.equal(samplingPlugin, appInsightsCore.getPlugin(samplingPlugin.identifier).plugin, "Sampling Plugin");
Assert.equal(testPlugin, appInsightsCore.getPlugin(testPlugin.identifier).plugin, "testPlugin Plugin");
Assert.equal(trackPlugin, appInsightsCore.getPlugin(trackPlugin.identifier).plugin, "trackPlugin Plugin");
Assert.equal(1, channelPlugin.events.length, "We should have a track call");
Assert.equal(0, channelPlugin.events[0].data.trackPlugin);
Assert.equal(true, channelPlugin.events[0].data.sampled);
appInsightsCore.track({
name: "MyCustomEvent"
});
Assert.equal(2, channelPlugin.events.length, "We should have a track call");
Assert.equal(1, channelPlugin.events[1].data.trackPlugin);
Assert.equal(true, channelPlugin.events[1].data.sampled);
// Unload the track plugin
let removed = false;
appInsightsCore.getPlugin(samplingPlugin.identifier).remove(false, () => {
removed = true;
});
Assert.equal(true, removed, "Track Plugin should have been removed");
Assert.equal(null, appInsightsCore.getPlugin(samplingPlugin.identifier), "samplingPlugin Plugin");
appInsightsCore.track({
name: "MyCustomEvent2"
});
Assert.equal(3, channelPlugin.events.length, "We should have a track call");
Assert.equal(2, channelPlugin.events[2].data.trackPlugin);
Assert.equal(undefined, (channelPlugin.events[2].data || {}).sampled);
let pluginAdded = false;
appInsightsCore.addPlugin(samplingPlugin, false, false, (added) => {
pluginAdded = added;
});
Assert.equal(true, pluginAdded, "sampling plugin should have been re-added");
Assert.equal(samplingPlugin, appInsightsCore.getPlugin(samplingPlugin.identifier).plugin, "Sampling Plugin should be present again");
appInsightsCore.track({
name: "MyCustomEvent3"
});
Assert.equal(4, channelPlugin.events.length, "We should have a track call");
Assert.equal(3, channelPlugin.events[3].data.trackPlugin);
Assert.equal(true, channelPlugin.events[3].data.sampled);
let newSamplingPlugin = new TestSamplingPlugin();
let replacedPlugin = false;
appInsightsCore.addPlugin(newSamplingPlugin, false, false, (added) => {
replacedPlugin = added;
});
Assert.equal(false, replacedPlugin, "sampling plugin should NOT have been replaced");
Assert.equal(samplingPlugin, appInsightsCore.getPlugin(samplingPlugin.identifier).plugin, "Sampling Plugin should be present again");
appInsightsCore.track({
name: "MyCustomEvent4"
});
Assert.equal(5, channelPlugin.events.length, "We should have a track call");
Assert.equal(4, channelPlugin.events[4].data.trackPlugin);
Assert.equal(true, channelPlugin.events[4].data.sampled);
replacedPlugin = false;
appInsightsCore.addPlugin(newSamplingPlugin, true, false, (added) => {
replacedPlugin = added;
});
Assert.equal(true, replacedPlugin, "sampling plugin should have been replaced");
Assert.equal(newSamplingPlugin, appInsightsCore.getPlugin(samplingPlugin.identifier).plugin, "New Sampling Plugin should be present");
appInsightsCore.track({
name: "MyCustomEvent5"
});
Assert.equal(6, channelPlugin.events.length, "We should have a track call");
Assert.equal(5, channelPlugin.events[5].data.trackPlugin);
Assert.equal(true, channelPlugin.events[5].data.sampled);
samplingPlugin.isSampledOut = true;
appInsightsCore.track({
name: "MyCustomEvent6"
});
Assert.equal(7, channelPlugin.events.length, "We should have a track call");
Assert.equal(6, channelPlugin.events[6].data.trackPlugin);
Assert.equal(true, channelPlugin.events[6].data.sampled, "Should still have been sampled");
newSamplingPlugin.isSampledOut = true;
appInsightsCore.track({
name: "MyCustomEvent7"
});
Assert.equal(7, channelPlugin.events.length, "The event should have been sampled out");
Assert.equal(6, channelPlugin.events[6].data.trackPlugin);
Assert.equal(true, channelPlugin.events[6].data.sampled, "Should still have been sampled");
}
});
this.testCase({
name: "Dynamic shared remove: Initialization with plugins and unload shared trackPlugin only",
test: () => {
const coreChannelPlugin = new TestChannelPlugin();
const sharedChannelPlugin = new TestChannelPlugin();
const trackPlugin = new TrackPlugin();
const appInsightsCore = new AppInsightsCore();
const appInsightsSharedCore = new AppInsightsCore();
const config: IConfiguration = {
instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41"
};
try {
appInsightsCore.initialize(config, [coreChannelPlugin, new TestPlugin(), trackPlugin, new TestSamplingPlugin()]);
} catch (error) {
Assert.ok(false, "Everything should be initialized");
}
Assert.equal(1, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal(0, coreChannelPlugin.events[0].data.trackPlugin);
Assert.equal(true, coreChannelPlugin.events[0].data.sampled);
try {
appInsightsSharedCore.initialize(config, [sharedChannelPlugin, new TestPlugin(), trackPlugin, new TestSamplingPlugin()]);
} catch (error) {
Assert.ok(false, "Everything should be initialized");
}
// The 2nd usage of the trackPlugin doesn't call initialize so we won't have any additional event (from the initialize of trackPlugin)
Assert.equal(0, sharedChannelPlugin.events.length, "We should have a track call");
let testTrackPlugin = appInsightsCore.getPlugin(trackPlugin.identifier);
Assert.ok(testTrackPlugin != null, "Track plugin should be returned");
Assert.equal(trackPlugin, testTrackPlugin.plugin, "The returned plugin should be the same instance");
let testSharedTrackPlugin = appInsightsSharedCore.getPlugin(trackPlugin.identifier);
Assert.ok(testSharedTrackPlugin != null, "Shared Track plugin should be returned");
Assert.equal(trackPlugin, testSharedTrackPlugin.plugin, "The returned Shared plugin should be the same instance");
appInsightsCore.track({
name: "MyCustomEvent"
});
appInsightsSharedCore.track({
name: "MySharedCustomEvent"
});
Assert.equal(2, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal("MyCustomEvent", coreChannelPlugin.events[1].name);
Assert.equal(1, coreChannelPlugin.events[1].data.trackPlugin);
Assert.equal(true, coreChannelPlugin.events[1].data.sampled);
Assert.equal(1, sharedChannelPlugin.events.length, "We should have a track call");
Assert.equal("MySharedCustomEvent", sharedChannelPlugin.events[0].name);
Assert.equal(2, sharedChannelPlugin.events[0].data.trackPlugin);
Assert.equal(true, sharedChannelPlugin.events[0].data.sampled);
// Unload shared instance track plugin
let removed = false;
appInsightsSharedCore.getPlugin(trackPlugin.identifier).remove(false, () => {
removed = true;
});
Assert.equal(true, removed, "Shared Track Plugin should have been removed");
Assert.equal(true, trackPlugin.isInitialized(), "But should not have been un-initialized");
Assert.equal(trackPlugin, appInsightsCore.getPlugin(trackPlugin.identifier).plugin, "The returned plugin should be the same instance");
Assert.equal(null, appInsightsSharedCore.getPlugin(trackPlugin.identifier), "The returned Shared plugin should not be present");
appInsightsCore.track({
name: "MyCustomEvent2"
});
appInsightsSharedCore.track({
name: "MySharedCustomEvent2"
});
Assert.equal(3, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal("MyCustomEvent2", coreChannelPlugin.events[2].name);
Assert.equal(3, coreChannelPlugin.events[2].data.trackPlugin);
Assert.equal(true, coreChannelPlugin.events[2].data.sampled);
Assert.equal(2, sharedChannelPlugin.events.length, "We should have a track call");
Assert.equal("MySharedCustomEvent2", sharedChannelPlugin.events[1].name);
Assert.equal(undefined, (sharedChannelPlugin.events[1].data || {}).trackPlugin, "The track plugin should not have been applied to the shared instance");
Assert.equal(true, sharedChannelPlugin.events[1].data.sampled);
}
});
this.testCase({
name: "Dynamic shared remove: Initialization with plugins and unload core but not trackPlugin",
test: () => {
const coreChannelPlugin = new TestChannelPlugin();
const sharedChannelPlugin = new TestChannelPlugin();
const trackPlugin = new TrackPlugin();
const appInsightsCore = new AppInsightsCore();
const appInsightsSharedCore = new AppInsightsCore();
const config: IConfiguration = {
instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41"
};
try {
appInsightsCore.initialize(config, [coreChannelPlugin, new TestPlugin(), trackPlugin, new TestSamplingPlugin()]);
} catch (error) {
Assert.ok(false, "Everything should be initialized");
}
Assert.equal(1, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal(0, coreChannelPlugin.events[0].data.trackPlugin);
Assert.equal(true, coreChannelPlugin.events[0].data.sampled);
try {
appInsightsSharedCore.initialize(config, [sharedChannelPlugin, new TestPlugin(), trackPlugin, new TestSamplingPlugin()]);
} catch (error) {
Assert.ok(false, "Everything should be initialized");
}
// The 2nd usage of the trackPlugin doesn't call initialize so we won't have any additional event (from the initialize of trackPlugin)
Assert.equal(0, sharedChannelPlugin.events.length, "We should have a track call");
let testTrackPlugin = appInsightsCore.getPlugin(trackPlugin.identifier);
Assert.ok(testTrackPlugin != null, "Track plugin should be returned");
Assert.equal(trackPlugin, testTrackPlugin.plugin, "The returned plugin should be the same instance");
let testSharedTrackPlugin = appInsightsSharedCore.getPlugin(trackPlugin.identifier);
Assert.ok(testSharedTrackPlugin != null, "Shared Track plugin should be returned");
Assert.equal(trackPlugin, testSharedTrackPlugin.plugin, "The returned Shared plugin should be the same instance");
appInsightsCore.track({
name: "MyCustomEvent"
});
appInsightsSharedCore.track({
name: "MySharedCustomEvent"
});
Assert.equal(2, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal("MyCustomEvent", coreChannelPlugin.events[1].name);
Assert.equal(1, coreChannelPlugin.events[1].data.trackPlugin);
Assert.equal(true, coreChannelPlugin.events[1].data.sampled);
Assert.equal(1, sharedChannelPlugin.events.length, "We should have a track call");
Assert.equal("MySharedCustomEvent", sharedChannelPlugin.events[0].name);
Assert.equal(2, sharedChannelPlugin.events[0].data.trackPlugin);
Assert.equal(true, sharedChannelPlugin.events[0].data.sampled);
// Unload shared instance track plugin
let removed = false;
appInsightsCore.getPlugin(trackPlugin.identifier).remove(false, () => {
removed = true;
});
Assert.equal(true, removed, "Shared Track Plugin should have been removed");
Assert.equal(false, trackPlugin.isInitialized(), "But should not have been un-initialized");
Assert.equal(null, appInsightsCore.getPlugin(trackPlugin.identifier), "The returned core plugin should no longer be present");
Assert.equal(trackPlugin, appInsightsSharedCore.getPlugin(trackPlugin.identifier).plugin, "The returned Shared plugin should be present");
appInsightsCore.track({
name: "MyCustomEvent2"
});
appInsightsSharedCore.track({
name: "MySharedCustomEvent2"
});
Assert.equal(3, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal("MyCustomEvent2", coreChannelPlugin.events[2].name);
Assert.equal(undefined, (coreChannelPlugin.events[2].data || {}).trackPlugin);
Assert.equal(true, coreChannelPlugin.events[2].data.sampled);
Assert.equal(2, sharedChannelPlugin.events.length, "We should have a track call");
Assert.equal("MySharedCustomEvent2", sharedChannelPlugin.events[1].name);
Assert.equal(undefined, (sharedChannelPlugin.events[1].data || {}).trackPlugin, "The track plugin should not have been applied to the shared instance");
Assert.equal(true, sharedChannelPlugin.events[1].data.sampled);
}
});
this.testCase({
name: "Dynamic shared remove: Initialization with plugins and unload shared old trackPlugin only",
test: () => {
const coreChannelPlugin = new TestChannelPlugin();
const sharedChannelPlugin = new TestChannelPlugin();
const oldTrackPlugin = new OldTrackPlugin();
const appInsightsCore = new AppInsightsCore();
const appInsightsSharedCore = new AppInsightsCore();
const config: IConfiguration = {
instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41"
};
try {
appInsightsCore.initialize(config, [coreChannelPlugin, new TestPlugin(), oldTrackPlugin, new TestSamplingPlugin()]);
} catch (error) {
Assert.ok(false, "Everything should be initialized");
}
Assert.equal(1, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal(0, coreChannelPlugin.events[0].data.trackPlugin);
Assert.equal(true, coreChannelPlugin.events[0].data.sampled);
try {
appInsightsSharedCore.initialize(config, [sharedChannelPlugin, new TestPlugin(), oldTrackPlugin, new TestSamplingPlugin()]);
} catch (error) {
Assert.ok(false, "Everything should be initialized");
}
// The 2nd usage of the trackPlugin doesn't call initialize so we won't have any additional event (from the initialize of trackPlugin)
Assert.equal(0, sharedChannelPlugin.events.length, "We should have a track call");
let testTrackPlugin = appInsightsCore.getPlugin(oldTrackPlugin.identifier);
Assert.ok(testTrackPlugin != null, "Track plugin should be returned");
Assert.equal(oldTrackPlugin, testTrackPlugin.plugin, "The returned plugin should be the same instance");
let testSharedTrackPlugin = appInsightsSharedCore.getPlugin(oldTrackPlugin.identifier);
Assert.ok(testSharedTrackPlugin != null, "Shared Track plugin should be returned");
Assert.equal(oldTrackPlugin, testSharedTrackPlugin.plugin, "The returned Shared plugin should be the same instance");
appInsightsCore.track({
name: "MyCustomEvent"
});
appInsightsSharedCore.track({
name: "MySharedCustomEvent"
});
Assert.equal(2, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal("MyCustomEvent", coreChannelPlugin.events[1].name);
Assert.equal(1, coreChannelPlugin.events[1].data.trackPlugin);
Assert.equal(true, coreChannelPlugin.events[1].data.sampled);
Assert.equal(1, sharedChannelPlugin.events.length, "We should have a track call");
Assert.equal("MySharedCustomEvent", sharedChannelPlugin.events[0].name);
Assert.equal(2, sharedChannelPlugin.events[0].data.trackPlugin);
Assert.equal(true, sharedChannelPlugin.events[0].data.sampled);
// Unload shared instance track plugin
let removed = false;
appInsightsSharedCore.getPlugin(oldTrackPlugin.identifier).remove(false, () => {
removed = true;
});
Assert.equal(true, removed, "Shared Track Plugin should have been removed");
Assert.equal(oldTrackPlugin, appInsightsCore.getPlugin(oldTrackPlugin.identifier).plugin, "The returned plugin should be the same instance");
Assert.equal(null, appInsightsSharedCore.getPlugin(oldTrackPlugin.identifier), "The returned Shared plugin should not be present");
appInsightsCore.track({
name: "MyCustomEvent2"
});
appInsightsSharedCore.track({
name: "MySharedCustomEvent2"
});
Assert.equal(3, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal("MyCustomEvent2", coreChannelPlugin.events[2].name);
Assert.equal(3, coreChannelPlugin.events[2].data.trackPlugin);
Assert.equal(true, coreChannelPlugin.events[2].data.sampled);
Assert.equal(2, sharedChannelPlugin.events.length, "We should have a track call");
Assert.equal("MySharedCustomEvent2", sharedChannelPlugin.events[1].name);
Assert.equal(undefined, (sharedChannelPlugin.events[1].data || {}).trackPlugin, "The track plugin should not have been applied to the shared instance");
Assert.equal(true, sharedChannelPlugin.events[1].data.sampled);
}
});
this.testCase({
name: "Dynamic shared remove: Initialization with plugins and unload core but not old trackPlugin",
test: () => {
const coreChannelPlugin = new TestChannelPlugin();
const sharedChannelPlugin = new TestChannelPlugin();
const oldTrackPlugin = new OldTrackPlugin();
const appInsightsCore = new AppInsightsCore();
const appInsightsSharedCore = new AppInsightsCore();
const config: IConfiguration = {
instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41"
};
try {
appInsightsCore.initialize(config, [coreChannelPlugin, new TestPlugin(), oldTrackPlugin, new TestSamplingPlugin()]);
} catch (error) {
Assert.ok(false, "Everything should be initialized");
}
Assert.equal(1, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal(0, coreChannelPlugin.events[0].data.trackPlugin);
Assert.equal(true, coreChannelPlugin.events[0].data.sampled);
try {
appInsightsSharedCore.initialize(config, [sharedChannelPlugin, new TestPlugin(), oldTrackPlugin, new TestSamplingPlugin()]);
} catch (error) {
Assert.ok(false, "Everything should be initialized");
}
// The 2nd usage of the trackPlugin doesn't call initialize so we won't have any additional event (from the initialize of trackPlugin)
Assert.equal(0, sharedChannelPlugin.events.length, "We should have a track call");
let testTrackPlugin = appInsightsCore.getPlugin(oldTrackPlugin.identifier);
Assert.ok(testTrackPlugin != null, "Track plugin should be returned");
Assert.equal(oldTrackPlugin, testTrackPlugin.plugin, "The returned plugin should be the same instance");
let testSharedTrackPlugin = appInsightsSharedCore.getPlugin(oldTrackPlugin.identifier);
Assert.ok(testSharedTrackPlugin != null, "Shared Track plugin should be returned");
Assert.equal(oldTrackPlugin, testSharedTrackPlugin.plugin, "The returned Shared plugin should be the same instance");
appInsightsCore.track({
name: "MyCustomEvent"
});
appInsightsSharedCore.track({
name: "MySharedCustomEvent"
});
Assert.equal(2, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal("MyCustomEvent", coreChannelPlugin.events[1].name);
Assert.equal(1, coreChannelPlugin.events[1].data.trackPlugin);
Assert.equal(true, coreChannelPlugin.events[1].data.sampled);
Assert.equal(1, sharedChannelPlugin.events.length, "We should have a track call");
Assert.equal("MySharedCustomEvent", sharedChannelPlugin.events[0].name);
Assert.equal(2, sharedChannelPlugin.events[0].data.trackPlugin);
Assert.equal(true, sharedChannelPlugin.events[0].data.sampled);
// Unload shared instance track plugin
let removed = false;
appInsightsCore.getPlugin(oldTrackPlugin.identifier).remove(false, () => {
removed = true;
});
Assert.equal(true, removed, "Shared Track Plugin should have been removed");
Assert.equal(null, appInsightsCore.getPlugin(oldTrackPlugin.identifier), "The returned core plugin should no longer be present");
Assert.equal(oldTrackPlugin, appInsightsSharedCore.getPlugin(oldTrackPlugin.identifier).plugin, "The returned Shared plugin should be present");
appInsightsCore.track({
name: "MyCustomEvent2"
});
appInsightsSharedCore.track({
name: "MySharedCustomEvent2"
});
Assert.equal(3, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal("MyCustomEvent2", coreChannelPlugin.events[2].name);
Assert.equal(undefined, (coreChannelPlugin.events[2].data || {}).trackPlugin);
Assert.equal(true, coreChannelPlugin.events[2].data.sampled);
Assert.equal(2, sharedChannelPlugin.events.length, "We should have a track call");
Assert.equal("MySharedCustomEvent2", sharedChannelPlugin.events[1].name);
Assert.equal(undefined, (sharedChannelPlugin.events[1].data || {}).trackPlugin, "The track plugin should not have been applied to the shared instance");
Assert.equal(true, sharedChannelPlugin.events[1].data.sampled);
}
});
this.testCase({
name: "Dynamic shared unload: Initialization with plugins and unload shared old trackPlugin only",
test: () => {
const coreChannelPlugin = new TestChannelPlugin();
const sharedChannelPlugin = new TestChannelPlugin();
const oldTrackPlugin = new OldTrackPlugin();
const appInsightsCore = new AppInsightsCore();
const appInsightsSharedCore = new AppInsightsCore();
const config: IConfiguration = {
instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41"
};
try {
appInsightsCore.initialize(config, [coreChannelPlugin, new TestPlugin(), oldTrackPlugin, new TestSamplingPlugin()]);
} catch (error) {
Assert.ok(false, "Everything should be initialized");
}
Assert.equal(1, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal(0, coreChannelPlugin.events[0].data.trackPlugin);
Assert.equal(true, coreChannelPlugin.events[0].data.sampled);
try {
appInsightsSharedCore.initialize(config, [sharedChannelPlugin, new TestPlugin(), oldTrackPlugin, new TestSamplingPlugin()]);
} catch (error) {
Assert.ok(false, "Everything should be initialized");
}
// The 2nd usage of the trackPlugin doesn't call initialize so we won't have any additional event (from the initialize of trackPlugin)
Assert.equal(0, sharedChannelPlugin.events.length, "We should have a track call");
let testTrackPlugin = appInsightsCore.getPlugin(oldTrackPlugin.identifier);
Assert.ok(testTrackPlugin != null, "Track plugin should be returned");
Assert.equal(oldTrackPlugin, testTrackPlugin.plugin, "The returned plugin should be the same instance");
let testSharedTrackPlugin = appInsightsSharedCore.getPlugin(oldTrackPlugin.identifier);
Assert.ok(testSharedTrackPlugin != null, "Shared Track plugin should be returned");
Assert.equal(oldTrackPlugin, testSharedTrackPlugin.plugin, "The returned Shared plugin should be the same instance");
appInsightsCore.track({
name: "MyCustomEvent"
});
appInsightsSharedCore.track({
name: "MySharedCustomEvent"
});
Assert.equal(2, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal("MyCustomEvent", coreChannelPlugin.events[1].name);
Assert.equal(1, coreChannelPlugin.events[1].data.trackPlugin);
Assert.equal(true, coreChannelPlugin.events[1].data.sampled);
Assert.equal(1, sharedChannelPlugin.events.length, "We should have a track call");
Assert.equal("MySharedCustomEvent", sharedChannelPlugin.events[0].name);
Assert.equal(2, sharedChannelPlugin.events[0].data.trackPlugin);
Assert.equal(true, sharedChannelPlugin.events[0].data.sampled);
// Unload shared instance track plugin
let removed = false;
appInsightsSharedCore.unload(false, () => {
removed = true;
});
Assert.equal(true, removed, "Shared Track Plugin should have been removed");
Assert.equal(oldTrackPlugin, appInsightsCore.getPlugin(oldTrackPlugin.identifier).plugin, "The returned plugin should be the same instance");
Assert.equal(null, appInsightsSharedCore.getPlugin(oldTrackPlugin.identifier), "The returned Shared plugin should not be present");
appInsightsCore.track({
name: "MyCustomEvent2"
});
Assert.equal(3, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal("MyCustomEvent2", coreChannelPlugin.events[2].name);
Assert.equal(3, coreChannelPlugin.events[2].data.trackPlugin);
Assert.equal(true, coreChannelPlugin.events[2].data.sampled);
}
});
this.testCase({
name: "Dynamic shared unload: Initialization with plugins and unload core but not old trackPlugin",
test: () => {
const coreChannelPlugin = new TestChannelPlugin();
const sharedChannelPlugin = new TestChannelPlugin();
const oldTrackPlugin = new OldTrackPlugin();
const appInsightsCore = new AppInsightsCore();
const appInsightsSharedCore = new AppInsightsCore();
const config: IConfiguration = {
instrumentationKey: "09465199-12AA-4124-817F-544738CC7C41"
};
try {
appInsightsCore.initialize(config, [coreChannelPlugin, new TestPlugin(), oldTrackPlugin, new TestSamplingPlugin()]);
} catch (error) {
Assert.ok(false, "Everything should be initialized");
}
Assert.equal(1, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal(0, coreChannelPlugin.events[0].data.trackPlugin);
Assert.equal(true, coreChannelPlugin.events[0].data.sampled);
try {
appInsightsSharedCore.initialize(config, [sharedChannelPlugin, new TestPlugin(), oldTrackPlugin, new TestSamplingPlugin()]);
} catch (error) {
Assert.ok(false, "Everything should be initialized");
}
// The 2nd usage of the trackPlugin doesn't call initialize so we won't have any additional event (from the initialize of trackPlugin)
Assert.equal(0, sharedChannelPlugin.events.length, "We should have a track call");
let testTrackPlugin = appInsightsCore.getPlugin(oldTrackPlugin.identifier);
Assert.ok(testTrackPlugin != null, "Track plugin should be returned");
Assert.equal(oldTrackPlugin, testTrackPlugin.plugin, "The returned plugin should be the same instance");
let testSharedTrackPlugin = appInsightsSharedCore.getPlugin(oldTrackPlugin.identifier);
Assert.ok(testSharedTrackPlugin != null, "Shared Track plugin should be returned");
Assert.equal(oldTrackPlugin, testSharedTrackPlugin.plugin, "The returned Shared plugin should be the same instance");
appInsightsCore.track({
name: "MyCustomEvent"
});
appInsightsSharedCore.track({
name: "MySharedCustomEvent"
});
Assert.equal(2, coreChannelPlugin.events.length, "We should have a track call");
Assert.equal("MyCustomEvent", coreChannelPlugin.events[1].name);
Assert.equal(1, coreChannelPlugin.events[1].data.trackPlugin);
Assert.equal(true, coreChannelPlugin.events[1].data.sampled);
Assert.equal(1, sharedChannelPlugin.events.length, "We should have a track call");
Assert.equal("MySharedCustomEvent", sharedChannelPlugin.events[0].name);
Assert.equal(2, sharedChannelPlugin.events[0].data.trackPlugin);
Assert.equal(true, sharedChannelPlugin.events[0].data.sampled);
// Unload shared instance track plugin
let removed = false;
appInsightsCore.unload(false, () => {
removed = true;
});
Assert.equal(true, removed, "Shared Track Plugin should have been removed");
Assert.equal(null, appInsightsCore.getPlugin(oldTrackPlugin.identifier), "The returned core plugin should no longer be present");
Assert.equal(oldTrackPlugin, appInsightsSharedCore.getPlugin(oldTrackPlugin.identifier).plugin, "The returned Shared plugin should be present");
appInsightsSharedCore.track({
name: "MySharedCustomEvent2"
});
Assert.equal(2, sharedChannelPlugin.events.length, "We should have a track call");
Assert.equal("MySharedCustomEvent2", sharedChannelPlugin.events[1].name);
Assert.equal(undefined, (sharedChannelPlugin.events[1].data || {}).trackPlugin, "The track plugin should not have been applied to the shared instance");
Assert.equal(true, sharedChannelPlugin.events[1].data.sampled);
}
});
}
}
/**
* Test plugin doesn't implement the teardown "unload" function
*/
class TestSamplingPlugin implements ITelemetryPlugin {
public processTelemetry: (env: ITelemetryItem) => void;
public initialize: (config: IConfiguration) => void;
public identifier: string = "AzureSamplingPlugin";
public setNextPlugin: (next: ITelemetryPlugin) => void;
public priority: number = 5;
public version = "1.0.31-Beta";
public nextPlugin: ITelemetryPlugin;
public isSampledOut: boolean = false;
public teardownCalled: boolean = false;
private _validateItem = false;
constructor(validateItem: boolean = false) {
this.processTelemetry = this._processTelemetry.bind(this);
this.initialize = this._start.bind(this);
this.setNextPlugin = this._setNextPlugin.bind(this);
this._validateItem = validateItem;
}
public teardown() {
this.teardownCalled = true;
}
private _processTelemetry(env: ITelemetryItem) {
if (!env) {
throw Error("Invalid telemetry object");
}
if (this._validateItem) {
Assert.ok(env.baseData);
Assert.ok(env.baseType);
Assert.ok(env.data);
Assert.ok(env.ext);
Assert.ok(env.tags);
}
let data = env.data = (env.data || {});
data.sampled = true;
if (!this.isSampledOut) {
this.nextPlugin.processTelemetry(env);
}
}
private _start(config: IConfiguration) {
if (!config) {
throw Error("required configuration missing");
}
const pluginConfig = config.extensions ? config.extensions[this.identifier] : null;
this.isSampledOut = pluginConfig ? pluginConfig.isSampledOut : false;
}
private _setNextPlugin(next: ITelemetryPlugin): void {
this.nextPlugin = next;
}
}
class TestChannelPlugin implements IChannelControls {
public _nextPlugin: ITelemetryPlugin;
public isFlushInvoked = false;
public isUnloadInvoked = false;
public isTearDownInvoked = false;
public isResumeInvoked = false;
public isPauseInvoked = false;
public version: string = "1.0.33-Beta";
public processTelemetry;
public identifier = "TestSender";
public priority: number = 1001;
public events: ITelemetryItem[] = [];
constructor() {
this.processTelemetry = this._processTelemetry.bind(this);
}
public pause(): void {
this.isPauseInvoked = true;
}
public resume(): void {
this.isResumeInvoked = true;
}
public teardown(): void {
this.isTearDownInvoked = true;
}
flush(async?: boolean, callBack?: () => void): void {
this.isFlushInvoked = true;
if (callBack) {
callBack();
}
}
onunloadFlush(async?: boolean) {
this.isUnloadInvoked = true;
}
setNextPlugin(next: ITelemetryPlugin) {
this._nextPlugin = next;
}
public initialize = (config: IConfiguration) => {
}
public _processTelemetry(env: ITelemetryItem) {
this.events.push(env);
// Just calling processTelemetry as this is the original design of the Plugins (as opposed to the newer processNext())
this._nextPlugin.processTelemetry(env);
}
}
class TestPlugin implements IPlugin {
public identifier: string = "TestPlugin";
public version: string = "1.0.31-Beta";
private _config: IConfiguration;
public initialize(config: IConfiguration) {
this._config = config;
// do custom one time initialization
}
}
class TrackPlugin extends BaseTelemetryPlugin {
public identifier: string = "TrackPlugin";
public version: string = "1.0.31-Beta";
public priority = 2;
public isInitialized: any;
private _config: IConfiguration;
public index: number = 0;
public initialize(config: IConfiguration, core: IAppInsightsCore, extensions: IPlugin[], pluginChain?: ITelemetryPluginChain) {
super.initialize(config, core, extensions, pluginChain)
this._config = config;
core.track({ name: 'TestEvent1' });
}
public processTelemetry(evt: ITelemetryItem, itemCtx: IProcessTelemetryContext) {
let data = evt.data = (evt.data || {});
data.trackPlugin = this.index++;
itemCtx.processNext(evt);
}
}
class OldTrackPlugin implements ITelemetryPlugin {
public identifier: string = "OldTrackPlugin";
public priority = 2;
public isInitialized: any;
private _config: IConfiguration;
public index: number = 0;
public initialize(config: IConfiguration, core: IAppInsightsCore, extensions: IPlugin[], pluginChain?: ITelemetryPluginChain) {
this._config = config;
core.track({ name: 'TestEvent1' });
}
public processTelemetry(evt: ITelemetryItem, itemCtx: IProcessTelemetryContext) {
let data = evt.data = (evt.data || {});
data.trackPlugin = this.index++;
itemCtx.processNext(evt);
}
} | the_stack |
import { InDiv, Component, Utils, NvModule, OnInit, DoCheck, BeforeMount, AfterMount, ReceiveInputs, SetState, OnDestory, ElementRef, HasRender, Input, ViewChild, ViewChildren, StateSetter, Watch, ContentChildren, ContentChild, ChangeDetectionStrategy, MarkForCheck, TMarkForCheck, Pipe, PipeTransform } from '@indiv/core';
import { Injector, Optional, Inject, Self, Injectable } from '@indiv/di';
import { RouteChange, NvLocation, RouteModule, RouteCanActive } from '@indiv/router';
import { PlatformBrowser } from '@indiv/platform-browser';
import { HttpClient, HttpClientResponse } from '@indiv/common';
import { Observable } from 'rxjs';
import { SharedModule, TestDirective } from './share.module';
import { HeroSearchService, HeroSearchService1, HeroSearchService2, TestService } from './service';
import { PrivateService } from './private.service';
import { ErrorHandler } from '@indiv/core/handler/error-handler';
class ValueType { }
@Component({
selector: 'test-content-component',
template: '<p nv-on:click="click()">这个是个测试组件content的东西 {{test}}</p>',
})
class TestContentComponent {
public test: number = 2;
public click() {
console.log(999999, this.test);
this.test = 1002;
}
}
@Component({
selector: 'pc-component',
template: (`
<div>
<p nv-if="e" nv-class="a" nv-repeat="da in d" nv-on:click="componentClick(d)">你好: {{da.z}}</p>
state.d: <input nv-repeat="da in d" nv-model="da.z" />
<p nv-on:click="sendProps(5)">props from component.state.a: {{ax}}</p>
<test-component manName="{a}"></test-component>
</div>
`),
})
class PComponent implements DoCheck, BeforeMount, ReceiveInputs, OnDestory {
@StateSetter() public setState: SetState;
public a: any = 'a子组件';
public b: number = 100;
public c: string = '<p>1111</p>';
public d: any = [
{
z: 111111111111111,
b: 'a',
},
{
z: 33333333333333,
b: 'a',
}];
public e: boolean = true;
@Input() public ax: any;
@Input('b') public bx: (ax: any) => void;
constructor(
private element: ElementRef,
) {}
public nvBeforeMount() {
console.log('nvBeforeMount props11');
}
public componentClick(a: any) {
console.log('aa', a);
}
public sendProps(ax: any) {
this.bx(ax);
}
public getProps(a: any) {
alert('子组件里 里面传出来了');
// this.setState({ a: a });
this.a = a;
this.bx(a);
}
public nvDoCheck() {
}
public nvReceiveInputs(nextInputs: any) {
console.log(1111111111111, nextInputs);
// this.ax = nextInputs.ax;
}
public nvOnDestory() {
console.log('PComponent is nvOnDestory');
}
}
@Component({
selector: 'R1',
template: (`
<div>
<pc-component ax="{a}" b="{getProps}"></pc-component>
下面跟组件没关系<br/>
<div nv-if="f">
ef
<input nv-repeat="ea in e" nv-model="ea.z" />
<p nv-class="c" nv-if="ea.z" nv-repeat="ea in e" nv-text="ea.z" nv-on:click="showAlert(ea)"></p>
<p>111this.a:{{a}}</p>
<input nv-model="a" />
</div>
下面是子路由<br/>
<router-render></router-render>
</div>
`),
})
class R1 implements OnInit, BeforeMount, DoCheck, RouteChange, OnDestory, RouteCanActive {
@StateSetter() public setState: SetState;
public a: string = 'a11';
public b: number = 2;
public d: any[] = [
{
z: 111111111111111,
b: 'a',
show: true,
},
{
z: 33333333333333,
b: 'a',
show: true,
},
];
public c: string = 'c';
public e: any = [
{
z: 232323,
b: 'a',
show: true,
},
{
z: 1111,
b: 'a',
show: false,
},
];
public f: boolean = true;
constructor(
private heroSearchService: HeroSearchService,
private location: NvLocation,
private element: ElementRef,
private indiv: InDiv,
) {
console.log(9999888777, 'from R1', this.element, this.indiv);
this.heroSearchService.test();
}
public nvRouteCanActive(lastRoute: string): boolean {
console.log('R1 is nvRouteCanActive', 444444, lastRoute);
// this.location.set('/');
return true;
}
public nvOnInit() {
console.log('R1 nvOnInit', this.location.get());
}
public nvBeforeMount() {
console.log('is nvBeforeMount');
}
public nvRouteChange(lastRoute: string, newRoute: string) {
console.log('R1 is nvRouteChange', lastRoute, newRoute);
}
public nvDoCheck() {
}
public showAlert(a: any) {
this.location.set('/R1/C1', { a: '1' });
console.log('this.$location', this.location.get());
}
public getProps(a: any) {
console.log('被触发了!', a);
this.a = a;
// this.setState({ a: a });
}
public nvOnDestory() {
console.log(this.location.get(), 'R1 is nvOnDestory');
}
}
// @Injected
@Component({
selector: 'R2',
template: (`
<div>
<p nv-on:click="showLocation()">点击显示子路由跳转</p>
<input nv-model="a"/>
<br/>
<p nv-on:click="showAlert()">点击显示this.a:{{a}}</p>
子组件:<br/>
<route-child a="{a}"></route-child>
<router-render></router-render>
</div>
`),
})
class R2 implements OnInit, BeforeMount, AfterMount, DoCheck, RouteChange, OnDestory {
public state: any;
public a: any = 1;
constructor(
private heroSearchService1: HeroSearchService1,
private location: NvLocation,
private sss: HeroSearchService,
private element: ElementRef,
) {
this.heroSearchService1.test();
console.log('this.heroSearchService1', this.heroSearchService1, this.element);
this.sss.test();
}
public nvOnInit() {
console.log('this.getLocation', this.location.get());
}
public nvBeforeMount() {
// console.log('is nvBeforeMount');
}
public nvAfterMount() {
// console.log('is nvAfterMount');
}
public nvHasRender() {
console.log('!!father: this.a', this.a);
}
public nvRouteChange(lastRoute: string, newRoute: string) {
console.log('R2 is nvRouteChange', lastRoute, newRoute);
}
public nvDoCheck() {
}
public nvOnDestory() {
console.log(this.location.get(), 'R2 is nvOnDestory');
}
public showAlert() {
console.log('this.a', this.a);
// alert('我错了 点下控制台看看吧');
// this.setState(() => ({ a: 2 }));
}
public bindChange(a: any) {
console.log('aaa', a);
}
public showLocation() {
this.location.set('/R1/C1/D1', { b: '1' });
}
}
@Pipe({
name: 'test-pipe',
})
class TestPipe implements PipeTransform {
transform(value: any, ...args: any[]) {
// console.error('pipe value =>>>>>', value, args);
return args[0];
}
}
@Component({
selector: 'test-component',
template: (`
<div>
<p nv-on:click="click()">测试repeat组件: {{manName}}</p>
</div>
<div class="22" nv-repeat='num in repeatData'>
<p nv-on:click="click()">测试repeat组件: {{num}}</p>
<nv-content></nv-content>
</div>
<nv-content></nv-content>
`),
providers: [
{
provide: HeroSearchService,
},
{
provide: TestService,
deps: [ HeroSearchService ],
},
],
changeDetection: ChangeDetectionStrategy.OnPush,
})
class TestComponent implements OnDestory, ReceiveInputs, AfterMount, HasRender {
public state: any;
@Input() public manName: any;
@MarkForCheck() public markForCheck: TMarkForCheck;
public repeatData: number[] = [1];
public man: {name: string} = {
name: 'fucker',
};
@ContentChild('test-content-component') private testComponent: TestContentComponent;
@ContentChild('a') private tagA: HTMLElement;
@ContentChildren('test-directive') private testDirectiveString: TestDirective[];
@ContentChildren('a') private tagAs: TestDirective[];
@ContentChildren(TestDirective) private testDirective: TestDirective[];
constructor(
private httpClient: HttpClient,
private indiv: InDiv,
private element: ElementRef,
private heroSearchService: HeroSearchService,
private testService: TestService,
) {
console.log(55544333, 'init TestComponent', this.testService, this.indiv, this.element);
this.heroSearchService.test(988);
this.httpClient.get('/success').subscribe({
next: (value: any) => { console.log(4444, value); },
});
}
public click() {
console.log('this.manName', this.manName);
this.manName = 'fuck!';
this.markForCheck().then(() => {
console.log('渲染完成');
});
}
public nvHasRender() {
console.log('TestComponent HasRender', this.tagA, this.tagAs, this.testDirectiveString);
}
public nvAfterMount() {
console.log('TestComponent AfterMount');
}
public nvOnDestory() {
console.log('TestComponent OnDestory');
}
public nvReceiveInputs(p: any) {
console.log('test-component nvReceiveInputs', p);
}
}
@Component({
selector: 'container-wrap',
changeDetection: ChangeDetectionStrategy.OnPush,
template: (`
<!-- container: {{countState(color)}} -->
<div class="fucck" nv-class="test.a" nv-id="'cc'">
<p>{{testNumber}}</p>
<input nv-model="test.a" nv-on:click="show(test)" />
<p test-directive="{test.a}" fuck-y="fuckyou" nv-id="232" nv-if="countState(a)" nv-on:click="changeInput()">{{a}}</p>
<test-component test-directive="{test.a}" nv-repeat="man in testArray" nv-key="man.id" manName="{countState(man.name)}" nv-if="a">
<a>this is {{man.name}}</a>
<test-content-component></test-content-component>
</test-component>
<p nv-on:click="go()">
<!-- container: {{countState(color)}} -->
container: {{countState(color)}}
<!-- <a nv-href="countState(man.sex, $index)">a {{man.sex}}</a> -->
</p>
<!-- <a nv-href="countState(man.sex, $index)">a {{man.sex}}</a> -->
<input type="number" nv-model="a" />
<!-- <a nv-href="countState(man.sex, $index)">a {{man.sex}}</a> -->
<div nv-repeat="man in testArray" nv-key="man.name">
<!-- <a nv-href="countState(man.sex, $index)">a {{man.sex}}</a> -->
<div nv-on:click="show(testArray2, '你111')" nv-text="man.name"></div>
<div>
<p>性别:{{countState(man.sex, $index)}}</p>
</div>
<a nv-href="countState(man.sex, $index)">a {{man.sex}}</a>
<img nv-src="man.sex" nv-alt="man.sex" />
<test-component nv-key="man.name" manName="{countState2(man.name, bd)}" nv-repeat="bd in testArray2"></test-component>
<p nv-key="man.name" nv-class="man.name" nv-id="bd" nv-repeat="bd in testArray2">{{bd}}</p>
<input nv-on:click="show(_b, $index)" nv-repeat="_b in testArray2" nv-model="man.name" nv-class="_b" />
<input nv-model="test.a"/>
<div class="fuck" nv-class="man.name" nv-repeat="c in man.job" nv-key="c.id">
<input nv-on:click="show(c, $index)" nv-model="c.name" nv-class="c.id" />
<p test-directive="{'123'}" nv-key="man.name" nv-class="man.name | test-pipe:testNumber | test-pipe:man.name" nv-id="c.name">{{man.name | test-pipe:man.name}}</p>
<div nv-repeat="_bb in man.job">
<p nv-class="man.name" nv-repeat="_test in testArray2">
1
<a nv-class="_bbc" nv-repeat="_bbc in testArray2">{{man.name | test-pipe:_bb.id}} {{_bb.name}}</a>
</p>
</div>
</div>
</div>
<router-render></router-render>
</div>
<p>1111</p>
<!-- <b nv-href="countState(man.sex, $index)"></b> -->
`),
})
class Container implements OnInit, AfterMount, DoCheck, HasRender, RouteChange {
@Watch() public aaaaa: number;
public ss: HeroSearchService;
public ss2: HeroSearchService1;
public state: any;
public testNumber: number = 4;
public color: any = 'red';
public test: any = {
a: 3,
};
public a: any = 1;
public b: any = 3;
public testArray: any = [
{
name: 'gerry',
sex: '男',
id: 1,
job: [
{
id: 1,
name: '程序员',
},
{
id: 2,
name: '码农',
},
{
id: 3,
name: '帅',
},
],
},
{
name: 'nina',
sex: '女',
id: 2,
// job: ['老师', '英语老师', '美1'],
job: [
{
id: 1,
name: '老师',
},
{
id: 2,
name: '英语老师',
},
{
id: 3,
name: '美',
},
],
},
];
public testArray2: any = ['程序员2', '码农2', '架构师2'];
// public testArray2: any = ['程序员2'];
public props: any;
@StateSetter() public setState: SetState;
@MarkForCheck() public markForCheck: TMarkForCheck;
public http$: Observable<HttpClientResponse>;
@ViewChild('test-component') private testComponent: TestComponent;
@ViewChild('router-render') private routerRenderElementRef: ElementRef;
@ViewChildren('test-directive') private testDirectiveString: TestDirective[];
@ViewChildren(TestDirective) private testDirective: TestDirective[];
@Optional()
@Self()
@Inject()
private value: ValueType;
constructor(
private hss: HeroSearchService,
@Inject() private value2: ValueType,
private location: NvLocation,
private httpClient: HttpClient,
private element: ElementRef,
private indiv: InDiv,
private privateService: PrivateService,
private sharedModule: SharedModule,
private privateInjector: Injector,
) {
this.privateService.change();
console.log(99988, 'from Container', this.privateInjector, this.sharedModule, this.element, this.indiv, this.privateService.isPrivate);
this.httpClient.createResponseInterceptor((value: HttpClientResponse) => {
return {
data: value.data,
};
});
this.http$ = this.httpClient.get('/success');
// this.http$.subscribe({
// next: this.httpHandler,
// });
this.hss.test();
setTimeout(() => {
this.setState({
test: {
a: 5,
},
});
}, 1000);
}
public nvRouteChange(lastRoute?: string, newRoute?: string) {
console.log('nvRouteChange Container', lastRoute, newRoute);
throw new Error('111111');
}
public nvOnInit() {
console.log('nvOnInit Container', this.location.get());
console.log('value =>', this.value, this.value2);
}
public nvBeforeMount() {
// this.testNumber = 11;
// this.testNumber = 12;
console.log('nvBeforeMount Container');
}
public nvHasRender() {
this.testNumber = 6;
this.testNumber = 7;
console.log('nvHasRender Container', 33333333, this.testComponent, this.testDirective, this.routerRenderElementRef, this.testDirectiveString);
}
public nvAfterMount() {
// this.testNumber = 8;
// this.testNumber = 9;
console.log('nvAfterMount Container', 222222, this.testComponent, this.testDirective, this.routerRenderElementRef, this.testDirectiveString);
}
public go() {
this.location.redirectTo('/R1', { b: '1' });
}
public countState(a: any, index: number): any {
return a;
}
public countState2(a: any, index: number): any {
return index;
}
public show(a: any, index?: string) {
console.log('aaaa', a);
console.log('$index', index);
console.log('testArray2', this.testArray2);
setTimeout(() => {
this.setState({
test: {
a: 5,
},
});
}, 2000);
this.test.a = 222;
}
public showInput(event: any, index: number) {
this.testArray2[index] = event.target.value;
}
public nvDoCheck() {
console.log(999999, 'container do check!');
}
public changeInput() {
this.setState({
color: "green",
a: 5,
testArray: [
{
name: 'gerry1',
sex: '女',
id: 1,
job: [
{
id: 1,
name: '程序员',
},
{
id: 2,
name: '码农',
},
{
id: 3,
name: '帅',
},
],
},
{
name: 'gerry2',
sex: '男2',
id: 3,
job: [
{
id: 1,
name: '程序员2',
},
{
id: 2,
name: '码农2',
},
{
id: 3,
name: '帅2',
},
],
},
{
name: 'nina3',
sex: '男',
id: 2,
job: [
{
id: 1,
name: '老师',
},
{
id: 2,
name: '英语老师',
},
{
id: 3,
name: '美',
},
],
}],
});
this.a = 100;
this.markForCheck();
}
private httpHandler = (value: any) => {
this.a = 0;
this.b = 44;
console.log(33333, 'from container', value);
}
}
@Injectable()
class GlobalErrorHandler implements ErrorHandler {
public handleError(error: any): void {
console.warn('拦击到的报错 =>>', error);
}
}
@NvModule({
imports: [
SharedModule,
],
declarations: [
R2,
],
providers: [
Utils,
HttpClient,
HeroSearchService,
{
provide: HeroSearchService1,
useClass: HeroSearchService1,
},
HeroSearchService2,
{
provide: ValueType,
useValue: 1123,
},
NvLocation,
],
exports: [
R2,
SharedModule,
],
})
class M2 {
constructor(
private indiv: InDiv,
) {
console.log(99999988866666, '来自注入的模块 M2', this.indiv);
}
}
@NvModule({
imports: [
M2,
],
declarations: [
TestPipe,
TestContentComponent,
Container,
PComponent,
TestComponent,
R1,
],
exports: [
RouteModule,
],
providers: [
{ provide: ErrorHandler, useClass: GlobalErrorHandler },
],
bootstrap: Container,
})
class M1 {
constructor(
private hsr: HeroSearchService,
private indiv: InDiv,
private m2: M2,
) {
console.log(999999888777, '来自注入的模块 M1', this.hsr, this.indiv, this);
}
}
// const inDiv = new InDiv();
// inDiv.bootstrapModule(M1);
// inDiv.use(PlatformBrowser);
// inDiv.init();
InDiv.bootstrapFactory(M1, {
plugins: [
PlatformBrowser,
],
}); | the_stack |
import { DocumentEditor } from '../../../src/document-editor/document-editor';
import { createElement } from '@syncfusion/ej2-base';
import { TablePropertiesDialog } from '../../../src/document-editor/implementation/dialogs/table-properties-dialog';
import { TestHelper } from '../../test-helper.spec';
import { Editor } from '../../../src/index';
import { Selection } from '../../../src/index';
import { EditorHistory } from '../../../src/document-editor/implementation/editor-history/editor-history';
/**
* table alignment
*/
describe('Table vertical alignment - center validation', () => {
let editor: DocumentEditor;
beforeAll((): void => {
editor = undefined;
let ele: HTMLElement = createElement('div', { id: 'container' });
document.body.appendChild(ele);
DocumentEditor.Inject(Editor, Selection, TablePropertiesDialog, EditorHistory);
editor = new DocumentEditor({ enableEditor: true, enableEditorHistory: true, enableSelection: true, isReadOnly: false, enableTablePropertiesDialog: true });
(editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas;
(editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas;
(editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas;
(editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas;
editor.appendTo('#container');
});
afterAll((done) => {
editor.destroy();
document.body.removeChild(document.getElementById('container'));
editor = undefined;
document.body.innerHTML = '';
setTimeout(function () {
done();
}, 2000);
});
it('in 3*4 table cell table vertical alignment validation', () => {
console.log('in 3*4 table cell table vertical alignment validation');
editor.editor.insertTable(2, 2);
editor.selection.tableFormat.leftIndent = 10.8;
let tablePropertiesDialog: TablePropertiesDialog = editor.tablePropertiesDialogModule;
tablePropertiesDialog.show();
(tablePropertiesDialog as any).center.click();
tablePropertiesDialog.applyTableProperties();
expect(editor.selection.tableFormat.tableAlignment).toBe('Center');
expect(editor.selection.tableFormat.leftIndent).toBe(0);
});
it('in 3*4 table and last column resized with minimum width', () => {
console.log('in 3*4 table and last column resized with minimum width');
editor.openBlank();
editor.editor.insertTable(2, 2);
editor.selection.cellFormat.preferredWidth = 0;
let tablePropertiesDialog: TablePropertiesDialog = editor.tablePropertiesDialogModule;
tablePropertiesDialog.show();
(tablePropertiesDialog as any).preferredCellWidthCheckBox.checked = false;
(tablePropertiesDialog as any).preferredCellWidth.value = 0;
(tablePropertiesDialog as any).preferCheckBox.checked = false;
(tablePropertiesDialog as any).rowHeightCheckBox.checked = false;
(tablePropertiesDialog as any).rowHeight.value = 0;
tablePropertiesDialog.applyTableProperties();
expect(editor.selection.tableFormat.preferredWidth).toBe(0);
});
});
describe('Table direction- right to left and left to right validation', () => {
let editor: DocumentEditor;
let dialog: TablePropertiesDialog;
let event: any;
beforeAll((): void => {
editor = undefined;
let ele: HTMLElement = createElement('div', { id: 'container' });
document.body.appendChild(ele);
DocumentEditor.Inject(Editor, Selection, TablePropertiesDialog, EditorHistory);
editor = new DocumentEditor({ enableEditor: true, enableEditorHistory: true, enableSelection: true, isReadOnly: false, enableTablePropertiesDialog: true });
(editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas;
(editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas;
(editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas;
(editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas;
editor.appendTo('#container');
dialog = editor.tablePropertiesDialogModule
});
afterAll((done) => {
editor.destroy();
document.body.removeChild(document.getElementById('container'));
editor = undefined;
document.body.innerHTML = '';
setTimeout(function () {
done();
}, 2000);
});
it('Table for bidi is false and left indent is 0', () => {
console.log('Table for bidi is false and left indent is 0');
editor.editor.insertTable(2, 2);
editor.tablePropertiesDialogModule.show();
event = { value: "rtl" };
(dialog as any).changeBidirectional(event);
dialog.applyTableProperties();
expect(editor.selection.tableFormat.bidi).toBe(true);
});
it('undo after applt rtl via dialog',()=>{
console.log('undo after applt rtl via dialog');
editor.editorHistory.undo();
expect(editor.selection.tableFormat.bidi).toBe(false);
});
it('redo after applt rtl via dialog',()=>{
console.log('redo after applt rtl via dialog');
editor.editorHistory.redo();
expect(editor.selection.tableFormat.bidi).toBe(true);
});
it('apply left to right for RTl table',()=>{
console.log('apply left to right for RTl table');
editor.tablePropertiesDialogModule.show();
event = { value: "ltr" };
(dialog as any).changeBidirectional(event);
dialog.applyTableProperties();
expect(editor.selection.tableFormat.bidi).toBe(false);
});
it('undo after apply ltr via dialog',()=>{
console.log('undo after apply ltr via dialog');
editor.editorHistory.undo();
expect(editor.selection.tableFormat.bidi).toBe(true);
});
it('redo after apply ltr via dialog',()=>{
console.log('redo after apply ltr via dialog');
editor.editorHistory.redo();
expect(editor.selection.tableFormat.bidi).toBe(false);
});
});
describe('Rtl table change table alignment validation', () => {
let editor: DocumentEditor;
let dialog: TablePropertiesDialog;
let event: any;
beforeAll((): void => {
editor = undefined;
let ele: HTMLElement = createElement('div', { id: 'container' });
document.body.appendChild(ele);
DocumentEditor.Inject(Editor, Selection, TablePropertiesDialog, EditorHistory);
editor = new DocumentEditor({ enableEditor: true, enableEditorHistory: true, enableSelection: true, isReadOnly: false, enableTablePropertiesDialog: true });
(editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas;
(editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas;
(editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas;
(editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas;
editor.appendTo('#container');
dialog = editor.tablePropertiesDialogModule
});
afterAll((done) => {
editor.destroy();
document.body.removeChild(document.getElementById('container'));
editor = undefined;
document.body.innerHTML = '';
setTimeout(function () {
done();
}, 2000);
});
it('Table for bidi is true and table alignment as left', () => {
console.log('Table for bidi is true and table alignment as left');
editor.editor.insertTable(2, 2);
editor.selection.tableFormat.bidi=true;
editor.tablePropertiesDialogModule.show();
// let event: any = {
// target: createElement('div', { className: 'e-de-table-properties-alignment e-de-table-left-alignment' }),
// preventDefault: function () { },
// ctrlKey: false, shiftKey: false, which: 0
// };
// dialog.changeTableAlignment(event);
(dialog as any).left.click();
dialog.applyTableProperties();
expect(editor.selection.tableFormat.tableAlignment).toBe('Right');
});
it('undo after applt rtl via dialog',()=>{
console.log('undo after applt rtl via dialog');
editor.editorHistory.undo();
expect(editor.selection.tableFormat.tableAlignment).toBe('Left');
});
it('redo after applt rtl via dialog',()=>{
console.log('redo after applt rtl via dialog');
editor.editorHistory.redo();
expect(editor.selection.tableFormat.tableAlignment).toBe('Right');
});
});
describe('Change RTl options with table indent', () => {
let editor: DocumentEditor;
let dialog: TablePropertiesDialog;
let event: any;
beforeAll((): void => {
editor = undefined;
let ele: HTMLElement = createElement('div', { id: 'container' });
document.body.appendChild(ele);
DocumentEditor.Inject(Editor, Selection, TablePropertiesDialog, EditorHistory);
editor = new DocumentEditor({ enableEditor: true, enableEditorHistory: true, enableSelection: true, isReadOnly: false, enableTablePropertiesDialog: true });
(editor.documentHelper as any).containerCanvasIn = TestHelper.containerCanvas;
(editor.documentHelper as any).selectionCanvasIn = TestHelper.selectionCanvas;
(editor.documentHelper.render as any).pageCanvasIn = TestHelper.pageCanvas;
(editor.documentHelper.render as any).selectionCanvasIn = TestHelper.pageSelectionCanvas;
editor.appendTo('#container');
dialog = editor.tablePropertiesDialogModule
});
afterAll((done) => {
editor.destroy();
document.body.removeChild(document.getElementById('container'));
editor = undefined;
document.body.innerHTML = '';
setTimeout(function () {
done();
}, 2000);
});
it('Table for bidi is true and table alignment as left', () => {
console.log('Table for bidi is true and table alignment as left');
editor.editor.insertTable(2, 2);
editor.selection.tableFormat.preferredWidthType='Point';
editor.selection.tableFormat.preferredWidth=100;
editor.selection.tableFormat.leftIndent=36;
editor.tablePropertiesDialogModule.show();
event = { value: "rtl" };
(dialog as any).changeBidirectional(event);
dialog.applyTableProperties();
expect(editor.selection.tableFormat.bidi).toBe(true);
expect(editor.selection.tableFormat.leftIndent).toBe(0);
});
it('undo after applt rtl via dialog',()=>{
console.log('undo after applt rtl via dialog');
editor.editorHistory.undo();
expect(editor.selection.tableFormat.leftIndent).toBe(36);
});
it('redo after applt rtl via dialog',()=>{
console.log('redo after applt rtl via dialog');
editor.editorHistory.redo();
expect(editor.selection.tableFormat.leftIndent).toBe(0);
});
}); | the_stack |
import { ethers, network } from "hardhat"
import { expect } from "chai"
import { ADDRESS_ZERO, advanceTimeAndBlock, advanceBlockTo, latest, duration, increase } from "./utilities"
describe("MasterChefJoeV2", function () {
before(async function () {
this.signers = await ethers.getSigners()
this.alice = this.signers[0]
this.bob = this.signers[1]
this.carol = this.signers[2]
this.dev = this.signers[3]
this.treasury = this.signers[4]
this.investor = this.signers[5]
this.minter = this.signers[6]
this.MCV1PerBlock = await ethers.getContractFactory("MasterChef")
this.MCV1PerSec = await ethers.getContractFactory("MasterChefPerSec")
this.MCV2 = await ethers.getContractFactory("MasterChefJoeV2")
this.SimpleRewarderPerBlock = await ethers.getContractFactory("SimpleRewarderPerBlock")
this.SimpleRewarderPerSec = await ethers.getContractFactory("SimpleRewarderPerSec")
this.MasterChefRewarderPerBlock = await ethers.getContractFactory("MasterChefRewarderPerBlock")
this.MasterChefRewarderPerSec = await ethers.getContractFactory("MasterChefRewarderPerSec")
this.JoeToken = await ethers.getContractFactory("JoeToken")
this.ERC20Mock = await ethers.getContractFactory("ERC20Mock", this.minter)
this.SushiToken = await ethers.getContractFactory("SushiToken")
this.devPercent = 200
this.treasuryPercent = 200
this.investorPercent = 100
this.lpPercent = 1000 - this.devPercent - this.treasuryPercent
this.joePerSec = 100
this.secOffset = 1
this.tokenOffset = 1
this.reward = (sec: number, percent: number) => (sec * this.joePerSec * percent) / 1000
// Partner MasterChef parameters
this.partnerDev = this.signers[6]
this.partnerRewardPerBlock = 40
this.partnerRewardPerSec = 40
this.partnerStartBlock = 0
this.partnerBonusEndBlock = 10
this.partnerChefPid = 0
this.partnerChefAllocPoint = 100
})
beforeEach(async function () {
this.joe = await this.JoeToken.deploy() // b=1
await this.joe.deployed()
this.partnerToken = await this.SushiToken.deploy() // b=2
await this.partnerToken.deployed()
})
it("should revert contract creation if dev and treasury percents don't meet criteria", async function () {
const startTime = (await latest()).add(60)
// Invalid dev percent failure
await expect(
this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
"100",
startTime,
"1100",
this.treasuryPercent,
this.investorPercent
)
).to.be.revertedWith("constructor: invalid dev percent value")
// Invalid treasury percent failure
await expect(
this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
"100",
startTime,
this.devPercent,
"1100",
this.investorPercent
)
).to.be.revertedWith("constructor: invalid treasury percent value")
// Invalid treasury percent failure
await expect(
this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
"100",
startTime,
this.devPercent,
this.treasuryPercent,
"1100"
)
).to.be.revertedWith("constructor: invalid investor percent value")
// Sum of dev, treasury and investor precent too high
await expect(
this.MCV2.deploy(this.joe.address, this.dev.address, this.treasury.address, this.investor.address, "100", startTime, "300", "300", "401")
).to.be.revertedWith("constructor: total percent over max")
})
it("should set correct state variables", async function () {
// We make start time 60 seconds past the last block
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed()
await this.joe.transferOwnership(this.chef.address)
const joe = await this.chef.joe()
const devAddr = await this.chef.devAddr()
const treasuryAddr = await this.chef.treasuryAddr()
const investorAddr = await this.chef.investorAddr()
const owner = await this.joe.owner()
const devPercent = await this.chef.devPercent()
const treasuryPercent = await this.chef.treasuryPercent()
const investorPercent = await this.chef.investorPercent()
expect(joe).to.equal(this.joe.address)
expect(devAddr).to.equal(this.dev.address)
expect(treasuryAddr).to.equal(this.treasury.address)
expect(investorAddr).to.equal(this.investor.address)
expect(owner).to.equal(this.chef.address)
expect(devPercent).to.equal(this.devPercent)
expect(treasuryPercent).to.equal(this.treasuryPercent)
expect(investorPercent).to.equal(this.investorPercent)
})
it("should allow dev, treasury and investor to update themselves", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed()
expect(await this.chef.devAddr()).to.equal(this.dev.address)
await expect(this.chef.connect(this.bob).dev(this.bob.address, { from: this.bob.address })).to.be.revertedWith("dev: wut?")
await this.chef.connect(this.dev).dev(this.bob.address, { from: this.dev.address })
expect(await this.chef.devAddr()).to.equal(this.bob.address)
await expect(this.chef.connect(this.bob).setTreasuryAddr(this.bob.address, { from: this.bob.address })).to.be.revertedWith(
"setTreasuryAddr: wut?"
)
await this.chef.connect(this.treasury).setTreasuryAddr(this.bob.address, { from: this.treasury.address })
expect(await this.chef.treasuryAddr()).to.equal(this.bob.address)
await expect(this.chef.connect(this.bob).setInvestorAddr(this.bob.address, { from: this.bob.address })).to.be.revertedWith(
"setInvestorAddr: wut?"
)
await this.chef.connect(this.investor).setInvestorAddr(this.bob.address, { from: this.investor.address })
expect(await this.chef.investorAddr()).to.equal(this.bob.address)
})
it("should check dev, treasury and investor percents are set correctly", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed()
await this.chef.setDevPercent(100)
await this.chef.setTreasuryPercent(100)
await this.chef.setInvestorPercent(800)
expect(await this.chef.devPercent()).to.equal("100")
expect(await this.chef.treasuryPercent()).to.equal("100")
expect(await this.chef.investorPercent()).to.equal("800")
// We don't test negative values because function only takes in unsigned ints
await expect(this.chef.setDevPercent("1200")).to.be.revertedWith("setDevPercent: invalid percent value")
await expect(this.chef.setDevPercent("900")).to.be.revertedWith("setDevPercent: total percent over max")
await expect(this.chef.setTreasuryPercent("1200")).to.be.revertedWith("setTreasuryPercent: invalid percent value")
await expect(this.chef.setTreasuryPercent("900")).to.be.revertedWith("setTreasuryPercent: total percent over max")
})
context("With ERC/LP token added to the field and using SimpleRewarderPerBlock", function () {
beforeEach(async function () {
this.lp = await this.ERC20Mock.deploy("LPToken", "LP", "10000000000") // b=3
await this.lp.transfer(this.alice.address, "1000") // b=4
await this.lp.transfer(this.bob.address, "1000") // b=5
await this.lp.transfer(this.carol.address, "1000") // b=6
this.lp2 = await this.ERC20Mock.deploy("LPToken2", "LP2", "10000000000") // b=7
await this.lp2.transfer(this.alice.address, "1000") // b=8
await this.lp2.transfer(this.bob.address, "1000") // b=9
await this.lp2.transfer(this.carol.address, "1000") // b=10
})
it("should check rewarder's arguments are contracts", async function () {
await expect(
this.SimpleRewarderPerBlock.deploy(ADDRESS_ZERO, this.lp.address, this.partnerRewardPerBlock, this.chef.address)
).to.be.revertedWith("constructor: reward token must be a valid contract")
await expect(
this.SimpleRewarderPerBlock.deploy(this.partnerToken.address, ADDRESS_ZERO, this.partnerRewardPerBlock, this.chef.address)
).to.be.revertedWith("constructor: LP token must be a valid contract")
await expect(
this.SimpleRewarderPerBlock.deploy(this.partnerToken.address, this.lp.address, this.partnerRewardPerBlock, ADDRESS_ZERO)
).to.be.revertedWith("constructor: MasterChefJoeV2 must be a valid contract")
})
it("should check rewarder added and set properly", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed()
this.rewarder = await this.SimpleRewarderPerBlock.deploy(this.joe.address, this.lp.address, this.partnerRewardPerBlock, this.chef.address)
await this.rewarder.deployed()
// Try to add rewarder that is neither zero address or contract address
await expect(this.chef.add("100", this.lp.address, this.dev.address)).to.be.revertedWith("add: rewarder must be contract or zero")
await this.chef.add("100", this.lp.address, this.rewarder.address)
// Try to set rewarder that is neither zero address or contract address
await expect(this.chef.set("0", "200", this.dev.address, true)).to.be.revertedWith("set: rewarder must be contract or zero")
await this.chef.set("0", "200", this.rewarder.address, false)
expect((await this.chef.poolInfo(0)).allocPoint).to.equal("200")
})
it("should allow a given pool's allocation weight and rewarder to be updated", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed()
this.rewarder = await this.SimpleRewarderPerBlock.deploy(this.joe.address, this.lp.address, this.partnerRewardPerBlock, this.chef.address)
await this.rewarder.deployed()
await this.chef.add("100", this.lp.address, ADDRESS_ZERO)
expect((await this.chef.poolInfo(0)).allocPoint).to.equal("100")
expect((await this.chef.poolInfo(0)).rewarder).to.equal(ADDRESS_ZERO)
await this.chef.set("0", "150", this.rewarder.address, true)
expect((await this.chef.poolInfo(0)).allocPoint).to.equal("150")
expect((await this.chef.poolInfo(0)).rewarder).to.equal(this.rewarder.address)
})
it("should allow emergency withdraw from MasterChefJoeV2", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed()
await this.chef.add("100", this.lp.address, ADDRESS_ZERO)
await this.lp.connect(this.bob).approve(this.chef.address, "1000")
await this.chef.connect(this.bob).deposit(0, "100")
expect(await this.lp.balanceOf(this.bob.address)).to.equal("900")
await this.chef.connect(this.bob).emergencyWithdraw(0)
expect(await this.lp.balanceOf(this.bob.address)).to.equal("1000")
})
it("should allow emergency withdraw from rewarder contract", async function () {
this.rewarder = await this.SimpleRewarderPerBlock.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerBlock,
this.chef.address
)
await this.rewarder.deployed()
await this.partnerToken.mint(this.rewarder.address, "1000000")
await this.rewarder.emergencyWithdraw()
expect(await this.partnerToken.balanceOf(this.alice.address)).to.equal("1000000")
})
it("should reward partner token accurately after rewarder runs out of tokens and is topped up again", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59, b=14
this.rewarder = await this.SimpleRewarderPerBlock.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerBlock,
this.chef.address
)
await this.rewarder.deployed() // t-58, b=15
await this.partnerToken.mint(this.rewarder.address, "80") // t-57, b=16
await this.joe.transferOwnership(this.chef.address) // t-56, b=17
await this.chef.add("100", this.lp.address, this.rewarder.address) // t-55, b=18
await this.lp.connect(this.bob).approve(this.chef.address, "1000") // t-54, b=19
await this.chef.connect(this.bob).deposit(0, "100") // t-53, b=20
await advanceTimeAndBlock(1) // t-52, b=21
await advanceTimeAndBlock(1) // t-51, b=22
await advanceTimeAndBlock(1) // t-50, b=23
await advanceTimeAndBlock(1) // t-49, b=24
await this.chef.connect(this.bob).deposit(0, "0") // t-48, b=25
// Bob should have:
// - 0 JoeToken
// - 80 PartnerToken
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal(80)
await advanceTimeAndBlock(1) // t-47, b=26
await advanceTimeAndBlock(1) // t-46, b=27
await advanceTimeAndBlock(1) // t-45, b=28
await advanceTimeAndBlock(1) // t-44, b=29
await advanceTimeAndBlock(1) // t-43, b=30
await this.partnerToken.mint(this.rewarder.address, "1000") // t-42, b=31
await advanceTimeAndBlock(1) // t-41, b=32
await advanceTimeAndBlock(1) // t-40, b=33
await advanceTimeAndBlock(1) // t-39, b=34
await advanceTimeAndBlock(1) // t-38, b=35
await advanceTimeAndBlock(1) // t-37, b=36
await this.chef.connect(this.bob).deposit(0, "0") // t-36, b=37
// Bob should have:
// - 0 JoeToken
// - 80 + 12*40 = 560 (+40) PartnerToken
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(560, 600)
})
it("should only allow MasterChefJoeV2 to call onJoeReward", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59, b=14
this.rewarder = await this.SimpleRewarderPerBlock.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerBlock,
this.chef.address
)
await this.rewarder.deployed() // t-58, b=15
await this.partnerToken.mint(this.rewarder.address, "1000000000000000000000000") // t-57, b=16
await this.joe.transferOwnership(this.chef.address) // t-56, b=17
await this.chef.setDevPercent(this.devPercent) // t-55, b=18
await this.chef.setTreasuryPercent(this.treasuryPercent) // t-54, b=19
await this.chef.add("100", this.lp.address, this.rewarder.address) // t-53, b=20
await this.lp.connect(this.bob).approve(this.chef.address, "1000") // t-52, b=21
await this.chef.connect(this.bob).deposit(0, "100") // t-51, b=22
await advanceTimeAndBlock(40) // t-11, b=23
await expect(this.rewarder.onJoeReward(this.bob.address, "100")).to.be.revertedWith("onlyMCV2: only MasterChef V2 can call this function") // t-10, b=24
await this.chef.connect(this.bob).deposit(0, "0") // t-9, b=25
// Bob should have:
// - 0 JoeToken
// - 3*40 = 80 PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal("120")
})
it("should allow rewarder to be set and removed mid farming", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59, b=14
this.rewarder = await this.SimpleRewarderPerBlock.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerBlock,
this.chef.address
)
await this.rewarder.deployed() // t-58, b=15
await this.partnerToken.mint(this.rewarder.address, "1000000000000000000000000") // t-57, b=16
await this.joe.transferOwnership(this.chef.address) // t-56, b=17
await this.chef.add("100", this.lp.address, ADDRESS_ZERO) // t-55, b=18
await this.lp.connect(this.bob).approve(this.chef.address, "1000") // t-54, b=19
await this.chef.connect(this.bob).deposit(0, "100") // t-53, b=20
await advanceTimeAndBlock(42) // t-11, b=21
await this.chef.connect(this.bob).deposit(0, "0") // t-10, b=24
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
// At t+10, Bob should have pending:
// - 10*50 = 500 (+50) JoeToken
// - 0 PartnerToken
await advanceTimeAndBlock(20) // t+10, b=25
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingJoe).to.be.within(500, 550)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenAddress).to.equal(ADDRESS_ZERO)
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingBonusToken).to.equal(0)
// Pass rewarder but don't overwrite
await this.chef.set(0, 100, this.rewarder.address, false) // t+11 ,b=26
// At t+20, Bob should have pending:
// - 500 + 10*50 = 1000 (+50) JoeToken
// - 0 PartnerToken
await advanceTimeAndBlock(9) // t+20, b=27
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingJoe).to.be.within(1000, 1050)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenAddress).to.equal(ADDRESS_ZERO)
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingBonusToken).to.equal(0)
// Pass rewarder and overwrite
await this.chef.set(0, 100, this.rewarder.address, true) // t+21, b=28
// At t+30, Bob should have pending:
// - 1000 + 10*50 = 1500 (+50) JoeToken
// - 0 PartnerToken - this is because rewarder hasn't registered the user yet! User needs to call deposit again
await advanceTimeAndBlock(4) // t+25, b=29
await advanceTimeAndBlock(5) // t+30, b=30
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingJoe).to.be.within(1500, 1550)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenAddress).to.equal(this.partnerToken.address)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenSymbol).to.equal("SUSHI")
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingBonusToken).to.equal(0)
// Call deposit to start receiving PartnerTokens
await this.chef.connect(this.bob).deposit(0, 0) // t+31, b=31
// At t+40, Bob should have pending:
// - 9*50 = 450 (+50) JoeToken
// - 2*40 = 80 PartnerToken
await advanceTimeAndBlock(4) // t+35, b=32
await advanceTimeAndBlock(5) // t+40, b=33
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingJoe).to.be.within(450, 500)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenAddress).to.equal(this.partnerToken.address)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenSymbol).to.equal("SUSHI")
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingBonusToken).to.equal(80)
// Set reward rate to zero
await this.rewarder.setRewardRate(0) // t+41, b=34
// At t+50, Bob should have pending:
// - 450 + 10*50 = 950 (+50) JoeToken
// - 80 + 1*40 = 120 PartnerToken
await advanceTimeAndBlock(4) // t+45, b=35
await advanceTimeAndBlock(5) // t+50, b=36
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingJoe).to.be.within(950, 1000)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenAddress).to.equal(this.partnerToken.address)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenSymbol).to.equal("SUSHI")
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingBonusToken).to.equal(120)
// Claim reward
await this.chef.connect(this.bob).deposit(0, 0) // t+51, b=37
// Bob should have:
// - 1500 + 1*50 + 950 + 1*50 = 2550 (+50) JoeToken
// - 120 PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(2550, 2600)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal(120)
})
it("should give out JOEs only after farming time", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59, b=14
this.rewarder = await this.SimpleRewarderPerBlock.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerBlock,
this.chef.address
)
await this.rewarder.deployed() // t-58, b=15
await this.partnerToken.mint(this.rewarder.address, "1000000000000000000000000") // t-57, b=16
await this.joe.transferOwnership(this.chef.address) // t-56, b=17
await this.chef.add("100", this.lp.address, this.rewarder.address) // t-55, b=18
await this.lp.connect(this.bob).approve(this.chef.address, "1000") // t-54, b=19
await this.chef.connect(this.bob).deposit(0, "100") // t-53, b=20
await advanceTimeAndBlock(42) // t-11, b=21
await this.chef.connect(this.bob).deposit(0, "0") // t-10, b=22
// Bob should have:
// - 0 JoeToken
// - 2*40 = 80 PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal("80")
await advanceTimeAndBlock(8) // t-2, b=23
await this.chef.connect(this.bob).deposit(0, "0") // t-1, b=24
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
await advanceTimeAndBlock(10) // t+9, b=25
await this.chef.connect(this.bob).deposit(0, "0") // t+10, b=26
// Bob should have:
// - 10*50 = 500 (+50) JoeToken
// - 80 + 4*40 = 240 PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(500, 550)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal("240")
await advanceTimeAndBlock(4) // t+14, b=27
await this.chef.connect(this.bob).deposit(0, "0") // t+15, b=28
// At this point:
// Bob should have:
// - 500 + 5*50 = 750 (+50) JoeToken
// - 240 + 2*40 = 320 PartnerToken
// Dev should have: 15*20 = 300 (+20)
// Treasury should have: 15*20 = 300 (+20)
// Investor should have: 15*10 = 150 (+10)
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(750, 800)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal("320")
expect(await this.joe.balanceOf(this.dev.address)).to.be.within(300, 320)
expect(await this.joe.balanceOf(this.treasury.address)).to.be.within(300, 320)
expect(await this.joe.balanceOf(this.investor.address)).to.be.within(150, 160)
expect(await this.joe.totalSupply()).to.be.within(1500, 1600)
})
it("should not distribute JOEs if no one deposit", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59, b=14
this.rewarder = await this.SimpleRewarderPerBlock.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerBlock,
this.chef.address
)
await this.rewarder.deployed() // t-58, b=15
await this.partnerToken.mint(this.rewarder.address, "1000000000000000000000000") // t-57, b=16
await this.joe.transferOwnership(this.chef.address) // t-56, b=17
await this.chef.add("100", this.lp.address, this.rewarder.address) // t-55, b=18
await this.lp.connect(this.bob).approve(this.chef.address, "1000") // t-54, b=19
await advanceTimeAndBlock(108) // t+54, b=20
expect(await this.joe.totalSupply()).to.equal("0")
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal("0")
await advanceTimeAndBlock(5) // t+59, b=21
expect(await this.joe.totalSupply()).to.equal("0")
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal("0")
await advanceTimeAndBlock(5) // t+64, b=22
await this.chef.connect(this.bob).deposit(0, "10") // t+65, b=23
expect(await this.joe.totalSupply()).to.equal("0")
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal("0")
expect(await this.joe.balanceOf(this.dev.address)).to.equal("0")
expect(await this.lp.balanceOf(this.bob.address)).to.equal("990")
await advanceTimeAndBlock(10) // t+75, b=24
// Revert if Bob withdraws more than he deposited
await expect(this.chef.connect(this.bob).withdraw(0, "11")).to.be.revertedWith("withdraw: not good") // t+76, b=25
await this.chef.connect(this.bob).withdraw(0, "10") // t+77, b=26
// At this point:
// Bob should have:
// - 12*50 = 600 (+50) JoeToken
// - 3*40 = 120 PartnerToken
// Dev should have:
// - 12*20 = 240 (+20) JoeToken
// Treasury should have:
// - 12*20 = 240 (+20) JoeToken
// Investor should have:
// - 12*10 = 120 (+10) JoeToken
expect(await this.joe.totalSupply()).to.be.within(1200, 1300)
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(600, 650)
expect(await this.joe.balanceOf(this.dev.address)).to.be.within(240, 260)
expect(await this.joe.balanceOf(this.treasury.address)).to.be.within(240, 260)
expect(await this.joe.balanceOf(this.investor.address)).to.be.within(120, 130)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal(120)
})
it("should distribute JOEs properly for each staker", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59, b=14
this.rewarder = await this.SimpleRewarderPerBlock.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerBlock,
this.chef.address
)
await this.rewarder.deployed() // t-58, b=15
await this.partnerToken.mint(this.rewarder.address, "1000000000000000000000000") // t-57, b=16
await this.joe.transferOwnership(this.chef.address) // t-56, b=17
await this.chef.add("100", this.lp.address, this.rewarder.address) // t-55, b=18
await this.lp.connect(this.alice).approve(this.chef.address, "1000", {
from: this.alice.address,
}) // t-54, b=19
await this.lp.connect(this.bob).approve(this.chef.address, "1000", {
from: this.bob.address,
}) // t-53, b=20
await this.lp.connect(this.carol).approve(this.chef.address, "1000", {
from: this.carol.address,
}) // t-52, b=21
// Alice deposits 10 LPs at t+10
await advanceTimeAndBlock(61) // t+9, b=22
await this.chef.connect(this.alice).deposit(0, "10", { from: this.alice.address }) // t+10, b=23
// Bob deposits 20 LPs at t+14
await advanceTimeAndBlock(3) // t+13, b=24
await this.chef.connect(this.bob).deposit(0, "20") // t+14, b=25
// Carol deposits 30 LPs at block t+18
await advanceTimeAndBlock(3) // t+17, b=26
await this.chef.connect(this.carol).deposit(0, "30", { from: this.carol.address }) // t+18, b=27
// Alice deposits 10 more LPs at t+20. At this point:
// Alice should have:
// - 4*50 + 4*50*1/3 + 2*50*1/6 = 283 (+50) JoeToken
// - 2*40 + 2*40*1/3 + 2*40*1/6 = 120 PartnerToken
// Dev should have: 10*20 = 200 (+20)
// Treasury should have: 10*20 = 200 (+20)
// Investor should have: 10*10 = 100 (+10)
// MasterChef should have: 1000 - 283 - 200 - 200 - 100 = 217 (+100)
await advanceTimeAndBlock(1) // t+19, b=28
await this.chef.connect(this.alice).deposit(0, "10", { from: this.alice.address }) // t+20, b=29
expect(await this.joe.totalSupply()).to.be.within(1000, 1100)
// Because LP rewards are divided among participants and rounded down, we account
// for rounding errors with an offset
expect(await this.joe.balanceOf(this.alice.address)).to.be.within(283 - this.tokenOffset, 333 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.alice.address)).to.be.within(120 - this.tokenOffset, 120 + this.tokenOffset)
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal("0")
expect(await this.joe.balanceOf(this.carol.address)).to.equal("0")
expect(await this.partnerToken.balanceOf(this.carol.address)).to.equal("0")
expect(await this.joe.balanceOf(this.dev.address)).to.be.within(200 - this.tokenOffset, 220 + this.tokenOffset)
expect(await this.joe.balanceOf(this.treasury.address)).to.be.within(200 - this.tokenOffset, 220 + this.tokenOffset)
expect(await this.joe.balanceOf(this.investor.address)).to.be.within(100 - this.tokenOffset, 110 + this.tokenOffset)
expect(await this.joe.balanceOf(this.chef.address)).to.be.within(217 - this.tokenOffset, 317 + this.tokenOffset)
// Bob withdraws 5 LPs at t+30. At this point:
// Bob should have:
// - 4*50*2/3 + 2*50*2/6 + 10*50*2/7 = 309 (+50) JoeToken
// - 2*40*2/3 + 2*40*2/6 + 2*40*2/7 = 102 PartnerToken
// Dev should have: 20*20= 400 (+20)
// Treasury should have: 20*20 = 400 (+20)
// Investor should have: 20*10 = 200 (+10)
// MasterChef should have: 217 + 1000 - 309 - 200 - 200 - 100 = 408 (+100)
await advanceTimeAndBlock(9) // t+29, b=32
await this.chef.connect(this.bob).withdraw(0, "5", { from: this.bob.address }) // t+30, b=33
expect(await this.joe.totalSupply()).to.be.within(2000, 2100)
// Because of rounding errors, we use token offsets
expect(await this.joe.balanceOf(this.alice.address)).to.be.within(283 - this.tokenOffset, 333 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.alice.address)).to.be.within(119 - this.tokenOffset, 119 + this.tokenOffset)
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(309 - this.tokenOffset, 359 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(101 - this.tokenOffset, 101 + this.tokenOffset)
expect(await this.joe.balanceOf(this.carol.address)).to.equal("0")
expect(await this.partnerToken.balanceOf(this.carol.address)).to.equal("0")
expect(await this.joe.balanceOf(this.dev.address)).to.be.within(400 - this.tokenOffset, 420 + this.tokenOffset)
expect(await this.joe.balanceOf(this.treasury.address)).to.be.within(400 - this.tokenOffset, 420 + this.tokenOffset)
expect(await this.joe.balanceOf(this.investor.address)).to.be.within(200 - this.tokenOffset, 210 + this.tokenOffset)
expect(await this.joe.balanceOf(this.chef.address)).to.be.within(408 - this.tokenOffset, 508 + this.tokenOffset)
// Alice withdraws 20 LPs at t+40
// Bob withdraws 15 LPs at t+50
// Carol withdraws 30 LPs at t+60
await advanceTimeAndBlock(9) // t+39, b=34
await this.chef.connect(this.alice).withdraw(0, "20", { from: this.alice.address }) // t+40, b=35
await advanceTimeAndBlock(9) // t+49, b=36
await this.chef.connect(this.bob).withdraw(0, "15", { from: this.bob.address }) // t+50, b=37
await advanceTimeAndBlock(9) // t+59, b=38
await this.chef.connect(this.carol).withdraw(0, "30", { from: this.carol.address }) // t+60, b=39
expect(await this.joe.totalSupply()).to.be.within(5000, 5100)
// Alice should have:
// - 283 + 10*50*2/7 + 10*50*20/65 = 579 (+50) JoeToken
// - 120 + 2*40*2/7 + 2*40*20/65 = 167 PartnerToken
expect(await this.joe.balanceOf(this.alice.address)).to.be.within(579 - this.tokenOffset, 629 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.alice.address)).to.be.within(167 - this.tokenOffset, 167 + this.tokenOffset)
// Bob should have:
// - 309 + 10*50*15/65 + 10*50*15/45 = 591 (+50) JoeToken
// - 102 + 2*40*15/65 + 2*40*15/45 = 147 PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(591 - this.tokenOffset, 641 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(147 - this.tokenOffset, 147 + this.tokenOffset)
// Carol should have:
// - 2*50*3/6 + 10*50*3/7 + 10*50*30/65 + 10*50*30/45 + 10*50 = 1445 (+50) JoeToken
// - 2*40*1/2 + 2*40*3/7 + 2*40*30/65 + 2*40*30/45 + 2*40 = 244 PartnerToken
expect(await this.joe.balanceOf(this.carol.address)).to.be.within(1328 - this.tokenOffset, 1378 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.carol.address)).to.be.within(244 - this.tokenOffset, 244 + this.tokenOffset)
// Dev should have: 50*20 = 1000 (+20)
// Treasury should have: 50*20 = 1000 (+20)
// Investor should have: 50*10 = 500 (+10)
expect(await this.joe.balanceOf(this.dev.address)).to.be.within(1000 - this.tokenOffset, 1020 + this.tokenOffset)
expect(await this.joe.balanceOf(this.treasury.address)).to.be.within(1000 - this.tokenOffset, 1020 + this.tokenOffset)
expect(await this.joe.balanceOf(this.investor.address)).to.be.within(500 - this.tokenOffset, 510 + this.tokenOffset)
// MasterChefJoe should have nothing
expect(await this.joe.balanceOf(this.chef.address)).to.be.within(0, 0 + this.tokenOffset)
// // All of them should have 1000 LPs back.
expect(await this.lp.balanceOf(this.alice.address)).to.equal("1000")
expect(await this.lp.balanceOf(this.bob.address)).to.equal("1000")
expect(await this.lp.balanceOf(this.carol.address)).to.equal("1000")
})
it("should give proper JOEs allocation to each pool", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59, b=14
this.rewarder = await this.SimpleRewarderPerBlock.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerBlock,
this.chef.address
)
await this.rewarder.deployed() // t-58, b=15
await this.partnerToken.mint(this.rewarder.address, "1000000000000000000000000") // t-57, b=16
await this.joe.transferOwnership(this.chef.address) // t-56, b=17
await this.lp.connect(this.alice).approve(this.chef.address, "1000", { from: this.alice.address }) // t-55, b=18
await this.lp2.connect(this.bob).approve(this.chef.address, "1000", { from: this.bob.address }) // t-54, b=19
// Add first LP to the pool with allocation 10
await this.chef.add("10", this.lp.address, this.rewarder.address) // t-53, b=20
// Alice deposits 10 LPs at t+10
await advanceTimeAndBlock(62) // t+9, b=21
await this.chef.connect(this.alice).deposit(0, "10", { from: this.alice.address }) // t+10, b=22
// Add LP2 to the pool with allocation 20 at t+20
await advanceTimeAndBlock(9) // t+19, b=23
await this.chef.add("20", this.lp2.address, ADDRESS_ZERO) // t+20, b=24
// Alice's pending reward should be:
// - 10*50 = 500 (+50) JoeToken
// - 2*40 = 80 PartnerToken
expect((await this.chef.pendingTokens(0, this.alice.address)).pendingJoe).to.be.within(500 - this.tokenOffset, 550 + this.tokenOffset)
expect(await this.rewarder.pendingTokens(this.alice.address)).to.equal(80)
// Bob deposits 10 LP2s at t+25
await advanceTimeAndBlock(4) // t+24, b=25
await this.chef.connect(this.bob).deposit(1, "10", { from: this.bob.address }) // t+25, b=26
// Alice's pending reward should be:
// - 500 + 5*1/3*50 = 583 (+50) JoeToken
// - 80 + 2*40 = 160 PartnerToken
expect((await this.chef.pendingTokens(0, this.alice.address)).pendingJoe).to.be.within(583 - this.tokenOffset, 633 + this.tokenOffset)
expect(await this.rewarder.pendingTokens(this.alice.address)).to.equal(160)
// At this point:
// Alice's pending reward should be:
// - 583 + 5*1/3*50 = 666 (+50) JoeToken
// - 160 + 1*40 = 200 PartnerToken
// Bob's pending reward should be:
// - 5*2/3*50 = 166 (+50) JoeToken
// - 0 PartnerToken
await advanceTimeAndBlock(5) // t+30, b=27
expect((await this.chef.pendingTokens(0, this.alice.address)).pendingJoe).to.be.within(666 - this.tokenOffset, 716 + this.tokenOffset)
expect(await this.rewarder.pendingTokens(this.alice.address)).to.equal(200)
expect((await this.chef.pendingTokens(1, this.bob.address)).pendingJoe).to.be.within(166 - this.tokenOffset, 216 + this.tokenOffset)
expect(await this.rewarder.pendingTokens(this.bob.address)).to.equal(0)
// Alice and Bob should not have pending rewards in pools they're not staked in
expect((await this.chef.pendingTokens(1, this.alice.address)).pendingJoe).to.equal("0")
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingJoe).to.equal("0")
// Make sure they have receive the same amount as what was pending
await this.chef.connect(this.alice).withdraw(0, "10", { from: this.alice.address }) // t+31, b=28
// Alice should have:
// - 666 + 1*1/3*50 = 682 (+50) JoeToken
// - 200 + 1*40 = 240 PartnerToken
expect(await this.joe.balanceOf(this.alice.address)).to.be.within(682 - this.tokenOffset, 732 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.alice.address)).to.equal(240)
await this.chef.connect(this.bob).withdraw(1, "5", { from: this.bob.address }) // t+32, b=29
// Bob should have:
// - 166 + 2*2/3*50 = 232 (+50) JoeToken
// - 0 PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(232 - this.tokenOffset, 282 + this.tokenOffset)
expect(await this.rewarder.pendingTokens(this.bob.address)).to.equal(0)
})
it("should give proper JOEs after updating emission rate", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59, b=14
this.rewarder = await this.SimpleRewarderPerBlock.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerBlock,
this.chef.address
)
await this.rewarder.deployed() // t-58, b=15
await this.partnerToken.mint(this.rewarder.address, "1000000000000000000000000") // t-57, b=16
await this.joe.transferOwnership(this.chef.address) // t-56, b=17
await this.lp.connect(this.alice).approve(this.chef.address, "1000", { from: this.alice.address }) // t-55, b=18
await this.chef.add("10", this.lp.address, this.rewarder.address) // t-54, b=19
// Alice deposits 10 LPs at t+10
await advanceTimeAndBlock(63) // t+9, b=20
await this.chef.connect(this.alice).deposit(0, "10", { from: this.alice.address }) // t+10, b=21
// At t+110, Alice should have:
// - 100*50 = 5000 (+50) JoeToken
// - 1*40 = 40 PartnerToken
await advanceTimeAndBlock(100) // t+110, b=22
expect((await this.chef.pendingTokens(0, this.alice.address)).pendingJoe).to.be.within(5000, 5050)
expect(await this.rewarder.pendingTokens(this.alice.address)).to.equal(40)
// Lower JOE emission rate to 40 JOE per sec
await this.chef.updateEmissionRate(40) // t+111, b=23
// At t+115, Alice should have:
// - 5000 + 1*100*0.5 + 4*40*0.5 = 5130 (+50) JoeToken
// - 40 + 2*40 = 120 PartnerToken
await advanceTimeAndBlock(4) // t+115, b=24
expect((await this.chef.pendingTokens(0, this.alice.address)).pendingJoe).to.be.within(5130, 5180)
expect(await this.rewarder.pendingTokens(this.alice.address)).to.equal(120)
// Increase PartnerToken emission rate to 90 PartnerToken per block
await this.rewarder.setRewardRate(90) // t+116, b=25
// At b=35, Alice should have:
// - 5130 + 1*40*0.5 + 20*40*0.5 = 5550 (+50) JoeToken
// - 120 + 1*40 + 5*90 = 610 PartnerToken
await advanceTimeAndBlock(2) // t+118, b=26
await advanceTimeAndBlock(3) // t+121, b=27
await advanceTimeAndBlock(4) // t+125, b=28
await advanceTimeAndBlock(5) // t+130, b=29
await advanceTimeAndBlock(6) // t+136, b=30
expect((await this.chef.pendingTokens(0, this.alice.address)).pendingJoe).to.be.within(5550, 5600)
expect(await this.rewarder.pendingTokens(this.alice.address)).to.equal(610)
})
})
context("With ERC/LP token added to the field and using SimpleRewarderPerSec", function () {
beforeEach(async function () {
this.lp = await this.ERC20Mock.deploy("LPToken", "LP", "10000000000")
await this.lp.transfer(this.alice.address, "1000")
await this.lp.transfer(this.bob.address, "1000")
await this.lp.transfer(this.carol.address, "1000")
this.lp2 = await this.ERC20Mock.deploy("LPToken2", "LP2", "10000000000")
await this.lp2.transfer(this.alice.address, "1000")
await this.lp2.transfer(this.bob.address, "1000")
await this.lp2.transfer(this.carol.address, "1000")
this.dummyToken = await this.ERC20Mock.deploy("DummyToken", "DUMMY", "1")
await this.dummyToken.transfer(this.partnerDev.address, "1")
})
it("should check rewarder's arguments are contracts", async function () {
await expect(
this.SimpleRewarderPerSec.deploy(ADDRESS_ZERO, this.lp.address, this.partnerRewardPerSec, this.chef.address, false)
).to.be.revertedWith("constructor: reward token must be a valid contract")
await expect(
this.SimpleRewarderPerSec.deploy(this.partnerToken.address, ADDRESS_ZERO, this.partnerRewardPerSec, this.chef.address, false)
).to.be.revertedWith("constructor: LP token must be a valid contract")
await expect(
this.SimpleRewarderPerSec.deploy(this.partnerToken.address, this.lp.address, this.partnerRewardPerSec, ADDRESS_ZERO, false)
).to.be.revertedWith("constructor: MasterChefJoe must be a valid contract")
})
it("should check rewarder added and set properly", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed()
this.rewarder = await this.SimpleRewarderPerSec.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerSec,
this.chef.address,
false
)
await this.rewarder.deployed()
// Try to add rewarder that is neither zero address or contract address
await expect(this.chef.add("100", this.lp.address, this.dev.address)).to.be.revertedWith("add: rewarder must be contract or zero")
await this.chef.add("100", this.lp.address, this.rewarder.address)
// Try to set rewarder that is neither zero address or contract address
await expect(this.chef.set("0", "200", this.dev.address, true)).to.be.revertedWith("set: rewarder must be contract or zero")
await this.chef.set("0", "200", this.rewarder.address, false)
expect((await this.chef.poolInfo(0)).allocPoint).to.equal("200")
})
it("should allow a given pool's allocation weight and rewarder to be updated", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed()
this.rewarder = await this.SimpleRewarderPerSec.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerSec,
this.chef.address,
false
)
await this.rewarder.deployed()
await this.chef.add("100", this.lp.address, ADDRESS_ZERO)
expect((await this.chef.poolInfo(0)).allocPoint).to.equal("100")
expect((await this.chef.poolInfo(0)).rewarder).to.equal(ADDRESS_ZERO)
await this.chef.set("0", "150", this.rewarder.address, true)
expect((await this.chef.poolInfo(0)).allocPoint).to.equal("150")
expect((await this.chef.poolInfo(0)).rewarder).to.equal(this.rewarder.address)
})
it("should allow emergency withdraw from rewarder contract", async function () {
// ERC-20
this.rewarder = await this.SimpleRewarderPerSec.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerSec,
this.chef.address,
false
)
await this.rewarder.deployed()
await this.partnerToken.mint(this.rewarder.address, "1000000")
await this.rewarder.emergencyWithdraw()
expect(await this.partnerToken.balanceOf(this.alice.address)).to.equal("1000000")
// AVAX
this.rewarderAVAX = await this.SimpleRewarderPerSec.deploy(
this.partnerToken.address, // Use any token address
this.lp.address,
this.partnerRewardPerSec,
this.chef.address,
true
)
await this.rewarderAVAX.deployed()
const rewardAmount = ethers.utils.parseEther("10")
const tx = { to: this.rewarderAVAX.address, value: rewardAmount }
await this.bob.sendTransaction(tx)
const bal = await ethers.provider.getBalance(this.rewarderAVAX.address)
expect(bal).to.equal(rewardAmount)
const aliceBalBefore = await this.alice.getBalance()
await this.rewarderAVAX.emergencyWithdraw()
const aliceBalAfter = await this.alice.getBalance()
expect(aliceBalAfter.sub(aliceBalBefore)).to.lt(rewardAmount)
})
it("should reward partner token accurately after rewarder runs out of tokens and is topped up again", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59
this.rewarder = await this.SimpleRewarderPerSec.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerSec,
this.chef.address,
false
)
await this.rewarder.deployed() // t-58
await this.partnerToken.mint(this.rewarder.address, "80") // t-57
await this.joe.transferOwnership(this.chef.address) // t-56
await this.chef.add("100", this.lp.address, this.rewarder.address) // t-55
await this.lp.connect(this.bob).approve(this.chef.address, "1000") // t-54
await this.chef.connect(this.bob).deposit(0, "100") // t-53
await advanceTimeAndBlock(4) // t-49
await this.chef.connect(this.bob).deposit(0, "0") // t-48
// Bob should have:
// - 0 JoeToken
// - 80 PartnerToken
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal(80)
await advanceTimeAndBlock(5) // t-43
await this.partnerToken.mint(this.rewarder.address, "1000") // t-42
await advanceTimeAndBlock(10) // t-32
await this.chef.connect(this.bob).deposit(0, "0") // t-31
// Bob should have:
// - 0 JoeToken
// - 80 + 20*40 = 880 (+40) PartnerToken
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(760, 920)
})
it("should reward AVAX accurately after rewarder runs out of AVAX and is topped up again", async function () {
const bobBalBefore = await this.bob.getBalance()
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59
this.rewarderAVAX = await this.SimpleRewarderPerSec.deploy(
this.partnerToken.address, // Use any token
this.lp.address,
ethers.utils.parseEther("10"),
this.chef.address,
true
)
await this.rewarderAVAX.deployed() // t-58
await this.alice.sendTransaction({ to: this.rewarderAVAX.address, value: ethers.utils.parseEther("20") }) // t-57
await this.joe.transferOwnership(this.chef.address) // t-56
await this.chef.add("100", this.lp.address, this.rewarderAVAX.address) // t-55
await this.lp.connect(this.bob).approve(this.chef.address, "1000") // t-54
await this.chef.connect(this.bob).deposit(0, "100") // t-53
await advanceTimeAndBlock(4) // t-49
await this.chef.connect(this.bob).deposit(0, "0") // t-48
// Bob should have:
// - 0 JoeToken
// - 20 Ether
const bobBalAfter = await this.bob.getBalance()
expect(bobBalAfter.sub(bobBalBefore)).to.gt(ethers.utils.parseEther("19"))
expect(bobBalAfter.sub(bobBalBefore)).to.lt(ethers.utils.parseEther("20"))
await advanceTimeAndBlock(5) // t-43
await this.alice.sendTransaction({ to: this.rewarderAVAX.address, value: ethers.utils.parseEther("1000") }) // t-42
await advanceTimeAndBlock(10) // t-32
await this.chef.connect(this.bob).deposit(0, "0") // t-31
// Bob should have:
// - 0 JoeToken
// - 20 + 20*10 = 220 (+10) PartnerToken
const bobBalFinal = await this.bob.getBalance()
const b = bobBalFinal.sub(bobBalAfter)
console.log(b.toString())
expect(bobBalFinal.sub(bobBalAfter)).to.gt(ethers.utils.parseEther("190"))
expect(bobBalFinal.sub(bobBalAfter)).to.lt(ethers.utils.parseEther("210"))
})
it("should only allow MasterChefJoeV2 to call onJoeReward", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59
this.rewarder = await this.SimpleRewarderPerSec.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerSec,
this.chef.address,
false
)
await this.rewarder.deployed() // t-58
await this.partnerToken.mint(this.rewarder.address, "1000000000000000000000000") // t-57
await this.joe.transferOwnership(this.chef.address) // t-56
await this.chef.add("100", this.lp.address, this.rewarder.address) // t-55
await this.lp.connect(this.bob).approve(this.chef.address, "1000") // t-54
await this.chef.connect(this.bob).deposit(0, "100") // t-53
await advanceTimeAndBlock(42) // t-11
await expect(this.rewarder.onJoeReward(this.bob.address, "100")).to.be.revertedWith("onlyMCJ: only MasterChefJoe can call this function") // t-10
await this.chef.connect(this.bob).deposit(0, "0") // t-9
// Bob should have:
// - 0 JoeToken
// - 44*40 = 1760 (+40) PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(1760, 1800)
})
it("should allow rewarder to be set and removed mid farming", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59
this.rewarder = await this.SimpleRewarderPerSec.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerSec,
this.chef.address,
false
)
await this.rewarder.deployed() // t-58
await this.partnerToken.mint(this.rewarder.address, "1000000000000000000000000") // t-57
await this.joe.transferOwnership(this.chef.address) // t-56
await this.chef.add("100", this.lp.address, ADDRESS_ZERO) // t-55
await this.lp.connect(this.bob).approve(this.chef.address, "1000") // t-54
await this.chef.connect(this.bob).deposit(0, "100") // t-53
await advanceTimeAndBlock(42) // t-11
await this.chef.connect(this.bob).deposit(0, "0") // t-10
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
// At t+10, Bob should have pending:
// - 10*50 = 500 (+50) JoeToken
// - 0 PartnerToken
await advanceTimeAndBlock(20) // t+10
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingJoe).to.be.within(500, 550)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenAddress).to.equal(ADDRESS_ZERO)
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingBonusToken).to.equal(0)
// Pass rewarder but don't overwrite
await this.chef.set(0, 100, this.rewarder.address, false) // t+11
// At t+20, Bob should have pending:
// - 500 + 10*50 = 1000 (+50) JoeToken
// - 0 PartnerToken
await advanceTimeAndBlock(9) // t+20
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingJoe).to.be.within(1000, 1050)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenAddress).to.equal(ADDRESS_ZERO)
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingBonusToken).to.equal(0)
// Pass rewarder and overwrite
await this.chef.set(0, 100, this.rewarder.address, true) // t+21
// At t+30, Bob should have pending:
// - 1000 + 10*50 = 1500 (+50) JoeToken
// - 0 PartnerToken - this is because rewarder hasn't registered the user yet! User needs to call deposit again
await advanceTimeAndBlock(9) // t+30
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingJoe).to.be.within(1500, 1550)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenAddress).to.equal(this.partnerToken.address)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenSymbol).to.equal("SUSHI")
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingBonusToken).to.equal(0)
// Call deposit to start receiving PartnerTokens
await this.chef.connect(this.bob).deposit(0, 0) // t+31
// At t+40, Bob should have pending:
// - 9*50 = 450 (+50) JoeToken
// - 9*40 = 360 (+40) PartnerToken
await advanceTimeAndBlock(9) // t+40
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingJoe).to.be.within(450, 500)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenAddress).to.equal(this.partnerToken.address)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenSymbol).to.equal("SUSHI")
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingBonusToken).to.be.within(360, 400)
// Set reward rate to zero
await this.rewarder.setRewardRate(0) // t+41
// At t+50, Bob should have pending:
// - 450 + 10*50 = 950 (+50) JoeToken
// - 360 + 1*40 = 400 (+40) PartnerToken
await advanceTimeAndBlock(4) // t+45
await advanceTimeAndBlock(5) // t+50
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingJoe).to.be.within(950, 1000)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenAddress).to.equal(this.partnerToken.address)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenSymbol).to.equal("SUSHI")
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingBonusToken).to.be.within(400, 440)
// Claim reward
await this.chef.connect(this.bob).deposit(0, 0) // t+51
// Bob should have:
// - 1500 + 1*50 + 950 + 1*50 = 2550 (+50) JoeToken
// - 400 (+40) PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(2550, 2600)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(400, 440)
})
it("should give out JOEs only after farming time", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59
this.rewarder = await this.SimpleRewarderPerSec.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerSec,
this.chef.address,
false
)
await this.rewarder.deployed() // t-58
await this.partnerToken.mint(this.rewarder.address, "1000000000000000000000000") // t-57
await this.joe.transferOwnership(this.chef.address) // t-56
await this.chef.add("100", this.lp.address, this.rewarder.address) // t-55
await this.lp.connect(this.bob).approve(this.chef.address, "1000") // t-54
await this.chef.connect(this.bob).deposit(0, "100") // t-53
await advanceTimeAndBlock(42) // t-11
await this.chef.connect(this.bob).deposit(0, "0") // t-10
// Bob should have:
// - 0 JoeToken
// - 43*40 = 1720 (+40) PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(1720, 1760)
await advanceTimeAndBlock(8) // t-2
await this.chef.connect(this.bob).deposit(0, "0") // t-1
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
await advanceTimeAndBlock(10) // t+9
await this.chef.connect(this.bob).deposit(0, "0") // t+10
// Bob should have:
// - 10*50 = 500 (+50) JoeToken
// - 1720 + 20*40 = 2520 (+40) PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(500, 550)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(2520, 2560)
await advanceTimeAndBlock(4) // t+14
await this.chef.connect(this.bob).deposit(0, "0") // t+15
// At this point:
// Bob should have:
// - 500 + 5*50 = 750 (+50) JoeToken
// - 2520 + 5*40 = 2720 (+40) PartnerToken
// Dev should have: 15*20 = 300 (+20)
// Treasury should have: 15*20 = 300 (+20)
// Investor should have: 15*10 = 150 (+10)
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(750, 800)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(2720, 2760)
expect(await this.joe.balanceOf(this.dev.address)).to.be.within(300, 320)
expect(await this.joe.balanceOf(this.treasury.address)).to.be.within(300, 320)
expect(await this.joe.balanceOf(this.investor.address)).to.be.within(150, 160)
expect(await this.joe.totalSupply()).to.be.within(1500, 1600)
})
it("should not distribute JOEs if no one deposit", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59
this.rewarder = await this.SimpleRewarderPerSec.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerSec,
this.chef.address,
false
)
await this.rewarder.deployed() // t-58
await this.partnerToken.mint(this.rewarder.address, "1000000000000000000000000") // t-57
await this.joe.transferOwnership(this.chef.address) // t-56
await this.chef.add("100", this.lp.address, this.rewarder.address) // t-55
await this.lp.connect(this.bob).approve(this.chef.address, "1000") // t-54
await advanceTimeAndBlock(108) // t+54
expect(await this.joe.totalSupply()).to.equal("0")
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal("0")
await advanceTimeAndBlock(5) // t+59
expect(await this.joe.totalSupply()).to.equal("0")
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal("0")
await advanceTimeAndBlock(5) // t+64
await this.chef.connect(this.bob).deposit(0, "10") // t+65
expect(await this.joe.totalSupply()).to.equal("0")
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal("0")
expect(await this.joe.balanceOf(this.dev.address)).to.equal("0")
expect(await this.lp.balanceOf(this.bob.address)).to.equal("990")
await advanceTimeAndBlock(10) // t+75
// Revert if Bob withdraws more than he deposited
await expect(this.chef.connect(this.bob).withdraw(0, "11")).to.be.revertedWith("withdraw: not good") // t+76
await this.chef.connect(this.bob).withdraw(0, "10") // t+77
// At this point:
// Bob should have:
// - 12*50 = 600 (+50) JoeToken
// - 12*40 = 480 (+40) PartnerToken
// Dev should have:
// - 12*20 = 240 (+20) JoeToken
// Treasury should have:
// - 12*20 = 240 (+20) JoeToken
// Investor should have:
// - 12*10 = 120 (+10) Joetoken
expect(await this.joe.totalSupply()).to.be.within(1200, 1300)
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(600, 650)
expect(await this.joe.balanceOf(this.dev.address)).to.be.within(240, 260)
expect(await this.joe.balanceOf(this.treasury.address)).to.be.within(240, 260)
expect(await this.joe.balanceOf(this.investor.address)).to.be.within(120, 130)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(480, 520)
})
it("should distribute JOEs properly for each staker", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59
this.rewarder = await this.SimpleRewarderPerSec.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerSec,
this.chef.address,
false
)
await this.rewarder.deployed() // t-58
await this.partnerToken.mint(this.rewarder.address, "1000000000000000000000000") // t-57
await this.joe.transferOwnership(this.chef.address) // t-56
await this.chef.add("100", this.lp.address, this.rewarder.address) // t-55
await this.lp.connect(this.alice).approve(this.chef.address, "1000", {
from: this.alice.address,
}) // t-54
await this.lp.connect(this.bob).approve(this.chef.address, "1000", {
from: this.bob.address,
}) // t-53
await this.lp.connect(this.carol).approve(this.chef.address, "1000", {
from: this.carol.address,
}) // t-52
// Alice deposits 10 LPs at t+10
await advanceTimeAndBlock(59) // t+9
await this.chef.connect(this.alice).deposit(0, "10", { from: this.alice.address }) // t+10
// Bob deposits 20 LPs at t+14
await advanceTimeAndBlock(3) // t+13
await this.chef.connect(this.bob).deposit(0, "20") // t+14
// Carol deposits 30 LPs at block t+18
await advanceTimeAndBlock(3) // t+17
await this.chef.connect(this.carol).deposit(0, "30", { from: this.carol.address }) // t+18
// Alice deposits 10 more LPs at t+20. At this point:
// Alice should have:
// - 4*50 + 4*50*1/3 + 2*50*1/6 = 283 (+50) JoeToken
// - 4*40 + 4*40*1/3 + 2*40*1/6 = 226 (+40) PartnerToken
// Dev should have: 10*20 = 200 (+20)
// Treasury should have: 10*20 = 200 (+20)
// Investor should have: 10*10 = 100 (+10)
// MasterChef should have: 1000 - 283 - 200 - 200 - 100 = 217 (+100)
await advanceTimeAndBlock(1) // t+19
await this.chef.connect(this.alice).deposit(0, "10", { from: this.alice.address }) // t+20,
expect(await this.joe.totalSupply()).to.be.within(1000, 1100)
// Because LP rewards are divided among participants and rounded down, we account
// for rounding errors with an offset
expect(await this.joe.balanceOf(this.alice.address)).to.be.within(283 - this.tokenOffset, 333 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.alice.address)).to.be.within(226 - this.tokenOffset, 266 + this.tokenOffset)
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal("0")
expect(await this.joe.balanceOf(this.carol.address)).to.equal("0")
expect(await this.partnerToken.balanceOf(this.carol.address)).to.equal("0")
expect(await this.joe.balanceOf(this.dev.address)).to.be.within(200 - this.tokenOffset, 220 + this.tokenOffset)
expect(await this.joe.balanceOf(this.treasury.address)).to.be.within(200 - this.tokenOffset, 220 + this.tokenOffset)
expect(await this.joe.balanceOf(this.investor.address)).to.be.within(100 - this.tokenOffset, 110 + this.tokenOffset)
expect(await this.joe.balanceOf(this.chef.address)).to.be.within(217 - this.tokenOffset, 317 + this.tokenOffset)
// Bob withdraws 5 LPs at t+30. At this point:
// Bob should have:
// - 4*50*2/3 + 2*50*2/6 + 10*50*2/7 = 309 (+50) JoeToken
// - 4*40*2/3 + 2*40*2/6 + 10*40*2/7 = 247 (+40) PartnerToken
// Dev should have: 20*20 = 400 (+20)
// Treasury should have: 20*20 = 400 (+20)
// Investor should have: 20*10 = 200 (+10)
// MasterChef should have: 217 + 1000 - 309 - 200 - 200 - 100 = 408 (+100)
await advanceTimeAndBlock(9) // t+29
await this.chef.connect(this.bob).withdraw(0, "5", { from: this.bob.address }) // t+30
expect(await this.joe.totalSupply()).to.be.within(2000, 2100)
// Because of rounding errors, we use token offsets
expect(await this.joe.balanceOf(this.alice.address)).to.be.within(283 - this.tokenOffset, 333 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.alice.address)).to.be.within(226 - this.tokenOffset, 266 + this.tokenOffset)
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(309 - this.tokenOffset, 359 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(247 - this.tokenOffset, 287 + this.tokenOffset)
expect(await this.joe.balanceOf(this.carol.address)).to.equal("0")
expect(await this.partnerToken.balanceOf(this.carol.address)).to.equal("0")
expect(await this.joe.balanceOf(this.dev.address)).to.be.within(400 - this.tokenOffset, 420 + this.tokenOffset)
expect(await this.joe.balanceOf(this.treasury.address)).to.be.within(400 - this.tokenOffset, 420 + this.tokenOffset)
expect(await this.joe.balanceOf(this.investor.address)).to.be.within(200 - this.tokenOffset, 210 + this.tokenOffset)
expect(await this.joe.balanceOf(this.chef.address)).to.be.within(408 - this.tokenOffset, 508 + this.tokenOffset)
// Alice withdraws 20 LPs at t+40
// Bob withdraws 15 LPs at t+50
// Carol withdraws 30 LPs at t+60
await advanceTimeAndBlock(9) // t+39
await this.chef.connect(this.alice).withdraw(0, "20", { from: this.alice.address }) // t+40
await advanceTimeAndBlock(9) // t+49
await this.chef.connect(this.bob).withdraw(0, "15", { from: this.bob.address }) // t+50
await advanceTimeAndBlock(9) // t+59
await this.chef.connect(this.carol).withdraw(0, "30", { from: this.carol.address }) // t+60
expect(await this.joe.totalSupply()).to.be.within(5000, 5100)
// Alice should have:
// - 283 + 10*50*2/7 + 10*50*20/65 = 579 (+50) JoeToken
// - 226 + 10*40*2/7 + 10*40*20/65 = 463 (+40) PartnerToken
expect(await this.joe.balanceOf(this.alice.address)).to.be.within(579 - this.tokenOffset, 629 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.alice.address)).to.be.within(463 - this.tokenOffset, 503 + this.tokenOffset)
// Bob should have:
// - 309 + 10*50*15/65 + 10*50*15/45 = 591 (+50) JoeToken
// - 247 + 10*40*15/65 + 10*40*15/45 = 472 (+40) PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(591 - this.tokenOffset, 641 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(472 - this.tokenOffset, 512 + this.tokenOffset)
// Carol should have:
// - 2*50*3/6 + 10*50*3/7 + 10*50*30/65 + 10*50*30/45 + 10*50 = 1328 (+50) JoeToken
// - 2*40*1/2 + 10*40*3/7 + 10*40*30/65 + 10*40*30/45 + 10*40 = 1062 (+40) PartnerToken
expect(await this.joe.balanceOf(this.carol.address)).to.be.within(1328 - this.tokenOffset, 1378 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.carol.address)).to.be.within(1062 - this.tokenOffset, 1102 + this.tokenOffset)
// Dev should have: 50*20 = 1000 (+20)
// Treasury should have: 50*20 = 1000 (+20)
// Investor should have: 50*10 = 500 (+10)
expect(await this.joe.balanceOf(this.dev.address)).to.be.within(1000 - this.tokenOffset, 1020 + this.tokenOffset)
expect(await this.joe.balanceOf(this.treasury.address)).to.be.within(1000 - this.tokenOffset, 1020 + this.tokenOffset)
expect(await this.joe.balanceOf(this.investor.address)).to.be.within(500 - this.tokenOffset, 510 + this.tokenOffset)
// MasterChefJoe should have nothing
expect(await this.joe.balanceOf(this.chef.address)).to.be.within(0, 0 + this.tokenOffset)
// // All of them should have 1000 LPs back.
expect(await this.lp.balanceOf(this.alice.address)).to.equal("1000")
expect(await this.lp.balanceOf(this.bob.address)).to.equal("1000")
expect(await this.lp.balanceOf(this.carol.address)).to.equal("1000")
})
it("should give proper JOEs allocation to each pool", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59
this.rewarder = await this.SimpleRewarderPerSec.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerSec,
this.chef.address,
false
)
await this.rewarder.deployed() // t-58
await this.partnerToken.mint(this.rewarder.address, "1000000000000000000000000") // t-57
await this.joe.transferOwnership(this.chef.address) // t-56
await this.lp.connect(this.alice).approve(this.chef.address, "1000", { from: this.alice.address }) // t-55
await this.lp2.connect(this.bob).approve(this.chef.address, "1000", { from: this.bob.address }) // t-54
// Add first LP to the pool with allocation 10
await this.chef.add("10", this.lp.address, this.rewarder.address) // t-53
// Alice deposits 10 LPs at t+10
await advanceTimeAndBlock(62) // t+9
await this.chef.connect(this.alice).deposit(0, "10", { from: this.alice.address }) // t+10
// Add LP2 to the pool with allocation 20 at t+20
await advanceTimeAndBlock(9) // t+19
await this.chef.add("20", this.lp2.address, ADDRESS_ZERO) // t+20
// Alice's pending reward should be:
// - 10*50 = 500 (+50) JoeToken
// - 10*40 = 400 (+40) PartnerToken
expect((await this.chef.pendingTokens(0, this.alice.address)).pendingJoe).to.be.within(500 - this.tokenOffset, 550 + this.tokenOffset)
expect(await this.rewarder.pendingTokens(this.alice.address)).to.be.within(400, 440)
// Bob deposits 10 LP2s at t+25
await advanceTimeAndBlock(4) // t+24
await this.chef.connect(this.bob).deposit(1, "10", { from: this.bob.address }) // t+25
// Alice's pending reward should be:
// - 500 + 5*1/3*50 = 583 (+50) JoeToken
// - 400 + 5*40 = 600 (+40) PartnerToken
expect((await this.chef.pendingTokens(0, this.alice.address)).pendingJoe).to.be.within(583 - this.tokenOffset, 633 + this.tokenOffset)
expect(await this.rewarder.pendingTokens(this.alice.address)).to.be.within(600, 640)
// At this point:
// Alice's pending reward should be:
// - 583 + 5*1/3*50 = 666 (+50) JoeToken
// - 600 + 5*40 = 800 (+40) PartnerToken
// Bob's pending reward should be:
// - 5*2/3*50 = 166 (+50) JoeToken
// - 0 PartnerToken
await advanceTimeAndBlock(5) // t+30
expect((await this.chef.pendingTokens(0, this.alice.address)).pendingJoe).to.be.within(666 - this.tokenOffset, 716 + this.tokenOffset)
expect(await this.rewarder.pendingTokens(this.alice.address)).to.be.within(800, 840)
expect((await this.chef.pendingTokens(1, this.bob.address)).pendingJoe).to.be.within(166 - this.tokenOffset, 216 + this.tokenOffset)
expect(await this.rewarder.pendingTokens(this.bob.address)).to.equal(0)
// Alice and Bob should not have pending rewards in pools they're not staked in
expect((await this.chef.pendingTokens(1, this.alice.address)).pendingJoe).to.equal("0")
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingJoe).to.equal("0")
// Make sure they have receive the same amount as what was pending
await this.chef.connect(this.alice).withdraw(0, "10", { from: this.alice.address }) // t+31
// Alice should have:
// - 666 + 1*1/3*50 = 682 (+50) JoeToken
// - 800 + 1*40 = 840 (+40) PartnerToken
expect(await this.joe.balanceOf(this.alice.address)).to.be.within(682 - this.tokenOffset, 732 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.alice.address)).to.be.within(840, 880)
await this.chef.connect(this.bob).withdraw(1, "5", { from: this.bob.address }) // t+32
// Bob should have:
// - 166 + 2*2/3*50 = 232 (+50) JoeToken
// - 0 PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(232 - this.tokenOffset, 282 + this.tokenOffset)
expect(await this.rewarder.pendingTokens(this.bob.address)).to.equal(0)
})
it("should give proper JOEs after updating emission rate", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59
this.rewarder = await this.SimpleRewarderPerSec.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerSec,
this.chef.address,
false
)
await this.rewarder.deployed() // t-58
await this.partnerToken.mint(this.rewarder.address, "1000000000000000000000000") // t-57
await this.joe.transferOwnership(this.chef.address) // t-56
await this.lp.connect(this.alice).approve(this.chef.address, "1000", { from: this.alice.address }) // t-55
await this.chef.add("10", this.lp.address, this.rewarder.address) // t-54
// Alice deposits 10 LPs at t+10
await advanceTimeAndBlock(63) // t+9
await this.chef.connect(this.alice).deposit(0, "10", { from: this.alice.address }) // t+10
// At t+110, Alice should have:
// - 100*100*0.5 = 5000 (+50) JoeToken
// - 100*40 = 4000 (+40) PartnerToken
await advanceTimeAndBlock(100) // t+110
expect((await this.chef.pendingTokens(0, this.alice.address)).pendingJoe).to.be.within(5000, 5050)
expect(await this.rewarder.pendingTokens(this.alice.address)).to.be.within(4000, 4040)
// Lower JOE emission rate to 40 JOE per sec
await this.chef.updateEmissionRate(40) // t+111
// At t+115, Alice should have:
// - 5000 + 1*100*0.5 + 4*40*0.5 = 5130 (+50) JoeToken
// - 4000 + 5*40 = 4200 (+40) PartnerToken
await advanceTimeAndBlock(4) // t+115
expect((await this.chef.pendingTokens(0, this.alice.address)).pendingJoe).to.be.within(5130, 5180)
expect(await this.rewarder.pendingTokens(this.alice.address)).to.be.within(4200, 4240)
// Increase PartnerToken emission rate to 90 PartnerToken per block
await this.rewarder.setRewardRate(90) // t+116
// At b=35, Alice should have:
// - 5130 + 21*40*0.5 = 5550 (+50) JoeToken
// - 4200 + 1*40 + 20*90 = 6040 (+90) PartnerToken
await advanceTimeAndBlock(20) // t+136
expect((await this.chef.pendingTokens(0, this.alice.address)).pendingJoe).to.be.within(5550, 5600)
expect(await this.rewarder.pendingTokens(this.alice.address)).to.be.within(6040, 6130)
})
})
context("With ERC/LP token added to the field and using MasterChefRewarderPerBlock", function () {
beforeEach(async function () {
this.lp = await this.ERC20Mock.deploy("LPToken", "LP", "10000000000") // b=3
await this.lp.transfer(this.alice.address, "1000") // b=4
await this.lp.transfer(this.bob.address, "1000") // b=5
await this.lp.transfer(this.carol.address, "1000") // b=6
this.lp2 = await this.ERC20Mock.deploy("LPToken2", "LP2", "10000000000") // b=7
await this.lp2.transfer(this.alice.address, "1000") // b=8
await this.lp2.transfer(this.bob.address, "1000") // b=9
await this.lp2.transfer(this.carol.address, "1000") // b=10
this.dummyToken = await this.ERC20Mock.deploy("DummyToken", "DUMMY", "1") // b=11
await this.dummyToken.transfer(this.partnerDev.address, "1") // b=12
this.partnerChef = await this.MCV1PerBlock.deploy(
this.partnerToken.address,
this.partnerDev.address,
this.partnerRewardPerBlock,
this.partnerStartBlock,
this.partnerBonusEndBlock
) // b=13
await this.partnerChef.deployed()
})
it("should check LP token is a contract", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed()
// Use address that is not a contract
await expect(this.chef.add("100", this.dev.address, ADDRESS_ZERO)).to.be.revertedWith("add: LP token must be a valid contract")
})
it("should not allow same LP token to be added twice", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed()
expect(await this.chef.poolLength()).to.equal("0")
await this.chef.add("100", this.lp.address, ADDRESS_ZERO)
expect(await this.chef.poolLength()).to.equal("1")
await expect(this.chef.add("100", this.lp.address, ADDRESS_ZERO)).to.be.revertedWith("add: LP already added")
})
it("should check rewarder's arguments are contracts", async function () {
await expect(
this.MasterChefRewarderPerBlock.deploy(
ADDRESS_ZERO,
this.lp.address,
this.partnerRewardPerBlock,
this.partnerChefAllocPoint,
this.partnerChefPid,
this.partnerChef.address,
this.chef.address
)
).to.be.revertedWith("constructor: reward token must be a valid contract")
await expect(
this.MasterChefRewarderPerBlock.deploy(
this.partnerToken.address,
ADDRESS_ZERO,
this.partnerRewardPerBlock,
this.partnerChefAllocPoint,
this.partnerChefPid,
this.partnerChef.address,
this.chef.address
)
).to.be.revertedWith("constructor: LP token must be a valid contract")
await expect(
this.MasterChefRewarderPerBlock.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerBlock,
this.partnerChefAllocPoint,
this.partnerChefPid,
ADDRESS_ZERO,
this.chef.address
)
).to.be.revertedWith("constructor: MasterChef must be a valid contract")
await expect(
this.MasterChefRewarderPerBlock.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerBlock,
this.partnerChefAllocPoint,
this.partnerChefPid,
this.partnerChef.address,
ADDRESS_ZERO
)
).to.be.revertedWith("constructor: MasterChefJoeV2 must be a valid contract")
})
it("should check rewarder added and set properly", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed()
this.rewarder = await this.MasterChefRewarderPerBlock.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerBlock,
this.partnerChefAllocPoint,
this.partnerChefPid,
this.partnerChef.address,
this.chef.address
)
await this.rewarder.deployed()
// Try to add rewarder that is neither zero address or contract address
await expect(this.chef.add("100", this.lp.address, this.dev.address)).to.be.revertedWith("add: rewarder must be contract or zero")
await this.chef.add("100", this.lp.address, this.rewarder.address)
// Try to set rewarder that is neither zero address or contract address
await expect(this.chef.set("0", "200", this.dev.address, true)).to.be.revertedWith("set: rewarder must be contract or zero")
await this.chef.set("0", "200", this.rewarder.address, false)
expect((await this.chef.poolInfo(0)).allocPoint).to.equal("200")
// Alice has no DummyToken, so it should fail to init
await expect(this.rewarder.connect(this.alice).init(this.dummyToken.address)).to.be.revertedWith("init: Balance must exceed 0")
// Successfully init the rewarder
await this.partnerChef.add(this.partnerChefAllocPoint, this.dummyToken.address, true)
await this.dummyToken.connect(this.partnerDev).approve(this.rewarder.address, "1")
await this.rewarder.connect(this.partnerDev).init(this.dummyToken.address)
expect((await this.partnerChef.poolInfo(this.partnerChefPid)).lpToken).to.equal(this.dummyToken.address)
})
it("should allow a given pool's allocation weight and rewarder to be updated", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed()
this.rewarder = await this.MasterChefRewarderPerBlock.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerBlock,
this.partnerChefAllocPoint,
this.partnerChefPid,
this.partnerChef.address,
this.chef.address
)
await this.rewarder.deployed()
await this.chef.add("100", this.lp.address, ADDRESS_ZERO)
expect((await this.chef.poolInfo(0)).allocPoint).to.equal("100")
expect((await this.chef.poolInfo(0)).rewarder).to.equal(ADDRESS_ZERO)
await this.chef.set("0", "150", this.rewarder.address, true)
expect((await this.chef.poolInfo(0)).allocPoint).to.equal("150")
expect((await this.chef.poolInfo(0)).rewarder).to.equal(this.rewarder.address)
})
it("should only allow MasterChefJoeV2 to call onJoeReward", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59, b=14
this.rewarder = await this.MasterChefRewarderPerBlock.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerBlock,
this.partnerChefAllocPoint,
this.partnerChefPid,
this.partnerChef.address,
this.chef.address
)
await this.rewarder.deployed() // t-58, b=15
await this.partnerToken.transferOwnership(this.partnerChef.address) // t-57, b=16
await this.partnerChef.add(this.partnerChefAllocPoint, this.dummyToken.address, true) // t-56, b=17
await this.dummyToken.connect(this.partnerDev).approve(this.rewarder.address, "1") // t-55, b=18
await this.rewarder.connect(this.partnerDev).init(this.dummyToken.address) // t-54, b=19
await this.joe.transferOwnership(this.chef.address) // t-53, b=20
await this.chef.add("100", this.lp.address, this.rewarder.address) // t-52, b=21
await this.lp.connect(this.bob).approve(this.chef.address, "1000") // t-51, b=22
await this.chef.connect(this.bob).deposit(0, "100") // t-50, b=23
await advanceTimeAndBlock(39) // t-11, b=24
await expect(this.rewarder.onJoeReward(this.bob.address, "100")).to.be.revertedWith("onlyMCV2: only MasterChef V2 can call this function") // t-10, b=25
await this.chef.connect(this.bob).deposit(0, "0") // t-9, b=26
// Bob should have:
// - 0 JoeToken
// - 3*40 = 80 PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal("120")
})
it("should allow rewarder to be set and removed mid farming", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59, b=14
this.rewarder = await this.MasterChefRewarderPerBlock.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerBlock,
this.partnerChefAllocPoint,
this.partnerChefPid,
this.partnerChef.address,
this.chef.address
)
await this.rewarder.deployed() // t-58, b=15
await this.partnerToken.transferOwnership(this.partnerChef.address) // t-57, b=16
await this.partnerChef.add(this.partnerChefAllocPoint, this.dummyToken.address, true) // t-56, b=17
await this.dummyToken.connect(this.partnerDev).approve(this.rewarder.address, "1") // t-55, b=18
await this.rewarder.connect(this.partnerDev).init(this.dummyToken.address) // t-54, b=19
await this.joe.transferOwnership(this.chef.address) // t-53, b=20
await this.chef.add("100", this.lp.address, ADDRESS_ZERO) // t-52, b=21
await this.lp.connect(this.bob).approve(this.chef.address, "1000") // t-51, b=22
await this.chef.connect(this.bob).deposit(0, "100") // t-50, b=23
await advanceTimeAndBlock(39) // t-11, b=24
await this.chef.connect(this.bob).deposit(0, "0") // t-10, b=25
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
// At t+10, Bob should have pending:
// - 10*50 = 500 (+50) JoeToken
// - 0 PartnerToken
await advanceTimeAndBlock(20) // t+10, b=26
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingJoe).to.be.within(500, 550)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenAddress).to.equal(ADDRESS_ZERO)
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingBonusToken).to.equal(0)
// Pass rewarder but don't overwrite
await this.chef.set(0, 100, this.rewarder.address, false) // t+11 ,b=27
// At t+20, Bob should have pending:
// - 500 + 10*50 = 1000 (+50) JoeToken
// - 0 PartnerToken
await advanceTimeAndBlock(9) // t+20, b=28
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingJoe).to.be.within(1000, 1050)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenAddress).to.equal(ADDRESS_ZERO)
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingBonusToken).to.equal(0)
// Pass rewarder and overwrite
await this.chef.set(0, 100, this.rewarder.address, true) // t+21, b=29
// At t+30, Bob should have pending:
// - 1000 + 10*50 = 1500 (+50) JoeToken
// - 0 PartnerToken - this is because rewarder hasn't registered the user yet! User needs to call deposit again
await advanceTimeAndBlock(4) // t+25, b=30
await advanceTimeAndBlock(5) // t+30, b=31
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingJoe).to.be.within(1500, 1550)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenAddress).to.equal(this.partnerToken.address)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenSymbol).to.equal("SUSHI")
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingBonusToken).to.equal(0)
// Call deposit to start receiving PartnerTokens
await this.chef.connect(this.bob).deposit(0, 0) // t+31, b=32
// At t+40, Bob should have pending:
// - 9*50 = 450 (+50) JoeToken
// - 2*40 = 80 PartnerToken
await advanceTimeAndBlock(4) // t+35, b=33
await advanceTimeAndBlock(5) // t+40, b=34
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingJoe).to.be.within(450, 500)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenAddress).to.equal(this.partnerToken.address)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenSymbol).to.equal("SUSHI")
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingBonusToken).to.equal(80)
// Set reward rate to zero
await this.rewarder.setRewardRate(0) // t+41, b=35
// At t+50, Bob should have pending:
// - 450 + 10*50 = 950 (+50) JoeToken
// - 80 + 1*40 = 120 PartnerToken
await advanceTimeAndBlock(4) // t+45, b=36
await advanceTimeAndBlock(5) // t+50, b=37
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingJoe).to.be.within(950, 1000)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenAddress).to.equal(this.partnerToken.address)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenSymbol).to.equal("SUSHI")
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingBonusToken).to.equal(120)
// Claim reward
await this.chef.connect(this.bob).deposit(0, 0) // t+51, b=38
// Bob should have:
// - 1500 + 1*50 + 950 + 1*50 = 2550 (+50) JoeToken
// - 120 PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(2550, 2600)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal(120)
})
it("should allow allocation point to be set mid farming", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59, b=14
this.rewarder = await this.MasterChefRewarderPerBlock.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerBlock,
this.partnerChefAllocPoint,
this.partnerChefPid,
this.partnerChef.address,
this.chef.address
)
await this.rewarder.deployed() // t-58, b=15
await this.partnerToken.transferOwnership(this.partnerChef.address) // t-57, b=16
await this.partnerChef.add(this.partnerChefAllocPoint, this.dummyToken.address, true) // t-56, b=17
await this.partnerChef.add("200", this.lp2.address, true) // t-55, b=18
await this.dummyToken.connect(this.partnerDev).approve(this.rewarder.address, "1") // t-54, b=19
await this.rewarder.connect(this.partnerDev).init(this.dummyToken.address) // t-53, b=20
await this.joe.transferOwnership(this.chef.address) // t-52, b=21
await this.chef.add("100", this.lp.address, this.rewarder.address) // t-51, b=22
await this.lp.connect(this.bob).approve(this.chef.address, "1000") // t-50, b=23
await this.chef.connect(this.bob).deposit(0, "100") // t-49, b=24
await advanceTimeAndBlock(38) // t-11, b=25
await this.chef.connect(this.bob).deposit(0, "0") // t-10, b=26
// Bob should have:
// - 0 JoeToken
// - 2*40*1/3 = 26 PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(26 - this.tokenOffset, 26 + this.tokenOffset)
await advanceTimeAndBlock(8) // t-2, b=27
await this.chef.connect(this.bob).deposit(0, "0") // t-1, b=28
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
await advanceTimeAndBlock(10) // t+9, b=29
await this.chef.connect(this.bob).deposit(0, "0") // t+10, b=30
// Bob should have:
// - 10*50 = 500 (+50) JoeToken
// - 26 + 4*40*1/3 = 79 PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(500, 550)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(79 - this.tokenOffset, 79 + this.tokenOffset)
// Increase pool 1's alloc point
// For a brief amount of time, the rewarder is emitting 40/4 = 10 tokens per block because the total allocPoint
// has increased to 400, but the pool alloc point on the rewarder has not been increased yet.
await this.partnerChef.set(0, "200", true) // t+11, b=31
await this.rewarder.updatePool() // t+12, b=32
await this.rewarder.setAllocPoint(200) // t+13, b=33
await advanceTimeAndBlock(2) // t+15, b=34
await advanceTimeAndBlock(5) // t+20, b=35
await advanceTimeAndBlock(9) // t+29, b=36
await this.chef.connect(this.bob).deposit(0, 0) // t+30, b=37
// Bob should have:
// - 500 + 20*50 = 1500 (+50) JoeToken
// - 79 + 3*40*1/4 + 4*40*1/2 = 189 PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(1500, 1550)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(189 - this.tokenOffset, 189 + this.tokenOffset)
})
it("should give out JOEs only after farming time", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59, b=14
this.rewarder = await this.MasterChefRewarderPerBlock.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerBlock,
this.partnerChefAllocPoint,
this.partnerChefPid,
this.partnerChef.address,
this.chef.address
)
await this.rewarder.deployed() // t-58, b=15
await this.partnerToken.transferOwnership(this.partnerChef.address) // t-57, b=16
await this.partnerChef.add(this.partnerChefAllocPoint, this.dummyToken.address, true) // t-56, b=17
await this.dummyToken.connect(this.partnerDev).approve(this.rewarder.address, "1") // t-55, b=18
await this.rewarder.connect(this.partnerDev).init(this.dummyToken.address) // t-54, b=19
await this.joe.transferOwnership(this.chef.address) // t-53, b=20
await this.chef.add("100", this.lp.address, this.rewarder.address) // t-52, b=21
await this.lp.connect(this.bob).approve(this.chef.address, "1000") // t-51, b=22
await this.chef.connect(this.bob).deposit(0, "100") // t-50, b=23
await advanceTimeAndBlock(39) // t-11, b=24
await this.chef.connect(this.bob).deposit(0, "0") // t-10, b=25
// Bob should have:
// - 0 JoeToken
// - 2*40 = 80 PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal("80")
await advanceTimeAndBlock(8) // t-2, b=26
await this.chef.connect(this.bob).deposit(0, "0") // t-1, b=27
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
await advanceTimeAndBlock(10) // t+9, b=28
await this.chef.connect(this.bob).deposit(0, "0") // t+10, b=29
// Bob should have:
// - 10*50 = 500 (+50) JoeToken
// - 80 + 4*40 = 240 PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(500, 550)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal("240")
await advanceTimeAndBlock(4) // t+14, b=30
await this.chef.connect(this.bob).deposit(0, "0") // t+15, b=31
// At this point:
// Bob should have:
// - 500 + 5*50 = 750 (+50) JoeToken
// - 240 + 2*40 = 320 PartnerToken
// Dev should have: 15*20 = 300 (+20)
// Treasury should have: 15*20 = 300 (+20)
// Investor should have: 15*10 = 150 (+10)
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(750, 800)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal("320")
expect(await this.joe.balanceOf(this.dev.address)).to.be.within(300, 320)
expect(await this.joe.balanceOf(this.treasury.address)).to.be.within(300, 320)
expect(await this.joe.balanceOf(this.investor.address)).to.be.within(150, 160)
expect(await this.joe.totalSupply()).to.be.within(1500, 1600)
})
it("should not distribute JOEs if no one deposit", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59, b=14
this.rewarder = await this.MasterChefRewarderPerBlock.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerBlock,
this.partnerChefAllocPoint,
this.partnerChefPid,
this.partnerChef.address,
this.chef.address
)
await this.rewarder.deployed() // t-58, b=15
await this.partnerToken.transferOwnership(this.partnerChef.address) // t-57, b=16
await this.partnerChef.add(this.partnerChefAllocPoint, this.dummyToken.address, true) // t-56, b=17
await this.dummyToken.connect(this.partnerDev).approve(this.rewarder.address, "1") // t-55, b=18
await this.rewarder.connect(this.partnerDev).init(this.dummyToken.address) // t-54, b=19
await this.joe.transferOwnership(this.chef.address) // t-53, b=20
await this.chef.add("100", this.lp.address, this.rewarder.address) // t-52, b=21
await this.lp.connect(this.bob).approve(this.chef.address, "1000") // t-51, b=22
await advanceTimeAndBlock(105) // t+54, b=23
expect(await this.joe.totalSupply()).to.equal("0")
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal("0")
await advanceTimeAndBlock(5) // t+59, b=24
expect(await this.joe.totalSupply()).to.equal("0")
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal("0")
await advanceTimeAndBlock(5) // t+64, b=25
await this.chef.connect(this.bob).deposit(0, "10") // t+65, b=26
expect(await this.joe.totalSupply()).to.equal("0")
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal("0")
expect(await this.joe.balanceOf(this.dev.address)).to.equal("0")
expect(await this.lp.balanceOf(this.bob.address)).to.equal("990")
await advanceTimeAndBlock(10) // t+75, b=27
// Revert if Bob withdraws more than he deposited
await expect(this.chef.connect(this.bob).withdraw(0, "11")).to.be.revertedWith("withdraw: not good") // t+76, b=28
await this.chef.connect(this.bob).withdraw(0, "10") // t+77, b=29
// At this point:
// Bob should have:
// - 12*50 = 600 (+50) JoeToken
// - 3*40 = 120 PartnerToken
// Dev should have:
// - 12*20 = 240 (+20) JoeToken
// Treasury should have:
// - 12*20 = 240 (+20) JoeToken
// Investor should have:
// - 12*10 = 120 (+10) JoeToken
expect(await this.joe.totalSupply()).to.be.within(1200, 1300)
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(600, 650)
expect(await this.joe.balanceOf(this.dev.address)).to.be.within(240, 260)
expect(await this.joe.balanceOf(this.treasury.address)).to.be.within(240, 260)
expect(await this.joe.balanceOf(this.investor.address)).to.be.within(120, 130)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal(120)
})
it("should distribute JOEs properly for each staker", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59, b=14
this.rewarder = await this.MasterChefRewarderPerBlock.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerBlock,
this.partnerChefAllocPoint,
this.partnerChefPid,
this.partnerChef.address,
this.chef.address
)
await this.rewarder.deployed() // t-58, b=15
await this.partnerToken.transferOwnership(this.partnerChef.address) // t-57, b=16
await this.partnerChef.add(this.partnerChefAllocPoint, this.dummyToken.address, true) // t-56, b=17
await this.dummyToken.connect(this.partnerDev).approve(this.rewarder.address, "1") // t-55, b=18
await this.rewarder.connect(this.partnerDev).init(this.dummyToken.address) // t-54, b=19
await this.joe.transferOwnership(this.chef.address) // t-53, b=20
await this.chef.add("100", this.lp.address, this.rewarder.address) // t-52, b=21
await this.lp.connect(this.alice).approve(this.chef.address, "1000", {
from: this.alice.address,
}) // t-51, b=22
await this.lp.connect(this.bob).approve(this.chef.address, "1000", {
from: this.bob.address,
}) // t-50, b=23
await this.lp.connect(this.carol).approve(this.chef.address, "1000", {
from: this.carol.address,
}) // t-49, b=24
// Alice deposits 10 LPs at t+10
await advanceTimeAndBlock(58) // t+9, b=25
await this.chef.connect(this.alice).deposit(0, "10", { from: this.alice.address }) // t+10, b=26
// Bob deposits 20 LPs at t+14
await advanceTimeAndBlock(3) // t+13, b=27
await this.chef.connect(this.bob).deposit(0, "20") // t+14, b=28
// Carol deposits 30 LPs at block t+18
await advanceTimeAndBlock(3) // t+17, b=29
await this.chef.connect(this.carol).deposit(0, "30", { from: this.carol.address }) // t+18, b=30
// Alice deposits 10 more LPs at t+20. At this point:
// Alice should have:
// - 4*50 + 4*50*1/3 + 2*50*1/6 = 283 (+50) JoeToken
// - 2*40 + 2*40*1/3 + 2*40*1/6 = 120 PartnerToken
// Dev should have: 10*20 = 200 (+20)
// Treasury should have: 10*20 = 200 (+20)
// Investor should have: 10*10 = 100 (+10)
// MasterChef should have: 1000 - 283 - 200 - 200 - 100 = 217 (+100)
await advanceTimeAndBlock(1) // t+19, b=31
await this.chef.connect(this.alice).deposit(0, "10", { from: this.alice.address }) // t+20, b=32
expect(await this.joe.totalSupply()).to.be.within(1000, 1100)
// Because LP rewards are divided among participants and rounded down, we account
// for rounding errors with an offset
expect(await this.joe.balanceOf(this.alice.address)).to.be.within(283 - this.tokenOffset, 333 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.alice.address)).to.be.within(120 - this.tokenOffset, 120 + this.tokenOffset)
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal("0")
expect(await this.joe.balanceOf(this.carol.address)).to.equal("0")
expect(await this.partnerToken.balanceOf(this.carol.address)).to.equal("0")
expect(await this.joe.balanceOf(this.dev.address)).to.be.within(200 - this.tokenOffset, 220 + this.tokenOffset)
expect(await this.joe.balanceOf(this.treasury.address)).to.be.within(200 - this.tokenOffset, 220 + this.tokenOffset)
expect(await this.joe.balanceOf(this.investor.address)).to.be.within(100 - this.tokenOffset, 110 + this.tokenOffset)
expect(await this.joe.balanceOf(this.chef.address)).to.be.within(217 - this.tokenOffset, 317 + this.tokenOffset)
// Bob withdraws 5 LPs at t+30. At this point:
// Bob should have:
// - 4*50*2/3 + 2*50*2/6 + 10*50*2/7 = 309 (+50) JoeToken
// - 2*40*2/3 + 2*40*2/6 + 2*40*2/7 = 102 PartnerToken
// Dev should have: 20*20= 400 (+20)
// Treasury should have: 20*20 = 400 (+20)
// Investor should have: 20*10 = 200 (+10)
// MasterChef should have: 217 + 1000 - 309 - 200 - 200 - 100 = 408 (+100)
await advanceTimeAndBlock(9) // t+29, b=33
await this.chef.connect(this.bob).withdraw(0, "5", { from: this.bob.address }) // t+30, b=34
expect(await this.joe.totalSupply()).to.be.within(2000, 2100)
// Because of rounding errors, we use token offsets
expect(await this.joe.balanceOf(this.alice.address)).to.be.within(283 - this.tokenOffset, 333 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.alice.address)).to.be.within(119 - this.tokenOffset, 119 + this.tokenOffset)
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(309 - this.tokenOffset, 359 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(101 - this.tokenOffset, 101 + this.tokenOffset)
expect(await this.joe.balanceOf(this.carol.address)).to.equal("0")
expect(await this.partnerToken.balanceOf(this.carol.address)).to.equal("0")
expect(await this.joe.balanceOf(this.dev.address)).to.be.within(400 - this.tokenOffset, 420 + this.tokenOffset)
expect(await this.joe.balanceOf(this.treasury.address)).to.be.within(400 - this.tokenOffset, 420 + this.tokenOffset)
expect(await this.joe.balanceOf(this.investor.address)).to.be.within(200 - this.tokenOffset, 210 + this.tokenOffset)
expect(await this.joe.balanceOf(this.chef.address)).to.be.within(408 - this.tokenOffset, 508 + this.tokenOffset)
// Alice withdraws 20 LPs at t+40
// Bob withdraws 15 LPs at t+50
// Carol withdraws 30 LPs at t+60
await advanceTimeAndBlock(9) // t+39, b=35
await this.chef.connect(this.alice).withdraw(0, "20", { from: this.alice.address }) // t+40, b=36
await advanceTimeAndBlock(9) // t+49, b=37
await this.chef.connect(this.bob).withdraw(0, "15", { from: this.bob.address }) // t+50, b=38
await advanceTimeAndBlock(9) // t+59, b=39
await this.chef.connect(this.carol).withdraw(0, "30", { from: this.carol.address }) // t+60, b=40
expect(await this.joe.totalSupply()).to.be.within(5000, 5100)
// Alice should have:
// - 283 + 10*50*2/7 + 10*50*20/65 = 579 (+50) JoeToken
// - 120 + 2*40*2/7 + 2*40*20/65 = 167 PartnerToken
expect(await this.joe.balanceOf(this.alice.address)).to.be.within(579 - this.tokenOffset, 629 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.alice.address)).to.be.within(167 - this.tokenOffset, 167 + this.tokenOffset)
// Bob should have:
// - 309 + 10*50*15/65 + 10*50*15/45 = 591 (+50) JoeToken
// - 102 + 2*40*15/65 + 2*40*15/45 = 147 PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(591 - this.tokenOffset, 641 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(147 - this.tokenOffset, 147 + this.tokenOffset)
// Carol should have:
// - 2*50*3/6 + 10*50*3/7 + 10*50*30/65 + 10*50*30/45 + 10*50 = 1328 (+50) JoeToken
// - 2*40*1/2 + 2*40*3/7 + 2*40*30/65 + 2*40*30/45 + 2*40 = 244 PartnerToken
expect(await this.joe.balanceOf(this.carol.address)).to.be.within(1328 - this.tokenOffset, 1378 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.carol.address)).to.be.within(244 - this.tokenOffset, 244 + this.tokenOffset)
// Dev should have: 50*20 = 1000 (+20)
// Treasury should have: 50*20 = 1000 (+20)
// Investor should have: 50*10 = 500 (+10)
expect(await this.joe.balanceOf(this.dev.address)).to.be.within(1000 - this.tokenOffset, 1020 + this.tokenOffset)
expect(await this.joe.balanceOf(this.treasury.address)).to.be.within(1000 - this.tokenOffset, 1020 + this.tokenOffset)
expect(await this.joe.balanceOf(this.investor.address)).to.be.within(500 - this.tokenOffset, 510 + this.tokenOffset)
// MasterChefJoe and PartnerChef should have nothing
expect(await this.joe.balanceOf(this.chef.address)).to.be.within(0, 0 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.partnerChef.address)).to.be.within(0, 0 + this.tokenOffset)
// // All of them should have 1000 LPs back.
expect(await this.lp.balanceOf(this.alice.address)).to.equal("1000")
expect(await this.lp.balanceOf(this.bob.address)).to.equal("1000")
expect(await this.lp.balanceOf(this.carol.address)).to.equal("1000")
})
it("should give proper JOEs allocation to each pool", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59
this.rewarder = await this.MasterChefRewarderPerBlock.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerBlock,
this.partnerChefAllocPoint,
this.partnerChefPid,
this.partnerChef.address,
this.chef.address
)
await this.rewarder.deployed() // t-58, b=15
await this.partnerToken.transferOwnership(this.partnerChef.address) // t-57, b=16
await this.partnerChef.add(this.partnerChefAllocPoint, this.dummyToken.address, true) // t-56, b=17
await this.dummyToken.connect(this.partnerDev).approve(this.rewarder.address, "1") // t-55, b=18
await this.rewarder.connect(this.partnerDev).init(this.dummyToken.address) // t-54, b=19
await this.joe.transferOwnership(this.chef.address) // t-53, b=20
await this.lp.connect(this.alice).approve(this.chef.address, "1000", { from: this.alice.address }) // t-52, b=21
await this.lp2.connect(this.bob).approve(this.chef.address, "1000", { from: this.bob.address }) // t-51, b=22
// Add first LP to the pool with allocation 10
await this.chef.add("10", this.lp.address, this.rewarder.address) // t-50, b=23
// Alice deposits 10 LPs at t+10
await advanceTimeAndBlock(59) // t+9, b=24
await this.chef.connect(this.alice).deposit(0, "10", { from: this.alice.address }) // t+10, b=25
// Add LP2 to the pool with allocation 20 at t+20
await advanceTimeAndBlock(9) // t+19, b=26
await this.chef.add("20", this.lp2.address, ADDRESS_ZERO) // t+20, b=27
// Alice's pending reward should be:
// - 10*50 = 500 (+50) JoeToken
// - 2*40 = 80 PartnerToken
expect((await this.chef.pendingTokens(0, this.alice.address)).pendingJoe).to.be.within(500 - this.tokenOffset, 550 + this.tokenOffset)
expect(await this.rewarder.pendingTokens(this.alice.address)).to.equal(80)
// Bob deposits 10 LP2s at t+25
await advanceTimeAndBlock(4) // t+24, b=28
await this.chef.connect(this.bob).deposit(1, "10", { from: this.bob.address }) // t+25, b=29
// Alice's pending reward should be:
// - 500 + 5*1/3*50 = 583 (+50) JoeToken
// - 80 + 2*40 = 160 PartnerToken
expect((await this.chef.pendingTokens(0, this.alice.address)).pendingJoe).to.be.within(583 - this.tokenOffset, 633 + this.tokenOffset)
expect(await this.rewarder.pendingTokens(this.alice.address)).to.equal(160)
// At this point:
// Alice's pending reward should be:
// - 583 + 5*1/3*50 = 666 (+50) JoeToken
// - 160 + 1*40 = 200 PartnerToken
// Bob's pending reward should be:
// - 5*2/3*50 = 166 (+50) JoeToken
// - 0 PartnerToken
await advanceTimeAndBlock(5) // t+30, b=30
expect((await this.chef.pendingTokens(0, this.alice.address)).pendingJoe).to.be.within(666 - this.tokenOffset, 716 + this.tokenOffset)
expect(await this.rewarder.pendingTokens(this.alice.address)).to.equal(200)
expect((await this.chef.pendingTokens(1, this.bob.address)).pendingJoe).to.be.within(166 - this.tokenOffset, 216 + this.tokenOffset)
expect(await this.rewarder.pendingTokens(this.bob.address)).to.equal(0)
// Alice and Bob should not have pending rewards in pools they're not staked in
expect((await this.chef.pendingTokens(1, this.alice.address)).pendingJoe).to.equal("0")
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingJoe).to.equal("0")
// Make sure they have receive the same amount as what was pending
await this.chef.connect(this.alice).withdraw(0, "10", { from: this.alice.address }) // t+31, b=31
// Alice should have:
// - 666 + 1*1/3*50 = 682 (+50) JoeToken
// - 200 + 1*40 = 240 PartnerToken
expect(await this.joe.balanceOf(this.alice.address)).to.be.within(682 - this.tokenOffset, 732 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.alice.address)).to.equal(240)
await this.chef.connect(this.bob).withdraw(1, "5", { from: this.bob.address }) // t+32, b=32
// Bob should have:
// - 166 + 2*2/3*50 = 232 (+50) JoeToken
// - 0 PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(232 - this.tokenOffset, 282 + this.tokenOffset)
expect(await this.rewarder.pendingTokens(this.bob.address)).to.equal(0)
})
it("should give proper JOEs after updating emission rate", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59
this.rewarder = await this.MasterChefRewarderPerBlock.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerBlock,
this.partnerChefAllocPoint,
this.partnerChefPid,
this.partnerChef.address,
this.chef.address
)
await this.rewarder.deployed() // t-58, b=15
await this.partnerToken.transferOwnership(this.partnerChef.address) // t-57, b=16
await this.partnerChef.add(this.partnerChefAllocPoint, this.dummyToken.address, true) // t-56, b=17
await this.dummyToken.connect(this.partnerDev).approve(this.rewarder.address, "1") // t-55, b=18
await this.rewarder.connect(this.partnerDev).init(this.dummyToken.address) // t-54, b=19
await this.joe.transferOwnership(this.chef.address) // t-53, b=20
await this.lp.connect(this.alice).approve(this.chef.address, "1000", { from: this.alice.address }) // t-52, b=21
await this.chef.add("10", this.lp.address, this.rewarder.address) // t-51, b=22
// Alice deposits 10 LPs at t+10
await advanceTimeAndBlock(60) // t+9, b=23
await this.chef.connect(this.alice).deposit(0, "10", { from: this.alice.address }) // t+10, b=24
// At t+110, Alice should have:
// - 100*100*0.5 = 5000 (+50) JoeToken
// - 1*40 = 40 PartnerToken
await advanceTimeAndBlock(100) // t+110, b=25
expect((await this.chef.pendingTokens(0, this.alice.address)).pendingJoe).to.be.within(5000, 5050)
expect(await this.rewarder.pendingTokens(this.alice.address)).to.equal(40)
// Lower JOE emission rate to 40 JOE per sec
await this.chef.updateEmissionRate(40) // t+111, b=26
// At t+115, Alice should have:
// - 5000 + 1*100*0.5 + 4*40*0.5 = 5130 (+50) JoeToken
// - 40 + 2*40 = 120 PartnerToken
await advanceTimeAndBlock(4) // t+115, b=27
expect((await this.chef.pendingTokens(0, this.alice.address)).pendingJoe).to.be.within(5130, 5180)
expect(await this.rewarder.pendingTokens(this.alice.address)).to.equal(120)
// Increase PartnerToken emission rate to 90 PartnerToken per block
await this.rewarder.setRewardRate(90) // t+116, b=28
// At b=35, Alice should have:
// - 5130 + 1*40*0.5 + 20*40*0.5 = 5550 (+50) JoeToken
// - 120 + 1*40 + 5*90 = 610 PartnerToken
await advanceTimeAndBlock(2) // t+118, b=29
await advanceTimeAndBlock(3) // t+121, b=30
await advanceTimeAndBlock(4) // t+125, b=31
await advanceTimeAndBlock(5) // t+130, b=32
await advanceTimeAndBlock(6) // t+136, b=33
expect((await this.chef.pendingTokens(0, this.alice.address)).pendingJoe).to.be.within(5550, 5600)
expect(await this.rewarder.pendingTokens(this.alice.address)).to.equal(610)
})
})
context("With ERC/LP token added to the field and using MasterChefRewarderPerSec", function () {
beforeEach(async function () {
this.lp = await this.ERC20Mock.deploy("LPToken", "LP", "10000000000")
await this.lp.transfer(this.alice.address, "1000")
await this.lp.transfer(this.bob.address, "1000")
await this.lp.transfer(this.carol.address, "1000")
this.lp2 = await this.ERC20Mock.deploy("LPToken2", "LP2", "10000000000")
await this.lp2.transfer(this.alice.address, "1000")
await this.lp2.transfer(this.bob.address, "1000")
await this.lp2.transfer(this.carol.address, "1000")
this.dummyToken = await this.ERC20Mock.deploy("DummyToken", "DUMMY", "1")
await this.dummyToken.transfer(this.partnerDev.address, "1")
this.partnerChef = await this.MCV1PerSec.deploy(
this.partnerToken.address,
this.partnerDev.address,
this.partnerRewardPerSec,
this.partnerStartBlock,
this.partnerBonusEndBlock
)
await this.partnerChef.deployed()
})
it("should check rewarder's arguments are contracts", async function () {
await expect(
this.MasterChefRewarderPerSec.deploy(
ADDRESS_ZERO,
this.lp.address,
this.partnerRewardPerSec,
this.partnerChefAllocPoint,
this.partnerChefPid,
this.partnerChef.address,
this.chef.address
)
).to.be.revertedWith("constructor: reward token must be a valid contract")
await expect(
this.MasterChefRewarderPerSec.deploy(
this.partnerToken.address,
ADDRESS_ZERO,
this.partnerRewardPerSec,
this.partnerChefAllocPoint,
this.partnerChefPid,
this.partnerChef.address,
this.chef.address
)
).to.be.revertedWith("constructor: LP token must be a valid contract")
await expect(
this.MasterChefRewarderPerSec.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerSec,
this.partnerChefAllocPoint,
this.partnerChefPid,
ADDRESS_ZERO,
this.chef.address
)
).to.be.revertedWith("constructor: MasterChef must be a valid contract")
await expect(
this.MasterChefRewarderPerSec.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerSec,
this.partnerChefAllocPoint,
this.partnerChefPid,
this.partnerChef.address,
ADDRESS_ZERO
)
).to.be.revertedWith("constructor: MasterChefJoeV2 must be a valid contract")
})
it("should check rewarder added and set properly", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed()
this.rewarder = await this.MasterChefRewarderPerSec.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerSec,
this.partnerChefAllocPoint,
this.partnerChefPid,
this.partnerChef.address,
this.chef.address
)
await this.rewarder.deployed()
// Try to add rewarder that is neither zero address or contract address
await expect(this.chef.add("100", this.lp.address, this.dev.address)).to.be.revertedWith("add: rewarder must be contract or zero")
await this.chef.add("100", this.lp.address, this.rewarder.address)
// Try to set rewarder that is neither zero address or contract address
await expect(this.chef.set("0", "200", this.dev.address, true)).to.be.revertedWith("set: rewarder must be contract or zero")
await this.chef.set("0", "200", this.rewarder.address, false)
expect((await this.chef.poolInfo(0)).allocPoint).to.equal("200")
// Alice has no DummyToken, so it should fail to init
await expect(this.rewarder.connect(this.alice).init(this.dummyToken.address)).to.be.revertedWith("init: Balance must exceed 0")
// Successfully init the rewarder
await this.partnerChef.add(this.partnerChefAllocPoint, this.dummyToken.address, true)
await this.dummyToken.connect(this.partnerDev).approve(this.rewarder.address, "1")
await this.rewarder.connect(this.partnerDev).init(this.dummyToken.address)
expect((await this.partnerChef.poolInfo(this.partnerChefPid)).lpToken).to.equal(this.dummyToken.address)
})
it("should allow a given pool's allocation weight and rewarder to be updated", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed()
this.rewarder = await this.MasterChefRewarderPerSec.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerSec,
this.partnerChefAllocPoint,
this.partnerChefPid,
this.partnerChef.address,
this.chef.address
)
await this.rewarder.deployed()
await this.chef.add("100", this.lp.address, ADDRESS_ZERO)
expect((await this.chef.poolInfo(0)).allocPoint).to.equal("100")
expect((await this.chef.poolInfo(0)).rewarder).to.equal(ADDRESS_ZERO)
await this.chef.set("0", "150", this.rewarder.address, true)
expect((await this.chef.poolInfo(0)).allocPoint).to.equal("150")
expect((await this.chef.poolInfo(0)).rewarder).to.equal(this.rewarder.address)
})
it("should only allow MasterChefJoeV2 to call onJoeReward", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59
this.rewarder = await this.MasterChefRewarderPerSec.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerSec,
this.partnerChefAllocPoint,
this.partnerChefPid,
this.partnerChef.address,
this.chef.address
)
await this.rewarder.deployed() // t-58
await this.partnerToken.transferOwnership(this.partnerChef.address) // t-57
await this.partnerChef.add(this.partnerChefAllocPoint, this.dummyToken.address, true) // t-56
await this.dummyToken.connect(this.partnerDev).approve(this.rewarder.address, "1") // t-55
await this.rewarder.connect(this.partnerDev).init(this.dummyToken.address) // t-54
await this.joe.transferOwnership(this.chef.address) // t-53
await this.chef.add("100", this.lp.address, this.rewarder.address) // t-52
await this.lp.connect(this.bob).approve(this.chef.address, "1000") // t-51
await this.chef.connect(this.bob).deposit(0, "100") // t-50
await advanceTimeAndBlock(39) // t-11
await expect(this.rewarder.onJoeReward(this.bob.address, "100")).to.be.revertedWith("onlyMCV2: only MasterChef V2 can call this function") // t-10
await this.chef.connect(this.bob).deposit(0, "0") // t-9
// Bob should have:
// - 0 JoeToken
// - 41*40 = 1640 (+40) PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(1640, 1680)
})
it("should allow rewarder to be set and removed mid farming", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59
this.rewarder = await this.MasterChefRewarderPerSec.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerSec,
this.partnerChefAllocPoint,
this.partnerChefPid,
this.partnerChef.address,
this.chef.address
)
await this.rewarder.deployed() // t-58
await this.partnerToken.transferOwnership(this.partnerChef.address) // t-57
await this.partnerChef.add(this.partnerChefAllocPoint, this.dummyToken.address, true) // t-56
await this.dummyToken.connect(this.partnerDev).approve(this.rewarder.address, "1") // t-55
await this.rewarder.connect(this.partnerDev).init(this.dummyToken.address) // t-54
await this.joe.transferOwnership(this.chef.address) // t-53
await this.chef.add("100", this.lp.address, ADDRESS_ZERO) // t-52
await this.lp.connect(this.bob).approve(this.chef.address, "1000") // t-51
await this.chef.connect(this.bob).deposit(0, "100") // t-50
await advanceTimeAndBlock(39) // t-11
await this.chef.connect(this.bob).deposit(0, "0") // t-10
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
// At t+10, Bob should have pending:
// - 10*50 = 500 (+50) JoeToken
// - 0 PartnerToken
await advanceTimeAndBlock(20) // t+10
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingJoe).to.be.within(500, 550)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenAddress).to.equal(ADDRESS_ZERO)
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingBonusToken).to.equal(0)
// Pass rewarder but don't overwrite
await this.chef.set(0, 100, this.rewarder.address, false) // t+11
// At t+20, Bob should have pending:
// - 500 + 10*50 = 1000 (+50) JoeToken
// - 0 PartnerToken
await advanceTimeAndBlock(9) // t+20
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingJoe).to.be.within(1000, 1050)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenAddress).to.equal(ADDRESS_ZERO)
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingBonusToken).to.equal(0)
// Pass rewarder and overwrite
await this.chef.set(0, 100, this.rewarder.address, true) // t+21
// At t+30, Bob should have pending:
// - 1000 + 10*50 = 1500 (+50) JoeToken
// - 0 PartnerToken - this is because rewarder hasn't registered the user yet! User needs to call deposit again
await advanceTimeAndBlock(9) // t+30
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingJoe).to.be.within(1500, 1550)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenAddress).to.equal(this.partnerToken.address)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenSymbol).to.equal("SUSHI")
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingBonusToken).to.equal(0)
// Call deposit to start receiving PartnerTokens
await this.chef.connect(this.bob).deposit(0, 0) // t+31
// At t+40, Bob should have pending:
// - 9*50 = 450 (+50) JoeToken
// - 9*40 = 360 (+40) PartnerToken
await advanceTimeAndBlock(9) // t+40
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingJoe).to.be.within(450, 500)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenAddress).to.equal(this.partnerToken.address)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenSymbol).to.equal("SUSHI")
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingBonusToken).to.be.within(360, 400)
// Set reward rate to zero
await this.rewarder.setRewardRate(0) // t+41
// At t+50, Bob should have pending:
// - 450 + 10*50 = 950 (+50) JoeToken
// - 360 + 1*40 = 400 (+40) PartnerToken
await advanceTimeAndBlock(4) // t+45
await advanceTimeAndBlock(5) // t+50
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingJoe).to.be.within(950, 1000)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenAddress).to.equal(this.partnerToken.address)
expect((await this.chef.pendingTokens(0, this.bob.address)).bonusTokenSymbol).to.equal("SUSHI")
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingBonusToken).to.be.within(400, 440)
// Claim reward
await this.chef.connect(this.bob).deposit(0, 0) // t+51
// Bob should have:
// - 1500 + 1*50 + 950 + 1*50 = 2550 (+50) JoeToken
// - 400 (+40) ParnterToken
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(2550, 2600)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(400, 440)
})
it("should allow allocation point to be set mid farming", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59
this.rewarder = await this.MasterChefRewarderPerSec.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerSec,
this.partnerChefAllocPoint,
this.partnerChefPid,
this.partnerChef.address,
this.chef.address
)
await this.rewarder.deployed() // t-58
await this.partnerToken.transferOwnership(this.partnerChef.address) // t-57
await this.partnerChef.add(this.partnerChefAllocPoint, this.dummyToken.address, true) // t-56
await this.partnerChef.add("200", this.lp2.address, true) // t-55
await this.dummyToken.connect(this.partnerDev).approve(this.rewarder.address, "1") // t-54
await this.rewarder.connect(this.partnerDev).init(this.dummyToken.address) // t-53
await this.joe.transferOwnership(this.chef.address) // t-52
await this.chef.add("100", this.lp.address, this.rewarder.address) // t-51
await this.lp.connect(this.bob).approve(this.chef.address, "1000") // t-50
await this.chef.connect(this.bob).deposit(0, "100") // t-49
await advanceTimeAndBlock(38) // t-11
await this.chef.connect(this.bob).deposit(0, "0") // t-10
// Bob should have:
// - 0 JoeToken
// - 37*40*1/3 = 493 (+60) PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(493 - this.tokenOffset, 553 + this.tokenOffset)
await advanceTimeAndBlock(8) // t-2
await this.chef.connect(this.bob).deposit(0, "0") // t-1
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
await advanceTimeAndBlock(10) // t+9
await this.chef.connect(this.bob).deposit(0, "0") // t+10
// Bob should have:
// - 10*50 = 500 (+50) JoeToken
// - 493 + 20*40*1/3 = 760 (+60) PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(500, 550)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(760 - this.tokenOffset, 820 + this.tokenOffset)
// Increase pool 1's alloc point
// For a brief amount of time, the rewarder is emitting 40/4 = 10 tokens per sec because the total allocPoint
// has increased to 400, but the pool alloc point on the rewarder has not been increased yet.
await this.partnerChef.set(0, "200", true) // t+11
await this.rewarder.updatePool() // t+12
await this.rewarder.setAllocPoint(200) // t+13
await advanceTimeAndBlock(2) // t+15
await advanceTimeAndBlock(5) // t+20
await advanceTimeAndBlock(9) // t+29
await this.chef.connect(this.bob).deposit(0, 0) // t+30
// Bob should have:
// - 500 + 20*50 = 1500 (+50) JoeToken
// - 760 + 3*40*1/4 + 17*40*1/2 = 1130 (+60) PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(1500, 1550)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(1130 - this.tokenOffset, 1190 + this.tokenOffset)
})
it("should give out JOEs only after farming time", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59
this.rewarder = await this.MasterChefRewarderPerSec.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerSec,
this.partnerChefAllocPoint,
this.partnerChefPid,
this.partnerChef.address,
this.chef.address
)
await this.rewarder.deployed() // t-58
await this.partnerToken.transferOwnership(this.partnerChef.address) // t-57
await this.partnerChef.add(this.partnerChefAllocPoint, this.dummyToken.address, true) // t-56
await this.dummyToken.connect(this.partnerDev).approve(this.rewarder.address, "1") // t-55
await this.rewarder.connect(this.partnerDev).init(this.dummyToken.address) // t-54
await this.joe.transferOwnership(this.chef.address) // t-53
await this.chef.add("100", this.lp.address, this.rewarder.address) // t-52
await this.lp.connect(this.bob).approve(this.chef.address, "1000") // t-51
await this.chef.connect(this.bob).deposit(0, "100") // t-50
await advanceTimeAndBlock(39) // t-11
await this.chef.connect(this.bob).deposit(0, "0") // t-10
// Bob should have:
// - 0 JoeToken
// - 40*40 = 1600 (+40) PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(1600, 1640)
await advanceTimeAndBlock(8) // t-2
await this.chef.connect(this.bob).deposit(0, "0") // t-1
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
await advanceTimeAndBlock(10) // t+9
await this.chef.connect(this.bob).deposit(0, "0") // t+10
// Bob should have:
// - 10*50 = 500 (+50) JoeToken
// - 1600 + 20*40 = 2400 (+40) PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(500, 550)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(2400, 2440)
await advanceTimeAndBlock(4) // t+14, b=32
await this.chef.connect(this.bob).deposit(0, "0") // t+15, b=33
// At this point:
// Bob should have:
// - 500 + 5*50 = 750 (+50) JoeToken
// - 2400 + 5*40 = 2600 (+40) PartnerToken
// Dev should have: 15*20 = 300 (+20)
// Treasury should have: 15*20 = 300 (+20)
// Investor should have: 15*10 = 150 (+10)
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(750, 800)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(2600, 2640)
expect(await this.joe.balanceOf(this.dev.address)).to.be.within(300, 320)
expect(await this.joe.balanceOf(this.treasury.address)).to.be.within(300, 320)
expect(await this.joe.balanceOf(this.investor.address)).to.be.within(150, 160)
expect(await this.joe.totalSupply()).to.be.within(1500, 1600)
})
it("should not distribute JOEs if no one deposit", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59
this.rewarder = await this.MasterChefRewarderPerSec.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerSec,
this.partnerChefAllocPoint,
this.partnerChefPid,
this.partnerChef.address,
this.chef.address
)
await this.rewarder.deployed() // t-58
await this.partnerToken.transferOwnership(this.partnerChef.address) // t-57
await this.partnerChef.add(this.partnerChefAllocPoint, this.dummyToken.address, true) // t-56
await this.dummyToken.connect(this.partnerDev).approve(this.rewarder.address, "1") // t-55
await this.rewarder.connect(this.partnerDev).init(this.dummyToken.address) // t-54
await this.joe.transferOwnership(this.chef.address) // t-53
await this.chef.add("100", this.lp.address, this.rewarder.address) // t-52
await this.lp.connect(this.bob).approve(this.chef.address, "1000") // t-51
await advanceTimeAndBlock(105) // t+54
expect(await this.joe.totalSupply()).to.equal("0")
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal("0")
await advanceTimeAndBlock(5) // t+59
expect(await this.joe.totalSupply()).to.equal("0")
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal("0")
await advanceTimeAndBlock(5) // t+64
await this.chef.connect(this.bob).deposit(0, "10") // t+65
expect(await this.joe.totalSupply()).to.equal("0")
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal("0")
expect(await this.joe.balanceOf(this.dev.address)).to.equal("0")
expect(await this.lp.balanceOf(this.bob.address)).to.equal("990")
await advanceTimeAndBlock(10) // t+75
// Revert if Bob withdraws more than he deposited
await expect(this.chef.connect(this.bob).withdraw(0, "11")).to.be.revertedWith("withdraw: not good") // t+76
await this.chef.connect(this.bob).withdraw(0, "10") // t+77
// At this point:
// Bob should have:
// - 12*50 = 600 (+50) JoeToken
// - 12*40 = 480 (+40) PartnerToken
// Dev should have:
// - 12*20 = 240 (+20) JoeToken
// Treasury should have:
// - 12*20 = 240 (+20) JoeToken
// Investor should have:
// - 12*10 = 120 (+10) JoeToken
expect(await this.joe.totalSupply()).to.be.within(1200, 1300)
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(600, 650)
expect(await this.joe.balanceOf(this.dev.address)).to.be.within(240, 260)
expect(await this.joe.balanceOf(this.treasury.address)).to.be.within(240, 260)
expect(await this.joe.balanceOf(this.investor.address)).to.be.within(120, 130)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(480, 520)
})
it("should distribute JOEs properly for each staker", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59
this.rewarder = await this.MasterChefRewarderPerSec.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerSec,
this.partnerChefAllocPoint,
this.partnerChefPid,
this.partnerChef.address,
this.chef.address
)
await this.rewarder.deployed() // t-58
await this.partnerToken.transferOwnership(this.partnerChef.address) // t-57
await this.partnerChef.add(this.partnerChefAllocPoint, this.dummyToken.address, true) // t-56
await this.dummyToken.connect(this.partnerDev).approve(this.rewarder.address, "1") // t-55
await this.rewarder.connect(this.partnerDev).init(this.dummyToken.address) // t-54
await this.joe.transferOwnership(this.chef.address) // t-53
await this.chef.add("100", this.lp.address, this.rewarder.address) // t-52
await this.lp.connect(this.alice).approve(this.chef.address, "1000", {
from: this.alice.address,
}) // t-50
await this.lp.connect(this.bob).approve(this.chef.address, "1000", {
from: this.bob.address,
}) // t-49
await this.lp.connect(this.carol).approve(this.chef.address, "1000", {
from: this.carol.address,
}) // t-48
// Alice deposits 10 LPs at t+10
await advanceTimeAndBlock(57) // t+9
await this.chef.connect(this.alice).deposit(0, "10", { from: this.alice.address }) // t+10
// Bob deposits 20 LPs at t+14
await advanceTimeAndBlock(3) // t+13
await this.chef.connect(this.bob).deposit(0, "20") // t+14
// Carol deposits 30 LPs at block t+18
await advanceTimeAndBlock(3) // t+17
await this.chef.connect(this.carol).deposit(0, "30", { from: this.carol.address }) // t+18
// Alice deposits 10 more LPs at t+20. At this point:
// Alice should have:
// - 4*50 + 4*50*1/3 + 2*50*1/6 = 283 (+50) JoeToken
// - 4*40 + 4*40*1/3 + 2*40*1/6 = 226 (+40) PartnerToken
// Dev should have: 10*20 = 200 (+20)
// Treasury should have: 10*20 = 200 (+20)
// Investor should have: 10*10 = 100 (+10)
// MasterChef should have: 1000 - 283 - 200 - 200 - 100 = 217 (+100)
await advanceTimeAndBlock(1) // t+19
await this.chef.connect(this.alice).deposit(0, "10", { from: this.alice.address }) // t+20,
expect(await this.joe.totalSupply()).to.be.within(1000, 1100)
// Because LP rewards are divided among participants and rounded down, we account
// for rounding errors with an offset
expect(await this.joe.balanceOf(this.alice.address)).to.be.within(283 - this.tokenOffset, 333 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.alice.address)).to.be.within(226 - this.tokenOffset, 266 + this.tokenOffset)
expect(await this.joe.balanceOf(this.bob.address)).to.equal("0")
expect(await this.partnerToken.balanceOf(this.bob.address)).to.equal("0")
expect(await this.joe.balanceOf(this.carol.address)).to.equal("0")
expect(await this.partnerToken.balanceOf(this.carol.address)).to.equal("0")
expect(await this.joe.balanceOf(this.dev.address)).to.be.within(200 - this.tokenOffset, 220 + this.tokenOffset)
expect(await this.joe.balanceOf(this.treasury.address)).to.be.within(200 - this.tokenOffset, 220 + this.tokenOffset)
expect(await this.joe.balanceOf(this.investor.address)).to.be.within(100 - this.tokenOffset, 110 + this.tokenOffset)
expect(await this.joe.balanceOf(this.chef.address)).to.be.within(217 - this.tokenOffset, 317 + this.tokenOffset)
// Bob withdraws 5 LPs at t+30. At this point:
// Bob should have:
// - 4*50*2/3 + 2*50*2/6 + 10*50*2/7 = 309 (+50) JoeToken
// - 4*40*2/3 + 2*40*2/6 + 10*40*2/7 = 247 (+40) PartnerToken
// Dev should have: 20*20= 400 (+20)
// Treasury should have: 20*20 = 400 (+20)
// Investor should have: 20*10 = 200 (+10)
// MasterChef should have: 217 + 1000 - 309 - 200 - 200 - 100 = 408 (+100)
await advanceTimeAndBlock(9) // t+29
await this.chef.connect(this.bob).withdraw(0, "5", { from: this.bob.address }) // t+30
expect(await this.joe.totalSupply()).to.be.within(2000, 2100)
// Because of rounding errors, we use token offsets
expect(await this.joe.balanceOf(this.alice.address)).to.be.within(283 - this.tokenOffset, 333 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.alice.address)).to.be.within(226 - this.tokenOffset, 266 + this.tokenOffset)
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(309 - this.tokenOffset, 359 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(247 - this.tokenOffset, 287 + this.tokenOffset)
expect(await this.joe.balanceOf(this.carol.address)).to.equal("0")
expect(await this.partnerToken.balanceOf(this.carol.address)).to.equal("0")
expect(await this.joe.balanceOf(this.dev.address)).to.be.within(400 - this.tokenOffset, 420 + this.tokenOffset)
expect(await this.joe.balanceOf(this.treasury.address)).to.be.within(400 - this.tokenOffset, 420 + this.tokenOffset)
expect(await this.joe.balanceOf(this.investor.address)).to.be.within(200 - this.tokenOffset, 210 + this.tokenOffset)
expect(await this.joe.balanceOf(this.chef.address)).to.be.within(408 - this.tokenOffset, 508 + this.tokenOffset)
// Alice withdraws 20 LPs at t+40
// Bob withdraws 15 LPs at t+50
// Carol withdraws 30 LPs at t+60
await advanceTimeAndBlock(9) // t+39
await this.chef.connect(this.alice).withdraw(0, "20", { from: this.alice.address }) // t+40
await advanceTimeAndBlock(9) // t+49
await this.chef.connect(this.bob).withdraw(0, "15", { from: this.bob.address }) // t+50
await advanceTimeAndBlock(9) // t+59
await this.chef.connect(this.carol).withdraw(0, "30", { from: this.carol.address }) // t+60
expect(await this.joe.totalSupply()).to.be.within(5000, 5100)
// Alice should have:
// - 283 + 10*50*2/7 + 10*50*20/65 = 579 (+50) JoeToken
// - 226 + 10*40*2/7 + 10*40*20/65 = 463 (+40) PartnerToken
expect(await this.joe.balanceOf(this.alice.address)).to.be.within(579 - this.tokenOffset, 629 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.alice.address)).to.be.within(463 - this.tokenOffset, 503 + this.tokenOffset)
// Bob should have:
// - 309 + 10*50*15/65 + 10*50*15/45 = 591 (+50) JoeToken
// - 247 + 10*40*15/65 + 10*40*15/45 = 472 (+40) PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(591 - this.tokenOffset, 641 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.bob.address)).to.be.within(472 - this.tokenOffset, 512 + this.tokenOffset)
// Carol should have:
// - 2*50*3/6 + 10*50*3/7 + 10*50*30/65 + 10*50*30/45 + 10*50 = 1328 (+50) JoeToken
// - 2*40*1/2 + 10*40*3/7 + 10*40*30/65 + 10*40*30/45 + 10*40 = 1062 (+40) PartnerToken
expect(await this.joe.balanceOf(this.carol.address)).to.be.within(1328 - this.tokenOffset, 1378 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.carol.address)).to.be.within(1062 - this.tokenOffset, 1102 + this.tokenOffset)
// Dev should have: 50*20 = 1000 (+20)
// Treasury should have: 50*20 = 1000 (+20)
// Investor should have: 50*10 = 500 (+10)
expect(await this.joe.balanceOf(this.dev.address)).to.be.within(1000 - this.tokenOffset, 1020 + this.tokenOffset)
expect(await this.joe.balanceOf(this.treasury.address)).to.be.within(1000 - this.tokenOffset, 1020 + this.tokenOffset)
expect(await this.joe.balanceOf(this.investor.address)).to.be.within(500 - this.tokenOffset, 510 + this.tokenOffset)
// MasterChefJoe and PartnerChef should have nothing
expect(await this.joe.balanceOf(this.chef.address)).to.be.within(0, 0 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.partnerChef.address)).to.be.within(0, 0 + this.tokenOffset)
// // All of them should have 1000 LPs back.
expect(await this.lp.balanceOf(this.alice.address)).to.equal("1000")
expect(await this.lp.balanceOf(this.bob.address)).to.equal("1000")
expect(await this.lp.balanceOf(this.carol.address)).to.equal("1000")
})
it("should give proper JOEs allocation to each pool", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59
this.rewarder = await this.MasterChefRewarderPerSec.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerSec,
this.partnerChefAllocPoint,
this.partnerChefPid,
this.partnerChef.address,
this.chef.address
)
await this.rewarder.deployed() // t-58
await this.partnerToken.transferOwnership(this.partnerChef.address) // t-57
await this.partnerChef.add(this.partnerChefAllocPoint, this.dummyToken.address, true) // t-56
await this.dummyToken.connect(this.partnerDev).approve(this.rewarder.address, "1") // t-55
await this.rewarder.connect(this.partnerDev).init(this.dummyToken.address) // t-54
await this.joe.transferOwnership(this.chef.address) // t-53
await this.lp.connect(this.alice).approve(this.chef.address, "1000", { from: this.alice.address }) // t-52
await this.lp2.connect(this.bob).approve(this.chef.address, "1000", { from: this.bob.address }) // t-51
// Add first LP to the pool with allocation 10
await this.chef.add("10", this.lp.address, this.rewarder.address) // t-50
// Alice deposits 10 LPs at t+10
await advanceTimeAndBlock(59) // t+9
await this.chef.connect(this.alice).deposit(0, "10", { from: this.alice.address }) // t+10
// Add LP2 to the pool with allocation 20 at t+20
await advanceTimeAndBlock(9) // t+19
await this.chef.add("20", this.lp2.address, ADDRESS_ZERO) // t+20
// Alice's pending reward should be:
// - 10*50 = 500 (+50) JoeToken
// - 10*40 = 400 (+40) PartnerToken
expect((await this.chef.pendingTokens(0, this.alice.address)).pendingJoe).to.be.within(500 - this.tokenOffset, 550 + this.tokenOffset)
expect(await this.rewarder.pendingTokens(this.alice.address)).to.be.within(400, 440)
// Bob deposits 10 LP2s at t+25
await advanceTimeAndBlock(4) // t+24
await this.chef.connect(this.bob).deposit(1, "10", { from: this.bob.address }) // t+25
// Alice's pending reward should be:
// - 500 + 5*1/3*50 = 583 (+50) JoeToken
// - 400 + 5*40 = 600 (+40) PartnerToken
expect((await this.chef.pendingTokens(0, this.alice.address)).pendingJoe).to.be.within(583 - this.tokenOffset, 633 + this.tokenOffset)
expect(await this.rewarder.pendingTokens(this.alice.address)).to.be.within(600, 640)
// At this point:
// Alice's pending reward should be:
// - 583 + 5*1/3*50 = 666 (+50) JoeToken
// - 600 + 5*40 = 800 (+40) PartnerToken
// Bob's pending reward should be:
// - 5*2/3*50 = 166 (+50) JoeToken
// - 0 PartnerToken
await advanceTimeAndBlock(5) // t+30
expect((await this.chef.pendingTokens(0, this.alice.address)).pendingJoe).to.be.within(666 - this.tokenOffset, 716 + this.tokenOffset)
expect(await this.rewarder.pendingTokens(this.alice.address)).to.be.within(800, 840)
expect((await this.chef.pendingTokens(1, this.bob.address)).pendingJoe).to.be.within(166 - this.tokenOffset, 216 + this.tokenOffset)
expect(await this.rewarder.pendingTokens(this.bob.address)).to.equal(0)
// Alice and Bob should not have pending rewards in pools they're not staked in
expect((await this.chef.pendingTokens(1, this.alice.address)).pendingJoe).to.equal("0")
expect((await this.chef.pendingTokens(0, this.bob.address)).pendingJoe).to.equal("0")
// Make sure they have receive the same amount as what was pending
await this.chef.connect(this.alice).withdraw(0, "10", { from: this.alice.address }) // t+31
// Alice should have:
// - 666 + 1*1/3*50 = 682 (+50) JoeToken
// - 800 + 1*40 = 840 (+40) PartnerToken
expect(await this.joe.balanceOf(this.alice.address)).to.be.within(682 - this.tokenOffset, 732 + this.tokenOffset)
expect(await this.partnerToken.balanceOf(this.alice.address)).to.be.within(840, 880)
await this.chef.connect(this.bob).withdraw(1, "5", { from: this.bob.address }) // t+32
// Bob should have:
// - 166 + 2*2/3*50 = 232 (+50) JoeToken
// - 0 PartnerToken
expect(await this.joe.balanceOf(this.bob.address)).to.be.within(232 - this.tokenOffset, 282 + this.tokenOffset)
expect(await this.rewarder.pendingTokens(this.bob.address)).to.equal(0)
})
it("should give proper JOEs after updating emission rate", async function () {
const startTime = (await latest()).add(60)
this.chef = await this.MCV2.deploy(
this.joe.address,
this.dev.address,
this.treasury.address,
this.investor.address,
this.joePerSec,
startTime,
this.devPercent,
this.treasuryPercent,
this.investorPercent
)
await this.chef.deployed() // t-59
this.rewarder = await this.MasterChefRewarderPerSec.deploy(
this.partnerToken.address,
this.lp.address,
this.partnerRewardPerSec,
this.partnerChefAllocPoint,
this.partnerChefPid,
this.partnerChef.address,
this.chef.address
)
await this.rewarder.deployed() // t-58
await this.partnerToken.transferOwnership(this.partnerChef.address) // t-57
await this.partnerChef.add(this.partnerChefAllocPoint, this.dummyToken.address, true) // t-56
await this.dummyToken.connect(this.partnerDev).approve(this.rewarder.address, "1") // t-55
await this.rewarder.connect(this.partnerDev).init(this.dummyToken.address) // t-54
await this.joe.transferOwnership(this.chef.address) // t-53
await this.lp.connect(this.alice).approve(this.chef.address, "1000", { from: this.alice.address }) // t-52
await this.chef.add("10", this.lp.address, this.rewarder.address) // t-51
// Alice deposits 10 LPs at t+10
await advanceTimeAndBlock(60) // t+9
await this.chef.connect(this.alice).deposit(0, "10", { from: this.alice.address }) // t+10
// At t+110, Alice should have:
// - 100*100*0.5 = 5000 (+50) JoeToken
// - 100*40 = 4000 (+40) PartnerToken
await advanceTimeAndBlock(100) // t+110
expect((await this.chef.pendingTokens(0, this.alice.address)).pendingJoe).to.be.within(5000, 5050)
expect(await this.rewarder.pendingTokens(this.alice.address)).to.be.within(4000, 4040)
// Lower JOE emission rate to 40 JOE per sec
await this.chef.updateEmissionRate(40) // t+111
// At t+115, Alice should have:
// - 5000 + 1*100*0.5 + 4*40*0.5 = 5130 (+50) JoeToken
// - 4000 + 5*40 = 4200 (+40) PartnerToken
await advanceTimeAndBlock(4) // t+115
expect((await this.chef.pendingTokens(0, this.alice.address)).pendingJoe).to.be.within(5130, 5180)
expect(await this.rewarder.pendingTokens(this.alice.address)).to.be.within(4200, 4240)
// Increase PartnerToken emission rate to 90 PartnerToken per block
await this.rewarder.setRewardRate(90) // t+116
// At b=35, Alice should have:
// - 5130 + 21*40*0.5 = 5550 (+50) JoeToken
// - 4200 + 1*40 + 20*90 = 6040 (+90) PartnerToken
await advanceTimeAndBlock(20) // t+136
expect((await this.chef.pendingTokens(0, this.alice.address)).pendingJoe).to.be.within(5550, 5600)
expect(await this.rewarder.pendingTokens(this.alice.address)).to.be.within(6040, 6130)
})
})
after(async function () {
await network.provider.request({
method: "hardhat_reset",
params: [],
})
})
}) | the_stack |
import { EventEmitter } from 'events';
import { connect as netConnect, Socket, TcpNetConnectOpts } from 'net';
import { connect as tlsConnect } from 'tls';
import { RethinkDBErrorType, RServerConnectionOptions } from '../types';
import { RethinkDBError } from '../error/error';
import { QueryJson, ResponseJson } from '../internal-types';
import { QueryType, ResponseType } from '../proto/enums';
import { DataQueue } from './data-queue';
import {
buildAuthBuffer,
compareDigest,
computeSaltedPassword,
NULL_BUFFER,
validateVersion,
} from './handshake-utils';
import { isNativeError } from '../util';
export type RNConnOpts = RServerConnectionOptions & {
host: string;
port: number;
};
export function setConnectionDefaults(
connectionOptions: RServerConnectionOptions,
): RNConnOpts {
return {
...connectionOptions,
host: connectionOptions.host || 'localhost',
port: connectionOptions.port || 28015,
};
}
export class RethinkDBSocket extends EventEmitter {
public connectionOptions: RNConnOpts;
public readonly user: string;
public readonly password: Buffer;
public lastError?: Error;
public get status() {
if (this.lastError) {
return 'errored';
}
if (!this.isOpen) {
return 'closed';
}
if (this.mode === 'handshake') {
return 'handshake';
}
return 'open';
}
public socket?: Socket;
public runningQueries = new Map<
number,
{
query: QueryJson;
data: DataQueue<ResponseJson | Error>;
}
>();
private isOpen = false;
private nextToken = 0;
private buffer = Buffer.alloc(0);
private mode: 'handshake' | 'response' = 'handshake';
constructor({
connectionOptions,
user = 'admin',
password = '',
}: {
connectionOptions: RNConnOpts;
user?: string;
password?: string;
}) {
super();
this.connectionOptions = setConnectionDefaults(connectionOptions);
this.user = user;
this.password = password ? Buffer.from(password) : NULL_BUFFER;
}
public async connect() {
if (this.socket) {
throw new RethinkDBError('Socket already connected', {
type: RethinkDBErrorType.CONNECTION,
});
}
const { tls = false, ...options } = this.connectionOptions;
try {
const socket = await new Promise<Socket>((resolve, reject) => {
const s = tls
? tlsConnect(options)
: netConnect(options as TcpNetConnectOpts);
s.once('connect', () => resolve(s)).once('error', reject);
});
socket.removeAllListeners();
socket
.on('close', () => this.close())
.on('end', () => this.close())
.on('error', (error) => this.handleError(error))
.on('data', (data) => {
try {
this.buffer = Buffer.concat([this.buffer, data]);
switch (this.mode) {
case 'handshake':
this.handleHandshakeData();
break;
case 'response':
this.handleData();
break;
default:
break;
}
} catch (error: any) {
this.handleError(error);
}
});
socket.setKeepAlive(true);
this.socket = socket;
await new Promise<void>((resolve, reject) => {
socket.once('connect', resolve);
socket.once('error', reject);
if (socket.destroyed) {
socket.removeListener('connect', resolve);
socket.removeListener('error', reject);
reject(this.lastError);
} else if (!socket.connecting) {
socket.removeListener('connect', resolve);
socket.removeListener('error', reject);
resolve();
}
});
this.isOpen = true;
this.lastError = undefined;
await this.performHandshake();
this.emit('connect');
} catch (error: any) {
this.handleError(error);
}
}
public sendQuery(newQuery: QueryJson, token?: number) {
if (!this.socket || this.status !== 'open') {
throw new RethinkDBError(
'`run` was called with a closed connection after:',
{ query: newQuery, type: RethinkDBErrorType.CONNECTION },
);
}
if (token === undefined) {
token = this.nextToken++;
}
const encoded = JSON.stringify(newQuery);
const querySize = Buffer.byteLength(encoded);
const buffer = Buffer.alloc(8 + 4 + querySize);
// eslint-disable-next-line no-bitwise
buffer.writeUInt32LE(token & 0xffffffff, 0);
buffer.writeUInt32LE(Math.floor(token / 0xffffffff), 4);
buffer.writeUInt32LE(querySize, 8);
buffer.write(encoded, 12);
const { noreply = false } = newQuery[2] || {};
if (noreply) {
this.socket.write(buffer);
this.emit('query', token);
return token;
}
const [type] = newQuery;
const { query = newQuery, data = null } =
this.runningQueries.get(token) || {};
if (type === QueryType.STOP) {
// console.log('STOP ' + token);
this.socket.write(buffer);
if (data) {
// Resolving and not rejecting so there won't be "unhandled rejection" if nobody listens
data.destroy(
new RethinkDBError('Query cancelled', {
query,
type: RethinkDBErrorType.CANCEL,
}),
);
this.runningQueries.delete(token);
this.emit('release', this.runningQueries.size);
}
return token;
}
if (!data) {
this.runningQueries.set(token, {
data: new DataQueue(),
query,
});
}
this.socket.write(buffer);
this.emit('query', token);
return token;
}
public stopQuery(token: number) {
if (this.runningQueries.has(token)) {
this.sendQuery([QueryType.STOP], token);
}
}
public continueQuery(token: number) {
if (this.runningQueries.has(token)) {
this.sendQuery([QueryType.CONTINUE], token);
}
}
public async readNext<T = ResponseJson>(token: number): Promise<T> {
if (!this.isOpen) {
throw (
this.lastError ||
new RethinkDBError(
'The connection was closed before the query could be completed',
{
type: RethinkDBErrorType.CONNECTION,
},
)
);
}
if (!this.runningQueries.has(token)) {
throw new RethinkDBError('No more rows in the cursor.', {
type: RethinkDBErrorType.CURSOR_END,
});
}
const { data = null } = this.runningQueries.get(token) || {};
if (!data) {
throw new RethinkDBError('Query is not running.', {
type: RethinkDBErrorType.CURSOR,
});
}
const res = await data.dequeue();
if (isNativeError(res)) {
data.destroy(res);
this.runningQueries.delete(token);
throw res;
} else if (this.status === 'handshake') {
this.runningQueries.delete(token);
} else if (res.t !== ResponseType.SUCCESS_PARTIAL) {
this.runningQueries.delete(token);
this.emit('release', this.runningQueries.size);
}
return res as any;
}
public close(error?: Error) {
for (const { data, query } of this.runningQueries.values()) {
data.destroy(
new RethinkDBError(
'The connection was closed before the query could be completed',
{
query,
type: RethinkDBErrorType.CONNECTION,
},
),
);
}
this.runningQueries.clear();
if (!this.socket) {
return;
}
this.socket.removeAllListeners();
this.socket.destroy();
this.socket = undefined;
this.isOpen = false;
this.mode = 'handshake';
this.emit('close', error);
this.removeAllListeners();
this.nextToken = 0;
}
private async performHandshake() {
let token = 0;
const generateRunningQuery = () => {
this.runningQueries.set(token++, {
data: new DataQueue(),
query: [QueryType.START],
});
};
if (!this.socket || this.status !== 'handshake') {
throw new RethinkDBError('Connection is not open', {
type: RethinkDBErrorType.CONNECTION,
});
}
const { randomString, authBuffer } = buildAuthBuffer(this.user);
generateRunningQuery();
generateRunningQuery();
this.socket.write(authBuffer);
validateVersion(await this.readNext<any>(0));
const { authentication } = await this.readNext<any>(1);
const { serverSignature, proof } = await computeSaltedPassword(
authentication,
randomString,
this.user,
this.password,
);
generateRunningQuery();
this.socket.write(proof);
const { authentication: returnedSignature } = await this.readNext<any>(2);
compareDigest(returnedSignature, serverSignature);
this.mode = 'response';
}
private handleHandshakeData() {
let index = -1;
while ((index = this.buffer.indexOf(0)) >= 0) {
const strMsg = this.buffer.slice(0, index).toString('utf8');
const { data = null } = this.runningQueries.get(this.nextToken++) || {};
let error: RethinkDBError | undefined;
try {
const jsonMsg = JSON.parse(strMsg);
if (jsonMsg.success) {
if (data) {
data.enqueue(jsonMsg as any);
}
} else {
error = new RethinkDBError(jsonMsg.error, {
errorCode: jsonMsg.error_code,
});
}
} catch (cause: any) {
error = new RethinkDBError(strMsg, {
cause,
type: RethinkDBErrorType.AUTH,
});
}
if (error) {
if (data) {
data.destroy(error);
}
this.handleError(error);
}
this.buffer = this.buffer.slice(index + 1);
index = this.buffer.indexOf(0);
}
}
private handleData() {
while (this.buffer.length >= 12) {
const token =
this.buffer.readUInt32LE(0) + 0x100000000 * this.buffer.readUInt32LE(4);
const responseLength = this.buffer.readUInt32LE(8);
if (this.buffer.length < 12 + responseLength) {
break;
}
const responseBuffer = this.buffer.slice(12, 12 + responseLength);
const response: ResponseJson = JSON.parse(
responseBuffer.toString('utf8'),
);
this.buffer = this.buffer.slice(12 + responseLength);
const { data = null } = this.runningQueries.get(token) || {};
if (data) {
data.enqueue(response);
}
}
}
private handleError(err: Error) {
this.close(err);
this.lastError = err;
if (this.listenerCount('error') > 0) {
this.emit('error', err);
}
}
} | the_stack |
import { IContent, MatrixClient, MatrixEvent } from "../../../src";
import { Room } from "../../../src/models/room";
import { IEncryptedFile, RelationType, UNSTABLE_MSC3089_BRANCH } from "../../../src/@types/event";
import { EventTimelineSet } from "../../../src/models/event-timeline-set";
import { EventTimeline } from "../../../src/models/event-timeline";
import { MSC3089Branch } from "../../../src/models/MSC3089Branch";
import { MSC3089TreeSpace } from "../../../src/models/MSC3089TreeSpace";
describe("MSC3089Branch", () => {
let client: MatrixClient;
// @ts-ignore - TS doesn't know that this is a type
let indexEvent: any;
let directory: MSC3089TreeSpace;
let branch: MSC3089Branch;
let branch2: MSC3089Branch;
const branchRoomId = "!room:example.org";
const fileEventId = "$file";
const fileEventId2 = "$second_file";
const staticTimelineSets = {} as EventTimelineSet;
const staticRoom = {
getUnfilteredTimelineSet: () => staticTimelineSets,
} as any as Room; // partial
beforeEach(() => {
// TODO: Use utility functions to create test rooms and clients
client = <MatrixClient>{
getRoom: (roomId: string) => {
if (roomId === branchRoomId) {
return staticRoom;
} else {
throw new Error("Unexpected fetch for unknown room");
}
},
};
indexEvent = ({
getRoomId: () => branchRoomId,
getStateKey: () => fileEventId,
});
directory = new MSC3089TreeSpace(client, branchRoomId);
branch = new MSC3089Branch(client, indexEvent, directory);
branch2 = new MSC3089Branch(client, {
getRoomId: () => branchRoomId,
getStateKey: () => fileEventId2,
} as MatrixEvent, directory);
});
it('should know the file event ID', () => {
expect(branch.id).toEqual(fileEventId);
});
it('should know if the file is active or not', () => {
indexEvent.getContent = () => ({});
expect(branch.isActive).toBe(false);
indexEvent.getContent = () => ({ active: false });
expect(branch.isActive).toBe(false);
indexEvent.getContent = () => ({ active: true });
expect(branch.isActive).toBe(true);
indexEvent.getContent = () => ({ active: "true" }); // invalid boolean, inactive
expect(branch.isActive).toBe(false);
});
it('should be able to delete the file', async () => {
const eventIdOrder = [fileEventId, fileEventId2];
const stateFn = jest.fn()
.mockImplementation((roomId: string, eventType: string, content: any, stateKey: string) => {
expect(roomId).toEqual(branchRoomId);
expect(eventType).toEqual(UNSTABLE_MSC3089_BRANCH.unstable); // test that we're definitely using the unstable value
expect(content).toMatchObject({});
expect(content['active']).toBeUndefined();
expect(stateKey).toEqual(eventIdOrder[stateFn.mock.calls.length - 1]);
return Promise.resolve(); // return value not used
});
client.sendStateEvent = stateFn;
const redactFn = jest.fn().mockImplementation((roomId: string, eventId: string) => {
expect(roomId).toEqual(branchRoomId);
expect(eventId).toEqual(eventIdOrder[stateFn.mock.calls.length - 1]);
return Promise.resolve(); // return value not used
});
client.redactEvent = redactFn;
branch.getVersionHistory = () => Promise.resolve([branch, branch2]);
branch2.getVersionHistory = () => Promise.resolve([branch2]);
await branch.delete();
expect(stateFn).toHaveBeenCalledTimes(2);
expect(redactFn).toHaveBeenCalledTimes(2);
});
it('should know its name', async () => {
const name = "My File.txt";
indexEvent.getContent = () => ({ active: true, name: name });
const res = branch.getName();
expect(res).toEqual(name);
});
it('should be able to change its name', async () => {
const name = "My File.txt";
indexEvent.getContent = () => ({ active: true, retained: true });
const stateFn = jest.fn()
.mockImplementation((roomId: string, eventType: string, content: any, stateKey: string) => {
expect(roomId).toEqual(branchRoomId);
expect(eventType).toEqual(UNSTABLE_MSC3089_BRANCH.unstable); // test that we're definitely using the unstable value
expect(content).toMatchObject({
retained: true, // canary for copying state
active: true,
name: name,
});
expect(stateKey).toEqual(fileEventId);
return Promise.resolve(); // return value not used
});
client.sendStateEvent = stateFn;
await branch.setName(name);
expect(stateFn).toHaveBeenCalledTimes(1);
});
it('should be v1 by default', () => {
indexEvent.getContent = () => ({ active: true });
const res = branch.version;
expect(res).toEqual(1);
});
it('should be vN when set', () => {
indexEvent.getContent = () => ({ active: true, version: 3 });
const res = branch.version;
expect(res).toEqual(3);
});
it('should be unlocked by default', async () => {
indexEvent.getContent = () => ({ active: true });
const res = branch.isLocked();
expect(res).toEqual(false);
});
it('should use lock status from index event', async () => {
indexEvent.getContent = () => ({ active: true, locked: true });
const res = branch.isLocked();
expect(res).toEqual(true);
});
it('should be able to change its locked status', async () => {
const locked = true;
indexEvent.getContent = () => ({ active: true, retained: true });
const stateFn = jest.fn()
.mockImplementation((roomId: string, eventType: string, content: any, stateKey: string) => {
expect(roomId).toEqual(branchRoomId);
expect(eventType).toEqual(UNSTABLE_MSC3089_BRANCH.unstable); // test that we're definitely using the unstable value
expect(content).toMatchObject({
retained: true, // canary for copying state
active: true,
locked: locked,
});
expect(stateKey).toEqual(fileEventId);
return Promise.resolve(); // return value not used
});
client.sendStateEvent = stateFn;
await branch.setLocked(locked);
expect(stateFn).toHaveBeenCalledTimes(1);
});
it('should be able to return event information', async () => {
const mxcLatter = "example.org/file";
const fileContent = { isFile: "not quite", url: "mxc://" + mxcLatter };
const fileEvent = { getId: () => fileEventId, getOriginalContent: () => ({ file: fileContent }) };
staticRoom.getUnfilteredTimelineSet = () => ({
findEventById: (eventId) => {
expect(eventId).toEqual(fileEventId);
return fileEvent;
},
}) as EventTimelineSet;
client.mxcUrlToHttp = (mxc: string) => {
expect(mxc).toEqual("mxc://" + mxcLatter);
return `https://example.org/_matrix/media/v1/download/${mxcLatter}`;
};
client.decryptEventIfNeeded = () => Promise.resolve();
const res = await branch.getFileInfo();
expect(res).toBeDefined();
expect(res).toMatchObject({
info: fileContent,
// Escape regex from MDN guides: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
httpUrl: expect.stringMatching(`.+${mxcLatter.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`),
});
});
it('should be able to return the event object', async () => {
const mxcLatter = "example.org/file";
const fileContent = { isFile: "not quite", url: "mxc://" + mxcLatter };
const fileEvent = { getId: () => fileEventId, getOriginalContent: () => ({ file: fileContent }) };
staticRoom.getUnfilteredTimelineSet = () => ({
findEventById: (eventId) => {
expect(eventId).toEqual(fileEventId);
return fileEvent;
},
}) as EventTimelineSet;
client.mxcUrlToHttp = (mxc: string) => {
expect(mxc).toEqual("mxc://" + mxcLatter);
return `https://example.org/_matrix/media/v1/download/${mxcLatter}`;
};
client.decryptEventIfNeeded = () => Promise.resolve();
const res = await branch.getFileEvent();
expect(res).toBeDefined();
expect(res).toBe(fileEvent);
});
it('should create new versions of itself', async () => {
const canaryName = "canary";
const canaryContents = "contents go here";
const canaryFile = {} as IEncryptedFile;
const canaryAddl = { canary: true };
indexEvent.getContent = () => ({ active: true, retained: true });
const stateKeyOrder = [fileEventId2, fileEventId];
const stateFn = jest.fn()
.mockImplementation((roomId: string, eventType: string, content: any, stateKey: string) => {
expect(roomId).toEqual(branchRoomId);
expect(eventType).toEqual(UNSTABLE_MSC3089_BRANCH.unstable); // test that we're definitely using the unstable value
expect(stateKey).toEqual(stateKeyOrder[stateFn.mock.calls.length - 1]);
if (stateKey === fileEventId) {
expect(content).toMatchObject({
retained: true, // canary for copying state
active: false,
});
} else if (stateKey === fileEventId2) {
expect(content).toMatchObject({
active: true,
version: 2,
name: canaryName,
});
} else {
throw new Error("Unexpected state key: " + stateKey);
}
return Promise.resolve(); // return value not used
});
client.sendStateEvent = stateFn;
const createFn = jest.fn().mockImplementation((
name: string,
contents: ArrayBuffer,
info: Partial<IEncryptedFile>,
addl: IContent,
) => {
expect(name).toEqual(canaryName);
expect(contents).toBe(canaryContents);
expect(info).toBe(canaryFile);
expect(addl).toMatchObject({
...canaryAddl,
"m.new_content": true,
"m.relates_to": {
"rel_type": RelationType.Replace,
"event_id": fileEventId,
},
});
return Promise.resolve({ event_id: fileEventId2 });
});
directory.createFile = createFn;
await branch.createNewVersion(canaryName, canaryContents, canaryFile, canaryAddl);
expect(stateFn).toHaveBeenCalledTimes(2);
expect(createFn).toHaveBeenCalledTimes(1);
});
it('should fetch file history', async () => {
branch2.getFileEvent = () => Promise.resolve({
replacingEventId: () => undefined,
getId: () => fileEventId2,
} as MatrixEvent);
branch.getFileEvent = () => Promise.resolve({
replacingEventId: () => fileEventId2,
getId: () => fileEventId,
} as MatrixEvent);
const events = [await branch.getFileEvent(), await branch2.getFileEvent(), {
replacingEventId: (): string => null,
getId: () => "$unknown",
}];
staticRoom.getLiveTimeline = () => ({ getEvents: () => events }) as EventTimeline;
directory.getFile = (evId: string) => {
expect(evId).toEqual(fileEventId);
return branch;
};
const results = await branch2.getVersionHistory();
expect(results).toMatchObject([
branch2,
branch,
]);
});
}); | the_stack |
import Vue from 'vue';
import {
IS_DEBUG,
PASTED_IMG_CLASS,
USERNAME_REGEX,
PASTED_GIPHY_CLASS
} from '@/ts/utils/consts';
import {
MessageDataEncode,
UploadFile
} from '@/ts/types/types';
import {
BlobType,
CurrentUserSettingsModel,
FileModel,
MessageModel,
UserModel
} from '@/ts/types/model';
import recordIcon from '@/assets/img/audio.svg';
import fileIcon from '@/assets/img/file.svg';
import { getFlag } from '@/ts/utils/flags';
import videoIcon from '@/assets/img/icon-play-red.svg';
import {
Smile,
smileys,
} from '@/ts/utils/smileys';
import loggerFactory from '@/ts/instances/loggerFactory';
import {
Logger,
LogLevel
} from 'lines-logger';
import {
MEDIA_API_URL,
webpSupported
} from '@/ts/utils/runtimeConsts';
import {DefaultStore} from '@/ts/classes/DefaultStore';
import { hexEncode } from '@/ts/utils/pureFunctions';
import { GIFObject } from 'giphy-api';
const tmpCanvasContext: CanvasRenderingContext2D = document.createElement('canvas').getContext('2d')!; // TODO why is it not safe?
const yotubeTimeRegex = /(?:(\d*)h)?(?:(\d*)m)?(?:(\d*)s)?(\d)?/;
const logger: Logger = loggerFactory.getLogger('htmlApi');
export const savedFiles: { [id: string]: Blob } = {};
if (IS_DEBUG) {
window.savedFiles = savedFiles;
}
export const requestFileSystem: (type: number, size: number, successCallback: FileSystemCallback, errorCallback?: ErrorCallback) => void = window.webkitRequestFileSystem || window.mozRequestFileSystem || window.requestFileSystem;
const escapeMap: { [id: string]: string } = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
'\'': ''',
'\n': '<br>',
'/': '/'
};
export function forEach<T extends Node>(array: NodeListOf<T> | undefined, cb: (a: T) => void) {
if (array && array.length) {
for (let i = 0; i < array.length; i++) {
cb(array[i]);
}
}
}
export const allSmileysKeysNoVariations : Record<string, Smile> = (function() {
const result: Record<string, Smile>= {};
Object.entries(smileys).forEach(([tabName, tabSmileys]) => {
Object.entries(tabSmileys).forEach(([smileyCode, smileyValue]) => {
result[smileyCode] = {
alt: smileyValue.alt,
src: smileyValue.src,
skinVariations: smileyValue.skinVariations,
}
});
})
return result;
})()
export const allSmileysKeys : Record<string, Smile> = (function() {
const result: Record<string, Smile>= {};
Object.entries(smileys).forEach(([tabName, tabSmileys]) => {
Object.entries(tabSmileys).forEach(([smileyCode, smileyValue]) => {
if (smileyValue.skinVariations) {
Object.entries(smileyValue.skinVariations).forEach(([smileyCodeVar, smileyValueVasr]) => {
if (smileyCode !== smileyCodeVar) {
// order of properties of object is js matter,
// first object added will be first in Object.keys array
// skin variation should be set first, in order to smileyUniceRegex to be gready
// since we have smileys like \u01 = smiley white person, and \u01\u02 = smiley black person
// they both start with \u01 so, we should replace \u01\u02, otherwiose we leave \u02 symbol undecoded
result[smileyCodeVar] = {
alt: smileyValueVasr.alt,
src: smileyValueVasr.src
}
}
});
}
result[smileyCode] = {
alt: smileyValue.alt,
src: smileyValue.src,
skinVariations: smileyValue.skinVariations,
}
});
})
return result;
})()
export const smileUnicodeRegex = (function() {
let allSmileyRegexarray = Object.keys(allSmileysKeys).map(hexEncode);
return new RegExp(allSmileyRegexarray.join('|'), 'g');
})();
const imageUnicodeRegex = /[\u3501-\u3600]/g;
const patterns = [
{
search: /(https?://.+?(?=\s+|<br>|"|$))/g, /*http://anycharacter except end of text, <br> or space*/
replace: '<a href="$1" target="_blank">$1</a>',
name: 'links'
}, {
search: /<a href="http(?:s?)://(?:www\.)?youtu(?:be\.com/watch\?v=|\.be\/)([\w\-\_]*)(?:[^"]*?\&\;t=([\w\-\_]*))?[^"]*" target="_blank">[^<]+<\/a>/g,
replace: '<div class="youtube-player" data-id="$1" data-time="$2"><div><img src="https://i.ytimg.com/vi/$1/hqdefault.jpg"><div class="icon-youtube-play"></div></div></div>',
name: 'embeddedYoutube'
},
{
search: /```(.+?)(?=```)```/g,
replace: '<pre>$1</pre>',
name: 'highlightCode'
},
{
search: new RegExp(`(^\(\d\d:\d\d:\d\d\)\s${USERNAME_REGEX}:)(.*)>>><br>`),
replace: '<div class="quote"><span>$1</span>$2</div>',
name: 'quote'
}
];
export function getCurrentWordInHtml(el: HTMLElement) {
let position = 0;
const sel: Selection = window.getSelection()!;
if (!sel.rangeCount) {
return
}
const range = sel.getRangeAt(0);
if (range.commonAncestorContainer.parentNode === el) {
position = range.endOffset;
}
// Get content of div
const content = (range.commonAncestorContainer as any).data; // this this is undefined todo, really undefied somethng
if (!content) { // content is undefined when e.g. user selects all
return "";
}
// Check if clicked at the end of word
position = content![position] === ' ' ? position - 1 : position; /* TODO vue.js:1897 TypeError: Cannot read property '0' of undefined*/
// Get the start and end index
let startPosition = content!.lastIndexOf(' ', position);
startPosition = startPosition === content!.length ? 0 : startPosition;
let endPosition = content!.indexOf(' ', position);
endPosition = endPosition === -1 ? content!.length : endPosition;
return content!.substring(startPosition + 1, endPosition);
}
export function sliceZero(n: number, count: number = -2) {
return String('00' + n).slice(count);
}
export function timeToString(time: number) {
const date = new Date(time);
return [sliceZero(date.getHours()), sliceZero(date.getMinutes()), sliceZero(date.getSeconds())].join(':');
}
const replaceHtmlRegex = new RegExp('[' + Object.keys(escapeMap).join('') + ']', 'g');
export function encodeHTML(html: string) {
return html.replace(replaceHtmlRegex, s => escapeMap[s]);
}
export function getFlagPath(countryCode: string) {
return getFlag(countryCode);
}
export function getSmileyHtml(symbol: string) {
let smile: Smile | undefined = allSmileysKeys[symbol];
if (!smile) {
throw Error(`Invalid smile ${symbol}`);
}
return `<img src="${smile.src}" symbol="${symbol}" class="emoji" alt="${smile.alt}">`;
}
export function getGiphyHtml(gif: GIFObject) {
let src;
if (gif.images.fixed_height_small) {
src = webpSupported && gif.images.fixed_height_small.webp ? gif.images.fixed_height_small.webp : gif.images.fixed_height_small.url;
} else if (gif.images.fixed_height) {
src = webpSupported && gif.images.fixed_height.webp ? gif.images.fixed_height.webp : gif.images.fixed_height.url;
} else {
throw Error(`Invalid image ${JSON.stringify(gif)}`)
}
const webp = gif.images.original.webp ? `webp="${gif.images.original.webp}"` : ``;
return `<img src="${src}" class="${PASTED_GIPHY_CLASS} ${PASTED_IMG_CLASS}" ${webp} url="${gif.images.original.url}" />`;
}
export const isDateMissing = (function () {
const input = document.createElement('input');
input.setAttribute('type', 'date');
const notADateValue = 'not-a-date';
input.setAttribute('value', notADateValue);
return input.value === notADateValue;
})();
export function resolveMediaUrl<T extends string|null>(src: T): T {
if (!src) {
return null as T;
}
return src.indexOf('blob:http') === 0 ? src : `${MEDIA_API_URL}${src}` as T;
}
export function encodeSmileys(html: string): string {
return html.replace(smileUnicodeRegex, getSmileyHtml);
}
export function encodeP(data: MessageModel, store: DefaultStore) {
if (!data.content) {
throw Error(`Message ${data.id} doesn't have content`);
}
let html = encodeHTML(data.content);
html = encodeFiles(html, data.files);
html = encodePTags(html, data.tags, store);
return encodeSmileys(html);
}
export const canvasContext: CanvasRenderingContext2D = document.createElement('canvas').getContext('2d')!; // TODO wtf it's nullable?
export function placeCaretAtEnd(userMessage: HTMLElement) {
const range = document.createRange();
range.selectNodeContents(userMessage);
range.collapse(false);
const sel = window.getSelection();
if (sel) {
sel.removeAllRanges();
sel.addRange(range);
} else {
logger.warn(`Can't place selection`)();
}
}
export function encodeMessage(data: MessageModel, store: DefaultStore) {
//logger.debug('Encoding message {}: {}', data.id, data)();
if (!data.content) {
throw Error(`Message ${data.id} doesn't have content`);
}
let html = encodeHTML(data.content);
const replaceElements: unknown[] = [];
patterns.forEach((pattern) => {
if (store.userSettings
&& store.userSettings[pattern.name as keyof CurrentUserSettingsModel] === false) { // can be undefined as well
return;
}
const res = html.replace(pattern.search, pattern.replace);
if (res !== html) {
replaceElements.push(pattern.name);
html = res;
}
});
if (replaceElements.length) {
logger.debug('Replaced {} in message #{}', replaceElements.join(', '), data.id)();
}
html = encodeFiles(html, data.files);
html = encodeTags(html, data.tags, store);
return encodeSmileys(html);
}
function encodePTags(html: string, tags: { [id: string]: number } | null, store: DefaultStore) {
if (tags && Object.keys(tags).length) {
html = html.replace(imageUnicodeRegex, (s) => {
const v = tags[s];
if (v) {
let tag = createTag(store.allUsersDict[v]);
return tag.outerHTML;
}
return s; // if it's absent in files, it could be also in tags so return it. (don't replace )
});
}
return html;
}
function encodeTags(html: string, tags: { [id: string]: number } | null, store: DefaultStore) {
if (tags && Object.keys(tags).length) {
html = html.replace(imageUnicodeRegex, (s) => {
const v = tags[s];
if (v) {
return `<span user-id='${v}' symbol='${s}' class="tag-user">@${store.allUsersDict[v].user}</span>`
}
return s; // if it's absent in files, it could be also in tags so return it. (don't replace )
});
}
return html;
}
function encodeFiles(html: string, files: { [id: string]: FileModel } | null) {
if (files && Object.keys(files).length) {
html = html.replace(imageUnicodeRegex, (s) => {
const v = files[s];
if (v) {
if (v.type === 'i') {
return `<img src='${resolveMediaUrl(v.url!)}' symbol='${s}' class='${PASTED_IMG_CLASS}' serverId="${v.serverId}"/>`;
} else if (v.type === 'v' || v.type === 'm') {
const className = v.type === 'v' ? 'video-player' : 'video-player video-record';
return `<div class='${className}' serverId="${v.serverId}" associatedVideo='${v.url}'><div><img ${v.preview? `src="${resolveMediaUrl(v.preview)}"`: ""} symbol='${s}' class='${PASTED_IMG_CLASS}'/><div class="icon-youtube-play"></div></div></div>`;
} else if (v.type === 'a') {
return `<img src='${recordIcon}' serverId="${v.serverId}" symbol='${s}' associatedAudio='${v.url}' class='audio-record'/>`;
} else if (v.type === 'f') {
return `<a href="${resolveMediaUrl(v.url!)}" serverId="${v.serverId}" target="_blank" download><img src='${fileIcon}' symbol='${s}' class='uploading-file'/></a>`;
} else if (v.type === 'g') {
// giphy api sometimes doesn't contain webp, so it can be null
return `<img serverId="${v.serverId}" src='${webpSupported && v.preview? v.preview : v.url}' ${v.preview ? `webp="${v.preview}"`: ''} url="${v.url}" symbol='${s}' class='${PASTED_IMG_CLASS} ${PASTED_GIPHY_CLASS}'/>`;
} else {
logger.error('Invalid type {}', v.type)();
}
}
return s; // if it's absent in files, it could be also in tags so return it. (don't replace )
});
}
return html;
}
let uniqueTagId = 1;
function getUniqueTagId() {
return uniqueTagId++;
}
export function createTag(user: UserModel) {
let a = document.createElement('span');
const style = document.createElement('style');
style.type = 'text/css';
let id = `usertag${getUniqueTagId()}`;
style.innerHTML = ` #${id}:after { content: '@${user.user}'}`;
document.getElementsByTagName('head')[0].appendChild(style);
a.id = id;
a.setAttribute('user-id', String(user.id));
a.className = 'tag-user';
return a;
}
export function replaceCurrentWord(containerEl: HTMLElement, replacedTo: HTMLElement) {
containerEl.focus();
let range;
let sel = window.getSelection()!;
if (sel.rangeCount === 0) {
logger.error('Can\'t place tag, rangeCount is 0')();
return
}
range = sel.getRangeAt(0).cloneRange()!;
range.collapse(true);
range.setStart(containerEl, 0);
let words = range.toString().trim().split(' ');
let lastWord = words[words.length - 1];
if (!lastWord) {
logger.error('Can\'t place tag, last word not found')();
}
logger.log('replace word ' + lastWord)();
/* Find word start and end */
let data = (range.endContainer as any).data;
if (!data) {
logger.error('Can\'t place tag, Selected word data is null')();
return
}
let wordStart = data.lastIndexOf(lastWord);
let wordEnd = wordStart + lastWord.length;
logger.log('pos: (' + wordStart + ', ' + wordEnd + ')')();
range.setStart(range.endContainer, wordStart);
range.setEnd(range.endContainer, wordEnd);
range.deleteContents();
range.insertNode(replacedTo);
// delete That specific word and replace if with resultValue
range.setStartAfter(replacedTo);
let textAfter = document.createTextNode(' ');
range.insertNode(textAfter);
range.setStartAfter(textAfter);
sel.removeAllRanges();
sel.addRange(range);
}
export function pasteNodeAtCaret(img: Node, div: HTMLElement) {
div.focus();
const sel = window.getSelection();
if (sel) {
let range = sel.getRangeAt(0);
range.deleteContents();
// Range.createContextualFragment() would be useful here but is
// non-standard and not supported in all browsers (IE9, for one)
const frag = document.createDocumentFragment();
frag.appendChild(img);
range.insertNode(frag);
// Preserve the selection
range = range.cloneRange();
range.setStartAfter(img);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
} else {
div.appendChild(img);
logger.warn(`Can't handle selection`)();
}
}
export function pasteHtmlAtCaret(html: string, div: HTMLElement) {
const divOuter = document.createElement('div');
divOuter.innerHTML = html;
const img: Node | null = divOuter.firstChild;
if (!img) {
throw Error(`Can't paste image`);
}
pasteNodeAtCaret(img, div);
}
export function setVideoEvent(e: HTMLElement) {
const r: NodeListOf<HTMLElement> = e.querySelectorAll('.video-player');
forEach(r, e => {
const querySelector: HTMLElement = <HTMLElement>e.querySelector('.icon-youtube-play')!;
const url: string = e.getAttribute('associatedVideo')!;
logger.debug('Embedding video url {}', url)();
querySelector.onclick = function (event) {
const video = document.createElement('video');
video.setAttribute('controls', '');
video.className = 'video-player-ready';
logger.debug('Replacing video url {}', url)();
video.src = resolveMediaUrl(url);
e.parentNode!.replaceChild(video, e);
video.play();
};
});
}
export function setAudioEvent(e: HTMLElement) {
const r: NodeListOf<HTMLElement> = e.querySelectorAll('.audio-record');
forEach<HTMLElement>(r, (e: HTMLElement) => {
e.onclick = function (event) {
const associatedAudio: string = e.getAttribute('associatedAudio')!;
const url: string = resolveMediaUrl(associatedAudio);
const audio = document.createElement('audio');
audio.setAttribute('controls', '');
audio.className = 'audio-player-ready';
logger.debug('Replacing audio url {}', url)();
audio.src = url;
e.parentNode!.replaceChild(audio, e);
audio.play();
};
});
}
export function setImageFailEvents(e: HTMLElement, bus: Vue) {
const r = e.querySelectorAll('img');
for (let i = 0; i < r.length; i++) {
(function (img) {
img.onerror = function () {
this.className += ' failed';
};
img.onload = function () {
bus.$emit('scroll');
};
})(r[i]);
}
}
function getTime(time: string): number {
let start = 0;
if (time) {
const res = yotubeTimeRegex.exec(time);
if (res) {
if (res[1]) {
start += parseInt(res[1]) * 3600;
}
if (res[2]) {
start += parseInt(res[2]) * 60;
}
if (res[3]) {
start += parseInt(res[3]);
}
if (res[4]) {
start += parseInt(res[4]);
}
}
}
return start;
}
export function setYoutubeEvent(e: HTMLElement) {
const r: NodeListOf<HTMLElement> = e.querySelectorAll('.youtube-player');
forEach(r, (a: HTMLElement) => {
const querySelector: HTMLElement = <HTMLElement>a.querySelector('.icon-youtube-play')!;
const id = a.getAttribute('data-id');
logger.debug('Embedding youtube view {}', id)();
querySelector.onclick = function (event: MouseEvent) {
const iframe = document.createElement('iframe');
let time: string = getTime(e.getAttribute('data-time')!).toString();
if (time) {
time = '&start=' + time;
} else {
time = '';
}
const src = `https://www.youtube.com/embed/${id}?autoplay=1${time}`;
iframe.setAttribute('src', src);
iframe.setAttribute('frameborder', '0');
iframe.className = 'video-player-ready';
logger.log('Replacing youtube url {}', src)();
iframe.setAttribute('allowfullscreen', '1');
e.parentNode!.replaceChild(iframe, e);
};
});
}
export function stopVideo(stream: MediaStream | null) {
if (stream) {
logger.debug('Stopping stream {}', stream)();
if (stream.stop) {
stream.stop();
} else {
stream.getTracks().forEach(e => e.stop());
}
}
}
function setBlobName(blob: Blob) {
if (!blob.name && blob.type.indexOf('/') > 1) {
blob.name = '.' + blob.type.split('/')[1];
}
}
function blobToImg(blob: Blob) {
const img = document.createElement('img');
img.className = PASTED_IMG_CLASS;
const src = URL.createObjectURL(blob);
img.src = src;
setBlobName(blob);
savedFiles[src] = blob;
return img;
}
export function pasteBlobToContentEditable(blob: Blob, textArea: HTMLElement) {
const img = blobToImg(blob);
textArea.appendChild(img);
}
export function pasteBlobVideoToTextArea(file: Blob, textArea: HTMLElement, videoType: string, errCb: Function) {
const video = document.createElement('video');
if (video.canPlayType(file.type)) {
video.autoplay = false;
const src = URL.createObjectURL(file);
video.loop = false;
video.addEventListener('loadeddata', function () {
tmpCanvasContext.canvas.width = video.videoWidth;
tmpCanvasContext.canvas.height = video.videoHeight;
tmpCanvasContext.drawImage(video, 0, 0);
tmpCanvasContext.canvas.toBlob(
function (blob) {
const img = document.createElement('img');
if (!blob) {
logger.error(`Failed to render 1st frame image for file ${file.name}, setting videoIcon instead`)();
img.src = videoIcon as string;
} else {
const url = URL.createObjectURL(blob);
savedFiles[url] = blob;
blob.name = '.jpg';
img.src = url;
}
img.className = PASTED_IMG_CLASS;
img.setAttribute('videoType', videoType);
img.setAttribute('associatedVideo', src);
savedFiles[src] = file;
pasteNodeAtCaret(img, textArea);
},
'image/jpeg',
0.95
);
}, false);
video.src = src;
} else {
errCb(`Browser doesn't support playing ${file.type}`);
}
}
export function pasteBlobAudioToTextArea(file: Blob, textArea: HTMLElement) {
const img = document.createElement('img');
const associatedAudio = URL.createObjectURL(file);
img.setAttribute('associatedAudio', associatedAudio);
img.className = `audio-record ${PASTED_IMG_CLASS}`;
setBlobName(file);
savedFiles[associatedAudio] = file;
img.src = recordIcon as string;
pasteNodeAtCaret(img, textArea);
}
export function pasteBlobFileToTextArea(file: Blob, textArea: HTMLElement) {
const img = document.createElement('img');
const associatedFile = URL.createObjectURL(file);
img.setAttribute('associatedFile', associatedFile);
img.className = `uploading-file ${PASTED_IMG_CLASS}`;
setBlobName(file);
savedFiles[associatedFile] = file;
img.src = fileIcon as string;
pasteNodeAtCaret(img, textArea);
}
export function pasteFileToTextArea(file: File, textArea: HTMLElement, errCb: Function) {
if (file.size > 90_000_000) {
errCb(`Can't upload file greater than 90MB`);
} else {
pasteBlobFileToTextArea(file, textArea);
}
}
export function pasteImgToTextArea(file: File, textArea: HTMLElement, errCb: Function) {
if (file.type.indexOf('image') >= 0) {
const img = blobToImg(file);
pasteNodeAtCaret(img, textArea);
} else if (file.type.indexOf('video') >= 0) {
pasteBlobVideoToTextArea(file, textArea, 'v', errCb);
} else {
errCb(`Pasted file type ${file.type}, which is not an image`);
}
}
export function highlightCode(element: HTMLElement) {
const s = element.querySelectorAll('pre');
if (s.length) {
import(/* webpackChunkName: "highlightjs" */ 'highlightjs').then(hljs => {
for (let i = 0; i < s.length; i++) {
hljs.highlightBlock(s[i]);
}
});
}
}
function nextChar(c: string): string {
return String.fromCharCode(c.charCodeAt(0) + 1);
}
export function getMessageData(userMessage: HTMLElement, messageModel?: MessageModel): MessageDataEncode {
let currSymbol: string = messageModel?.symbol ?? '\u3500';
const files: Record<string, FileModel>| null = {}; // return array from nodeList
const images = userMessage.querySelectorAll(`.${PASTED_IMG_CLASS}`);
forEach(images, img => {
let oldSymbol = img.getAttribute('symbol');
let src = img.getAttribute('src');
const assVideo = img.getAttribute('associatedVideo') ?? null;
const assAudio = img.getAttribute('associatedAudio') ?? null;
const assFile = img.getAttribute('associatedFile') ?? null;
const serverId = parseInt(img.getAttribute('serverId')!);
const asGiphy = img.className.indexOf(PASTED_GIPHY_CLASS) >= 0 ? img.getAttribute('url') : null;
const asGiphyPreview = img.className.indexOf(PASTED_GIPHY_CLASS) >= 0 ? img.getAttribute('webp') : null;
const videoType: BlobType = img.getAttribute('videoType')! as BlobType;
let elSymbol = oldSymbol;
if (!elSymbol) {
currSymbol = nextChar(currSymbol);
elSymbol = currSymbol;
}
const textNode = document.createTextNode(elSymbol);
img.parentNode!.replaceChild(textNode, img);
if (messageModel?.files) {
let fm: FileModel = messageModel.files[elSymbol];
if (fm && !fm.sending) {
files[elSymbol] = fm;
return;
}
}
let type: BlobType;
if (videoType) {
type = videoType;
} else if (assAudio) {
type = 'a'
} else if (assFile) {
type = 'f'
} else if (asGiphy) {
type = 'g'
} else {
type = 'i'
}
let url: string;
if (assAudio) {
url = assAudio;
} else if (assFile) {
url = assFile;
} else if (assVideo) {
url = assVideo;
} else if (asGiphy) {
url = asGiphy;
} else {
url = src!;
}
let preview: string|null = null;
if (assVideo && src !== videoIcon) {
preview = src;
} else if (asGiphyPreview) {
preview = asGiphyPreview;
} else if (src !== videoIcon) {
preview = assVideo;
}
files[elSymbol] = {
type,
preview,
url,
serverId: serverId || null,
sending: !asGiphy, // if it's not giphy, we need to transfer it to backend. giphy as absolute url already
fileId: null,
previewFileId: null,
}
});
let tags: Record<string, number> = {};
forEach(userMessage.querySelectorAll(`.tag-user`), img => {
currSymbol = nextChar(currSymbol);
tags[currSymbol] = parseInt(img.getAttribute('user-id')!);
/// https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/replaceWith
img.replaceWith(document.createTextNode(currSymbol));
});
userMessage.innerHTML = userMessage.innerHTML.replace(/<img[^>]*symbol="([^"]+)"[^>]*>/g, '$1');
let messageContent: string | null = typeof userMessage.innerText !== 'undefined' ? userMessage.innerText : userMessage.textContent;
messageContent = !messageContent || /^\s*$/.test(messageContent) ? null : messageContent;
if (messageContent) {
messageContent = messageContent.trim();
}
userMessage.innerHTML = '';
return {files, messageContent, currSymbol, tags};
} | the_stack |
import { BigNumber, Signer, providers, utils } from "ethers";
import PriorityQueue from "p-queue";
import {
createLoggingContext,
delay,
getUuid,
jsonifyError,
Logger,
NxtpError,
RequestContext,
} from "@connext/nxtp-utils";
import interval from "interval-promise";
import {
BadNonce,
TransactionReplaced,
TransactionReverted,
OperationTimeout,
TransactionBackfilled,
InitialSubmitFailure,
TransactionProcessingError,
NotEnoughConfirmations,
TransactionAlreadyKnown,
Gas,
WriteTransaction,
OnchainTransaction,
TransactionBuffer,
} from "./shared";
import { ChainConfig } from "./config";
import { RpcProviderAggregator } from "./rpcProviderAggregator";
export type DispatchCallbacks = {
onSubmit: (transaction: OnchainTransaction) => void;
onMined: (transaction: OnchainTransaction) => void;
onConfirm: (transaction: OnchainTransaction) => void;
onFail: (transaction: OnchainTransaction) => void;
};
// TODO: Merge responsibility with TransactionService. Should not extend ProviderAggregator.
/**
* @classdesc Transaction lifecycle manager.
*
*/
export class TransactionDispatch extends RpcProviderAggregator {
private loopsRunning = false;
// Based on default per account rate limiting on geth.
// TODO: Make this a configurable value, since the dev may be able to implement or may be using a custom geth node.
static MAX_INFLIGHT_TRANSACTIONS = 64;
// Buffer of in-flight transactions waiting to get 1 confirmation.
private inflightBuffer: TransactionBuffer;
// TODO: Cap this buffer as well. # of inflight txs max * # of confirmations needed seems reasonable as a max # of waiting-for-x-confirmations queue length
// Buffer of mined transactions waiting for X confirmations.
private minedBuffer: TransactionBuffer;
private readonly queue = new PriorityQueue({ concurrency: 1 });
// The current nonce of the signer is tracked locally here. It will be used for comparison
// to the nonce we get back from the pending transaction count call to our providers.
// NOTE: Should not be accessed outside of the helper methods, getNonce and incrementNonce.
private nonce = 0;
private lastReceivedTxCount = -1;
/**
* Transaction lifecycle management class. Extends ChainRpcProvider, thus exposing all provider methods
* through this class.
*
* @param logger Logger used for logging.
* @param signer Signer instance or private key used for signing transactions.
* @param chainId The ID of the chain for which this class's providers will be servicing.
* @param chainConfig Configuration for this specified chain, including the providers we'll
* be using for it.
* @param config The shared TransactionServiceConfig with general configuration.
*
* @throws ChainError.reasons.ProviderNotFound if no valid providers are found in the
* configuration.
*/
constructor(
logger: Logger,
public readonly chainId: number,
config: ChainConfig,
signer: string | Signer,
private readonly callbacks: DispatchCallbacks,
startLoops = true,
) {
super(logger, chainId, config, signer);
this.inflightBuffer = new TransactionBuffer(logger, TransactionDispatch.MAX_INFLIGHT_TRANSACTIONS, {
name: "INFLIGHT",
chainId: this.chainId,
});
this.minedBuffer = new TransactionBuffer(logger, undefined, {
name: "MINED",
chainId: this.chainId,
});
if (startLoops) {
this.startLoops();
}
}
/**
* Start background loops for mining and confirming transactions.
*/
public startLoops() {
if (!this.loopsRunning) {
this.loopsRunning = true;
// Use interval promise to make sure loop iterations don't overlap.
interval(async () => await this.mineLoop(), 2_000);
interval(async () => await this.confirmLoop(), 2_000);
// Starts an interval loop that synchronizes the provider every configured interval.
interval(async () => await this.syncProviders(), this.config.syncProvidersInterval);
}
}
/**
* Check for mined transactions in the inflight buffer; if any are present it will wait for 1 confirmation
* and then push the transaction to the mined buffer for each one in FIFO order.
*/
private async mineLoop() {
const { requestContext, methodContext } = createLoggingContext(this.mineLoop.name);
let transaction: OnchainTransaction | undefined = undefined;
try {
while (this.inflightBuffer.length > 0) {
// Shift the first transaction from the buffer and get it mined.
transaction = this.inflightBuffer.shift();
if (!transaction) {
// This shouldn't happen, but this block is a necessity for compilation.
return;
}
const meta = {
shouldResubmit: false,
shouldBump: false,
};
while (!transaction.didMine && !transaction.error) {
try {
if (meta.shouldResubmit) {
if (meta.shouldBump) {
await this.bump(transaction);
}
await this.submit(transaction);
}
await this.mine(transaction);
this.minedBuffer.push(transaction);
break;
} catch (error) {
this.logger.debug("Received error waiting for transaction to be mined.", requestContext, methodContext, {
chainId: this.chainId,
txsId: transaction.uuid,
error,
});
if (error.type === OperationTimeout.type || error.type === BadNonce.type) {
// Check to see if the transaction did indeed make it to chain.
const responses = await this.getTransaction(transaction);
if (responses.every((response) => response === null)) {
// If all responses are null, then this transaction was not found / does not exist.
this.logger.warn("Transaction was not found on chain!", requestContext, methodContext, {
chainId: this.chainId,
transaction: transaction.loggable,
responses,
});
// Check to see if this nonce has already been mined.
const transactionCount = await this.getTransactionCount("latest");
if (transactionCount > transaction.nonce) {
// Transaction must have been replaced by another.
transaction.error = new TransactionBackfilled({
latestTransactionCount: transactionCount,
nonce: transaction.nonce,
});
} else {
// This transaction does not exist, and this nonce is still the blockade. We should
// resubmit immediately using the same nonce without bumping.
meta.shouldResubmit = true;
meta.shouldBump = false;
}
} else {
// Transaction was found on chain.
const response = responses.find((response) => response !== null);
if (response?.confirmations && response?.confirmations > 0) {
// Transaction was mined! We should immediately continue to the next loop without
// resubmitting and let the mine function get the receipt.
meta.shouldResubmit = false;
meta.shouldBump = false;
continue;
}
// Transaction was found, but it's not going through. We should bump the gas and submit
// a replacement to speed things up.
meta.shouldResubmit = true;
meta.shouldBump = true;
}
} else if (
error.type === TransactionReverted.type &&
error.reason === TransactionReverted.reasons.InsufficientFunds
) {
/**
* If we get an insufficient funds error during a resubmit, we should log this critical
* alert but continue to try to mine whatever txs we've sent so far, on the basis that
* the router owner will eventually refill the account (and we'll eventually) be able to
* bump.
*
* Set shouldResubmit to false; next time around it will only attempt to mine. Should the
* mine timeout again, it will go back to attempting to resubmit - allowing us to a chance
* to respond to a refill for the gas money for this signer.
*/
this.logger.error(
"SIGNER HAS INSUFFICIENT FUNDS TO SUBMIT TRANSACTION (FOR GAS BUMP).",
requestContext,
methodContext,
jsonifyError(error),
{
chainId: this.chainId,
transaction: transaction.loggable,
},
);
meta.shouldResubmit = false;
meta.shouldBump = false;
} else {
transaction.error = error;
}
}
}
// If any errors occurred, fail that transaction and move on.
if (transaction.error) {
await this.fail(transaction);
}
}
} catch (error) {
this.logger.error("Error in mine loop.", requestContext, methodContext, jsonifyError(error), {
handlingTransaction: transaction ? transaction.loggable : undefined,
});
}
}
/**
* Check for mined transactions in the mined buffer; if any are present it will wait for the target confirmations for each
* one in FIFO order.
*/
private async confirmLoop() {
const { requestContext, methodContext } = createLoggingContext(this.confirmLoop.name);
const promises: Promise<void>[] = [];
while (this.minedBuffer.length > 0) {
const transaction = this.minedBuffer.shift()!;
promises.push(
new Promise<void>((resolve) => {
// Checks to make sure we hit the target number of confirmations.
this.confirm(transaction)
.then(() => resolve())
.catch((error) => {
this.logger.debug(
"Received error waiting for transaction to be confirmed:",
requestContext,
methodContext,
{
chainId: this.chainId,
txsId: transaction.uuid,
error,
},
);
transaction.error = error;
this.fail(transaction).then(() => resolve());
});
}),
);
}
await Promise.all(promises);
}
/**
* Determine the nonce assignment for a transaction based on the current state, as well as what nonces have already
* been attempted, etc.
* @remarks
* This should only ever be called within the queue in the send() method.
*
* @param attemptedNonces - Array of nonces that have already been attempted, in order of attempt.
* @param error - (optional) The last error that was thrown when attempting to send an initial transaction.
* @param previousNonce - (optional) The previous nonce assigned. Should only be defined if the error argument is also
* passed in.
* @returns object - containing nonce, backfill, and transactionCount.
*/
private async determineNonce(
attemptedNonces: number[],
error?: BadNonce,
): Promise<{ nonce: number; backfill: boolean; transactionCount: number }> {
const transactionCount = await this.getTransactionCount("latest");
// Set the nonce initially to the last used nonce. If no nonce has been used yet (i.e. this is the first initial send attempt),
// set to whichever value is higher: local nonce or txcount. This should almost always be our local nonce, but often both will be the same.
let nonce =
attemptedNonces.length > 0 ? attemptedNonces[attemptedNonces.length - 1] : Math.max(this.nonce, transactionCount);
// If backfill conditions are met, then we should instead set the nonce to the backfill value.
const backfill = transactionCount < this.lastReceivedTxCount;
if (backfill) {
// If for some reason the transaction count we received from the provider is lower than the last once we received (meaning nonce
// backtracked), we should start at the lower value instead. This will backfill any nonce gaps that may have been left behind
// as a result of provider connection issues and/or reorgs.
// NOTE: If this backfill replaces an "existing" faulty transaction (i.e. one that the provider doesn't actually have in mempool),
// the push operation to the inflight buffer we do in the send method will handle replacing/killing the faulty transaction.
nonce = transactionCount;
} else if (error) {
if (
error.reason === BadNonce.reasons.NonceExpired ||
// TODO: Should replacement underpriced result in us raising the gas price and attempting to override the transaction?
// Or should we treat the nonce as expired?
error.reason === BadNonce.reasons.ReplacementUnderpriced
) {
// If we are here, likely one of following has occurred:
// 1. Signer used outside of this class to send tx (should never happen).
// 2. The router was rebooted, and our nonce has not yet caught up with that in the current pending pool of txs.
// 3. We just performed a backfill operation, and are now catching back up to the *actual* nonce.
if (!attemptedNonces.includes(transactionCount)) {
// If we have not tried mined tx count, let's try that next.
nonce = transactionCount;
} else {
// If we haven't tried the up-to-date tx count (latest or pending), let's try that next.
const pendingTransactionCount = await this.getTransactionCount("pending");
if (!attemptedNonces.includes(pendingTransactionCount)) {
nonce = pendingTransactionCount;
} else {
// If mined and pending tx count fail, we should just increment the nonce by 1 until we get a nonce we haven't tried.
// This is sort of a spray-and-pray solution, but it's the best we can do when providers aren't giving us more reliable info.
// Set the nonce to the lowest/min value in the array of attempted nonce first.
nonce = Math.min(...attemptedNonces);
while (attemptedNonces.includes(nonce)) {
nonce++;
}
}
}
} else if (error.reason === BadNonce.reasons.NonceIncorrect) {
// It's unknown whether nonce was too low or too high. For safety, we're going to set the nonce to the latest transaction count
// and retry (continually). Eventually the transaction count will catch up to / converge on the correct number.
// NOTE: This occasionally happens because a provider falls behind in terms of the current mempool and hasn't registered a tx yet.
// Regardless of whether we've already attempted this nonce, we're going to try it again.
nonce = transactionCount;
}
}
// Set lastReceivedTxCount - this will be used in future calls of this method to determine if we need to backtrack nonce (i.e. backfill).
this.lastReceivedTxCount = transactionCount;
attemptedNonces.push(nonce);
return { nonce, backfill, transactionCount };
}
/// LIFECYCLE
/**
*
* @param minTx - Minimum transaction params needed to form a transaction.
* @param context - Request context object used for logging.
*
* @returns A list of receipts or errors that occurred for each.
*/
public async send(minTx: WriteTransaction, context: RequestContext): Promise<providers.TransactionReceipt> {
const method = this.send.name;
const { requestContext, methodContext } = createLoggingContext(method, context);
const txsId = getUuid();
this.logger.debug("Method start", requestContext, methodContext, {
chainId: this.chainId,
txsId,
});
const result = await this.queue.add(
async (): Promise<{ value: OnchainTransaction | NxtpError; success: boolean }> => {
try {
// Wait until there's room in the buffer.
if (this.inflightBuffer.isFull) {
this.logger.warn("Inflight buffer is full! Waiting in queue to send.", requestContext, methodContext, {
chainId: this.chainId,
bufferLength: this.inflightBuffer.length,
txsId,
});
while (this.inflightBuffer.isFull) {
// TODO: This delay was raised to help alleviate a "trickling bottleneck" when the inflight buffer remains full for
// an extended period. An alternative: maybe we should wait until the buffer falls *below* a certain threshold?
await delay(10_000);
}
}
// Estimate gas here will throw if the transaction is going to revert on-chain for "legit" reasons. This means
// that, if we get past this method, we can *generally* assume that the transaction will go through on submit - although it's
// still possible to revert due to a state change below.
const attemptedNonces: number[] = [];
const [gasLimit, gasPrice, nonceInfo] = await Promise.all([
this.estimateGas(minTx),
this.getGasPrice(requestContext),
this.determineNonce(attemptedNonces),
]);
let { nonce, backfill, transactionCount } = nonceInfo;
// TODO: Remove hardcoded (exposed gasLimitInflation config var should replace this).
const gas: Gas = {
limit: gasLimit,
price: gasPrice,
};
if (this.chainId === 42161) {
gas.limit = BigNumber.from(10_000_000);
}
// Here we are going to ensure our initial submit gets through at the correct nonce. If all goes well, it should
// go through on the first try.
let transaction: OnchainTransaction | undefined = undefined;
let lastErrorReceived: Error | undefined = undefined;
// It should never take more than MAX_INFLIGHT_TRANSACTIONS + 2 iterations to get the transaction through.
let iterations = 0;
while (
iterations < TransactionDispatch.MAX_INFLIGHT_TRANSACTIONS + 2 &&
(!transaction || !transaction.didSubmit)
) {
iterations++;
// Create a new transaction instance to track lifecycle. We will be submitting below.
transaction = new OnchainTransaction(
requestContext,
minTx,
nonce,
gas,
{
confirmationTimeout: this.config.confirmationTimeout,
confirmationsRequired: this.config.confirmations,
},
txsId,
);
this.logger.debug("Sending initial submit for transaction.", requestContext, methodContext, {
chainId: this.chainId,
iterations,
lastErrorReceived,
transaction: transaction.loggable,
nonceInfo: {
attemptedNonces,
backfill: backfill ?? undefined,
transactionCount,
localNonce: this.nonce,
assignedNonce: nonce,
},
});
try {
if (backfill) {
const replaced = this.inflightBuffer.getTxByNonce(transaction.nonce);
// Lets make sure we only replace/backfill a transaction that did not actually make it to chain.
if (replaced) {
transaction.gas.price = replaced.gas.price;
}
}
await this.submit(transaction);
} catch (error) {
if (error.type === BadNonce.type) {
lastErrorReceived = error.reason;
({ nonce, backfill, transactionCount } = await this.determineNonce(attemptedNonces, error));
continue;
} else if (error.type === TransactionAlreadyKnown.type) {
// Ignore, indicates provider already has this tx indexed, meaning it was sent properly.
break;
}
// This could be a reverted error, etc.
throw error;
}
}
if (!transaction || transaction.responses.length === 0) {
throw new InitialSubmitFailure(
"Transaction never submitted: exceeded maximum iterations in initial submit loop.",
);
}
// Push submitted transaction to inflight buffer.
this.inflightBuffer.push(transaction);
// Increment the successful nonce, and assign our local nonce to that value.
this.nonce = nonce + 1;
return { value: transaction, success: true };
} catch (error) {
return { value: error, success: false };
}
},
);
if (!result.success) {
throw result.value;
}
const transaction = result.value as OnchainTransaction;
// Wait for transaction to be picked up by the mine and confirm loops and closed out.
while (!transaction.didFinish && !transaction.error) {
// TODO: Use wait, and wait a designated number of blocks if possible to optimize!
await delay(1_000);
}
if (transaction.error) {
// If a transaction fails and it didn't get mined, we may need to backfill its nonce.
if (!transaction.didMine) {
this.logger.warn(
"Transaction failed, and was never mined. Rewinding local nonce to this transaction's nonce for backfill.",
requestContext,
methodContext,
{
chainId: this.chainId,
transaction: transaction.loggable,
txsId,
},
);
this.nonce = transaction.nonce;
}
throw transaction.error;
}
if (!transaction.receipt) {
throw new TransactionProcessingError(TransactionProcessingError.reasons.NoReceipt, method);
}
return transaction.receipt;
}
/**
* Submit an OnchainTransaction to the chain.
*
* @param transaction - OnchainTransaction object to modify based on submit result.
*/
private async submit(transaction: OnchainTransaction) {
const method = this.submit.name;
const { requestContext, methodContext } = createLoggingContext(method, transaction.context);
this.logger.debug("Method start", requestContext, methodContext, {
chainId: this.chainId,
txsId: transaction.uuid,
});
// Check to make sure we haven't already mined this transaction.
if (transaction.didFinish) {
throw new TransactionProcessingError(TransactionProcessingError.reasons.SubmitOutOfOrder, method);
}
// Increment transaction # attempts made.
transaction.attempt++;
// Send the tx.
try {
const response = await this.sendTransaction(transaction);
// Add this response to our local response history.
if (transaction.hashes.includes(response.hash)) {
// Duplicate response? This should never happen.
throw new TransactionProcessingError(TransactionProcessingError.reasons.DuplicateHash, method, {
chainId: this.chainId,
response,
transaction: transaction.loggable,
});
}
transaction.responses.push(response);
this.logger.info(`Tx submitted.`, requestContext, methodContext, {
chainId: this.chainId,
response: {
hash: response.hash,
nonce: response.nonce,
gasPrice: response.gasPrice ? utils.formatUnits(response.gasPrice, "gwei") : undefined,
gasLimit: response.gasLimit.toString(),
},
transaction: transaction.loggable,
});
this.callbacks.onSubmit(transaction);
} catch (error) {
// If we end up with an error, it should be thrown here. But first, log loudly if we get an insufficient
// funds error.
if (
error.type === TransactionReverted.type &&
(error as TransactionReverted).reason === TransactionReverted.reasons.InsufficientFunds
) {
this.logger.error(
"SIGNER HAS INSUFFICIENT FUNDS TO SUBMIT TRANSACTION.",
requestContext,
methodContext,
jsonifyError(error),
{
chainId: this.chainId,
transaction: transaction.loggable,
},
);
}
throw error;
}
}
/**
* Wait for an OnchainTransaction to be mined (1 confirmation).
*
* @param transaction - OnchainTransaction object to modify based on mine result.
*/
private async mine(transaction: OnchainTransaction) {
const method = this.mine.name;
const { requestContext, methodContext } = createLoggingContext(method, transaction.context);
this.logger.debug("Method start", requestContext, methodContext, {
chainId: this.chainId,
txsId: transaction.uuid,
});
// Ensure we've submitted at least 1 tx.
if (!transaction.didSubmit) {
throw new TransactionProcessingError(TransactionProcessingError.reasons.MineOutOfOrder, method, {
chainId: this.chainId,
transaction: transaction.loggable,
});
}
try {
// Get receipt for tx with at least 1 confirmation. If it times out (using default, configured timeout),
// it will throw a TransactionTimeout error.
const receipt = await this.confirmTransaction(transaction, 1);
// Sanity checks.
if (receipt.status === 0) {
// This should never occur. We should always get a TransactionReverted error in this event.
throw new TransactionProcessingError(TransactionProcessingError.reasons.DidNotThrowRevert, method, {
chainId: this.chainId,
receipt,
transaction: transaction.loggable,
});
} else if (receipt.confirmations < 1) {
// Again, should never occur.
throw new TransactionProcessingError(TransactionProcessingError.reasons.InsufficientConfirmations, method, {
chainId: this.chainId,
receipt: transaction.receipt,
confirmations: receipt.confirmations,
transaction: transaction.loggable,
});
}
// Set transaction's receipt.
transaction.receipt = receipt;
} catch (_error) {
if (_error.type === TransactionReplaced.type) {
const error = _error as TransactionReplaced;
this.logger.debug(
"Received TransactionReplaced error - but this may be expected behavior.",
requestContext,
methodContext,
{
chainId: this.chainId,
error,
transaction: transaction.loggable,
},
);
// Sanity check.
if (!error.replacement || !error.receipt) {
throw new TransactionProcessingError(TransactionProcessingError.reasons.ReplacedButNoReplacement, method, {
chainId: this.chainId,
replacement: error.replacement,
receipt: error.receipt,
transaction: transaction.loggable,
});
}
// Validate that we've been replaced by THIS transaction (and not an unrecognized transaction).
if (
transaction.responses.length < 2 ||
!transaction.responses.map((response) => response.hash).includes(error.replacement.hash)
) {
throw error;
}
// error.receipt - the receipt of the replacement transaction (a TransactionReceipt)
transaction.receipt = error.receipt;
} else if (_error.type === TransactionReverted.type) {
const error = _error as TransactionReverted;
// NOTE: This is the official receipt with status of 0, so it's safe to say the
// transaction was in fact reverted and we should throw here.
transaction.receipt = error.receipt;
throw error;
} else {
throw _error;
}
}
this.logger.info(`Tx mined.`, requestContext, methodContext, {
chainId: this.chainId,
receipt: {
transactionHash: transaction.receipt.transactionHash,
blockNumber: transaction.receipt.blockNumber,
},
transaction: transaction.loggable,
});
this.callbacks.onMined(transaction);
}
/**
* Makes an attempt to confirm this transaction, waiting up to a designated period to achieve
* a desired number of confirmation blocks. If confirmation times out, throws TimeoutError.
* If all txs, including replacements, are reverted, throws TransactionReverted.
*
* @param transaction - OnchainTransaction object to modify based on confirm result.
*/
private async confirm(transaction: OnchainTransaction) {
const method = this.confirm.name;
const { requestContext, methodContext } = createLoggingContext(method, transaction.context);
this.logger.debug("Method start", requestContext, methodContext, {
chainId: this.chainId,
txsId: transaction.uuid,
});
// Ensure we've submitted a tx.
if (!transaction.didSubmit) {
throw new TransactionProcessingError(TransactionProcessingError.reasons.MineOutOfOrder, method, {
chainId: this.chainId,
transaction: transaction.loggable,
});
}
if (!transaction.receipt) {
throw new TransactionProcessingError(TransactionProcessingError.reasons.ConfirmOutOfOrder, method, {
chainId: this.chainId,
receipt: transaction.receipt === undefined ? "undefined" : transaction.receipt,
transaction: transaction.loggable,
});
}
// Here we wait for the target confirmations.
// TODO: Ensure we are comfortable with how this timeout period is calculated.
const timeout = this.config.confirmationTimeout * this.config.confirmations * 2;
let receipt: providers.TransactionReceipt;
try {
receipt = await this.confirmTransaction(transaction, this.config.confirmations, timeout);
} catch (error) {
this.logger.error(
"Did not get enough confirmations for a *mined* transaction! Did a re-org occur?",
requestContext,
methodContext,
jsonifyError(error),
{
chainId: this.chainId,
transaction: transaction.loggable,
confirmations: transaction.receipt.confirmations,
confirmationsRequired: this.config.confirmations,
},
);
// No other errors should normally occur during this confirmation attempt. This could occur during a reorg.
throw new NotEnoughConfirmations(
this.config.confirmations,
transaction.receipt.transactionHash,
transaction.receipt.confirmations,
{
method,
chainId: this.chainId,
receipt: transaction.receipt,
error: transaction.error,
transaction: transaction.loggable,
},
);
}
// Sanity checks.
if (receipt.status === 0) {
// This should never occur. We should always get a TransactionReverted error in this event : and that error should
// have been thrown in the mine() method.
throw new TransactionProcessingError(TransactionProcessingError.reasons.DidNotThrowRevert, method, {
chainId: this.chainId,
receipt,
transaction: transaction.loggable,
});
}
transaction.receipt = receipt;
this.logger.info(`Tx confirmed.`, requestContext, methodContext, {
chainId: this.chainId,
receipt: {
transactionHash: transaction.receipt.transactionHash,
confirmations: transaction.receipt.confirmations,
blockNumber: transaction.receipt.blockNumber,
},
transactionExecutionTime: Date.now() - transaction.timestamp,
transaction: transaction.loggable,
});
this.callbacks.onConfirm(transaction);
}
/**
* Bump the gas price for this tx up by the configured percentage.
*
* @param transaction - OnchainTransaction object to modify based on bump result.
*/
public async bump(transaction: OnchainTransaction) {
const { requestContext, methodContext } = createLoggingContext(this.bump.name, transaction.context);
const currentGasPrice = (transaction.gas.price ?? transaction.gas.maxPriorityFeePerGas)!;
if (
transaction.bumps >= transaction.hashes.length ||
currentGasPrice.gte(BigNumber.from(this.config.gasPriceMaximum))
) {
// If we've already bumped this tx but it's failed to resubmit, we should return here without bumping.
// The number of gas bumps we've done should always be less than the number of txs we've submitted.
this.logger.warn("Bump skipped.", requestContext, methodContext, {
chainId: this.chainId,
bumps: transaction.bumps,
gasPrice: utils.formatUnits(currentGasPrice, "gwei"),
gasMaximum: utils.formatUnits(this.config.gasPriceMaximum, "gwei"),
});
return;
}
transaction.bumps++;
// TODO: EIP-1559 support.
// Get the current gas baseline price, in case it has changed drastically in the last block.
let updatedGasPrice: BigNumber;
try {
updatedGasPrice = await this.getGasPrice(requestContext, false);
} catch {
updatedGasPrice = BigNumber.from(this.config.gasPriceMinimum);
}
const determinedBaseline = updatedGasPrice.gt(currentGasPrice) ? updatedGasPrice : currentGasPrice;
// Scale up gas by percentage as specified by config.
if (transaction.type === 0) {
transaction.gas.price = determinedBaseline
.add(determinedBaseline.mul(this.config.gasPriceReplacementBumpPercent).div(100))
.add(1);
} else {
transaction.gas.maxPriorityFeePerGas = determinedBaseline
.add(determinedBaseline.mul(this.config.gasPriceReplacementBumpPercent).div(100))
.add(1);
}
this.logger.info(`Tx bumped.`, requestContext, methodContext, {
chainId: this.chainId,
updatedGasPrice: utils.formatUnits(updatedGasPrice, "gwei"),
previousGasPrice: utils.formatUnits(currentGasPrice, "gwei"),
transaction: transaction.loggable,
});
}
/**
* Handles OnchainTransaction failure.
*
* @param transaction - OnchainTransaction object to read from and modify based on fail event.
*/
private async fail(transaction: OnchainTransaction) {
const { requestContext, methodContext } = createLoggingContext(this.fail.name, transaction.context);
this.logger.error(
"Tx failed.",
requestContext,
methodContext,
jsonifyError(transaction.error ?? new Error("No transaction error was present.")),
{
chainId: this.chainId,
transaction: transaction.loggable,
},
);
this.callbacks.onFail(transaction);
}
} | the_stack |
import * as React from 'react';
import BLeakResults from '../../lib/bleak_results';
import {scaleLinear as d3ScaleLinear, line as d3Line, select as d3Select,
axisBottom, axisLeft, mean, deviation, max, min, zip as d3Zip, range as d3Range} from 'd3';
import {SnapshotSizeSummary} from '../../common/interfaces';
interface HeapGrowthGraphProps {
bleakResults: BLeakResults;
}
interface Line {
name: string;
value: number[];
se?: number[];
}
const BYTES_PER_MB = 1024 * 1024;
function getLine(name: string, sss: SnapshotSizeSummary[][]): Line {
const rv: Line = { name, value: [], se: [] };
const numDataPoints = sss[0].length;
for (let i = 0; i < numDataPoints; i++) {
const values = sss.map((ss) => ss[i].totalSize / BYTES_PER_MB);
rv.value.push(mean(values));
if (values.length > 1) {
rv.se.push(deviation(values) / Math.sqrt(values.length));
}
}
if (rv.se.length === 0) {
rv.se = undefined;
}
return rv;
}
function countNonNull<T>(count: number, a: T[] | T): number {
if (Array.isArray(a)) {
const aCount = a.reduce(countNonNull, 0);
if (aCount !== a.length) {
return count;
} else {
return count + 1;
}
}
if (a) {
return count + 1;
} else {
return count;
}
}
function distillResults(results: BLeakResults): Line[] {
if (!isRankingEvaluationComplete(results)) {
return [{
name: 'No Leaks Fixed',
value: results.heapStats.map((hs) => hs.totalSize / BYTES_PER_MB)
}];
}
const numLeaks = results.rankingEvaluation.leakShare.length;
const zeroLeaksFixed = results.rankingEvaluation.leakShare[0];
const allLeaksFixed = results.rankingEvaluation.leakShare[numLeaks - 1];
// Make sure all of the data is there!
if (!zeroLeaksFixed || !allLeaksFixed || zeroLeaksFixed.reduce(countNonNull, 0) < zeroLeaksFixed.length || allLeaksFixed.reduce(countNonNull, 0) < allLeaksFixed.length) {
throw new Error();
}
// Calculate into a line.
return [getLine('No Leaks Fixed', zeroLeaksFixed), getLine('All Leaks Fixed', allLeaksFixed)];
}
export function isRankingEvaluationComplete(results: BLeakResults): boolean {
const numLeaks = results.rankingEvaluation.leakShare.length;
try {
const zeroLeaksFixed = results.rankingEvaluation.leakShare[0];
const allLeaksFixed = results.rankingEvaluation.leakShare[numLeaks - 1];
// Make sure all of the data is there!
if (!zeroLeaksFixed || !allLeaksFixed || zeroLeaksFixed.reduce(countNonNull, 0) < zeroLeaksFixed.length || allLeaksFixed.reduce(countNonNull, 0) < allLeaksFixed.length) {
return false;
}
return true;
} catch (e) {
return false;
}
}
interface HeapGrowthGraphState {
averageGrowth: number;
averageGrowthSe?: number;
growthReduction: number;
growthReductionSe?: number;
growthReductionPercent: number;
growthReductionPercentSe?: number;
}
export function averageGrowth(data: SnapshotSizeSummary[][]): { mean: number, se?: number } {
// HS => Growth
const growthData = data.map((d, i) => d.slice(1).map((d, j) => (d.totalSize - data[i][j].totalSize) / BYTES_PER_MB));
// Growth => Avg Growth
let avgGrowths: number[] = [];
const iterations = data[0].length;
for (let i = 0; i < iterations; i++) {
avgGrowths.push(mean(growthData.map((d) => d[i])));
}
const se = deviation(avgGrowths.slice(5)) / Math.sqrt(avgGrowths.length - 5);
const meanData = mean(avgGrowths.slice(5));
if (isNaN(se)) {
return {
mean: meanData
};
}
return {
mean: meanData,
se
};
}
export function averageGrowthReduction(avgGrowthNoFixed: { mean: number, se?: number}, allFixed: SnapshotSizeSummary[][]): { mean: number, se?: number, percent: number, percentSe?: number } {
const avgGrowthAllFixed = averageGrowth(allFixed);
const growthReduction = avgGrowthNoFixed.mean - avgGrowthAllFixed.mean;
const percent = 100 * (growthReduction / avgGrowthNoFixed.mean);
if (avgGrowthNoFixed.se !== undefined) {
const growthReductionSe = Math.sqrt(Math.pow(avgGrowthAllFixed.se, 2) + Math.pow(avgGrowthNoFixed.se, 2));
const percentSe = 100 * Math.abs((avgGrowthNoFixed.mean - avgGrowthAllFixed.mean) / avgGrowthNoFixed.mean) * Math.sqrt(Math.pow(growthReductionSe / growthReduction, 2) + Math.pow(avgGrowthNoFixed.se / avgGrowthNoFixed.mean, 2));
return {
mean: growthReduction,
se: growthReductionSe,
percent,
percentSe
};
} else {
return {
mean: growthReduction,
percent
};
}
}
// TODO: Support toggling different size stats, not just totalSize.
export default class HeapGrowthGraph extends React.Component<HeapGrowthGraphProps, HeapGrowthGraphState> {
private _resizeListener = this._updateGraph.bind(this);
public componentWillMount() {
if (this._hasHeapStats()) {
if (isRankingEvaluationComplete(this.props.bleakResults)) {
const rankingEval = this.props.bleakResults.rankingEvaluation;
// Check if zero point is same or different across rankings.
// Hack for legacy airbnb data, which has different data for the "no
// fixes" run across the three metrics (which we leverage to give us
// tighter error bars on that number / repro the numbers in the paper).
//
// On all data produced by BLeak moving forward, the data for the "no fixes"
// run is the same / shared across metrics -- so we just use the data reported
// for one metric as the base case.
let zeroPointData = rankingEval.leakShare[0];
if (zeroPointData[0][0].totalSize !== rankingEval.retainedSize[0][0][0].totalSize) {
// Different data across metrics, so can use.
zeroPointData = [].concat(rankingEval.leakShare[0], rankingEval.retainedSize[0], rankingEval.transitiveClosureSize[0]);
}
const zeroMean = averageGrowth(zeroPointData);
const growthReduction = averageGrowthReduction(zeroMean, rankingEval.leakShare[rankingEval.leakShare.length - 1]);
this.setState({
averageGrowth: zeroMean.mean,
averageGrowthSe: zeroMean.se,
growthReduction: growthReduction.mean,
growthReductionSe: growthReduction.se,
growthReductionPercent: growthReduction.percent,
growthReductionPercentSe: growthReduction.percentSe
});
} else {
const mean = averageGrowth([this.props.bleakResults.heapStats]);
this.setState({
averageGrowth: mean.mean,
averageGrowthSe: mean.se
});
}
}
}
public componentDidMount() {
this._updateGraph();
window.addEventListener('resize', this._resizeListener);
}
public componentDidUpdate() {
this._updateGraph();
}
public componentWillUnmount() {
window.removeEventListener('resize', this._resizeListener);
}
private _updateGraph() {
if (!this._hasHeapStats()) {
return;
}
const d3div = this.refs['d3_div'] as HTMLDivElement;
if (d3div.childNodes && d3div.childNodes.length > 0) {
const nodes: Node[] = [];
for (let i = 0; i < d3div.childNodes.length; i++) {
nodes.push(d3div.childNodes[i]);
}
nodes.forEach((n) => d3div.removeChild(n));
}
const svg = d3Select(d3div).append<SVGElement>("svg");
const svgStyle = getComputedStyle(svg.node());
const margins = {left: 65, right: 20, top: 10, bottom: 35};
const svgHeight = parseFloat(svgStyle.height);
const svgWidth = parseFloat(svgStyle.width);
const radius = 3;
const tickSize = 6;
const lines = distillResults(this.props.bleakResults);
const maxHeapSize = 1.02 * max(lines.map((l) => max(l.value.map((v, i) => v + (l.se ? (1.96 * l.se[i]) : 0)))));
const minHeapSize = 0.98 * min(lines.map((l) => min(l.value.map((v, i) => v - (l.se ? (1.96 * l.se[i]) : 0)))));
const plotWidth = svgWidth - margins.left - margins.right;
const plotHeight = svgHeight - margins.top - margins.bottom;
const x = d3ScaleLinear()
.range([0, plotWidth])
.domain([0, lines[0].value.length - 1]);
const y = d3ScaleLinear().range([plotHeight, 0])
.domain([minHeapSize, maxHeapSize]);
const valueline = d3Line<[number, number, number]>()
.x(function(d) { return x(d[0]); })
.y(function(d) { return y(d[1]); });
const data = lines.map((l): [number, number, number][] =>
d3Zip(d3Range(0, l.value.length), l.value, l.se ? l.se : d3Range(0, l.value.length)) as [number, number, number][]
);
const g = svg.append("g").attr('transform', `translate(${margins.left}, ${margins.top})`);
const plots = g.selectAll("g.plot")
.data(data)
.enter()
.append('g')
.attr('class', (d, i) => `plot plot_${i}`);
const hasError = !!lines[0].se;
const self = this;
function drawPointsAndErrorBars(this: Element, d: [number, number, number][], i: number): void {
// Prevent overlapping points / bars
const move = i * 5;
const g = d3Select(this)
.selectAll('circle')
.data(d)
.enter()
.append('g')
.attr('class', 'data-point')
.attr('data-placement', 'left')
.attr('title', (d) => `${lines[i].name} Iteration ${d[0]}: ${self._presentStat(d[1], 'MB', hasError ? d[2] : undefined)}`)
.each((_, __, g) => {
for (let i = 0; i < g.length; i++) {
$(g[i]).tooltip();
}
});
g.append('circle')
.attr('r', radius)
.attr('cx', (d) => x(d[0]) + move)
.attr('cy', (d) => y(d[1]));
if (hasError) {
// Straight line
g.append("line")
.attr("class", "error-line")
.attr("x1", function(d) {
return x(d[0]) + move;
})
.attr("y1", function(d) {
return y(d[1] + (1.96 * d[2]));
})
.attr("x2", function(d) {
return x(d[0]) + move;
})
.attr("y2", function(d) {
return y(d[1] - (1.96 * d[2]));
});
// Top cap
g.append("line")
.attr("class", "error-cap")
.attr("x1", function(d) {
return x(d[0]) - 4 + move;
})
.attr("y1", function(d) {
return y(d[1] + (1.96 * d[2]));
})
.attr("x2", function(d) {
return x(d[0]) + 4 + move;
})
.attr("y2", function(d) {
return y(d[1] + (1.96 * d[2]));
});
// Bottom cap
g.append("line")
.attr("class", "error-cap")
.attr("x1", function(d) {
return x(d[0]) - 4 + move;
})
.attr("y1", function(d) {
return y(d[1] - (1.96 * d[2]));
})
.attr("x2", function(d) {
return x(d[0]) + 4 + move;
})
.attr("y2", function(d) {
return y(d[1] - (1.96 * d[2]));
});
}
}
plots.append('path')
.attr("class", 'line')
.attr("d", valueline);
plots.each(drawPointsAndErrorBars);
// Add the X Axis
g.append("g")
.attr('class', 'xaxis')
.attr("transform", `translate(0,${plotHeight})`)
.call(axisBottom(x).tickSizeOuter(tickSize).tickFormat((n) => {
let val = typeof(n) === 'number' ? n : n.valueOf();
if (Math.floor(val) !== val) {
// Drop the tick mark.
return undefined as any;
}
return n;
}));
// Add the Y Axis
g.append("g")
.attr('class', 'yaxis')
.call(axisLeft(y).tickSizeOuter(tickSize).tickFormat((n) => `${n} MB`));
// Add X axis title
g.append('text')
.attr('class', 'xtitle')
.attr('x', plotWidth >> 1)
.attr('y', 32) // Approximate height of x axis
.attr('transform', `translate(0, ${plotHeight})`)
.style('text-anchor', 'middle')
.text('Round Trips Completed');
// Add Y axis title
g.append('text')
.attr('class', 'ytitle')
.attr('x', -1 * (plotHeight >> 1)) // x and y are flipped because of rotation
.attr('y', -58) // Approximate width of y-axis
.attr('transform', 'rotate(-90)')
.style('text-anchor', 'middle')
.style('alignment-baseline', 'central')
.text('Live Heap Size');
if (lines.length > 1) {
// Put up a legend
const legend = g.append('g')
.attr('class', 'legend')
.attr('transform', `translate(15, 15)`);
const rect = legend.append('rect');
const legendItems = legend.append<SVGGElement>('g')
.attr('class', 'legend-items');
const liWithData = legendItems.selectAll('text')
.data(lines)
.enter();
liWithData.append('text')
.attr('x', '1.3em')
.attr('y', (l, i) => `${i}em`)
.text((l) => l.name);
liWithData.append('line')
.attr('class', (_, i) => `plot_${i}`)
.attr('x1', 0)
.attr('y1', (d, i) => `${i - 0.3}em`)
.attr('x2', `1em`)
.attr('y2', (d, i) => `${i - 0.3}em`);
// x, y, height, width
const bbox = legendItems.node().getBBox();
rect.attr('x', bbox.x - 5)
.attr('y', bbox.y - 5)
.attr('height', bbox.height + 10)
.attr('width', bbox.width + 10);
}
}
private _hasHeapStats(): boolean {
return !!this.props.bleakResults.heapStats && this.props.bleakResults.heapStats.length > 0;
}
private _presentStat(stat: number, metric: string, se?: number) {
return `${stat.toFixed(2)}${metric}${se ? `, 95% CI [${(stat - (1.96 * se)).toFixed(2)}, ${(stat + (1.96 * se)).toFixed(2)}]` : ''}`
}
public render() {
// TODO: Growth reduction.
return <div>
{this._hasHeapStats() && this.state.averageGrowth ?
<div key="heap_stats">
<b>Average Growth:</b> {this._presentStat(this.state.averageGrowth, 'MB / round trip', this.state.averageGrowthSe)} <br />
{this.state.growthReduction ? <span><b>Growth Reduction:</b> {this._presentStat(this.state.growthReductionPercent, '%', this.state.growthReductionPercentSe)} ({this._presentStat(this.state.growthReduction, 'MB / round trip', this.state.growthReductionSe)})<br /></span> : ''}
(The above stats ignore the impact of first 5 heap snapshots, which are typically noisy due to application startup + JavaScript engine warmup)
</div>
: ''}
<div ref="d3_div" className="heap-growth-graph">
<div className={this._hasHeapStats() ? 'hidden' : ''}>
Results file does not contain any heap growth information. Please re-run in the newest version of BLeak.
</div>
</div>
</div>;
}
} | the_stack |
import { Cluster } from './cluster'
import { CouchbaseError, GroupNotFoundError, UserNotFoundError } from './errors'
import { HttpExecutor, HttpMethod, HttpServiceType } from './httpexecutor'
import { RequestSpan } from './tracing'
import { cbQsStringify, NodeCallback, PromiseHelper } from './utilities'
/**
* Contains information about an origin for a role.
*
* @category Management
*/
export class Origin {
/**
* The type of this origin.
*/
type: string
/**
* The name of this origin.
*/
name: string
/**
* @internal
*/
constructor(data: Origin) {
this.type = data.type
this.name = data.name
}
/**
* @internal
*/
static _fromNsData(data: any): Origin {
return new Origin({
type: data.type,
name: data.name,
})
}
}
/**
* Contains information about a role.
*
* @category Management
*/
export class Role {
/**
* The name of the role.
*/
name: string
/**
* The bucket this role applies to.
*/
bucket: string | undefined
/**
* The scope this role applies to.
*/
scope: string | undefined
/**
* The collection this role applies to.
*/
collection: string | undefined
/**
* @internal
*/
constructor(data: Role) {
this.name = data.name
this.bucket = data.bucket
this.scope = data.scope
this.collection = data.collection
}
/**
* @internal
*/
static _fromNsData(data: any): Role {
return new Role({
name: data.role,
bucket: data.bucket_name,
scope: data.scope_name,
collection: data.collection_name,
})
}
/**
* @internal
*/
static _toNsStr(role: string | Role): string {
if (typeof role === 'string') {
return role
}
if (role.bucket && role.scope && role.collection) {
return `${role.name}[${role.bucket}:${role.scope}:${role.collection}]`
} else if (role.bucket && role.scope) {
return `${role.name}[${role.bucket}:${role.scope}]`
} else if (role.bucket) {
return `${role.name}[${role.bucket}]`
} else {
return role.name
}
}
}
/**
* Contains information about a role along with its description.
*
* @category Management
*/
export class RoleAndDescription extends Role {
/**
* The user-friendly display name for this role.
*/
displayName: string
/**
* The description of this role.
*/
description: string
/**
* @internal
*/
constructor(data: RoleAndDescription) {
super(data)
this.displayName = data.displayName
this.description = data.description
}
/**
* @internal
*/
static _fromNsData(data: any): RoleAndDescription {
return new RoleAndDescription({
...Role._fromNsData(data),
displayName: data.name,
description: data.description,
})
}
}
/**
* Contains information about a role along with its origin.
*
* @category Management
*/
export class RoleAndOrigin extends Role {
/**
* The origins for this role.
*/
origins: Origin[]
/**
* @internal
*/
constructor(data: RoleAndOrigin) {
super(data)
this.origins = data.origins
}
/**
* @internal
*/
static _fromNsData(data: any): RoleAndOrigin {
let origins: Origin[]
if (data.origins) {
origins = data.origins.map((originData: any) =>
Origin._fromNsData(originData)
)
} else {
origins = []
}
return new RoleAndOrigin({
...Role._fromNsData(data),
origins,
})
}
}
/**
* Specifies information about a user.
*
* @category Management
*/
export interface IUser {
/**
* The username of the user.
*/
username: string
/**
* The display name of the user.
*/
displayName?: string
/**
* The groups associated with this user.
*/
groups?: string[]
/**
* The roles associates with this user.
*/
roles?: (Role | string)[]
/**
* The password for this user.
*/
password?: string
}
/**
* Contains information about a user.
*
* @category Management
*/
export class User implements IUser {
/**
* The username of the user.
*/
username: string
/**
* The display name of the user.
*/
displayName: string
/**
* The groups associated with this user.
*/
groups: string[]
/**
* The roles associates with this user.
*/
roles: Role[]
/**
* This is never populated in a result returned by the server.
*/
password: undefined
/**
* @internal
*/
constructor(data: User) {
this.username = data.username
this.displayName = data.displayName
this.groups = data.groups
this.roles = data.roles
}
/**
* @internal
*/
static _fromNsData(data: any): User {
let roles: Role[]
if (data.roles) {
roles = data.roles
.filter((roleData: any) => {
// Check whether or not this role has originated from the user directly
// or whether it was through a group.
if (!roleData.origins || roleData.origins.length === 0) {
return false
}
return !!roleData.origins.find(
(originData: any) => originData.type === 'user'
)
})
.map((roleData: any) => Role._fromNsData(roleData))
} else {
roles = []
}
return new User({
username: data.id,
displayName: data.name,
groups: data.groups,
roles: roles,
password: undefined,
})
}
/**
* @internal
*/
static _toNsData(user: IUser): any {
let groups: any = undefined
if (user.groups && user.groups.length > 0) {
groups = user.groups
}
let roles: any = undefined
if (user.roles && user.roles.length > 0) {
roles = user.roles.map((role) => Role._toNsStr(role)).join(',')
}
return {
name: user.displayName,
groups: groups,
password: user.password,
roles: roles,
}
}
}
/**
* Contains information about a user along with some additional meta-data
* about that user.
*
* @category Management
*/
export class UserAndMetadata extends User {
/**
* The domain this user is part of.
*/
domain: string
/**
* The effective roles that are associated with this user.
*/
effectiveRoles: RoleAndOrigin[]
/**
* The last time the users password was changed.
*/
passwordChanged: Date
/**
* The external groups that this user is associated with.
*/
externalGroups: string[]
/**
* Same as {@link effectiveRoles}, which already contains the roles
* including their origins.
*
* @deprecated Use {@link effectiveRoles} instead.
*/
get effectiveRolesAndOrigins(): RoleAndOrigin[] {
return this.effectiveRoles
}
/**
* @internal
*/
constructor(data: UserAndMetadata) {
super(data)
this.domain = data.domain
this.effectiveRoles = data.effectiveRoles
this.passwordChanged = data.passwordChanged
this.externalGroups = data.externalGroups
}
/**
* @internal
*/
static _fromNsData(data: any): UserAndMetadata {
let effectiveRoles: RoleAndOrigin[]
if (data.roles) {
effectiveRoles = data.roles.map((roleData: any) =>
RoleAndOrigin._fromNsData(roleData)
)
} else {
effectiveRoles = []
}
return new UserAndMetadata({
...User._fromNsData(data),
domain: data.domain,
effectiveRoles: effectiveRoles,
effectiveRolesAndOrigins: effectiveRoles,
passwordChanged: new Date(data.password_change_date),
externalGroups: data.external_groups,
})
}
}
/**
* Specifies information about a group.
*
* @category Management
*/
export interface IGroup {
/**
* The name of the group.
*/
name: string
/**
* The description for the group.
*/
description?: string
/**
* The roles which are associated with this group.
*/
roles?: (Role | string)[]
/**
* The LDAP group that this group is associated with.
*/
ldapGroupReference?: string
}
/**
* Contains information about a group.
*
* @category Management
*/
export class Group {
/**
* The name of the group.
*/
name: string
/**
* The description for the group.
*/
description: string
/**
* The roles which are associated with this group.
*/
roles: Role[]
/**
* The LDAP group that this group is associated with.
*/
ldapGroupReference: string | undefined
/**
* @internal
*/
constructor(data: Group) {
this.name = data.name
this.description = data.description
this.roles = data.roles
this.ldapGroupReference = data.ldapGroupReference
}
/**
* @internal
*/
static _fromNsData(data: any): Group {
let roles: Role[]
if (data.roles) {
roles = data.roles.map((roleData: any) => Role._fromNsData(roleData))
} else {
roles = []
}
return new Group({
name: data.id,
description: data.description,
roles: roles,
ldapGroupReference: data.ldap_group_reference,
})
}
/**
* @internal
*/
static _toNsData(group: IGroup): any {
let roles: any = undefined
if (group.roles && group.roles.length > 0) {
roles = group.roles.map((role) => Role._toNsStr(role)).join(',')
}
return {
description: group.description,
roles: roles,
ldap_group_reference: group.ldapGroupReference,
}
}
}
/**
* @category Management
*/
export interface GetUserOptions {
/**
* The domain to look in for the user.
*/
domainName?: string
/**
* The parent tracing span that this operation will be part of.
*/
parentSpan?: RequestSpan
/**
* The timeout for this operation, represented in milliseconds.
*/
timeout?: number
}
/**
* @category Management
*/
export interface GetAllUsersOptions {
/**
* The domain to look in for users.
*/
domainName?: string
/**
* The parent tracing span that this operation will be part of.
*/
parentSpan?: RequestSpan
/**
* The timeout for this operation, represented in milliseconds.
*/
timeout?: number
}
/**
* @category Management
*/
export interface UpsertUserOptions {
/**
* The domain to upsert the user within.
*/
domainName?: string
/**
* The parent tracing span that this operation will be part of.
*/
parentSpan?: RequestSpan
/**
* The timeout for this operation, represented in milliseconds.
*/
timeout?: number
}
/**
* @category Management
*/
export interface DropUserOptions {
/**
* The domain to drop the user from.
*/
domainName?: string
/**
* The parent tracing span that this operation will be part of.
*/
parentSpan?: RequestSpan
/**
* The timeout for this operation, represented in milliseconds.
*/
timeout?: number
}
/**
* @category Management
*/
export interface GetRolesOptions {
/**
* The parent tracing span that this operation will be part of.
*/
parentSpan?: RequestSpan
/**
* The timeout for this operation, represented in milliseconds.
*/
timeout?: number
}
/**
* @category Management
*/
export interface GetGroupOptions {
/**
* The parent tracing span that this operation will be part of.
*/
parentSpan?: RequestSpan
/**
* The timeout for this operation, represented in milliseconds.
*/
timeout?: number
}
/**
* @category Management
*/
export interface GetAllGroupsOptions {
/**
* The parent tracing span that this operation will be part of.
*/
parentSpan?: RequestSpan
/**
* The timeout for this operation, represented in milliseconds.
*/
timeout?: number
}
/**
* @category Management
*/
export interface UpsertGroupOptions {
/**
* The parent tracing span that this operation will be part of.
*/
parentSpan?: RequestSpan
/**
* The timeout for this operation, represented in milliseconds.
*/
timeout?: number
}
/**
* @category Management
*/
export interface DropGroupOptions {
/**
* The parent tracing span that this operation will be part of.
*/
parentSpan?: RequestSpan
/**
* The timeout for this operation, represented in milliseconds.
*/
timeout?: number
}
/**
* UserManager is an interface which enables the management of users,
* groups and roles for the cluster.
*
* @category Management
*/
export class UserManager {
private _cluster: Cluster
/**
* @internal
*/
constructor(cluster: Cluster) {
this._cluster = cluster
}
private get _http() {
return new HttpExecutor(this._cluster._getClusterConn())
}
/**
* Returns a specific user by their username.
*
* @param username The username of the user to fetch.
* @param options Optional parameters for this operation.
* @param callback A node-style callback to be invoked after execution.
*/
async getUser(
username: string,
options?: GetUserOptions,
callback?: NodeCallback<UserAndMetadata>
): Promise<UserAndMetadata> {
if (options instanceof Function) {
callback = arguments[1]
options = undefined
}
if (!options) {
options = {}
}
const domainName = options.domainName || 'local'
const parentSpan = options.parentSpan
const timeout = options.timeout
return PromiseHelper.wrapAsync(async () => {
const res = await this._http.request({
type: HttpServiceType.Management,
method: HttpMethod.Get,
path: `/settings/rbac/users/${domainName}/${username}`,
parentSpan: parentSpan,
timeout: timeout,
})
if (res.statusCode !== 200) {
const errCtx = HttpExecutor.errorContextFromResponse(res)
if (res.statusCode === 404) {
throw new UserNotFoundError(undefined, errCtx)
}
throw new CouchbaseError('failed to get the user', undefined, errCtx)
}
const userData = JSON.parse(res.body.toString())
return UserAndMetadata._fromNsData(userData)
}, callback)
}
/**
* Returns a list of all existing users.
*
* @param options Optional parameters for this operation.
* @param callback A node-style callback to be invoked after execution.
*/
async getAllUsers(
options?: GetAllUsersOptions,
callback?: NodeCallback<UserAndMetadata[]>
): Promise<UserAndMetadata[]> {
if (options instanceof Function) {
callback = arguments[0]
options = undefined
}
if (!options) {
options = {}
}
const domainName = options.domainName || 'local'
const parentSpan = options.parentSpan
const timeout = options.timeout
return PromiseHelper.wrapAsync(async () => {
const res = await this._http.request({
type: HttpServiceType.Management,
method: HttpMethod.Get,
path: `/settings/rbac/users/${domainName}`,
parentSpan: parentSpan,
timeout: timeout,
})
if (res.statusCode !== 200) {
const errCtx = HttpExecutor.errorContextFromResponse(res)
throw new CouchbaseError('failed to get users', undefined, errCtx)
}
const usersData = JSON.parse(res.body.toString())
const users = usersData.map((userData: any) =>
UserAndMetadata._fromNsData(userData)
)
return users
}, callback)
}
/**
* Creates or updates an existing user.
*
* @param user The user to update.
* @param options Optional parameters for this operation.
* @param callback A node-style callback to be invoked after execution.
*/
async upsertUser(
user: IUser,
options?: UpsertUserOptions,
callback?: NodeCallback<void>
): Promise<void> {
if (options instanceof Function) {
callback = arguments[1]
options = undefined
}
if (!options) {
options = {}
}
const domainName = options.domainName || 'local'
const parentSpan = options.parentSpan
const timeout = options.timeout
return PromiseHelper.wrapAsync(async () => {
const userData = User._toNsData(user)
const res = await this._http.request({
type: HttpServiceType.Management,
method: HttpMethod.Put,
path: `/settings/rbac/users/${domainName}/${user.username}`,
contentType: 'application/x-www-form-urlencoded',
body: cbQsStringify(userData),
parentSpan: parentSpan,
timeout: timeout,
})
if (res.statusCode !== 200) {
const errCtx = HttpExecutor.errorContextFromResponse(res)
throw new CouchbaseError('failed to upsert user', undefined, errCtx)
}
}, callback)
}
/**
* Drops an existing user.
*
* @param username The username of the user to drop.
* @param options Optional parameters for this operation.
* @param callback A node-style callback to be invoked after execution.
*/
async dropUser(
username: string,
options?: DropUserOptions,
callback?: NodeCallback<void>
): Promise<void> {
if (options instanceof Function) {
callback = arguments[1]
options = undefined
}
if (!options) {
options = {}
}
const domainName = options.domainName || 'local'
const parentSpan = options.parentSpan
const timeout = options.timeout
return PromiseHelper.wrapAsync(async () => {
const res = await this._http.request({
type: HttpServiceType.Management,
method: HttpMethod.Delete,
path: `/settings/rbac/users/${domainName}/${username}`,
parentSpan: parentSpan,
timeout: timeout,
})
if (res.statusCode !== 200) {
const errCtx = HttpExecutor.errorContextFromResponse(res)
if (res.statusCode === 404) {
throw new UserNotFoundError(undefined, errCtx)
}
throw new CouchbaseError('failed to drop the user', undefined, errCtx)
}
}, callback)
}
/**
* Returns a list of roles available on the server.
*
* @param options Optional parameters for this operation.
* @param callback A node-style callback to be invoked after execution.
*/
async getRoles(
options?: GetRolesOptions,
callback?: NodeCallback<Role[]>
): Promise<Role[]> {
if (options instanceof Function) {
callback = arguments[1]
options = undefined
}
if (!options) {
options = {}
}
const parentSpan = options.parentSpan
const timeout = options.timeout
return PromiseHelper.wrapAsync(async () => {
const res = await this._http.request({
type: HttpServiceType.Management,
method: HttpMethod.Get,
path: `/settings/rbac/roles`,
parentSpan: parentSpan,
timeout: timeout,
})
if (res.statusCode !== 200) {
const errCtx = HttpExecutor.errorContextFromResponse(res)
throw new CouchbaseError('failed to get roles', undefined, errCtx)
}
const rolesData = JSON.parse(res.body.toString())
const roles = rolesData.map((roleData: any) =>
RoleAndDescription._fromNsData(roleData)
)
return roles
}, callback)
}
/**
* Returns a group by it's name.
*
* @param groupName The name of the group to retrieve.
* @param options Optional parameters for this operation.
* @param callback A node-style callback to be invoked after execution.
*/
async getGroup(
groupName: string,
options?: GetGroupOptions,
callback?: NodeCallback<Group>
): Promise<Group> {
if (options instanceof Function) {
callback = arguments[1]
options = undefined
}
if (!options) {
options = {}
}
const parentSpan = options.parentSpan
const timeout = options.timeout
return PromiseHelper.wrapAsync(async () => {
const res = await this._http.request({
type: HttpServiceType.Management,
method: HttpMethod.Get,
path: `/settings/rbac/groups/${groupName}`,
parentSpan: parentSpan,
timeout: timeout,
})
if (res.statusCode !== 200) {
const errCtx = HttpExecutor.errorContextFromResponse(res)
if (res.statusCode === 404) {
throw new GroupNotFoundError(undefined, errCtx)
}
throw new CouchbaseError('failed to get the group', undefined, errCtx)
}
const groupData = JSON.parse(res.body.toString())
return Group._fromNsData(groupData)
}, callback)
}
/**
* Returns a list of all existing groups.
*
* @param options Optional parameters for this operation.
* @param callback A node-style callback to be invoked after execution.
*/
async getAllGroups(
options?: GetAllGroupsOptions,
callback?: NodeCallback<Group[]>
): Promise<Group[]> {
if (options instanceof Function) {
callback = arguments[0]
options = undefined
}
if (!options) {
options = {}
}
const parentSpan = options.parentSpan
const timeout = options.timeout
return PromiseHelper.wrapAsync(async () => {
const res = await this._http.request({
type: HttpServiceType.Management,
method: HttpMethod.Get,
path: `/settings/rbac/groups`,
parentSpan: parentSpan,
timeout: timeout,
})
if (res.statusCode !== 200) {
const errCtx = HttpExecutor.errorContextFromResponse(res)
throw new CouchbaseError('failed to get groups', undefined, errCtx)
}
const groupsData = JSON.parse(res.body.toString())
const groups = groupsData.map((groupData: any) =>
Group._fromNsData(groupData)
)
return groups
}, callback)
}
/**
* Creates or updates an existing group.
*
* @param group The group to update.
* @param options Optional parameters for this operation.
* @param callback A node-style callback to be invoked after execution.
*/
async upsertGroup(
group: IGroup,
options?: UpsertGroupOptions,
callback?: NodeCallback<void>
): Promise<void> {
if (options instanceof Function) {
callback = arguments[1]
options = undefined
}
if (!options) {
options = {}
}
const parentSpan = options.parentSpan
const timeout = options.timeout
return PromiseHelper.wrapAsync(async () => {
const groupData = Group._toNsData(group)
const res = await this._http.request({
type: HttpServiceType.Management,
method: HttpMethod.Put,
path: `/settings/rbac/groups/${group.name}`,
contentType: 'application/x-www-form-urlencoded',
body: cbQsStringify(groupData),
parentSpan: parentSpan,
timeout: timeout,
})
if (res.statusCode !== 200) {
const errCtx = HttpExecutor.errorContextFromResponse(res)
throw new CouchbaseError('failed to upsert group', undefined, errCtx)
}
}, callback)
}
/**
* Drops an existing group.
*
* @param groupName The name of the group to drop.
* @param options Optional parameters for this operation.
* @param callback A node-style callback to be invoked after execution.
*/
async dropGroup(
groupName: string,
options?: DropGroupOptions,
callback?: NodeCallback<void>
): Promise<void> {
if (options instanceof Function) {
callback = arguments[1]
options = undefined
}
if (!options) {
options = {}
}
const parentSpan = options.parentSpan
const timeout = options.timeout
return PromiseHelper.wrapAsync(async () => {
const res = await this._http.request({
type: HttpServiceType.Management,
method: HttpMethod.Delete,
path: `/settings/rbac/groups/${groupName}`,
parentSpan: parentSpan,
timeout: timeout,
})
if (res.statusCode !== 200) {
const errCtx = HttpExecutor.errorContextFromResponse(res)
if (res.statusCode === 404) {
throw new GroupNotFoundError(undefined, errCtx)
}
throw new CouchbaseError('failed to drop the group', undefined, errCtx)
}
}, callback)
}
} | the_stack |
import { test, expect } from "@jest/globals";
import { Mock, It } from "typemoq";
import { OvaleASTClass } from "./ast";
import { OvaleConditionClass } from "./condition";
import { DebugTools, Tracer } from "./debug";
import { OvaleScriptsClass } from "./scripts";
import { OvaleSpellBookClass } from "../states/SpellBook";
import { format } from "@wowts/string";
import { assertDefined, assertIs } from "../tests/helpers";
function makeContext() {
const context = {
ovaleConditionMock: Mock.ofType<OvaleConditionClass>(),
ovaleDebugMock: Mock.ofType<DebugTools>(),
ovaleScriptsMock: Mock.ofType<OvaleScriptsClass>(),
ovaleSpellbookMock: Mock.ofType<OvaleSpellBookClass>(),
tracerMock: Mock.ofType<Tracer>(),
};
const tracer = context.tracerMock;
tracer
.setup((x) => x.warning(It.isAnyString()))
.callback((x) => {
expect(format(x)).toBeUndefined();
});
tracer
.setup((x) => x.warning(It.isAnyString(), It.isAny()))
.callback((x, y) => {
expect(format(x, y)).toBeUndefined();
});
tracer
.setup((x) => x.warning(It.isAnyString(), It.isAny(), It.isAny()))
.callback((x, y, z) => {
expect(format(x, y, z)).toBeUndefined();
});
tracer
.setup((x) => x.error(It.isAny()))
.callback((x) => expect(x).toBeUndefined());
context.ovaleDebugMock
.setup((x) => x.create(It.isAnyString()))
.returns(() => tracer.object);
return context;
}
function makeAst() {
const context = makeContext();
return {
ast: new OvaleASTClass(
context.ovaleConditionMock.object,
context.ovaleDebugMock.object,
context.ovaleScriptsMock.object,
context.ovaleSpellbookMock.object
),
astAnnotation: { definition: {}, nodeList: {} },
context,
};
}
test("ast: parse Define", () => {
// Act
const { ast, astAnnotation } = makeAst();
const [astNode, nodeList, annotation] = ast.parseCode(
"script",
`Define(test 18)`,
{},
astAnnotation
);
// Assert
assertDefined(astNode);
assertDefined(nodeList);
assertDefined(annotation);
assertDefined(annotation.definition);
expect(annotation.definition["test"]).toBe(18);
});
test("ast: parse SpellInfo", () => {
// Act
const { ast, astAnnotation } = makeAst();
const [astNode, nodeList, annotation] = ast.parseCode(
"script",
"SpellInfo(123 cd=30 rage=10)",
{},
astAnnotation
);
// Assert
assertDefined(astNode);
assertDefined(nodeList);
assertDefined(annotation);
assertIs(astNode.type, "script");
const spellInfoNode = astNode.child[1];
assertIs(spellInfoNode.type, "spell_info");
expect(spellInfoNode.spellId).toBe(123);
const cd = spellInfoNode.rawNamedParams.cd;
assertDefined(cd);
assertIs(cd.type, "value");
expect(cd.value).toBe(30);
const rage = spellInfoNode.rawNamedParams.rage;
assertDefined(rage);
assertIs(rage.type, "value");
expect(rage.value).toBe(10);
});
test("ast: parse expression with a if with SpellInfo", () => {
// Act
const { ast, astAnnotation } = makeAst();
const [astNode, nodeList, annotation] = ast.parseCode(
"icon",
"AddIcon { if Talent(12) Spell(115) }",
{},
astAnnotation
);
// Assert
assertDefined(astNode);
assertDefined(nodeList);
assertDefined(annotation);
// t.is(astNode!.asString, "AddIcon\n{\n if talent(12) spell(115)\n}");
assertIs(astNode.type, "icon");
const group = astNode.child[1];
assertIs(group.type, "group");
const ifNode = group.child[1];
assertIs(ifNode.type, "if");
const talentNode = ifNode.child[1];
assertIs(talentNode.type, "custom_function");
expect(talentNode.name).toBe("talent");
const spellNode = ifNode.child[2];
assertIs(spellNode.type, "action");
expect(spellNode.name).toBe("spell");
const spellid = spellNode.rawPositionalParams[1];
assertDefined(spellid);
assertIs(spellid.type, "value");
expect(spellid.value).toBe(115);
});
test("ast: dedupe nodes", () => {
// Act
const { ast } = makeAst();
const astNode = ast.parseScript(
"AddIcon { if BuffPresent(12) Spell(15) if BuffPresent(12) Spell(16) }"
);
// Assert
assertDefined(astNode);
assertIs(astNode.type, "script");
const icon = astNode.child[1];
assertIs(icon.type, "icon");
const group = icon.child[1];
assertIs(group.type, "group");
const firstChild = group.child[1];
assertIs(firstChild.type, "if");
const secondChild = group.child[2];
assertIs(secondChild.type, "if");
expect(firstChild.child[1]).toBe(secondChild.child[1]);
});
test("ast: itemrequire", () => {
// Act
const { ast, astAnnotation } = makeAst();
const [astNode, nodeList, annotation] = ast.parseCode(
"script",
"ItemRequire(coagulated_nightwell_residue unusable buff set=1 enabled=(not buffpresent(nightwell_energy_buff)))",
{},
astAnnotation
);
// Assert
assertDefined(astNode);
assertDefined(nodeList);
assertDefined(annotation);
assertIs(astNode.type, "script");
const itemRequire = astNode.child[1];
assertIs(itemRequire.type, "itemrequire");
expect(itemRequire.property).toBe("unusable");
});
test("ast: addcheckbox", () => {
// Act
const { ast, astAnnotation } = makeAst();
const [astNode] = ast.parseCode(
"script",
"AddCheckBox(opt_interrupt l(interrupt) default enabled=(specialization(blood)))",
{},
astAnnotation
);
// Assert
assertDefined(astNode);
});
test("ast: spellaura", () => {
// Arrange
const { ast, astAnnotation } = makeAst();
// Act
const [astNode] = ast.parseCode(
"script",
"SpellAddBuff(bloodthirst bloodthirst_buff set=1)",
{},
astAnnotation
);
// Assert
assertDefined(astNode);
});
test("if in {}", () => {
const { ast, astAnnotation } = makeAst();
const [astNode] = ast.parseCode(
"expression",
`if { if 0 == 30 and equippedruneforge(disciplinary_command_runeforge) 50 } == 30 10`,
{},
astAnnotation
);
// Assert
assertDefined(astNode);
assertIs(astNode.type, "if");
});
test("typed condition with only position parameters", () => {
// Arrange
const { ast, astAnnotation, context } = makeAst();
context.ovaleConditionMock
.setup((x) => x.getInfos("test"))
.returns(() => ({
func: () => [0, 12, "a"],
namedParameters: {},
parameters: {
1: { type: "string", name: "a", optional: true },
2: { type: "number", name: "b", optional: true },
},
returnValue: { name: "return", type: "string" },
}));
// Act
const [astNode] = ast.parseCode(
"expression",
`test("example" 12)`,
{},
astAnnotation
);
// Assert
assertDefined(astNode);
assertIs(astNode.type, "typed_function");
expect(astNode.name).toBe("test");
expect(astNode.rawNamedParams).toEqual({});
assertDefined(astNode.rawPositionalParams[1]);
assertIs(astNode.rawPositionalParams[1].type, "string");
assertDefined(astNode.rawPositionalParams[2]);
assertIs(astNode.rawPositionalParams[2].type, "value");
expect(astNode.asString).toBe('test("example" 12)');
});
test("typed condition with only named parameters", () => {
// Arrange
const { ast, astAnnotation, context } = makeAst();
context.ovaleConditionMock
.setup((x) => x.getInfos("test"))
.returns(() => ({
func: () => [0, 12, "a"],
namedParameters: { a: 1, b: 2 },
parameters: {
1: { type: "string", name: "a", optional: true },
2: { type: "number", name: "b", optional: true },
},
returnValue: { name: "return", type: "string" },
}));
// Act
const [astNode] = ast.parseCode(
"expression",
`test(b=12 a="example")`,
{},
astAnnotation
);
// Assert
assertDefined(astNode);
assertIs(astNode.type, "typed_function");
expect(astNode.name).toBe("test");
assertDefined(astNode.rawPositionalParams[1]);
assertIs(astNode.rawPositionalParams[1].type, "string");
expect(astNode.rawPositionalParams[1].value).toBe("example");
assertDefined(astNode.rawPositionalParams[2]);
assertIs(astNode.rawPositionalParams[2].type, "value");
expect(astNode.rawPositionalParams[2].value).toBe(12);
expect(astNode.asString).toEqual('test("example" 12)');
});
test("typed condition with parameters with default values", () => {
// Arrange
const { ast, astAnnotation, context } = makeAst();
context.ovaleConditionMock
.setup((x) => x.getInfos("test"))
.returns(() => ({
func: () => [0, 12, "a"],
namedParameters: {},
parameters: {
1: {
type: "string",
name: "a",
optional: true,
defaultValue: "test",
},
2: {
type: "string",
name: "a",
optional: true,
},
3: {
type: "number",
name: "b",
optional: true,
defaultValue: 14,
},
4: {
type: "boolean",
name: "c",
optional: true,
defaultValue: true,
},
},
returnValue: { name: "return", type: "string" },
}));
// Act
const [astNode] = ast.parseCode("expression", `test()`, {}, astAnnotation);
// Assert
assertDefined(astNode);
assertIs(astNode.type, "typed_function");
expect(astNode.name).toBe("test");
assertDefined(astNode.rawPositionalParams[1]);
assertIs(astNode.rawPositionalParams[1].type, "string");
expect(astNode.rawPositionalParams[1].value).toBe("test");
assertDefined(astNode.rawPositionalParams[3]);
assertIs(astNode.rawPositionalParams[3].type, "value");
expect(astNode.rawPositionalParams[3].value).toBe(14);
assertDefined(astNode.rawPositionalParams[4]);
assertIs(astNode.rawPositionalParams[4].type, "boolean");
expect(astNode.rawPositionalParams[4].value).toBe(true);
expect(astNode.asString).toEqual("test()");
});
test("boolean node", () => {
// Arrange
const { ast, astAnnotation } = makeAst();
// Act
const [astNode] = ast.parseCode(
"expression",
`if true or false 18`,
{},
astAnnotation
);
// Assert
assertDefined(astNode);
assertIs(astNode.type, "if");
assertDefined(astNode.child[1]);
assertIs(astNode.child[1].type, "logical");
expect(astNode.child[1].operator).toEqual("or");
const left = astNode.child[1].child[1];
assertDefined(left);
assertIs(left.type, "boolean");
expect(left.value).toBe(true);
const right = astNode.child[1].child[2];
assertDefined(right);
assertIs(right.type, "boolean");
expect(right.value).toBe(false);
});
test("unparse typed function with optional parameters", () => {
// Arrange
const { ast, astAnnotation, context } = makeAst();
context.ovaleConditionMock
.setup((x) => x.getInfos("test"))
.returns(() => ({
func: () => [0, 12, "a"],
namedParameters: { a: 1, b: 2, c: 3 },
parameters: {
1: {
type: "string",
name: "a",
optional: true,
defaultValue: "test",
},
2: {
type: "number",
name: "b",
optional: true,
defaultValue: 14,
},
3: {
type: "boolean",
name: "c",
optional: true,
defaultValue: true,
},
},
returnValue: { name: "return", type: "string" },
}));
// Act
const [astNode] = ast.parseCode(
"expression",
`test(b=15)`,
{},
astAnnotation
);
// Assert
assertDefined(astNode);
assertIs(astNode.type, "typed_function");
expect(astNode.asString).toBe("test(b=15)");
}); | the_stack |
import { action, computed } from "mobx"
import type { ActionMiddlewareDisposer } from "../action/middleware"
import { modelAction } from "../action/modelAction"
import { Model } from "../model/Model"
import { model } from "../modelShared/modelDecorator"
import { fastGetRootPath } from "../parent/path"
import type { Path } from "../parent/pathTypes"
import { applyPatches, Patch, patchRecorder, PatchRecorder } from "../patch"
import { assertTweakedObject } from "../tweaker/core"
import { typesArray } from "../typeChecking/array"
import { tProp } from "../typeChecking/tProp"
import { typesUnchecked } from "../typeChecking/unchecked"
import { failure, getMobxVersion, mobx6 } from "../utils"
import { actionTrackingMiddleware, SimpleActionContext } from "./actionTrackingMiddleware"
/**
* An undo/redo event without attached state.
*/
export type UndoEventWithoutAttachedState = UndoSingleEvent | UndoEventGroup
/**
* An undo/redo event.
*/
export type UndoEvent = UndoEventWithoutAttachedState & {
/**
* The state saved before the event actions started / after the event actions finished.
*/
attachedState: {
/**
* The state saved before the event actions started.
*/
beforeEvent?: unknown
/**
* The state saved after the event actions finished.
*/
afterEvent?: unknown
}
}
/**
* Undo event type.
*/
export enum UndoEventType {
Single = "single",
Group = "group",
}
/**
* An undo/redo single event.
*/
export interface UndoSingleEvent {
/**
* Expresses this is a single event.
*/
readonly type: UndoEventType.Single
/**
* Path to the object that invoked the action from its root.
*/
readonly targetPath: Path
/**
* Name of the action that was invoked.
*/
readonly actionName: string
/**
* Patches with changes done inside the action.
* Use `redo()` in the `UndoManager` to apply them.
*/
readonly patches: ReadonlyArray<Patch>
/**
* Patches to undo the changes done inside the action.
* Use `undo()` in the `UndoManager` to apply them.
*/
readonly inversePatches: ReadonlyArray<Patch>
}
/**
* An undo/redo event group.
*/
export interface UndoEventGroup {
/**
* Expresses this is an event group.
*/
readonly type: UndoEventType.Group
/**
* Name of the group (if any).
*/
readonly groupName?: string
/**
* Events that conform this group (might be single events or other nested groups).
*/
readonly events: ReadonlyArray<UndoEventWithoutAttachedState>
}
function toSingleEvents(
event: UndoEventWithoutAttachedState,
reverse: boolean
): ReadonlyArray<UndoSingleEvent> {
if (event.type === UndoEventType.Single) return [event]
else {
const array: UndoSingleEvent[] = []
for (const e of event.events) {
if (reverse) {
array.unshift(...toSingleEvents(e, true))
} else {
array.push(...toSingleEvents(e, false))
}
}
return array
}
}
/**
* Store model instance for undo/redo actions.
* Do not manipulate directly, other that creating it.
*/
@model("mobx-keystone/UndoStore")
export class UndoStore extends Model({
// TODO: add proper type checking to undo store
undoEvents: tProp(typesArray(typesUnchecked<UndoEvent>()), () => []),
redoEvents: tProp(typesArray(typesUnchecked<UndoEvent>()), () => []),
}) {
/**
* @ignore
*/
@modelAction
_clearUndo() {
withoutUndo(() => {
this.undoEvents.length = 0
})
}
/**
* @ignore
*/
@modelAction
_clearRedo() {
withoutUndo(() => {
this.redoEvents.length = 0
})
}
/**
* @ignore
*/
@modelAction
_undo() {
withoutUndo(() => {
const event = this.undoEvents.pop()!
this.redoEvents.push(event)
})
}
/**
* @ignore
*/
@modelAction
_redo() {
withoutUndo(() => {
const event = this.redoEvents.pop()!
this.undoEvents.push(event)
})
}
/**
* @ignore
*/
@modelAction
_addUndo(event: UndoEvent) {
withoutUndo(() => {
this.undoEvents.push(event)
// once an undo event is added redo queue is no longer valid
this.redoEvents.length = 0
})
}
private _groupStack: UndoEventGroup[] = []
/**
* @ignore
*/
_addUndoToParentGroup(parentGroup: UndoEventGroup, event: UndoEventWithoutAttachedState) {
;(parentGroup.events as UndoEventWithoutAttachedState[]).push(event)
}
/**
* @ignore
*/
get _currentGroup(): UndoEventGroup | undefined {
return this._groupStack[this._groupStack.length - 1]
}
/**
* @ignore
*/
_startGroup(
groupName: string | undefined,
startRunning: boolean,
options: UndoMiddlewareOptions<unknown> | undefined
) {
let running = false
let ended = false
const parentGroup = this._currentGroup
const group: UndoEventGroup = {
type: UndoEventType.Group,
groupName,
events: [],
}
const attachedStateBeforeEvent = parentGroup ? undefined : options?.attachedState?.save()
const api = {
pause: () => {
if (ended) {
throw failure("cannot pause a group when it is already ended")
}
if (!running) {
throw failure("cannot pause a group when it is not running")
}
if (this._currentGroup !== group) {
throw failure("group out of order")
}
this._groupStack.pop()
running = false
},
resume: () => {
if (ended) {
throw failure("cannot resume a group when it is already ended")
}
if (running) {
throw failure("cannot resume a group when it is already running")
}
this._groupStack.push(group)
running = true
},
end: () => {
if (running) {
api.pause()
}
ended = true
if (parentGroup) {
this._addUndoToParentGroup(parentGroup, group)
} else {
this._addUndo({
...group,
attachedState: {
beforeEvent: attachedStateBeforeEvent,
afterEvent: options?.attachedState?.save(),
},
})
}
},
}
if (startRunning) {
api.resume()
}
return api
}
}
/**
* Manager class returned by `undoMiddleware` that allows you to perform undo/redo actions.
*/
export class UndoManager {
/**
* The store currently being used to store undo/redo action events.
*/
readonly store: UndoStore
/**
* The undo stack, where the first operation to undo will be the last of the array.
* Do not manipulate this array directly.
*/
@computed
get undoQueue(): ReadonlyArray<UndoEvent> {
return this.store.undoEvents
}
/**
* The redo stack, where the first operation to redo will be the last of the array.
* Do not manipulate this array directly.
*/
@computed
get redoQueue(): ReadonlyArray<UndoEvent> {
return this.store.redoEvents
}
/**
* The number of undo actions available.
*/
@computed
get undoLevels() {
return this.undoQueue.length
}
/**
* If undo can be performed (if there is at least one undo action available).
*/
@computed
get canUndo() {
return this.undoLevels > 0
}
/**
* Clears the undo queue.
*/
@action
clearUndo() {
this.store._clearUndo()
}
/**
* The number of redo actions available.
*/
@computed
get redoLevels() {
return this.redoQueue.length
}
/**
* If redo can be performed (if there is at least one redo action available)
*/
@computed
get canRedo() {
return this.redoLevels > 0
}
/**
* Clears the redo queue.
*/
@action
clearRedo() {
this.store._clearRedo()
}
/**
* Undoes the last action.
* Will throw if there is no action to undo.
*/
@action
undo() {
if (!this.canUndo) {
throw failure("nothing to undo")
}
const event = this.undoQueue[this.undoQueue.length - 1]
withoutUndo(() => {
toSingleEvents(event, true).forEach((e) => {
applyPatches(this.subtreeRoot, e.inversePatches, true)
})
// restore the attached state before the operation was made
if (event.attachedState?.beforeEvent) {
this.options?.attachedState?.restore(event.attachedState.beforeEvent)
}
})
this.store._undo()
}
/**
* Redoes the previous action.
* Will throw if there is no action to redo.
*/
@action
redo() {
if (!this.canRedo) {
throw failure("nothing to redo")
}
const event = this.redoQueue[this.redoQueue.length - 1]
withoutUndo(() => {
toSingleEvents(event, false).forEach((e) => {
applyPatches(this.subtreeRoot, e.patches)
})
// restore the attached state after the operation was made
if (event.attachedState?.afterEvent) {
this.options?.attachedState?.restore(event.attachedState.afterEvent)
}
})
this.store._redo()
}
/**
* Disposes the undo middleware.
*/
dispose() {
this.disposer()
}
private _isUndoRecordingDisabled = false
/**
* Returns if undo recording is currently disabled or not for this particular `UndoManager`.
*/
get isUndoRecordingDisabled() {
return this._isUndoRecordingDisabled
}
/**
* Skips the undo recording mechanism for the code block that gets run synchronously inside.
*
* @typeparam T Code block return type.
* @param fn Code block to run.
* @returns The value returned by the code block.
*/
withoutUndo<T>(fn: () => T): T {
const savedUndoDisabled = this._isUndoRecordingDisabled
this._isUndoRecordingDisabled = true
try {
return fn()
} finally {
this._isUndoRecordingDisabled = savedUndoDisabled
}
}
/**
* Creates a custom group that can be continued multiple times and then ended.
* @param groupName Optional group name.
* @returns An API to continue/end the group.
*/
createGroup(groupName?: string) {
const group = this.store._startGroup(groupName, false, this.options)
return {
continue<T>(fn: () => T): T {
group.resume()
try {
return fn()
} finally {
group.pause()
}
},
end() {
group.end()
},
}
}
/**
* Runs a synchronous code block as an undo group.
* Note that nested groups are allowed.
*
* @param groupName Group name.
* @param fn Code block.
* @returns Code block return value.
*/
withGroup<T>(groupName: string, fn: () => T): T
/**
* Runs a synchronous code block as an undo group.
* Note that nested groups are allowed.
*
* @param fn Code block.
* @returns Code block return value.
*/
withGroup<T>(fn: () => T): T
withGroup<T>(arg1: any, arg2?: any): T {
let groupName: string | undefined
let fn: () => T
if (typeof arg1 === "string") {
groupName = arg1
fn = arg2
} else {
fn = arg1
}
const group = this.store._startGroup(groupName, true, this.options)
try {
return fn()
} finally {
group.end()
}
}
/**
* Runs an asynchronous code block as an undo group.
* Note that nested groups are allowed.
*
* @param groupName Group name.
* @param fn Flow function.
* @returns Flow function return value.
*/
withGroupFlow<R>(groupName: string, fn: () => Generator<any, R, any>): Promise<R>
/**
* Runs an asynchronous code block as an undo group.
* Note that nested groups are allowed.
*
* @param fn Flow function.
* @returns Flow function return value.
*/
withGroupFlow<R>(fn: () => Generator<any, R, any>): Promise<R>
withGroupFlow<R>(arg1: any, arg2?: any): Promise<R> {
let groupName: string | undefined
let fn: () => Generator<any, R, any>
if (typeof arg1 === "string") {
groupName = arg1
fn = arg2
} else {
fn = arg1
}
const gen = fn()
const group = this.store._startGroup(groupName, false, this.options)
// use bound functions to fix es6 compilation
const genNext = gen.next.bind(gen)
const genThrow = gen.throw!.bind(gen)
const promise = new Promise<R>(function (resolve, reject) {
function onFulfilled(res: any): void {
group.resume()
let ret
try {
ret = genNext(res)
} catch (e) {
group.end()
reject(e)
return
}
group.pause()
next(ret)
}
function onRejected(err: any): void {
group.resume()
let ret
try {
ret = genThrow(err)
} catch (e) {
group.end()
reject(e)
return
}
group.pause()
next(ret)
}
function next(ret: any): void {
if (ret && typeof ret.then === "function") {
// an async iterator
ret.then(next, reject)
} else if (ret.done) {
// done
group.end()
resolve(ret.value)
} else {
// continue
Promise.resolve(ret.value).then(onFulfilled, onRejected)
}
}
onFulfilled(undefined) // kick off the process
})
return promise
}
/**
* Creates an instance of `UndoManager`.
* Do not use directly, use `undoMiddleware` instead.
*
* @param disposer
* @param subtreeRoot
* @param [store]
*/
constructor(
private readonly disposer: ActionMiddlewareDisposer,
private readonly subtreeRoot: object,
store: UndoStore | undefined,
private readonly options: UndoMiddlewareOptions<unknown> | undefined
) {
if (getMobxVersion() >= 6) {
mobx6.makeObservable(this)
}
this.store = store ?? new UndoStore({})
}
}
/**
* Undo middleware options.
*/
export interface UndoMiddlewareOptions<S> {
attachedState?: {
save(): S
restore(s: S): void
}
}
/**
* Creates an undo middleware.
*
* @param subtreeRoot Subtree root target object.
* @param store Optional `UndoStore` where to store the undo/redo queues. Use this if you want to
* store such queues somewhere in your models. If none is provided it will reside in memory.
* @param options Extra options, such as how to save / restore certain snapshot of the state to be restored when undoing/redoing.
* @returns An `UndoManager` which allows you to do the manage the undo/redo operations and dispose of the middleware.
*/
export function undoMiddleware<S>(
subtreeRoot: object,
store?: UndoStore,
options?: UndoMiddlewareOptions<S>
): UndoManager {
assertTweakedObject(subtreeRoot, "subtreeRoot")
let manager: UndoManager
interface PatchRecorderData {
recorder: PatchRecorder
recorderStack: number
undoRootContext: SimpleActionContext
group: UndoEventGroup | undefined
attachedStateBeforeEvent: S | undefined
}
const patchRecorderSymbol = Symbol("patchRecorder")
function initPatchRecorder(ctx: SimpleActionContext) {
const group = manager.store._currentGroup
const patchRecorderData: PatchRecorderData = {
recorder: patchRecorder(subtreeRoot, {
recording: false,
filter: () => {
return !_isGlobalUndoRecordingDisabled && !manager.isUndoRecordingDisabled
},
}),
recorderStack: 0,
undoRootContext: ctx,
group,
attachedStateBeforeEvent: options?.attachedState?.save(),
}
ctx.rootContext.data[patchRecorderSymbol] = patchRecorderData
}
function getPatchRecorderData(ctx: SimpleActionContext): PatchRecorderData {
return ctx.rootContext.data[patchRecorderSymbol]
}
const middlewareDisposer = actionTrackingMiddleware(subtreeRoot, {
onStart(ctx) {
if (!getPatchRecorderData(ctx)) {
initPatchRecorder(ctx)
}
},
onResume(ctx) {
const patchRecorderData = getPatchRecorderData(ctx)
patchRecorderData.recorderStack++
patchRecorderData.recorder.recording = patchRecorderData.recorderStack > 0
},
onSuspend(ctx) {
const patchRecorderData = getPatchRecorderData(ctx)
patchRecorderData.recorderStack--
patchRecorderData.recorder.recording = patchRecorderData.recorderStack > 0
},
onFinish(ctx) {
const patchRecorderData = getPatchRecorderData(ctx)
if (patchRecorderData && patchRecorderData.undoRootContext === ctx) {
const patchRecorder = patchRecorderData.recorder
if (patchRecorder.events.length > 0) {
const patches: Patch[] = []
const inversePatches: Patch[] = []
for (const event of patchRecorder.events) {
patches.push(...event.patches)
inversePatches.push(...event.inversePatches)
}
const event = {
type: UndoEventType.Single,
targetPath: fastGetRootPath(ctx.target).path,
actionName: ctx.actionName,
patches,
inversePatches,
} as const
const parentGroup = patchRecorderData.group
if (parentGroup) {
manager.store._addUndoToParentGroup(parentGroup, event)
} else {
manager.store._addUndo({
...event,
attachedState: {
beforeEvent: patchRecorderData.attachedStateBeforeEvent,
afterEvent: options?.attachedState?.save(),
},
})
}
}
patchRecorder.dispose()
}
},
})
manager = new UndoManager(middlewareDisposer, subtreeRoot, store, options)
return manager
}
let _isGlobalUndoRecordingDisabled = false
/**
* Returns if the undo recording mechanism is currently disabled.
*
* @returns `true` if it is currently disabled, `false` otherwise.
*/
export function isGlobalUndoRecordingDisabled() {
return _isGlobalUndoRecordingDisabled
}
/**
* Globally skips the undo recording mechanism for the code block that gets run synchronously inside.
* Consider using the `withoutUndo` method of a particular `UndoManager` instead.
*
* @typeparam T Code block return type.
* @param fn Code block to run.
* @returns The value returned by the code block.
*/
export function withoutUndo<T>(fn: () => T): T {
const savedUndoDisabled = _isGlobalUndoRecordingDisabled
_isGlobalUndoRecordingDisabled = true
try {
return fn()
} finally {
_isGlobalUndoRecordingDisabled = savedUndoDisabled
}
} | the_stack |
module android.widget {
import Canvas = android.graphics.Canvas;
import Rect = android.graphics.Rect;
import Drawable = android.graphics.drawable.Drawable;
import SoundEffectConstants = android.view.SoundEffectConstants;
import View = android.view.View;
import PositionMetadata = android.widget.ExpandableListConnector.PositionMetadata;
import ArrayList = java.util.ArrayList;
import Adapter = android.widget.Adapter;
import AdapterView = android.widget.AdapterView;
import ExpandableListAdapter = android.widget.ExpandableListAdapter;
import ExpandableListConnector = android.widget.ExpandableListConnector;
import ExpandableListPosition = android.widget.ExpandableListPosition;
import ListAdapter = android.widget.ListAdapter;
import ListView = android.widget.ListView;
import ScrollView = android.widget.ScrollView;
import Long = goog.math.Long;
import AttrBinder = androidui.attr.AttrBinder;
/**
* A view that shows items in a vertically scrolling two-level list. This
* differs from the {@link ListView} by allowing two levels: groups which can
* individually be expanded to show its children. The items come from the
* {@link ExpandableListAdapter} associated with this view.
* <p>
* Expandable lists are able to show an indicator beside each item to display
* the item's current state (the states are usually one of expanded group,
* collapsed group, child, or last child). Use
* {@link #setChildIndicator(Drawable)} or {@link #setGroupIndicator(Drawable)}
* (or the corresponding XML attributes) to set these indicators (see the docs
* for each method to see additional state that each Drawable can have). The
* default style for an {@link ExpandableListView} provides indicators which
* will be shown next to Views given to the {@link ExpandableListView}. The
* layouts android.R.layout.simple_expandable_list_item_1 and
* android.R.layout.simple_expandable_list_item_2 (which should be used with
* {@link SimpleCursorTreeAdapter}) contain the preferred position information
* for indicators.
* <p>
* The context menu information set by an {@link ExpandableListView} will be a
* {@link ExpandableListContextMenuInfo} object with
* {@link ExpandableListContextMenuInfo#packedPosition} being a packed position
* that can be used with {@link #getPackedPositionType(long)} and the other
* similar methods.
* <p>
* <em><b>Note:</b></em> You cannot use the value <code>wrap_content</code>
* for the <code>android:layout_height</code> attribute of a
* ExpandableListView in XML if the parent's size is also not strictly specified
* (for example, if the parent were ScrollView you could not specify
* wrap_content since it also can be any length. However, you can use
* wrap_content if the ExpandableListView parent has a specific size, such as
* 100 pixels.
*
* @attr ref android.R.styleable#ExpandableListView_groupIndicator
* @attr ref android.R.styleable#ExpandableListView_indicatorLeft
* @attr ref android.R.styleable#ExpandableListView_indicatorRight
* @attr ref android.R.styleable#ExpandableListView_childIndicator
* @attr ref android.R.styleable#ExpandableListView_childIndicatorLeft
* @attr ref android.R.styleable#ExpandableListView_childIndicatorRight
* @attr ref android.R.styleable#ExpandableListView_childDivider
* @attr ref android.R.styleable#ExpandableListView_indicatorStart
* @attr ref android.R.styleable#ExpandableListView_indicatorEnd
* @attr ref android.R.styleable#ExpandableListView_childIndicatorStart
* @attr ref android.R.styleable#ExpandableListView_childIndicatorEnd
*/
export class ExpandableListView extends ListView {
/**
* The packed position represents a group.
*/
static PACKED_POSITION_TYPE_GROUP:number = 0;
/**
* The packed position represents a child.
*/
static PACKED_POSITION_TYPE_CHILD:number = 1;
/**
* The packed position represents a neither/null/no preference.
*/
static PACKED_POSITION_TYPE_NULL:number = 2;
/**
* The value for a packed position that represents neither/null/no
* preference. This value is not otherwise possible since a group type
* (first bit 0) should not have a child position filled.
*/
static PACKED_POSITION_VALUE_NULL:number = 0x00000000FFFFFFFF;
/** The mask (in packed position representation) for the child */
private static PACKED_POSITION_MASK_CHILD = Long.fromNumber(0x00000000FFFFFFFF);
/** The mask (in packed position representation) for the group */
private static PACKED_POSITION_MASK_GROUP = Long.fromNumber(0x7FFFFFFF00000000);
/** The mask (in packed position representation) for the type */
private static PACKED_POSITION_MASK_TYPE = Long.fromNumber(0x8000000000000000);
/** The shift amount (in packed position representation) for the group */
private static PACKED_POSITION_SHIFT_GROUP:number = 32;
/** The shift amount (in packed position representation) for the type */
private static PACKED_POSITION_SHIFT_TYPE:number = 63;
/** The mask (in integer child position representation) for the child */
private static PACKED_POSITION_INT_MASK_CHILD = Long.fromNumber(0xFFFFFFFF);
/** The mask (in integer group position representation) for the group */
private static PACKED_POSITION_INT_MASK_GROUP = Long.fromNumber(0x7FFFFFFF);
/** Serves as the glue/translator between a ListView and an ExpandableListView */
private mConnector:ExpandableListConnector;
/** Gives us Views through group+child positions */
private mExpandAdapter:ExpandableListAdapter;
/** Left bound for drawing the indicator. */
private mIndicatorLeft:number = 0;
/** Right bound for drawing the indicator. */
private mIndicatorRight:number = 0;
/** Start bound for drawing the indicator. */
private mIndicatorStart:number = 0;
/** End bound for drawing the indicator. */
private mIndicatorEnd:number = 0;
/**
* Left bound for drawing the indicator of a child. Value of
* {@link #CHILD_INDICATOR_INHERIT} means use mIndicatorLeft.
*/
private mChildIndicatorLeft:number = 0;
/**
* Right bound for drawing the indicator of a child. Value of
* {@link #CHILD_INDICATOR_INHERIT} means use mIndicatorRight.
*/
private mChildIndicatorRight:number = 0;
/**
* Start bound for drawing the indicator of a child. Value of
* {@link #CHILD_INDICATOR_INHERIT} means use mIndicatorStart.
*/
private mChildIndicatorStart:number = 0;
/**
* End bound for drawing the indicator of a child. Value of
* {@link #CHILD_INDICATOR_INHERIT} means use mIndicatorEnd.
*/
private mChildIndicatorEnd:number = 0;
/**
* Denotes when a child indicator should inherit this bound from the generic
* indicator bounds
*/
static CHILD_INDICATOR_INHERIT:number = -1;
/**
* Denotes an undefined value for an indicator
*/
private static INDICATOR_UNDEFINED:number = -2;
/** The indicator drawn next to a group. */
private mGroupIndicator:Drawable;
/** The indicator drawn next to a child. */
private mChildIndicator:Drawable;
/** State indicating the group is expanded. */
private static GROUP_EXPANDED_STATE_SET:number[] = [ View.VIEW_STATE_EXPANDED ];
/** State indicating the group is empty (has no children). */
private static GROUP_EMPTY_STATE_SET:number[] = [ View.VIEW_STATE_EMPTY ];
/** State indicating the group is expanded and empty (has no children). */
private static GROUP_EXPANDED_EMPTY_STATE_SET:number[] = [ View.VIEW_STATE_EXPANDED, View.VIEW_STATE_EMPTY ];
/** States for the group where the 0th bit is expanded and 1st bit is empty. */
private static GROUP_STATE_SETS:number[][] = [
// 00
ExpandableListView.EMPTY_STATE_SET,
// 01
ExpandableListView.GROUP_EXPANDED_STATE_SET,
// 10
ExpandableListView.GROUP_EMPTY_STATE_SET,
// 11
ExpandableListView.GROUP_EXPANDED_EMPTY_STATE_SET ];
/** State indicating the child is the last within its group. */
private static CHILD_LAST_STATE_SET:number[] = [ View.VIEW_STATE_LAST ];
/** Drawable to be used as a divider when it is adjacent to any children */
private mChildDivider:Drawable;
// Bounds of the indicator to be drawn
private mIndicatorRect:Rect = new Rect();
constructor(context:android.content.Context, attrs?:HTMLElement, defStyle=android.R.attr.expandableListViewStyle) {
super(context, attrs, defStyle);
let a = context.obtainStyledAttributes(attrs, defStyle);
this.mGroupIndicator = a.getDrawable('groupIndicator');
this.mChildIndicator = a.getDrawable('childIndicator');
this.mIndicatorLeft = a.getDimensionPixelSize('indicatorLeft', 0);
this.mIndicatorRight = a.getDimensionPixelSize('indicatorRight', 0);
if (this.mIndicatorRight == 0 && this.mGroupIndicator != null) {
this.mIndicatorRight = this.mIndicatorLeft + this.mGroupIndicator.getIntrinsicWidth();
}
this.mChildIndicatorLeft = a.getDimensionPixelSize('childIndicatorLeft', ExpandableListView.CHILD_INDICATOR_INHERIT);
this.mChildIndicatorRight = a.getDimensionPixelSize('childIndicatorRight', ExpandableListView.CHILD_INDICATOR_INHERIT);
this.mChildDivider = a.getDrawable('childDivider');
if (!this.isRtlCompatibilityMode()) {
this.mIndicatorStart = a.getDimensionPixelSize('indicatorStart', ExpandableListView.INDICATOR_UNDEFINED);
this.mIndicatorEnd = a.getDimensionPixelSize('indicatorEnd', ExpandableListView.INDICATOR_UNDEFINED);
this.mChildIndicatorStart = a.getDimensionPixelSize('childIndicatorStart', ExpandableListView.CHILD_INDICATOR_INHERIT);
this.mChildIndicatorEnd = a.getDimensionPixelSize('childIndicatorEnd', ExpandableListView.CHILD_INDICATOR_INHERIT);
}
a.recycle();
}
protected createClassAttrBinder(): androidui.attr.AttrBinder.ClassBinderMap {
return super.createClassAttrBinder().set('groupIndicator', {
setter(v:ExpandableListView, value:any, attrBinder:AttrBinder) {
v.setGroupIndicator(attrBinder.parseDrawable(value));
}, getter(v:ExpandableListView) {
return v.mGroupIndicator;
}
}).set('childIndicator', {
setter(v:ExpandableListView, value:any, attrBinder:AttrBinder) {
v.setChildIndicator(attrBinder.parseDrawable(value));
}, getter(v:ExpandableListView) {
return v.mChildIndicator;
}
}).set('indicatorLeft', {
setter(v:ExpandableListView, value:any, attrBinder:AttrBinder) {
v.setIndicatorBounds(attrBinder.parseNumberPixelOffset(value, 0), v.mIndicatorRight);
}, getter(v:ExpandableListView) {
return v.mIndicatorLeft;
}
}).set('indicatorRight', {
setter(v:ExpandableListView, value:any, attrBinder:AttrBinder) {
let num = attrBinder.parseNumberPixelOffset(value, 0);
if (num == 0 && v.mGroupIndicator != null) {
num = v.mIndicatorLeft + v.mGroupIndicator.getIntrinsicWidth();
}
this.setIndicatorBounds(v.mIndicatorLeft, num);
}, getter(v:ExpandableListView) {
return v.mIndicatorRight;
}
}).set('childIndicatorLeft', {
setter(v:ExpandableListView, value:any, attrBinder:AttrBinder) {
v.setChildIndicatorBounds(attrBinder.parseNumberPixelOffset(value, ExpandableListView.CHILD_INDICATOR_INHERIT), v.mChildIndicatorRight);
}, getter(v:ExpandableListView) {
return v.mChildIndicatorLeft;
}
}).set('childIndicatorRight', {
setter(v:ExpandableListView, value:any, attrBinder:AttrBinder) {
let num = attrBinder.parseNumberPixelOffset(value, ExpandableListView.CHILD_INDICATOR_INHERIT);
if (num == 0 && v.mChildIndicator != null) {
num = v.mChildIndicatorLeft + v.mChildIndicator.getIntrinsicWidth();
}
v.setIndicatorBounds(v.mChildIndicatorLeft, num);
}, getter(v:ExpandableListView) {
return v.mChildIndicatorRight;
}
}).set('childDivider', {
setter(v:ExpandableListView, value:any, attrBinder:AttrBinder) {
v.setChildDivider(attrBinder.parseDrawable(value));
}, getter(v:ExpandableListView) {
return v.mChildDivider;
}
});
}
/**
* Return true if we are in RTL compatibility mode (either before Jelly Bean MR1 or
* RTL not supported)
*/
private isRtlCompatibilityMode():boolean {
return !this.hasRtlSupport();
}
/**
* Return true if the application tag in the AndroidManifest has set "supportRtl" to true
*/
private hasRtlSupport():boolean {
return false;
}
onRtlPropertiesChanged(layoutDirection:number):void {
this.resolveIndicator();
this.resolveChildIndicator();
}
/**
* Resolve start/end indicator. start/end indicator always takes precedence over left/right
* indicator when defined.
*/
private resolveIndicator():void {
const isLayoutRtl:boolean = this.isLayoutRtl();
if (isLayoutRtl) {
if (this.mIndicatorStart >= 0) {
this.mIndicatorRight = this.mIndicatorStart;
}
if (this.mIndicatorEnd >= 0) {
this.mIndicatorLeft = this.mIndicatorEnd;
}
} else {
if (this.mIndicatorStart >= 0) {
this.mIndicatorLeft = this.mIndicatorStart;
}
if (this.mIndicatorEnd >= 0) {
this.mIndicatorRight = this.mIndicatorEnd;
}
}
if (this.mIndicatorRight == 0 && this.mGroupIndicator != null) {
this.mIndicatorRight = this.mIndicatorLeft + this.mGroupIndicator.getIntrinsicWidth();
}
}
/**
* Resolve start/end child indicator. start/end child indicator always takes precedence over
* left/right child indicator when defined.
*/
private resolveChildIndicator():void {
const isLayoutRtl:boolean = this.isLayoutRtl();
if (isLayoutRtl) {
if (this.mChildIndicatorStart >= ExpandableListView.CHILD_INDICATOR_INHERIT) {
this.mChildIndicatorRight = this.mChildIndicatorStart;
}
if (this.mChildIndicatorEnd >= ExpandableListView.CHILD_INDICATOR_INHERIT) {
this.mChildIndicatorLeft = this.mChildIndicatorEnd;
}
} else {
if (this.mChildIndicatorStart >= ExpandableListView.CHILD_INDICATOR_INHERIT) {
this.mChildIndicatorLeft = this.mChildIndicatorStart;
}
if (this.mChildIndicatorEnd >= ExpandableListView.CHILD_INDICATOR_INHERIT) {
this.mChildIndicatorRight = this.mChildIndicatorEnd;
}
}
}
protected dispatchDraw(canvas:Canvas):void {
// Draw children, etc.
super.dispatchDraw(canvas);
// If we have any indicators to draw, we do it here
if ((this.mChildIndicator == null) && (this.mGroupIndicator == null)) {
return;
}
let saveCount:number = 0;
const clipToPadding:boolean = (this.mGroupFlags & ExpandableListView.CLIP_TO_PADDING_MASK) == ExpandableListView.CLIP_TO_PADDING_MASK;
if (clipToPadding) {
saveCount = canvas.save();
const scrollX:number = this.mScrollX;
const scrollY:number = this.mScrollY;
canvas.clipRect(scrollX + this.mPaddingLeft, scrollY + this.mPaddingTop, scrollX + this.mRight - this.mLeft - this.mPaddingRight, scrollY + this.mBottom - this.mTop - this.mPaddingBottom);
}
const headerViewsCount:number = this.getHeaderViewsCount();
const lastChildFlPos:number = this.mItemCount - this.getFooterViewsCount() - headerViewsCount - 1;
const myB:number = this.mBottom;
let pos:PositionMetadata;
let item:View;
let indicator:Drawable;
let t:number, b:number;
// Start at a value that is neither child nor group
let lastItemType:number = ~(ExpandableListPosition.CHILD | ExpandableListPosition.GROUP);
const indicatorRect:Rect = this.mIndicatorRect;
// The "child" mentioned in the following two lines is this
// View's child, not referring to an expandable list's
// notion of a child (as opposed to a group)
const childCount:number = this.getChildCount();
for (let i:number = 0, childFlPos:number = this.mFirstPosition - headerViewsCount; i < childCount; i++, childFlPos++) {
if (childFlPos < 0) {
// This child is header
continue;
} else if (childFlPos > lastChildFlPos) {
// This child is footer, so are all subsequent children
break;
}
item = this.getChildAt(i);
t = item.getTop();
b = item.getBottom();
// This item isn't on the screen
if ((b < 0) || (t > myB))
continue;
// Get more expandable list-related info for this item
pos = this.mConnector.getUnflattenedPos(childFlPos);
const isLayoutRtl:boolean = this.isLayoutRtl();
const width:number = this.getWidth();
// the left & right bounds
if (pos.position.type != lastItemType) {
if (pos.position.type == ExpandableListPosition.CHILD) {
indicatorRect.left = (this.mChildIndicatorLeft == ExpandableListView.CHILD_INDICATOR_INHERIT) ? this.mIndicatorLeft : this.mChildIndicatorLeft;
indicatorRect.right = (this.mChildIndicatorRight == ExpandableListView.CHILD_INDICATOR_INHERIT) ? this.mIndicatorRight : this.mChildIndicatorRight;
} else {
indicatorRect.left = this.mIndicatorLeft;
indicatorRect.right = this.mIndicatorRight;
}
if (isLayoutRtl) {
const temp:number = indicatorRect.left;
indicatorRect.left = width - indicatorRect.right;
indicatorRect.right = width - temp;
indicatorRect.left -= this.mPaddingRight;
indicatorRect.right -= this.mPaddingRight;
} else {
indicatorRect.left += this.mPaddingLeft;
indicatorRect.right += this.mPaddingLeft;
}
lastItemType = pos.position.type;
}
if (indicatorRect.left != indicatorRect.right) {
// Use item's full height + the divider height
if (this.mStackFromBottom) {
// See ListView#dispatchDraw
// - mDividerHeight;
indicatorRect.top = t;
indicatorRect.bottom = b;
} else {
indicatorRect.top = t;
// + mDividerHeight;
indicatorRect.bottom = b;
}
// Get the indicator (with its state set to the item's state)
indicator = this.getIndicator(pos);
if (indicator != null) {
// Draw the indicator
indicator.setBounds(indicatorRect);
indicator.draw(canvas);
}
}
pos.recycle();
}
if (clipToPadding) {
canvas.restoreToCount(saveCount);
}
}
/**
* Gets the indicator for the item at the given position. If the indicator
* is stateful, the state will be given to the indicator.
*
* @param pos The flat list position of the item whose indicator
* should be returned.
* @return The indicator in the proper state.
*/
private getIndicator(pos:PositionMetadata):Drawable {
let indicator:Drawable;
if (pos.position.type == ExpandableListPosition.GROUP) {
indicator = this.mGroupIndicator;
if (indicator != null && indicator.isStateful()) {
// Empty check based on availability of data. If the groupMetadata isn't null,
// we do a check on it. Otherwise, the group is collapsed so we consider it
// empty for performance reasons.
let isEmpty:boolean = (pos.groupMetadata == null) || (pos.groupMetadata.lastChildFlPos == pos.groupMetadata.flPos);
const stateSetIndex:number = // Expanded?
(pos.isExpanded() ? 1 : 0) | // Empty?
(isEmpty ? 2 : 0);
indicator.setState(ExpandableListView.GROUP_STATE_SETS[stateSetIndex]);
}
} else {
indicator = this.mChildIndicator;
if (indicator != null && indicator.isStateful()) {
// No need for a state sets array for the child since it only has two states
const stateSet = pos.position.flatListPos == pos.groupMetadata.lastChildFlPos ? ExpandableListView.CHILD_LAST_STATE_SET : ExpandableListView.EMPTY_STATE_SET;
indicator.setState(stateSet);
}
}
return indicator;
}
/**
* Sets the drawable that will be drawn adjacent to every child in the list. This will
* be drawn using the same height as the normal divider ({@link #setDivider(Drawable)}) or
* if it does not have an intrinsic height, the height set by {@link #setDividerHeight(int)}.
*
* @param childDivider The drawable to use.
*/
setChildDivider(childDivider:Drawable):void {
this.mChildDivider = childDivider;
}
drawDivider(canvas:Canvas, bounds:Rect, childIndex:number):void {
let flatListPosition:number = childIndex + this.mFirstPosition;
// all items, then the item below it has to be a group)
if (flatListPosition >= 0) {
const adjustedPosition:number = this.getFlatPositionForConnector(flatListPosition);
let pos:PositionMetadata = this.mConnector.getUnflattenedPos(adjustedPosition);
// If this item is a child, or it is a non-empty group that is expanded
if ((pos.position.type == ExpandableListPosition.CHILD) || (pos.isExpanded() && pos.groupMetadata.lastChildFlPos != pos.groupMetadata.flPos)) {
// These are the cases where we draw the child divider
const divider:Drawable = this.mChildDivider;
divider.setBounds(bounds);
divider.draw(canvas);
pos.recycle();
return;
}
pos.recycle();
}
// Otherwise draw the default divider
super.drawDivider(canvas, bounds, flatListPosition);
}
/**
* This overloaded method should not be used, instead use
* {@link #setAdapter(ExpandableListAdapter)}.
* <p>
* {@inheritDoc}
*/
setAdapter(adapter:ListAdapter):void {
throw Error(`new RuntimeException("For ExpandableListView, use setAdapter(ExpandableListAdapter) instead of " + "setAdapter(ListAdapter)")`);
}
/**
* This method should not be used, use {@link #getExpandableListAdapter()}.
*/
getAdapter():ListAdapter {
/*
* The developer should never really call this method on an
* ExpandableListView, so it would be nice to throw a RuntimeException,
* but AdapterView calls this
*/
return super.getAdapter();
}
/**
* Register a callback to be invoked when an item has been clicked and the
* caller prefers to receive a ListView-style position instead of a group
* and/or child position. In most cases, the caller should use
* {@link #setOnGroupClickListener} and/or {@link #setOnChildClickListener}.
* <p />
* {@inheritDoc}
*/
setOnItemClickListener(l:AdapterView.OnItemClickListener):void {
super.setOnItemClickListener(l);
}
/**
* Sets the adapter that provides data to this view.
* @param adapter The adapter that provides data to this view.
*/
setExpandableAdapter(adapter:ExpandableListAdapter):void {
// Set member variable
this.mExpandAdapter = adapter;
if (adapter != null) {
// Create the connector
this.mConnector = new ExpandableListConnector(adapter);
} else {
this.mConnector = null;
}
// Link the ListView (superclass) to the expandable list data through the connector
super.setAdapter(this.mConnector);
}
/**
* Gets the adapter that provides data to this view.
* @return The adapter that provides data to this view.
*/
getExpandableListAdapter():ExpandableListAdapter {
return this.mExpandAdapter;
}
/**
* @param position An absolute (including header and footer) flat list position.
* @return true if the position corresponds to a header or a footer item.
*/
private isHeaderOrFooterPosition(position:number):boolean {
const footerViewsStart:number = this.mItemCount - this.getFooterViewsCount();
return (position < this.getHeaderViewsCount() || position >= footerViewsStart);
}
/**
* Converts an absolute item flat position into a group/child flat position, shifting according
* to the number of header items.
*
* @param flatListPosition The absolute flat position
* @return A group/child flat position as expected by the connector.
*/
private getFlatPositionForConnector(flatListPosition:number):number {
return flatListPosition - this.getHeaderViewsCount();
}
/**
* Converts a group/child flat position into an absolute flat position, that takes into account
* the possible headers.
*
* @param flatListPosition The child/group flat position
* @return An absolute flat position.
*/
private getAbsoluteFlatPosition(flatListPosition:number):number {
return flatListPosition + this.getHeaderViewsCount();
}
performItemClick(v:View, position:number, id:number):boolean {
// Ignore clicks in header/footers
if (this.isHeaderOrFooterPosition(position)) {
// Clicked on a header/footer, so ignore pass it on to super
return super.performItemClick(v, position, id);
}
// Internally handle the item click
const adjustedPosition:number = this.getFlatPositionForConnector(position);
return this.handleItemClick(v, adjustedPosition, id);
}
/**
* This will either expand/collapse groups (if a group was clicked) or pass
* on the click to the proper child (if a child was clicked)
*
* @param position The flat list position. This has already been factored to
* remove the header/footer.
* @param id The ListAdapter ID, not the group or child ID.
*/
handleItemClick(v:View, position:number, id:number):boolean {
const posMetadata:PositionMetadata = this.mConnector.getUnflattenedPos(position);
id = this.getChildOrGroupId(posMetadata.position);
let returnValue:boolean;
if (posMetadata.position.type == ExpandableListPosition.GROUP) {
/* It's a group click, so pass on event */
if (this.mOnGroupClickListener != null) {
if (this.mOnGroupClickListener.onGroupClick(this, v, posMetadata.position.groupPos, id)) {
posMetadata.recycle();
return true;
}
}
if (posMetadata.isExpanded()) {
/* Collapse it */
this.mConnector.collapseGroupWithMeta(posMetadata);
this.playSoundEffect(SoundEffectConstants.CLICK);
if (this.mOnGroupCollapseListener != null) {
this.mOnGroupCollapseListener.onGroupCollapse(posMetadata.position.groupPos);
}
} else {
/* Expand it */
this.mConnector.expandGroupWithMeta(posMetadata);
this.playSoundEffect(SoundEffectConstants.CLICK);
if (this.mOnGroupExpandListener != null) {
this.mOnGroupExpandListener.onGroupExpand(posMetadata.position.groupPos);
}
const groupPos:number = posMetadata.position.groupPos;
const groupFlatPos:number = posMetadata.position.flatListPos;
const shiftedGroupPosition:number = groupFlatPos + this.getHeaderViewsCount();
this.smoothScrollToPosition(shiftedGroupPosition + this.mExpandAdapter.getChildrenCount(groupPos), shiftedGroupPosition);
}
returnValue = true;
} else {
/* It's a child, so pass on event */
if (this.mOnChildClickListener != null) {
this.playSoundEffect(SoundEffectConstants.CLICK);
return this.mOnChildClickListener.onChildClick(this, v, posMetadata.position.groupPos, posMetadata.position.childPos, id);
}
returnValue = false;
}
posMetadata.recycle();
return returnValue;
}
/**
* Expand a group in the grouped list view
*
* @param groupPos the group to be expanded
* @param animate true if the expanding group should be animated in
* @return True if the group was expanded, false otherwise (if the group
* was already expanded, this will return false)
*/
expandGroup(groupPos:number, animate=false):boolean {
let elGroupPos:ExpandableListPosition = ExpandableListPosition.obtain(ExpandableListPosition.GROUP, groupPos, -1, -1);
let pm:PositionMetadata = this.mConnector.getFlattenedPos(elGroupPos);
elGroupPos.recycle();
let retValue:boolean = this.mConnector.expandGroupWithMeta(pm);
if (this.mOnGroupExpandListener != null) {
this.mOnGroupExpandListener.onGroupExpand(groupPos);
}
if (animate) {
const groupFlatPos:number = pm.position.flatListPos;
const shiftedGroupPosition:number = groupFlatPos + this.getHeaderViewsCount();
this.smoothScrollToPosition(shiftedGroupPosition + this.mExpandAdapter.getChildrenCount(groupPos), shiftedGroupPosition);
}
pm.recycle();
return retValue;
}
/**
* Collapse a group in the grouped list view
*
* @param groupPos position of the group to collapse
* @return True if the group was collapsed, false otherwise (if the group
* was already collapsed, this will return false)
*/
collapseGroup(groupPos:number):boolean {
let retValue:boolean = this.mConnector.collapseGroup(groupPos);
if (this.mOnGroupCollapseListener != null) {
this.mOnGroupCollapseListener.onGroupCollapse(groupPos);
}
return retValue;
}
private mOnGroupCollapseListener:ExpandableListView.OnGroupCollapseListener;
setOnGroupCollapseListener(onGroupCollapseListener:ExpandableListView.OnGroupCollapseListener):void {
this.mOnGroupCollapseListener = onGroupCollapseListener;
}
private mOnGroupExpandListener:ExpandableListView.OnGroupExpandListener;
setOnGroupExpandListener(onGroupExpandListener:ExpandableListView.OnGroupExpandListener):void {
this.mOnGroupExpandListener = onGroupExpandListener;
}
private mOnGroupClickListener:ExpandableListView.OnGroupClickListener;
setOnGroupClickListener(onGroupClickListener:ExpandableListView.OnGroupClickListener):void {
this.mOnGroupClickListener = onGroupClickListener;
}
private mOnChildClickListener:ExpandableListView.OnChildClickListener;
setOnChildClickListener(onChildClickListener:ExpandableListView.OnChildClickListener):void {
this.mOnChildClickListener = onChildClickListener;
}
/**
* Converts a flat list position (the raw position of an item (child or group)
* in the list) to a group and/or child position (represented in a
* packed position). This is useful in situations where the caller needs to
* use the underlying {@link ListView}'s methods. Use
* {@link ExpandableListView#getPackedPositionType} ,
* {@link ExpandableListView#getPackedPositionChild},
* {@link ExpandableListView#getPackedPositionGroup} to unpack.
*
* @param flatListPosition The flat list position to be converted.
* @return The group and/or child position for the given flat list position
* in packed position representation. #PACKED_POSITION_VALUE_NULL if
* the position corresponds to a header or a footer item.
*/
getExpandableListPosition(flatListPosition:number):number {
if (this.isHeaderOrFooterPosition(flatListPosition)) {
return ExpandableListView.PACKED_POSITION_VALUE_NULL;
}
const adjustedPosition:number = this.getFlatPositionForConnector(flatListPosition);
let pm:PositionMetadata = this.mConnector.getUnflattenedPos(adjustedPosition);
let packedPos:number = pm.position.getPackedPosition();
pm.recycle();
return packedPos;
}
/**
* Converts a group and/or child position to a flat list position. This is
* useful in situations where the caller needs to use the underlying
* {@link ListView}'s methods.
*
* @param packedPosition The group and/or child positions to be converted in
* packed position representation. Use
* {@link #getPackedPositionForChild(int, int)} or
* {@link #getPackedPositionForGroup(int)}.
* @return The flat list position for the given child or group.
*/
getFlatListPosition(packedPosition:number):number {
let elPackedPos:ExpandableListPosition = ExpandableListPosition.obtainPosition(packedPosition);
let pm:PositionMetadata = this.mConnector.getFlattenedPos(elPackedPos);
elPackedPos.recycle();
const flatListPosition:number = pm.position.flatListPos;
pm.recycle();
return this.getAbsoluteFlatPosition(flatListPosition);
}
/**
* Gets the position of the currently selected group or child (along with
* its type). Can return {@link #PACKED_POSITION_VALUE_NULL} if no selection.
*
* @return A packed position containing the currently selected group or
* child's position and type. #PACKED_POSITION_VALUE_NULL if no selection
* or if selection is on a header or a footer item.
*/
getSelectedPosition():number {
const selectedPos:number = this.getSelectedItemPosition();
// The case where there is no selection (selectedPos == -1) is also handled here.
return this.getExpandableListPosition(selectedPos);
}
/**
* Gets the ID of the currently selected group or child. Can return -1 if no
* selection.
*
* @return The ID of the currently selected group or child. -1 if no
* selection.
*/
getSelectedId():number {
let packedPos:number = this.getSelectedPosition();
if (packedPos == ExpandableListView.PACKED_POSITION_VALUE_NULL)
return -1;
let groupPos:number = ExpandableListView.getPackedPositionGroup(packedPos);
if (ExpandableListView.getPackedPositionType(packedPos) == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
// It's a group
return this.mExpandAdapter.getGroupId(groupPos);
} else {
// It's a child
return this.mExpandAdapter.getChildId(groupPos, ExpandableListView.getPackedPositionChild(packedPos));
}
}
/**
* Sets the selection to the specified group.
* @param groupPosition The position of the group that should be selected.
*/
setSelectedGroup(groupPosition:number):void {
let elGroupPos:ExpandableListPosition = ExpandableListPosition.obtainGroupPosition(groupPosition);
let pm:PositionMetadata = this.mConnector.getFlattenedPos(elGroupPos);
elGroupPos.recycle();
const absoluteFlatPosition:number = this.getAbsoluteFlatPosition(pm.position.flatListPos);
super.setSelection(absoluteFlatPosition);
pm.recycle();
}
/**
* Sets the selection to the specified child. If the child is in a collapsed
* group, the group will only be expanded and child subsequently selected if
* shouldExpandGroup is set to true, otherwise the method will return false.
*
* @param groupPosition The position of the group that contains the child.
* @param childPosition The position of the child within the group.
* @param shouldExpandGroup Whether the child's group should be expanded if
* it is collapsed.
* @return Whether the selection was successfully set on the child.
*/
setSelectedChild(groupPosition:number, childPosition:number, shouldExpandGroup:boolean):boolean {
let elChildPos:ExpandableListPosition = ExpandableListPosition.obtainChildPosition(groupPosition, childPosition);
let flatChildPos:PositionMetadata = this.mConnector.getFlattenedPos(elChildPos);
if (flatChildPos == null) {
// Shouldn't expand the group, so return false for we didn't set the selection
if (!shouldExpandGroup)
return false;
this.expandGroup(groupPosition);
flatChildPos = this.mConnector.getFlattenedPos(elChildPos);
// Sanity check
if (flatChildPos == null) {
throw Error(`new IllegalStateException("Could not find child")`);
}
}
let absoluteFlatPosition:number = this.getAbsoluteFlatPosition(flatChildPos.position.flatListPos);
super.setSelection(absoluteFlatPosition);
elChildPos.recycle();
flatChildPos.recycle();
return true;
}
/**
* Whether the given group is currently expanded.
*
* @param groupPosition The group to check.
* @return Whether the group is currently expanded.
*/
isGroupExpanded(groupPosition:number):boolean {
return this.mConnector.isGroupExpanded(groupPosition);
}
/**
* Gets the type of a packed position. See
* {@link #getPackedPositionForChild(int, int)}.
*
* @param packedPosition The packed position for which to return the type.
* @return The type of the position contained within the packed position,
* either {@link #PACKED_POSITION_TYPE_CHILD}, {@link #PACKED_POSITION_TYPE_GROUP}, or
* {@link #PACKED_POSITION_TYPE_NULL}.
*/
static getPackedPositionType(packedPosition:number):number {
if (packedPosition == ExpandableListView.PACKED_POSITION_VALUE_NULL) {
return ExpandableListView.PACKED_POSITION_TYPE_NULL;
}
//return (packedPosition & ExpandableListView.PACKED_POSITION_MASK_TYPE) == ExpandableListView.PACKED_POSITION_MASK_TYPE
// ? ExpandableListView.PACKED_POSITION_TYPE_CHILD : ExpandableListView.PACKED_POSITION_TYPE_GROUP;
return (Long.fromNumber(packedPosition).and(ExpandableListView.PACKED_POSITION_MASK_TYPE)).equals(ExpandableListView.PACKED_POSITION_MASK_TYPE)
? ExpandableListView.PACKED_POSITION_TYPE_CHILD : ExpandableListView.PACKED_POSITION_TYPE_GROUP;
}
/**
* Gets the group position from a packed position. See
* {@link #getPackedPositionForChild(int, int)}.
*
* @param packedPosition The packed position from which the group position
* will be returned.
* @return The group position portion of the packed position. If this does
* not contain a group, returns -1.
*/
static getPackedPositionGroup(packedPosition:number):number {
// Null
if (packedPosition == ExpandableListView.PACKED_POSITION_VALUE_NULL)
return -1;
//return (packedPosition & ExpandableListView.PACKED_POSITION_MASK_GROUP) >> ExpandableListView.PACKED_POSITION_SHIFT_GROUP;
return (Long.fromNumber(packedPosition).and(ExpandableListView.PACKED_POSITION_MASK_GROUP))
.shiftRight(ExpandableListView.PACKED_POSITION_SHIFT_GROUP).toNumber();
}
/**
* Gets the child position from a packed position that is of
* {@link #PACKED_POSITION_TYPE_CHILD} type (use {@link #getPackedPositionType(long)}).
* To get the group that this child belongs to, use
* {@link #getPackedPositionGroup(long)}. See
* {@link #getPackedPositionForChild(int, int)}.
*
* @param packedPosition The packed position from which the child position
* will be returned.
* @return The child position portion of the packed position. If this does
* not contain a child, returns -1.
*/
static getPackedPositionChild(packedPosition:number):number {
// Null
if (packedPosition == ExpandableListView.PACKED_POSITION_VALUE_NULL)
return -1;
// Group since a group type clears this bit
//if ((packedPosition & ExpandableListView.PACKED_POSITION_MASK_TYPE) != ExpandableListView.PACKED_POSITION_MASK_TYPE)
if ((Long.fromNumber(packedPosition).and(ExpandableListView.PACKED_POSITION_MASK_TYPE)).notEquals(ExpandableListView.PACKED_POSITION_MASK_TYPE))
return -1;
return Long.fromNumber(packedPosition).and(ExpandableListView.PACKED_POSITION_MASK_CHILD).toNumber();
}
/**
* Returns the packed position representation of a child's position.
* <p>
* In general, a packed position should be used in
* situations where the position given to/returned from an
* {@link ExpandableListAdapter} or {@link ExpandableListView} method can
* either be a child or group. The two positions are packed into a single
* long which can be unpacked using
* {@link #getPackedPositionChild(long)},
* {@link #getPackedPositionGroup(long)}, and
* {@link #getPackedPositionType(long)}.
*
* @param groupPosition The child's parent group's position.
* @param childPosition The child position within the group.
* @return The packed position representation of the child (and parent group).
*/
static getPackedPositionForChild(groupPosition:number, childPosition:number):number {
//return (ExpandableListView.PACKED_POSITION_TYPE_CHILD << ExpandableListView.PACKED_POSITION_SHIFT_TYPE)
// | ((groupPosition & ExpandableListView.PACKED_POSITION_INT_MASK_GROUP) << ExpandableListView.PACKED_POSITION_SHIFT_GROUP)
// | (childPosition & ExpandableListView.PACKED_POSITION_INT_MASK_CHILD);
return Long.fromInt(ExpandableListView.PACKED_POSITION_TYPE_CHILD).shiftLeft(ExpandableListView.PACKED_POSITION_SHIFT_TYPE)
.or(Long.fromNumber(groupPosition).and(ExpandableListView.PACKED_POSITION_INT_MASK_GROUP).shiftLeft(ExpandableListView.PACKED_POSITION_SHIFT_GROUP))
.or(Long.fromNumber(childPosition).and(ExpandableListView.PACKED_POSITION_INT_MASK_CHILD)).toNumber();
}
/**
* Returns the packed position representation of a group's position. See
* {@link #getPackedPositionForChild(int, int)}.
*
* @param groupPosition The child's parent group's position.
* @return The packed position representation of the group.
*/
static getPackedPositionForGroup(groupPosition:number):number {
// No need to OR a type in because PACKED_POSITION_GROUP == 0
//return ((groupPosition & ExpandableListView.PACKED_POSITION_INT_MASK_GROUP) << ExpandableListView.PACKED_POSITION_SHIFT_GROUP);
return Long.fromInt(groupPosition).and(ExpandableListView.PACKED_POSITION_INT_MASK_GROUP)
.shiftLeft(ExpandableListView.PACKED_POSITION_SHIFT_GROUP).toNumber();
}
//createContextMenuInfo(view:View, flatListPosition:number, id:number):ContextMenuInfo {
// if (this.isHeaderOrFooterPosition(flatListPosition)) {
// // Return normal info for header/footer view context menus
// return new AdapterView.AdapterContextMenuInfo(view, flatListPosition, id);
// }
// const adjustedPosition:number = this.getFlatPositionForConnector(flatListPosition);
// let pm:PositionMetadata = this.mConnector.getUnflattenedPos(adjustedPosition);
// let pos:ExpandableListPosition = pm.position;
// id = this.getChildOrGroupId(pos);
// let packedPosition:number = pos.getPackedPosition();
// pm.recycle();
// return new ExpandableListView.ExpandableListContextMenuInfo(view, packedPosition, id);
//}
/**
* Gets the ID of the group or child at the given <code>position</code>.
* This is useful since there is no ListAdapter ID -> ExpandableListAdapter
* ID conversion mechanism (in some cases, it isn't possible).
*
* @param position The position of the child or group whose ID should be
* returned.
*/
private getChildOrGroupId(position:ExpandableListPosition):number {
if (position.type == ExpandableListPosition.CHILD) {
return this.mExpandAdapter.getChildId(position.groupPos, position.childPos);
} else {
return this.mExpandAdapter.getGroupId(position.groupPos);
}
}
/**
* Sets the indicator to be drawn next to a child.
*
* @param childIndicator The drawable to be used as an indicator. If the
* child is the last child for a group, the state
* {@link android.R.attr#state_last} will be set.
*/
setChildIndicator(childIndicator:Drawable):void {
this.mChildIndicator = childIndicator;
}
/**
* Sets the drawing bounds for the child indicator. For either, you can
* specify {@link #CHILD_INDICATOR_INHERIT} to use inherit from the general
* indicator's bounds.
*
* @see #setIndicatorBounds(int, int)
* @param left The left position (relative to the left bounds of this View)
* to start drawing the indicator.
* @param right The right position (relative to the left bounds of this
* View) to end the drawing of the indicator.
*/
setChildIndicatorBounds(left:number, right:number):void {
this.mChildIndicatorLeft = left;
this.mChildIndicatorRight = right;
this.resolveChildIndicator();
}
/**
* Sets the relative drawing bounds for the child indicator. For either, you can
* specify {@link #CHILD_INDICATOR_INHERIT} to use inherit from the general
* indicator's bounds.
*
* @see #setIndicatorBounds(int, int)
* @param start The start position (relative to the start bounds of this View)
* to start drawing the indicator.
* @param end The end position (relative to the end bounds of this
* View) to end the drawing of the indicator.
*/
setChildIndicatorBoundsRelative(start:number, end:number):void {
this.mChildIndicatorStart = start;
this.mChildIndicatorEnd = end;
this.resolveChildIndicator();
}
/**
* Sets the indicator to be drawn next to a group.
*
* @param groupIndicator The drawable to be used as an indicator. If the
* group is empty, the state {@link android.R.attr#state_empty} will be
* set. If the group is expanded, the state
* {@link android.R.attr#state_expanded} will be set.
*/
setGroupIndicator(groupIndicator:Drawable):void {
this.mGroupIndicator = groupIndicator;
if (this.mIndicatorRight == 0 && this.mGroupIndicator != null) {
this.mIndicatorRight = this.mIndicatorLeft + this.mGroupIndicator.getIntrinsicWidth();
}
}
/**
* Sets the drawing bounds for the indicators (at minimum, the group indicator
* is affected by this; the child indicator is affected by this if the
* child indicator bounds are set to inherit).
*
* @see #setChildIndicatorBounds(int, int)
* @param left The left position (relative to the left bounds of this View)
* to start drawing the indicator.
* @param right The right position (relative to the left bounds of this
* View) to end the drawing of the indicator.
*/
setIndicatorBounds(left:number, right:number):void {
this.mIndicatorLeft = left;
this.mIndicatorRight = right;
this.resolveIndicator();
}
/**
* Sets the relative drawing bounds for the indicators (at minimum, the group indicator
* is affected by this; the child indicator is affected by this if the
* child indicator bounds are set to inherit).
*
* @see #setChildIndicatorBounds(int, int)
* @param start The start position (relative to the start bounds of this View)
* to start drawing the indicator.
* @param end The end position (relative to the end bounds of this
* View) to end the drawing of the indicator.
*/
setIndicatorBoundsRelative(start:number, end:number):void {
this.mIndicatorStart = start;
this.mIndicatorEnd = end;
this.resolveIndicator();
}
}
export module ExpandableListView{
/** Used for being notified when a group is collapsed */
export interface OnGroupCollapseListener {
/**
* Callback method to be invoked when a group in this expandable list has
* been collapsed.
*
* @param groupPosition The group position that was collapsed
*/
onGroupCollapse(groupPosition:number):void ;
}
/** Used for being notified when a group is expanded */
export interface OnGroupExpandListener {
/**
* Callback method to be invoked when a group in this expandable list has
* been expanded.
*
* @param groupPosition The group position that was expanded
*/
onGroupExpand(groupPosition:number):void ;
}
/**
* Interface definition for a callback to be invoked when a group in this
* expandable list has been clicked.
*/
export interface OnGroupClickListener {
/**
* Callback method to be invoked when a group in this expandable list has
* been clicked.
*
* @param parent The ExpandableListConnector where the click happened
* @param v The view within the expandable list/ListView that was clicked
* @param groupPosition The group position that was clicked
* @param id The row id of the group that was clicked
* @return True if the click was handled
*/
onGroupClick(parent:ExpandableListView, v:View, groupPosition:number, id:number):boolean ;
}
/**
* Interface definition for a callback to be invoked when a child in this
* expandable list has been clicked.
*/
export interface OnChildClickListener {
/**
* Callback method to be invoked when a child in this expandable list has
* been clicked.
*
* @param parent The ExpandableListView where the click happened
* @param v The view within the expandable list/ListView that was clicked
* @param groupPosition The group position that contains the child that
* was clicked
* @param childPosition The child position within the group
* @param id The row id of the child that was clicked
* @return True if the click was handled
*/
onChildClick(parent:ExpandableListView, v:View, groupPosition:number, childPosition:number, id:number):boolean ;
}
}
} | the_stack |
import { compileShader, createProgram, createTexture, calculateProjection, textureEnum } from './utils';
import { Matrix4, Vector3, Vector4 } from './matrix';
import { Camera } from './objects/index';
import parseHDR from 'parse-hdr';
import vertex from './shaders/env.webgpu.vert';
import cube from './shaders/cube.webgpu.frag';
import irradiance from './shaders/irradiance.webgpu.frag';
import cubeMipmap from './shaders/cube-mipmap.webgpu.frag';
import bdrf from './shaders/bdrf.webgpu.frag';
import quad from './shaders/quad.webgpu.glsl';
import { cubeVertex, quadFull } from './vertex';
import { SphericalHarmonics, SphericalPolynomial } from './SH';
import { UniformBuffer } from './objects/uniform';
let gl;
interface Texture extends WebGLTexture {
index: number;
}
interface FrameBuffer extends WebGLFramebuffer {
size: number;
}
interface IBLData {
specularImages: Array<Array<HTMLImageElement>>;
}
export class Env {
camera: Camera;
envMatrix: Matrix4;
VAO: WebGLBuffer;
quadVAO: WebGLBuffer;
IndexBufferLength: number;
cubeprogram: WebGLProgram;
irradianceprogram: WebGLProgram;
mipmapcubeprogram: WebGLProgram;
bdrfprogram: WebGLProgram;
level: WebGLUniformLocation;
diffuse: WebGLUniformLocation;
MVPMatrix: WebGLUniformLocation;
framebuffer: FrameBuffer;
irradiancebuffer: FrameBuffer;
prefilterbuffer: FrameBuffer;
views: Array<Matrix4>;
prefilterrender: WebGLRenderbuffer;
brdfbuffer: FrameBuffer;
canvas: HTMLCanvasElement;
url: string;
sampler: WebGLTexture;
samplerCube: WebGLTexture;
envData: IBLData;
uniformBuffer: UniformBuffer;
originalCubeTexture: GPUTexture;
brdfLUTTexture: Texture;
original2DTexture: Texture;
irradiancemap: Texture;
prefilterMap: Texture;
Sheen_E: Texture;
prefilterTexture: GPUTexture;
irradianceTexture: GPUTexture;
tempTexture: GPUTexture;
bdrfTexture: GPUTexture;
cubeTexture: GPUTexture;
constructor(url) {
this.url = url;
this.envMatrix = new Matrix4();
}
setCamera(camera) {
this.camera = camera;
}
setGl(g) {
gl = g;
}
setCanvas(canvas) {
this.canvas = canvas;
}
get width() {
return this.canvas.offsetWidth * devicePixelRatio;
}
get height() {
return this.canvas.offsetHeight * devicePixelRatio;
}
drawQuad(WebGPU: WEBGPU) {
const m = new Matrix4();
const cam = Object.assign({}, this.camera.props, {
perspective: {
yfov: 0.3,
znear: 0.01,
zfar: 10000
}
});
m.multiply(calculateProjection(cam));
const vertex = `#version 460
precision highp float;
layout (location = 0) in vec2 inPosition;
layout (location = 0) out vec2 outUV;
//uniform mat4 projection;
//uniform mat4 view;
void main() {
outUV = inPosition * 0.5 + 0.5;
gl_Position = vec4(inPosition, 0.0, 1.0);
}
`;
const fragment = `#version 460
precision highp float;
layout (location = 0) in vec2 outUV;
layout (location = 0) out vec4 color;
layout(set = 0, binding = 0) uniform sampler baseSampler;
layout(set = 0, binding = 1) uniform texture2D environmentMap;
void main() {
vec3 c = texture(sampler2D(environmentMap, baseSampler), outUV).rgb;
color = vec4(c, 1.0);
}
`;
//gl.uniformMatrix4fv(gl.getUniformLocation(program, 'projection'), false, m.elements);
//gl.uniformMatrix4fv(gl.getUniformLocation(program, 'view'), false, this.camera.matrixWorldInvert.elements);
const { device, context } = WebGPU;
let pass;
{
const depthTexture = device.createTexture({
size: [this.width, this.height, 1],
usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
format: 'depth32float'
});
const depthTextureView = depthTexture.createView();
pass = {
colorAttachments: [
{
view: context.getCurrentTexture().createView(),
loadValue: { r: 0, g: 0, b: 0, a: 1.0 }
}
],
depthStencilAttachment: {
view: depthTextureView,
depthLoadValue: 1.0,
depthStoreOp: 'store',
stencilLoadValue: 0,
stencilStoreOp: 'store'
}
};
}
const sampler = device.createSampler({
magFilter: 'linear',
minFilter: 'linear',
addressModeU: 'clamp-to-edge',
addressModeV: 'clamp-to-edge',
addressModeW: 'clamp-to-edge'
});
const entries = [
{
binding: 0,
resource: sampler
},
{
binding: 1,
resource: this.bdrfTexture.createView()
}
];
const commandEncoder = device.createCommandEncoder();
const shadowPass = commandEncoder.beginRenderPass(pass);
const p = this.buildPipeline(
WebGPU,
vertex,
fragment,
2,
[
{
binding: 0,
visibility: GPUShaderStage.FRAGMENT,
sampler: {}
},
{
binding: 1,
visibility: GPUShaderStage.FRAGMENT,
texture: {}
}
],
true
);
shadowPass.setPipeline(p);
shadowPass.setVertexBuffer(0, this.buildVertex(WebGPU, quadFull));
shadowPass.setBindGroup(
0,
device.createBindGroup({
layout: p.getBindGroupLayout(0),
entries
})
);
shadowPass.draw(6);
shadowPass.endPass();
device.queue.submit([commandEncoder.finish()]);
}
drawCube(WebGPU: WEBGPU) {
const { device, context } = WebGPU;
const m = new Matrix4();
const cam = Object.assign({}, this.camera.props, {
perspective: {
yfov: 0.3,
znear: 0.01,
zfar: 10000
}
});
m.multiply(calculateProjection(cam));
const uniformBuffer = new UniformBuffer();
uniformBuffer.add('view', this.camera.matrixWorldInvert.elements);
uniformBuffer.add('projection', m.elements);
uniformBuffer.done();
const matrixSize = uniformBuffer.store.byteLength;
const offset = 256; // uniformBindGroup offset must be 256-byte aligned
const uniformBufferSize = offset + matrixSize;
const u = device.createBuffer({
size: uniformBufferSize,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
});
device.queue.writeBuffer(u, 0, uniformBuffer.store.buffer, uniformBuffer.store.byteOffset, uniformBuffer.store.byteLength);
const vertex = `#version 460
precision highp float;
layout (location = 0) in vec3 inPosition;
layout (location = 0) out vec3 outUV;
layout(set = 0, binding = 0) uniform Uniforms {
mat4 view;
mat4 projection;
} uniforms;
void main() {
outUV = inPosition;
gl_Position = uniforms.projection * uniforms.view * vec4(inPosition, 1.0);
}
`;
const fragment = `#version 460
precision highp float;
layout (location = 0) in vec3 outUV;
layout (location = 0) out vec4 color;
layout(set = 0, binding = 1) uniform sampler baseSampler;
layout(set = 0, binding = 2) uniform textureCube environmentMap;
void main() {
vec3 c = textureLod(samplerCube(environmentMap, baseSampler), outUV, 0.0).rgb;
color = vec4(c, 1.0);
}
`;
let pass;
{
const depthTexture = device.createTexture({
size: [this.width, this.height, 1],
usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
format: 'depth32float'
});
const depthTextureView = depthTexture.createView();
pass = {
colorAttachments: [
{
view: context.getCurrentTexture().createView(),
loadValue: { r: 0, g: 0, b: 0, a: 1.0 }
}
],
depthStencilAttachment: {
view: depthTextureView,
depthLoadValue: 1.0,
depthStoreOp: 'store',
stencilLoadValue: 0,
stencilStoreOp: 'store'
}
};
}
const sampler = device.createSampler({
magFilter: 'linear',
minFilter: 'linear',
addressModeU: 'clamp-to-edge',
addressModeV: 'clamp-to-edge',
addressModeW: 'clamp-to-edge'
});
const entries = [
{
binding: 0,
resource: {
buffer: u,
offset: 0,
size: matrixSize
}
},
{
binding: 1,
resource: sampler
},
{
binding: 2,
resource: this.prefilterTexture.createView({
dimension: 'cube'
})
}
];
const commandEncoder = device.createCommandEncoder();
const shadowPass = commandEncoder.beginRenderPass(pass);
const p = this.buildPipeline(
WebGPU,
vertex,
fragment,
3,
[
{
binding: 0,
visibility: GPUShaderStage.VERTEX,
buffer: {}
},
{
binding: 1,
visibility: GPUShaderStage.FRAGMENT,
sampler: {}
},
{
binding: 2,
visibility: GPUShaderStage.FRAGMENT,
texture: {
viewDimension: 'cube'
}
}
],
true
);
shadowPass.setPipeline(p);
shadowPass.setVertexBuffer(0, this.buildVertex(WebGPU, cubeVertex));
shadowPass.setBindGroup(
0,
device.createBindGroup({
layout: p.getBindGroupLayout(0),
entries
})
);
shadowPass.draw(36);
shadowPass.endPass();
device.queue.submit([commandEncoder.finish()]);
}
async createTexture(WebGPU: WEBGPU) {
const views = [
[new Vector3([0, 1, 0]), Math.PI / 2], // Right
[new Vector3([0, 1, 0]), -Math.PI / 2], // Left
[new Vector3([1, 0, 0]), Math.PI / 2], // Top
[new Vector3([1, 0, 0]), -Math.PI / 2], // Bottom
[new Vector3([0, 1, 0]), Math.PI], // Front
[new Vector3([0, 1, 0]), 0] // Back
];
this.views = views.map((view, i) => {
const camMatrix = new Matrix4();
camMatrix.makeRotationAxis(view[0], view[1]);
if (i !== 2 && i !== 3) {
const m = new Matrix4();
m.makeRotationAxis(new Vector3([0, 0, 1]), Math.PI);
camMatrix.multiply(m);
}
return new Matrix4().setInverseOf(camMatrix);
});
const { device } = WebGPU;
await fetch(this.url)
.then(res => res.arrayBuffer())
.then(buffer => {
const { data, shape } = parseHDR(buffer);
// const uniformBuffer = device.createBuffer({
// size: data.byteLength,
// usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
// });
// device.queue.writeBuffer(
// uniformBuffer,
// 0,
// data.buffer,
// data.byteOffset,
// data.byteLength
// );
const img = new Float32Array(data.length);
let k;
let r;
let g;
let b;
let a;
let m;
for (let j = 0; j <= shape[1]; j++) {
for (let i = 0; i <= shape[0]; i++) {
k = j * shape[0] + i;
r = data[4 * k];
g = data[4 * k + 1];
b = data[4 * k + 2];
a = data[4 * k + 3];
m = (shape[1] - j + 1) * shape[0] + i;
img[4 * m] = r;
img[4 * m + 1] = g;
img[4 * m + 2] = b;
img[4 * m + 3] = a;
}
}
const tex = device.createTexture({
size: [shape[0], shape[1], 1],
format: 'rgba16float', // TODO 16 filtered vs 32 non-filtered
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST
});
const bytesPerRow = shape[0] * 4 * 4;
device.queue.writeTexture(
{ texture: tex },
img,
{
// offset: 0,
bytesPerRow
// rowsPerImage: shape[1]
},
[shape[0], shape[1], 1]
);
this.originalCubeTexture = tex;
return tex;
});
}
buildPass(WebGPU, size) {
const { device } = WebGPU;
const depthTexture = device.createTexture({
size: [size, size, 1],
usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING,
format: 'depth32float'
});
const depthTextureView = depthTexture.createView();
const colorTexture = device.createTexture({
size: [size, size, 1],
usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_SRC,
format: 'rgba16float'
});
this.tempTexture = colorTexture;
const colorTextureView = colorTexture.createView();
return {
colorAttachments: [
{
view: colorTextureView,
storeOp: 'store' as GPUStoreOp,
loadValue: { r: 0, g: 0, b: 0, a: 1.0 }
}
],
depthStencilAttachment: {
view: depthTextureView,
depthLoadValue: 1.0,
depthStoreOp: 'store' as GPUStoreOp,
stencilLoadValue: 0,
stencilStoreOp: 'store' as GPUStoreOp
}
};
}
buildPipeline(WebGPU, vertex, fragment, vertexId, entries, screen = false) {
const { device, glslang } = WebGPU;
const bindGroupLayout = device.createBindGroupLayout({
entries
});
const pipelineLayout = device.createPipelineLayout({
bindGroupLayouts: [bindGroupLayout]
});
const pipeline = device.createRenderPipeline({
layout: pipelineLayout,
vertex: {
module: device.createShaderModule({
code: glslang.compileGLSL(vertex, 'vertex'),
source: vertex,
transform: glsl => glslang.compileGLSL(glsl, 'vertex')
}),
entryPoint: 'main',
buffers: [
{
arrayStride: Float32Array.BYTES_PER_ELEMENT * vertexId,
attributes: [
{
// position
shaderLocation: 0,
offset: 0,
format: `float32x${vertexId}`
}
]
}
]
},
fragment: {
module: device.createShaderModule({
code: glslang.compileGLSL(fragment, 'fragment'),
source: fragment,
transform: glsl => glslang.compileGLSL(glsl, 'fragment')
}),
entryPoint: 'main',
targets: [
{
format: screen ? 'bgra8unorm' : 'rgba16float'
}
]
},
primitive: {
topology: 'triangle-list',
cullMode: 'none'
},
depthStencil: {
depthWriteEnabled: true,
depthCompare: 'less',
format: 'depth32float'
}
});
return pipeline;
}
buildVertex(WebGPU, g) {
const { device } = WebGPU;
const verticesBuffer = device.createBuffer({
size: g.byteLength,
usage: GPUBufferUsage.VERTEX,
mappedAtCreation: true
});
new Float32Array(verticesBuffer.getMappedRange()).set(g);
verticesBuffer.unmap();
return verticesBuffer;
}
drawBRDF(WebGPU: WEBGPU) {
const { device } = WebGPU;
this.bdrfTexture = device.createTexture({
size: [512, 512, 1],
usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
format: 'rgba16float'
});
const commandEncoder = device.createCommandEncoder();
const pass = this.buildPass(WebGPU, 512);
const shadowPass = commandEncoder.beginRenderPass(pass);
const p = this.buildPipeline(WebGPU, quad, bdrf, 2, []);
shadowPass.setPipeline(p);
shadowPass.setVertexBuffer(0, this.buildVertex(WebGPU, quadFull));
shadowPass.setBindGroup(
0,
device.createBindGroup({
layout: p.getBindGroupLayout(0),
entries: []
})
);
shadowPass.setViewport(0, 0, 512, 512, 0, 1);
shadowPass.draw(6);
shadowPass.endPass();
commandEncoder.copyTextureToTexture({ texture: this.tempTexture }, { texture: this.bdrfTexture }, [512, 512, 1]);
device.queue.submit([commandEncoder.finish()]);
}
drawWebGPU(WebGPU, mipWidth, mipHeight, layer, mip) {
const { device } = WebGPU;
const m = new Matrix4();
const cam = Object.assign({}, this.camera.props, {
aspect: 1,
perspective: {
yfov: Math.PI / 2,
znear: 0.01,
zfar: 10000
}
});
m.multiply(calculateProjection(cam));
const uniformBuffer = new UniformBuffer();
uniformBuffer.add('index', new Float32Array([layer, 0, 0, 0]));
uniformBuffer.add('projection', m.elements);
uniformBuffer.add('view0', this.views[0].elements);
uniformBuffer.add('view1', this.views[1].elements);
uniformBuffer.add('view2', this.views[2].elements);
uniformBuffer.add('view3', this.views[3].elements);
uniformBuffer.add('view4', this.views[4].elements);
uniformBuffer.add('view5', this.views[5].elements);
uniformBuffer.done();
const matrixSize = uniformBuffer.store.byteLength;
const offset = 256; // uniformBindGroup offset must be 256-byte aligned
const uniformBufferSize = offset + matrixSize;
const u = device.createBuffer({
size: uniformBufferSize,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
});
device.queue.writeBuffer(u, 0, uniformBuffer.store.buffer, uniformBuffer.store.byteOffset, uniformBuffer.store.byteLength);
const sampler = device.createSampler({
magFilter: 'linear',
minFilter: 'linear',
wrapS: 'clamp-to-edge',
wrapT: 'clamp-to-edge',
wrapR: 'clamp-to-edge'
});
const entries = [
{
binding: 0,
resource: {
buffer: u,
offset: 0,
size: matrixSize
}
},
{
binding: 1,
resource: sampler
},
{
binding: 2,
resource: this.originalCubeTexture.createView()
}
];
const entriesL = [
{
binding: 0,
visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
buffer: {}
},
{
binding: 1,
visibility: GPUShaderStage.FRAGMENT,
sampler: {}
},
{
binding: 2,
visibility: GPUShaderStage.FRAGMENT,
texture: {}
}
];
const commandEncoder = device.createCommandEncoder();
const pass = this.buildPass(WebGPU, 512);
const shadowPass = commandEncoder.beginRenderPass(pass);
const p = this.buildPipeline(WebGPU, vertex, cube, 3, entriesL);
shadowPass.setPipeline(p);
shadowPass.setVertexBuffer(0, this.buildVertex(WebGPU, cubeVertex));
shadowPass.setBindGroup(
0,
device.createBindGroup({
layout: p.getBindGroupLayout(0),
entries
})
);
shadowPass.setViewport(0, 0, mipWidth, mipHeight, 0, 1);
shadowPass.draw(36);
shadowPass.endPass();
commandEncoder.copyTextureToTexture(
{ texture: this.tempTexture },
{ texture: this.cubeTexture, mipLevel: mip, origin: { z: layer } },
[mipWidth, mipHeight, 1]
);
device.queue.submit([commandEncoder.finish()]);
}
drawWebGPU2(WebGPU, mipWidth, mipHeight, layer, mip) {
const { device } = WebGPU;
const m = new Matrix4();
const cam = Object.assign({}, this.camera.props, {
aspect: 1,
perspective: {
yfov: Math.PI / 2,
znear: 0.01,
zfar: 10000
}
});
m.multiply(calculateProjection(cam));
const uniformBuffer = new UniformBuffer();
uniformBuffer.add('index', new Float32Array([layer, 0, 0, 0]));
uniformBuffer.add('projection', m.elements);
uniformBuffer.add('view0', this.views[0].elements);
uniformBuffer.add('view1', this.views[1].elements);
uniformBuffer.add('view2', this.views[2].elements);
uniformBuffer.add('view3', this.views[3].elements);
uniformBuffer.add('view4', this.views[4].elements);
uniformBuffer.add('view5', this.views[5].elements);
uniformBuffer.done();
const matrixSize = uniformBuffer.store.byteLength;
const offset = 256; // uniformBindGroup offset must be 256-byte aligned
const uniformBufferSize = offset + matrixSize;
const u = device.createBuffer({
size: uniformBufferSize,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
});
device.queue.writeBuffer(u, 0, uniformBuffer.store.buffer, uniformBuffer.store.byteOffset, uniformBuffer.store.byteLength);
const sampler = device.createSampler({
magFilter: 'linear',
minFilter: 'linear',
wrapS: 'clamp-to-edge',
wrapT: 'clamp-to-edge',
wrapR: 'clamp-to-edge'
});
const entries = [
{
binding: 0,
resource: {
buffer: u,
offset: 0,
size: matrixSize
}
},
{
binding: 1,
resource: sampler
},
{
binding: 2,
resource: this.cubeTexture.createView({
dimension: 'cube'
})
}
];
const entriesL = [
{
binding: 0,
visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
buffer: {}
},
{
binding: 1,
visibility: GPUShaderStage.FRAGMENT,
sampler: {}
},
{
binding: 2,
visibility: GPUShaderStage.FRAGMENT,
texture: {
viewDimension: 'cube'
}
}
];
const commandEncoder = device.createCommandEncoder();
const pass = this.buildPass(WebGPU, 32);
const shadowPass = commandEncoder.beginRenderPass(pass);
const p = this.buildPipeline(WebGPU, vertex, irradiance, 3, entriesL);
shadowPass.setPipeline(p);
shadowPass.setVertexBuffer(0, this.buildVertex(WebGPU, cubeVertex));
shadowPass.setBindGroup(
0,
device.createBindGroup({
layout: p.getBindGroupLayout(0),
entries
})
);
shadowPass.setViewport(0, 0, mipWidth, mipHeight, 0, 1);
shadowPass.draw(36);
shadowPass.endPass();
commandEncoder.copyTextureToTexture(
{ texture: this.tempTexture },
{ texture: this.irradianceTexture, mipLevel: mip, origin: { z: layer } },
[mipWidth, mipHeight, 1]
);
device.queue.submit([commandEncoder.finish()]);
}
drawWebGPU3(WebGPU, mipWidth, mipHeight, layer, mip) {
const { device } = WebGPU;
const m = new Matrix4();
const cam = Object.assign({}, this.camera.props, {
aspect: 1,
perspective: {
yfov: Math.PI / 2,
znear: 0.01,
zfar: 10000
}
});
m.multiply(calculateProjection(cam));
const roughness = mip / 4;
const uniformBuffer = new UniformBuffer();
uniformBuffer.add('index', new Float32Array([layer, roughness, 0, 0]));
uniformBuffer.add('projection', m.elements);
uniformBuffer.add('view0', this.views[0].elements);
uniformBuffer.add('view1', this.views[1].elements);
uniformBuffer.add('view2', this.views[2].elements);
uniformBuffer.add('view3', this.views[3].elements);
uniformBuffer.add('view4', this.views[4].elements);
uniformBuffer.add('view5', this.views[5].elements);
uniformBuffer.done();
const matrixSize = uniformBuffer.store.byteLength;
const offset = 256; // uniformBindGroup offset must be 256-byte aligned
const uniformBufferSize = offset + matrixSize;
const u = device.createBuffer({
size: uniformBufferSize,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
});
device.queue.writeBuffer(u, 0, uniformBuffer.store.buffer, uniformBuffer.store.byteOffset, uniformBuffer.store.byteLength);
const sampler = device.createSampler({
magFilter: 'linear',
minFilter: 'linear',
wrapS: 'clamp-to-edge',
wrapT: 'clamp-to-edge',
wrapR: 'clamp-to-edge'
});
const entries = [
{
binding: 0,
resource: {
buffer: u,
offset: 0,
size: matrixSize
}
},
{
binding: 1,
resource: sampler
},
{
binding: 2,
resource: this.cubeTexture.createView({
dimension: 'cube'
})
}
];
const entriesL = [
{
binding: 0,
visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
buffer: {}
},
{
binding: 1,
visibility: GPUShaderStage.FRAGMENT,
sampler: {}
},
{
binding: 2,
visibility: GPUShaderStage.FRAGMENT,
texture: {
viewDimension: 'cube'
}
}
];
const commandEncoder = device.createCommandEncoder();
const pass = this.buildPass(WebGPU, 128);
const shadowPass = commandEncoder.beginRenderPass(pass);
const p = this.buildPipeline(WebGPU, vertex, cubeMipmap, 3, entriesL);
shadowPass.setPipeline(p);
shadowPass.setVertexBuffer(0, this.buildVertex(WebGPU, cubeVertex));
shadowPass.setBindGroup(
0,
device.createBindGroup({
layout: p.getBindGroupLayout(0),
entries
})
);
shadowPass.setViewport(0, 0, mipWidth, mipHeight, 0, 1);
shadowPass.draw(36);
shadowPass.endPass();
commandEncoder.copyTextureToTexture(
{ texture: this.tempTexture },
{ texture: this.prefilterTexture, mipLevel: mip, origin: { z: layer } },
[mipWidth, mipHeight, 1]
);
device.queue.submit([commandEncoder.finish()]);
}
drawMips(WebGPU: WEBGPU) {
const { device } = WebGPU;
this.cubeTexture = device.createTexture({
mipLevelCount: 5,
size: [512, 512, 6],
usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
format: 'rgba16float'
});
const maxMipLevels = 5;
for (let mip = 0; mip < maxMipLevels; ++mip) {
const mipWidth = 512 * Math.pow(0.5, mip);
const mipHeight = 512 * Math.pow(0.5, mip);
for (let i = 0; i < 6; i++) {
this.drawWebGPU(WebGPU, mipWidth, mipHeight, i, mip);
}
}
}
drawIrradiance(WebGPU: WEBGPU) {
const { device } = WebGPU;
this.irradianceTexture = device.createTexture({
size: [32, 32, 6],
usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
format: 'rgba16float'
});
for (let i = 0; i < 6; i++) {
this.drawWebGPU2(WebGPU, 32, 32, i, 0);
}
}
drawPrefilter(WebGPU: WEBGPU) {
const { device } = WebGPU;
this.prefilterTexture = device.createTexture({
mipLevelCount: 5,
size: [128, 128, 6],
usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
format: 'rgba16float'
});
const maxMipLevels = 5;
for (let mip = 0; mip < maxMipLevels; ++mip) {
const mipWidth = 128 * Math.pow(0.5, mip);
const mipHeight = 128 * Math.pow(0.5, mip);
for (let i = 0; i < 6; i++) {
this.drawWebGPU3(WebGPU, mipWidth, mipHeight, i, mip);
}
}
}
} | the_stack |
import type * as BalenaSdk from '..';
import type { AnyObject } from '../typings/utils';
import type * as PineClient from '../typings/pinejs-client-core';
const sdk: BalenaSdk.BalenaSDK = {} as any;
let aAny: any;
let aNumber: number;
let aNumberOrUndefined: number | undefined;
let aString: string;
let aStringOrUndefined: string | undefined;
// This file is in .prettierignore, since otherwise
// the @ts-expect-error comments would move to the wrong place
// $select
{
type deviceOptionsNoProps = PineClient.TypedResult<
BalenaSdk.Device,
undefined
>;
const result: deviceOptionsNoProps = {} as any;
aNumber = result.id;
aString = result.device_name;
aNumber = result.belongs_to__application.__id;
aNumberOrUndefined = result.should_be_running__release?.__id;
// @ts-expect-error
aNumber = result.should_be_running__release.__id;
// @ts-expect-error
aAny = result.device_tag;
}
{
type deviceOptionsNoProps = PineClient.TypedResult<BalenaSdk.Device, {}>;
const result: deviceOptionsNoProps = {} as any;
aNumber = result.id;
aString = result.device_name;
aNumber = result.belongs_to__application.__id;
aNumberOrUndefined = result.should_be_running__release?.__id;
// @ts-expect-error
aNumber = result.should_be_running__release.__id;
// @ts-expect-error
aAny = result.device_tag;
}
{
type deviceOptionsSelectAsterisk = PineClient.TypedResult<
BalenaSdk.Device,
{
$select: '*';
}
>;
const result: deviceOptionsSelectAsterisk = {} as any;
aNumber = result.id;
aString = result.device_name;
aNumber = result.belongs_to__application.__id;
aNumberOrUndefined = result.should_be_running__release?.__id;
// @ts-expect-error
aNumber = result.should_be_running__release.__id;
// @ts-expect-error
aAny = result.device_tag;
}
{
type deviceOptionsSelectId = PineClient.TypedResult<
BalenaSdk.Device,
{
$select: 'id';
}
>;
const result: deviceOptionsSelectId = {} as any;
aNumber = result.id;
// @ts-expect-error
aNumber = result.belongs_to__application.__id;
// @ts-expect-error
aNumber = result.should_be_running__release.__id;
// @ts-expect-error
aAny = result.device_tag;
}
{
type deviceOptionsSelectRelease = PineClient.TypedResult<
BalenaSdk.Device,
{
$select: 'belongs_to__application';
}
>;
const result: deviceOptionsSelectRelease = {} as any;
aNumber = result.belongs_to__application.__id;
// @ts-expect-error
aAny = result.should_be_running__release;
// @ts-expect-error
aNumber = result.id;
// @ts-expect-error
aAny = result.device_tag;
}
{
type deviceOptionsSelectRelease = PineClient.TypedResult<
BalenaSdk.Device,
{
$select: 'should_be_running__release';
}
>;
const result: deviceOptionsSelectRelease = {} as any;
aNumberOrUndefined = result.should_be_running__release?.__id;
// @ts-expect-error
aNumber = result.should_be_running__release.__id;
// @ts-expect-error
aNumber = result.id;
// @ts-expect-error
aAny = result.device_tag;
}
{
type deviceOptionsSelectArray = PineClient.TypedResult<
BalenaSdk.Device,
{
$select: ['id', 'note', 'device_name', 'uuid', 'belongs_to__application'];
}
>;
const result: deviceOptionsSelectArray = {} as any;
aNumber = result.id;
aString = result.device_name;
aNumber = result.belongs_to__application.__id;
// @ts-expect-error
aAny = result.device_tag;
}
// $expand w/o $select
{
type deviceOptionsExpandNavigationResourceString = PineClient.TypedResult<
BalenaSdk.Device,
{
$expand: 'belongs_to__application';
}
>;
const result: deviceOptionsExpandNavigationResourceString = {} as any;
aNumber = result.belongs_to__application[0].id;
aNumber = result.id;
aString = result.device_name;
// @ts-expect-error
aAny = result.belongs_to__application[1];
// @ts-expect-error
aAny = result.device_tag;
}
{
type deviceOptionsExpandNavigationResourceString = PineClient.TypedResult<
BalenaSdk.Device,
{
$expand: 'should_be_running__release';
}
>;
const result: deviceOptionsExpandNavigationResourceString = {} as any;
aNumber = result.id;
aString = result.device_name;
aNumberOrUndefined = result.should_be_running__release[0]?.id;
// @ts-expect-error
aAny = result.should_be_running__release[0].id;
// @ts-expect-error
aAny = result.should_be_running__release.__id;
// @ts-expect-error
aAny = result.should_be_running__release[1];
// @ts-expect-error
aAny = result.device_tag;
}
{
type deviceOptionsExpandReverseNavigationResourceString = PineClient.TypedResult<
BalenaSdk.Device,
{
$expand: 'device_tag';
}
>;
const result: deviceOptionsExpandReverseNavigationResourceString = {} as any;
aNumber = result.device_tag[1].id;
aNumber = result.id;
aString = result.device_name;
aNumber = result.belongs_to__application.__id;
aNumberOrUndefined = result.should_be_running__release?.__id;
}
// $expand w $select
{
type deviceOptionsExpandNavigationResourceString = PineClient.TypedResult<
BalenaSdk.Device,
{
$select: 'belongs_to__application';
$expand: 'belongs_to__application';
}
>;
const result: deviceOptionsExpandNavigationResourceString = {} as any;
aNumber = result.belongs_to__application[0].id;
aString = result.belongs_to__application[0].app_name;
// @ts-expect-error
aNumber = result.id;
// @ts-expect-error
aString = result.device_name;
// @ts-expect-error
aAny = result.belongs_to__application[1];
// @ts-expect-error
aAny = result.device_tag;
}
{
type deviceOptionsExpandNavigationResourceString = PineClient.TypedResult<
BalenaSdk.Device,
{
$select: 'should_be_running__release';
$expand: 'should_be_running__release';
}
>;
const result: deviceOptionsExpandNavigationResourceString = {} as any;
aNumberOrUndefined = result.should_be_running__release[0]?.id;
aStringOrUndefined = result.should_be_running__release[0]?.commit;
// @ts-expect-error
aNumber = result.id;
// @ts-expect-error
aString = result.device_name;
// @ts-expect-error
aAny = result.should_be_running__release[1];
// @ts-expect-error
aAny = result.device_tag;
}
{
type deviceOptionsExpandReverseNavigationResourceString = PineClient.TypedResult<
BalenaSdk.Device,
{
$select: 'id';
$expand: 'device_tag';
}
>;
const result: deviceOptionsExpandReverseNavigationResourceString = {} as any;
aNumber = result.device_tag[1].id;
aString = result.device_tag[1].tag_key;
aNumber = result.id;
// @ts-expect-error
aString = result.device_name;
// @ts-expect-error
aNumber = result.should_be_running__release.__id;
}
// empty $expand object
{
type deviceOptionsExpandNavigationResourceString = PineClient.TypedResult<
BalenaSdk.Device,
{
$select: 'belongs_to__application';
$expand: {
belongs_to__application: {};
};
}
>;
const result: deviceOptionsExpandNavigationResourceString = {} as any;
aNumber = result.belongs_to__application[0].id;
aString = result.belongs_to__application[0].app_name;
// @ts-expect-error
aNumber = result.id;
// @ts-expect-error
aString = result.device_name;
// @ts-expect-error
aAny = result.belongs_to__application[1];
// @ts-expect-error
aAny = result.device_tag;
}
{
type deviceOptionsExpandNavigationResourceString = PineClient.TypedResult<
BalenaSdk.Device,
{
$select: 'should_be_running__release';
$expand: {
should_be_running__release: {};
};
}
>;
const result: deviceOptionsExpandNavigationResourceString = {} as any;
aNumberOrUndefined = result.should_be_running__release[0]?.id;
aStringOrUndefined = result.should_be_running__release[0]?.commit;
// @ts-expect-error
aNumber = result.id;
// @ts-expect-error
aString = result.device_name;
// @ts-expect-error
aAny = result.should_be_running__release[1];
// @ts-expect-error
aAny = result.device_tag;
}
{
type deviceOptionsExpandReverseNavigationResourceString = PineClient.TypedResult<
BalenaSdk.Device,
{
$select: 'id';
$expand: {
device_tag: {};
};
}
>;
const result: deviceOptionsExpandReverseNavigationResourceString = {} as any;
aNumber = result.device_tag[1].id;
aString = result.device_tag[1].tag_key;
aNumber = result.id;
// @ts-expect-error
aString = result.device_name;
// @ts-expect-error
aNumber = result.should_be_running__release.__id;
}
// $expand object w/ nested options
{
type deviceOptionsExpandNavigationResourceString = PineClient.TypedResult<
BalenaSdk.Device,
{
$select: 'id';
$expand: {
belongs_to__application: {
$select: 'app_name';
};
};
}
>;
const result: deviceOptionsExpandNavigationResourceString = {} as any;
aNumber = result.id;
aString = result.belongs_to__application[0].app_name;
// @ts-expect-error
aNumber = result.belongs_to__application[0].id;
// @ts-expect-error
aString = result.device_name;
// @ts-expect-error
aAny = result.belongs_to__application[1];
// @ts-expect-error
aAny = result.device_tag;
}
{
type deviceOptionsExpandNavigationResourceString = PineClient.TypedResult<
BalenaSdk.Device,
{
$select: 'id';
$expand: {
should_be_running__release: {
$select: 'commit';
};
};
}
>;
const result: deviceOptionsExpandNavigationResourceString = {} as any;
aNumber = result.id;
aStringOrUndefined = result.should_be_running__release[0]?.commit;
// @ts-expect-error
aNumberOrUndefined = result.should_be_running__release[0]?.id;
// @ts-expect-error
aString = result.device_name;
// @ts-expect-error
aAny = result.should_be_running__release[1];
// @ts-expect-error
aAny = result.device_tag;
}
{
type deviceOptionsExpandNavigationResourceString = PineClient.TypedResult<
AnyObject,
{
$select: 'id';
$expand: {
should_be_running__release: {
$select: 'commit';
};
};
}
>;
const result: deviceOptionsExpandNavigationResourceString = {} as any;
aNumber = result.id;
// Errors, since it could be an OptionalNavigationResource
// @ts-expect-error
aStringOrUndefined = result.should_be_running__release[0].commit;
aStringOrUndefined = result.should_be_running__release[0]?.commit;
// @ts-expect-error
aNumberOrUndefined = result.should_be_running__release[0]?.id;
// This also works, since the typings don't know whether this is Navigation or a Reverse Navigation Resounce
aAny = result.should_be_running__release[1].commit;
// @ts-expect-error
aString = result.device_name;
// @ts-expect-error
aAny = result.device_tag;
}
{
type deviceOptionsExpandReverseNavigationResourceString = PineClient.TypedResult<
BalenaSdk.Device,
{
$select: 'id';
$expand: {
device_tag: {
$select: 'tag_key';
};
};
}
>;
const result: deviceOptionsExpandReverseNavigationResourceString = {} as any;
aNumber = result.id;
aString = result.device_tag[1].tag_key;
// @ts-expect-error
aString = result.device_name;
// @ts-expect-error
aNumber = result.device_tag[1].id;
// @ts-expect-error
aNumber = result.should_be_running__release.__id;
}
// $count
{
type deviceOptionsNoProps = PineClient.TypedResult<
BalenaSdk.Device,
{ $count: {} }
>;
const result: deviceOptionsNoProps = {} as any;
aNumber = result;
}
{
type deviceOptionsNoProps = PineClient.TypedResult<
BalenaSdk.Device,
{
$select: 'id';
$expand: {
belongs_to__application: {
$count: {};
};
};
}
>;
const result: deviceOptionsNoProps = {} as any;
aNumber = result.id;
aNumber = result.belongs_to__application;
}
{
type deviceOptionsNoProps = PineClient.TypedResult<
BalenaSdk.Device,
{
$select: 'id';
$expand: {
device_tag: {
$count: {};
};
};
}
>;
const result: deviceOptionsNoProps = {} as any;
aNumber = result.id;
aNumber = result.device_tag;
} | the_stack |
import * as ccp from "cocopa";
import * as os from "os";
import * as path from "path";
import * as constants from "../common/constants";
import { arduinoChannel } from "../common/outputChannel";
import { ArduinoWorkspace } from "../common/workspace";
import { DeviceContext } from "../deviceContext";
import { VscodeSettings } from "./vscodeSettings";
export interface ICoCoPaContext {
callback: (s: string) => void;
conclude: () => Promise<void>;
}
/**
* Returns true if the combination of global enable/disable and project
* specific override enable the auto-generation of the IntelliSense
* configuration.
*/
export function isCompilerParserEnabled(dc?: DeviceContext) {
if (!dc) {
dc = DeviceContext.getInstance();
}
const globalDisable = VscodeSettings.getInstance().disableIntelliSenseAutoGen;
const projectSetting = dc.intelliSenseGen;
return projectSetting !== "disable" && !globalDisable ||
projectSetting === "enable";
}
/**
* Creates a context which is used for compiler command parsing
* during building (verify, upload, ...).
*
* This context makes sure that it can be used in those sections
* without having to check whether this feature is en- or disabled
* and keeps the calling context more readable.
*
* @param dc The device context of the caller.
*
* Possible enhancements:
*
* * Order of includes: Perhaps insert the internal includes at the front
* as at least for the forcedIncludes IntelliSense seems to take the
* order into account.
*/
export function makeCompilerParserContext(dc: DeviceContext): ICoCoPaContext {
// TODO: callback for local setting: when IG gen is re-enabled file
// analysis trigger. Perhaps for global possible as well?
if (!isCompilerParserEnabled(dc)) {
return {
callback: undefined,
conclude: async () => {
arduinoChannel.info("IntelliSense auto-configuration disabled.");
},
};
}
const engines = makeCompilerParserEngines(dc);
const runner = new ccp.Runner(engines);
// Set up the callback to be called after parsing
const _conclude = async () => {
if (!runner.result) {
arduinoChannel.warning("Failed to generate IntelliSense configuration.");
return;
}
// Normalize compiler and include paths (resolve ".." and ".")
runner.result.normalize();
// Remove invalid paths
await runner.result.cleanup();
// Search for Arduino.h in the include paths - we need it for a
// forced include - users expect Arduino symbols to be available
// in main sketch without having to include the header explicitly
const ardHeader = await runner.result.findFile("Arduino.h");
const forcedIncludes = ardHeader.length > 0
? ardHeader
: undefined;
if (!forcedIncludes) {
arduinoChannel.warning("Unable to locate \"Arduino.h\" within IntelliSense include paths.");
}
// The C++ standard is set to the following default value if no compiler flag has been found.
const content = new ccp.CCppPropertiesContentResult(runner.result,
constants.C_CPP_PROPERTIES_CONFIG_NAME,
ccp.CCppPropertiesISMode.Gcc_X64,
ccp.CCppPropertiesCStandard.C11,
ccp.CCppPropertiesCppStandard.Cpp11,
forcedIncludes);
// The following 4 lines are added to prevent null.d from being created in the workspace
// directory on MacOS and Linux. This is may be a bug in intelliSense
const mmdIndex = runner.result.options.findIndex((element) => element === "-MMD");
if (mmdIndex) {
runner.result.options.splice(mmdIndex);
}
// Add USB Connected marco to defines
runner.result.defines.push("USBCON")
try {
const cmd = os.platform() === "darwin" ? "Cmd" : "Ctrl";
const help = `To manually rebuild your IntelliSense configuration run "${cmd}+Alt+I"`;
const pPath = path.join(ArduinoWorkspace.rootPath, constants.CPP_CONFIG_FILE);
const prop = new ccp.CCppProperties();
prop.read(pPath);
prop.merge(content, ccp.CCppPropertiesMergeMode.ReplaceSameNames);
if (prop.write(pPath)) {
arduinoChannel.info(`IntelliSense configuration updated. ${help}`);
} else {
arduinoChannel.info(`IntelliSense configuration already up to date. ${help}`);
}
} catch (e) {
const estr = JSON.stringify(e);
arduinoChannel.error(`Failed to read or write IntelliSense configuration: ${estr}`);
}
};
return {
callback: runner.callback(),
conclude: _conclude,
}
}
/**
* Assembles compiler parser engines which then will be used to find the main
* sketch's compile command and parse the infomation from it required for
* assembling an IntelliSense configuration from it.
*
* It could return multiple engines for different compilers or - if necessary -
* return specialized engines based on the current board architecture.
*
* @param dc Current device context used to generate the engines.
*/
function makeCompilerParserEngines(dc: DeviceContext) {
const sketch = path.basename(dc.sketch);
const trigger = ccp.getTriggerForArduinoGcc(sketch);
const gccParserEngine = new ccp.ParserGcc(trigger);
return [gccParserEngine];
}
// Not sure why eslint fails to detect usage of these enums, so disable checking.
/**
* Possible states of AnalysisManager's state machine.
*/
enum AnalysisState {
/**
* No analysis request pending.
*/
Idle = "idle",
/**
* Analysis request pending. Waiting for the time out to expire or for
* another build to complete.
*/
Waiting = "waiting",
/**
* Analysis in progress.
*/
Analyzing = "analyzing",
/**
* Analysis in progress with yet another analysis request pending.
* As soon as the current analysis completes the manager will directly
* enter the Waiting state.
*/
AnalyzingWaiting = "analyzing and waiting",
}
/**
* Events (edges) which cause state changes within AnalysisManager.
*/
enum AnalysisEvent {
/**
* The only external event. Requests an analysis to be run.
*/
AnalysisRequest,
/**
* The internal wait timeout expired.
*/
WaitTimeout,
/**
* The current analysis build finished.
*/
AnalysisBuildDone,
}
/**
* This class manages analysis builds for the automatic IntelliSense
* configuration synthesis. Its primary purposes are:
*
* * delaying analysis requests caused by DeviceContext setting change
* events such that multiple subsequent requests don't cause
* multiple analysis builds
* * make sure that an analysis request is postponed when another build
* is currently in progress
*
* TODO: check time of c_cpp_properties.json and compare it with
* * arduino.json
* * main sketch file
* This way we can perhaps optimize this further. But be aware
* that settings events fire before their corresponding values
* are actually written to arduino.json -> time of arduino.json
* is outdated if no countermeasure is taken.
*/
export class AnalysisManager {
/** The manager's state. */
private _state: AnalysisState = AnalysisState.Idle;
/** A callback used by the manager to query if the build backend is busy. */
private _isBuilding: () => boolean;
/** A callback used by the manager to initiate an analysis build. */
private _doBuild: () => Promise<void>;
/** Timeout for the timeouts/delays in milliseconds. */
private _waitPeriodMs: number;
/** The internal timer used to implement the above timeouts and delays. */
private _timer: NodeJS.Timer;
/**
* Constructor.
* @param isBuilding Provide a callback which returns true if another build
* is currently in progress.
* @param doBuild Provide a callback which runs the analysis build.
* @param waitPeriodMs The delay the manger should wait for potential new
* analysis request. This delay is used as polling interval as well when
* checking for ongoing builds.
*/
constructor(isBuilding: () => boolean,
doBuild: () => Promise<void>,
waitPeriodMs: number = 1000) {
this._isBuilding = isBuilding;
this._doBuild = doBuild;
this._waitPeriodMs = waitPeriodMs;
}
/**
* File an analysis request.
* The analysis will be delayed until no further requests are filed
* within a wait period or until any build in progress has terminated.
*/
public async requestAnalysis() {
await this.update(AnalysisEvent.AnalysisRequest);
}
/**
* Update the manager's state machine.
* @param event The event which will cause the state transition.
*
* Implementation note: asynchronous edge actions must be called after
* setting the new state since they don't return immediately.
*/
private async update(event: AnalysisEvent) {
switch (this._state) {
case AnalysisState.Idle:
if (event === AnalysisEvent.AnalysisRequest) {
this._state = AnalysisState.Waiting;
this.startWaitTimeout();
}
break;
case AnalysisState.Waiting:
if (event === AnalysisEvent.AnalysisRequest) {
// every new request restarts timer
this.startWaitTimeout();
} else if (event === AnalysisEvent.WaitTimeout) {
if (this._isBuilding()) {
// another build in progress, continue waiting
this.startWaitTimeout();
} else {
// no other build in progress -> launch analysis
this._state = AnalysisState.Analyzing;
await this.startAnalysis();
}
}
break;
case AnalysisState.Analyzing:
if (event === AnalysisEvent.AnalysisBuildDone) {
this._state = AnalysisState.Idle;
} else if (event === AnalysisEvent.AnalysisRequest) {
this._state = AnalysisState.AnalyzingWaiting;
}
break;
case AnalysisState.AnalyzingWaiting:
if (event === AnalysisEvent.AnalysisBuildDone) {
// emulate the transition from idle to waiting
// (we don't care if this adds an additional
// timeout - event driven analysis is not time-
// critical)
this._state = AnalysisState.Idle;
await this.update(AnalysisEvent.AnalysisRequest);
}
break;
}
}
/**
* Starts the wait timeout timer.
* If it's already running, the current timer is stopped and restarted.
* The timeout callback will then update the state machine.
*/
private startWaitTimeout() {
if (this._timer) {
clearTimeout(this._timer);
}
this._timer = setTimeout(() => {
// reset timer variable first - calling update can cause
// the timer to be restarted.
this._timer = undefined;
this.update(AnalysisEvent.WaitTimeout);
}, this._waitPeriodMs);
}
/**
* Starts the analysis build.
* When done, the callback will update the state machine.
*/
private async startAnalysis() {
await this._doBuild()
.then(() => {
this.update(AnalysisEvent.AnalysisBuildDone);
})
.catch((reason) => {
this.update(AnalysisEvent.AnalysisBuildDone);
});
}
} | the_stack |
import type { TApplicationContext } from '@commercetools-frontend/application-shell-connectors';
import type {
TApplicationsMenu,
TNavbarMenu,
} from '../../types/generated/proxy';
import type {
TFetchProjectExtensionsNavbarQuery,
TFetchProjectExtensionsNavbarQueryVariables,
} from '../../types/generated/settings';
import {
useCallback,
useEffect,
useLayoutEffect,
useReducer,
useRef,
} from 'react';
import isNil from 'lodash/isNil';
import throttle from 'lodash/throttle';
import { GRAPHQL_TARGETS } from '@commercetools-frontend/constants';
import { reportErrorToSentry } from '@commercetools-frontend/sentry';
import { STORAGE_KEYS } from '../../constants';
import { useMcQuery } from '../../hooks/apollo-hooks';
import useApplicationsMenu from '../../hooks/use-applications-menu';
import FetchProjectExtensionsNavbar from './fetch-project-extensions-navbar.settings.graphql';
import nonNullable from './non-nullable';
type HookProps = {
environment: TApplicationContext<{}>['environment'];
DEV_ONLY__loadNavbarMenuConfig?: () => Promise<TApplicationsMenu['navBar']>;
};
type State = {
activeItemIndex?: string;
isExpanderVisible: boolean;
isMenuOpen: boolean;
};
type Action =
| { type: 'setActiveItemIndex'; payload: string }
| { type: 'unsetActiveItemIndex' }
| { type: 'setIsExpanderVisible' }
| { type: 'toggleIsMenuOpen' }
| { type: 'setIsMenuOpenAndMakeExpanderVisible'; payload: boolean }
| { type: 'reset' };
const getInitialState = (isForcedMenuOpen: boolean | null): State => ({
isExpanderVisible: true,
isMenuOpen: isNil(isForcedMenuOpen) ? false : isForcedMenuOpen,
});
const reducer = (state: State, action: Action): State => {
switch (action.type) {
case 'setActiveItemIndex':
return { ...state, activeItemIndex: action.payload };
case 'unsetActiveItemIndex':
return { ...state, activeItemIndex: undefined };
case 'setIsExpanderVisible':
return { ...state, isExpanderVisible: true };
case 'toggleIsMenuOpen':
return { ...state, isMenuOpen: !state.isMenuOpen };
case 'setIsMenuOpenAndMakeExpanderVisible':
return { ...state, isExpanderVisible: true, isMenuOpen: action.payload };
case 'reset':
return {
isExpanderVisible: false,
isMenuOpen: false,
};
default:
return state;
}
};
const useNavbarStateManager = (props: HookProps) => {
const navBarNode = useRef<HTMLElement>(null);
const applicationsNavBarMenu = useApplicationsMenu<'navBar'>('navBar', {
queryOptions: {
onError: reportErrorToSentry,
},
environment: props.environment,
loadMenuConfig: props.DEV_ONLY__loadNavbarMenuConfig,
});
const { data: projectExtensionsQuery } = useMcQuery<
TFetchProjectExtensionsNavbarQuery,
TFetchProjectExtensionsNavbarQueryVariables
>(FetchProjectExtensionsNavbar, {
skip: !props.environment.servedByProxy,
context: {
target: GRAPHQL_TARGETS.SETTINGS_SERVICE,
},
fetchPolicy: 'cache-and-network',
onError: reportErrorToSentry,
});
const legacyCustomAppsMenu =
projectExtensionsQuery &&
projectExtensionsQuery.projectExtension &&
projectExtensionsQuery.projectExtension.applications
? projectExtensionsQuery.projectExtension.applications
.map<TNavbarMenu | undefined>((app) => {
// Map the menu properties to match the one from the proxy schema.
// This is to ensure that the menu object is the same from the proxy
// config and the custom apps config, thus allowing them to be
// concatenated and rendered the same way.
if (!app.navbarMenu) return;
return {
key: app.navbarMenu.key,
uriPath: app.navbarMenu.uriPath,
labelAllLocales: app.navbarMenu.labelAllLocales || [],
icon: app.navbarMenu.icon,
featureToggle: app.navbarMenu.featureToggle,
permissions: app.navbarMenu.permissions as string[],
submenu: (app.navbarMenu.submenu || []).map((menu) => ({
key: menu.key,
uriPath: menu.uriPath,
labelAllLocales: menu.labelAllLocales || [],
featureToggle: menu.featureToggle,
permissions: menu.permissions as string[],
menuVisibility: undefined,
actionRights: undefined,
dataFences: undefined,
})),
menuVisibility: undefined,
actionRights: undefined,
dataFences: undefined,
shouldRenderDivider: false,
};
})
.filter(nonNullable)
: [];
const organizationCustomAppsMenu =
projectExtensionsQuery &&
projectExtensionsQuery.projectExtension &&
projectExtensionsQuery.projectExtension.installedApplications
? projectExtensionsQuery.projectExtension.installedApplications
.map<TNavbarMenu | undefined>((installedApplication) => {
const application = installedApplication.application;
// Map the menu properties to match the one from the proxy schema.
// This is to ensure that the menu object is the same from the proxy
// config and the custom apps config, thus allowing them to be
// concatenated and rendered the same way.
if (!application.menuLinks) return;
return {
key: application.id,
uriPath: application.entryPointUriPath,
labelAllLocales: application.menuLinks.labelAllLocales || [],
icon: application.menuLinks.icon,
permissions: application.menuLinks.permissions as string[],
defaultLabel: application.menuLinks.defaultLabel,
featureToggle: undefined,
menuVisibility: undefined,
actionRights: undefined,
dataFences: undefined,
shouldRenderDivider: false,
submenu: (application.menuLinks.submenuLinks || []).map(
(submenuLink) => ({
key: submenuLink.id,
uriPath: submenuLink.uriPath,
labelAllLocales: submenuLink.labelAllLocales || [],
permissions: submenuLink.permissions as string[],
defaultLabel: submenuLink.defaultLabel,
featureToggle: undefined,
menuVisibility: undefined,
actionRights: undefined,
dataFences: undefined,
})
),
};
})
.filter(nonNullable)
: [];
const cachedIsForcedMenuOpen = window.localStorage.getItem(
STORAGE_KEYS.IS_FORCED_MENU_OPEN
);
const isForcedMenuOpen = isNil(cachedIsForcedMenuOpen)
? null
: (JSON.parse(cachedIsForcedMenuOpen) as boolean);
const [state, dispatch] = useReducer<
(prevState: State, action: Action) => State
>(reducer, getInitialState(isForcedMenuOpen));
const checkSize = useCallback(
throttle(() => {
const shouldOpen = window.innerWidth > 1024;
const canExpandMenu = window.innerWidth > 918;
// If the screen is small, we should always keep the menu closed,
// no matter the settings.
if (!canExpandMenu) {
if (state.isMenuOpen || state.isExpanderVisible) {
// and resets the state to avoid conflicts
dispatch({ type: 'reset' });
}
} else if (canExpandMenu && state.isExpanderVisible !== true) {
dispatch({ type: 'setIsExpanderVisible' });
} else if (isNil(isForcedMenuOpen) && state.isMenuOpen !== shouldOpen) {
// User has no settings yet (this.props.isForcedMenuOpen === null)
// We check the viewport size and:
// - if screen is big, we open the menu
// - if screen is small we close it
dispatch({
type: 'setIsMenuOpenAndMakeExpanderVisible',
payload: shouldOpen,
});
} else if (
!isNil(isForcedMenuOpen) &&
state.isMenuOpen !== isForcedMenuOpen
) {
// User has setting, we should use that and ignore the screen size.
// Note: if viewport size is small, we should ignore the user settings.
dispatch({
type: 'setIsMenuOpenAndMakeExpanderVisible',
payload: isForcedMenuOpen,
});
}
}, 100),
[isForcedMenuOpen, state.isExpanderVisible, state.isMenuOpen]
);
const shouldCloseMenuFly = useCallback<
(e: React.MouseEvent<HTMLElement> | MouseEvent) => void
>(
(event) => {
if (
navBarNode &&
navBarNode.current &&
!navBarNode.current.contains(event.target as Node) &&
!state.isMenuOpen
)
dispatch({ type: 'unsetActiveItemIndex' });
else if (event.type === 'mouseleave')
dispatch({ type: 'unsetActiveItemIndex' });
},
[state.isMenuOpen]
);
useEffect(() => {
window.addEventListener('resize', checkSize);
window.addEventListener('click', shouldCloseMenuFly, true);
return () => {
window.removeEventListener('resize', checkSize);
window.removeEventListener('click', shouldCloseMenuFly, true);
};
}, [checkSize, shouldCloseMenuFly]);
useEffect(() => {
checkSize();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []); // <-- run this only once!!
useLayoutEffect(() => {
if (state.isMenuOpen) document.body.classList.add('body__menu-open');
if (!state.isMenuOpen) document.body.classList.remove('body__menu-open');
}, [state.isMenuOpen]);
const handleToggleItem = useCallback(
(nextActiveItemIndex: string) => {
if (state.activeItemIndex !== nextActiveItemIndex)
dispatch({
type: 'setActiveItemIndex',
payload: nextActiveItemIndex,
});
},
[state.activeItemIndex]
);
const handleToggleMenu = useCallback(() => {
if (state.isMenuOpen && state.activeItemIndex) {
dispatch({ type: 'unsetActiveItemIndex' });
}
dispatch({ type: 'toggleIsMenuOpen' });
// Synchronize the menu state with local storage.
window.localStorage.setItem(
STORAGE_KEYS.IS_FORCED_MENU_OPEN,
String(!state.isMenuOpen)
);
}, [state.activeItemIndex, state.isMenuOpen]);
const allApplicationNavbarMenu = (applicationsNavBarMenu || [])
.concat(legacyCustomAppsMenu)
.concat(organizationCustomAppsMenu);
return {
...state,
navBarNode,
handleToggleItem,
handleToggleMenu,
shouldCloseMenuFly,
allApplicationNavbarMenu,
};
};
export default useNavbarStateManager; | the_stack |
import { Secp256k1, Secp256k1Signature, sha256 } from "@cosmjs/crypto";
import { fromBase64, fromHex } from "@cosmjs/encoding";
import { makeCosmoshubPath } from "./paths";
import { extractKdfConfiguration, Secp256k1HdWallet } from "./secp256k1hdwallet";
import { serializeSignDoc, StdSignDoc } from "./signdoc";
import { base64Matcher } from "./testutils.spec";
import { executeKdf, KdfConfiguration } from "./wallet";
describe("Secp256k1HdWallet", () => {
// m/44'/118'/0'/0/0
// pubkey: 02baa4ef93f2ce84592a49b1d729c074eab640112522a7a89f7d03ebab21ded7b6
const defaultMnemonic = "special sign fit simple patrol salute grocery chicken wheat radar tonight ceiling";
const defaultPubkey = fromHex("02baa4ef93f2ce84592a49b1d729c074eab640112522a7a89f7d03ebab21ded7b6");
const defaultAddress = "cosmos1jhg0e7s6gn44tfc5k37kr04sznyhedtc9rzys5";
describe("fromMnemonic", () => {
it("works", async () => {
const wallet = await Secp256k1HdWallet.fromMnemonic(defaultMnemonic);
expect(wallet).toBeTruthy();
expect(wallet.mnemonic).toEqual(defaultMnemonic);
});
it("works with options", async () => {
const wallet = await Secp256k1HdWallet.fromMnemonic(defaultMnemonic, {
bip39Password: "password123",
hdPaths: [makeCosmoshubPath(123)],
prefix: "yolo",
});
expect(wallet.mnemonic).toEqual(defaultMnemonic);
const [account] = await wallet.getAccounts();
expect(account.pubkey).not.toEqual(defaultPubkey);
expect(account.address.slice(0, 4)).toEqual("yolo");
});
it("works with explicitly undefined options", async () => {
const wallet = await Secp256k1HdWallet.fromMnemonic(defaultMnemonic, {
bip39Password: undefined,
hdPaths: undefined,
prefix: undefined,
});
expect(wallet.mnemonic).toEqual(defaultMnemonic);
const [account] = await wallet.getAccounts();
expect(account.pubkey).toEqual(defaultPubkey);
expect(account.address).toEqual(defaultAddress);
});
});
describe("generate", () => {
it("defaults to 12 words", async () => {
const wallet = await Secp256k1HdWallet.generate();
expect(wallet.mnemonic.split(" ").length).toEqual(12);
});
it("can use different mnemonic lengths", async () => {
expect((await Secp256k1HdWallet.generate(12)).mnemonic.split(" ").length).toEqual(12);
expect((await Secp256k1HdWallet.generate(15)).mnemonic.split(" ").length).toEqual(15);
expect((await Secp256k1HdWallet.generate(18)).mnemonic.split(" ").length).toEqual(18);
expect((await Secp256k1HdWallet.generate(21)).mnemonic.split(" ").length).toEqual(21);
expect((await Secp256k1HdWallet.generate(24)).mnemonic.split(" ").length).toEqual(24);
});
});
describe("deserialize", () => {
it("can restore", async () => {
const original = await Secp256k1HdWallet.fromMnemonic(defaultMnemonic);
const password = "123";
const serialized = await original.serialize(password);
const deserialized = await Secp256k1HdWallet.deserialize(serialized, password);
const accounts = await deserialized.getAccounts();
expect(deserialized.mnemonic).toEqual(defaultMnemonic);
expect(accounts).toEqual([
{
algo: "secp256k1",
address: defaultAddress,
pubkey: defaultPubkey,
},
]);
});
it("can restore multiple accounts", async () => {
const mnemonic =
"economy stock theory fatal elder harbor betray wasp final emotion task crumble siren bottom lizard educate guess current outdoor pair theory focus wife stone";
const prefix = "wasm";
const accountNumbers = [0, 1, 2, 3, 4];
const hdPaths = accountNumbers.map(makeCosmoshubPath);
const original = await Secp256k1HdWallet.fromMnemonic(mnemonic, {
hdPaths: hdPaths,
prefix: prefix,
});
const password = "123";
const serialized = await original.serialize(password);
const deserialized = await Secp256k1HdWallet.deserialize(serialized, password);
const accounts = await deserialized.getAccounts();
expect(deserialized.mnemonic).toEqual(mnemonic);
// These values are taken from the generate_addresses.js script in the scripts/wasmd directory
expect(accounts).toEqual([
{
algo: "secp256k1",
pubkey: fromBase64("A08EGB7ro1ORuFhjOnZcSgwYlpe0DSFjVNUIkNNQxwKQ"),
address: "wasm1pkptre7fdkl6gfrzlesjjvhxhlc3r4gm32kke3",
},
{
algo: "secp256k1",
pubkey: fromBase64("AiDosfIbBi54XJ1QjCeApumcy/FjdtF+YhywPf3DKTx7"),
address: "wasm10dyr9899g6t0pelew4nvf4j5c3jcgv0r5d3a5l",
},
{
algo: "secp256k1",
pubkey: fromBase64("AzQg33JZqH7vSsm09esZY5bZvmzYwE/SY78cA0iLxpD7"),
address: "wasm1xy4yqngt0nlkdcenxymg8tenrghmek4n3u2lwa",
},
{
algo: "secp256k1",
pubkey: fromBase64("A3gOAlB6aiRTCPvWMQg2+ZbGYNsLd8qlvV28m8p2UhY2"),
address: "wasm142u9fgcjdlycfcez3lw8x6x5h7rfjlnfaallkd",
},
{
algo: "secp256k1",
pubkey: fromBase64("Aum2063ub/ErUnIUB36sK55LktGUStgcbSiaAnL1wadu"),
address: "wasm1hsm76p4ahyhl5yh3ve9ur49r5kemhp2r93f89d",
},
]);
});
});
describe("deserializeWithEncryptionKey", () => {
it("can restore", async () => {
const password = "123";
let serialized: string;
{
const original = await Secp256k1HdWallet.fromMnemonic(defaultMnemonic);
const anyKdfParams: KdfConfiguration = {
algorithm: "argon2id",
params: {
outputLength: 32,
opsLimit: 4,
memLimitKib: 3 * 1024,
},
};
const encryptionKey = await executeKdf(password, anyKdfParams);
serialized = await original.serializeWithEncryptionKey(encryptionKey, anyKdfParams);
}
{
const kdfConfiguration = extractKdfConfiguration(serialized);
const encryptionKey = await executeKdf(password, kdfConfiguration);
const deserialized = await Secp256k1HdWallet.deserializeWithEncryptionKey(serialized, encryptionKey);
expect(deserialized.mnemonic).toEqual(defaultMnemonic);
expect(await deserialized.getAccounts()).toEqual([
{
algo: "secp256k1",
address: defaultAddress,
pubkey: defaultPubkey,
},
]);
}
});
it("can restore multiple accounts", async () => {
const mnemonic =
"economy stock theory fatal elder harbor betray wasp final emotion task crumble siren bottom lizard educate guess current outdoor pair theory focus wife stone";
const prefix = "wasm";
const password = "123";
const accountNumbers = [0, 1, 2, 3, 4];
const hdPaths = accountNumbers.map(makeCosmoshubPath);
let serialized: string;
{
const original = await Secp256k1HdWallet.fromMnemonic(mnemonic, { prefix: prefix, hdPaths: hdPaths });
const anyKdfParams: KdfConfiguration = {
algorithm: "argon2id",
params: {
outputLength: 32,
opsLimit: 4,
memLimitKib: 3 * 1024,
},
};
const encryptionKey = await executeKdf(password, anyKdfParams);
serialized = await original.serializeWithEncryptionKey(encryptionKey, anyKdfParams);
}
{
const kdfConfiguration = extractKdfConfiguration(serialized);
const encryptionKey = await executeKdf(password, kdfConfiguration);
const deserialized = await Secp256k1HdWallet.deserializeWithEncryptionKey(serialized, encryptionKey);
const accounts = await deserialized.getAccounts();
expect(deserialized.mnemonic).toEqual(mnemonic);
expect(deserialized.mnemonic).toEqual(mnemonic);
// These values are taken from the generate_addresses.js script in the scripts/wasmd directory
expect(accounts).toEqual([
{
algo: "secp256k1",
pubkey: fromBase64("A08EGB7ro1ORuFhjOnZcSgwYlpe0DSFjVNUIkNNQxwKQ"),
address: "wasm1pkptre7fdkl6gfrzlesjjvhxhlc3r4gm32kke3",
},
{
algo: "secp256k1",
pubkey: fromBase64("AiDosfIbBi54XJ1QjCeApumcy/FjdtF+YhywPf3DKTx7"),
address: "wasm10dyr9899g6t0pelew4nvf4j5c3jcgv0r5d3a5l",
},
{
algo: "secp256k1",
pubkey: fromBase64("AzQg33JZqH7vSsm09esZY5bZvmzYwE/SY78cA0iLxpD7"),
address: "wasm1xy4yqngt0nlkdcenxymg8tenrghmek4n3u2lwa",
},
{
algo: "secp256k1",
pubkey: fromBase64("A3gOAlB6aiRTCPvWMQg2+ZbGYNsLd8qlvV28m8p2UhY2"),
address: "wasm142u9fgcjdlycfcez3lw8x6x5h7rfjlnfaallkd",
},
{
algo: "secp256k1",
pubkey: fromBase64("Aum2063ub/ErUnIUB36sK55LktGUStgcbSiaAnL1wadu"),
address: "wasm1hsm76p4ahyhl5yh3ve9ur49r5kemhp2r93f89d",
},
]);
}
});
});
describe("getAccounts", () => {
it("resolves to a list of accounts", async () => {
const wallet = await Secp256k1HdWallet.fromMnemonic(defaultMnemonic);
const accounts = await wallet.getAccounts();
expect(accounts.length).toEqual(1);
expect(accounts[0]).toEqual({
address: defaultAddress,
algo: "secp256k1",
pubkey: defaultPubkey,
});
});
it("creates the same address as Go implementation", async () => {
const wallet = await Secp256k1HdWallet.fromMnemonic(
"oyster design unusual machine spread century engine gravity focus cave carry slot",
);
const [{ address }] = await wallet.getAccounts();
expect(address).toEqual("cosmos1cjsxept9rkggzxztslae9ndgpdyt2408lk850u");
});
});
describe("signAmino", () => {
it("resolves to valid signature", async () => {
const wallet = await Secp256k1HdWallet.fromMnemonic(defaultMnemonic);
const signDoc: StdSignDoc = {
msgs: [],
fee: { amount: [], gas: "23" },
chain_id: "foochain",
memo: "hello, world",
account_number: "7",
sequence: "54",
};
const { signed, signature } = await wallet.signAmino(defaultAddress, signDoc);
expect(signed).toEqual(signDoc);
const valid = await Secp256k1.verifySignature(
Secp256k1Signature.fromFixedLength(fromBase64(signature.signature)),
sha256(serializeSignDoc(signed)),
defaultPubkey,
);
expect(valid).toEqual(true);
});
});
describe("serialize", () => {
it("can save with password", async () => {
const wallet = await Secp256k1HdWallet.fromMnemonic(defaultMnemonic);
const serialized = await wallet.serialize("123");
expect(JSON.parse(serialized)).toEqual({
type: "secp256k1wallet-v1",
kdf: {
algorithm: "argon2id",
params: {
outputLength: 32,
opsLimit: 24,
memLimitKib: 12 * 1024,
},
},
encryption: {
algorithm: "xchacha20poly1305-ietf",
},
data: jasmine.stringMatching(base64Matcher),
});
});
});
describe("serializeWithEncryptionKey", () => {
it("can save with password", async () => {
const wallet = await Secp256k1HdWallet.fromMnemonic(defaultMnemonic);
const key = fromHex("aabb221100aabb332211aabb33221100aabb221100aabb332211aabb33221100");
const customKdfConfiguration: KdfConfiguration = {
algorithm: "argon2id",
params: {
outputLength: 32,
opsLimit: 321,
memLimitKib: 11 * 1024,
},
};
const serialized = await wallet.serializeWithEncryptionKey(key, customKdfConfiguration);
expect(JSON.parse(serialized)).toEqual({
type: "secp256k1wallet-v1",
kdf: customKdfConfiguration,
encryption: {
algorithm: "xchacha20poly1305-ietf",
},
data: jasmine.stringMatching(base64Matcher),
});
});
});
}); | the_stack |
/*
* Copyright (c) 2016 - now David Sehnal, licensed under Apache 2.0, See LICENSE file for more info.
*/
namespace LiteMol.Core.Structure {
/**
* The query is a mapping from a context to a sequence of fragments.
*/
export type Query = (ctx: Query.Context) => Query.FragmentSeq;
export namespace Query {
export function apply(q: Source, m: Molecule.Model) {
return Builder.toQuery(q)(m.queryContext);
}
export type Source = Query | string | Builder
/**
* The context of a query.
*
* Stores:
* - the mask of "active" atoms.
* - kd-tree for fast geometry queries.
* - the molecule itself.
*
*/
export class Context {
private lazyLoopup3d: Geometry.Query3D.LookupStructure<number>;
/**
* Number of atoms in the current context.
*/
get atomCount() {
return this.mask.size;
}
/**
* Determine if the context contains all atoms of the input model.
*/
get isComplete() {
return this.mask.size === this.structure.data.atoms.count;
}
/**
* The structure this context is based on.
*/
structure: Molecule.Model;
/**
* Get a 3d loopup structure for the atoms in the current context.
*/
get lookup3d() {
if (!this.lazyLoopup3d) this.makeLookup3d();
return this.lazyLoopup3d;
}
/**
* Checks if an atom is included in the current context.
*/
hasAtom(index: number) {
return !!this.mask.has(index);
}
/**
* Checks if an atom from the range is included in the current context.
*/
hasRange(start: number, end: number) {
for (let i = start; i < end; i++) {
if (this.mask.has(i)) return true;
}
return false;
}
/**
* Create a new context based on the provide structure.
*/
static ofStructure(structure: Molecule.Model) {
return new Context(structure, Utils.Mask.ofStructure(structure));
}
/**
* Create a new context from a sequence of fragments.
*/
static ofFragments(seq: FragmentSeq) {
return new Context(seq.context.structure, Utils.Mask.ofFragments(seq));
}
/**
* Create a new context from a sequence of fragments.
*/
static ofAtomIndices(structure: Molecule.Model, atomIndices: number[]) {
return new Context(structure, Utils.Mask.ofIndices(structure.data.atoms.count, atomIndices));
}
constructor(structure: Molecule.Model, public readonly mask: Utils.Mask) {
this.structure = structure;
}
private makeLookup3d() {
let data = new Int32Array(this.mask.size),
dataCount = 0,
{x, y, z} = this.structure.positions;
for (let i = 0, _b = this.structure.positions.count; i < _b; i++) {
if (this.mask.has(i)) data[dataCount++] = i;
}
const inputData = Geometry.Query3D.createInputData(data as any as number[], (i, add) => add(x[i], y[i], z[i]));
this.lazyLoopup3d = Geometry.Query3D.createSpatialHash(inputData);
}
}
/**
* The basic element of the query language.
* Everything is represented as a fragment.
*/
export class Fragment {
/**
* The index of the first atom of the generator.
*/
tag: number;
/**
* Indices of atoms.
*/
atomIndices: number[];
/**
* The context the fragment belongs to.
*/
context: Context;
private _hashCode = 0;
private _hashComputed = false;
/**
* The hash code of the fragment.
*/
get hashCode() {
if (this._hashComputed) return this._hashCode;
let code = 23;
for (let i of this.atomIndices) {
code = (31 * code + i) | 0;
}
this._hashCode = code;
this._hashComputed = true;
return code;
}
/**
* Id composed of <moleculeid>_<tag>.
*/
get id() {
return this.context.structure.id + "_" + this.tag;
}
/**
* Number of atoms.
*/
get atomCount() {
return this.atomIndices.length;
}
/**
* Determines if a fragment is HET based on the tag.
*/
get isHet() {
let residue = (<any>this.context.structure.data.atoms).residueIndex[this.tag];
return (<any>this.context.structure.data.residues).isHet[residue];
}
private _fingerprint: string;
/**
* A sorted list of residue identifiers.
*/
get fingerprint() {
if (this._fingerprint) return this._fingerprint;
let indexList: number[] = this.residueIndices,
residues = this.context.structure.data.residues,
cName = residues.name, cAsym = residues.asymId, cSeq = residues.seqNumber, insCode = residues.insCode,
names:string[] = [];
for (let i of indexList) {
let name = cName[i] + " " + cAsym[i] + " " + cSeq[i];
if (insCode[i]) name += " i:" + insCode[i];
names[names.length] = name;
}
return names.join("-");
}
private _authFingerprint: string;
/**
* A sorted list of residue identifiers.
*/
get authFingerprint() {
if (this._authFingerprint) return this._authFingerprint;
let indexList: number[] = this.residueIndices,
residues = this.context.structure.data.residues,
cName = residues.authName, cAsym = residues.authAsymId, cSeq = residues.authSeqNumber, insCode = residues.insCode,
names: string[] = [];
for (let i of indexList) {
let name = cName[i] + " " + cAsym[i] + " " + cSeq[i];
if (insCode[i]) name += " i:" + insCode[i];
names[names.length] = name;
}
return names.join("-");
}
/**
* Executes a query on the current fragment.
*/
find(what: Source): FragmentSeq {
let ctx = Context.ofFragments(new FragmentSeq(this.context, [this]));
return Builder.toQuery(what)(ctx);
}
private _residueIndices: number[];
private _chainIndices: number[];
private _entityIndices: number[];
private computeIndices() {
if (this._residueIndices) return;
let residueIndices = Utils.FastSet.create<number>(),
chainIndices = Utils.FastSet.create<number>(),
entityIndices = Utils.FastSet.create<number>(),
rIndices = this.context.structure.data.atoms.residueIndex,
cIndices = this.context.structure.data.residues.chainIndex,
eIndices = this.context.structure.data.chains.entityIndex;
for (let i of this.atomIndices) { residueIndices.add(rIndices[i]); }
this._residueIndices = Utils.integerSetToSortedTypedArray(residueIndices);
for (let i of this._residueIndices) { chainIndices.add(cIndices[i]); }
this._chainIndices = Utils.integerSetToSortedTypedArray(chainIndices);
for (let i of this._chainIndices) { entityIndices.add(eIndices[i]); }
this._entityIndices = Utils.integerSetToSortedTypedArray(entityIndices);
}
/**
* A sorted list of residue indices.
*/
get residueIndices() {
this.computeIndices();
return this._residueIndices;
}
/**
* A sorted list of chain indices.
*/
get chainIndices() {
this.computeIndices();
return this._chainIndices;
}
/**
* A sorted list of entity indices.
*/
get entityIndices() {
this.computeIndices();
return this._entityIndices;
}
static areEqual(a: Fragment, b: Fragment) {
if (a.atomCount !== b.atomCount) return false;
let xs = a.atomIndices, ys = b.atomIndices;
for (let i = 0; i < xs.length; i++) {
if (xs[i] !== ys[i]) return false;
}
return a.tag === b.tag;
}
/**
* Create a fragment from an integer set.
* Assumes the set is in the given context's mask.
*/
static ofSet(context: Context, atomIndices: Utils.FastSet<number>) {
let array = new Int32Array(atomIndices.size);
atomIndices.forEach((i, ctx) => { ctx!.array[ctx!.index++] = i }, { array, index: 0 });
Array.prototype.sort.call(array, function (a: number, b: number) { return a - b; });
return new Fragment(context, array[0], <any>array);
}
/**
* Create a fragment from an integer array.
* Assumes the set is in the given context's mask.
* Assumes the array is sorted.
*/
static ofArray(context: Context, tag: number, atomIndices: Int32Array | number[]) {
return new Fragment(context, tag, <any>atomIndices);
}
/**
* Create a fragment from a single index.
* Assumes the index is in the given context's mask.
*/
static ofIndex(context: Context, index: number) {
let indices = new Int32Array(1);
indices[0] = index;
return new Fragment(context, index, <any>indices);
}
/**
* Create a fragment from a <start,end) range.
* Assumes the fragment is non-empty in the given context's mask.
*/
static ofIndexRange(context: Context, start: number, endExclusive: number) {
let count = 0;
for (let i = start; i < endExclusive; i++) {
if (context.hasAtom(i)) count++;
}
let atoms = new Int32Array(count), offset = 0;
for (let i = start; i < endExclusive; i++) {
if (context.hasAtom(i)) atoms[offset++] = i;
}
return new Fragment(context, start, <any>atoms);
}
/**
* Create a fragment from an integer set.
*/
constructor(context: Context, tag: number, atomIndices: number[]) {
this.context = context;
this.tag = tag;
this.atomIndices = atomIndices;
}
}
/**
* A sequence of fragments the queries operate on.
*/
export class FragmentSeq {
static empty(ctx: Context) {
return new FragmentSeq(ctx, []);
}
get length() {
return this.fragments.length;
}
/**
* Merges atom indices from all fragments.
*/
unionAtomIndices(): number[] {
if (!this.length) return [];
if (this.length === 1) return this.fragments[0].atomIndices;
let map = <number[]><any>new Int8Array(this.context.structure.data.atoms.count),
atomCount = 0;
for (let f of this.fragments) {
for (let i of f.atomIndices) {
map[i] = 1;
}
}
for (let i of map) {
atomCount += i;
}
let ret = new Int32Array(atomCount),
offset = 0;
for (let i = 0, _l = map.length; i < _l; i++) {
if (map[i]) ret[offset++] = i;
}
return <number[]><any>ret;
}
/**
* Merges atom indices from all fragments into a single fragment.
*/
unionFragment(): Fragment {
if (!this.length) return new Fragment(this.context, 0, <any>new Int32Array(0));
if (this.length === 1) return this.fragments[0];
let union = this.unionAtomIndices();
return new Fragment(this.context, union[0], union);
}
constructor(
public context: Context,
public fragments: Fragment[]) {
}
}
/**
* A builder that includes all fragments.
*/
export class FragmentSeqBuilder {
private fragments: Fragment[] = [];
add(f: Fragment) {
this.fragments[this.fragments.length] = f;
}
getSeq() {
return new FragmentSeq(this.ctx, this.fragments);
}
constructor(private ctx: Context) {
}
}
/**
* A builder that includes only unique fragments.
*/
export class HashFragmentSeqBuilder {
private fragments: Fragment[] = [];
private byHash = Utils.FastMap.create<number, Fragment[]>();
add(f: Fragment) {
let hash = f.hashCode;
if (this.byHash.has(hash)) {
let fs = this.byHash.get(hash)!;
for (let q of fs) {
if (Fragment.areEqual(f, q)) return this;
}
this.fragments[this.fragments.length] = f;
fs[fs.length] = f;
} else {
this.fragments[this.fragments.length] = f;
this.byHash.set(hash, [f]);
}
return this;
}
getSeq() {
return new FragmentSeq(this.ctx, this.fragments);
}
constructor(private ctx: Context) {
}
}
}
} | the_stack |
import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing';
import {loadStandardTestFiles} from '@angular/compiler-cli/src/ngtsc/testing';
import {platform} from 'os';
import {NgtscTestEnvironment} from './env';
const testFiles = loadStandardTestFiles({fakeCore: true, fakeCommon: true});
runInEachFileSystem(os => {
let env!: NgtscTestEnvironment;
if (os === 'Windows' || platform() === 'win32') {
// xi18n tests are skipped on Windows as the paths in the expected message files are platform-
// sensitive. These tests will be deleted when xi18n is removed, so it's not a major priority
// to make them work with Windows.
return;
}
describe('ngtsc xi18n', () => {
beforeEach(() => {
env = NgtscTestEnvironment.setup(testFiles);
env.tsconfig();
writeTestCode(env);
});
it('should extract xmb', () => {
env.driveXi18n('xmb', 'messages.xmb');
expect(env.getContents('messages.xmb')).toEqual(EXPECTED_XMB);
});
it('should extract xlf', () => {
// Note that only in XLF mode do we pass a locale into the extraction.
env.driveXi18n('xlf', 'messages.xlf', 'fr');
expect(env.getContents('messages.xlf')).toEqual(EXPECTED_XLIFF);
});
it('should extract xlf', () => {
env.driveXi18n('xlf2', 'messages.xliff2.xlf');
expect(env.getContents('messages.xliff2.xlf')).toEqual(EXPECTED_XLIFF2);
});
it('should not emit js', () => {
env.driveXi18n('xlf2', 'messages.xliff2.xlf');
env.assertDoesNotExist('src/module.js');
});
});
});
const EXPECTED_XMB = `<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE messagebundle [
<!ELEMENT messagebundle (msg)*>
<!ATTLIST messagebundle class CDATA #IMPLIED>
<!ELEMENT msg (#PCDATA|ph|source)*>
<!ATTLIST msg id CDATA #IMPLIED>
<!ATTLIST msg seq CDATA #IMPLIED>
<!ATTLIST msg name CDATA #IMPLIED>
<!ATTLIST msg desc CDATA #IMPLIED>
<!ATTLIST msg meaning CDATA #IMPLIED>
<!ATTLIST msg obsolete (obsolete) #IMPLIED>
<!ATTLIST msg xml:space (default|preserve) "default">
<!ATTLIST msg is_hidden CDATA #IMPLIED>
<!ELEMENT source (#PCDATA)>
<!ELEMENT ph (#PCDATA|ex)*>
<!ATTLIST ph name CDATA #REQUIRED>
<!ELEMENT ex (#PCDATA)>
]>
<messagebundle>
<msg id="8136548302122759730" desc="desc" meaning="meaning"><source>src/basic.html:1</source><source>src/comp2.ts:1</source><source>src/basic.html:1</source>translate me</msg>
<msg id="9038505069473852515"><source>src/basic.html:3,4</source><source>src/comp2.ts:3,4</source><source>src/comp2.ts:2,3</source><source>src/basic.html:3,4</source>
Welcome</msg>
<msg id="5611534349548281834" desc="with ICU"><source>src/icu.html:1,3</source><source>src/icu.html:5</source>{VAR_PLURAL, plural, =1 {book} other {books} }</msg>
<msg id="5811701742971715242" desc="with ICU and other things"><source>src/icu.html:4,6</source>
foo <ph name="ICU"><ex>{ count, plural, =1 {...} other {...}}</ex>{ count, plural, =1 {...} other {...}}</ph>
</msg>
<msg id="7254052530614200029" desc="with placeholders"><source>src/placeholders.html:1,3</source>Name: <ph name="START_BOLD_TEXT"><ex><b></ex><b></ph><ph name="NAME"><ex>{{
name // i18n(ph="name")
}}</ex>{{
name // i18n(ph="name")
}}</ph><ph name="CLOSE_BOLD_TEXT"><ex></b></ex></b></ph></msg>
</messagebundle>
`;
const EXPECTED_XLIFF = `<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="fr" datatype="plaintext" original="ng2.template">
<body>
<trans-unit id="76e1eccb1b772fa9f294ef9c146ea6d0efa8a2d4" datatype="html">
<source>translate me</source>
<context-group purpose="location">
<context context-type="sourcefile">src/basic.html</context>
<context context-type="linenumber">1</context>
</context-group>
<context-group purpose="location">
<context context-type="sourcefile">src/comp2.ts</context>
<context context-type="linenumber">1</context>
</context-group>
<context-group purpose="location">
<context context-type="sourcefile">src/basic.html</context>
<context context-type="linenumber">1</context>
</context-group>
<note priority="1" from="description">desc</note>
<note priority="1" from="meaning">meaning</note>
</trans-unit>
<trans-unit id="085a5ecc40cc87451d216725b2befd50866de18a" datatype="html">
<source>
Welcome</source>
<context-group purpose="location">
<context context-type="sourcefile">src/basic.html</context>
<context context-type="linenumber">3</context>
</context-group>
<context-group purpose="location">
<context context-type="sourcefile">src/comp2.ts</context>
<context context-type="linenumber">3</context>
</context-group>
<context-group purpose="location">
<context context-type="sourcefile">src/comp2.ts</context>
<context context-type="linenumber">2</context>
</context-group>
<context-group purpose="location">
<context context-type="sourcefile">src/basic.html</context>
<context context-type="linenumber">3</context>
</context-group>
</trans-unit>
<trans-unit id="83937c05b1216e7f4c02a85454260e28fd72d1e3" datatype="html">
<source>{VAR_PLURAL, plural, =1 {book} other {books} }</source>
<context-group purpose="location">
<context context-type="sourcefile">src/icu.html</context>
<context context-type="linenumber">1</context>
</context-group>
<note priority="1" from="description">with ICU</note>
</trans-unit>
<trans-unit id="540c5f481129419ef21017f396b6c2d0869ca4d2" datatype="html">
<source>
foo <x id="ICU" equiv-text="{ count, plural, =1 {...} other {...}}"/>
</source>
<context-group purpose="location">
<context context-type="sourcefile">src/icu.html</context>
<context context-type="linenumber">4</context>
</context-group>
<note priority="1" from="description">with ICU and other things</note>
</trans-unit>
<trans-unit id="ca7678090fddd04441d63b1218177af65f23342d" datatype="html">
<source>{VAR_PLURAL, plural, =1 {book} other {books} }</source>
<context-group purpose="location">
<context context-type="sourcefile">src/icu.html</context>
<context context-type="linenumber">5</context>
</context-group>
</trans-unit>
<trans-unit id="9311399c1ca7c75f771d77acb129e50581c6ec1f" datatype="html">
<source>Name: <x id="START_BOLD_TEXT" ctype="x-b" equiv-text="<b>"/><x id="NAME" equiv-text="{{
name // i18n(ph="name")
}}"/><x id="CLOSE_BOLD_TEXT" ctype="x-b" equiv-text="</b>"/></source>
<context-group purpose="location">
<context context-type="sourcefile">src/placeholders.html</context>
<context context-type="linenumber">1</context>
</context-group>
<note priority="1" from="description">with placeholders</note>
</trans-unit>
</body>
</file>
</xliff>
`;
const EXPECTED_XLIFF2 = `<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="en">
<file original="ng.template" id="ngi18n">
<unit id="8136548302122759730">
<notes>
<note category="description">desc</note>
<note category="meaning">meaning</note>
<note category="location">src/basic.html:1</note>
<note category="location">src/comp2.ts:1</note>
<note category="location">src/basic.html:1</note>
</notes>
<segment>
<source>translate me</source>
</segment>
</unit>
<unit id="9038505069473852515">
<notes>
<note category="location">src/basic.html:3,4</note>
<note category="location">src/comp2.ts:3,4</note>
<note category="location">src/comp2.ts:2,3</note>
<note category="location">src/basic.html:3,4</note>
</notes>
<segment>
<source>
Welcome</source>
</segment>
</unit>
<unit id="5611534349548281834">
<notes>
<note category="description">with ICU</note>
<note category="location">src/icu.html:1,3</note>
<note category="location">src/icu.html:5</note>
</notes>
<segment>
<source>{VAR_PLURAL, plural, =1 {book} other {books} }</source>
</segment>
</unit>
<unit id="5811701742971715242">
<notes>
<note category="description">with ICU and other things</note>
<note category="location">src/icu.html:4,6</note>
</notes>
<segment>
<source>
foo <ph id="0" equiv="ICU" disp="{ count, plural, =1 {...} other {...}}"/>
</source>
</segment>
</unit>
<unit id="7254052530614200029">
<notes>
<note category="description">with placeholders</note>
<note category="location">src/placeholders.html:1,3</note>
</notes>
<segment>
<source>Name: <pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="<b>" dispEnd="</b>"><ph id="1" equiv="NAME" disp="{{
name // i18n(ph="name")
}}"/></pc></source>
</segment>
</unit>
</file>
</xliff>
`;
/**
* Note: the indentation here is load-bearing.
*/
function writeTestCode(env: NgtscTestEnvironment): void {
const welcomeMessage = `
<!--i18n-->
Welcome<!--/i18n-->
`;
env.write('src/basic.html', `<div title="translate me" i18n-title="meaning|desc"></div>
<p id="welcomeMessage">${welcomeMessage}</p>`);
env.write('src/comp1.ts', `
import {Component} from '@angular/core';
@Component({
selector: 'basic',
templateUrl: './basic.html',
})
export class BasicCmp1 {}`);
env.write('src/comp2.ts', `
import {Component} from '@angular/core';
@Component({
selector: 'basic2',
template: \`<div title="translate me" i18n-title="meaning|desc"></div>
<p id="welcomeMessage">${welcomeMessage}</p>\`,
})
export class BasicCmp2 {}
@Component({
selector: 'basic4',
template: \`<p id="welcomeMessage">${welcomeMessage}</p>\`,
})
export class BasicCmp4 {}`);
env.write('src/comp3.ts', `
import {Component} from '@angular/core';
@Component({
selector: 'basic3',
templateUrl: './basic.html',
})
export class BasicCmp3 {}`);
env.write('src/placeholders.html', `<div i18n="with placeholders">Name: <b>{{
name // i18n(ph="name")
}}</b></div>`);
env.write('src/placeholder_cmp.ts', `
import {Component} from '@angular/core';
@Component({
selector: 'placeholders',
templateUrl: './placeholders.html',
})
export class PlaceholderCmp { name = 'whatever'; }`);
env.write('src/icu.html', `<div i18n="with ICU">{
count, plural, =1 {book} other {books}
}</div>
<div i18n="with ICU and other things">
foo { count, plural, =1 {book} other {books} }
</div>`);
env.write('src/icu_cmp.ts', `
import {Component} from '@angular/core';
@Component({
selector: 'icu',
templateUrl: './icu.html',
})
export class IcuCmp { count = 3; }`);
env.write('src/module.ts', `
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {BasicCmp1} from './comp1';
import {BasicCmp2, BasicCmp4} from './comp2';
import {BasicCmp3} from './comp3';
import {PlaceholderCmp} from './placeholder_cmp';
import {IcuCmp} from './icu_cmp';
@NgModule({
declarations: [
BasicCmp1,
BasicCmp2,
BasicCmp3,
BasicCmp4,
PlaceholderCmp,
IcuCmp,
],
imports: [CommonModule],
})
export class I18nModule {}
`);
} | the_stack |
import type {Mutable, Proto} from "@swim/util";
import type {FastenerOwner, FastenerFlags, Fastener} from "@swim/component";
import {FileRelationInit, FileRelationClass, FileRelation} from "./FileRelation";
/** @internal */
export type FileRefValue<F extends FileRef<any, any>> =
F extends FileRef<any, infer T> ? T : never;
/** @public */
export interface FileRefInit<T = unknown> extends FileRelationInit<T> {
extends?: {prototype: FileRef<any, any>} | string | boolean | null;
fileName?: string;
value?: T;
getFileName?(): string | undefined;
willSetFileName?(newFileName: string | undefined, oldFileName: string | undefined): void;
didSetFileName?(newFileName: string | undefined, oldFileName: string | undefined): void;
}
/** @public */
export type FileRefDescriptor<O = unknown, T = unknown, I = {}> = ThisType<FileRef<O, T> & I> & FileRefInit<T> & Partial<I>;
/** @public */
export interface FileRefClass<F extends FileRef<any, any> = FileRef<any, any>> extends FileRelationClass<F> {
/** @internal */
readonly LoadedFlag: FastenerFlags;
/** @internal */
readonly ModifiedFlag: FastenerFlags;
/** @internal @override */
readonly FlagShift: number;
/** @internal @override */
readonly FlagMask: FastenerFlags;
}
/** @public */
export interface FileRefFactory<F extends FileRef<any, any> = FileRef<any, any>> extends FileRefClass<F> {
extend<I = {}>(className: string, classMembers?: Partial<I> | null): FileRefFactory<F> & I;
define<O, T = unknown>(className: string, descriptor: FileRefDescriptor<O, T>): FileRefFactory<FileRef<any, T>>;
define<O, T = unknown, I = {}>(className: string, descriptor: {implements: unknown} & FileRefDescriptor<O, T, I>): FileRefFactory<FileRef<any, T> & I>;
<O, T = unknown>(descriptor: FileRefDescriptor<O, T>): PropertyDecorator;
<O, T = unknown, I = {}>(descriptor: {implements: unknown} & FileRefDescriptor<O, T, I>): PropertyDecorator;
}
/** @public */
export interface FileRef<O = unknown, T = unknown> extends FileRelation<O, T> {
(): T | null;
(fileName: string | undefined): O;
/** @override */
get fastenerType(): Proto<FileRef<any, any>>;
/** @protected @override */
onInherit(superFastener: Fastener): void;
readonly fileName: string | undefined;
getFileName(): string | undefined;
/** @internal */
initFileName(fileName: string | undefined): void;
setFileName(fileName: string | undefined): void;
/** @protected */
willSetFileName(newFileName: string | undefined, oldFileName: string | undefined): void;
/** @protected */
onSetFileName(newFileName: string | undefined, oldFileName: string | undefined): void;
/** @protected */
didSetFileName(newFileName: string | undefined, oldFileName: string | undefined): void;
resolve(): Promise<string | undefined>;
get loaded(): boolean;
load(path?: string): Promise<T>;
loadIfExists(path?: string): Promise<T | undefined>;
loadIfExists<E>(path: string | undefined, elseValue: E): Promise<T | E>;
get modified(): boolean;
store(path?: string, value?: T): Promise<void>;
readonly path: string | undefined;
readonly value: T;
getOrLoad(): Promise<T>;
getOrLoadIfExists(): Promise<T | undefined>;
getOrLoadIfExists<E>(elseValue: E): Promise<T | E>;
/** @internal */
initValue(value: T): void;
setValue(path: string, value: T): T;
}
/** @public */
export const FileRef = (function (_super: typeof FileRelation) {
const FileRef: FileRefFactory = _super.extend("FileRef");
Object.defineProperty(FileRef.prototype, "fastenerType", {
get: function (this: FileRef): Proto<FileRef<any, any>> {
return FileRef;
},
configurable: true,
});
FileRef.prototype.onInherit = function (this: FileRef, superFastener: FileRef): void {
this.setBaseDir(superFastener.baseDir);
this.setFileName(superFastener.fileName);
};
FileRef.prototype.getFileName = function (this: FileRef): string | undefined {
return this.fileName;
};
FileRef.prototype.initFileName = function (this: FileRef, fileName: string | undefined): void {
(this as Mutable<typeof this>).fileName = fileName;
};
FileRef.prototype.setFileName = function (this: FileRef, newFileName: string | undefined): void {
const oldFileName = this.fileName;
if (newFileName !== oldFileName) {
this.willSetFileName(newFileName, oldFileName);
(this as Mutable<typeof this>).fileName = newFileName;
this.onSetFileName(newFileName, oldFileName);
this.didSetFileName(newFileName, oldFileName);
}
};
FileRef.prototype.willSetFileName = function (this: FileRef, newFileName: string | undefined, oldFileName: string | undefined): void {
// hook
};
FileRef.prototype.onSetFileName = function (this: FileRef, newFileName: string | undefined, oldFileName: string | undefined): void {
// hook
};
FileRef.prototype.didSetFileName = function (this: FileRef, newFileName: string | undefined, oldFileName: string | undefined): void {
// hook
};
FileRef.prototype.resolve = function (this: FileRef): Promise<string | undefined> {
const baseDir = this.getBaseDir();
const fileName = this.getFileName();
return this.resolveFile(baseDir, fileName);
};
Object.defineProperty(FileRef.prototype, "loaded", {
get: function (this: FileRef): boolean {
return (this.flags & FileRef.LoadedFlag) !== 0;
},
configurable: true,
});
FileRef.prototype.load = async function <T>(this: FileRef<unknown, T>, path?: string): Promise<T> {
if (path === void 0) {
const baseDir = this.getBaseDir();
const fileName = this.getFileName();
path = await this.resolveFile(baseDir, fileName);
if (path === void 0) {
let message = "unable to resolve file " + fileName;
if (baseDir !== void 0) {
message += " in directory " + baseDir;
}
throw new Error(message);
}
}
const value = await this.readFile(path);
this.setFlags(this.flags | FileRef.LoadedFlag);
this.setValue(path, value);
return value;
};
FileRef.prototype.loadIfExists = async function <T, E>(this: FileRef<unknown, T>, path?: string, elseValue?: E): Promise<T | E> {
if (path === void 0) {
const baseDir = this.getBaseDir();
const fileName = this.getFileName();
path = await this.resolveFile(baseDir, fileName);
}
if (path !== void 0 && this.exists(path)) {
const value = await this.readFile(path);
this.setFlags(this.flags | FileRef.LoadedFlag);
this.setValue(path, value);
return value;
} else {
return elseValue as E;
}
};
Object.defineProperty(FileRef.prototype, "modified", {
get: function (this: FileRef): boolean {
return (this.flags & FileRef.ModifiedFlag) !== 0;
},
configurable: true,
});
FileRef.prototype.store = async function <T>(this: FileRef<unknown, T>, path?: string, value?: T): Promise<void> {
if (path === void 0) {
path = this.path;
if (path === void 0) {
const baseDir = this.getBaseDir();
const fileName = this.getFileName();
path = await this.resolveFile(baseDir, fileName);
if (path === void 0) {
let message = "unable to resolve file " + fileName;
if (baseDir !== void 0) {
message += " in directory " + baseDir;
}
throw new Error(message);
}
(this as Mutable<typeof this>).path = path;
}
}
if (value === void 0) {
value = this.value;
} else {
this.setValue(path, value);
}
await this.writeFile(path, value);
this.setFlags(this.flags & ~FileRef.ModifiedFlag);
};
FileRef.prototype.getOrLoad = async function <T>(this: FileRef<unknown, T>): Promise<T> {
if (this.loaded) {
return this.value;
} else {
return this.load();
}
};
FileRef.prototype.getOrLoadIfExists = async function <T, E>(this: FileRef<unknown, T>, elseValue?: E): Promise<T | E> {
if (this.loaded) {
return this.value;
} else {
return this.loadIfExists(void 0, elseValue as E);
}
};
FileRef.prototype.initValue = function <T>(this: FileRef<unknown, T>, value: T): void {
(this as Mutable<typeof this>).value = value;
};
FileRef.prototype.setValue = function <T>(this: FileRef<unknown, T>, path: string, newValue: T): void {
(this as Mutable<typeof this>).path = path;
const oldValue = this.value;
if (!this.equalValues(newValue, oldValue)) {
this.willSetValue(path, newValue, oldValue);
(this as Mutable<typeof this>).value = newValue;
this.setFlags(this.flags | FileRef.ModifiedFlag);
this.onSetValue(path, newValue, oldValue);
this.didSetValue(path, newValue, oldValue);
}
};
FileRef.construct = function <F extends FileRef<any, any>>(fastenerClass: {prototype: F}, fastener: F | null, owner: FastenerOwner<F>): F {
if (fastener === null) {
fastener = function (fileName?: string | undefined): FileRefValue<F> | FastenerOwner<F> {
if (arguments.length === 0) {
return fastener!.value;
} else {
fastener!.setFileName(fileName);
return fastener!.owner;
}
} as F;
delete (fastener as Partial<Mutable<F>>).name; // don't clobber prototype name
Object.setPrototypeOf(fastener, fastenerClass.prototype);
}
fastener = _super.construct(fastenerClass, fastener, owner) as F;
(fastener as Mutable<typeof fastener>).fileName = void 0;
(fastener as Mutable<typeof fastener>).path = void 0;
(fastener as Mutable<typeof fastener>).value = void 0;
return fastener;
};
FileRef.define = function <O, T>(className: string, descriptor: FileRefDescriptor<O, T>): FileRefFactory<FileRef<any, T>> {
let superClass = descriptor.extends as FileRefFactory | null | undefined;
const affinity = descriptor.affinity;
const inherits = descriptor.inherits;
const baseDir = descriptor.baseDir;
const fileName = descriptor.fileName;
const resolves = descriptor.resolves;
const value = descriptor.value;
delete descriptor.extends;
delete descriptor.implements;
delete descriptor.affinity;
delete descriptor.inherits;
delete descriptor.baseDir;
delete descriptor.fileName;
delete descriptor.resolves;
delete descriptor.value;
if (superClass === void 0 || superClass === null) {
superClass = this;
}
const fastenerClass = superClass.extend(className, descriptor);
fastenerClass.construct = function (fastenerClass: {prototype: FileRef<any, any>}, fastener: FileRef<O, T> | null, owner: O): FileRef<O, T> {
fastener = superClass!.construct(fastenerClass, fastener, owner);
if (affinity !== void 0) {
fastener.initAffinity(affinity);
}
if (inherits !== void 0) {
fastener.initInherits(inherits);
}
if (baseDir !== void 0) {
fastener.initBaseDir(baseDir);
}
if (fileName !== void 0) {
fastener.initFileName(fileName);
}
if (resolves !== void 0) {
fastener.initResolves(resolves);
}
if (value !== void 0) {
fastener.initValue(value);
}
return fastener;
};
return fastenerClass;
};
(FileRef as Mutable<typeof FileRef>).LoadedFlag = 1 << (_super.FlagShift + 0);
(FileRef as Mutable<typeof FileRef>).ModifiedFlag = 1 << (_super.FlagShift + 1);
(FileRef as Mutable<typeof FileRef>).FlagShift = _super.FlagShift + 2;
(FileRef as Mutable<typeof FileRef>).FlagMask = (1 << FileRef.FlagShift) - 1;
return FileRef;
})(FileRelation); | the_stack |
import type {
AnyFramework,
InputType,
StoryContext as StoryContextForFramework,
LegacyStoryFn as LegacyStoryFnForFramework,
PartialStoryFn as PartialStoryFnForFramework,
ArgsStoryFn as ArgsStoryFnForFramework,
StoryFn as StoryFnForFramework,
DecoratorFunction as DecoratorFunctionForFramework,
LoaderFunction as LoaderFunctionForFramework,
StoryId,
StoryKind,
StoryName,
Args,
} from '@storybook/csf';
import { Addon } from './index';
// NOTE: The types exported from this file are simplified versions of the types exported
// by @storybook/csf, with the simpler form retained for backwards compatibility.
// We will likely start exporting the more complex <StoryFnReturnType> based types in 7.0
export type {
StoryId,
StoryKind,
StoryName,
StoryIdentifier,
ViewMode,
Args,
} from '@storybook/csf';
export interface ArgType<TArg = unknown> extends InputType {
defaultValue?: TArg;
}
export type ArgTypes<TArgs = Args> = {
[key in keyof Partial<TArgs>]: ArgType<TArgs[key]>;
} &
{
// for custom defined args
[key in string]: ArgType<unknown>;
};
export type Comparator<T> = ((a: T, b: T) => boolean) | ((a: T, b: T) => number);
export type StorySortMethod = 'configure' | 'alphabetical';
export interface StorySortObjectParameter {
method?: StorySortMethod;
order?: any[];
locales?: string;
includeNames?: boolean;
}
interface StoryIndexEntry {
id: StoryId;
name: StoryName;
title: string;
importPath: string;
}
// The `any` here is the story store's `StoreItem` record. Ideally we should probably only
// pass a defined subset of that full data, but we pass it all so far :shrug:
export type StorySortComparator = Comparator<[StoryId, any, Parameters, Parameters]>;
export type StorySortParameter = StorySortComparator | StorySortObjectParameter;
export type StorySortComparatorV7 = Comparator<StoryIndexEntry>;
export type StorySortParameterV7 = StorySortComparatorV7 | StorySortObjectParameter;
export interface OptionsParameter extends Object {
storySort?: StorySortParameter;
theme?: {
base: string;
brandTitle?: string;
};
[key: string]: any;
}
export interface Parameters {
fileName?: string;
options?: OptionsParameter;
/** The layout property defines basic styles added to the preview body where the story is rendered. If you pass 'none', no styles are applied. */
layout?: 'centered' | 'fullscreen' | 'padded' | 'none';
docsOnly?: boolean;
[key: string]: any;
}
export type StoryContext = StoryContextForFramework<AnyFramework>;
export type StoryContextUpdate = Partial<StoryContext>;
type ReturnTypeFramework<ReturnType> = { component: any; storyResult: ReturnType };
export type PartialStoryFn<ReturnType = unknown> = PartialStoryFnForFramework<
ReturnTypeFramework<ReturnType>
>;
export type LegacyStoryFn<ReturnType = unknown> = LegacyStoryFnForFramework<
ReturnTypeFramework<ReturnType>
>;
export type ArgsStoryFn<ReturnType = unknown> = ArgsStoryFnForFramework<
ReturnTypeFramework<ReturnType>
>;
export type StoryFn<ReturnType = unknown> = StoryFnForFramework<ReturnTypeFramework<ReturnType>>;
export type DecoratorFunction<StoryFnReturnType = unknown> = DecoratorFunctionForFramework<
ReturnTypeFramework<StoryFnReturnType>
>;
export type LoaderFunction = LoaderFunctionForFramework<ReturnTypeFramework<unknown>>;
export enum types {
TAB = 'tab',
PANEL = 'panel',
TOOL = 'tool',
TOOLEXTRA = 'toolextra',
PREVIEW = 'preview',
NOTES_ELEMENT = 'notes-element',
}
export type Types = types | string;
export function isSupportedType(type: Types): boolean {
return !!Object.values(types).find((typeVal) => typeVal === type);
}
export interface WrapperSettings {
options: object;
parameters: {
[key: string]: any;
};
}
export type StoryWrapper = (
storyFn: LegacyStoryFn,
context: StoryContext,
settings: WrapperSettings
) => any;
export type MakeDecoratorResult = (...args: any) => any;
export interface AddStoryArgs<StoryFnReturnType = unknown> {
id: StoryId;
kind: StoryKind;
name: StoryName;
storyFn: StoryFn<StoryFnReturnType>;
parameters: Parameters;
}
export interface ClientApiAddon<StoryFnReturnType = unknown> extends Addon {
apply: (a: StoryApi<StoryFnReturnType>, b: any[]) => any;
}
export interface ClientApiAddons<StoryFnReturnType> {
[key: string]: ClientApiAddon<StoryFnReturnType>;
}
// Old types for getStorybook()
export interface IStorybookStory {
name: string;
render: (context: any) => any;
}
export interface IStorybookSection {
kind: string;
stories: IStorybookStory[];
}
export type ClientApiReturnFn<StoryFnReturnType = unknown> = (
...args: any[]
) => StoryApi<StoryFnReturnType>;
export interface StoryApi<StoryFnReturnType = unknown> {
kind: StoryKind;
add: (
storyName: StoryName,
storyFn: StoryFn<StoryFnReturnType>,
parameters?: Parameters
) => StoryApi<StoryFnReturnType>;
addDecorator: (decorator: DecoratorFunction<StoryFnReturnType>) => StoryApi<StoryFnReturnType>;
addLoader: (decorator: LoaderFunction) => StoryApi<StoryFnReturnType>;
addParameters: (parameters: Parameters) => StoryApi<StoryFnReturnType>;
[k: string]: string | ClientApiReturnFn<StoryFnReturnType>;
}
export interface ClientStoryApi<StoryFnReturnType = unknown> {
storiesOf(kind: StoryKind, module: NodeModule): StoryApi<StoryFnReturnType>;
addDecorator(decorator: DecoratorFunction<StoryFnReturnType>): StoryApi<StoryFnReturnType>;
addParameters(parameter: Parameters): StoryApi<StoryFnReturnType>;
}
type LoadFn = () => any;
type RequireContext = any; // FIXME
export type Loadable = RequireContext | [RequireContext] | LoadFn;
// CSF types, to be re-org'ed in 6.1
export type BaseDecorators<StoryFnReturnType> = Array<
(story: () => StoryFnReturnType, context: StoryContext) => StoryFnReturnType
>;
export interface BaseAnnotations<Args, StoryFnReturnType> {
/**
* Dynamic data that are provided (and possibly updated by) Storybook and its addons.
* @see [Arg story inputs](https://storybook.js.org/docs/react/api/csf#args-story-inputs)
*/
args?: Partial<Args>;
/**
* ArgTypes encode basic metadata for args, such as `name`, `description`, `defaultValue` for an arg. These get automatically filled in by Storybook Docs.
* @see [Control annotations](https://github.com/storybookjs/storybook/blob/91e9dee33faa8eff0b342a366845de7100415367/addons/controls/README.md#control-annotations)
*/
argTypes?: ArgTypes<Args>;
/**
* Custom metadata for a story.
* @see [Parameters](https://storybook.js.org/docs/basics/writing-stories/#parameters)
*/
parameters?: Parameters;
/**
* Wrapper components or Storybook decorators that wrap a story.
*
* Decorators defined in Meta will be applied to every story variation.
* @see [Decorators](https://storybook.js.org/docs/addons/introduction/#1-decorators)
*/
decorators?: BaseDecorators<StoryFnReturnType>;
/**
* Define a custom render function for the story(ies). If not passed, a default render function by the framework will be used.
*/
render?: (args: Args, context: StoryContext) => StoryFnReturnType;
/**
* Function that is executed after the story is rendered.
*/
play?: (context: StoryContext) => Promise<void> | void;
}
export interface Annotations<Args, StoryFnReturnType>
extends BaseAnnotations<Args, StoryFnReturnType> {
/**
* Used to only include certain named exports as stories. Useful when you want to have non-story exports such as mock data or ignore a few stories.
* @example
* includeStories: ['SimpleStory', 'ComplexStory']
* includeStories: /.*Story$/
*
* @see [Non-story exports](https://storybook.js.org/docs/formats/component-story-format/#non-story-exports)
*/
includeStories?: string[] | RegExp;
/**
* Used to exclude certain named exports. Useful when you want to have non-story exports such as mock data or ignore a few stories.
* @example
* excludeStories: ['simpleData', 'complexData']
* excludeStories: /.*Data$/
*
* @see [Non-story exports](https://storybook.js.org/docs/formats/component-story-format/#non-story-exports)
*/
excludeStories?: string[] | RegExp;
}
export interface BaseMeta<ComponentType> {
/**
* Title of the story which will be presented in the navigation. **Should be unique.**
*
* Stories can be organized in a nested structure using "/" as a separator.
*
* Since CSF 3.0 this property is optional.
*
* @example
* export default {
* ...
* title: 'Design System/Atoms/Button'
* }
*
* @see [Story Hierarchy](https://storybook.js.org/docs/basics/writing-stories/#story-hierarchy)
*/
title?: string;
/**
* Manually set the id of a story, which in particular is useful if you want to rename stories without breaking permalinks.
*
* Storybook will prioritize the id over the title for ID generation, if provided, and will prioritize the story.storyName over the export key for display.
*
* @see [Sidebar and URLs](https://storybook.js.org/docs/react/configure/sidebar-and-urls#permalinking-to-stories)
*/
id?: string;
/**
* The primary component for your story.
*
* Used by addons for automatic prop table generation and display of other component metadata.
*/
component?: ComponentType;
/**
* Auxiliary subcomponents that are part of the stories.
*
* Used by addons for automatic prop table generation and display of other component metadata.
*
* @example
* import { Button, ButtonGroup } from './components';
*
* export default {
* ...
* subcomponents: { Button, ButtonGroup }
* }
*
* By defining them each component will have its tab in the args table.
*/
subcomponents?: Record<string, ComponentType>;
}
export type BaseStoryObject<Args, StoryFnReturnType> = {
/**
* Override the display name in the UI
*/
storyName?: string;
};
export type BaseStoryFn<Args, StoryFnReturnType> = {
(args: Args, context: StoryContext): StoryFnReturnType;
} & BaseStoryObject<Args, StoryFnReturnType>;
export type BaseStory<Args, StoryFnReturnType> =
| BaseStoryFn<Args, StoryFnReturnType>
| BaseStoryObject<Args, StoryFnReturnType>; | the_stack |
import React, {
CSSProperties,
useCallback,
useEffect,
useMemo,
useRef,
} from 'react'
import { mdiClose } from '@mdi/js'
import cc from 'classcat'
import { ModalElement, useModal } from '../../../lib/stores/modal'
import { isActiveElementAnInput } from '../../../lib/dom'
import { useGlobalKeyDownHandler } from '../../../lib/keyboard'
import styled from '../../../lib/styled'
import Button from '../../atoms/Button'
import Scroller from '../../atoms/Scroller'
import { useWindow } from '../../../lib/stores/window'
import { OverlayScrollbarsComponent } from 'overlayscrollbars-react'
import { useEffectOnce } from 'react-use'
import { useRouter } from '../../../../cloud/lib/router'
import { useEffectOnUnmount } from '../../../../lib/hooks'
import {
ModalEventDetails,
modalEventEmitter,
} from '../../../../cloud/lib/utils/events'
const Modal = () => {
const { modals, closeLastModal } = useModal()
const keydownHandler = useMemo(() => {
return (event: KeyboardEvent) => {
if (event.key.toLowerCase() === 'escape' && !isActiveElementAnInput()) {
modalEventEmitter.dispatch({ type: `modal-${modals.length - 1}-close` })
}
}
}, [modals.length])
useGlobalKeyDownHandler(keydownHandler)
if (modals.length === 0) return null
return (
<Container
className={cc([
'modal',
modals.length === 1 && modals[0].position != null && 'modal--context',
])}
>
{modals.map((modal, i) => {
if (modal.position != null) {
return (
<ContextModalItem
key={`modal-${i}`}
modal={modal}
id={i}
closeModal={closeLastModal}
/>
)
}
return (
<ModalItem
key={`modal-${i}`}
modal={modal}
id={i}
closeModal={closeLastModal}
/>
)
})}
</Container>
)
}
const ContextModalItem = ({
closeModal,
modal,
id,
}: {
closeModal: () => void
modal: ModalElement
id: number
}) => {
const {
windowSize: { width: windowWidth, height: windowHeight },
} = useWindow()
const modalWidth = typeof modal.width === 'string' ? 400 : modal.width
const contentScrollerRef = useRef<OverlayScrollbarsComponent>(null)
const manualClosing = useRef(false)
const style: CSSProperties | undefined = useMemo(() => {
const properties: CSSProperties = {
width: modalWidth,
height: modal.height,
maxHeight:
modal.position?.alignment === 'bottom-left' ||
modal.position?.alignment === 'bottom-right' ||
modal.position?.alignment === 'right'
? windowHeight - (modal.position?.bottom || 0) - 10
: modal.maxHeight != null
? modal.maxHeight
: (modal.position?.top || 0) -
((modal.position?.bottom || 0) - (modal.position?.top || 0)) -
10,
}
if (modal.position != null) {
switch (modal.position.alignment) {
case 'bottom-right':
properties.left =
modal.position.right < windowWidth - 10
? modal.position.right - modalWidth
: windowWidth - modalWidth - 10
properties.top = modal.position.bottom + 6
break
case 'bottom-left':
properties.left =
modal.position.left + modalWidth < windowWidth - 10
? modal.position.left
: windowWidth - modalWidth - 10
properties.top = modal.position.bottom + 6
break
case 'top-left':
properties.left =
modal.position.left + modalWidth < windowWidth - 10
? modal.position.left
: windowWidth - modalWidth - 10
properties.bottom = windowHeight - modal.position.top + 10
break
case 'right':
properties.left =
modal.position.right + modalWidth < windowWidth - 10
? modal.position.right + 10
: windowWidth - modalWidth - 10
properties.top = modal.position.top
break
default:
break
}
}
if (properties.maxHeight! < 80) {
properties.minHeight = modal.minHeight != null ? modal.minHeight : 100
properties.maxHeight = 200
properties.top = undefined
properties.bottom = 6
}
return properties
}, [
modal.minHeight,
modal.position,
windowWidth,
modalWidth,
windowHeight,
modal.height,
modal.maxHeight,
])
useEffectOnce(() => {
if (contentScrollerRef.current != null) {
const instance = contentScrollerRef.current.osInstance()
if (instance != null) {
instance.scroll({ top: 0 })
}
}
})
const closing = useCallback(() => {
manualClosing.current = true
closeModal()
}, [closeModal])
const closeModalOnEscape = useCallback(
(event: CustomEvent<ModalEventDetails>) => {
if (event.detail.type !== `modal-${id}-close`) {
return
}
closing()
},
[closing, id]
)
useEffect(() => {
modalEventEmitter.listen(closeModalOnEscape)
return () => {
modalEventEmitter.unlisten(closeModalOnEscape)
}
}, [closeModalOnEscape])
useModalNavigationHistory(modal, manualClosing)
if (modal.onBlur != null) {
return (
<>
<div className='modal__window__anchor' />
<Scroller
ref={contentScrollerRef}
className={cc([
'modal__window',
`modal__window__width--${modal.width}`,
modal.position != null && `modal__window--context`,
modal.hideBackground && 'modal__window--no-bg',
modal.removePadding && 'modal__window--no-padding',
])}
style={style}
>
<div className='modal__wrapper'>
{modal.title != null && (
<h3 className='modal__title'>{modal.title}</h3>
)}
<div className='modal__content'>{modal.content}</div>
</div>
</Scroller>
</>
)
}
return (
<>
<div className='modal__window__scroller'>
<div className='modal__bg__hidden' onClick={closeModal}></div>
<div className='modal__window__anchor' />
<Scroller
ref={contentScrollerRef}
className={cc([
'modal__window',
`modal__window__width--${modal.width}`,
modal.position != null && `modal__window--context`,
modal.hideBackground && 'modal__window--no-bg',
modal.removePadding && 'modal__window--no-padding',
])}
style={style}
>
<div className='modal__wrapper'>
{modal.title != null && (
<h3 className='modal__title'>{modal.title}</h3>
)}
<div className='modal__content'>{modal.content}</div>
</div>
</Scroller>
</div>
</>
)
}
const ModalItem = ({
closeModal,
modal,
id,
}: {
closeModal: () => void
modal: ModalElement
id: number
}) => {
const contentRef = useRef<HTMLDivElement>(null)
const manualClosing = useRef(false)
const closing = useCallback(() => {
manualClosing.current = true
closeModal()
}, [closeModal])
const onScrollClickHandler: React.MouseEventHandler = useCallback(
(event) => {
if (
contentRef.current != null &&
contentRef.current.contains(event.target as Node)
) {
return
}
closing()
},
[closing]
)
const closeModalOnEscape = useCallback(
(event: CustomEvent<ModalEventDetails>) => {
if (event.detail.type !== `modal-${id}-close`) {
return
}
closing()
},
[closing, id]
)
useEffect(() => {
modalEventEmitter.listen(closeModalOnEscape)
return () => {
modalEventEmitter.unlisten(closeModalOnEscape)
}
}, [closeModalOnEscape])
useModalNavigationHistory(modal, manualClosing)
return (
<Scroller
className='modal__window__scroller'
onClick={onScrollClickHandler}
>
<div
ref={contentRef}
className={cc([
'modal__window',
`modal__window__width--${modal.width}`,
modal.hideBackground && 'modal__window--no-bg',
modal.position != null && `modal__window--context`,
modal.removePadding && 'modal__window--no-padding',
])}
>
{modal.showCloseIcon && (
<Button
variant='icon'
iconPath={mdiClose}
onClick={closing}
className='modal__window__close'
iconSize={26}
/>
)}
<div className='modal__wrapper'>
{modal.title != null && (
<h3 className='modal__title'>{modal.title}</h3>
)}
<div className='modal__content'>{modal.content}</div>
</div>
</div>
</Scroller>
)
}
function useModalNavigationHistory(
modal: ModalElement,
manualClosing: React.MutableRefObject<boolean>
) {
const { push, goBack } = useRouter()
const previousModalRef = useRef({
id: modal.id,
navigation: modal.navigation,
})
//push modal's url to history on load
useEffectOnce(() => {
if (modal.navigation == null) {
return
}
push(modal.navigation.url)
})
//on modals change ( no unmount ), triggers the navigation for the replaced modal
useEffect(() => {
if (modal.id !== previousModalRef.current.id) {
if (previousModalRef.current.navigation == null) {
previousModalRef.current = {
id: modal.id,
navigation: modal.navigation,
}
return
}
if (previousModalRef.current.navigation.fallbackUrl != null) {
push(previousModalRef.current.navigation.fallbackUrl)
} else if (goBack != null) {
goBack()
}
previousModalRef.current = { id: modal.id, navigation: modal.navigation }
}
}, [modal, push, goBack])
//on modal's closure, goes back to wanted URL
useEffectOnUnmount(() => {
if (!manualClosing.current || modal.navigation == null) {
return
}
if (modal.navigation.fallbackUrl != null) {
push(modal.navigation.fallbackUrl)
} else if (goBack != null) {
goBack()
}
})
}
export const zIndexModals = 8001
const Container = styled.div`
z-index: ${zIndexModals};
&:not(.modal--context)::before {
content: '';
z-index: ${zIndexModals + 1};
position: fixed;
height: 100vh;
width: 100vw;
top: 0;
left: 0;
background-color: #000;
opacity: 0.7;
}
.modal__window--no-bg {
background: none !important;
}
.modal__window--no-padding,
.modal__window--no-padding .modal__wrapper {
padding: 0 !important;
}
.modal__bg__hidden {
z-index: ${zIndexModals + 1};
position: fixed;
height: 100vh;
width: 100vw;
top: 0;
left: 0;
}
.modal__window__anchor {
position: relative;
z-index: ${zIndexModals + 3};
}
.modal__window__scroller {
z-index: ${zIndexModals + 2};
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
overflow-x: hidden;
overflow-y: auto;
outline: 0;
}
.modal__window--context {
border: 1px solid ${({ theme }) => theme.colors.border.main};
height: auto !important;
position: fixed !important;
margin: 0 !important;
right: 0;
left: 0;
background-color: ${({ theme }) =>
theme.colors.background.primary} !important;
}
.modal__window {
z-index: ${zIndexModals + 2};
position: relative;
width: 900px;
max-width: 96%;
background-color: ${({ theme }) => theme.colors.background.primary};
box-shadow: ${({ theme }) => theme.colors.shadow};
border-radius: 4px;
height: fit-content;
margin: 1.75rem auto;
display: block;
float: center;
&.modal__window__width--fit {
width: fit-content;
}
&.modal__window__width--small {
width: 600px;
}
&.modal__window__width--large {
width: 1100px;
}
&.modal__window__width--full {
width: 96%;
}
}
.modal__window__close {
position: absolute;
top: ${({ theme }) => theme.sizes.spaces.sm}px;
right: ${({ theme }) => theme.sizes.spaces.df}px;
white-space: nowrap;
z-index: 1;
}
.modal__wrapper {
display: flex;
margin: 0;
min-width: 0;
width: 100%;
flex-direction: column;
align-items: stretch;
padding: ${({ theme }) => theme.sizes.spaces.df}px
${({ theme }) => theme.sizes.spaces.df}px;
}
.modal__title {
flex: 0 0 auto;
margin: 0 0 ${({ theme }) => theme.sizes.spaces.md}px 0;
font-size: ${({ theme }) => theme.sizes.fonts.xl}px;
}
.modal__content {
flex: 1 1 10px;
}
`
export default React.memo(Modal) | the_stack |
* @title: Texture effects
* @description:
* This sample shows how to use advanced texture effects with the Draw2D API.
* You can select, customize and combine the following effects to be applied to the rendered texture:
* Distortion, Color Matrix, Bloom and Gaussian blur.
*/
/*{{ javascript("jslib/observer.js") }}*/
/*{{ javascript("jslib/requesthandler.js") }}*/
/*{{ javascript("jslib/utilities.js") }}*/
/*{{ javascript("jslib/services/turbulenzservices.js") }}*/
/*{{ javascript("jslib/services/turbulenzbridge.js") }}*/
/*{{ javascript("jslib/services/gamesession.js") }}*/
/*{{ javascript("jslib/services/mappingtable.js") }}*/
/*{{ javascript("jslib/shadermanager.js") }}*/
/*{{ javascript("jslib/draw2d.js") }}*/
/*{{ javascript("jslib/textureeffects.js") }}*/
/*{{ javascript("scripts/htmlcontrols.js") }}*/
/*global TurbulenzEngine: true */
/*global TurbulenzServices: false */
/*global RequestHandler: false */
/*global Draw2D: false */
/*global Draw2DSprite: false */
/*global TextureEffects: false */
/*global HTMLControls: false */
TurbulenzEngine.onload = function onloadFn()
{
//==========================================================================
// HTML Controls
//==========================================================================
var htmlControls;
var distort = false;
var strength = 10; //px
var rotation = 0; //radian
var scale = 1; // factor.
var colormatrix = false;
var saturation = 1; // factor.
var hue = 0; //radian
var brightness = 0; // normalised offset.
var contrast = 1; // factor
var additiveRGB = [0, 0, 0];
var grayscale = false;
var sepia = false;
var negative = false;
var bloom = false;
var bloomRadius = 20;
var bloomThreshold = 0.65;
var bloomIntensity = 1.2;
var bloomSaturation = 1.2;
var originalIntensity = 1.0;
var originalSaturation = 1.0;
var thresholdCutoff = 3;
var gausblur = false;
var gausBlurRadius = 10;
//==========================================================================
// Turbulenz Initialization
//==========================================================================
var graphicsDevice = TurbulenzEngine.createGraphicsDevice({});
var mathDevice = TurbulenzEngine.createMathDevice({});
var requestHandler = RequestHandler.create({});
var loadedResources = 0;
// Textures to load:
var distortionTextureName = "textures/texfxdisplace.png";
var backgroundTextureName = "textures/texfxbg.png";
var textureNames = [distortionTextureName, backgroundTextureName];
// List to store Texture objects.
var textures = {};
var numResources = textureNames.length;
function mappingTableReceived(mappingTable)
{
function textureParams(src)
{
return {
src : mappingTable.getURL(src),
mipmaps : true,
onload : function (texture)
{
if (texture)
{
textures[src] = texture;
loadedResources += 1;
}
}
};
}
var i;
for (i = 0; i < textureNames.length; i += 1)
{
graphicsDevice.createTexture(textureParams(textureNames[i]));
}
}
var gameSession;
function sessionCreated()
{
TurbulenzServices.createMappingTable(
requestHandler,
gameSession,
mappingTableReceived
);
}
gameSession = TurbulenzServices.createGameSession(requestHandler, sessionCreated);
//==========================================================================
// Draw2D and TextureEffects initialization
//==========================================================================
var clearColor = mathDevice.v4Build(0, 0, 0, 1);
var draw2D = Draw2D.create({
graphicsDevice : graphicsDevice
});
var effects = TextureEffects.create({
graphicsDevice : graphicsDevice,
mathDevice : mathDevice
});
// Create render targets used for effects rendering.
var renderTargetFullScreen1 = draw2D.createRenderTarget({});
var renderTargetFullScreen2 = draw2D.createRenderTarget({});
var renderTargetFullScreen3 = draw2D.createRenderTarget({});
var renderTarget256A = draw2D.createRenderTarget({ width : 256, height : 256 });
var renderTarget256B = draw2D.createRenderTarget({ width : 256, height : 256 });
// Distortion effect.
// ------------------
var distortEffectParam = {
transform : [1, 0, 0, 1, 0, 0],
source: null,
destination: null,
strength: 0,
distortion: <Texture>null
};
function applyDistort(src, dest)
{
var param = distortEffectParam;
param.source = src;
param.destination = dest;
param.strength = strength;
var xform = param.transform;
// We invert rotation and scale as this transformation
// occurs in texture lookup to distortion texture.
// so to scale by 200% we have to scale texture lookups by 50%.
var cos = Math.cos(rotation) / scale;
var sin = - Math.sin(rotation) / scale;
// Determine additional scaling to fit distortion texture to
// section of back buffer / render target in use.
var w = src.width / graphicsDevice.width;
var h = src.height / graphicsDevice.height;
xform[0] = cos * w;
xform[1] = sin * w;
xform[2] = -sin * h;
xform[3] = cos * h;
xform[4] = 0.5 * (1 - cos + sin);
xform[5] = 0.5 * (1 - cos - sin);
effects.applyDistort(param);
}
// ColorMatrix effect.
// -------------------
var tmpMatrix = mathDevice.m43BuildIdentity();
var colorMatrixEffectParam = {
colorMatrix : mathDevice.m43BuildIdentity(),
source: null,
destination: null
};
function applyColorMatrix(src, dest)
{
var param = colorMatrixEffectParam;
var xform = param.colorMatrix;
var tmp = tmpMatrix;
param.source = src;
param.destination = dest;
mathDevice.m43BuildIdentity(xform);
if (saturation !== 1)
{
effects.saturationMatrix(saturation, tmp);
mathDevice.m43Mul(xform, tmp, xform);
}
if ((hue % (Math.PI * 2)) !== 0)
{
effects.hueMatrix(hue, tmp);
mathDevice.m43Mul(xform, tmp, xform);
}
if (contrast !== 1)
{
effects.contrastMatrix(contrast, tmp);
mathDevice.m43Mul(xform, tmp, xform);
}
if (brightness !== 0)
{
effects.brightnessMatrix(brightness, tmp);
mathDevice.m43Mul(xform, tmp, xform);
}
if (additiveRGB[0] !== 0 ||
additiveRGB[1] !== 0 ||
additiveRGB[2] !== 0)
{
effects.additiveMatrix(additiveRGB, tmp);
mathDevice.m43Mul(xform, tmp, xform);
}
if (grayscale)
{
effects.grayScaleMatrix(tmp);
mathDevice.m43Mul(xform, tmp, xform);
}
if (negative)
{
effects.negativeMatrix(tmp);
mathDevice.m43Mul(xform, tmp, xform);
}
if (sepia)
{
effects.sepiaMatrix(tmp);
mathDevice.m43Mul(xform, tmp, xform);
}
effects.applyColorMatrix(param);
}
// Bloom effect.
// -------------
var bloomEffectParam = {
source: null,
destination: null,
blurRadius: 0,
bloomThreshold: 0,
bloomIntensity: 0,
bloomSaturation: 0,
originalIntensity: 0,
originalSaturation: 0,
thresholdCutoff: 0,
blurTarget1: <RenderTarget>null,
blurTarget2: <RenderTarget>null
};
function applyBloom(src, dest)
{
var param = bloomEffectParam;
param.source = src;
param.destination = dest;
param.blurRadius = bloomRadius;
param.bloomThreshold = bloomThreshold;
param.bloomIntensity = bloomIntensity;
param.bloomSaturation = bloomSaturation;
param.originalIntensity = originalIntensity;
param.originalSaturation = originalSaturation;
param.thresholdCutoff = thresholdCutoff;
// Strictly speaking as these are non-dynamic render targets,
// we can be sure the render target is not going to change
// instead of accessing it each time.
param.blurTarget1 = draw2D.getRenderTarget(renderTarget256A);
param.blurTarget2 = draw2D.getRenderTarget(renderTarget256B);
effects.applyBloom(param);
}
// GaussianBlur effect.
// --------------------
var gausBlurEffectParam = {
source: null,
destination: null,
blurRadius: 0,
blurTarget: <RenderTarget>null
};
function applyGausBlur(src, dest)
{
var param = gausBlurEffectParam;
param.source = src;
param.destination = dest;
param.blurRadius = gausBlurRadius;
param.blurTarget = draw2D.getRenderTarget(renderTargetFullScreen3);
effects.applyGaussianBlur(param);
}
// List of active effect applicators.
var effElement = document.getElementById("effectInfo");
var activeEffects = [];
function invalidateEffects()
{
var names = [];
var i;
for (i = 0; i < activeEffects.length; i += 1)
{
names[i] = activeEffects[i].name;
}
effElement.innerHTML = names.toString();
}
//==========================================================================
// Main loop.
//==========================================================================
var fpsElement = document.getElementById("fpscounter");
var lastFPS = "";
var nextUpdate = 0;
function displayPerformance()
{
var currentTime = TurbulenzEngine.time;
if (currentTime > nextUpdate)
{
nextUpdate = (currentTime + 0.1);
var fpsText = (graphicsDevice.fps).toFixed(2);
if (lastFPS !== fpsText)
{
lastFPS = fpsText;
fpsElement.innerHTML = fpsText + " fps";
}
}
}
var backgroundSprite = null;
var distortionSprite = null;
function mainLoop()
{
if (!graphicsDevice.beginFrame())
{
return;
}
// If no effects applied, render directly to back buffer.
if (activeEffects.length === 0)
{
draw2D.setBackBuffer();
}
else
{
draw2D.setRenderTarget(renderTargetFullScreen1);
}
draw2D.clear(clearColor);
draw2D.begin();
backgroundSprite.setWidth(graphicsDevice.width);
backgroundSprite.setHeight(graphicsDevice.height);
draw2D.drawSprite(backgroundSprite);
draw2D.end();
// Apply effects!
var src = renderTargetFullScreen1;
var dest = renderTargetFullScreen2;
var i;
for (i = 0; i < activeEffects.length; i += 1)
{
activeEffects[i].applyEffect(
draw2D.getRenderTargetTexture(src),
draw2D.getRenderTarget(dest)
);
var tmp = src;
src = dest;
dest = tmp;
}
// If we have effects applied, copy to back buffer.
if (activeEffects.length !== 0)
{
draw2D.setBackBuffer();
draw2D.copyRenderTarget(src);
}
// Render distortion texture at end to display what it looks like.
if (distort)
{
draw2D.begin();
draw2D.drawSprite(distortionSprite);
draw2D.end();
}
graphicsDevice.endFrame();
if (fpsElement)
{
displayPerformance();
}
}
var intervalID;
function loadingLoop()
{
if (loadedResources === numResources)
{
// Set distortion texture, create background sprite.
distortEffectParam.distortion = textures[distortionTextureName];
backgroundSprite = Draw2DSprite.create({
texture : textures[backgroundTextureName],
origin : [0, 0]
});
distortionSprite = Draw2DSprite.create({
texture : distortEffectParam.distortion,
origin : [0, 0],
width : 128,
height : 128
});
TurbulenzEngine.clearInterval(intervalID);
intervalID = TurbulenzEngine.setInterval(mainLoop, 1000 / 60);
}
}
intervalID = TurbulenzEngine.setInterval(loadingLoop, 100);
//==========================================================================
function loadHtmlControls()
{
var distortEffect = {
applyEffect : applyDistort,
name : "distort"
};
var colorMatrixEffect = {
applyEffect : applyColorMatrix,
name : "colorMatrix"
};
var gausBlurEffect = {
applyEffect : applyGausBlur,
name : "gaussianBlur"
};
var bloomEffect = {
applyEffect : applyBloom,
name : "bloom"
};
htmlControls = HTMLControls.create();
htmlControls.addCheckboxControl({
id: "distortBox",
value: "distort",
isSelected: distort,
fn: function ()
{
distort = !distort;
if (distort)
{
activeEffects.push(distortEffect);
}
else
{
activeEffects.splice(activeEffects.indexOf(distortEffect), 1);
}
invalidateEffects();
return distort;
}
});
htmlControls.addSliderControl({
id: "strengthSlider",
value: strength,
max: 100,
min: -100,
step: 1,
fn: function ()
{
strength = this.value;
htmlControls.updateSlider("strengthSlider", strength);
}
});
htmlControls.addSliderControl({
id: "rotationSlider",
value: Math.round(rotation * 180 / Math.PI),
max: 360,
min: 0,
step: 1,
fn: function ()
{
rotation = this.value * Math.PI / 180;
htmlControls.updateSlider("rotationSlider", Math.round(rotation * 180 / Math.PI));
}
});
htmlControls.addSliderControl({
id: "scaleSlider",
value: (scale * 100),
max: 300,
min: -300,
step: 1,
fn: function ()
{
scale = this.value / 100;
htmlControls.updateSlider("scaleSlider", scale * 100);
}
});
htmlControls.addCheckboxControl({
id: "colorMatrixBox",
value: "colormatrix",
isSelected: colormatrix,
fn: function ()
{
colormatrix = !colormatrix;
if (colormatrix)
{
activeEffects.push(colorMatrixEffect);
}
else
{
activeEffects.splice(activeEffects.indexOf(colorMatrixEffect), 1);
}
invalidateEffects();
return colormatrix;
}
});
htmlControls.addSliderControl({
id: "saturationSlider",
value: (saturation * 100),
max: 200,
min: -200,
step: 1,
fn: function ()
{
saturation = this.value / 100;
htmlControls.updateSlider("saturationSlider", saturation * 100);
}
});
htmlControls.addSliderControl({
id: "hueSlider",
value: Math.round(hue * 180 / Math.PI),
max: 360,
min: 0,
step: 1,
fn: function ()
{
hue = this.value * Math.PI / 180;
htmlControls.updateSlider("hueSlider", Math.round(hue * 180 / Math.PI));
}
});
htmlControls.addSliderControl({
id: "brightnessSlider",
value: brightness,
max: 1,
min: -1,
step: 0.01,
fn: function ()
{
brightness = this.value;
htmlControls.updateSlider("brightnessSlider", brightness);
}
});
htmlControls.addSliderControl({
id: "additiveRedSlider",
value: additiveRGB[0],
max: 1,
min: -1,
step: 0.01,
fn: function ()
{
additiveRGB[0] = this.value;
htmlControls.updateSlider("additiveRedSlider", additiveRGB[0]);
}
});
htmlControls.addSliderControl({
id: "additiveGreenSlider",
value: additiveRGB[1],
max: 1,
min: -1,
step: 0.01,
fn: function ()
{
additiveRGB[1] = this.value;
htmlControls.updateSlider("additiveGreenSlider", additiveRGB[1]);
}
});
htmlControls.addSliderControl({
id: "additiveBlueSlider",
value: additiveRGB[1],
max: 1,
min: -1,
step: 0.01,
fn: function ()
{
additiveRGB[2] = this.value;
htmlControls.updateSlider("additiveBlueSlider", additiveRGB[2]);
}
});
htmlControls.addSliderControl({
id: "contrastSlider",
value: (contrast * 100),
max: 200,
min: 0,
step: 1,
fn: function ()
{
contrast = this.value / 100;
htmlControls.updateSlider("contrastSlider", contrast * 100);
}
});
htmlControls.addCheckboxControl({
id: "grayscaleBox",
value: "grayscale",
isSelected: grayscale,
fn: function ()
{
grayscale = !grayscale;
return grayscale;
}
});
htmlControls.addCheckboxControl({
id: "negativeBox",
value: "negative",
isSelected: negative,
fn: function ()
{
negative = !negative;
return negative;
}
});
htmlControls.addCheckboxControl({
id: "sepiaBox",
value: "sepia",
isSelected: sepia,
fn: function ()
{
sepia = !sepia;
return sepia;
}
});
htmlControls.addCheckboxControl({
id: "bloomBox",
value: "bloom",
isSelected: bloom,
fn: function ()
{
bloom = !bloom;
if (bloom)
{
activeEffects.push(bloomEffect);
}
else
{
activeEffects.splice(activeEffects.indexOf(bloomEffect), 1);
}
invalidateEffects();
return bloom;
}
});
htmlControls.addSliderControl({
id: "bloomRadiusSlider",
value: bloomRadius,
max: 50,
min: 0,
step: 0.5,
fn: function ()
{
bloomRadius = this.value;
htmlControls.updateSlider("bloomRadiusSlider", bloomRadius);
}
});
htmlControls.addSliderControl({
id: "bloomThresholdSlider",
value: bloomThreshold,
max: 1,
min: 0,
step: 0.01,
fn: function ()
{
bloomThreshold = this.value;
htmlControls.updateSlider("bloomThresholdSlider", bloomThreshold);
}
});
htmlControls.addSliderControl({
id: "bloomThresholdCutoffSlider",
value: thresholdCutoff,
max: 6,
min: -3,
step: 0.25,
fn: function ()
{
thresholdCutoff = this.value;
htmlControls.updateSlider("bloomThresholdCutoffSlider", thresholdCutoff);
}
});
htmlControls.addSliderControl({
id: "bloomIntensitySlider",
value: bloomIntensity,
max: 2,
min: 0,
step: 0.02,
fn: function ()
{
bloomIntensity = this.value;
htmlControls.updateSlider("bloomIntensitySlider", bloomIntensity);
}
});
htmlControls.addSliderControl({
id: "bloomSaturationSlider",
value: bloomSaturation,
max: 2,
min: -2,
step: 0.04,
fn: function ()
{
bloomSaturation = this.value;
htmlControls.updateSlider("bloomSaturationSlider", bloomSaturation);
}
});
htmlControls.addSliderControl({
id: "originalIntensitySlider",
value: originalIntensity,
max: 2,
min: 0,
step: 0.02,
fn: function ()
{
originalIntensity = this.value;
htmlControls.updateSlider("originalIntensitySlider", originalIntensity);
}
});
htmlControls.addSliderControl({
id: "originalSaturationSlider",
value: originalSaturation,
max: 2,
min: -2,
step: 0.04,
fn: function ()
{
originalSaturation = this.value;
htmlControls.updateSlider("originalSaturationSlider", originalSaturation);
}
});
htmlControls.addCheckboxControl({
id: "gausBlurBox",
value: "gausblur",
isSelected: gausblur,
fn: function ()
{
gausblur = !gausblur;
if (gausblur)
{
activeEffects.push(gausBlurEffect);
}
else
{
activeEffects.splice(activeEffects.indexOf(gausBlurEffect), 1);
}
invalidateEffects();
return gausblur;
}
});
htmlControls.addSliderControl({
id: "gausBlurRadiusSlider",
value: gausBlurRadius,
max: 50,
min: 0,
step: 0.5,
fn: function ()
{
gausBlurRadius = this.value;
htmlControls.updateSlider("gausBlurRadiusSlider", gausBlurRadius);
}
});
htmlControls.register();
}
loadHtmlControls();
// Create a scene destroy callback to run when the window is closed
TurbulenzEngine.onunload = function destroyScene()
{
if (intervalID)
{
TurbulenzEngine.clearInterval(intervalID);
}
if (gameSession)
{
gameSession.destroy();
gameSession = null;
}
};
}; | the_stack |
export function CortoDecoder(data, byteOffset?, byteLength?) {
if (byteOffset & 0x3) throw "Memory aligned on 4 bytes is mandatory";
var t = this;
var stream = t.stream = new Stream(data, byteOffset, byteLength);
var magic = stream.readInt();
if (magic != 2021286656) return;
var version = stream.readInt();
t.entropy = stream.readUChar(); //exif
t.geometry = {};
var n = stream.readInt();
for (var i = 0; i < n; i++) {
var key = stream.readString();
t.geometry[key] = stream.readString();
} //attributes
var n = stream.readInt();
t.attributes = {};
for (var i = 0; i < n; i++) {
var a = {};
var name = stream.readString();
var codec = stream.readInt();
var q = stream.readFloat();
var components = stream.readUChar(); //internal number of components
var type = stream.readUChar(); //default type (same as it was in input), can be overridden
var strategy = stream.readUChar();
var attr;
switch (codec) {
case 2:
attr = NormalAttr;
break;
case 3:
attr = ColorAttr;
break;
case 1: //generic codec
default:
attr = Attribute;
break;
}
t.attributes[name] = new attr(name, q, components, type, strategy);
} //TODO move this vars into an array.
t.geometry.nvert = t.nvert = t.stream.readInt();
t.geometry.nface = t.nface = t.stream.readInt();
}
onmessage = function (job) {
if (typeof job.data == "string") return;
var buffer = job.data.buffer;
if (!buffer) return;
var decoder = new CortoDecoder(buffer);
if (decoder.attributes.normal && job.data.short_normals) decoder.attributes.normal.type = 3;
if (decoder.attributes.color && job.data.rgba_colors) decoder.attributes.color.outcomponents = 4;
var model = decoder.decode(); //pass back job
postMessage({
model: model,
buffer: buffer,
request: job.data.request
}, "*");
};
CortoDecoder.prototype = {
decode: function () {
var t = this;
t.last = new Uint32Array(t.nvert * 3); //for parallelogram prediction
t.last_count = 0;
for (var i in t.attributes) t.attributes[i].init(t.nvert, t.nface);
if (t.nface == 0) t.decodePointCloud();else t.decodeMesh();
return t.geometry;
},
decodePointCloud: function () {
var t = this;
t.index = new IndexAttr(t.nvert, t.nface, 0);
t.index.decodeGroups(t.stream);
t.geometry.groups = t.index.groups;
for (var i in t.attributes) {
var a = t.attributes[i];
a.decode(t.nvert, t.stream);
a.deltaDecode(t.nvert);
a.dequantize(t.nvert);
t.geometry[a.name] = a.buffer;
}
},
decodeMesh: function () {
var t = this;
t.index = new IndexAttr(t.nvert, t.nface);
t.index.decodeGroups(t.stream);
t.index.decode(t.stream);
t.vertex_count = 0;
var start = 0;
t.cler = 0;
for (var p = 0; p < t.index.groups.length; p++) {
var end = t.index.groups[p].end;
this.decodeFaces(start * 3, end * 3);
start = end;
}
t.geometry['index'] = t.index.faces;
t.geometry.groups = t.index.groups;
for (var i in t.attributes) t.attributes[i].decode(t.nvert, t.stream);
for (var i in t.attributes) t.attributes[i].deltaDecode(t.nvert, t.index.prediction);
for (var i in t.attributes) t.attributes[i].postDelta(t.nvert, t.nface, t.attributes, t.index);
for (var i in t.attributes) {
var a = t.attributes[i];
a.dequantize(t.nvert);
t.geometry[a.name] = a.buffer;
}
},
/* an edge is: uint16_t face, uint16_t side, uint32_t prev, next, bool deleted
I do not want to create millions of small objects, I will use aUint32Array.
Problem is how long, sqrt(nface) we will over blow using nface.
*/
ilog2: function (p) {
var k = 0;
while (p >>= 1) {
++k;
}
return k;
},
decodeFaces: function (start, end) {
var t = this;
var clers = t.index.clers;
var bitstream = t.index.bitstream;
var front = t.index.front;
var front_count = 0; //count each integer so it's front_back*5
function addFront(_v0, _v1, _v2, _prev, _next) {
front[front_count] = _v0;
front[front_count + 1] = _v1;
front[front_count + 2] = _v2;
front[front_count + 3] = _prev;
front[front_count + 4] = _next;
front_count += 5;
}
var faceorder = new Uint32Array(end - start);
var order_front = 0;
var order_back = 0;
var delayed = [];
var splitbits = t.ilog2(t.nvert) + 1;
var new_edge = -1;
var prediction = t.index.prediction;
while (start < end) {
if (new_edge == -1 && order_front >= order_back && !delayed.length) {
var last_index = t.vertex_count - 1;
var vindex = [];
var split = 0;
if (clers[t.cler++] == 6) {
//split look ahead
split = bitstream.read(3);
}
for (var k = 0; k < 3; k++) {
var v;
if (split & 1 << k) v = bitstream.read(splitbits);else {
prediction[t.vertex_count * 3] = prediction[t.vertex_count * 3 + 1] = prediction[t.vertex_count * 3 + 2] = last_index;
last_index = v = t.vertex_count++;
}
vindex[k] = v;
t.index.faces[start++] = v;
}
var current_edge = front_count;
faceorder[order_back++] = front_count;
addFront(vindex[1], vindex[2], vindex[0], current_edge + 2 * 5, current_edge + 1 * 5);
faceorder[order_back++] = front_count;
addFront(vindex[2], vindex[0], vindex[1], current_edge + 0 * 5, current_edge + 2 * 5);
faceorder[order_back++] = front_count;
addFront(vindex[0], vindex[1], vindex[2], current_edge + 1 * 5, current_edge + 0 * 5);
continue;
}
var edge;
if (new_edge != -1) {
edge = new_edge;
new_edge = -1;
} else if (order_front < order_back) {
edge = faceorder[order_front++];
} else {
edge = delayed.pop();
}
if (typeof edge == "undefined") throw "aarrhhj";
if (front[edge] < 0) continue; //deleted
var c = clers[t.cler++];
if (c == 4) continue; //BOUNDARY
var v0 = front[edge + 0];
var v1 = front[edge + 1];
var v2 = front[edge + 2];
var prev = front[edge + 3];
var next = front[edge + 4];
new_edge = front_count; //points to new edge to be inserted
var opposite = -1;
if (c == 0 || c == 6) {
//VERTEX
if (c == 6) {
//split
opposite = bitstream.read(splitbits);
} else {
prediction[t.vertex_count * 3] = v1;
prediction[t.vertex_count * 3 + 1] = v0;
prediction[t.vertex_count * 3 + 2] = v2;
opposite = t.vertex_count++;
}
front[prev + 4] = new_edge;
front[next + 3] = new_edge + 5;
front[front_count] = v0;
front[front_count + 1] = opposite;
front[front_count + 2] = v1;
front[front_count + 3] = prev;
front[front_count + 4] = new_edge + 5;
front_count += 5;
faceorder[order_back++] = front_count;
front[front_count] = opposite;
front[front_count + 1] = v1;
front[front_count + 2] = v0;
front[front_count + 3] = new_edge;
front[front_count + 4] = next;
front_count += 5;
} else if (c == 1) {
//LEFT
front[front[prev + 3] + 4] = new_edge;
front[next + 3] = new_edge;
opposite = front[prev];
front[front_count] = opposite;
front[front_count + 1] = v1;
front[front_count + 2] = v0;
front[front_count + 3] = front[prev + 3];
front[front_count + 4] = next;
front_count += 5;
front[prev] = -1; //deleted
} else if (c == 2) {
//RIGHT
front[front[next + 4] + 3] = new_edge;
front[prev + 4] = new_edge;
opposite = front[next + 1];
front[front_count] = v0;
front[front_count + 1] = opposite;
front[front_count + 2] = v1;
front[front_count + 3] = prev;
front[front_count + 4] = front[next + 4];
front_count += 5;
front[next] = -1;
} else if (c == 5) {
//DELAY
delayed.push(edge);
new_edge = -1;
continue;
} else if (c == 3) {
//END
front[front[prev + 3] + 4] = front[next + 4];
front[front[next + 4] + 3] = front[prev + 3];
opposite = front[prev];
front[prev] = -1;
front[next] = -1;
new_edge = -1;
} else {
throw "INVALID CLER!";
}
if (v1 >= t.nvert || v0 >= t.nvert || opposite >= t.nvert) throw "Topological error";
t.index.faces[start] = v1;
t.index.faces[start + 1] = v0;
t.index.faces[start + 2] = opposite;
start += 3;
}
}
};
/*
Corto
Copyright (c) 2017-2020, Visual Computing Lab, ISTI - CNR
All rights reserved.
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.
*/
function Attribute(name, q, components, type, strategy) {
var t = this;
t.name = name;
t.q = q; //float
t.components = components; //integer
t.type = type;
t.strategy = strategy;
}
Attribute.prototype = {
Type: {
UINT32: 0,
INT32: 1,
UINT16: 2,
INT16: 3,
UINT8: 4,
INT8: 5,
FLOAT: 6,
DOUBLE: 7
},
Strategy: {
PARALLEL: 1,
CORRELATED: 2
},
init: function (nvert, nface) {
var t = this;
var n = nvert * t.components;
t.values = new Int32Array(n); //local workspace
//init output buffers
switch (t.type) {
case t.Type.UINT32:
case t.Type.INT32:
t.values = t.buffer = new Int32Array(n);
break;
//no point replicating.
case t.Type.UINT16:
case t.Type.INT16:
t.buffer = new Int16Array(n);
break;
case t.Type.UINT8:
t.buffer = new Uint8Array(n);
break;
case t.Type.INT8:
t.buffer = new Int8Array(n);
break;
case t.Type.FLOAT:
case t.Type.DOUBLE:
t.buffer = new Float32Array(n);
break;
default:
throw "Error if reading";
}
},
decode: function (nvert, stream) {
var t = this;
if (t.strategy & t.Strategy.CORRELATED) //correlated
stream.decodeArray(t.components, t.values);else stream.decodeValues(t.components, t.values);
},
deltaDecode: function (nvert, context) {
var t = this;
var values = t.values;
var N = t.components;
if (t.strategy & t.Strategy.PARALLEL) {
//parallel
var n = context.length / 3;
for (var i = 1; i < n; i++) {
for (var c = 0; c < N; c++) {
values[i * N + c] += values[context[i * 3] * N + c] + values[context[i * 3 + 1] * N + c] - values[context[i * 3 + 2] * N + c];
}
}
} else if (context) {
var n = context.length / 3;
for (var i = 1; i < n; i++) for (var c = 0; c < N; c++) values[i * N + c] += values[context[i * 3] * N + c];
} else {
for (i = N; i < nvert * N; i++) values[i] += values[i - N];
}
},
postDelta: function () {},
dequantize: function (nvert) {
var t = this;
var n = t.components * nvert;
switch (t.type) {
case t.Type.UINT32:
case t.Type.INT32:
break;
case t.Type.UINT16:
case t.Type.INT16:
case t.Type.UINT8:
case t.Type.INT8:
for (var i = 0; i < n; i++) t.buffer[i] = t.values[i] * t.q;
break;
case t.Type.FLOAT:
case t.Type.DOUBLE:
for (var i = 0; i < n; i++) t.buffer[i] = t.values[i] * t.q;
break;
}
}
};
/* COLOR ATTRIBUTE */
function ColorAttr(name, q, components, type, strategy) {
Attribute.call(this, name, q, components, type, strategy);
this.qc = [];
this.outcomponents = 3;
}
ColorAttr.prototype = Object.create(Attribute.prototype);
ColorAttr.prototype.decode = function (nvert, stream) {
for (var c = 0; c < 4; c++) this.qc[c] = stream.readUChar();
Attribute.prototype.decode.call(this, nvert, stream);
};
ColorAttr.prototype.dequantize = function (nvert) {
var t = this;
for (var i = 0; i < nvert; i++) {
var offset = i * 4;
var rgboff = i * t.outcomponents;
var e0 = t.values[offset + 0];
var e1 = t.values[offset + 1];
var e2 = t.values[offset + 2];
t.buffer[rgboff + 0] = (e2 + e0) * t.qc[0] & 0xff;
t.buffer[rgboff + 1] = e0 * t.qc[1];
t.buffer[rgboff + 2] = (e1 + e0) * t.qc[2] & 0xff; // t.buffer[offset + 3] = t.values[offset + 3] * t.qc[3];
}
};
/* NORMAL ATTRIBUTE */
function NormalAttr(name, q, components, type, strategy) {
Attribute.call(this, name, q, components, type, strategy);
}
NormalAttr.prototype = Object.create(Attribute.prototype);
NormalAttr.prototype.Prediction = {
DIFF: 0,
ESTIMATED: 1,
BORDER: 2
};
NormalAttr.prototype.init = function (nvert, nface) {
var t = this;
var n = nvert * t.components;
t.values = new Int32Array(2 * nvert); //local workspace
//init output buffers
switch (t.type) {
case t.Type.INT16:
t.buffer = new Int16Array(n);
break;
case t.Type.FLOAT:
case t.Type.DOUBLE:
t.buffer = new Float32Array(n);
break;
default:
throw "Error if reading";
}
};
NormalAttr.prototype.decode = function (nvert, stream) {
var t = this;
t.prediction = stream.readUChar();
stream.decodeArray(2, t.values);
};
NormalAttr.prototype.deltaDecode = function (nvert, context) {
var t = this;
if (t.prediction != t.Prediction.DIFF) return;
if (context) {
for (var i = 1; i < nvert; i++) {
for (var c = 0; c < 2; c++) {
var d = t.values[i * 2 + c];
t.values[i * 2 + c] += t.values[context[i * 3] * 2 + c];
}
}
} else {
//point clouds assuming values are already sorted by proximity.
for (var i = 2; i < nvert * 2; i++) {
var d = t.values[i];
t.values[i] += t.values[i - 2];
}
}
};
NormalAttr.prototype.postDelta = function (nvert, nface, attrs, index) {
var t = this; //for border and estimate we need the position already deltadecoded but before dequantized
if (t.prediction == t.Prediction.DIFF) return;
if (!attrs.position) throw "No position attribute found. Use DIFF normal strategy instead.";
var coord = attrs.position;
t.estimated = new Float32Array(nvert * 3);
t.estimateNormals(nvert, coord.values, nface, index.faces);
if (t.prediction == t.Prediction.BORDER) {
t.boundary = new Uint32Array(nvert);
t.markBoundary(nvert, nface, index.faces, t.boundary);
}
t.computeNormals(nvert);
};
NormalAttr.prototype.dequantize = function (nvert) {
var t = this;
if (t.prediction != t.Prediction.DIFF) return;
for (var i = 0; i < nvert; i++) t.toSphere(i, t.values, i, t.buffer, t.q);
};
NormalAttr.prototype.computeNormals = function (nvert) {
var t = this;
var norm = t.estimated;
if (t.prediction == t.Prediction.ESTIMATED) {
for (var i = 0; i < nvert; i++) {
t.toOcta(i, norm, i, t.values, t.q);
t.toSphere(i, t.values, i, t.buffer, t.q);
}
} else {
//BORDER
var count = 0; //here for the border.
for (var i = 0, k = 0; i < nvert; i++, k += 3) {
if (t.boundary[i] != 0) {
t.toOcta(i, norm, count, t.values, t.q);
t.toSphere(count, t.values, i, t.buffer, t.q);
count++;
} else {
//no correction
var len = 1 / Math.sqrt(norm[k] * norm[k] + norm[k + 1] * norm[k + 1] + norm[k + 2] * norm[k + 2]);
if (t.type == t.Type.INT16) len *= 32767;
t.buffer[k] = norm[k] * len;
t.buffer[k + 1] = norm[k + 1] * len;
t.buffer[k + 2] = norm[k + 2] * len;
}
}
}
};
NormalAttr.prototype.markBoundary = function (nvert, nface, index, boundary) {
for (var f = 0; f < nface * 3; f += 3) {
boundary[index[f + 0]] ^= index[f + 1] ^ index[f + 2];
boundary[index[f + 1]] ^= index[f + 2] ^ index[f + 0];
boundary[index[f + 2]] ^= index[f + 0] ^ index[f + 1];
}
};
NormalAttr.prototype.estimateNormals = function (nvert, coords, nface, index) {
var t = this;
for (var f = 0; f < nface * 3; f += 3) {
var a = 3 * index[f + 0];
var b = 3 * index[f + 1];
var c = 3 * index[f + 2];
var ba0 = coords[b + 0] - coords[a + 0];
var ba1 = coords[b + 1] - coords[a + 1];
var ba2 = coords[b + 2] - coords[a + 2];
var ca0 = coords[c + 0] - coords[a + 0];
var ca1 = coords[c + 1] - coords[a + 1];
var ca2 = coords[c + 2] - coords[a + 2];
var n0 = ba1 * ca2 - ba2 * ca1;
var n1 = ba2 * ca0 - ba0 * ca2;
var n2 = ba0 * ca1 - ba1 * ca0;
t.estimated[a + 0] += n0;
t.estimated[a + 1] += n1;
t.estimated[a + 2] += n2;
t.estimated[b + 0] += n0;
t.estimated[b + 1] += n1;
t.estimated[b + 2] += n2;
t.estimated[c + 0] += n0;
t.estimated[c + 1] += n1;
t.estimated[c + 2] += n2;
}
}; //taks input in ingress at i offset, adds out at c offset
NormalAttr.prototype.toSphere = function (i, input, o, out, unit) {
var t = this;
var j = i * 2;
var k = o * 3;
var av0 = input[j] > 0 ? input[j] : -input[j];
var av1 = input[j + 1] > 0 ? input[j + 1] : -input[j + 1];
out[k] = input[j];
out[k + 1] = input[j + 1];
out[k + 2] = unit - av0 - av1;
if (out[k + 2] < 0) {
out[k] = input[j] > 0 ? unit - av1 : av1 - unit;
out[k + 1] = input[j + 1] > 0 ? unit - av0 : av0 - unit;
}
var len = 1 / Math.sqrt(out[k] * out[k] + out[k + 1] * out[k + 1] + out[k + 2] * out[k + 2]);
if (t.type == t.Type.INT16) len *= 32767;
out[k] *= len;
out[k + 1] *= len;
out[k + 2] *= len;
};
NormalAttr.prototype.toOcta = function (i, input, o, output, unit) {
var k = o * 2;
var j = i * 3; //input
var av0 = input[j] > 0 ? input[j] : -input[j];
var av1 = input[j + 1] > 0 ? input[j + 1] : -input[j + 1];
var av2 = input[j + 2] > 0 ? input[j + 2] : -input[j + 2];
var len = av0 + av1 + av2;
var p0 = input[j] / len;
var p1 = input[j + 1] / len;
var ap0 = p0 > 0 ? p0 : -p0;
var ap1 = p1 > 0 ? p1 : -p1;
if (input[j + 2] < 0) {
p0 = input[j] >= 0 ? 1.0 - ap1 : ap1 - 1;
p1 = input[j + 1] >= 0 ? 1.0 - ap0 : ap0 - 1;
}
output[k] += p0 * unit;
output[k + 1] += p1 * unit;
/*
Point2f p(v[0], v[1]);
p /= (fabs(v[0]) + fabs(v[1]) + fabs(v[2]));
if(v[2] < 0) {
p = Point2f(1.0f - fabs(p[1]), 1.0f - fabs(p[0]));
if(v[0] < 0) p[0] = -p[0];
if(v[1] < 0) p[1] = -p[1];
}
return Point2i(p[0]*unit, p[1]*unit); */
};
/* INDEX ATTRIBUTE */
function IndexAttr(nvert, nface, type?) {
var t = this;
if (!type && nface < 1 << 16 || type == 0) //uint16
t.faces = new Uint16Array(nface * 3);else if (!type || type == 2) //uint32
t.faces = new Uint32Array(nface * 3);else throw "Unsupported type";
t.prediction = new Uint32Array(nvert * 3);
}
IndexAttr.prototype = {
decode: function (stream) {
var t = this;
var max_front = stream.readInt();
t.front = new Int32Array(max_front * 5);
var tunstall = new Tunstall();
t.clers = tunstall.decompress(stream);
t.bitstream = stream.readBitStream();
},
decodeGroups: function (stream) {
var t = this;
var n = stream.readInt();
t.groups = new Array(n);
for (var i = 0; i < n; i++) {
var end = stream.readInt();
var np = stream.readUChar();
var g = {
end: end,
properties: {}
};
for (var k = 0; k < np; k++) {
var key = stream.readString();
g.properties[key] = stream.readString();
}
t.groups[i] = g;
}
}
};
/*
Corto
Copyright (c) 2017-2020, Visual Computing Lab, ISTI - CNR
All rights reserved.
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.
*/
function BitStream(array) {
var t = this;
t.a = array;
t.current = array[0];
t.position = 0; //position in the buffer
t.pending = 32; //bits still to read
}
;
BitStream.prototype = {
read: function (bits) {
var t = this;
if (bits > t.pending) {
t.pending = bits - t.pending;
var result = t.current << t.pending >>> 0; //looks the same.
t.pending = 32 - t.pending;
t.current = t.a[++t.position];
result |= t.current >>> t.pending;
t.current = (t.current & (1 << t.pending) - 1) >>> 0; //slighting faster than mask.
return result;
} else {
//splitting result in branch seems faster.
t.pending -= bits;
var result = t.current >>> t.pending;
t.current = (t.current & (1 << t.pending) - 1) >>> 0; //slighting faster than mask,
return result;
}
}
};
function Stream(buffer, byteOffset, byteLength) {
var t = this;
t.data = buffer;
t.buffer = new Uint8Array(buffer);
t.pos = byteOffset ? byteOffset : 0;
t.view = new DataView(buffer);
}
Stream.prototype = {
logs: new Uint8Array(16768),
readChar: function () {
var c = this.buffer[this.pos++];
if (c > 127) c -= 256;
return c;
},
readUChar: function () {
return this.buffer[this.pos++];
},
readShort: function () {
this.pos += 2;
return this.view.getInt16(this.pos - 2, true);
},
readFloat: function () {
this.pos += 4;
return this.view.getFloat32(this.pos - 4, true);
},
readInt: function () {
this.pos += 4;
return this.view.getInt32(this.pos - 4, true);
},
readArray: function (n) {
var a = this.buffer.subarray(this.pos, this.pos + n);
this.pos += n;
return a;
},
readString: function () {
var n = this.readShort();
var s = String.fromCharCode.apply(null, this.readArray(n - 1));
this.pos++; //null terminator of string.
return s;
},
readBitStream: function () {
var n = this.readInt();
var pad = this.pos & 0x3;
if (pad != 0) this.pos += 4 - pad;
var b = new BitStream(new Uint32Array(this.data, this.pos, n));
this.pos += n * 4;
return b;
},
//make decodearray2,3 later //TODO faster to create values here or passing them?
decodeArray: function (N, values) {
var t = this;
var bitstream = t.readBitStream();
var tunstall = new Tunstall();
while (t.logs.length < values.length) t.logs = new Uint8Array(values.length);
tunstall.decompress(this, t.logs);
for (var i = 0; i < t.logs.readed; i++) {
var diff = t.logs[i];
if (diff == 0) {
for (var c = 0; c < N; c++) values[i * N + c] = 0;
continue;
}
var max = 1 << diff >>> 1;
for (var c = 0; c < N; c++) values[i * N + c] = bitstream.read(diff) - max;
}
return t.logs.readed;
},
//assumes values alread allocated
decodeValues: function (N, values) {
var t = this;
var bitstream = t.readBitStream();
var tunstall = new Tunstall();
var size = values.length / N;
while (t.logs.length < size) t.logs = new Uint8Array(size);
for (var c = 0; c < N; c++) {
tunstall.decompress(this, t.logs);
for (var i = 0; i < t.logs.readed; i++) {
var diff = t.logs[i];
if (diff == 0) {
values[i * N + c] = 0;
continue;
}
var val = bitstream.read(diff);
var middle = 1 << diff - 1 >>> 0;
if (val < middle) val = -val - middle;
values[i * N + c] = val;
}
}
return t.logs.readed;
},
//assumes values alread allocated
decodeDiffs: function (values) {
var t = this;
var bitstream = t.readBitStream();
var tunstall = new Tunstall();
var size = values.length;
while (t.logs.length < size) t.logs = new Uint8Array(size);
tunstall.decompress(this, t.logs);
for (var i = 0; i < t.logs.readed; i++) {
var diff = t.logs[i];
if (diff == 0) {
values[i] = 0;
continue;
}
var max = 1 << diff >>> 1;
values[i] = bitstream.read(diff) - max;
}
return t.logs.readed;
},
//assumes values alread allocated
decodeIndices: function (values) {
var t = this;
var bitstream = t.readBitStream();
var tunstall = new Tunstall();
var size = values.length;
while (t.logs.length < size) t.logs = new Uint8Array(size);
tunstall.decompress(this, t.logs);
for (var i = 0; i < t.logs.readed; i++) {
var ret = t.logs[i];
if (ret == 0) {
values[i] = 0;
continue;
}
values[i] = (1 << ret) + bitstream.read(ret) - 1;
}
return t.logs.readed;
}
};
function Tunstall() {}
Tunstall.prototype = {
wordsize: 8,
dictionary_size: 256,
starts: new Uint32Array(256),
//starts of each queue
queue: new Uint32Array(512),
//array of n symbols array of prob, position in buffer, length //limit to 8k*3
index: new Uint32Array(512),
lengths: new Uint32Array(512),
table: new Uint8Array(8192),
//worst case for 2
decompress: function (stream, data) {
var nsymbols = stream.readUChar();
this.probs = stream.readArray(nsymbols * 2);
this.createDecodingTables();
var size = stream.readInt();
if (size > 100000000) throw "TOO LARGE!";
if (!data) data = new Uint8Array(size);
if (data.length < size) throw "Array for results too small";
data.readed = size;
var compressed_size = stream.readInt();
if (size > 100000000) throw "TOO LARGE!";
var compressed_data = stream.readArray(compressed_size);
if (size) this._decompress(compressed_data, compressed_size, data, size);
return data;
},
createDecodingTables: function () {
var t = this;
var n_symbols = t.probs.length / 2;
if (n_symbols <= 1) return;
var queue = Tunstall.prototype.queue;
var end = 0; //keep track of queue end
var pos = 0; //keep track of buffer first free space
var n_words = 0; //Here probs will range from 0 to 0xffff for better precision
for (var i = 0; i < n_symbols; i++) queue[i] = t.probs[2 * i + 1] << 8;
var max_repeat = Math.floor((t.dictionary_size - 1) / (n_symbols - 1));
var repeat = 2;
var p0 = queue[0];
var p1 = queue[1];
var prob = p0 * p0 >>> 16;
while (prob > p1 && repeat < max_repeat) {
prob = prob * p0 >>> 16;
repeat++;
}
if (repeat >= 16) {
//Very low entropy results in large tables > 8K.
t.table[pos++] = t.probs[0];
for (var k = 1; k < n_symbols; k++) {
for (var i = 0; i < repeat - 1; i++) t.table[pos++] = t.probs[0];
t.table[pos++] = t.probs[2 * k];
}
t.starts[0] = (repeat - 1) * n_symbols;
for (var k = 1; k < n_symbols; k++) t.starts[k] = k;
for (var col = 0; col < repeat; col++) {
for (var row = 1; row < n_symbols; row++) {
var off = row + col * n_symbols;
if (col > 0) queue[off] = prob * queue[row] >> 16;
t.index[off] = row * repeat - col;
t.lengths[off] = col + 1;
}
if (col == 0) prob = p0;else prob = prob * p0 >>> 16;
}
var first = (repeat - 1) * n_symbols;
queue[first] = prob;
t.index[first] = 0;
t.lengths[first] = repeat;
n_words = 1 + repeat * (n_symbols - 1);
end = repeat * n_symbols;
} else {
//initialize adding all symbols to queues
for (var i = 0; i < n_symbols; i++) {
queue[i] = t.probs[i * 2 + 1] << 8;
t.index[i] = i;
t.lengths[i] = 1;
t.starts[i] = i;
t.table[i] = t.probs[i * 2];
}
pos = n_symbols;
end = n_symbols;
n_words = n_symbols;
} //at each step we grow all queues using the most probable sequence
while (n_words < t.dictionary_size) {
//find highest probability word
var best = 0;
var max_prob = 0;
for (var i = 0; i < n_symbols; i++) {
var p = queue[t.starts[i]]; //front of queue probability.
if (p > max_prob) {
best = i;
max_prob = p;
}
}
var start = t.starts[best];
var offset = t.index[start];
var len = t.lengths[start];
for (var i = 0; i < n_symbols; i++) {
queue[end] = queue[i] * queue[start] >>> 16;
t.index[end] = pos;
t.lengths[end] = len + 1;
end++;
for (var k = 0; k < len; k++) t.table[pos + k] = t.table[offset + k]; //copy sequence of symbols
pos += len;
t.table[pos++] = t.probs[i * 2]; //append symbol
if (i + n_words == t.dictionary_size - 1) break;
}
if (i == n_symbols) t.starts[best] += n_symbols; //move one column
n_words += n_symbols - 1;
}
var word = 0;
for (i = 0, row = 0; i < end; i++, row++) {
if (row >= n_symbols) row = 0;
if (t.starts[row] > i) continue; //skip deleted words
t.index[word] = t.index[i];
t.lengths[word] = t.lengths[i];
word++;
}
},
_decompress: function (input, input_size, output, output_size) {
//TODO optimize using buffer arrays
var input_pos = 0;
var output_pos = 0;
if (this.probs.length == 2) {
var symbol = this.probs[0];
for (var i = 0; i < output_size; i++) output[i] = symbol;
return;
}
while (input_pos < input_size - 1) {
var symbol = input[input_pos++];
var start = this.index[symbol];
var end = start + this.lengths[symbol];
for (i = start; i < end; i++) output[output_pos++] = this.table[i];
} //last symbol might override so we check.
var symbol = input[input_pos];
var start = this.index[symbol];
end = start + output_size - output_pos;
var length = output_size - output_pos;
for (i = start; i < end; i++) output[output_pos++] = this.table[i];
return output;
}
}; | the_stack |
import { ParseTreeVisitor } from 'antlr4ts/tree/ParseTreeVisitor';
import { DocumentationContext } from './TomParser';
import { BodyContext } from './TomParser';
import { WhitespaceContext } from './TomParser';
import { AnnotationsContext } from './TomParser';
import { TagContext } from './TomParser';
import { TagNameContext } from './TomParser';
import { TagIDContext } from './TomParser';
import { OptionalTagIDContext } from './TomParser';
import { PropertyTagIDContext } from './TomParser';
import { OptionalTagOrIdentifierContext } from './TomParser';
import { TypeContext } from './TomParser';
import { UnaryTypeContext } from './TomParser';
import { TupleTypeContext } from './TomParser';
import { TupleTypeListContext } from './TomParser';
import { PrimaryTypeContext } from './TomParser';
import { IdentifierOrKeywordContext } from './TomParser';
import { ParenthesizedTypeContext } from './TomParser';
import { LambdaTypeContext } from './TomParser';
import { FormalParameterSequenceContext } from './TomParser';
import { ParameterContext } from './TomParser';
import { ArrayTypeContext } from './TomParser';
import { ObjectTypeContext } from './TomParser';
import { ObjectPairTypeListContext } from './TomParser';
import { ObjectPairTypeContext } from './TomParser';
import { OptionalTypeContext } from './TomParser';
import { PropertyTypeContext } from './TomParser';
import { OptionalTypeOrIdentiferContext } from './TomParser';
import { ValueContext } from './TomParser';
import { ExpressionContext } from './TomParser';
import { UnaryExpressionContext } from './TomParser';
import { ArrayExpressionContext } from './TomParser';
import { ObjectExpressionContext } from './TomParser';
import { ObjectPairExpressionListContext } from './TomParser';
import { ObjectPairExpressionContext } from './TomParser';
import { LambdaExpressionContext } from './TomParser';
import { LiteralContext } from './TomParser';
import { ParenthesizedExpressionContext } from './TomParser';
import { DescriptionContext } from './TomParser';
import { DescriptionLineContext } from './TomParser';
import { DescriptionLineStartContext } from './TomParser';
import { DescriptionTextContext } from './TomParser';
import { DescriptionLineElementContext } from './TomParser';
import { DescriptionLineTextContext } from './TomParser';
import { InlineTagContext } from './TomParser';
import { InlineTagNameContext } from './TomParser';
import { InlineTagBodyContext } from './TomParser';
import { BraceExpressionContext } from './TomParser';
import { BraceBodyContext } from './TomParser';
import { BraceTextContext } from './TomParser';
import { IdentifierContext } from './TomParser';
/**
* This interface defines a complete generic visitor for a parse tree produced
* by `TomParser`.
*
* @param <Result> The return type of the visit operation. Use `void` for
* operations with no return type.
*/
export interface TomParserVisitor<Result> extends ParseTreeVisitor<Result> {
/**
* Visit a parse tree produced by `TomParser.documentation`.
* @param ctx the parse tree
* @return the visitor result
*/
visitDocumentation?: (ctx: DocumentationContext) => Result;
/**
* Visit a parse tree produced by `TomParser.body`.
* @param ctx the parse tree
* @return the visitor result
*/
visitBody?: (ctx: BodyContext) => Result;
/**
* Visit a parse tree produced by `TomParser.whitespace`.
* @param ctx the parse tree
* @return the visitor result
*/
visitWhitespace?: (ctx: WhitespaceContext) => Result;
/**
* Visit a parse tree produced by `TomParser.annotations`.
* @param ctx the parse tree
* @return the visitor result
*/
visitAnnotations?: (ctx: AnnotationsContext) => Result;
/**
* Visit a parse tree produced by `TomParser.tag`.
* @param ctx the parse tree
* @return the visitor result
*/
visitTag?: (ctx: TagContext) => Result;
/**
* Visit a parse tree produced by `TomParser.tagName`.
* @param ctx the parse tree
* @return the visitor result
*/
visitTagName?: (ctx: TagNameContext) => Result;
/**
* Visit a parse tree produced by `TomParser.tagID`.
* @param ctx the parse tree
* @return the visitor result
*/
visitTagID?: (ctx: TagIDContext) => Result;
/**
* Visit a parse tree produced by `TomParser.optionalTagID`.
* @param ctx the parse tree
* @return the visitor result
*/
visitOptionalTagID?: (ctx: OptionalTagIDContext) => Result;
/**
* Visit a parse tree produced by `TomParser.propertyTagID`.
* @param ctx the parse tree
* @return the visitor result
*/
visitPropertyTagID?: (ctx: PropertyTagIDContext) => Result;
/**
* Visit a parse tree produced by `TomParser.optionalTagOrIdentifier`.
* @param ctx the parse tree
* @return the visitor result
*/
visitOptionalTagOrIdentifier?: (ctx: OptionalTagOrIdentifierContext) => Result;
/**
* Visit a parse tree produced by `TomParser.type`.
* @param ctx the parse tree
* @return the visitor result
*/
visitType?: (ctx: TypeContext) => Result;
/**
* Visit a parse tree produced by `TomParser.unaryType`.
* @param ctx the parse tree
* @return the visitor result
*/
visitUnaryType?: (ctx: UnaryTypeContext) => Result;
/**
* Visit a parse tree produced by `TomParser.tupleType`.
* @param ctx the parse tree
* @return the visitor result
*/
visitTupleType?: (ctx: TupleTypeContext) => Result;
/**
* Visit a parse tree produced by `TomParser.tupleTypeList`.
* @param ctx the parse tree
* @return the visitor result
*/
visitTupleTypeList?: (ctx: TupleTypeListContext) => Result;
/**
* Visit a parse tree produced by `TomParser.primaryType`.
* @param ctx the parse tree
* @return the visitor result
*/
visitPrimaryType?: (ctx: PrimaryTypeContext) => Result;
/**
* Visit a parse tree produced by `TomParser.identifierOrKeyword`.
* @param ctx the parse tree
* @return the visitor result
*/
visitIdentifierOrKeyword?: (ctx: IdentifierOrKeywordContext) => Result;
/**
* Visit a parse tree produced by `TomParser.parenthesizedType`.
* @param ctx the parse tree
* @return the visitor result
*/
visitParenthesizedType?: (ctx: ParenthesizedTypeContext) => Result;
/**
* Visit a parse tree produced by `TomParser.lambdaType`.
* @param ctx the parse tree
* @return the visitor result
*/
visitLambdaType?: (ctx: LambdaTypeContext) => Result;
/**
* Visit a parse tree produced by `TomParser.formalParameterSequence`.
* @param ctx the parse tree
* @return the visitor result
*/
visitFormalParameterSequence?: (ctx: FormalParameterSequenceContext) => Result;
/**
* Visit a parse tree produced by `TomParser.parameter`.
* @param ctx the parse tree
* @return the visitor result
*/
visitParameter?: (ctx: ParameterContext) => Result;
/**
* Visit a parse tree produced by `TomParser.arrayType`.
* @param ctx the parse tree
* @return the visitor result
*/
visitArrayType?: (ctx: ArrayTypeContext) => Result;
/**
* Visit a parse tree produced by `TomParser.objectType`.
* @param ctx the parse tree
* @return the visitor result
*/
visitObjectType?: (ctx: ObjectTypeContext) => Result;
/**
* Visit a parse tree produced by `TomParser.objectPairTypeList`.
* @param ctx the parse tree
* @return the visitor result
*/
visitObjectPairTypeList?: (ctx: ObjectPairTypeListContext) => Result;
/**
* Visit a parse tree produced by `TomParser.objectPairType`.
* @param ctx the parse tree
* @return the visitor result
*/
visitObjectPairType?: (ctx: ObjectPairTypeContext) => Result;
/**
* Visit a parse tree produced by `TomParser.optionalType`.
* @param ctx the parse tree
* @return the visitor result
*/
visitOptionalType?: (ctx: OptionalTypeContext) => Result;
/**
* Visit a parse tree produced by `TomParser.propertyType`.
* @param ctx the parse tree
* @return the visitor result
*/
visitPropertyType?: (ctx: PropertyTypeContext) => Result;
/**
* Visit a parse tree produced by `TomParser.optionalTypeOrIdentifer`.
* @param ctx the parse tree
* @return the visitor result
*/
visitOptionalTypeOrIdentifer?: (ctx: OptionalTypeOrIdentiferContext) => Result;
/**
* Visit a parse tree produced by `TomParser.value`.
* @param ctx the parse tree
* @return the visitor result
*/
visitValue?: (ctx: ValueContext) => Result;
/**
* Visit a parse tree produced by `TomParser.expression`.
* @param ctx the parse tree
* @return the visitor result
*/
visitExpression?: (ctx: ExpressionContext) => Result;
/**
* Visit a parse tree produced by `TomParser.unaryExpression`.
* @param ctx the parse tree
* @return the visitor result
*/
visitUnaryExpression?: (ctx: UnaryExpressionContext) => Result;
/**
* Visit a parse tree produced by `TomParser.arrayExpression`.
* @param ctx the parse tree
* @return the visitor result
*/
visitArrayExpression?: (ctx: ArrayExpressionContext) => Result;
/**
* Visit a parse tree produced by `TomParser.objectExpression`.
* @param ctx the parse tree
* @return the visitor result
*/
visitObjectExpression?: (ctx: ObjectExpressionContext) => Result;
/**
* Visit a parse tree produced by `TomParser.objectPairExpressionList`.
* @param ctx the parse tree
* @return the visitor result
*/
visitObjectPairExpressionList?: (ctx: ObjectPairExpressionListContext) => Result;
/**
* Visit a parse tree produced by `TomParser.objectPairExpression`.
* @param ctx the parse tree
* @return the visitor result
*/
visitObjectPairExpression?: (ctx: ObjectPairExpressionContext) => Result;
/**
* Visit a parse tree produced by `TomParser.lambdaExpression`.
* @param ctx the parse tree
* @return the visitor result
*/
visitLambdaExpression?: (ctx: LambdaExpressionContext) => Result;
/**
* Visit a parse tree produced by `TomParser.literal`.
* @param ctx the parse tree
* @return the visitor result
*/
visitLiteral?: (ctx: LiteralContext) => Result;
/**
* Visit a parse tree produced by `TomParser.parenthesizedExpression`.
* @param ctx the parse tree
* @return the visitor result
*/
visitParenthesizedExpression?: (ctx: ParenthesizedExpressionContext) => Result;
/**
* Visit a parse tree produced by `TomParser.description`.
* @param ctx the parse tree
* @return the visitor result
*/
visitDescription?: (ctx: DescriptionContext) => Result;
/**
* Visit a parse tree produced by `TomParser.descriptionLine`.
* @param ctx the parse tree
* @return the visitor result
*/
visitDescriptionLine?: (ctx: DescriptionLineContext) => Result;
/**
* Visit a parse tree produced by `TomParser.descriptionLineStart`.
* @param ctx the parse tree
* @return the visitor result
*/
visitDescriptionLineStart?: (ctx: DescriptionLineStartContext) => Result;
/**
* Visit a parse tree produced by `TomParser.descriptionText`.
* @param ctx the parse tree
* @return the visitor result
*/
visitDescriptionText?: (ctx: DescriptionTextContext) => Result;
/**
* Visit a parse tree produced by `TomParser.descriptionLineElement`.
* @param ctx the parse tree
* @return the visitor result
*/
visitDescriptionLineElement?: (ctx: DescriptionLineElementContext) => Result;
/**
* Visit a parse tree produced by `TomParser.descriptionLineText`.
* @param ctx the parse tree
* @return the visitor result
*/
visitDescriptionLineText?: (ctx: DescriptionLineTextContext) => Result;
/**
* Visit a parse tree produced by `TomParser.inlineTag`.
* @param ctx the parse tree
* @return the visitor result
*/
visitInlineTag?: (ctx: InlineTagContext) => Result;
/**
* Visit a parse tree produced by `TomParser.inlineTagName`.
* @param ctx the parse tree
* @return the visitor result
*/
visitInlineTagName?: (ctx: InlineTagNameContext) => Result;
/**
* Visit a parse tree produced by `TomParser.inlineTagBody`.
* @param ctx the parse tree
* @return the visitor result
*/
visitInlineTagBody?: (ctx: InlineTagBodyContext) => Result;
/**
* Visit a parse tree produced by `TomParser.braceExpression`.
* @param ctx the parse tree
* @return the visitor result
*/
visitBraceExpression?: (ctx: BraceExpressionContext) => Result;
/**
* Visit a parse tree produced by `TomParser.braceBody`.
* @param ctx the parse tree
* @return the visitor result
*/
visitBraceBody?: (ctx: BraceBodyContext) => Result;
/**
* Visit a parse tree produced by `TomParser.braceText`.
* @param ctx the parse tree
* @return the visitor result
*/
visitBraceText?: (ctx: BraceTextContext) => Result;
/**
* Visit a parse tree produced by `TomParser.identifier`.
* @param ctx the parse tree
* @return the visitor result
*/
visitIdentifier?: (ctx: IdentifierContext) => Result;
} | the_stack |
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { StoreModule, Store } from '@ngrx/store';
import * as faker from 'faker';
import { NgrxStateAtom, runtimeChecks } from 'app/ngrx.reducers';
import { using } from 'app/testing/spec-helpers';
import { IndexedEntities } from 'app/entities/entities';
import { UserPermEntity } from 'app/entities/userperms/userperms.entity';
import { Status } from 'app/entities/userperms/userperms.reducer';
import { GetSomeUserPerms, GetUserParamPerms } from 'app/entities/userperms/userperms.actions';
import { AuthorizedChecker } from 'app/helpers/auth/authorized';
import { AuthorizedComponent, Check } from './authorized.component';
describe('AuthorizedComponent', () => {
let component: AuthorizedComponent;
let fixture: ComponentFixture<AuthorizedComponent>;
let dispatchSpy: jasmine.Spy;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
StoreModule.forRoot({
userperms: () => ({
status: Status.loadingSuccess,
byId: <IndexedEntities<UserPermEntity>>{
'authed/endpoint': {
id: 'authed/endpoint',
get: true,
put: true,
post: true,
delete: true,
patch: true
},
'another/authed/endpoint': {
id: 'another/authed/endpoint',
get: true,
put: true,
post: true,
delete: true,
patch: true
},
'notauthed/endpoint': {
id: 'notauthed/endpoint',
get: false,
put: false,
post: false,
delete: false,
patch: false
},
'another/notauthed/endpoint': {
id: 'another/notauthed/endpoint',
get: false,
put: false,
post: false,
delete: false,
patch: false
}
}
})
}, { runtimeChecks })
],
declarations: [
AuthorizedComponent
]
}).compileComponents();
const store: Store<NgrxStateAtom> = TestBed.inject(Store);
dispatchSpy = spyOn(store, 'dispatch').and.callThrough();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AuthorizedComponent);
component = fixture.componentInstance;
});
it('exists', () => {
fixture.detectChanges();
expect(component).toBeTruthy();
});
using([
['disallowed endpoint', genCheck('notauthed/endpoint'), false],
['allowed endpoint', genCheck('authed/endpoint'), true]
], function (description: string, singleEp: Check, expected: boolean) {
it(('supports single checks to be passed without nesting for ' + description), done => {
component.allOf = singleEp;
fixture.detectChanges();
checkAfterDebounce(expected, done);
});
});
using([
['disallowed endpoint with all uppercase', [genCheck('notauthed/endpoint', 'POST')], false],
['disallowed endpoint with mixed case', [genCheck('notauthed/endpoint', 'GeT')], false],
['disallowed endpoint with all lowercase', [genCheck('notauthed/endpoint', 'patch')], false],
['allowed endpoint with all uppercase', [genCheck('authed/endpoint', 'POST')], true],
['allowed endpoint with mixed case', [genCheck('authed/endpoint', 'GeT')], true],
['allowed endpoint with all lowercase', [genCheck('authed/endpoint', 'patch')], true]
], function (description: string, epList: Check[], expected: boolean) {
it('supports ' + description, done => {
component.allOf = epList;
fixture.detectChanges();
checkAfterDebounce(expected, done);
});
});
describe('visibility setting', () => {
it('is visible when allOf are all valid', done => {
component.allOf = [
genCheck('authed/endpoint'),
genCheck('another/authed/endpoint')];
fixture.detectChanges();
const expected = true;
checkAfterDebounce(expected, done);
});
it('is NOT visible when allOf are not all valid', done => {
component.allOf = [
genCheck('authed/endpoint'),
genCheck('notauthed/endpoint')];
fixture.detectChanges();
const expected = false;
checkAfterDebounce(expected, done);
});
it('is visible when allOf is an empty list', done => {
component.allOf = [];
component.anyOf = [ genCheck('another/authed/endpoint') ];
fixture.detectChanges();
const expected = true;
checkAfterDebounce(expected, done);
});
it('is visible when anyOf are all valid', done => {
component.anyOf = [
genCheck('authed/endpoint'),
genCheck('another/authed/endpoint')];
fixture.detectChanges();
const expected = true;
checkAfterDebounce(expected, done);
});
it('is visible when anyOf are NOT all valid', done => {
component.anyOf = [
genCheck('authed/endpoint'),
genCheck('notauthed/endpoint')];
fixture.detectChanges();
const expected = true;
checkAfterDebounce(expected, done);
});
it('is NOT visible when anyOf are all invalid', done => {
component.anyOf = [
genCheck('notauthed/endpoint'),
genCheck('another/notauthed/endpoint')];
fixture.detectChanges();
const expected = false;
checkAfterDebounce(expected, done);
});
it('is visible when anyOf is an empty list', done => {
component.anyOf = [];
component.allOf = [ genCheck('another/authed/endpoint') ];
fixture.detectChanges();
const expected = true;
checkAfterDebounce(expected, done);
});
it('is visible when neither anyOf or allOf are specified', done => {
fixture.detectChanges();
const expected = true;
checkAfterDebounce(expected, done);
});
});
describe('non-parameterized endpoints', () => {
using([
['some allOf and no anyOf',
[genCheck(), genCheck()],
[]
],
['no allOf and some anyOf',
[],
[genCheck(), genCheck(), genCheck()]
],
['some allOf and some anyOf',
[genCheck(), genCheck()],
[genCheck(), genCheck(), genCheck()]
]
], function (description, allOfList: Check[], anyOfList: Check[]) {
it('dispatches just one action when passing ' + description, () => {
component.allOf = allOfList;
component.anyOf = anyOfList;
fixture.detectChanges();
expect(dispatchSpy).toHaveBeenCalledTimes(1);
const args = dispatchSpy.calls.argsFor(0);
expect(args[0] instanceof GetSomeUserPerms).toBeTruthy();
});
});
it('does not dispatch action when passing no endpoints', () => {
component.allOf = [];
component.anyOf = [];
fixture.detectChanges();
expect(dispatchSpy).not.toHaveBeenCalled();
});
});
describe('parameterized endpoints', () => {
using([
['some allOf and no anyOf',
[genCheckParameterized('some/ep1/{a}'), genCheckParameterized('some/ep2/{a}')],
[]
],
['no allOf and some anyOf',
[],
[genCheckParameterized('some/ep3/{a}'),
genCheckParameterized('some/ep4/{a}'),
genCheckParameterized('some/ep5/{a}')]
],
['some allOf and some anyOf',
[genCheckParameterized('some/ep1/{a}'), genCheckParameterized('some/ep2/{a}')],
[genCheckParameterized('some/ep3/{a}'),
genCheckParameterized('some/ep4/{a}'),
genCheckParameterized('some/ep5/{a}')]
]
], function (description, allOfList: Check[], anyOfList: Check[]) {
it('dispatches one action for each parameterized endpoint when passing ' + description,
() => {
component.allOf = allOfList;
component.anyOf = anyOfList;
fixture.detectChanges();
expect(dispatchSpy).toHaveBeenCalledTimes(allOfList.length + anyOfList.length);
for (let i = 0; i < dispatchSpy.calls.count(); i++) {
const args = dispatchSpy.calls.argsFor(i);
expect(args[0] instanceof GetUserParamPerms).toBeTruthy();
}
});
});
it('does not dispatch action when passing no endpoints', () => {
component.allOf = [];
component.anyOf = [];
fixture.detectChanges();
expect(dispatchSpy).not.toHaveBeenCalled();
});
});
it('dispatches BOTH parameterized AND non-parameterized actions with mixed endpoints',
() => {
component.allOf = [genCheckParameterized('some/ep1/{username}'), genCheck()];
component.anyOf = [genCheck(), genCheckParameterized('some/ep4/{email}'), genCheck()];
// NB: for simplicity in testing, leave the param lists empty above
// so we can match the literal placeholders in the `toContain` predicate below.
const parameterizedEntries = 2;
fixture.detectChanges();
expect(dispatchSpy).toHaveBeenCalledTimes(parameterizedEntries + 1);
let args = dispatchSpy.calls.argsFor(0); // first call is all non-parameterized eps
expect(args[0] instanceof GetSomeUserPerms).toBeTruthy();
for (let i = 0; i < parameterizedEntries; i++) {
args = dispatchSpy.calls.argsFor(i + 1); // parameterized eps follow, one for each
expect(args[0] instanceof GetUserParamPerms).toBeTruthy();
}
});
function genCheck(path?: string, method?: string, paramList?: string | string[]): Check {
const methods = ['get', 'put', 'post', 'delete', 'patch'];
return [
path || `/${faker.lorem.word()}/${faker.lorem.word()}/${faker.lorem.word()}`,
method || faker.random.arrayElement(methods),
paramList || []
];
}
function genCheckParameterized(path: string, paramList?: string | string[]): Check {
return genCheck(path, null, paramList);
}
function checkAfterDebounce(expected: boolean, done: any) {
// simple way to account for debounce()
setTimeout(() => {
expect(component.visible).toBe(expected);
done();
}, AuthorizedChecker.DebounceTime + 1);
}
}); | the_stack |
import { Component, Input, Optional, ViewChild, OnInit, OnDestroy } from '@angular/core';
import { CoreTabsComponent } from '@components/tabs/tabs';
import { CoreCourseModuleMainActivityComponent } from '@features/course/classes/main-activity-component';
import { CoreCourseContentsPage } from '@features/course/pages/contents/contents';
import { IonContent } from '@ionic/angular';
import { CoreGroupInfo, CoreGroups } from '@services/groups';
import { CoreNavigator } from '@services/navigator';
import { CoreTextUtils } from '@services/utils/text';
import { CoreTimeUtils } from '@services/utils/time';
import { CoreUtils } from '@services/utils/utils';
import { CoreEventObserver, CoreEvents } from '@singletons/events';
import {
AddonModFeedback,
AddonModFeedbackGetFeedbackAccessInformationWSResponse,
AddonModFeedbackProvider,
AddonModFeedbackWSFeedback,
AddonModFeedbackWSItem,
} from '../../services/feedback';
import { AddonModFeedbackOffline } from '../../services/feedback-offline';
import {
AddonModFeedbackAutoSyncData,
AddonModFeedbackSync,
AddonModFeedbackSyncProvider,
AddonModFeedbackSyncResult,
} from '../../services/feedback-sync';
import { AddonModFeedbackModuleHandlerService } from '../../services/handlers/module';
import { AddonModFeedbackPrefetchHandler } from '../../services/handlers/prefetch';
/**
* Component that displays a feedback index page.
*/
@Component({
selector: 'addon-mod-feedback-index',
templateUrl: 'addon-mod-feedback-index.html',
})
export class AddonModFeedbackIndexComponent extends CoreCourseModuleMainActivityComponent implements OnInit, OnDestroy {
@ViewChild(CoreTabsComponent) tabsComponent?: CoreTabsComponent;
@Input() tab = 'overview';
@Input() group = 0;
component = AddonModFeedbackProvider.COMPONENT;
moduleName = 'feedback';
feedback?: AddonModFeedbackWSFeedback;
goPage?: number;
items: AddonModFeedbackItem[] = [];
warning?: string;
showAnalysis = false;
tabsReady = false;
firstSelectedTab?: number;
access?: AddonModFeedbackGetFeedbackAccessInformationWSResponse;
completedCount = 0;
itemsCount = 0;
groupInfo?: CoreGroupInfo;
overview = {
timeopen: 0,
openTimeReadable: '',
timeclose: 0,
closeTimeReadable: '',
};
tabsLoaded = {
overview: false,
analysis: false,
};
protected submitObserver: CoreEventObserver;
protected syncEventName = AddonModFeedbackSyncProvider.AUTO_SYNCED;
protected checkCompletionAfterLog = false;
constructor(
protected content?: IonContent,
@Optional() courseContentsPage?: CoreCourseContentsPage,
) {
super('AddonModLessonIndexComponent', content, courseContentsPage);
// Listen for form submit events.
this.submitObserver = CoreEvents.on(AddonModFeedbackProvider.FORM_SUBMITTED, async (data) => {
if (!this.feedback || data.feedbackId != this.feedback.id) {
return;
}
this.tabsLoaded.analysis = false;
this.tabsLoaded.overview = false;
this.showLoading = true;
// Prefetch data if needed.
if (!data.offline && this.isPrefetched()) {
await CoreUtils.ignoreErrors(AddonModFeedbackSync.prefetchAfterUpdate(
AddonModFeedbackPrefetchHandler.instance,
this.module,
this.courseId,
));
}
// Load the right tab.
if (data.tab != this.tab) {
this.tabChanged(data.tab);
} else {
this.loadContent(true);
}
}, this.siteId);
}
/**
* @inheritdoc
*/
async ngOnInit(): Promise<void> {
super.ngOnInit();
try {
await this.loadContent(false, true);
} finally {
this.tabsReady = true;
}
}
/**
* @inheritdoc
*/
protected async logActivity(): Promise<void> {
if (!this.feedback) {
return; // Shouldn't happen.
}
await AddonModFeedback.logView(this.feedback.id, this.feedback.name);
}
/**
* @inheritdoc
*/
protected async invalidateContent(): Promise<void> {
const promises: Promise<void>[] = [];
promises.push(AddonModFeedback.invalidateFeedbackData(this.courseId));
if (this.feedback) {
promises.push(AddonModFeedback.invalidateFeedbackAccessInformationData(this.feedback.id));
promises.push(AddonModFeedback.invalidateAnalysisData(this.feedback.id));
promises.push(CoreGroups.invalidateActivityAllowedGroups(this.feedback.coursemodule));
promises.push(CoreGroups.invalidateActivityGroupMode(this.feedback.coursemodule));
promises.push(AddonModFeedback.invalidateResumePageData(this.feedback.id));
}
this.tabsLoaded.analysis = false;
this.tabsLoaded.overview = false;
await Promise.all(promises);
}
/**
* @inheritdoc
*/
protected isRefreshSyncNeeded(syncEventData: AddonModFeedbackAutoSyncData): boolean {
if (this.feedback && syncEventData.feedbackId == this.feedback.id) {
// Refresh the data.
this.content?.scrollToTop();
return true;
}
return false;
}
/**
* @inheritdoc
*/
protected async fetchContent(refresh?: boolean, sync = false, showErrors = false): Promise<void> {
try {
this.feedback = await AddonModFeedback.getFeedback(this.courseId, this.module.id);
this.description = this.feedback.intro;
this.dataRetrieved.emit(this.feedback);
if (sync) {
// Try to synchronize the feedback.
await this.syncActivity(showErrors);
}
// Check if there are answers stored in offline.
this.access = await AddonModFeedback.getFeedbackAccessInformation(this.feedback.id, { cmId: this.module.id });
this.showAnalysis = (this.access.canviewreports || this.access.canviewanalysis) && !this.access.isempty;
this.firstSelectedTab = 0;
if (!this.showAnalysis) {
this.tab = 'overview';
}
if (this.tab == 'analysis') {
this.firstSelectedTab = 1;
return await this.fetchFeedbackAnalysisData();
}
await this.fetchFeedbackOverviewData();
} finally {
if (this.feedback) {
// Check if there are responses stored in offline.
this.hasOffline = await AddonModFeedbackOffline.hasFeedbackOfflineData(this.feedback.id);
}
if (this.tabsReady) {
// Make sure the right tab is selected.
this.tabsComponent?.selectTab(this.tab || 'overview');
}
}
}
/**
* Convenience function to get feedback overview data.
*
* @return Resolved when done.
*/
protected async fetchFeedbackOverviewData(): Promise<void> {
const promises: Promise<void>[] = [];
if (this.access!.cancomplete && this.access!.cansubmit && this.access!.isopen) {
promises.push(AddonModFeedback.getResumePage(this.feedback!.id, { cmId: this.module.id }).then((goPage) => {
this.goPage = goPage > 0 ? goPage : undefined;
return;
}));
}
if (this.access!.canedititems) {
this.overview.timeopen = (this.feedback!.timeopen || 0) * 1000;
this.overview.openTimeReadable = this.overview.timeopen ? CoreTimeUtils.userDate(this.overview.timeopen) : '';
this.overview.timeclose = (this.feedback!.timeclose || 0) * 1000;
this.overview.closeTimeReadable = this.overview.timeclose ? CoreTimeUtils.userDate(this.overview.timeclose) : '';
}
if (this.access!.canviewanalysis) {
// Get groups (only for teachers).
promises.push(this.fetchGroupInfo(this.module.id));
}
try {
await Promise.all(promises);
} finally {
this.tabsLoaded.overview = true;
}
}
/**
* Convenience function to get feedback analysis data.
*
* @param accessData Retrieved access data.
* @return Resolved when done.
*/
protected async fetchFeedbackAnalysisData(): Promise<void> {
try {
if (this.access!.canviewanalysis) {
// Get groups (only for teachers).
await this.fetchGroupInfo(this.module.id);
} else {
this.tabChanged('overview');
}
} finally {
this.tabsLoaded.analysis = true;
}
}
/**
* Fetch Group info data.
*
* @param cmId Course module ID.
* @return Resolved when done.
*/
protected async fetchGroupInfo(cmId: number): Promise<void> {
this.groupInfo = await CoreGroups.getActivityGroupInfo(cmId);
await this.setGroup(CoreGroups.validateGroupId(this.group, this.groupInfo));
}
/**
* Parse the analysis info to show the info correctly formatted.
*
* @param item Item to parse.
* @return Parsed item.
*/
protected parseAnalysisInfo(item: AddonModFeedbackItem): AddonModFeedbackItem {
switch (item.typ) {
case 'numeric':
item.average = item.data.reduce((prev, current) => prev + Number(current), 0) / item.data.length;
item.templateName = 'numeric';
break;
case 'info':
item.data = <string[]> item.data.map((dataItem) => {
const parsed = <Record<string, string>> CoreTextUtils.parseJSON(dataItem);
return parsed.show !== undefined ? parsed.show : false;
}).filter((dataItem) => dataItem); // Filter false entries.
case 'textfield':
case 'textarea':
item.templateName = 'list';
break;
case 'multichoicerated':
case 'multichoice': {
const parsedData = <Record<string, string | number>[]> item.data.map((dataItem) => {
const parsed = <Record<string, string | number>> CoreTextUtils.parseJSON(dataItem);
return parsed.answertext !== undefined ? parsed : false;
}).filter((dataItem) => dataItem); // Filter false entries.
// Format labels.
item.labels = parsedData.map((dataItem) => {
dataItem.quotient = (<number> dataItem.quotient * 100).toFixed(2);
let label = '';
if (dataItem.value !== undefined) {
label = '(' + dataItem.value + ') ';
}
label += dataItem.answertext;
label += Number(dataItem.quotient) > 0 ? ' (' + dataItem.quotient + '%)' : '';
return label;
});
item.chartData = parsedData.map((dataItem) => <number> dataItem.answercount);
if (item.typ == 'multichoicerated') {
item.average = parsedData.reduce((prev, current) => prev + Number(current.avg), 0.0);
}
const subtype = item.presentation.charAt(0);
const single = subtype != 'c';
item.chartType = single ? 'doughnut' : 'bar';
item.templateName = 'chart';
break;
}
default:
break;
}
return item;
}
/**
* Function to go to the questions form.
*
* @param preview Preview or edit the form.
*/
gotoAnswerQuestions(preview: boolean = false): void {
CoreNavigator.navigateToSitePath(
AddonModFeedbackModuleHandlerService.PAGE_NAME + `/${this.courseId}/${this.module.id}/form`,
{
params: {
preview,
fromIndex: true,
},
},
);
}
/**
* User entered the page that contains the component.
*/
ionViewDidEnter(): void {
super.ionViewDidEnter();
this.tabsComponent?.ionViewDidEnter();
}
/**
* User left the page that contains the component.
*/
ionViewDidLeave(): void {
super.ionViewDidLeave();
this.tabsComponent?.ionViewDidLeave();
}
/**
* Open non respondents page.
*/
openNonRespondents(): void {
CoreNavigator.navigateToSitePath(
AddonModFeedbackModuleHandlerService.PAGE_NAME + `/${this.courseId}/${this.module.id}/nonrespondents`,
{
params: {
group: this.group,
},
},
);
}
/**
* Open attempts page.
*/
openAttempts(): void {
if (!this.access!.canviewreports || this.completedCount <= 0) {
return;
}
CoreNavigator.navigateToSitePath(
AddonModFeedbackModuleHandlerService.PAGE_NAME + `/${this.courseId}/${this.module.id}/attempts`,
{
params: {
group: this.group,
},
},
);
}
/**
* Tab changed, fetch content again.
*
* @param tabName New tab name.
*/
tabChanged(tabName: string): void {
this.tab = tabName;
if (!this.tabsLoaded[this.tab]) {
this.loadContent(false, false, true);
}
}
/**
* Set group to see the analysis.
*
* @param groupId Group ID.
* @return Resolved when done.
*/
async setGroup(groupId: number): Promise<void> {
this.group = groupId;
const analysis = await AddonModFeedback.getAnalysis(this.feedback!.id, { groupId, cmId: this.module.id });
this.completedCount = analysis.completedcount;
this.itemsCount = analysis.itemscount;
if (this.tab == 'analysis') {
let num = 1;
this.items = <AddonModFeedbackItem[]> analysis.itemsdata.map((itemData) => {
const item: AddonModFeedbackItem = Object.assign(itemData.item, {
data: itemData.data,
num: num++,
});
// Move data inside item.
if (item.data && item.data.length) {
return this.parseAnalysisInfo(item);
}
return false;
}).filter((item) => item);
this.warning = '';
if (analysis.warnings?.length) {
const warning = analysis.warnings.find((warning) => warning.warningcode == 'insufficientresponsesforthisgroup');
this.warning = warning?.message;
}
}
}
/**
* @inheritdoc
*/
protected sync(): Promise<AddonModFeedbackSyncResult> {
return AddonModFeedbackSync.syncFeedback(this.feedback!.id);
}
/**
* @inheritdoc
*/
protected hasSyncSucceed(result: AddonModFeedbackSyncResult): boolean {
return result.updated;
}
/**
* Component being destroyed.
*/
ngOnDestroy(): void {
super.ngOnDestroy();
this.submitObserver?.off();
}
}
type AddonModFeedbackItem = AddonModFeedbackWSItem & {
data: string[];
num: number;
templateName?: string;
average?: number;
labels?: string[];
chartData?: number[];
chartType?: string;
}; | the_stack |
import * as React from 'react';
import Avatar from 'react-md/lib/Avatars';
import Chip from 'react-md/lib/Chips';
import TextField from 'react-md/lib/TextFields';
import Button from 'react-md/lib/Buttons/Button';
import Switch from 'react-md/lib/SelectionControls/Switch';
import InfoDrawer from '../common/InfoDrawer';
import { ToastActions } from '../Toast';
import SetupActions from '../../actions/SetupActions';
import SetupStore, { ISetupStoreState } from '../../stores/SetupStore';
interface ISetupState extends ISetupConfig {
editedEmail?: string;
validEmail?: boolean;
loaded?: boolean;
}
export default class Setup extends React.Component<any, ISetupState> {
state: ISetupState = {
admins: null,
stage: 'none',
enableAuthentication: false,
editedEmail: '',
validEmail: true,
allowHttp: false,
redirectUrl: '',
clientID: '',
clientSecret: '',
loaded: false,
issuer: ''
};
constructor(props: any) {
super(props);
this.updateSetupState = this.updateSetupState.bind(this);
this.checkEmailValue = this.checkEmailValue.bind(this);
this.onSave = this.onSave.bind(this);
this.onCancel = this.onCancel.bind(this);
this.onRemoveAdmin = this.onRemoveAdmin.bind(this);
this.onSwitchAllowHttp = this.onSwitchAllowHttp.bind(this);
this.onSwitchAuthenticationEnables = this.onSwitchAuthenticationEnables.bind(this);
this.onFieldChange = this.onFieldChange.bind(this);
this.getAdminArray = this.getAdminArray.bind(this);
this.addAdminEmail = this.addAdminEmail.bind(this);
this.onAddAdminClick = this.onAddAdminClick.bind(this);
this.addAdminEmailChange = this.addAdminEmailChange.bind(this);
this.redirectOut = this.redirectOut.bind(this);
this.areDefaultValues = this.areDefaultValues.bind(this);
}
updateSetupState(state: ISetupStoreState) {
this.setState(state);
}
componentDidMount() {
this.updateSetupState(SetupStore.getState());
SetupActions.load();
SetupStore.listen(this.updateSetupState);
}
componentWillUnmount() {
SetupStore.unlisten(this.updateSetupState);
}
validateEmail(email: string): boolean {
// tslint:disable-next-line:max-line-length
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
checkEmailValue(e: any) {
if (e.key === 'Enter') {
this.addAdminEmail();
return false;
}
this.setState({ validEmail: true });
return true;
}
onAddAdminClick() {
this.addAdminEmail();
}
addAdminEmailChange(newValue: any) {
this.setState({ editedEmail: newValue });
}
addAdminEmail() {
let email = this.state.editedEmail;
if (this.validateEmail(email)) {
var admins = this.state.admins;
admins.push(email);
this.setState({ admins, editedEmail: '' });
} else {
this.setState({ validEmail: false });
}
}
fixRedirectUrl(redirectUrl: string): string {
if (redirectUrl) { return redirectUrl; }
let host = '';
if (window && window.location) {
host = window.location.host;
}
let protocol = 'https:';
// On localhost, authentication requests go directly to port 4000
if (host === '' || host === 'localhost:3000' || host === 'localhost:4000') {
host = 'localhost:4000';
protocol = 'http:';
}
return protocol + '//' + host + '/auth/openid/return';
}
getAdminArray(): string[] {
let admins = this.state.admins || [];
if (this.state.editedEmail) {
admins.push(this.state.editedEmail);
}
return admins;
}
onSave(): any {
let admins = this.getAdminArray();
let redirectUrl = this.fixRedirectUrl(this.state.redirectUrl);
if (this.state.enableAuthentication) {
if (!admins || !admins.length) {
return ToastActions.addToast({ text: 'Fill in at least one admin', action: null });
}
if (!redirectUrl) {
return ToastActions.addToast({ text: 'Fill in redirect url', action: null });
}
if (!this.state.issuer) {
return ToastActions.addToast({ text: 'Fill in issuer', action: null });
}
if (this.state.issuer.indexOf('{Tenant-ID}') !== -1) {
return ToastActions.addToast({ text: 'Fill in a real issuer/tenant', action: null });
}
if (!this.state.clientID) {
return ToastActions.addToast({ text: 'Fill in client ID', action: null });
}
if (!this.state.clientSecret) {
return ToastActions.addToast({ text: 'Fill in client secret', action: null });
}
if (!this.state.allowHttp && redirectUrl.startsWith('http:')) {
return ToastActions.addToast(
{
text: 'Redirect url should start with https or enable http redirects',
action: null
});
}
}
var setupConfig = {
admins: admins,
stage: this.state.stage,
enableAuthentication: this.state.enableAuthentication,
allowHttp: this.state.allowHttp,
redirectUrl: redirectUrl,
clientID: this.state.clientID,
clientSecret: this.state.clientSecret,
issuer: this.state.issuer
};
SetupActions.save(setupConfig, () => { this.redirectOut(); });
}
onCancel () {
this.redirectOut();
}
redirectOut() {
if (window && window.location) {
window.location.replace('/');
}
}
onRemoveAdmin(admin: string) {
var admins = this.state.admins;
var adminIndex = admins.findIndex(adminName => adminName === admin);
if (adminIndex >= 0) {
admins.splice(adminIndex, 1);
this.setState({ admins });
}
}
onSwitchAuthenticationEnables(checked: boolean) {
this.setState({ enableAuthentication: checked });
}
onSwitchAllowHttp(checked: boolean) {
this.setState({ allowHttp: checked });
}
onFieldChange(value: string, e: any) {
let state = {};
state[e.target.id] = value;
this.setState(state);
}
// is it an empty configuration file?
areDefaultValues() {
return (
(this.state.admins == null || this.state.admins.length === 0)
&& !this.state.allowHttp
&& !this.state.clientID
&& !this.state.clientSecret
&& !this.state.enableAuthentication
&& !this.state.issuer
);
}
render() {
let { admins, loaded, validEmail, enableAuthentication,
redirectUrl, clientID, clientSecret, issuer, editedEmail } = this.state;
if (!issuer) {
issuer = 'https://sts.windows.net/{Tenant-ID}/';
}
// Setting default redirect parameter
redirectUrl = this.fixRedirectUrl(redirectUrl);
if (!loaded) {
return null;
}
let adminChips = (admins || []).map((admin, idx) => (
<Chip
key={idx}
label={admin}
avatar={<Avatar random>{admin.length && admin[0] || '?'}</Avatar>}
removable
onClick={this.onRemoveAdmin.bind(this, admin)}
/>
));
const instructionsUrl = 'https://docs.microsoft.com' +
'/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal' +
'#create-an-azure-active-directory-application';
// tslint:disable:max-line-length
return (
<div style={{ width: '100%' }}>
<Switch
id="enableAuthentication"
name="enableAuthentication"
label="Enable Authentication"
checked={enableAuthentication}
onChange={this.onSwitchAuthenticationEnables}
style={{ float: 'left' }}
/>
<InfoDrawer
width={300}
title="Authentication"
buttonIcon="help"
buttonTooltip="Click here to learn more about authentications"
buttonLabel="instructions"
>
<div>
Follow the <a href={instructionsUrl} target="_blank">instructions</a> to get:
<br />
<ul>
<li>Application ID (to Client ID)</li>
<li>Client Secret</li>
<li>Tenant ID</li>
<li>You don't need to follow <b>Assign application to role</b></li>
<li>Make sure <b>Sign-on URL/Reply URL</b> is the same as <b>Redirect URL</b> in this screen</li>
</ul>
<br />
(This process will require you to create a new application, add permissions, configure reply URL).
<br />
<br />
<hr/>
Please add an administrator email and press the 'Add' button.
<hr/>
This page (/setup) will continue to be available without authentication as long as you don't set up admin users.
</div>
</InfoDrawer>
<br />
{
enableAuthentication && (
<div>
<Switch
id="allowHttp"
name="allowHttp"
label="Allow http in authentication responses, e.g. during local development."
checked={this.state.allowHttp}
onChange={this.onSwitchAllowHttp}
/>
<div className="chip-list">
{adminChips}
</div>
<div className="md-grid md-cell md-cell--bottom" style={{margin: 0, padding: 0}}>
<TextField
id="adminEmail"
label="Administrator Email"
error={!validEmail}
errorText={(!validEmail && 'Please enter a valid email address') || ''}
lineDirection="center"
placeholder="Enter an additional administrator email"
className="md-cell md-cell--bottom md-cell--4"
value={editedEmail}
onKeyDown={this.checkEmailValue}
onChange={this.addAdminEmailChange}
/>
<span className="md-cell md-cell--bottom">
<Button icon primary onClick={this.onAddAdminClick}>add_circle</Button>
</span>
</div>
<TextField
id="redirectUrl"
label="Redirect Url"
lineDirection="center"
placeholder="Enter an additional administrator email"
className="md-cell md-cell--bottom"
defaultValue={redirectUrl}
onChange={this.onFieldChange}
/>
<TextField
id="clientID"
label="Client ID (Application ID)"
lineDirection="center"
placeholder="Enter an additional administrator email"
className="md-cell md-cell--bottom"
defaultValue={clientID}
onChange={this.onFieldChange}
/>
<TextField
id="clientSecret"
label="Client Secret"
type="password"
lineDirection="center"
placeholder="Enter client secret for registered application"
className="md-cell md-cell--bottom"
defaultValue={clientSecret}
onChange={this.onFieldChange}
/>
<TextField
id="issuer"
label="Issuer: https://sts.windows.net/{Tenant-ID}/"
lineDirection="center"
placeholder="https://sts.windows.net/{Tenant-ID}/"
className="md-cell md-cell--bottom"
defaultValue={issuer}
onChange={this.onFieldChange}
/>
</div>)
}
<Button flat primary label="Apply" onClick={this.onSave}>save</Button>
{
!this.areDefaultValues() && (
<Button flat primary label="Cancel" onClick={this.onCancel}>undo</Button>
)
}
</div>
);
// tslint:enable:max-line-length
}
} | the_stack |
import {FaceMesh, Results, FACEMESH_TESSELATION} from '@mediapipe/face_mesh';
import {TypedSopNode} from './_Base';
import {WebCamCopNode} from '../cop/WebCam';
import {NodeParamsConfig, ParamConfig} from '../utils/params/ParamsConfig';
import {NodeContext} from '../../poly/NodeContext';
import {BufferGeometry} from 'three/src/core/BufferGeometry';
import {BufferAttribute} from 'three/src/core/BufferAttribute';
import {Mesh} from 'three/src/objects/Mesh';
import {ObjectType} from '../../../core/geometry/Constant';
import {BaseNodeType} from '../_Base';
import {Texture} from 'three/src/textures/Texture';
import {CoreType} from '../../../core/Type';
import {MeshBasicMaterial} from 'three/src/materials/MeshBasicMaterial';
import {sRGBEncoding} from 'three/src/constants';
import {CoreSleep} from '../../../core/Sleep';
import {CoreGraphNode} from '../../../core/graph/CoreGraphNode';
import {isBooleanTrue} from '../../../core/BooleanValue';
import {CopType} from '../../poly/registers/nodes/types/Cop';
import {VideoCopNode} from '../cop/Video';
const FACEMESH_POINTS_COUNT = 468;
const ALLOWED_COP_TYPES = [CopType.VIDEO, CopType.WEB_CAM];
type AllowedCopType = WebCamCopNode | VideoCopNode;
type WebCamSnapshotResolve = (value: void | PromiseLike<void>) => void;
interface TextureAndImage {
texture: Texture;
image: HTMLImageElement;
}
class MediapipeFaceMeshSopParamsConfig extends NodeParamsConfig {
/** @param webcam node */
webcam = ParamConfig.NODE_PATH('', {
nodeSelection: {
context: NodeContext.COP,
types: ALLOWED_COP_TYPES,
},
});
/** @param scale */
scale = ParamConfig.FLOAT(2, {
range: [0, 2],
rangeLocked: [true, false],
});
/** @param selfie mode */
selfieMode = ParamConfig.BOOLEAN(0);
/** @param min detection confidence */
minDetectionConfidence = ParamConfig.FLOAT(0.5, {
range: [0, 1],
rangeLocked: [true, true],
});
/** @param max detection confidence */
maxDetectionConfidence = ParamConfig.FLOAT(0.5, {
range: [0, 1],
rangeLocked: [true, true],
});
/** @param number of frames that will be captured */
frames = ParamConfig.INTEGER(1, {
range: [1, 100],
rangeLocked: [true, false],
});
/** @param frames per second */
fps = ParamConfig.INTEGER(24, {
range: [1, 60],
rangeLocked: [true, false],
});
/** @param capture */
capture = ParamConfig.BUTTON(null, {
callback: (node: BaseNodeType) => {
MediapipeFaceMeshSopNode.PARAM_CALLBACK_capture(node as MediapipeFaceMeshSopNode);
},
});
/** @param show all meshes */
showAllMeshes = ParamConfig.BOOLEAN(1);
}
const ParamsConfig = new MediapipeFaceMeshSopParamsConfig();
export class MediapipeFaceMeshSopNode extends TypedSopNode<MediapipeFaceMeshSopParamsConfig> {
paramsConfig = ParamsConfig;
static type() {
return 'mediapipeFaceMesh';
}
private _faceMesh = this._createFaceMesh();
private _currentCapturedFrame = 9999999;
private _webcamSnapshotCanvases: HTMLCanvasElement[] = [];
private _webcamSnapshots: TextureAndImage[] = [];
private _faceMeshObjects: Mesh[] = [];
initializeNode() {
this._forceTimeDependent();
}
private _graph_node: CoreGraphNode | undefined;
private _forceTimeDependent() {
if (!this._graph_node) {
this._graph_node = new CoreGraphNode(this.scene(), 'facemesh_update_object');
this._graph_node.addGraphInput(this.scene().timeController.graphNode);
this._graph_node.addPostDirtyHook('on_time_change', this.setDirty.bind(this));
}
}
async cook() {
if (isBooleanTrue(this.pv.showAllMeshes)) {
this.setObjects(this._faceMeshObjects);
} else {
const frame = this.scene().frame() % this._faceMeshObjects.length;
const currentObject = this._faceMeshObjects[frame];
if (currentObject) {
this.setObject(currentObject);
} else {
this.setObjects([]);
}
}
}
private _createFaceMesh() {
const faceMesh = new FaceMesh({
locateFile: (file: string) => {
return `https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh@0.4/${file}`;
},
});
faceMesh.onResults(this._onResults.bind(this));
return faceMesh;
}
private async _getHTMLVideoElement() {
const node = this.pv.webcam.nodeWithContext(NodeContext.COP);
if (!node) {
this.states.error.set(`node is not a COP node`);
this.cookController.endCook();
return;
}
if (!ALLOWED_COP_TYPES.includes(node.type() as CopType)) {
this.states.error.set(
`node type '${node.type()}' is not accepted by MediapipeFaceMesh (${ALLOWED_COP_TYPES.join(', ')})`
);
this.cookController.endCook();
return;
}
const webcamNode = node as AllowedCopType;
await webcamNode.compute();
const videoElement = webcamNode.HTMLVideoElement();
if (!videoElement) {
console.log('no video element found');
return;
}
return {videoElement};
}
private _videoSnapshotCanvas(videoElement: HTMLVideoElement) {
const canvasElement = document.createElement('canvas');
// videoWidth and videoHeight are more robust than .width and .height (see https://discourse.threejs.org/t/how-to-get-camera-video-texture-size-or-resolution/2879)
canvasElement.width = videoElement.videoWidth;
canvasElement.height = videoElement.videoHeight;
const canvasCtx = canvasElement.getContext('2d')!;
canvasCtx.drawImage(videoElement, 0, 0, canvasElement.width, canvasElement.height);
return canvasElement;
}
private static _canvasToTexture(canvasElement: HTMLCanvasElement, index: number): Promise<TextureAndImage> {
return new Promise((resolve) => {
const imgDataURL = canvasElement.toDataURL('image/png');
const image = new Image();
console.log(`start ${index}`);
image.onload = () => {
const texture = new Texture(image);
texture.name = `facemesh-texture-${index}`;
texture.encoding = sRGBEncoding;
texture.needsUpdate = true;
console.log(`done ${index}`);
resolve({texture, image});
};
image.src = imgDataURL;
});
}
private _activeHTMLVideoElement: HTMLVideoElement | undefined;
private async _initActiveHTMLVideoElement() {
const data = await this._getHTMLVideoElement();
if (!data) {
return;
}
const {videoElement} = data;
while (videoElement.paused) {
console.log('video is paused');
await CoreSleep.sleep(500);
}
this._activeHTMLVideoElement = videoElement;
}
private _captureAllowed() {
return this._currentCapturedFrame < this.pv.frames;
}
private async _capture() {
// 1. capture video feed into images
// so that we have the expected fps
console.log('capture start');
await this._initActiveHTMLVideoElement();
this._currentCapturedFrame = 0;
await this._captureWebCamSnapshots();
console.log('capture complete');
// 2. init face meshes
this._initFaceMeshObjects();
// 3. send the captured images to mediapipe
// which will then be processed to create the meshes
this._currentCapturedFrame = 0;
await this._sendToFaceMeshAll();
console.log('facemesh generation completed');
return;
}
private _captureWebCamSnapshots(): Promise<void> {
return new Promise((resolve) => {
this._webcamSnapshotCanvases = [];
this._webcamSnapshots = [];
this._captureSingleWebCamSnapshot(resolve);
});
}
private async _captureSingleWebCamSnapshot(resolve: WebCamSnapshotResolve) {
if (!this._activeHTMLVideoElement) {
console.log('no video found');
return;
}
if (!this._captureAllowed()) {
console.log('converting snapshots to images and textures...');
let i = 0;
for (let snapshotCanvas of this._webcamSnapshotCanvases) {
const snapshot = await MediapipeFaceMeshSopNode._canvasToTexture(snapshotCanvas, i);
this._webcamSnapshots.push(snapshot);
i++;
}
resolve();
} else {
const canvas = this._videoSnapshotCanvas(this._activeHTMLVideoElement);
this._webcamSnapshotCanvases.push(canvas);
this._currentCapturedFrame++;
console.log('capture', this._currentCapturedFrame);
setTimeout(() => {
this._captureSingleWebCamSnapshot(resolve);
}, 1000 / this.pv.fps);
}
}
private _initFaceMeshObjects() {
this._faceMeshObjects = [];
const count = this.pv.frames;
for (let i = 0; i < count; i++) {
const object = this._createFaceMeshObject(i);
this._faceMeshObjects.push(object);
}
}
private _onSendToFaceMeshSingleResolve: WebCamSnapshotResolve | undefined;
private async _sendToFaceMeshAll() {
this._faceMesh.setOptions({
enableFaceGeometry: true,
selfieMode: this.pv.selfieMode,
maxNumFaces: 1,
minDetectionConfidence: this.pv.minDetectionConfidence,
minTrackingConfidence: this.pv.maxDetectionConfidence,
});
for (let snapshot of this._webcamSnapshots) {
await this._sendToFaceMeshSingle(snapshot);
}
}
private _sendToFaceMeshSingle(snapshot: TextureAndImage) {
return new Promise((resolve) => {
this._onSendToFaceMeshSingleResolve = resolve;
this._faceMesh.send({image: snapshot.image});
});
}
private _onResults(results: Results) {
if (!this._captureAllowed()) {
return;
}
console.log(this._currentCapturedFrame);
const landmark = results.multiFaceLandmarks[0];
if (!landmark) {
console.error(`no landmark found (${this._currentCapturedFrame})`);
console.log('results', results);
return;
}
const faceMeshObject = this._faceMeshObjects[this._currentCapturedFrame];
let i = 0;
const positionAttribute = faceMeshObject.geometry.getAttribute('position');
const uvAttribute = faceMeshObject.geometry.getAttribute('uv');
const positionArray = positionAttribute.array as number[];
const uvArray = uvAttribute.array as number[];
const scale = this.pv.scale;
for (let pt of landmark) {
positionArray[i * 3 + 0] = (1 - pt.x) * scale;
positionArray[i * 3 + 1] = (1 - pt.y) * scale;
positionArray[i * 3 + 2] = pt.z * scale;
uvArray[i * 2 + 0] = pt.x;
uvArray[i * 2 + 1] = 1 - pt.y;
i++;
}
positionAttribute.needsUpdate = true;
uvAttribute.needsUpdate = true;
this._updateMaterial(this._currentCapturedFrame);
this._currentCapturedFrame++;
if (this._onSendToFaceMeshSingleResolve) {
this._onSendToFaceMeshSingleResolve();
}
}
private _updateMaterial(currentCapturedFrame: number) {
const faceMeshObject = this._faceMeshObjects[currentCapturedFrame];
const material = faceMeshObject.material;
if (!CoreType.isArray(material)) {
const meshBasicMaterial = material as MeshBasicMaterial;
const texture = this._webcamSnapshots[currentCapturedFrame].texture;
meshBasicMaterial.map = texture;
meshBasicMaterial.needsUpdate = true;
}
}
private _createFaceMeshObject(index: number) {
const geometry = new BufferGeometry();
const positions: number[] = [];
const uvs: number[] = [];
for (let i = 0; i < FACEMESH_POINTS_COUNT; i++) {
positions.push(i);
positions.push(i);
positions.push(i);
uvs.push(i);
uvs.push(i);
}
const indices: number[] = [];
const polyCount = FACEMESH_TESSELATION.length / 3;
for (let i = 0; i < polyCount; i++) {
indices.push(FACEMESH_TESSELATION[i * 3 + 0][0]);
indices.push(FACEMESH_TESSELATION[i * 3 + 1][0]);
indices.push(FACEMESH_TESSELATION[i * 3 + 2][0]);
}
geometry.setAttribute('position', new BufferAttribute(new Float32Array(positions), 3));
geometry.setAttribute('uv', new BufferAttribute(new Float32Array(uvs), 2));
geometry.setIndex(indices);
const object = this.createObject(geometry, ObjectType.MESH, new MeshBasicMaterial());
object.name = `${this.path()}-${index}`;
return object;
}
static PARAM_CALLBACK_capture(node: MediapipeFaceMeshSopNode) {
node._paramCallbackCapture();
}
private _paramCallbackCapture() {
this._capture();
}
} | the_stack |
import path from "path";
import minimatch from "minimatch";
import type { PluginConfig, TransformerExtras } from "ts-patch";
import ts from "typescript";
import { assertDefined } from "./assert";
import {
EventBusMapInterface,
RuleInterface,
EventTransformInterface,
EventBusWhenInterface,
FunctionInterface,
makeFunctionlessChecker,
TsFunctionParameter,
} from "./checker";
import { ErrorCodes, SynthError } from "./error-code";
import { BinaryOp } from "./expression";
import { FunctionlessNode } from "./node";
import { anyOf, hasParent } from "./util";
export default compile;
/**
* Configuration options for the functionless TS transform.
*/
export interface FunctionlessConfig extends PluginConfig {
/**
* Glob to exclude
*/
exclude?: string[];
}
/**
* TypeScript Transformer which transforms functionless functions, such as `AppsyncResolver`,
* into an AST that can be interpreted at CDK synth time to produce VTL templates and AppSync
* Resolver configurations.
*
* @param program the TypeScript {@link ts.Program}
* @param config the {@link FunctionlessConfig}.
* @param _extras
* @returns the transformer
*/
export function compile(
program: ts.Program,
_config?: FunctionlessConfig,
_extras?: TransformerExtras
): ts.TransformerFactory<ts.SourceFile> {
const excludeMatchers = _config?.exclude
? _config.exclude.map((pattern) => minimatch.makeRe(path.resolve(pattern)))
: [];
const checker = makeFunctionlessChecker(program.getTypeChecker());
return (ctx) => {
const functionless = ts.factory.createUniqueName("functionless");
return (sf) => {
// Do not transform any of the files matched by "exclude"
if (excludeMatchers.some((matcher) => matcher.test(sf.fileName))) {
return sf;
}
const functionlessContext = {
requireFunctionless: false,
get functionless() {
this.requireFunctionless = true;
return functionless;
},
};
const functionlessImport = ts.factory.createImportDeclaration(
undefined,
undefined,
ts.factory.createImportClause(
false,
undefined,
ts.factory.createNamespaceImport(functionless)
),
ts.factory.createStringLiteral("functionless")
);
const statements = sf.statements.map(
(stmt) => visitor(stmt) as ts.Statement
);
return ts.factory.updateSourceFile(
sf,
[
// only require functionless if it is used.
...(functionlessContext.requireFunctionless
? [functionlessImport]
: []),
...statements,
],
sf.isDeclarationFile,
sf.referencedFiles,
sf.typeReferenceDirectives,
sf.hasNoDefaultLib,
sf.libReferenceDirectives
);
function visitor(node: ts.Node): ts.Node | ts.Node[] {
const visit = () => {
if (checker.isAppsyncResolver(node)) {
return visitAppsyncResolver(node as ts.NewExpression);
} else if (checker.isNewStepFunction(node)) {
return visitStepFunction(node as ts.NewExpression);
} else if (checker.isReflectFunction(node)) {
return errorBoundary(() =>
toFunction("FunctionDecl", node.arguments[0])
);
} else if (checker.isEventBusWhenFunction(node)) {
return visitEventBusWhen(node);
} else if (checker.isRuleMapFunction(node)) {
return visitEventBusMap(node);
} else if (checker.isNewRule(node)) {
return visitRule(node);
} else if (checker.isNewEventTransform(node)) {
return visitEventTransform(node);
} else if (checker.isNewFunctionlessFunction(node)) {
return visitFunction(node, ctx);
} else if (checker.isApiIntegration(node)) {
return visitApiIntegration(node);
}
return node;
};
// keep processing the children of the updated node.
return ts.visitEachChild(visit(), visitor, ctx);
}
/**
* Catches any errors and wraps them in a {@link Err} node.
*/
function errorBoundary<T extends ts.Node>(
func: () => T
): T | ts.NewExpression {
try {
return func();
} catch (err) {
const error =
err instanceof Error ? err : Error("Unknown compiler error.");
return newExpr("Err", [
ts.factory.createNewExpression(
ts.factory.createIdentifier(error.name),
undefined,
[ts.factory.createStringLiteral(error.message)]
),
]);
}
}
function visitStepFunction(call: ts.NewExpression): ts.Node {
return ts.factory.updateNewExpression(
call,
call.expression,
call.typeArguments,
call.arguments?.map((arg) =>
ts.isFunctionExpression(arg) || ts.isArrowFunction(arg)
? errorBoundary(() => toFunction("FunctionDecl", arg))
: arg
)
);
}
function visitRule(call: RuleInterface): ts.Node {
const [one, two, three, impl] = call.arguments;
return ts.factory.updateNewExpression(
call,
call.expression,
call.typeArguments,
[
one,
two,
three,
errorBoundary(() => toFunction("FunctionDecl", impl)),
]
);
}
function visitEventTransform(call: EventTransformInterface): ts.Node {
const [impl, ...rest] = call.arguments;
return ts.factory.updateNewExpression(
call,
call.expression,
call.typeArguments,
[errorBoundary(() => toFunction("FunctionDecl", impl)), ...rest]
);
}
function visitEventBusWhen(call: EventBusWhenInterface): ts.Node {
// support the 2 or 3 parameter when.
if (call.arguments.length === 3) {
const [one, two, impl] = call.arguments;
return ts.factory.updateCallExpression(
call,
call.expression,
call.typeArguments,
[one, two, errorBoundary(() => toFunction("FunctionDecl", impl))]
);
} else {
const [one, impl] = call.arguments;
return ts.factory.updateCallExpression(
call,
call.expression,
call.typeArguments,
[one, errorBoundary(() => toFunction("FunctionDecl", impl))]
);
}
}
function visitEventBusMap(call: EventBusMapInterface): ts.Node {
const [impl] = call.arguments;
return ts.factory.updateCallExpression(
call,
call.expression,
call.typeArguments,
[errorBoundary(() => toFunction("FunctionDecl", impl))]
);
}
function visitAppsyncResolver(call: ts.NewExpression): ts.Node {
if (call.arguments?.length === 1) {
const impl = call.arguments[0];
if (ts.isFunctionExpression(impl) || ts.isArrowFunction(impl)) {
return ts.factory.updateNewExpression(
call,
call.expression,
call.typeArguments,
[errorBoundary(() => toFunction("FunctionDecl", impl, 1))]
);
}
}
return call;
}
function visitFunction(
func: FunctionInterface,
context: ts.TransformationContext
): ts.Node {
const [_one, _two, _three, funcDecl] =
func.arguments.length === 4
? func.arguments
: [
func.arguments[0],
func.arguments[1],
undefined,
func.arguments[2],
];
return ts.factory.updateNewExpression(
func,
func.expression,
func.typeArguments,
[
_one,
_two,
...(_three ? [_three] : []),
errorBoundary(() => toNativeFunction(funcDecl, context)),
]
);
}
interface NativeExprContext {
preWarmContext: ts.Identifier;
closureNode: TsFunctionParameter;
/**
* Register an {@link IntegrationInvocation} found when processing a native closure.
*
* @param node - should be an {@link Integration}
* @param args - should be an array of {@link Argument}
*/
registerIntegration: (
node: ts.Expression,
args: ts.ArrayLiteralExpression
) => void;
}
/**
* A native function prepares a closure to be serialized,
* transforms functionless {@link Integrations} to be invoked at runtime,
* and extracts information needed to synthesize the Stack.
*
* Native Functions do not allow the creation of resources, CDK constructs or functionless.
*
* 1. Extracts functionless {@link Integrations} from the closure
* 2. Wraps the closure in another arrow function which accepts a {@link NativePrewarmContext}.
* 1. During synthesize (ex:, in a lambda {@link Function}) a prewarm context is generated
* and fed into the outer, generated closure.
* 2. The {@link NativePreWarmContext} is a client/object cache which can be used to run once
* before the first invocation of a lambda function.
* 3. Rewrites all of the integrations to invoke `await integration.native.call(args)` instead of `integration(args)`
* Also tries to simplify integration references to be outside of the closure.
* This reduces the amount of code and data that @functionless/nodejs-closure-serializer (a Pulumi closure serializer fork)
* tries to serialize during synthesis.
* 4. Returns the {@link ParameterDecl}s for the closure
*
* @see Function for an example of how this is used.
*
* Input
*
* ```ts
* const bus = new EventBus() // an example of an Integration, could be any Integration
*
* (arg1: string) => {
* bus.putEvents({ source: "src" })
* }
* ```
*
* Output
*
* ```ts
* const bus = new EventBus()
* new NativeFunctionDecl(
* [new ParameterDecl("arg1")], // parameters
* (prewarmContext: NativePreWarmContext) =>
* (arg1: string) => {
* // call can make use of the cached clients in prewarmContext to avoid duplicate inline effect
* await bus.native.call(prewarmContext, { source: "src" });
* },
* [bus] // integrations
* );
* ```
*/
function toNativeFunction(
impl: TsFunctionParameter,
context: ts.TransformationContext
): ts.NewExpression {
if (
!ts.isFunctionDeclaration(impl) &&
!ts.isArrowFunction(impl) &&
!ts.isFunctionExpression(impl)
) {
throw new Error(
`Functionless reflection only supports function parameters with bodies, no signature only declarations or references. Found ${impl.getText()}.`
);
}
if (impl.body === undefined) {
throw new Error(
`cannot parse declaration-only function: ${impl.getText()}`
);
}
// collection of integrations that are extracted from the closure
const integrations: {
expr: ts.Expression;
args: ts.ArrayLiteralExpression;
}[] = [];
// a reference to a client/object cache which the integrations can use
const preWarmContext =
context.factory.createUniqueName("preWarmContext");
// Context object which is available when transforming the tree
const nativeExprContext: NativeExprContext = {
// a reference to a prewarm context that will be passed into the closure during synthesis/runtime
preWarmContext,
// the closure node used to determine if variables are inside or outside of the closure
closureNode: impl,
// pass up integrations from inside of the closure
registerIntegration: (integ, args) =>
integrations.push({ expr: integ, args }),
};
const body = toNativeExpr(
impl.body,
context,
nativeExprContext
) as ts.ConciseBody;
// rebuilt the closure with the updated body
const closure = ts.factory.createArrowFunction(
impl.modifiers,
impl.typeParameters,
impl.parameters,
impl.type,
undefined,
body
);
return newExpr("NativeFunctionDecl", [
ts.factory.createArrayLiteralExpression(
impl.parameters
.map((param) => param.name.getText())
.map((arg) =>
newExpr("ParameterDecl", [ts.factory.createStringLiteral(arg)])
)
),
// (prewarmContext) => closure;
context.factory.createArrowFunction(
undefined,
undefined,
[
context.factory.createParameterDeclaration(
undefined,
undefined,
undefined,
preWarmContext,
undefined,
undefined,
undefined
),
],
undefined,
undefined,
closure
),
context.factory.createArrayLiteralExpression(
integrations.map(({ expr, args }) =>
context.factory.createObjectLiteralExpression([
context.factory.createPropertyAssignment("integration", expr),
context.factory.createPropertyAssignment("args", args),
])
)
),
]);
}
function toNativeExpr(
node: ts.Node,
context: ts.TransformationContext,
nativeExprContext: NativeExprContext
): ts.Node | undefined {
if (ts.isCallExpression(node)) {
// Integration nodes have a static "kind" property.
if (isIntegrationNode(node.expression)) {
const outOfScopeIntegrationReference = getOutOfScopeValueNode(
node.expression,
nativeExprContext.closureNode
);
if (!outOfScopeIntegrationReference) {
// integration variables can be CDK constructs which will fail serialization.
throw Error(
"Integration Variable must be defined out of scope: " +
node.expression.getText()
);
}
// add the function identifier to the integrations
nativeExprContext.registerIntegration(
outOfScopeIntegrationReference,
// try to capture the arguments into the integration to use during synth (integration.native.bind).
context.factory.createArrayLiteralExpression(
node.arguments.map((arg) => {
return toExpr(arg, nativeExprContext.closureNode);
})
)
);
// call the integration call function with the prewarm context and arguments
// At this point, we know native will not be undefined
// await integration.native.call(args, preWarmContext)
// TODO: Support both sync and async function invocations: https://github.com/functionless/functionless/issues/105
return context.factory.createAwaitExpression(
context.factory.createCallExpression(
context.factory.createPropertyAccessExpression(
context.factory.createPropertyAccessExpression(
node.expression,
"native"
),
"call"
),
undefined,
[
context.factory.createArrayLiteralExpression(node.arguments),
nativeExprContext.preWarmContext,
]
)
);
}
} else if (ts.isNewExpression(node)) {
const newType = checker.getTypeAtLocation(node);
// cannot create new resources in native runtime code.
const functionlessKind = checker.getFunctionlessTypeKind(newType);
if (checker.getFunctionlessTypeKind(newType)) {
throw new SynthError(
ErrorCodes.Unsupported_initialization_of_resources_in_function,
`Cannot initialize new resources in a native function, found ${functionlessKind}.`
);
} else if (checker.isCDKConstruct(newType)) {
throw new SynthError(
ErrorCodes.Unsupported_initialization_of_resources_in_function,
`Cannot initialize new CDK resources in a native function, found ${
newType.getSymbol()?.name
}.`
);
}
}
// let everything else fall through, process their children too
return ts.visitEachChild(
node,
(node) => toNativeExpr(node, context, nativeExprContext),
context
);
}
function toFunction(
type: "FunctionDecl" | "FunctionExpr",
impl: ts.Expression,
dropArgs?: number
): ts.Expression {
if (
!ts.isFunctionDeclaration(impl) &&
!ts.isArrowFunction(impl) &&
!ts.isFunctionExpression(impl)
) {
throw new Error(
`Functionless reflection only supports function parameters with bodies, no signature only declarations or references. Found ${impl.getText()}.`
);
}
const params =
dropArgs === undefined
? impl.parameters
: impl.parameters.slice(dropArgs);
if (impl.body === undefined) {
throw new Error(
`cannot parse declaration-only function: ${impl.getText()}`
);
}
const body = ts.isBlock(impl.body)
? toExpr(impl.body, impl)
: newExpr("BlockStmt", [
ts.factory.createArrayLiteralExpression([
newExpr("ReturnStmt", [toExpr(impl.body, impl)]),
]),
]);
return newExpr(type, [
ts.factory.createArrayLiteralExpression(
params
.map((param) => param.name.getText())
.map((arg) =>
newExpr("ParameterDecl", [ts.factory.createStringLiteral(arg)])
)
),
body,
]);
}
function visitApiIntegration(node: ts.NewExpression): ts.Node {
const [props, request, response, errors] = node.arguments ?? [];
return errorBoundary(() =>
ts.factory.updateNewExpression(
node,
node.expression,
node.typeArguments,
[
props,
toFunction("FunctionDecl", request),
ts.isObjectLiteralExpression(response)
? visitApiErrors(response)
: toFunction("FunctionDecl", response),
...(errors && ts.isObjectLiteralExpression(errors)
? [visitApiErrors(errors)]
: []),
]
)
);
}
function visitApiErrors(errors: ts.ObjectLiteralExpression) {
return errorBoundary(() =>
ts.factory.updateObjectLiteralExpression(
errors,
errors.properties.map((prop) =>
ts.isPropertyAssignment(prop)
? ts.factory.updatePropertyAssignment(
prop,
prop.name,
toFunction("FunctionDecl", prop.initializer)
)
: prop
)
)
);
}
function toExpr(
node: ts.Node | undefined,
scope: ts.Node
): ts.Expression {
if (node === undefined) {
return ts.factory.createIdentifier("undefined");
} else if (ts.isArrowFunction(node) || ts.isFunctionExpression(node)) {
return toFunction("FunctionExpr", node);
} else if (ts.isExpressionStatement(node)) {
return newExpr("ExprStmt", [toExpr(node.expression, scope)]);
} else if (ts.isCallExpression(node) || ts.isNewExpression(node)) {
const exprType = checker.getTypeAtLocation(node.expression);
const functionBrand = exprType.getProperty("__functionBrand");
let signature: ts.Signature | undefined;
if (functionBrand !== undefined) {
const functionType = checker.getTypeOfSymbolAtLocation(
functionBrand,
node.expression
);
const signatures = checker.getSignaturesOfType(
functionType,
ts.SignatureKind.Call
);
if (signatures.length === 1) {
signature = signatures[0];
} else {
throw new Error(
"Lambda Functions with multiple signatures are not currently supported."
);
}
} else {
signature = checker.getResolvedSignature(node);
}
if (signature && signature.parameters.length > 0) {
return newExpr(ts.isCallExpression(node) ? "CallExpr" : "NewExpr", [
toExpr(node.expression, scope),
ts.factory.createArrayLiteralExpression(
signature.parameters.map((parameter, i) =>
newExpr("Argument", [
(parameter.declarations?.[0] as ts.ParameterDeclaration)
?.dotDotDotToken
? newExpr("ArrayLiteralExpr", [
ts.factory.createArrayLiteralExpression(
node.arguments
?.slice(i)
.map((x) => toExpr(x, scope)) ?? []
),
])
: toExpr(node.arguments?.[i], scope),
ts.factory.createStringLiteral(parameter.name),
])
)
),
]);
} else {
return newExpr("CallExpr", [
toExpr(node.expression, scope),
ts.factory.createArrayLiteralExpression(
node.arguments?.map((arg) =>
newExpr("Argument", [
toExpr(arg, scope),
ts.factory.createIdentifier("undefined"),
])
) ?? []
),
]);
}
} else if (ts.isBlock(node)) {
return newExpr("BlockStmt", [
ts.factory.createArrayLiteralExpression(
node.statements.map((x) => toExpr(x, scope))
),
]);
} else if (ts.isIdentifier(node)) {
if (node.text === "undefined") {
return newExpr("UndefinedLiteralExpr", []);
} else if (node.text === "null") {
return newExpr("NullLiteralExpr", []);
}
if (isIntegrationNode(node)) {
// if this is a reference to a Table or Lambda, retain it
return ref(node);
}
const symbol = checker.getSymbolAtLocation(node);
/**
* If the identifier is not within the closure, we attempt to enclose the reference in its own closure.
* const val = "hello";
* reflect(() => return { value: val }; );
*
* result
*
* return { value: () => val };
*/
if (symbol) {
const ref = outOfScopeIdentifierToRef(symbol, scope);
if (ref) {
return ref;
}
}
return newExpr("Identifier", [
ts.factory.createStringLiteral(node.text),
]);
} else if (ts.isPropertyAccessExpression(node)) {
if (isIntegrationNode(node)) {
// if this is a reference to a Table or Lambda, retain it
return ref(node);
}
const type = checker.getTypeAtLocation(node.name);
return newExpr("PropAccessExpr", [
toExpr(node.expression, scope),
ts.factory.createStringLiteral(node.name.text),
type
? ts.factory.createStringLiteral(checker.typeToString(type))
: ts.factory.createIdentifier("undefined"),
]);
} else if (ts.isElementAccessExpression(node)) {
const type = checker.getTypeAtLocation(node.argumentExpression);
return newExpr("ElementAccessExpr", [
toExpr(node.expression, scope),
toExpr(node.argumentExpression, scope),
type
? ts.factory.createStringLiteral(checker.typeToString(type))
: ts.factory.createIdentifier("undefined"),
]);
} else if (
ts.isVariableStatement(node) &&
node.declarationList.declarations.length === 1
) {
return toExpr(node.declarationList.declarations[0], scope);
} else if (ts.isVariableDeclaration(node)) {
return newExpr("VariableStmt", [
ts.factory.createStringLiteral(node.name.getText()),
...(node.initializer ? [toExpr(node.initializer, scope)] : []),
]);
} else if (ts.isIfStatement(node)) {
return newExpr("IfStmt", [
// when
toExpr(node.expression, scope),
// then
toExpr(node.thenStatement, scope),
// else
...(node.elseStatement ? [toExpr(node.elseStatement, scope)] : []),
]);
} else if (ts.isConditionalExpression(node)) {
return newExpr("ConditionExpr", [
// when
toExpr(node.condition, scope),
// then
toExpr(node.whenTrue, scope),
// else
toExpr(node.whenFalse, scope),
]);
} else if (ts.isBinaryExpression(node)) {
const op = getOperator(node.operatorToken);
if (op === undefined) {
throw new Error(
`invalid Binary Operator: ${node.operatorToken.getText()}`
);
}
return newExpr("BinaryExpr", [
toExpr(node.left, scope),
ts.factory.createStringLiteral(op),
toExpr(node.right, scope),
]);
} else if (ts.isPrefixUnaryExpression(node)) {
if (
node.operator !== ts.SyntaxKind.ExclamationToken &&
node.operator !== ts.SyntaxKind.MinusToken
) {
throw new Error(
`invalid Unary Operator: ${ts.tokenToString(node.operator)}`
);
}
return newExpr("UnaryExpr", [
ts.factory.createStringLiteral(
assertDefined(
ts.tokenToString(node.operator),
`Unary operator token cannot be stringified: ${node.operator}`
)
),
toExpr(node.operand, scope),
]);
} else if (ts.isReturnStatement(node)) {
return newExpr(
"ReturnStmt",
node.expression
? [toExpr(node.expression, scope)]
: [newExpr("NullLiteralExpr", [])]
);
} else if (ts.isObjectLiteralExpression(node)) {
return newExpr("ObjectLiteralExpr", [
ts.factory.createArrayLiteralExpression(
node.properties.map((x) => toExpr(x, scope))
),
]);
} else if (ts.isPropertyAssignment(node)) {
return newExpr("PropAssignExpr", [
ts.isStringLiteral(node.name) || ts.isIdentifier(node.name)
? string(node.name.text)
: toExpr(node.name, scope),
toExpr(node.initializer, scope),
]);
} else if (ts.isComputedPropertyName(node)) {
return newExpr("ComputedPropertyNameExpr", [
toExpr(node.expression, scope),
]);
} else if (ts.isShorthandPropertyAssignment(node)) {
return newExpr("PropAssignExpr", [
newExpr("Identifier", [
ts.factory.createStringLiteral(node.name.text),
]),
toExpr(node.name, scope),
]);
} else if (ts.isSpreadAssignment(node)) {
return newExpr("SpreadAssignExpr", [toExpr(node.expression, scope)]);
} else if (ts.isSpreadElement(node)) {
return newExpr("SpreadElementExpr", [toExpr(node.expression, scope)]);
} else if (ts.isArrayLiteralExpression(node)) {
return newExpr("ArrayLiteralExpr", [
ts.factory.updateArrayLiteralExpression(
node,
node.elements.map((x) => toExpr(x, scope))
),
]);
} else if (node.kind === ts.SyntaxKind.NullKeyword) {
return newExpr("NullLiteralExpr", [
ts.factory.createIdentifier("false"),
]);
} else if (ts.isNumericLiteral(node)) {
return newExpr("NumberLiteralExpr", [node]);
} else if (
ts.isStringLiteral(node) ||
ts.isNoSubstitutionTemplateLiteral(node)
) {
return newExpr("StringLiteralExpr", [node]);
} else if (ts.isLiteralExpression(node)) {
// const type = checker.getTypeAtLocation(node);
// if (type.symbol.escapedName === "boolean") {
// return newExpr("BooleanLiteralExpr", [node]);
// }
} else if (
node.kind === ts.SyntaxKind.TrueKeyword ||
node.kind === ts.SyntaxKind.FalseKeyword
) {
return newExpr("BooleanLiteralExpr", [node as ts.Expression]);
} else if (ts.isForOfStatement(node) || ts.isForInStatement(node)) {
if (ts.isVariableDeclarationList(node.initializer)) {
if (node.initializer.declarations.length === 1) {
const varDecl = node.initializer.declarations[0];
if (ts.isIdentifier(varDecl.name)) {
// for (const i in list)
return newExpr(
ts.isForOfStatement(node) ? "ForOfStmt" : "ForInStmt",
[
toExpr(varDecl, scope),
toExpr(node.expression, scope),
toExpr(node.statement, scope),
]
);
} else if (ts.isArrayBindingPattern(varDecl.name)) {
// for (const [a, b] in list)
}
}
}
} else if (ts.isTemplateExpression(node)) {
const exprs = [];
if (node.head.text) {
exprs.push(string(node.head.text));
}
for (const span of node.templateSpans) {
exprs.push(toExpr(span.expression, scope));
if (span.literal.text) {
exprs.push(string(span.literal.text));
}
}
return newExpr("TemplateExpr", [
ts.factory.createArrayLiteralExpression(exprs),
]);
} else if (ts.isBreakStatement(node)) {
return newExpr("BreakStmt", []);
} else if (ts.isContinueStatement(node)) {
return newExpr("ContinueStmt", []);
} else if (ts.isTryStatement(node)) {
return newExpr("TryStmt", [
toExpr(node.tryBlock, scope),
node.catchClause
? toExpr(node.catchClause, scope)
: ts.factory.createIdentifier("undefined"),
node.finallyBlock
? toExpr(node.finallyBlock, scope)
: ts.factory.createIdentifier("undefined"),
]);
} else if (ts.isCatchClause(node)) {
return newExpr("CatchClause", [
node.variableDeclaration
? toExpr(node.variableDeclaration, scope)
: ts.factory.createIdentifier("undefined"),
toExpr(node.block, scope),
]);
} else if (ts.isThrowStatement(node)) {
return newExpr("ThrowStmt", [toExpr(node.expression, scope)]);
} else if (ts.isTypeOfExpression(node)) {
return newExpr("TypeOfExpr", [toExpr(node.expression, scope)]);
} else if (ts.isWhileStatement(node)) {
return newExpr("WhileStmt", [
toExpr(node.expression, scope),
ts.isBlock(node.statement)
? toExpr(node.statement, scope)
: // re-write a standalone statement as as BlockStmt
newExpr("BlockStmt", [
ts.factory.createArrayLiteralExpression([
toExpr(node.statement, scope),
]),
]),
]);
} else if (ts.isDoStatement(node)) {
return newExpr("DoStmt", [
ts.isBlock(node.statement)
? toExpr(node.statement, scope)
: // re-write a standalone statement as as BlockStmt
newExpr("BlockStmt", [
ts.factory.createArrayLiteralExpression([
toExpr(node.statement, scope),
]),
]),
toExpr(node.expression, scope),
]);
} else if (ts.isParenthesizedExpression(node)) {
return toExpr(node.expression, scope);
} else if (ts.isAsExpression(node)) {
return toExpr(node.expression, scope);
} else if (ts.isTypeAssertionExpression(node)) {
return toExpr(node.expression, scope);
} else if (ts.isNonNullExpression(node)) {
return toExpr(node.expression, scope);
} else if (node.kind === ts.SyntaxKind.ThisKeyword) {
// assuming that this is used in a valid location, create a closure around that instance.
return ref(ts.factory.createIdentifier("this"));
}
throw new Error(
`unhandled node: ${node.getText()} ${ts.SyntaxKind[node.kind]}`
);
}
function ref(node: ts.Expression) {
return newExpr("ReferenceExpr", [
ts.factory.createStringLiteral(exprToString(node)),
ts.factory.createArrowFunction(
undefined,
undefined,
[],
undefined,
undefined,
node
),
]);
}
/**
* Follow the parent of the symbol to determine if the identifier shares the same scope as the current closure being compiled.
* If not within the scope of the current closure, return a reference that returns the external value if possible.
* const val = "hello";
* reflect(() => return { value: val }; );
*
* result
*
* return { value: () => val };
*/
function outOfScopeIdentifierToRef(
symbol: ts.Symbol,
scope: ts.Node
): ts.NewExpression | undefined {
if (symbol) {
if (symbol.valueDeclaration) {
// Identifies if Shorthand Property Assignment value declarations return the shorthand prop assignment and not the value.
// const value = "hello"
// const v = { value } <== shorthand prop assignment.
// The checker supports getting the value assignment symbol, recursively call this method on the new symbol instead.
if (ts.isShorthandPropertyAssignment(symbol.valueDeclaration)) {
const updatedSymbol = checker.getShorthandAssignmentValueSymbol(
symbol.valueDeclaration
);
return updatedSymbol
? outOfScopeIdentifierToRef(updatedSymbol, scope)
: undefined;
} else if (ts.isVariableDeclaration(symbol.valueDeclaration)) {
if (
symbol.valueDeclaration.initializer &&
!hasParent(symbol.valueDeclaration, scope)
) {
return ref(ts.factory.createIdentifier(symbol.name));
}
}
}
}
return;
}
/**
* Flattens {@link ts.BindingElement} (destructured assignments) to a series of
* {@link ts.ElementAccessExpression} or {@link ts.PropertyAccessExpression}
*
* Caveat: It is not possible to flatten a destructured ParameterDeclaration (({ a }) => {}).
* Use {@link getDestructuredDeclaration} to determine if the {@link ts.BindingElement} is
* {@link ts.VariableDeclaration} or a {@link ts.ParameterDeclaration}.
*
* given a
*
* { a } = b;
* -> b.a;
*
* { x: a } = b;
* -> b.x;
*
* { "x-x": a } = b;
* b["x-x"];
*
* { b: { a } } = c;
* -> c.b.a;
*
* [a] = l;
* -> l[0];
*
* [{ a }] = l;
* -> l[0].a;
*
* { a } = b.c;
* -> b.c.a;
*
* { [key]: a } = b;
* b[key];
*/
function flattenDestructuredAssignment(
element: ts.BindingElement
): ts.ElementAccessExpression | ts.PropertyAccessExpression {
// if the binding renames the property, get the original
// { a : x } -> a
// { a } -> a
// [a] -> 0
const name = ts.isArrayBindingPattern(element.parent)
? element.pos
: // binding renames the property or is a nested binding pattern.
element.propertyName
? element.propertyName
: // the "name" can be a binding pattern. In that case the propertyName will be set.
(element.name as ts.Identifier);
const getParent = () => {
// { a } = b;
if (ts.isVariableDeclaration(element.parent.parent)) {
if (!element.parent.parent.initializer) {
throw Error(
"Expected a initializer on a destructured assignment: " +
element.getText()
);
}
return element.parent.parent.initializer;
} else if (ts.isBindingElement(element.parent.parent)) {
return flattenDestructuredAssignment(element.parent.parent);
} else {
throw Error(
"Cannot flatten destructured parameter: " + element.getText()
);
}
};
const parent = getParent();
// always use element access as this will work for all possible values.
// [parent][name]
return typeof name !== "number" && ts.isIdentifier(name)
? ts.factory.createPropertyAccessExpression(parent, name)
: ts.factory.createElementAccessExpression(
parent,
typeof name !== "number" && ts.isComputedPropertyName(name)
? name.expression
: name
);
}
/**
* Finds the top level declaration of a destructured binding element.
* Supports arbitrary nesting.
*
* const { a } = b; -> VariableDeclaration { initializer = b }
* const [a] = b; -> VariableDeclaration { initializer = b }
* ({ a }) => {} -> ParameterDeclaration { { a } }
* ([a]) => {} -> ParameterDeclaration { { a } }
*/
function getDestructuredDeclaration(
element: ts.BindingElement
): ts.VariableDeclaration | ts.ParameterDeclaration {
if (ts.isBindingElement(element.parent.parent)) {
return getDestructuredDeclaration(element.parent.parent);
}
return element.parent.parent;
}
/**
* Attempts to find the a version of a reference that is outside of a certain scope.
*
* This is useful for finding variables that have been instantiated outside of a closure, but
* renamed inside of the closure.
*
* When serializing the lambda functions, we want references from outside of the closure if possible.
*
* ```ts
* const bus = new EventBus()
* new Function(() => {
* const busbus = bus;
* busbus.putEvents(...)
* })
* ```
*
* Can also follow property access.
*
* ```ts
* const x = { y : () => {} };
*
* () => {
* const z = x;
* z.y() // x.y() is returned
* }
* ```
*
* getOutOfScopeValueNode(z.y) => x.y
*
* ```ts
* const x = () => {};
*
* () => {
* const z = { y: x };
* z.y()
* }
* ```
*
* getOutOfScopeValueNode(z.y) => x
*
* The call to busbus can be resolved to bus if the scope is the array function.
*/
function getOutOfScopeValueNode(
expression: ts.Expression,
scope: ts.Node
): ts.Expression | undefined {
const symbol = checker.getSymbolAtLocation(expression);
if (symbol) {
if (isSymbolOutOfScope(symbol, scope)) {
return expression;
} else {
if (ts.isIdentifier(expression)) {
if (symbol.valueDeclaration) {
if (
ts.isVariableDeclaration(symbol.valueDeclaration) &&
symbol.valueDeclaration.initializer
) {
return getOutOfScopeValueNode(
symbol.valueDeclaration.initializer,
scope
);
} else if (ts.isBindingElement(symbol.valueDeclaration)) {
/* when we find an identifier that was created using a binding assignment
flatten it and run the flattened form through again.
const b = { a: 1 };
() => {
const c = b;
const { a } = c;
}
-> b["a"];
*/
const flattened = flattenDestructuredAssignment(
symbol.valueDeclaration
);
return getOutOfScopeValueNode(flattened, scope);
}
}
}
}
}
if (
ts.isPropertyAccessExpression(expression) ||
ts.isElementAccessExpression(expression)
) {
if (symbol && symbol.valueDeclaration) {
if (
ts.isPropertyAssignment(symbol.valueDeclaration) &&
anyOf(
ts.isIdentifier,
ts.isPropertyAccessExpression,
ts.isElementAccessExpression
)(symbol.valueDeclaration.initializer)
) {
// this variable is assigned to by another variable, follow that node
return getOutOfScopeValueNode(
symbol.valueDeclaration.initializer,
scope
);
}
}
// this node is assigned a value, attempt to rewrite the parent
const outOfScope = getOutOfScopeValueNode(
expression.expression,
scope
);
return outOfScope
? ts.isElementAccessExpression(expression)
? ts.factory.updateElementAccessExpression(
expression,
outOfScope,
expression.argumentExpression
)
: ts.factory.updatePropertyAccessExpression(
expression,
outOfScope,
expression.name
)
: undefined;
}
return undefined;
}
/**
* Checks to see if a symbol is defined with the given scope.
*
* Any symbol that has no declaration or has a value declaration in the scope is considered to be in scope.
* Imports are considered out of scope.
*
* ```ts
* () => { // scope
* const x = "y";
* x // in scope
* }
* ```
*
* ```ts
* const x = "y"; // out of scope
* () => { // scope
* x // in scope
* }
* ```
*
* ```ts
* import x from y;
*
* () => { // scope
* x // out of scope
* }
* ```
*
* ```ts
* () => {
* const { x } = y;
* x // in scope
* }
* ```
*
* ```ts
* ({ x }) => {
* x // in scope
* }
* ```
*/
function isSymbolOutOfScope(symbol: ts.Symbol, scope: ts.Node): boolean {
if (symbol.valueDeclaration) {
if (ts.isShorthandPropertyAssignment(symbol.valueDeclaration)) {
const updatedSymbol = checker.getShorthandAssignmentValueSymbol(
symbol.valueDeclaration
);
return updatedSymbol
? isSymbolOutOfScope(updatedSymbol, scope)
: false;
} else if (ts.isVariableDeclaration(symbol.valueDeclaration)) {
return !hasParent(symbol.valueDeclaration, scope);
} else if (ts.isBindingElement(symbol.valueDeclaration)) {
/*
check if the binding element's declaration is within the scope or not.
example: if the scope if func's body
({ a }) => {
const { b } = a;
const func = ({ c }) => {
const { d: { x, y } } = b;
}
}
// in scope: c, x, y
// out of scope: a, b
*/
const declaration = getDestructuredDeclaration(
symbol.valueDeclaration
);
return !hasParent(declaration, scope);
}
} else if (symbol.declarations && symbol.declarations.length > 0) {
const [decl] = symbol.declarations;
// import x from y
if (
ts.isImportClause(decl) ||
ts.isImportSpecifier(decl) ||
ts.isNamespaceImport(decl)
) {
return true;
}
}
return false;
}
function exprToString(node: ts.Expression): string {
if (ts.isIdentifier(node)) {
return node.text;
} else if (ts.isPropertyAccessExpression(node)) {
return `${exprToString(node.expression)}.${exprToString(node.name)}`;
} else if (ts.isElementAccessExpression(node)) {
return `${exprToString(node.expression)}[${exprToString(
node.argumentExpression
)}]`;
} else {
return "";
}
}
function string(literal: string): ts.Expression {
return newExpr("StringLiteralExpr", [
ts.factory.createStringLiteral(literal),
]);
}
function newExpr(type: FunctionlessNode["kind"], args: ts.Expression[]) {
return ts.factory.createNewExpression(
ts.factory.createPropertyAccessExpression(
functionlessContext.functionless,
type
),
undefined,
args
);
}
function isIntegrationNode(node: ts.Node): boolean {
const exprType = checker.getTypeAtLocation(node);
const exprKind = exprType.getProperty("kind");
if (exprKind) {
const exprKindType = checker.getTypeOfSymbolAtLocation(
exprKind,
node
);
return exprKindType.isStringLiteral();
}
return false;
}
};
};
}
function getOperator(op: ts.BinaryOperatorToken): BinaryOp | undefined {
return OperatorMappings[op.kind as keyof typeof OperatorMappings];
}
const OperatorMappings: Record<number, BinaryOp> = {
[ts.SyntaxKind.EqualsToken]: "=",
[ts.SyntaxKind.PlusToken]: "+",
[ts.SyntaxKind.MinusToken]: "-",
[ts.SyntaxKind.AsteriskToken]: "*",
[ts.SyntaxKind.SlashToken]: "/",
[ts.SyntaxKind.AmpersandAmpersandToken]: "&&",
[ts.SyntaxKind.BarBarToken]: "||",
[ts.SyntaxKind.ExclamationEqualsToken]: "!=",
[ts.SyntaxKind.ExclamationEqualsEqualsToken]: "!=",
[ts.SyntaxKind.EqualsEqualsToken]: "==",
[ts.SyntaxKind.EqualsEqualsEqualsToken]: "==",
[ts.SyntaxKind.LessThanEqualsToken]: "<=",
[ts.SyntaxKind.LessThanToken]: "<",
[ts.SyntaxKind.GreaterThanEqualsToken]: ">=",
[ts.SyntaxKind.GreaterThanToken]: ">",
[ts.SyntaxKind.ExclamationEqualsToken]: "!=",
[ts.SyntaxKind.ExclamationEqualsEqualsToken]: "!=",
[ts.SyntaxKind.InKeyword]: "in",
} as const; | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace FormKnowledge_Article {
interface Header extends DevKit.Controls.IHeader {
/** Select the language that the article's content is in. */
LanguageLocaleId: DevKit.Controls.Lookup;
/** Select the article's status. */
StatusCode: DevKit.Controls.OptionSet;
}
interface tab_analytics_Sections {
Feedback: DevKit.Controls.Section;
Views: DevKit.Controls.Section;
}
interface tab_general_Sections {
Content: DevKit.Controls.Section;
Knowledge_Information: DevKit.Controls.Section;
}
interface tab_summary_Sections {
Portal_Settings: DevKit.Controls.Section;
Publish_Settings: DevKit.Controls.Section;
ref_pan_Related: DevKit.Controls.Section;
Timeline: DevKit.Controls.Section;
}
interface tab_analytics extends DevKit.Controls.ITab {
Section: tab_analytics_Sections;
}
interface tab_general extends DevKit.Controls.ITab {
Section: tab_general_Sections;
}
interface tab_summary extends DevKit.Controls.ITab {
Section: tab_summary_Sections;
}
interface Tabs {
analytics: tab_analytics;
general: tab_general;
summary: tab_summary;
}
interface Body {
Tab: Tabs;
/** Shows the automatically generated ID exposed to customers, partners, and other external users to reference and look up articles. */
ArticlePublicNumber: DevKit.Controls.String;
content: DevKit.Controls.ActionCards;
/** Unique identifier of the user who created the record. */
CreatedBy: DevKit.Controls.Lookup;
/** Date and time when the record was created. */
CreatedOn: DevKit.Controls.DateTime;
/** A short overview of the article, primarily used in search results and for search engine optimization. */
Description: DevKit.Controls.String;
/** Enter an expiration date for the article. Leave this field blank for no expiration date. */
ExpirationDate: DevKit.Controls.DateTime;
/** Shows whether this article is only visible internally. */
IsInternal: DevKit.Controls.Boolean;
/** Type keywords to be used for searches in knowledge base articles. Separate keywords by using commas. */
Keywords: DevKit.Controls.String;
/** Shows the total number of article views. */
KnowledgeArticleViews: DevKit.Controls.Integer;
/** Select the language that the article's content is in. */
LanguageLocaleId: DevKit.Controls.Lookup;
/** Shows the major version number of this article's content. */
MajorVersionNumber: DevKit.Controls.Integer;
/** Shows the minor version number of this article's content. */
MinorVersionNumber: DevKit.Controls.Integer;
/** Unique identifier of the user who modified the record. */
ModifiedBy: DevKit.Controls.Lookup;
/** Date and time when the record was modified. */
ModifiedOn: DevKit.Controls.DateTime;
notescontrol: DevKit.Controls.Note;
/** Unique identifier of the user or team who owns the record. */
OwnerId: DevKit.Controls.Lookup;
/** Contains the id of the parent article content associated with the entity. */
ParentArticleContentId: DevKit.Controls.Lookup;
/** Contains the id of the primary author associated with the article. */
primaryauthorid: DevKit.Controls.Lookup;
/** Date and time when the record was published. */
PublishOn: DevKit.Controls.DateTime;
/** Information which specifies how helpful the related record was. */
Rating: DevKit.Controls.Decimal;
/** Contains the id of the root article. */
RootArticleId: DevKit.Controls.Lookup;
/** Select the article's status. */
StatusCode: DevKit.Controls.OptionSet;
/** Choose the subject of the article to assist with article searches. You can configure subjects under Business Management in the Settings area. */
SubjectId: DevKit.Controls.Lookup;
/** Type a title for the article. */
Title: DevKit.Controls.String;
}
interface Footer extends DevKit.Controls.IFooter {
/** Shows the major version number of this article's content. */
MajorVersionNumber: DevKit.Controls.Integer;
/** Shows the minor version number of this article's content. */
MinorVersionNumber: DevKit.Controls.Integer;
}
interface ProcessNew_Process {
/** Enter an expiration date for the article. Leave this field blank for no expiration date. */
ExpirationDate: DevKit.Controls.DateTime;
/** Type keywords to be used for searches in knowledge base articles. Separate keywords by using commas. */
Keywords: DevKit.Controls.String;
/** Contains the id of the primary author associated with the article. */
primaryauthorid: DevKit.Controls.Lookup;
/** Ready For Review */
ReadyForReview: DevKit.Controls.Boolean;
/** Review */
Review: DevKit.Controls.OptionSet;
/** Choose the subject of the article to assist with article searches. You can configure subjects under Business Management in the Settings area. */
SubjectId: DevKit.Controls.Lookup;
/** Update Content */
UpdateContent: DevKit.Controls.Boolean;
}
interface ProcessTranslation_Process {
/** Enter an expiration date for the article. Leave this field blank for no expiration date. */
ExpirationDate: DevKit.Controls.DateTime;
/** Select the language that the article's content is in. */
LanguageLocaleId: DevKit.Controls.Lookup;
}
interface ProcessExpired_Process {
/** Enter an expiration date for the article. Leave this field blank for no expiration date. */
ExpirationDate: DevKit.Controls.DateTime;
/** Enter an expiration date for the article. Leave this field blank for no expiration date. */
ExpirationDate_1: DevKit.Controls.DateTime;
/** Expired Review Options */
ExpiredReviewOptions: DevKit.Controls.OptionSet;
/** Update Content */
UpdateContent: DevKit.Controls.Boolean;
}
interface Process extends DevKit.Controls.IProcess {
New_Process: ProcessNew_Process;
Translation_Process: ProcessTranslation_Process;
Expired_Process: ProcessExpired_Process;
}
interface Grid {
RelatedTranslationsGrid: DevKit.Controls.Grid;
RelatedCategoriesGrid: DevKit.Controls.Grid;
KnowledgearticleviewsGrid: DevKit.Controls.Grid;
Feedback: DevKit.Controls.Grid;
}
}
class FormKnowledge_Article extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Knowledge_Article
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form Knowledge_Article */
Body: DevKit.FormKnowledge_Article.Body;
/** The Footer section of form Knowledge_Article */
Footer: DevKit.FormKnowledge_Article.Footer;
/** The Header section of form Knowledge_Article */
Header: DevKit.FormKnowledge_Article.Header;
/** The Process of form Knowledge_Article */
Process: DevKit.FormKnowledge_Article.Process;
/** The Grid of form Knowledge_Article */
Grid: DevKit.FormKnowledge_Article.Grid;
}
namespace FormKnowledge_Article_for_Interactive_experience {
interface Header extends DevKit.Controls.IHeader {
/** Select the language that the article's content is in. */
LanguageLocaleId: DevKit.Controls.Lookup;
/** Select the article's status. */
StatusCode: DevKit.Controls.OptionSet;
}
interface tab_analytics_Sections {
Feedback: DevKit.Controls.Section;
Views: DevKit.Controls.Section;
}
interface tab_general_Sections {
Content: DevKit.Controls.Section;
Knowledge_Information: DevKit.Controls.Section;
}
interface tab_summary_Sections {
Portal_Settings: DevKit.Controls.Section;
Publish_Settings: DevKit.Controls.Section;
ref_pan_Related: DevKit.Controls.Section;
Timeline: DevKit.Controls.Section;
}
interface tab_analytics extends DevKit.Controls.ITab {
Section: tab_analytics_Sections;
}
interface tab_general extends DevKit.Controls.ITab {
Section: tab_general_Sections;
}
interface tab_summary extends DevKit.Controls.ITab {
Section: tab_summary_Sections;
}
interface Tabs {
analytics: tab_analytics;
general: tab_general;
summary: tab_summary;
}
interface Body {
Tab: Tabs;
/** Shows the automatically generated ID exposed to customers, partners, and other external users to reference and look up articles. */
ArticlePublicNumber: DevKit.Controls.String;
content: DevKit.Controls.ActionCards;
/** Unique identifier of the user who created the record. */
CreatedBy: DevKit.Controls.Lookup;
/** Date and time when the record was created. */
CreatedOn: DevKit.Controls.DateTime;
/** A short overview of the article, primarily used in search results and for search engine optimization. */
Description: DevKit.Controls.String;
/** Enter an expiration date for the article. Leave this field blank for no expiration date. */
ExpirationDate: DevKit.Controls.DateTime;
/** Shows whether this article is only visible internally. */
IsInternal: DevKit.Controls.Boolean;
/** Type keywords to be used for searches in knowledge base articles. Separate keywords by using commas. */
Keywords: DevKit.Controls.String;
/** Shows the total number of article views. */
KnowledgeArticleViews: DevKit.Controls.Integer;
/** Select the language that the article's content is in. */
LanguageLocaleId: DevKit.Controls.Lookup;
/** Shows the major version number of this article's content. */
MajorVersionNumber: DevKit.Controls.Integer;
/** Shows the minor version number of this article's content. */
MinorVersionNumber: DevKit.Controls.Integer;
/** Unique identifier of the user who modified the record. */
ModifiedBy: DevKit.Controls.Lookup;
/** Date and time when the record was modified. */
ModifiedOn: DevKit.Controls.DateTime;
notescontrol: DevKit.Controls.Note;
/** Unique identifier of the user or team who owns the record. */
OwnerId: DevKit.Controls.Lookup;
/** Contains the id of the parent article content associated with the entity. */
ParentArticleContentId: DevKit.Controls.Lookup;
/** Contains the id of the primary author associated with the article. */
primaryauthorid: DevKit.Controls.Lookup;
/** Date and time when the record was published. */
PublishOn: DevKit.Controls.DateTime;
/** Information which specifies how helpful the related record was. */
Rating: DevKit.Controls.Decimal;
/** Contains the id of the root article. */
RootArticleId: DevKit.Controls.Lookup;
/** Select the article's status. */
StatusCode: DevKit.Controls.OptionSet;
/** Choose the subject of the article to assist with article searches. You can configure subjects under Business Management in the Settings area. */
SubjectId: DevKit.Controls.Lookup;
/** Type a title for the article. */
Title: DevKit.Controls.String;
}
interface Footer extends DevKit.Controls.IFooter {
/** Shows the major version number of this article's content. */
MajorVersionNumber: DevKit.Controls.Integer;
/** Shows the minor version number of this article's content. */
MinorVersionNumber: DevKit.Controls.Integer;
}
interface ProcessNew_Process {
/** Enter an expiration date for the article. Leave this field blank for no expiration date. */
ExpirationDate: DevKit.Controls.DateTime;
/** Type keywords to be used for searches in knowledge base articles. Separate keywords by using commas. */
Keywords: DevKit.Controls.String;
/** Contains the id of the primary author associated with the article. */
primaryauthorid: DevKit.Controls.Lookup;
/** Ready For Review */
ReadyForReview: DevKit.Controls.Boolean;
/** Review */
Review: DevKit.Controls.OptionSet;
/** Choose the subject of the article to assist with article searches. You can configure subjects under Business Management in the Settings area. */
SubjectId: DevKit.Controls.Lookup;
/** Update Content */
UpdateContent: DevKit.Controls.Boolean;
}
interface ProcessTranslation_Process {
/** Enter an expiration date for the article. Leave this field blank for no expiration date. */
ExpirationDate: DevKit.Controls.DateTime;
/** Select the language that the article's content is in. */
LanguageLocaleId: DevKit.Controls.Lookup;
}
interface ProcessExpired_Process {
/** Enter an expiration date for the article. Leave this field blank for no expiration date. */
ExpirationDate: DevKit.Controls.DateTime;
/** Enter an expiration date for the article. Leave this field blank for no expiration date. */
ExpirationDate_1: DevKit.Controls.DateTime;
/** Expired Review Options */
ExpiredReviewOptions: DevKit.Controls.OptionSet;
/** Update Content */
UpdateContent: DevKit.Controls.Boolean;
}
interface Process extends DevKit.Controls.IProcess {
New_Process: ProcessNew_Process;
Translation_Process: ProcessTranslation_Process;
Expired_Process: ProcessExpired_Process;
}
interface Grid {
RelatedTranslationsGrid: DevKit.Controls.Grid;
RelatedCategoriesGrid: DevKit.Controls.Grid;
KnowledgearticleviewsGrid: DevKit.Controls.Grid;
Feedback: DevKit.Controls.Grid;
}
}
class FormKnowledge_Article_for_Interactive_experience extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Knowledge_Article_for_Interactive_experience
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form Knowledge_Article_for_Interactive_experience */
Body: DevKit.FormKnowledge_Article_for_Interactive_experience.Body;
/** The Footer section of form Knowledge_Article_for_Interactive_experience */
Footer: DevKit.FormKnowledge_Article_for_Interactive_experience.Footer;
/** The Header section of form Knowledge_Article_for_Interactive_experience */
Header: DevKit.FormKnowledge_Article_for_Interactive_experience.Header;
/** The Process of form Knowledge_Article_for_Interactive_experience */
Process: DevKit.FormKnowledge_Article_for_Interactive_experience.Process;
/** The Grid of form Knowledge_Article_for_Interactive_experience */
Grid: DevKit.FormKnowledge_Article_for_Interactive_experience.Grid;
}
namespace FormKnowledge_Article_Quick_Create {
interface tab_newKnowledgeArticle_Sections {
quickKnowledgeArticle: DevKit.Controls.Section;
quickKnowledgecontent: DevKit.Controls.Section;
quickKnowledgeowner: DevKit.Controls.Section;
}
interface tab_newKnowledgeArticle extends DevKit.Controls.ITab {
Section: tab_newKnowledgeArticle_Sections;
}
interface Tabs {
newKnowledgeArticle: tab_newKnowledgeArticle;
}
interface Body {
Tab: Tabs;
/** A short overview of the article, primarily used in search results and for search engine optimization. */
Description: DevKit.Controls.String;
/** Type keywords to be used for searches in knowledge base articles. Separate keywords by using commas. */
Keywords: DevKit.Controls.String;
/** Select the language that the article's content is in. */
LanguageLocaleId: DevKit.Controls.Lookup;
/** Unique identifier of the user or team who owns the record. */
OwnerId: DevKit.Controls.Lookup;
/** Contains the id of the primary author associated with the article. */
primaryauthorid: DevKit.Controls.Lookup;
/** Type a title for the article. */
Title: DevKit.Controls.String;
}
}
class FormKnowledge_Article_Quick_Create extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Knowledge_Article_Quick_Create
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form Knowledge_Article_Quick_Create */
Body: DevKit.FormKnowledge_Article_Quick_Create.Body;
}
class KnowledgeArticleApi {
/**
* DynamicsCrm.DevKit KnowledgeArticleApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Shows the automatically generated ID exposed to customers, partners, and other external users to reference and look up articles. */
ArticlePublicNumber: DevKit.WebApi.StringValue;
/** Shows the body of the article stored in HTML format. */
Content: DevKit.WebApi.StringValue;
/** Unique identifier of the user who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was created. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who created the record. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** A short overview of the article, primarily used in search results and for search engine optimization. */
Description: DevKit.WebApi.StringValue;
/** Exchange rate for the currency associated with the KnowledgeArticle with respect to the base currency. */
ExchangeRate: DevKit.WebApi.DecimalValueReadonly;
/** Enter an expiration date for the article. Leave this field blank for no expiration date. */
ExpirationDate_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Contains the id of the expiration state of the entity. */
ExpirationStateId: DevKit.WebApi.IntegerValue;
/** Contains the id of the expiration status of the entity. */
ExpirationStatusId: DevKit.WebApi.IntegerValue;
/** Expired Review Options */
ExpiredReviewOptions: DevKit.WebApi.OptionSetValue;
/** Sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Shows whether this article is only visible internally. */
IsInternal: DevKit.WebApi.BooleanValue;
/** Shows which version of the knowledge article is the latest version. */
IsLatestVersion: DevKit.WebApi.BooleanValue;
/** Select whether the article is the primary article. */
IsPrimary: DevKit.WebApi.BooleanValue;
/** Select whether the article is the root article. */
IsRootArticle: DevKit.WebApi.BooleanValue;
/** Type keywords to be used for searches in knowledge base articles. Separate keywords by using commas. */
Keywords: DevKit.WebApi.StringValue;
/** Unique identifier for entity instances */
knowledgearticleId: DevKit.WebApi.GuidValue;
/** Shows the total number of article views. */
KnowledgeArticleViews: DevKit.WebApi.IntegerValueReadonly;
/** The date time for Knowledge Article View. */
KnowledgeArticleViews_Date_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** State of Knowledge Article View. */
KnowledgeArticleViews_State: DevKit.WebApi.IntegerValueReadonly;
/** Select the language that the article's content is in. */
LanguageLocaleId: DevKit.WebApi.LookupValue;
LanguageLocaleIdLocaleId: DevKit.WebApi.IntegerValueReadonly;
/** Shows the major version number of this article's content. */
MajorVersionNumber: DevKit.WebApi.IntegerValue;
/** Shows the minor version number of this article's content. */
MinorVersionNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier of the user who modified the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was modified. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who modified the record. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Ingested article URL */
msdyn_ingestedarticleurl: DevKit.WebApi.StringValue;
/** Value is true for all Ingested articles */
msdyn_isingestedarticle: DevKit.WebApi.BooleanValue;
/** Date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValue;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValue;
/** Unique identifier for the business unit that owns the record */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the team that owns the record. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the user that owns the record. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Contains the id of the parent article content associated with the entity. */
ParentArticleContentId: DevKit.WebApi.LookupValue;
/** Shows the version that the current article was restored from. */
PreviousArticleContentId: DevKit.WebApi.LookupValue;
/** Contains the id of the primary author associated with the article. */
primaryauthorid: DevKit.WebApi.LookupValue;
/** Contains the id of the process associated with the entity. */
processid: DevKit.WebApi.GuidValue;
/** Date and time when the record was published. */
PublishOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Publish Status of the Article. */
PublishStatusId: DevKit.WebApi.IntegerValue;
/** Information which specifies how helpful the related record was. */
Rating: DevKit.WebApi.DecimalValueReadonly;
/** Rating Count */
Rating_Count: DevKit.WebApi.IntegerValueReadonly;
/** The date time for Rating. */
Rating_Date_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** State of Rating */
Rating_State: DevKit.WebApi.IntegerValueReadonly;
/** Total sum of Rating */
Rating_Sum: DevKit.WebApi.DecimalValueReadonly;
/** Ready For Review */
ReadyForReview: DevKit.WebApi.BooleanValue;
/** Review */
Review: DevKit.WebApi.OptionSetValue;
/** Contains the id of the root article. */
RootArticleId: DevKit.WebApi.LookupValue;
/** Contains the id of the scheduled status of the entity. */
ScheduledStatusId: DevKit.WebApi.IntegerValue;
/** Shows whether category associations have been set */
SetCategoryAssociations: DevKit.WebApi.BooleanValue;
/** Contains the id of the stage where the entity is located. */
stageid: DevKit.WebApi.GuidValue;
/** Shows whether the article is a draft or is published, archived, or discarded. Draft articles aren't available externally and can be edited. Published articles are available externally, based on applicable permissions, but can't be edited. All metadata changes are reflected in the published version. Archived and discarded articles aren't available externally and can't be edited. */
StateCode: DevKit.WebApi.OptionSetValue;
/** Select the article's status. */
StatusCode: DevKit.WebApi.OptionSetValue;
/** Choose the subject of the article to assist with article searches. You can configure subjects under Business Management in the Settings area. */
SubjectId: DevKit.WebApi.LookupValue;
SubjectIdDsc: DevKit.WebApi.IntegerValueReadonly;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Type a title for the article. */
Title: DevKit.WebApi.StringValue;
/** Exchange rate for the currency associated with the KnowledgeArticle with respect to the base currency. */
TransactionCurrencyId: DevKit.WebApi.LookupValue;
/** A comma separated list of string values representing the unique identifiers of stages in a Business Process Flow Instance in the order that they occur. */
traversedpath: DevKit.WebApi.StringValue;
/** Update Content */
UpdateContent: DevKit.WebApi.BooleanValue;
/** Time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
}
}
declare namespace OptionSet {
namespace KnowledgeArticle {
enum ExpiredReviewOptions {
/** 2 */
Archive,
/** 0 */
Needs_Updating,
/** 1 */
Republish
}
enum Review {
/** 0 */
Approved,
/** 1 */
Rejected
}
enum StateCode {
/** 1 */
Approved,
/** 5 */
Archived,
/** 6 */
Discarded,
/** 0 */
Draft,
/** 4 */
Expired,
/** 3 */
Published,
/** 2 */
Scheduled
}
enum StatusCode {
/** 5 */
Approved,
/** 12 */
Archived,
/** 13 */
Discarded,
/** 2 */
Draft,
/** 10 */
Expired,
/** 4 */
In_review,
/** 3 */
Needs_review_3,
/** 8 */
Needs_review_8,
/** 1 */
Proposed,
/** 7 */
Published,
/** 11 */
Rejected_11,
/** 14 */
Rejected_14,
/** 6 */
Scheduled,
/** 9 */
Updating
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Knowledge Article','Knowledge Article for Interactive experience','Quick Create'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
declare module 'bootstrap-styled' {
import {
getGlobalStyles,
getGlobalStyleNoBootstrapProvider
} from '@bootstrap-styled/css-utils';
export { getGlobalStyles, getGlobalStyleNoBootstrapProvider };
export type Theme = {
_name: string;
// Colors
$white: string;
$black: string;
$red: string;
$orange: string;
$yellow: string;
$green: string;
$blue: string;
$teal: string;
$pink: string;
$purple: string;
// Grayscale
'$gray-dark': string;
$gray: string;
'$gray-light': string;
'$gray-lighter': string;
'$gray-lightest': string;
// Semantic colour scheme
'$brand-primary': string;
'$brand-success': string;
'$brand-info': string;
'$brand-warning': string;
'$brand-danger': string;
'$brand-inverse': string;
// Options
'$enable-rounded': boolean;
'$enable-shadows': boolean;
'$enable-gradients': boolean;
'$enable-transitions': boolean;
'$enable-hover-media-query': boolean;
'$enable-grid-classes': boolean;
'$enable-print-styles': boolean;
// Spacing
$spacer: string;
'$spacer-halved': string;
'$spacer-x': string;
'$spacer-y': string;
$spacers: {
0: {
x: string;
y: string;
};
1: {
x: string;
y: string;
};
2: {
x: string;
y: string;
};
3: {
x: string;
y: string;
};
4: {
x: string;
y: string;
};
5: {
x: string;
y: string;
};
};
'$border-width': string;
// .h-* & .w-* classes
$sizes: {
25: string;
50: string;
75: string;
100: string;
};
// Body
'$body-bg': string;
'$body-color': string;
// Links
'$link-color': string;
'$link-decoration': string;
'$link-hover-color': string;
'$link-hover-decoration': string;
// Grid breakpoints
'$grid-breakpoints': {
xs: string;
sm: string;
md: string;
lg: string;
xl: string;
xxl: string;
};
// Grid containers
'$container-max-widths': {
sm: string;
md: string;
lg: string;
xl: string;
};
// Grid columns
'$grid-columns': string;
'$grid-gutter-width': string;
// Fonts
'$font-family-sans-serif': string;
'$font-family-monospace': string;
'$font-family-base': string;
'$font-size-base': string;
'$font-size-lg': string;
'$font-size-sm': string;
'$font-size-xs': string;
'$font-weight-normal': string;
'$font-weight-bold': string;
'$font-weight-base': string;
'$line-height-base': string;
'$font-size-h1': string;
'$font-size-h2': string;
'$font-size-h3': string;
'$font-size-h4': string;
'$font-size-h5': string;
'$font-size-h6': string;
'$headings-margin-bottom': string;
'$headings-font-family': string;
'$headings-font-weight': string;
'$headings-line-height': string;
'$headings-color': string;
'$display1-size': string;
'$display2-size': string;
'$display3-size': string;
'$display4-size': string;
'$display1-weight': string;
'$display2-weight': string;
'$display3-weight': string;
'$display4-weight': string;
'$display-line-height': string;
'$lead-font-size': string;
'$lead-font-weight': string;
'$small-font-size': string;
'$text-muted': string;
'$blockquote-small-color': string;
'$blockquote-font-size': string;
'$blockquote-border-color': string;
'$blockquote-border-width': string;
'$hr-border-color': string;
'$hr-border-width': string;
'$mark-padding': string;
'$dt-font-weight': string;
'$list-inline-padding': string;
// Components
'$line-height-lg': string;
'$line-height-sm': string;
'$border-radius': string;
'$border-radius-lg': string;
'$border-radius-sm': string;
'$component-active-color': string;
'$component-active-bg': string;
'$caret-width': string;
'$transition-base': string;
'$transition-fade': string;
'$transition-collapse': string;
// Tables
'$table-cell-padding': string;
'$table-sm-cell-padding': string;
'$table-bg': string;
'$table-inverse-bg': string;
'$table-inverse-bg-accent': string;
'$table-inverse-bg-hover': string;
'$table-inverse-color': string;
'$table-inverse-border': string;
'$table-bg-accent': string;
'$table-bg-hover': string;
'$table-bg-active': string;
'$table-head-bg': string;
'$table-head-color': string;
'$table-border-width': string;
'$table-border-color': string;
// Buttons
'$btn-padding-x': string;
'$btn-padding-y': string;
'$btn-line-height': string;
'$btn-font-weight': string;
'$btn-box-shadow': string;
'$btn-focus-box-shadow': string;
'$btn-disabled-opacity': string;
'$btn-active-box-shadow': string;
'$btn-primary-color': string;
'$btn-primary-bg': string;
'$btn-secondary-color': string;
'$btn-secondary-bg': string;
'$btn-info-color': string;
'$btn-info-bg': string;
'$btn-success-color': string;
'$btn-success-bg': string;
'$btn-warning-color': string;
'$btn-warning-bg': string;
'$btn-danger-color': string;
'$btn-danger-bg': string;
'$btn-primary-border': string;
'$btn-secondary-border': string;
'$btn-info-border': string;
'$btn-success-border': string;
'$btn-warning-border': string;
'$btn-danger-border': string;
'$btn-link-disabled-color': string;
'$btn-padding-x-sm': string;
'$btn-padding-y-sm': string;
'$btn-padding-x-lg': string;
'$btn-padding-y-lg': string;
'$btn-block-spacing-y': string;
'$btn-border-radius': string;
'$btn-border-radius-lg': string;
'$btn-border-radius-sm': string;
'$btn-border-width': string;
'$btn-transition': string;
// Forms
'$input-padding-x': string;
'$input-padding-y': string;
'$input-line-height': string;
'$input-bg': string;
'$input-bg-disabled': string;
'$input-color': string;
'$input-border-color': string;
'$input-btn-border-width': string;
'$input-box-shadow': string;
'$input-border-radius': string;
'$input-border-radius-lg': string;
'$input-border-radius-sm': string;
'$input-bg-focus': string;
'$input-border-focus': string;
'$input-box-shadow-focus': string;
'$input-color-focus': string;
'$input-color-placeholder': string;
'$input-padding-x-sm': string;
'$input-padding-y-sm': string;
'$input-padding-x-lg': string;
'$input-padding-y-lg': string;
'$input-height': string;
'$input-height-sm': string;
'$input-height-lg': string;
'$input-transition': string;
'$label-margin-bottom': string;
'$form-text-margin-top': string;
'$form-feedback-margin-top': string;
'$form-check-margin-bottom': string;
'$form-check-input-gutter': string;
'$form-check-input-margin-y': string;
'$form-check-input-margin-x': string;
'$form-check-inline-margin-x': string;
'$form-group-margin-bottom': string;
'$input-group-addon-bg': string;
'$input-group-addon-border-color': string;
'$cursor-disabled': string;
'$custom-control-gutter': string;
'$custom-control-spacer-x': string;
'$custom-control-spacer-y': string;
'$custom-control-indicator-size': string;
'$custom-control-indicator-bg': string;
'$custom-control-indicator-bg-size': string;
'$custom-control-indicator-box-shadow': string;
'$custom-control-disabled-cursor': string;
'$custom-control-disabled-indicator-bg': string;
'$custom-control-disabled-description-color': string;
'$custom-control-checked-indicator-color': string;
'$custom-control-checked-indicator-bg': string;
'$custom-control-checked-indicator-box-shadow': string;
'$custom-control-focus-indicator-box-shadow': string;
'$custom-control-active-indicator-color': string;
'$custom-control-active-indicator-bg': string;
'$custom-control-active-indicator-box-shadow': string;
'$custom-checkbox-radius': string;
'$custom-checkbox-checked-icon': string;
'$custom-checkbox-indeterminate-bg': string;
'$custom-checkbox-indeterminate-indicator-color': string;
'$custom-checkbox-indeterminate-icon': string;
'$custom-checkbox-indeterminate-box-shadow': string;
'$custom-radio-radius': string;
'$custom-radio-checked-icon': string;
'$custom-select-padding-x': string;
'$custom-select-padding-y': string;
'$custom-select-indicator-padding': string;
'$custom-select-line-height': string;
'$custom-select-color': string;
'$custom-select-disabled-color': string;
'$custom-select-bg': string;
'$custom-select-disabled-bg': string;
'$custom-select-bg-size': string;
'$custom-select-indicator-color': string;
'$custom-select-indicator': string;
'$custom-select-border-width': string;
'$custom-select-border-color': string;
'$custom-select-border-radius': string;
'$custom-select-focus-border-color': string;
'$custom-select-focus-box-shadow': string;
'$custom-select-sm-font-size': string;
'$custom-file-height': string;
'$custom-file-width': string;
'$custom-file-focus-box-shadow': string;
'$custom-file-padding-x': string;
'$custom-file-padding-y': string;
'$custom-file-line-height': string;
'$custom-file-color': string;
'$custom-file-bg': string;
'$custom-file-border-width': string;
'$custom-file-border-color': string;
'$custom-file-border-radius': string;
'$custom-file-box-shadow': string;
'$custom-file-button-color': string;
'$custom-file-button-bg': string;
'$custom-file-text': {
placeholder: {
en: string;
};
'button-label': {
en: string;
};
};
// Form validation icons
'$form-icon-success-color': string;
'$form-icon-success': string;
'$form-icon-warning-color': string;
'$form-icon-warning': string;
'$form-icon-danger-color': string;
'$form-icon-danger': string;
// Dropdowns
'$dropdown-min-width': string;
'$dropdown-padding-y': string;
'$dropdown-margin-top': string;
'$dropdown-bg': string;
'$dropdown-border-color': string;
'$dropdown-border-width': string;
'$dropdown-divider-bg': string;
'$dropdown-box-shadow': string;
'$dropdown-link-color': string;
'$dropdown-link-hover-color': string;
'$dropdown-link-hover-bg': string;
'$dropdown-link-active-color': string;
'$dropdown-link-active-bg': string;
'$dropdown-link-disabled-color': string;
'$dropdown-item-padding-x': string;
'$dropdown-header-color': string;
// Z-index master list
//
// Warning = 'Avoid customizing these values. They're used for a bird's eye view
// of components dependent on the z-axis and are designed to all work together.
'$zindex-dropdown-backdrop': string;
'$zindex-dropdown': string;
'$zindex-modal-backdrop': string;
'$zindex-modal': string;
'$zindex-popover': string;
'$zindex-tooltip': string;
'$zindex-navbar': string;
'$zindex-navbar-fixed': string;
'$zindex-navbar-sticky': string;
// Navbar
'$navbar-padding-x': string;
'$navbar-padding-y': string;
'$navbar-brand-padding-y': string;
'$navbar-divider-padding-y': string;
'$navbar-toggler-padding-x': string;
'$navbar-toggler-padding-y': string;
'$navbar-toggler-font-size': string;
'$navbar-toggler-border-radius': string;
'$navbar-inverse-color': string;
'$navbar-inverse-hover-color': string;
'$navbar-inverse-active-color': string;
'$navbar-inverse-disabled-color': string;
'$navbar-inverse-toggler-bg': string;
'$navbar-inverse-toggler-border': string;
'$navbar-light-color': string;
'$navbar-light-hover-color': string;
'$navbar-light-active-color': string;
'$navbar-light-disabled-color': string;
'$navbar-light-toggler-bg': string;
'$navbar-light-toggler-border': string;
// Navs
'$nav-link-padding': string;
'$nav-disabled-link-color': string;
'$nav-tabs-border-color': string;
'$nav-tabs-border-width': string;
'$nav-tabs-border-radius': string;
'$nav-tabs-link-hover-border-color': string;
'$nav-tabs-active-link-hover-color': string;
'$nav-tabs-active-link-hover-bg': string;
'$nav-tabs-active-link-hover-border-color': string;
'$nav-pills-border-radius': string;
'$nav-pills-active-link-color': string;
'$nav-pills-active-link-bg': string;
// Pagination
'$pagination-padding-x': string;
'$pagination-padding-y': string;
'$pagination-padding-x-sm': string;
'$pagination-padding-y-sm': string;
'$pagination-padding-x-lg': string;
'$pagination-padding-y-lg': string;
'$pagination-line-height': string;
'$pagination-color': string;
'$pagination-bg': string;
'$pagination-border-width': string;
'$pagination-border-color': string;
'$pagination-hover-color': string;
'$pagination-hover-bg': string;
'$pagination-hover-border': string;
'$pagination-active-color': string;
'$pagination-active-bg': string;
'$pagination-active-border': string;
'$pagination-disabled-color': string;
'$pagination-disabled-bg': string;
'$pagination-disabled-border': string;
// Jumbotron
'$jumbotron-padding': string;
'$jumbotron-bg': string;
// Form states and alerts
'$state-success-text': string;
'$state-success-bg': string;
'$state-success-border': string;
'$state-info-text': string;
'$state-info-bg': string;
'$state-info-border': string;
'$state-warning-text': string;
'$state-warning-bg': string;
'$state-warning-border': string;
'$mark-bg': string;
'$state-danger-text': string;
'$state-danger-bg': string;
'$state-danger-border': string;
// Cards
'$card-spacer-x': string;
'$card-spacer-y': string;
'$card-border-width': string;
'$card-border-radius': string;
'$card-border-color': string;
'$card-border-radius-inner': string;
'$card-cap-bg': string;
'$card-bg': string;
'$card-link-hover-color': string;
'$card-img-overlay-padding': string;
'$card-group-margin': string;
'$card-deck-margin': string;
'$card-columns-count-md': string;
'$card-columns-gap-md': string;
'$card-columns-margin-md': string;
'$card-columns-count-lg': string;
'$card-columns-gap-lg': string;
'$card-columns-margin-lg': string;
'$card-columns-count-xl': string;
'$card-columns-gap-xl': string;
'$card-columns-margin-xl': string;
'$card-columns-count-xxl': string;
'$card-columns-gap-xxl': string;
'$card-columns-margin-xxl': string;
// Tooltips
'$tooltip-max-width': string;
'$tooltip-color': string;
'$tooltip-bg': string;
'$tooltip-opacity': string;
'$tooltip-padding-y': string;
'$tooltip-padding-x': string;
'$tooltip-margin': string;
'$tooltip-arrow-width': string;
'$tooltip-arrow-color': string;
// Popovers
'$popover-inner-padding': string;
'$popover-bg': string;
'$popover-max-width': string;
'$popover-border-width': string;
'$popover-border-color': string;
'$popover-box-shadow': string;
'$popover-title-bg': string;
'$popover-title-padding-x': string;
'$popover-title-padding-y': string;
'$popover-content-padding-x': string;
'$popover-content-padding-y': string;
'$popover-arrow-width': string;
'$popover-arrow-color': string;
'$popover-arrow-outer-width': string;
'$popover-arrow-outer-color': string;
// Badges
'$badge-default-bg': string;
'$badge-primary-bg': string;
'$badge-success-bg': string;
'$badge-info-bg': string;
'$badge-warning-bg': string;
'$badge-danger-bg': string;
'$badge-color': string;
'$badge-link-hover-color': string;
'$badge-font-size': string;
'$badge-font-weight': string;
'$badge-padding-x': string;
'$badge-padding-y': string;
'$badge-pill-padding-x': string;
'$badge-pill-border-radius': string;
// Modals
'$modal-inner-padding': string;
'$modal-dialog-margin': string;
'$modal-dialog-sm-up-margin-y': string;
'$modal-title-line-height': string;
'$modal-content-bg': string;
'$modal-content-border-color': string;
'$modal-content-border-width': string;
'$modal-content-xs-box-shadow': string;
'$modal-content-sm-up-box-shadow': string;
'$modal-backdrop-bg': string;
'$modal-backdrop-opacity': string;
'$modal-header-border-color': string;
'$modal-footer-border-color': string;
'$modal-header-border-width': string;
'$modal-footer-border-width': string;
'$modal-header-padding': string;
'$modal-lg': string;
'$modal-md': string;
'$modal-sm': string;
'$modal-transition': string;
// Alerts
'$alert-padding-x': string;
'$alert-padding-y': string;
'$alert-margin-bottom': string;
'$alert-border-radius': string;
'$alert-link-font-weight': string;
'$alert-border-width': string;
'$alert-success-bg': string;
'$alert-success-text': string;
'$alert-success-border': string;
'$alert-info-bg': string;
'$alert-info-text': string;
'$alert-info-border': string;
'$alert-warning-bg': string;
'$alert-warning-text': string;
'$alert-warning-border': string;
'$alert-danger-bg': string;
'$alert-danger-text': string;
'$alert-danger-border': string;
// Progress bars
'$progress-height': string;
'$progress-font-size': string;
'$progress-bg': string;
'$progress-border-radius': string;
'$progress-box-shadow': string;
'$progress-bar-color': string;
'$progress-bar-bg': string;
'$progress-bar-animation-timing': string;
// List group
'$list-group-color': string;
'$list-group-bg': string;
'$list-group-border-color': string;
'$list-group-border-width': string;
'$list-group-border-radius': string;
'$list-group-item-padding-x': string;
'$list-group-item-padding-y': string;
'$list-group-hover-bg': string;
'$list-group-active-color': string;
'$list-group-active-bg': string;
'$list-group-active-border': string;
'$list-group-disabled-color': string;
'$list-group-disabled-bg': string;
'$list-group-link-color': string;
'$list-group-link-hover-color': string;
'$list-group-link-active-color': string;
'$list-group-link-active-bg': string;
// Image thumbnails
'$thumbnail-padding': string;
'$thumbnail-bg': string;
'$thumbnail-border-width': string;
'$thumbnail-border-color': string;
'$thumbnail-border-radius': string;
'$thumbnail-box-shadow': string;
'$thumbnail-transition': string;
// Figures
'$figure-caption-font-size': string;
'$figure-caption-color': string;
// Breadcrumbs
'$breadcrumb-padding-y': string;
'$breadcrumb-padding-x': string;
'$breadcrumb-item-padding': string;
'$breadcrumb-bg': string;
'$breadcrumb-divider-color': string;
'$breadcrumb-active-color': string;
'$breadcrumb-divider': string;
// Close
'$close-font-size': string;
'$close-font-weight': string;
'$close-color': string;
'$close-text-shadow': string;
// Code
'$code-font-size': string;
'$code-padding-x': string;
'$code-padding-y': string;
'$code-color': string;
'$code-bg': string;
'$kbd-color': string;
'$kbd-bg': string;
'$kbd-box-shadow': string;
'$nested-kbd-font-weight': string;
'$pre-color': string;
'$pre-scrollable-max-height': string;
};
export type UserTheme = {
[K in keyof Theme]?: Theme[K] | null;
};
export const theme: Theme;
export function makeTheme(userTheme: UserTheme): Theme;
export function createMakeTheme(
list: ((theme: Theme) => Theme)[]
): (theme: Theme) => Theme;
export function makeScopedTheme(
scopeName: string,
userTheme?: { [scope: string]: UserTheme }
): { [scope: string]: UserTheme };
export function toMakeTheme(theme: Theme): (userTheme: UserTheme) => Theme;
} | the_stack |
import * as fs from 'fs-extra';
import * as Path from 'path';
import * as recc from 'recursive-readdir';
import { AllTags } from './types';
import { themeConfig } from '../.vuepress/config';
import { IFrontmatterData, getFrontmatterFromPath, capitalize, Frontmatter, randomIntFromInterval, reccursiveIgnoreFunction } from './util';
import * as sharp from 'sharp';
var beautify = require('js-beautify').js;
const sidebars = ['guide', 'references', 'structures', 'FAQ', 'tags', 'snippets', 'releases', 'libraries', 'examples'];
const readmefiles = ['guide', 'references', 'structures', 'FAQ', 'snippets', 'releases', 'libraries', 'examples'];
const SNIPPETS_BASE_PATH = './snippets';
const TAGS_BASE_PATH = './tags';
(async () => {
console.log(new Date());
console.log(Date.now());
await createTagsDirectory();
createSidebars(sidebars);
createReadmeFiles(readmefiles);
await updatePrimaryColor();
generateAllDocsPage();
await createRoutes();
})().catch(console.error);
async function createTagsDirectory() {
fs.ensureDirSync(TAGS_BASE_PATH);
const frontmatterData: IFrontmatterData[] = [];
(await recc(Path.join('./'), ['README.md', reccursiveIgnoreFunction])).map((file) => {
frontmatterData.push({
path: file,
frontmatter: getFrontmatterFromPath(file)
});
});
createFilesInTagsFolder(frontmatterData);
createReadmePage();
function createReadmePage() {
let readmeData = '';
readmeData = readmeData.concat('# Tags', '\n\n');
readmeData = readmeData.concat('<div class="tags-container">', '\n\n');
Object.keys(AllTags).map((tag) => {
readmeData = readmeData.concat(`<Tag name="${tag}" />`, '\n');
});
readmeData = readmeData.concat(`</div>`);
fs.writeFileSync(Path.join(TAGS_BASE_PATH, 'README.md'), readmeData);
}
function createFilesInTagsFolder(data: IFrontmatterData[]) {
Object.keys(AllTags).map((tag) => {
const files = data.filter((d) => {
if (d.frontmatter && d.frontmatter.tags) {
return d.frontmatter.tags.includes(tag);
}
}).sort((a, b) => {
if (a.frontmatter.cover && b.frontmatter.cover) { return 0; }
if (a.frontmatter.cover && !b.frontmatter.cover) { return -1; }
if (!a.frontmatter.cover && b.frontmatter.cover) { return 1; }
return 0;
}).sort((a, b) => {
return (a.path > b.path) ? 1 : (a.path < b.path) ? -1 : 0
});
let str = '';
str = str.concat('---', '\n',
'pageClass : sidebar-metacard-container', '\n',
`description : ${AllTags[tag].description}`, '\n',
`title : ${tag}`, '\n',
'---', '\n\n');
// str = str.concat(`# ${capitalize(tag)}`, '\n\n');
str = str.concat(`<Tag name="${capitalize(tag)}" />`, '\n\n');
str = str.concat(`<Header />`, '\n\n');
str = str.concat('<div class="tags-container">', '\n\n');
files.map((file) => {
str = str.concat(
`<MetaCard link="/${file.path.replace('.md', '.html').replace(/[\\/]/g, '/')}" >`,
file.frontmatter.cover ? `<img src="${file.frontmatter.cover}"> ` : '',
'</MetaCard>', '\n\n'
);
});
str = str.concat('</div>', '\n');
fs.writeFileSync(Path.join(TAGS_BASE_PATH, tag + '.md'), str);
});
}
}
function createReadmeFiles(paths: string[]) {
paths.map((v) => {
createReadmeFile(v);
});
function createReadmeFile(path: string) {
fs.readdir(`./${path}`).then((dir) => {
const files = dir.filter((file) => { return file != 'README.md' });
const frontmatters = files
.map((file) => {
return getFrontmatterFromPath(Path.join(path, file));
}).sort((a, b) => {
if (a.cover && b.cover) { return 0; }
if (a.cover && !b.cover) { return -1; }
if (!a.cover && b.cover) { return 1; }
return 0;
});
let str = '';
str = str.concat('---', '\n', 'pageClass : no-sidebar-metacard-container', '\n', 'sidebar : false', '\n', '---', '\n\n');
str = str.concat(capitalize(`# ${path}`), '\n\n');
str = str.concat('<div class="tags-container">', '\n\n');
frontmatters.map((frontmatter) => {
if (frontmatter) {
str = str.concat(
`<MetaCard link="/${frontmatter.path.replace('.md', '.html').replace(/[\\/]/g, '/')}" >`,
frontmatter.cover ? `<img src="${frontmatter.cover}"> ` : '',
'</MetaCard>', '\n\n'
);
}
});
str = str.concat('</div>', '\n');
fs.writeFileSync(`./${path}/README.md`, str);
}).catch((err) => {
console.log(err);
});
}
}
async function updatePrimaryColor() {
//has to be hex code
const iconColor = '#020814';
// const iconColor = '#ffffff';
//can be rgb
// const accentColor = process.env.TRAVIS_EVENT_TYPE == 'cron' ? getRandomColor() : '#3880ff';
console.log(process.env.TRAVIS_EVENT_TYPE);
// const accentColor = '#3880ff';//ionic blue
const accentColor = '#055af9';//ionic blue
// const accentColor = '#020814';//black
const overrideFilePath = Path.resolve('./.vuepress/override.styl');
const svgFilePath = Path.resolve(`./.vuepress/public/images/icon-svg.svg`);
const pngFilePath = Path.resolve(`./.vuepress/public/images/icon.png`);
const manifestFilePath = Path.resolve(`./.vuepress/public/pwa/manifest.json`);
let override = fs.readFileSync(overrideFilePath).toString();
override = override.replace(/\$accentColor.+/, `$accentColor = ${accentColor}`);
fs.writeFileSync(overrideFilePath, override);
//svg color
let svg = fs.readFileSync(svgFilePath).toString();
svg = svg.replace(/fill="[#0-9a-z(),]+"/g, `fill="${iconColor}"`);
fs.writeFileSync(svgFilePath, svg);
//png image
const imageBuffer = await sharp(svgFilePath)
.png()
.toBuffer();
fs.writeFileSync(pngFilePath, imageBuffer);
//manifest json color
const manifest = fs.readJsonSync(manifestFilePath);
manifest.theme_color = accentColor;
fs.writeFileSync(manifestFilePath, JSON.stringify(manifest, undefined, 4));
function getRandomColor(): string {
const arr = [
'#ff5252',
'#3880ff',
'#3b5bdb',
'#ffce00',
'#09c372',
'#fa7c3b',
'#5851ff'
];
return arr[randomIntFromInterval(0, 6)]
}
}
function createSidebars(paths: string[]) {
const obj: ISidebarObject = {};
paths.map((path) => {
obj[`/${path}/`] = fs.readdirSync(`./${path}`).filter((val) => { return val != 'README.md' })
});
const initialObject: ISidebarObject = JSON.parse(JSON.stringify(themeConfig.sidebar));
const folders = Object.keys(obj);
folders.map((folder) => {
obj[folder].sort((a, b) => {
return initialObject[folder].indexOf(a) - initialObject[folder].indexOf(b)
});
});
fs.readFile('./.vuepress/config.js').then((file) => {
const str = String().concat('sidebar:', JSON.stringify(Object.assign(initialObject, obj)).replace(/(:|,|\[)/g, '$1\n'));
const match = file.toString().replace(/sidebar:(.|\n|\s|{)+?}/, str);
fs.writeFileSync('./.vuepress/config.js', beautify(match));
}).catch((err) => {
console.log(err);
});
}
function generateAllDocsPage() {
const folders = sidebars.filter((val) => {
return !val.match(/(tags|FAQ|all)/);
});
let str = ``;
str = str.concat(`---`, '\n');
str = str.concat(`description : All docs on one page.`, '\n');
str = str.concat(`author : nishkal`, '\n');
str = str.concat(`tags : []`, '\n');
str = str.concat(`sidebarDepth: 4`, '\n');
str = str.concat(`---`, '\n');
str = str.concat(`\n# All Docs\n`);
folders.map((folder) => {
str = str.concat('\n', `## ${caps(folder)}`, '\n');
let files = fs.readdirSync(folder).filter((val) => !val.includes('README.md'));
const initialObject: ISidebarObject = JSON.parse(JSON.stringify(themeConfig.sidebar));
files = files.sort((a, b) => {
return initialObject[`/${folder}/`].indexOf(a) - initialObject[`/${folder}/`].indexOf(b)
});
files.map((file) => {
const frontmatter = getFrontmatterFromPath(Path.join(folder, file));
let data = fs.readFileSync(Path.join(folder, file)).toString();
data = data
.replace(/---([\s\S\n]+?)---/, '')
.replace(/(#.*?)\s/g, '$1## ')
.replace(/\[\[toc\]\]/g, '');
//set heading
const regex = /[\s\n]#{3}\s(\w+)/;
const match = data.match(regex);
if (match) {
data = data.replace(regex, '### $1');
} else {
data = `\n\n### ${file.replace('.md', '')}\n\n`.concat(data);
}
if (frontmatter) {
data = data.replace(/<Header\/>/g, `<Header label="${frontmatter.description}" />`)
}
str = str.concat(data, '\n', '________', '\n\n');
});
});
fs.ensureFileSync('./all/README.md');
fs.writeFileSync('./all/README.md', str);
}
function caps(str: string) {
str = str[0].toUpperCase() + str.substr(1, str.length);
return str;
}
async function createRoutes() {
let results: any[] = await recc('./', ['README.md', reccursiveIgnoreFunction])
results = results.map((res) => {
const redirect = res.replace(/[\\]/g, '/').replace('.md', '');
return {
redirect: '/'.concat(redirect, '.html'),
path: '/'.concat(redirect, '/')
}
});
fs.writeFileSync('./.vuepress/routes.json', (JSON.stringify(results, undefined, 4)));
}
interface ISidebarObject {
[name: string]: string[];
} | the_stack |
import {
MockERC20Instance,
UniswapV2FactoryInstance,
UniswapV2Router02Instance,
UniswapV2PairInstance,
BankInstance,
SimpleBankConfigInstance,
WETHInstance,
IbETHRouterInstance,
} from '../typechain';
const { BN, ether, expectRevert } = require('@openzeppelin/test-helpers');
const UniswapV2Factory = artifacts.require('UniswapV2Factory');
const UniswapV2Router02 = artifacts.require('UniswapV2Router02');
const UniswapV2Pair = artifacts.require('UniswapV2Pair');
const Bank = artifacts.require('Bank');
const SimpleBankConfig = artifacts.require('SimpleBankConfig');
const IbETHRouter = artifacts.require('IbETHRouter');
const WETH = artifacts.require('WETH');
const MockERC20 = artifacts.require('MockERC20');
// Assert that actual is less than 0.01% difference from expected
function assertAlmostEqual(expected: string | BN, actual: string | BN) {
const expectedBN = BN.isBN(expected) ? expected : new BN(expected);
const actualBN = BN.isBN(actual) ? actual : new BN(actual);
const diffBN = expectedBN.gt(actualBN) ? expectedBN.sub(actualBN) : actualBN.sub(expectedBN);
return assert.ok(
diffBN.lt(expectedBN.div(new BN('1000'))),
`Not almost equal. Expected ${expectedBN.toString()}. Actual ${actualBN.toString()}`
);
}
const FOREVER = '2000000000';
contract('IbETHRouter', ([deployer, alice]) => {
const RESERVE_POOL_BPS = new BN('1000'); // 10% reserve pool
const KILL_PRIZE_BPS = new BN('1000'); // 10% Kill prize
const INTEREST_RATE = new BN('3472222222222'); // 30% per year
const MIN_DEBT_SIZE = ether('1'); // 1 ETH min debt size
const DEFAULT_ETH_BALANCE = ether('10000');
let factory: UniswapV2FactoryInstance;
let weth: WETHInstance;
let router: UniswapV2Router02Instance;
let ibETHRouter: IbETHRouterInstance;
let token: MockERC20Instance;
let lp: UniswapV2PairInstance;
let config: SimpleBankConfigInstance;
let bank: BankInstance;
beforeEach(async () => {
factory = await UniswapV2Factory.new(deployer);
weth = await WETH.new();
router = await UniswapV2Router02.new(factory.address, weth.address);
token = await MockERC20.new('ALPHA', 'ALPHA');
await token.mint(deployer, ether('10000'));
await token.mint(alice, ether('100'));
config = await SimpleBankConfig.new(MIN_DEBT_SIZE, INTEREST_RATE, RESERVE_POOL_BPS, KILL_PRIZE_BPS);
bank = await Bank.new(config.address);
await bank.deposit({ value: ether('100') });
await bank.deposit({ from: alice, value: ether('10') });
expect(await web3.eth.getBalance(bank.address)).to.be.bignumber.equal(ether('110'));
expect(await bank.balanceOf(alice)).to.be.bignumber.equal(ether('10'));
expect(await bank.balanceOf(deployer)).to.be.bignumber.equal(ether('100'));
// Send some ETH to Bank to create interest
// This make 1 ibETH = 1.045454545454545454 ETH
await web3.eth.sendTransaction({ from: deployer, to: bank.address, value: ether('5') });
// Create ibETH-MOCK pair
await factory.createPair(bank.address, token.address);
lp = await UniswapV2Pair.at(await factory.getPair(token.address, bank.address));
ibETHRouter = await IbETHRouter.new(router.address, bank.address, token.address);
// Deployer adds 10000 MOCK + 100 ibETH, price 100 MOCK : 1 ibETH
await token.approve(router.address, ether('10000'));
await bank.approve(router.address, ether('100'));
await router.addLiquidity(token.address, bank.address, ether('10000'), ether('100'), '0', '0', deployer, FOREVER);
});
it('should receive some interest when redeem ibETH', async () => {
await bank.withdraw(await bank.balanceOf(alice), { from: alice });
expect(await bank.balanceOf(alice)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(alice))).to.be.bignumber.above(DEFAULT_ETH_BALANCE);
});
it('should be able to add liquidity to ibETH-MOCK with ETH and MOCK', async () => {
await token.approve(ibETHRouter.address, ether('100'), { from: alice });
await ibETHRouter.addLiquidityETH(ether('100'), 0, 0, alice, FOREVER, {
from: alice,
value: ether('1'),
});
expect(await lp.balanceOf(alice)).to.be.bignumber.above(ether('0'));
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
it('should revert when add liquidity to ibETH-MOCK with too little ETH', async () => {
await token.approve(ibETHRouter.address, ether('100'), { from: alice });
expectRevert(
ibETHRouter.addLiquidityETH(ether('100'), 0, ether('50'), alice, FOREVER, {
from: alice,
value: ether('1'),
}),
'IbETHRouter: require more ETH than amountETHmin'
);
expect(await lp.balanceOf(alice)).to.be.bignumber.equal(ether('0'));
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
it('should revert when add liquidity to ibETH-MOCK with too little MOCK', async () => {
await token.approve(ibETHRouter.address, ether('100'), { from: alice });
expectRevert(
ibETHRouter.addLiquidityETH(ether('100'), ether('1000'), 0, alice, FOREVER, {
from: alice,
value: ether('1'),
}),
'UniswapV2Router: INSUFFICIENT_A_AMOUNT'
);
expect(await lp.balanceOf(alice)).to.be.bignumber.equal(ether('0'));
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
it('should be able to add liquidity with excess ETH and get dust ETH back', async () => {
await token.approve(ibETHRouter.address, ether('100'), { from: alice });
const aliceETHBalanceBefore = new BN(await web3.eth.getBalance(alice));
const aliceTokenBalanceBefore = await token.balanceOf(alice);
// Adding 100 MOCK requires adding 1 ibETH
// Deposit 1.045454545454545454 ETH, yield 1 ibETH
// Only need 1.045454545454545454 ETH, but add 10 ETH
await ibETHRouter.addLiquidityETH(ether('100'), 0, 0, alice, FOREVER, {
from: alice,
value: ether('10'),
});
expect(await lp.balanceOf(alice)).to.be.bignumber.above(ether('0'));
assertAlmostEqual(
new BN(await web3.eth.getBalance(alice)),
aliceETHBalanceBefore.sub(ether('1.045454545454545454'))
);
expect(await token.balanceOf(alice)).to.be.bignumber.equal(aliceTokenBalanceBefore.sub(ether('100')));
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
it('should be able to add liquidity with excess MOCK and has some leftover', async () => {
await token.approve(ibETHRouter.address, ether('100'), { from: alice });
const aliceETHBalanceBefore = new BN(await web3.eth.getBalance(alice));
const aliceTokenBalanceBefore = await token.balanceOf(alice);
// Add 100 MOCK requires adding 1 ibETH
// Deposit 0.1 ETH, yield 0.095652173913043478 ibETH
// Only need 9.565217391304347800 MOCK, but add 100 MOCK
await ibETHRouter.addLiquidityETH(ether('100'), 0, 0, alice, FOREVER, {
from: alice,
value: ether('0.1'),
});
expect(await lp.balanceOf(alice)).to.be.bignumber.above(ether('0'));
assertAlmostEqual(new BN(await web3.eth.getBalance(alice)), aliceETHBalanceBefore.sub(ether('0.1')));
expect(await token.balanceOf(alice)).to.be.bignumber.equal(
aliceTokenBalanceBefore.sub(ether('9.565217391304347800'))
);
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
it('should be able to add liquidity optimally with only ibETH', async () => {
const aliceIbETHBalanceBefore = await bank.balanceOf(alice);
await bank.approve(ibETHRouter.address, ether('5'), { from: alice });
// Sending 5 ibETH, 5*0.5 = 2.5 ibETH should be used to swap optimally for MOCK
// Should get slightly less than 250 MOCK from swap.
// So should add liquidity total of ~250 MOCK and ~2.5 ibETH and get ~25 lpToken
await ibETHRouter.addLiquidityTwoSidesOptimal(ether('5'), 0, 0, alice, FOREVER, {
from: alice,
});
expect(await lp.balanceOf(alice)).to.be.bignumber.equal(ether('24.657979004220051623'));
expect(await bank.balanceOf(alice)).to.be.bignumber.closeTo(aliceIbETHBalanceBefore.sub(ether('5')), new BN('1'));
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
it('should be able to add liquidity optimally with only MOCK', async () => {
const aliceTokenBalanceBefore = await token.balanceOf(alice);
await token.approve(ibETHRouter.address, ether('50'), { from: alice });
// Sending 50 MOCK, 50*0.5 = 25 MOCK should be used to swap optimally for ibETH
// Should get slightly less than 0.25 ibETH from swap.
// So should add liquidity total of ~25 MOCK and ~0.25 ibETH and get ~2.5 lpToken
await ibETHRouter.addLiquidityTwoSidesOptimal(0, ether('50'), 0, alice, FOREVER, {
from: alice,
});
expect(await lp.balanceOf(alice)).to.be.bignumber.equal(ether('2.493131844569650832'));
expect(await token.balanceOf(alice)).to.be.bignumber.closeTo(aliceTokenBalanceBefore.sub(ether('50')), new BN('1'));
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
it('should be able to add liquidity optimally with more ibETH than required', async () => {
const aliceTokenBalanceBefore = await token.balanceOf(alice);
const aliceIbETHBalanceBefore = await bank.balanceOf(alice);
await bank.approve(ibETHRouter.address, ether('5'), { from: alice });
await token.approve(ibETHRouter.address, ether('50'), { from: alice });
// Add 50 MOCK requires adding 0.5 ibETH
// Sending 5 ibETH, (5-0.5)*0.5 = 2.25 ibETH should be used to swap optimally for MOCK
// Should get slightly less than 225 MOCK from swap.
// So should add liquidity total of ~275 MOCK and ~2.75 ibETH and get ~27.5 lpToken
await ibETHRouter.addLiquidityTwoSidesOptimal(ether('5'), ether('50'), 0, alice, FOREVER, {
from: alice,
});
expect(await lp.balanceOf(alice)).to.be.bignumber.equal(ether('27.220190062987375140'));
expect(await token.balanceOf(alice)).to.be.bignumber.closeTo(aliceTokenBalanceBefore.sub(ether('50')), new BN('1'));
expect(await bank.balanceOf(alice)).to.be.bignumber.closeTo(aliceIbETHBalanceBefore.sub(ether('5')), new BN('1'));
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
it('should be able to add liquidity optimally with more MOCK than required', async () => {
const aliceTokenBalanceBefore = await token.balanceOf(alice);
const aliceIbETHBalanceBefore = await bank.balanceOf(alice);
await bank.approve(ibETHRouter.address, ether('0.1'), { from: alice });
await token.approve(ibETHRouter.address, ether('50'), { from: alice });
// Add 0.1 ibETH requires adding 10 MOCK
// Sending 50 MOCK, (50-10)*0.5 = 20 MOCK should be used to swap optimally for ibETH
// Should get slightly less than 0.2 ibETH from swap.
// So should add liquidity total of ~30 MOCK and ~0.3 ibETH and get ~3 lpToken
await ibETHRouter.addLiquidityTwoSidesOptimal(ether('0.1'), ether('50'), 0, alice, FOREVER, {
from: alice,
});
expect(await lp.balanceOf(alice)).to.be.bignumber.equal(ether('2.995004473319087933'));
expect(await token.balanceOf(alice)).to.be.bignumber.closeTo(aliceTokenBalanceBefore.sub(ether('50')), new BN('1'));
expect(await bank.balanceOf(alice)).to.be.bignumber.closeTo(aliceIbETHBalanceBefore.sub(ether('0.1')), new BN('1'));
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
it('should revert when add liquidity optimally with less lpToken than minumum specified', async () => {
const aliceTokenBalanceBefore = await token.balanceOf(alice);
const aliceIbETHBalanceBefore = await bank.balanceOf(alice);
await bank.approve(ibETHRouter.address, ether('0.1'), { from: alice });
await token.approve(ibETHRouter.address, ether('50'), { from: alice });
// Add 0.1 ibETH requires adding 10 MOCK
// Sending 50 MOCK, (50-10)*0.5 = 20 MOCK should be used to swap optimally for ibETH
// Should get slightly less than 0.2 ibETH from swap.
// So should add liquidity total of ~30 MOCK and ~0.3 ibETH and get ~3 lpToken, but require at least 100 lpToken
expectRevert(
ibETHRouter.addLiquidityTwoSidesOptimal(ether('0.1'), ether('50'), ether('100'), alice, FOREVER, {
from: alice,
}),
'IbETHRouter: receive less lpToken than amountLPMin'
);
expect(await lp.balanceOf(alice)).to.be.bignumber.equal(ether('0'));
expect(await token.balanceOf(alice)).to.be.bignumber.equal(aliceTokenBalanceBefore);
expect(await bank.balanceOf(alice)).to.be.bignumber.equal(aliceIbETHBalanceBefore);
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
it('should be able to add liquidity optimally with only ETH', async () => {
const aliceETHBalanceBefore = new BN(await web3.eth.getBalance(alice));
// Depositing 5 ETH yield 4.7826087 ibETH
// Sending 4.7826087 ibETH, 4.7826087*0.5 = 2.39130435 ibETH should be used to swap optimally for MOCK
// Should get slightly less than 239.130435 MOCK from swap.
// So should add liquidity total of ~239.13 MOCK and ~2.39 ibETH and get ~23.9 lpToken
await ibETHRouter.addLiquidityTwoSidesOptimalETH(0, 0, alice, FOREVER, {
from: alice,
value: ether('5'),
});
expect(await lp.balanceOf(alice)).to.be.bignumber.equal(ether('23.598262739768173752'));
expect(new BN(await web3.eth.getBalance(alice))).to.be.bignumber.closeTo(
aliceETHBalanceBefore.sub(ether('5')),
ether('0.01')
);
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
it('should be able to add liquidity optimally with more ETH than required', async () => {
const aliceTokenBalanceBefore = await token.balanceOf(alice);
const aliceETHBalanceBefore = new BN(await web3.eth.getBalance(alice));
await token.approve(ibETHRouter.address, ether('50'), { from: alice });
// Add 50 MOCK requires adding 0.5 ibETH
// Depositing 5 ETH yield 4.7826087 ibETH
// Sending 4.7826087 ibETH, (4.7826087-0.5)*0.5 = 2.14130435 ibETH should be used to swap optimally for MOCK
// Should get slightly less than 214.130435 MOCK from swap.
// So should add liquidity total of ~264 MOCK and ~2.64 ibETH and get ~26.4 lpToken
await ibETHRouter.addLiquidityTwoSidesOptimalETH(ether('50'), 0, alice, FOREVER, {
from: alice,
value: ether('5'),
});
expect(await lp.balanceOf(alice)).to.be.bignumber.equal(ether('26.157827816948699953'));
expect(await token.balanceOf(alice)).to.be.bignumber.closeTo(aliceTokenBalanceBefore.sub(ether('50')), new BN('1'));
expect(new BN(await web3.eth.getBalance(alice))).to.be.bignumber.closeTo(
aliceETHBalanceBefore.sub(ether('5')),
ether('0.01')
);
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
it('should be able to add liquidity optimally with less ETH than required', async () => {
const aliceTokenBalanceBefore = await token.balanceOf(alice);
const aliceETHBalanceBefore = new BN(await web3.eth.getBalance(alice));
await token.approve(ibETHRouter.address, ether('50'), { from: alice });
// Depositing 0.1 ETH yield 0.095652174 ibETH
// Add 0.095652174 ibETH requires adding 9.5652174 MOCK
// Sending 50 MOCK, (50-9.5652174)*0.5 = 20.2173913 MOCK should be used to swap optimally for ibETH
// Should get slightly less than 0.202 ibETH from swap.
// So should add liquidity total of ~29.7826087 MOCK and ~0.297 ibETH and get ~2.97 lpToken
await ibETHRouter.addLiquidityTwoSidesOptimalETH(ether('50'), 0, alice, FOREVER, {
from: alice,
value: ether('0.1'),
});
expect(await lp.balanceOf(alice)).to.be.bignumber.equal(ether('2.973189122784300740'));
expect(await token.balanceOf(alice)).to.be.bignumber.closeTo(aliceTokenBalanceBefore.sub(ether('50')), new BN('1'));
expect(new BN(await web3.eth.getBalance(alice))).to.be.bignumber.closeTo(
aliceETHBalanceBefore.sub(ether('0.1')),
ether('0.01')
);
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
it('should revert when add liquidity optimally ETH with less lpToken than minumum specified', async () => {
const aliceTokenBalanceBefore = await token.balanceOf(alice);
const aliceETHBalanceBefore = new BN(await web3.eth.getBalance(alice));
await token.approve(ibETHRouter.address, ether('50'), { from: alice });
// Add 50 MOCK requires adding 0.5 ibETH
// Depositing 5 ETH yield 4.7826087 ibETH
// Sending 4.7826087 ibETH, (4.7826087-0.5)*0.5 = 2.14130435 ibETH should be used to swap optimally for MOCK
// Should get slightly less than 214.130435 MOCK from swap.
// So should add liquidity total of ~264 MOCK and ~2.64 ibETH and get ~26.4 lpToken
expectRevert(
ibETHRouter.addLiquidityTwoSidesOptimalETH(ether('50'), ether('100'), alice, FOREVER, {
from: alice,
value: ether('5'),
}),
'IbETHRouter: receive less lpToken than amountLPMin'
);
expect(await lp.balanceOf(alice)).to.be.bignumber.equal(ether('0'));
expect(await token.balanceOf(alice)).to.be.bignumber.equal(aliceTokenBalanceBefore);
expect(new BN(await web3.eth.getBalance(alice))).to.be.bignumber.closeTo(aliceETHBalanceBefore, ether('0.01'));
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
it('should be able to remove liquidity and get ETH and MOCK back', async () => {
await token.approve(ibETHRouter.address, ether('100'), { from: alice });
await ibETHRouter.addLiquidityETH(ether('100'), 0, 0, alice, FOREVER, {
from: alice,
value: ether('1'),
});
const aliceLPBalanceBefore = await lp.balanceOf(alice);
const aliceTokenBalanceBefore = await token.balanceOf(alice);
const aliceETHBalanceBefore = new BN(await web3.eth.getBalance(alice));
expect(aliceLPBalanceBefore).to.be.bignumber.above(ether('0'));
// Deposit 1 ETH, yield 0.95652173913043478 ibETH
// Add liquidity with 0.95652173913043478 ibETH and 95.652173913043478 MOCK
// So, removeLiquidity should get 1 ETH and 95.652173913043478 MOCK back
await lp.approve(ibETHRouter.address, aliceLPBalanceBefore, { from: alice });
await ibETHRouter.removeLiquidityETH(aliceLPBalanceBefore, 0, 0, alice, FOREVER, {
from: alice,
});
expect(await lp.balanceOf(alice)).to.be.bignumber.equal(ether('0'));
expect(await token.balanceOf(alice)).to.be.bignumber.equal(
aliceTokenBalanceBefore.add(ether('95.652173913043478200'))
);
assertAlmostEqual(new BN(await web3.eth.getBalance(alice)), aliceETHBalanceBefore.add(ether('1')));
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
it('should revert when remove liquidity and receive too little ETH', async () => {
await token.approve(ibETHRouter.address, ether('100'), { from: alice });
await ibETHRouter.addLiquidityETH(ether('100'), 0, 0, alice, FOREVER, {
from: alice,
value: ether('1'),
});
const aliceLPBalanceBefore = await lp.balanceOf(alice);
expect(aliceLPBalanceBefore).to.be.bignumber.above(ether('0'));
// Deposit 1 ETH, yield 0.95652173913043478 ibETH
// Add liquidity with 0.95652173913043478 ibETH and 95.65217391304347800 MOCK
// So, removeLiquidity should get 1 ETH and 95.65217391304347800 MOCK back
await lp.approve(ibETHRouter.address, aliceLPBalanceBefore, { from: alice });
expectRevert(
ibETHRouter.removeLiquidityETH(aliceLPBalanceBefore, 0, ether('100'), alice, FOREVER, {
from: alice,
}),
'IbETHRouter: receive less ETH than amountETHmin'
);
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
it('should revert when remove liquidity and receive too little MOCK', async () => {
await token.approve(ibETHRouter.address, ether('100'), { from: alice });
await ibETHRouter.addLiquidityETH(ether('100'), 0, 0, alice, FOREVER, {
from: alice,
value: ether('1'),
});
const aliceLPBalanceBefore = await lp.balanceOf(alice);
expect(aliceLPBalanceBefore).to.be.bignumber.above(ether('0'));
// Deposit 1 ETH, yield 0.95652173913043478 ibETH
// Add liquidity with 0.95652173913043478 ibETH and 95.65217391304347800 MOCK
// So, removeLiquidity should get 1 ETH and 95.65217391304347800 MOCK back
await lp.approve(ibETHRouter.address, aliceLPBalanceBefore, { from: alice });
expectRevert(
ibETHRouter.removeLiquidityETH(aliceLPBalanceBefore, ether('1000'), 0, alice, FOREVER, {
from: alice,
}),
'UniswapV2Router: INSUFFICIENT_A_AMOUNT'
);
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
it('should be able to remove liquidity (all MOCK) and get only MOCK back', async () => {
await token.approve(ibETHRouter.address, ether('100'), { from: alice });
await ibETHRouter.addLiquidityETH(ether('100'), 0, 0, alice, FOREVER, {
from: alice,
value: ether('1'),
});
const aliceLPBalanceBefore = await lp.balanceOf(alice);
const aliceTokenBalanceBefore = await token.balanceOf(alice);
const aliceETHBalanceBefore = new BN(await web3.eth.getBalance(alice));
expect(aliceLPBalanceBefore).to.be.bignumber.above(ether('0'));
// Deposit 1 ETH, yield 0.95652173913043478 ibETH
// Add liquidity with 0.95652173913043478 ibETH and 95.65217391304347800 MOCK
// So, removeLiquidityAllAlpha should get slightly less than 2*95.65217391304347800 = 191.304348 MOCK (190.116529919717225111)
await lp.approve(ibETHRouter.address, aliceLPBalanceBefore, { from: alice });
await ibETHRouter.removeLiquidityAllAlpha(aliceLPBalanceBefore, 0, alice, FOREVER, {
from: alice,
});
expect(await lp.balanceOf(alice)).to.be.bignumber.equal(ether('0'));
expect(await token.balanceOf(alice)).to.be.bignumber.equal(
aliceTokenBalanceBefore.add(ether('190.116529919717225111'))
);
assertAlmostEqual(new BN(await web3.eth.getBalance(alice)), aliceETHBalanceBefore);
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
it('should revert when remove liquidity (all MOCK) and receive too little MOCK', async () => {
await token.approve(ibETHRouter.address, ether('100'), { from: alice });
await ibETHRouter.addLiquidityETH(ether('100'), 0, 0, alice, FOREVER, {
from: alice,
value: ether('1'),
});
const aliceLPBalanceBefore = await lp.balanceOf(alice);
expect(aliceLPBalanceBefore).to.be.bignumber.above(ether('0'));
// Deposit 1 ETH, yield 0.95652173913043478 ibETH
// Add liquidity with 0.95652173913043478 ibETH and 95.65217391304347800 MOCK
// So, removeLiquidityAllAlpha should get slightly less than 2*95.65217391304347800 = 191.304348 MOCK (190.116529919717225111)back
await lp.approve(ibETHRouter.address, aliceLPBalanceBefore, { from: alice });
expectRevert(
ibETHRouter.removeLiquidityAllAlpha(aliceLPBalanceBefore, ether('1000'), alice, FOREVER, {
from: alice,
}),
'IbETHRouter: receive less Alpha than amountAlphaMin'
);
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
it('should be able to swap exact ETH for MOCK', async () => {
const aliceETHBalanceBefore = new BN(await web3.eth.getBalance(alice));
const aliceBalanceBefore = await token.balanceOf(alice);
// 1 ETH, yield 0.95652173913043478 ibETH
// so should get slightly less than 95.6 MOCK back (94.464356006673746911)
await ibETHRouter.swapExactETHForAlpha(0, alice, FOREVER, {
from: alice,
value: ether('1'),
});
assertAlmostEqual(await web3.eth.getBalance(alice), aliceETHBalanceBefore.sub(ether('1')));
expect(await token.balanceOf(alice)).to.be.bignumber.equal(aliceBalanceBefore.add(ether('94.464356006673746911')));
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
it('should revert when swap exact ETH for MOCK and receive too little MOCK', async () => {
expectRevert(
ibETHRouter.swapExactETHForAlpha(ether('1000'), alice, FOREVER, {
from: alice,
value: ether('1'),
}),
'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'
);
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
it('should be able to swap MOCK for exact ETH', async () => {
const aliceETHBalanceBefore = new BN(await web3.eth.getBalance(alice));
const aliceTokenBalanceBefore = await token.balanceOf(alice);
await token.approve(ibETHRouter.address, ether('100'), { from: alice });
// 0.9 ETH, yield 0.860869565 ibETH
// so should use slightly more than 86.08 MOCK (87.095775529377361165)
await ibETHRouter.swapAlphaForExactETH(ether('0.9'), ether('100'), alice, FOREVER, {
from: alice,
});
assertAlmostEqual(await web3.eth.getBalance(alice), aliceETHBalanceBefore.add(ether('0.9')));
expect(await token.balanceOf(alice)).to.be.bignumber.equal(
aliceTokenBalanceBefore.sub(ether('87.095775529377361165'))
);
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
it('should revert when swap MOCK for exact ETH given too little MOCK', async () => {
await token.approve(ibETHRouter.address, ether('100'), { from: alice });
// 0.9 ETH, yield 0.860869565 ibETH
// so should use slightly more than 86.08 MOCK (87.095775529377361063)
expectRevert(
ibETHRouter.swapAlphaForExactETH(ether('0.9'), ether('1'), alice, FOREVER, {
from: alice,
}),
'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'
);
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
it('should be able to swap exact MOCK for ETH', async () => {
const aliceETHBalanceBefore = new BN(await web3.eth.getBalance(alice));
const aliceTokenBalanceBefore = await token.balanceOf(alice);
await token.approve(ibETHRouter.address, ether('100'), { from: alice });
// 100 MOCK, yield 1 ibETH
// so should get slightly less than 1.045 MOCK (1.032028854142382266)
await ibETHRouter.swapExactAlphaForETH(ether('100'), 0, alice, FOREVER, {
from: alice,
});
assertAlmostEqual(await web3.eth.getBalance(alice), aliceETHBalanceBefore.add(ether('1.032028854142382266')));
expect(await token.balanceOf(alice)).to.be.bignumber.equal(aliceTokenBalanceBefore.sub(ether('100')));
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
it('should revert when swap exact MOCK for ETH and receive too little ETH', async () => {
await token.approve(ibETHRouter.address, ether('100'), { from: alice });
// 100 MOCK, yield 1 ibETH
// so should get slightly less than 1.045 MOCK (1.032028854142382266)
expectRevert(
ibETHRouter.swapExactAlphaForETH(ether('100'), ether('1000'), alice, FOREVER, {
from: alice,
}),
'IbETHRouter: receive less ETH than amountETHmin'
);
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
it('should be able to swap ETH for exact MOCK with dust ETH back', async () => {
const aliceETHBalanceBefore = new BN(await web3.eth.getBalance(alice));
const aliceTokenBalanceBefore = await token.balanceOf(alice);
// 100 MOCK need ~1 ibETH
// Deposit 1.045454545454545454 ETH, yield 1 ibETH
// so should get add slightly more than 1.045 ETH (1.059192269185886404 ETH)
await ibETHRouter.swapETHForExactAlpha(ether('100'), alice, FOREVER, {
from: alice,
value: ether('1.1'),
});
assertAlmostEqual(await web3.eth.getBalance(alice), aliceETHBalanceBefore.sub(ether('1.059192269185886404')));
expect(await token.balanceOf(alice)).to.be.bignumber.equal(aliceTokenBalanceBefore.add(ether('100')));
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
it('should be able to swap ETH for exact MOCK with no dust ETH back', async () => {
const aliceETHBalanceBefore = new BN(await web3.eth.getBalance(alice));
const aliceTokenBalanceBefore = await token.balanceOf(alice);
// 100 MOCK need ~1 ibETH
// Deposit 1.045454545454545454 ETH, yield 1 ibETH
// so should get add slightly more than 1.045 ETH (1.059192269185886404 ETH)
await ibETHRouter.swapETHForExactAlpha(ether('100'), alice, FOREVER, {
from: alice,
value: ether('1.059192269185886403'),
});
assertAlmostEqual(await web3.eth.getBalance(alice), aliceETHBalanceBefore.sub(ether('1.059192269185886404')));
expect(await token.balanceOf(alice)).to.be.bignumber.equal(aliceTokenBalanceBefore.add(ether('100')));
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
it('should revert when swap ETH for exact MOCK given too little ETH', async () => {
expectRevert(
ibETHRouter.swapETHForExactAlpha(ether('100'), alice, FOREVER, {
from: alice,
value: ether('0.1'),
}),
'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'
);
expect(await token.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(await bank.balanceOf(ibETHRouter.address)).to.be.bignumber.equal(ether('0'));
expect(new BN(await web3.eth.getBalance(ibETHRouter.address))).to.be.bignumber.equal(ether('0'));
});
}); | the_stack |
import React, {FC, useEffect, useRef, useState} from "react";
import {useHistory} from 'react-router-dom'
import {Button, Form, Input, message, Switch, Select, Upload} from "antd";
import {PlusOutlined} from '@ant-design/icons';
import MdEditor from "../../components/mdEditor/mdEditor";
import {addArticle, editArticle, getArticleDetail} from "../../api/modules/article";
import {getAllCategory} from "../../api/modules/category";
import {getAllTag} from "../../api/modules/tag";
import {getQNToken, uploadToQN} from "../../api/modules/qn";
const {Option} = Select;
const ArticlePublish: FC = () => {
const [form] = Form.useForm();
const history = useHistory()
const md = useRef(null)
const [mdRef, setMdRef] = useState()
const domain = 'https://upload-z0.qiniup.com' // 七牛云的上传地址,根据自己所在地区选择,我这里是华东
const qiniuaddr = 'static.brandhuang.com' // 这是七牛云空间的外链默认域名,可换成自己的 p063wr224.bkt.clouddn.com
const [artTitle, setArtTitle] = useState('') // 文章标题
const [abstract, setAbstract] = useState('') // 文章摘要
const [category, setCategory] = useState('') // 文章分类
const [tag, setTag] = useState() // 文章标签
const [thumbnail, setThumbnail] = useState('') // 文章缩略图
const [tagList, setTagList] = useState([]) // 标签列表
const [categoryList, setCategoryList] = useState([]) // 分类列表
const [mdContent, setMdContent] = useState('') // 回填 md 数据
const [articleType, setArticleType] = useState('add') // 编辑或者添加
const [artDiscuss, setArtDiscuss] = useState(true) // 是否开启文章评论,默认开启
let queryId = history.location.state // 文章id
const uploadImage = (file: any) => {
let filetype = ''
if (file.type === 'image/png') {
filetype = 'png'
} else {
filetype = 'jpg'
}
// 重命名要上传的文件
const keyname = sessionStorage.getItem('username') + '-content-' + new Date().getTime() + '.' + filetype
getQNToken().then(res => {
const formdata = new FormData()
formdata.append('file', file)
formdata.append('token', res.data)
formdata.append('key', keyname)
// 获取到凭证之后再将文件上传到七牛云空间
uploadToQN(domain, formdata).then((result: { key: string; }) => {
let avatar = 'http://' + qiniuaddr + '/' + result.key
// 上传图片成功后,将url插入markdown中
mdRef.current.addImg(avatar)
})
})
}
const updateContent = (content: any) => {
form.setFieldsValue({
content: content,
})
}
useEffect(() => {
setMdRef(md)
}, [md])
useEffect(() => {
if (queryId) {
setArticleType('edit')
getArticleDetail({
id: queryId
}).then((res: any) => {
if (res.code === 200) {
setArtTitle(res.data.artTitle)
setAbstract(res.data.abstract)
setMdContent(res.data.content)
setCategory(res.data.category)
setTag(res.data.tag)
setThumbnail(res.data.thumbnail)
setArtDiscuss(!!res.data.artDiscuss)
form.setFieldsValue({
artTitle: res.data.artTitle,
artType: res.data.artType,
abstract: res.data.abstract,
category: res.data.category,
tag: res.data.tag.split(','),
thumbnail: res.data.thumbnail,
content: res.data.content,
artDiscuss: res.data.artDiscuss,
})
}
})
} else {
form.setFieldsValue({
artDiscuss: artDiscuss,
})
setArticleType('add')
}
}, [queryId])
useEffect(() => {
getAllCategory().then(res => {
if (res.code === 200) {
res.data.map((item: any) => {
item.id = item.id.toString()
})
setCategoryList(res.data)
}
}).catch(err => {
console.log(err)
})
getAllTag().then(res => {
if (res.code === 200) {
res.data.map((item: any) => {
item.id = item.id.toString()
})
setTagList(res.data)
}
}).catch(err => {
console.log(err)
})
}, [])
const saveData = async () => {
// 通过 mdRef.current.getInputData().md 获取输入的 md 格式数据
// 通过 mdRef.current.getInputData().mdToHtml 获取输入的 转为 HTML 格式数据
// let mdStr = mdRef.current.getInputData().md
try {
const values = await form.validateFields();
if (articleType === 'add') {
// 新增文章
let params = {
artTitle: values.artTitle,
artType: values.artType,
abstract: values.abstract,
thumbnail: values.thumbnail,
content: values.content,
category: values.category,
tag: values.tag.join(','),
artDiscuss: Number(artDiscuss)
}
addArticle(params).then(res => {
message.success('文章添加成功')
history.push('/article/list')
}).catch(err => {
console.log(err)
})
} else if (articleType === 'edit') {
// 编辑文章
let params = {
id: queryId,
artTitle: values.artTitle,
artType: values.artType,
abstract: values.abstract,
thumbnail: values.thumbnail,
content: values.content,
category: values.category,
tag: values.tag.join(','),
artDiscuss: Number(artDiscuss)
}
editArticle(params).then(res => {
message.success('文章修改成功')
history.push('/article/list')
}).catch(err => {
console.log(err)
})
}
} catch (e) {
}
}
// 图片上传七牛云
const uploadImg = (req: any) => {
// let config = {
// headers: { 'Content-Type': 'multipart/form-data' }
// }
let filetype = ''
if (req.file.type === 'image/png') {
filetype = 'png'
} else {
filetype = 'jpg'
}
// 重命名要上传的文件
const keyname = sessionStorage.getItem('username') + '-thumbnail-' + new Date().getTime() + '.' + filetype
getQNToken().then(res => {
const formdata = new FormData()
formdata.append('file', req.file)
formdata.append('token', res.data)
formdata.append('key', keyname)
// 获取到凭证之后再将文件上传到七牛云空间
uploadToQN(domain, formdata).then((result: { key: string; }) => {
let avatar = 'http://' + qiniuaddr + '/' + result.key
form.setFieldsValue({
thumbnail: avatar
})
setThumbnail(avatar)
})
})
}
// 图片上传前
const beforeUpload = (file: any, fileList: any) => {
const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
const isLt2M = file.size / 1024 / 1024 < 2
if (!isJPG) {
message.error('上传图片只能是 JPG 格式!')
}
if (!isLt2M) {
message.error('上传图片大小不能超过 2MB!')
}
return isJPG && isLt2M
}
const props = {
// action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
showUploadList: false,
fileList: [],
beforeUpload: beforeUpload,
customRequest: uploadImg,
};
return (
<Form form={form} className='article-p-container'>
<div className='article-p-left'>
<div style={{display: "flex", alignItems: "center"}}>
<Form.Item
label="标题"
style={{flex: 1,marginRight: '10px'}}
name="artTitle"
rules={[{required: true, message: '请填写文章标题'}]}
>
<Input placeholder={'请填写文章标题'} size='large'/>
</Form.Item>
<Form.Item
label="发布到"
name="artType"
initialValue={'code'}
rules={[{required: true, message: '请选择发布板块'}]}
>
<Select
size={"large"}
style={{width: '200px'}}
placeholder="请选择发布板块"
>
<Option value='code'>代码</Option>
<Option value='life'>生活</Option>
</Select>
</Form.Item>
</div>
<MdEditor defaultMd={mdContent} updateContent={updateContent} imgUpload={uploadImage} cRef={md} save/>
<Form.Item
name="content"
className='mdContent'
rules={[{required: true, message: '请填写文章内容'}]}
>
<Input size='large'
type={"hidden"}/>
</Form.Item>
</div>
<div className='article-p-right'>
<Form.Item
label="摘要"
className='abstract-item'
name="abstract"
rules={[{required: true, message: '请填写文章摘要!'}]}
>
<Input.TextArea
rows={5}
placeholder={'请填写文章摘要'}
style={{minHeight: '33px', resize: "none"}}/>
</Form.Item>
<Form.Item
label="分类"
name="category"
rules={[{required: true, message: '请选择一个分类!'}]}
>
<Select
placeholder="请选择文章分类"
allowClear
>
{
categoryList.map((cItem: any, cIndex) => {
return <Option value={cItem.id} key={'c-' + cIndex}>{cItem.categoryname}</Option>
})
}
</Select>
</Form.Item>
<Form.Item
label="标签"
name="tag"
initialValue={tag}
rules={[{required: true, message: '请选择至少一个标签'}]}
>
<Select
placeholder="请选择文章标签"
mode="multiple"
maxTagCount={3}
allowClear
>
{
tagList.map((tItem: any, tIndex) => {
return <Option value={tItem.id} key={'c-' + tIndex}>{tItem.tagname}</Option>
})
}
</Select>
</Form.Item>
<Form.Item
label="缩略图"
className='thumbnail-item'
name="thumbnail"
>
<Input size='large'
placeholder="文章缩略图"
onChange={(e) => {
setThumbnail(e.target.value)
}}/>
</Form.Item>
<Form.Item
className='thumbnail-item'
name="thumbnail"
>
<Upload
{...props}
className='upload-wrap'
>
{thumbnail ? <div className='upload-img-div'>
<img src={thumbnail} alt=""/>
</div> : <div className='upload-img-div plus-icon'>
<PlusOutlined/>
</div>}
</Upload>
</Form.Item>
<Form.Item label="评论"
name="artDiscuss">
<Switch checkedChildren="开启" unCheckedChildren="关闭" checked={artDiscuss} onChange={(e) => {
setArtDiscuss(e)
}}/>
</Form.Item>
<Form.Item>
<Button type={"primary"} onClick={saveData}>保存</Button>
</Form.Item>
</div>
</Form>
)
}
export default ArticlePublish | the_stack |
* @fileoverview Mappings for TeX parsing of the physics package.
*
* @author v.sorge@mathjax.org (Volker Sorge)
*/
import {EnvironmentMap, CommandMap, MacroMap, CharacterMap} from '../SymbolMap.js';
import PhysicsMethods from './PhysicsMethods.js';
import {TexConstant} from '../TexConstants.js';
import ParseMethods from '../ParseMethods.js';
import {TEXCLASS} from '../../../core/MmlTree/MmlNode.js';
/**
* Macros for physics package (section 2.1).
*/
new CommandMap('Physics-automatic-bracing-macros', {
'quantity': 'Quantity',
'qty': 'Quantity',
'pqty': ['Quantity', '(', ')', true],
'bqty': ['Quantity', '[', ']', true],
'vqty': ['Quantity', '|', '|', true],
'Bqty': ['Quantity', '\\{', '\\}', true],
'absolutevalue': ['Quantity', '|', '|', true],
'abs': ['Quantity', '|', '|', true],
'norm': ['Quantity', '\\|', '\\|', true],
'evaluated': 'Eval',
'eval': 'Eval',
'order': ['Quantity', '(', ')', true, 'O',
TexConstant.Variant.CALLIGRAPHIC],
'commutator': 'Commutator',
'comm': 'Commutator',
'anticommutator': ['Commutator', '\\{', '\\}'],
'acomm': ['Commutator', '\\{', '\\}'],
'poissonbracket': ['Commutator', '\\{', '\\}'],
'pb': ['Commutator', '\\{', '\\}']
}, PhysicsMethods);
/**
* Macros for physics package (section 2.2).
*/
new CharacterMap('Physics-vector-chars', ParseMethods.mathchar0mi, {
dotproduct: ['\u22C5', {mathvariant: TexConstant.Variant.BOLD}],
vdot: ['\u22C5', {mathvariant: TexConstant.Variant.BOLD}],
crossproduct: '\u00D7',
cross: '\u00D7',
cp: '\u00D7',
// This is auxiliary!
gradientnabla: ['\u2207', {mathvariant: TexConstant.Variant.BOLD}],
real: ['\u211C', {mathvariant: TexConstant.Variant.NORMAL}],
imaginary: ['\u2111', {mathvariant: TexConstant.Variant.NORMAL}]
});
new CommandMap('Physics-vector-macros', {
'vnabla': 'Vnabla',
'vectorbold': 'VectorBold',
'vb': 'VectorBold',
'vectorarrow': ['StarMacro', 1, '\\vec{\\vb', '{#1}}'],
'va': ['StarMacro', 1, '\\vec{\\vb', '{#1}}'],
'vectorunit': ['StarMacro', 1, '\\hat{\\vb', '{#1}}'],
'vu': ['StarMacro', 1, '\\hat{\\vb', '{#1}}'],
'gradient': ['OperatorApplication', '\\vnabla', '(', '['],
'grad': ['OperatorApplication', '\\vnabla', '(', '['],
'divergence': ['VectorOperator', '\\vnabla\\vdot', '(', '['],
'div': ['VectorOperator', '\\vnabla\\vdot', '(', '['],
'curl': ['VectorOperator', '\\vnabla\\crossproduct', '(', '['],
'laplacian': ['OperatorApplication', '\\nabla^2', '(', '['],
}, PhysicsMethods);
/**
* Macros for physics package (section 2.3).
*/
new CommandMap('Physics-expressions-macros', {
'sin': 'Expression',
'sinh': 'Expression',
'arcsin': 'Expression',
'asin': 'Expression',
'cos': 'Expression',
'cosh': 'Expression',
'arccos': 'Expression',
'acos': 'Expression',
'tan': 'Expression',
'tanh': 'Expression',
'arctan': 'Expression',
'atan': 'Expression',
'csc': 'Expression',
'csch': 'Expression',
'arccsc': 'Expression',
'acsc': 'Expression',
'sec': 'Expression',
'sech': 'Expression',
'arcsec': 'Expression',
'asec': 'Expression',
'cot': 'Expression',
'coth': 'Expression',
'arccot': 'Expression',
'acot': 'Expression',
'exp': ['Expression', false],
'log': 'Expression',
'ln': 'Expression',
'det': ['Expression', false],
'Pr': ['Expression', false],
// New expressions.
'tr': ['Expression', false],
'trace': ['Expression', false, 'tr'],
'Tr': ['Expression', false],
'Trace': ['Expression', false, 'Tr'],
'rank': 'NamedFn',
'erf': ['Expression', false],
'Residue': ['Macro', '\\mathrm{Res}'],
'Res': ['OperatorApplication', '\\Residue', '(', '[', '{'],
'principalvalue': ['OperatorApplication', '{\\cal P}'],
'pv': ['OperatorApplication', '{\\cal P}'],
'PV': ['OperatorApplication', '{\\rm P.V.}'],
'Re': ['OperatorApplication', '\\mathrm{Re}', '{'],
'Im': ['OperatorApplication', '\\mathrm{Im}', '{'],
// Old named functions.
'sine': ['NamedFn', 'sin'],
'hypsine': ['NamedFn', 'sinh'],
'arcsine': ['NamedFn', 'arcsin'],
'asine': ['NamedFn', 'asin'],
'cosine': ['NamedFn', 'cos'],
'hypcosine': ['NamedFn', 'cosh'],
'arccosine': ['NamedFn', 'arccos'],
'acosine': ['NamedFn', 'acos'],
'tangent': ['NamedFn', 'tan'],
'hyptangent': ['NamedFn', 'tanh'],
'arctangent': ['NamedFn', 'arctan'],
'atangent': ['NamedFn', 'atan'],
'cosecant': ['NamedFn', 'csc'],
'hypcosecant': ['NamedFn', 'csch'],
'arccosecant': ['NamedFn', 'arccsc'],
'acosecant': ['NamedFn', 'acsc'],
'secant': ['NamedFn', 'sec'],
'hypsecant': ['NamedFn', 'sech'],
'arcsecant': ['NamedFn', 'arcsec'],
'asecant': ['NamedFn', 'asec'],
'cotangent': ['NamedFn', 'cot'],
'hypcotangent': ['NamedFn', 'coth'],
'arccotangent': ['NamedFn', 'arccot'],
'acotangent': ['NamedFn', 'acot'],
'exponential': ['NamedFn', 'exp'],
'logarithm': ['NamedFn', 'log'],
'naturallogarithm': ['NamedFn', 'ln'],
'determinant': ['NamedFn', 'det'],
'Probability': ['NamedFn', 'Pr'],
}, PhysicsMethods);
/**
* Macros for physics package (section 2.4).
*/
new CommandMap('Physics-quick-quad-macros', {
'qqtext': 'Qqtext',
'qq': 'Qqtext',
'qcomma': ['Macro', '\\qqtext*{,}'],
'qc': ['Macro', '\\qqtext*{,}'],
'qcc': ['Qqtext', 'c.c.'],
'qif': ['Qqtext', 'if'],
'qthen': ['Qqtext', 'then'],
'qelse': ['Qqtext', 'else'],
'qotherwise': ['Qqtext', 'otherwise'],
'qunless': ['Qqtext', 'unless'],
'qgiven': ['Qqtext', 'given'],
'qusing': ['Qqtext', 'using'],
'qassume': ['Qqtext', 'assume'],
'qsince': ['Qqtext', 'since'],
'qlet': ['Qqtext', 'let'],
'qfor': ['Qqtext', 'for'],
'qall': ['Qqtext', 'all'],
'qeven': ['Qqtext', 'even'],
'qodd': ['Qqtext', 'odd'],
'qinteger': ['Qqtext', 'integer'],
'qand': ['Qqtext', 'and'],
'qor': ['Qqtext', 'or'],
'qas': ['Qqtext', 'as'],
'qin': ['Qqtext', 'in'],
}, PhysicsMethods);
/**
* Macros for physics package (section 2.5).
*/
new CommandMap('Physics-derivative-macros', {
'diffd': 'DiffD',
'flatfrac': ['Macro', '\\left.#1\\middle/#2\\right.', 2],
'differential': ['Differential', '\\diffd'],
'dd': ['Differential', '\\diffd'],
'variation': ['Differential', '\\delta'],
'var': ['Differential', '\\delta'],
'derivative': ['Derivative', 2, '\\diffd'],
'dv': ['Derivative', 2, '\\diffd'],
'partialderivative': ['Derivative', 3, '\\partial'],
'pderivative': ['Derivative', 3, '\\partial'],
'pdv': ['Derivative', 3, '\\partial'],
'functionalderivative': ['Derivative', 2, '\\delta'],
'fderivative': ['Derivative', 2, '\\delta'],
'fdv': ['Derivative', 2, '\\delta'],
}, PhysicsMethods);
/**
* Macros for physics package (section 2.6).
*/
new CommandMap('Physics-bra-ket-macros', {
'bra': 'Bra',
'ket': 'Ket',
'innerproduct': 'BraKet',
'ip': 'BraKet',
'braket': 'BraKet',
'outerproduct': 'KetBra',
'dyad': 'KetBra',
'ketbra': 'KetBra',
'op': 'KetBra',
'expectationvalue': 'Expectation',
'expval': 'Expectation',
'ev': 'Expectation',
'matrixelement': 'MatrixElement',
'matrixel': 'MatrixElement',
'mel': 'MatrixElement',
}, PhysicsMethods);
/**
* Macros for physics package (section 2.7).
*/
new CommandMap('Physics-matrix-macros', {
'matrixquantity': 'MatrixQuantity',
'mqty' : 'MatrixQuantity',
'pmqty': ['Macro', '\\mqty(#1)', 1],
'Pmqty': ['Macro', '\\mqty*(#1)', 1],
'bmqty': ['Macro', '\\mqty[#1]', 1],
'vmqty': ['Macro', '\\mqty|#1|', 1],
// Smallmatrices
'smallmatrixquantity': ['MatrixQuantity', true],
'smqty': ['MatrixQuantity', true],
'spmqty': ['Macro', '\\smqty(#1)', 1],
'sPmqty': ['Macro', '\\smqty*(#1)', 1],
'sbmqty': ['Macro', '\\smqty[#1]', 1],
'svmqty': ['Macro', '\\smqty|#1|', 1],
'matrixdeterminant': ['Macro', '\\vmqty{#1}', 1],
'mdet': ['Macro', '\\vmqty{#1}', 1],
'smdet': ['Macro', '\\svmqty{#1}', 1],
'identitymatrix': 'IdentityMatrix',
'imat': 'IdentityMatrix',
'xmatrix': 'XMatrix',
'xmat': 'XMatrix',
'zeromatrix': ['Macro', '\\xmat{0}{#1}{#2}', 2],
'zmat': ['Macro', '\\xmat{0}{#1}{#2}', 2],
'paulimatrix': 'PauliMatrix',
'pmat': 'PauliMatrix',
'diagonalmatrix': 'DiagonalMatrix',
'dmat': 'DiagonalMatrix',
'antidiagonalmatrix': ['DiagonalMatrix', true],
'admat': ['DiagonalMatrix', true]
}, PhysicsMethods);
/**
* Auxiliary environment map to define smallmatrix. This makes Physics
* independent of AmsMath.
*/
new EnvironmentMap('Physics-aux-envs', ParseMethods.environment, {
smallmatrix: ['Array', null, null, null, 'c', '0.333em', '.2em', 'S', 1]
}, PhysicsMethods);
/**
* Character map for braket package.
*/
new MacroMap('Physics-characters', {
'|': ['AutoClose', TEXCLASS.ORD], // texClass: TEXCLASS.ORD, // Have to push the closer as mml with special property
')': 'AutoClose',
']': 'AutoClose'
}, PhysicsMethods); | the_stack |
module TF {
export class Application {
config: Configuration;
router: Router;
root: string;
private express: EX.Application;
private declaration: Declaration;
private models: ModelInfo[] = [];
private controllers: ControllerInfo[] = [];
constructor(root: string) {
this.root = root;
this.config = new Configuration(root);
this.router = new Router();
// default settings
this.config.set('env', !process.env.NODE_ENV ? 'development' : process.env.NODE_ENV);
this.config.set('port', 3000);
this.config.set('assetPath', 'public');
this.config.set('view.path', 'app/views');
this.config.set('view.engine', 'ejs');
this.config.set('view.layout', false);
}
public configure(callback: () => void) {
callback.call(this);
}
public addDeclaration(filePath: string) {
this.declaration = new Declaration(path.join(this.root, filePath));
}
public addController(controller: any) {
if (controller.hasOwnProperty('configure'))
controller.configure();
var info = new ControllerInfo(controller, this.declaration);
this.controllers.push(info);
}
public addModel(model: any) {
if (model.hasOwnProperty('configure'))
model.configure();
var info = new ModelInfo(model, this.declaration);
this.models.push(info);
}
public start() {
this.buildExpress();
this.buildCollections();
this.buildRoutes();
var port = this.config.get('port');
this.express.listen(port);
console.log('Listening on port: ' + port);
}
private buildExpress() {
var express: any = require('express');
this.express = express();
this.express.set('views', path.join(this.root, this.config.get('view.path')));
this.express.set('view engine', this.config.get('view.engine'));
this.express.set('layout', this.config.get('view.layout'));
// add compression middleware
this.express.use(require('compression')());
// add logging middleware
var debugFormat = this.config.get('logging.format');
if (!!debugFormat)
this.express.use(require('morgan')(debugFormat));
// add body parser middleware
var bodyParser: any = require('body-parser');
this.express.use(bodyParser.urlencoded({ extended: true }));
this.express.use(bodyParser.json());
// add ejs layout middleware
this.express.use(require('express-ejs-layouts'));
}
private buildCollections() {
var Waterline = <WL.Waterline> require('waterline');
var adapterNames = Object.getOwnPropertyNames(this.config.get('adapters'));
var root = path.resolve(this.root);
while (true) {
if (fs.existsSync(path.resolve(root, 'node_modules'))) break;
if (root == '/') break;
root = path.resolve(root, '..');
}
var adapterObjects = _.map(adapterNames, (adapterName: string) => {
var settings = this.config.get('adapters.' + adapterName);
var adapter = require(path.join(root, 'node_modules', settings.module));
extend(adapter, settings);
adapter.schema = adapter.schema || true;
adapter.filePath && (adapter.filePath = path.join(this.root, adapter.filePath));
return adapter;
});
var adapters = _.object(adapterNames, adapterObjects);
this.models.forEach((model: ModelInfo) => {
var typeClass = model.type.prototype.constructor;
var attributes = typeClass['attributes'] || {};
model.properties.forEach((attr: MemberInfo) => {
var name = attr.name;
if (!attributes.hasOwnProperty(name))
attributes[name] = {};
if (!attributes[name].hasOwnProperty('type'))
attributes[name]['type'] =
attr.type == 'boolean' ? 'boolean' :
attr.type == 'number' ? 'integer' : 'string';
if (!attributes[name].hasOwnProperty('required'))
attributes[name].required = true;
});
var adapterName = typeClass['adapter'] || 'default';
var adapter = adapters[adapterName];
var definition = {
adapter: adapterName,
schema: typeClass['schema'] || adapter.schema,
tableName: typeClass['collectionName'] || model.name.toLowerCase(),
attributes: attributes
};
var Collection = Waterline.Collection.extend(definition);
new Collection({ adapters: { 'default': adapter } }, (err, collection) => {
model.type.prototype.constructor['collection'] = collection;
});
});
}
private buildRoutes() {
// public folder
var expressStatic: any = require('express').static;
this.express.use(expressStatic(path.join(this.root, this.config.get('assetPath'))));
// routes
this.router.routes.forEach((route: Route) => {
this.route(route);
});
// error handler
var custom500 = this.express.get('views') + '/500.ejs';
if (fs.existsSync(custom500))
this.express.use((error, req, res, next) => {
res.render(500, '500');
});
else
this.express.use((error: Error, req: EX.Request, res: EX.Response, next) => {
fs.readFile(__dirname + '/../views/500.html', { encoding: 'utf8' }, (err, data) => {
if (err) res.send(500, 'Server Error');
else if (this.config.get('env') == 'development')
res.send(500, data
.replace(/{{name}}/g, error.name)
.replace('{{message}}', error.message)
.replace('{{stack}}', error['stack']));
else
res.send(500, data
.replace(/{{name}}/g, 'Server Error')
.replace('{{message}}', 'The server has encountered an internal error.')
.replace('{{stack}}', ''));
});
});
// not found
var custom404 = this.express.get('views') + '/404.ejs';
if (fs.existsSync(custom404))
this.express.use((req, res) => {
res.render(404, '404');
});
else
this.express.use((req: EX.Request, res: EX.Response) => {
fs.readFile(__dirname + '/../views/404.html', { encoding: 'utf8' }, (err, data) => {
if (err) res.send(404, 'Not found');
else res.send(404, data);
});
});
}
private route(route: Route) {
var action = (req: EX.Request, res: EX.Response, next: Function) => {
res.header('X-Powered-By', 'TypeFramework');
var controllerName = req.params.controller || route.defaults.controller;
if (!controllerName) {
next(); return;
}
var controllerInfo = _.find<ControllerInfo>(this.controllers, (x: ControllerInfo) => x.name == controllerName.toLowerCase());
if (!controllerInfo) {
next(); return;
}
var actionName = req.params.action || route.defaults.action;
var actionInfo = controllerInfo.getAction(actionName);
if (!actionInfo) {
next(); return;
}
if (_.any(actionInfo.keywords, (x) => _.contains(['static', 'private'], x))) {
next(); return;
}
var params = actionInfo.parameters.map(paramInfo => {
var name = paramInfo.name;
var paramData = req.param(name) || route.defaults[name];
if (!!paramInfo) {
if (_.contains(paramInfo.type, '[]') && !(paramData instanceof Array))
paramData = [paramData];
switch (paramInfo.type) {
case 'boolean':
return !!paramData && (paramData == '1' || paramData == 'true');
case 'boolean[]':
return paramData.map((data) => !!data && (data == '1' || data == 'true'));
case 'number':
var num = Number(paramData);
if (isNaN(num)) throw new Error('Cannot parse number for param: ' + name);
return num;
case 'number[]':
return paramData.map((data) => {
var num = Number(data);
if (isNaN(num)) throw new Error('Cannot parse number for param: ' + name);
return num;
});
}
}
return paramData;
});
var response = new Response(res);
var result: IActionResult = null;
// generate after action filter chain
var complete = () => { result.execute(this, response) };
var afterActionChain = _.reduce(controllerInfo.type.filters || [], (next, filter: ActionFilter) => {
if (!filter['after'] || !filter.contains(actionName)) return next;
return function() {
filter['after'].call(filter, {
request: req,
response: response,
result: result,
reply: new Reply((actionResult: IActionResult) => { result = actionResult; complete(); }),
next: next });
};
}, complete);
// result will action will be executed when controller finish executing controller action
var resultAction = (actionResult: IActionResult) => {
result = actionResult;
afterActionChain();
};
// generate controller
var controller = new controllerInfo.type(req, response, resultAction);
var controllerAction = () => { controller[actionName].apply(controller, params) };
// generate model controller actions if has model
if (!!controllerInfo.type.model) {
var modelController = new ModelController(req, response, resultAction, controllerInfo.type.model);
controller._model = modelController._model;
!controller.find && (controller.find = modelController.find);
!controller.create && (controller.create = modelController.create);
!controller.update && (controller.update = modelController.update);
!controller.destroy && (controller.destroy = modelController.destroy);
}
// generate before action filter chain
var chain = _.reduceRight(controllerInfo.type.filters || [], (next, filter: ActionFilter) => {
if (!filter['before'] || !filter.contains(actionName)) return next;
return function() {
filter['before'].call(filter, {
request: req,
response: response,
reply: new Reply((actionResult: IActionResult) => { result = actionResult; complete(); }),
next: next });
};
}, controllerAction);
chain();
};
// map routes
var eRoute = this.express.route(route.path);
['GET', 'POST', 'PUT', 'DELETE', 'PATCH'].forEach((method) => {
if (!_.contains(route.methods, method)) return;
var map: Function = eRoute[method.toLowerCase()];
map.call(eRoute, action);
});
}
}
} | the_stack |
import { vec3, mat4 } from '@tlaukkan/tsm';
import { WebAppManifest } from './web_app_manifest';
import { AvActionState } from './aardvark';
import { nodeTransformFromMat4 } from './math_utils';
export const AardvarkPort = 23842;
export enum MessageType
{
// initialization messages. These are the only messages that
// aren't required to have a sender.
SetEndpointType = 100,
SetEndpointTypeResponse = 101,
Error = 102,
GetAardvarkManifest = 103,
GetAardvarkManifestResponse = 104,
//UserInfo = 105,
// Monitor messages
// these are send to monitors to give them meta context
NewEndpoint = 200,
LostEndpoint = 201,
OverrideTransform = 202,
// Gadget messages
UpdateSceneGraph = 300,
//GrabEvent = 301,
//GrabberState = 302,
GadgetStarted = 303,
//PokerProximity = 304,
//MouseEvent = 305,
NodeHaptic = 306,
// AttachGadgetToHook = 307,
// DetachGadgetFromHook = 308,
//MasterStartGadget = 309, // tells master to start a gadget
SaveSettings = 310,
UpdateActionState = 311,
DestroyGadget = 312,
ResourceLoadFailed = 313,
// SignRequest = 314,
// SignRequestResponse = 315,
InterfaceEvent = 316,
// System messages
GetInstalledGadgets = 400,
GetInstalledGadgetsResponse = 401,
InstallGadget = 402,
SetGadgetToAutoLaunch = 403,
RemoveGadgetFromAutoLaunch = 404,
// Interfaces and interface entities
InterfaceStarted = 700,
InterfaceEnded = 701,
InterfaceTransformUpdated = 702,
InterfaceSendEvent = 703,
InterfaceReceiveEvent = 704,
InterfaceLock = 705,
InterfaceLockResponse = 706,
InterfaceUnlock = 707,
InterfaceUnlockResponse = 708,
InterfaceRelock = 709,
InterfaceRelockResponse = 710,
InterfaceSendEventResponse = 711,
}
export enum WebSocketCloseCodes
{
UserDestroyedGadget = 4701,
}
export enum EndpointType
{
Unknown = -1,
Hub = 0,
Gadget = 1,
Node = 2,
Renderer = 3,
Monitor = 4,
Utility = 5,
}
export interface EndpointAddr
{
type: EndpointType;
endpointId?: number;
nodeId?: number;
}
function endpointTypeFromCharacter( c: string ): EndpointType
{
switch( c )
{
case "H": return EndpointType.Hub;
case "G": return EndpointType.Gadget;
case "N": return EndpointType.Node;
case "M": return EndpointType.Monitor;
case "R": return EndpointType.Renderer;
default: return EndpointType.Unknown;
}
}
function endpointCharacterFromType( ept: EndpointType ): string
{
switch( ept )
{
case EndpointType.Hub: return "H";
case EndpointType.Gadget: return "G";
case EndpointType.Node: return "N";
case EndpointType.Monitor: return "M";
case EndpointType.Renderer: return "R";
case EndpointType.Unknown: return "U";
default: return "?";
}
}
export function endpointAddrToString( epa: EndpointAddr ) : string
{
if( !epa )
{
return null;
}
else
{
return endpointCharacterFromType( epa.type )
+ ":" + ( epa.endpointId ? epa.endpointId : 0 )
+ ":" + ( epa.nodeId ? epa.nodeId : 0 );
}
}
export function stringToEndpointAddr( epaStr: string ) : EndpointAddr
{
let re = new RegExp( "^(.):([0-9]+):([0-9]+)$" );
let match = re.exec( epaStr );
if( !match )
{
console.log( `endpoint string ${ epaStr } failed to parse` );
return null;
}
return (
{
type: endpointTypeFromCharacter( match[1] ),
endpointId: parseInt( match[2] ),
nodeId: parseInt( match[3] ),
} );
}
export function endpointAddrIsEmpty( epa: EndpointAddr ): boolean
{
return epa == null || epa.type == undefined || epa.type == EndpointType.Unknown;
}
export function endpointAddrsMatch( epa1: EndpointAddr, epa2: EndpointAddr ): boolean
{
if( endpointAddrIsEmpty( epa1 ) )
return endpointAddrIsEmpty( epa2 );
else if( endpointAddrIsEmpty( epa2 ) )
return false;
return epa1.type == epa2.type && epa1.nodeId == epa2.nodeId && epa1.endpointId == epa2.endpointId;
}
export function indexOfEndpointAddrs( epaArray: EndpointAddr[], epa: EndpointAddr ): number
{
if( !epaArray )
{
return -1;
}
for( let i = 0; i < epaArray.length; i++ )
{
if( endpointAddrsMatch( epaArray[i], epa ) )
{
return i;
}
}
return -1;
}
export function computeEndpointFieldUri( epa: EndpointAddr, fieldName: string )
{
return `nodefield://${ endpointAddrToString( epa ) }/${ fieldName }`;
}
export interface Envelope
{
type: MessageType;
sequenceNumber: number;
replyTo?: number;
sender?: EndpointAddr;
target?: EndpointAddr;
payload?: string;
payloadUnpacked?: any;
}
export interface MsgError
{
messageType?: MessageType;
error: string;
}
export interface MsgSetEndpointType
{
newEndpointType: EndpointType;
gadgetUri?: string;
}
export interface MsgSetEndpointTypeResponse
{
endpointId: number;
settings?: any;
}
export interface MsgNewEndpoint
{
newEndpointType: EndpointType;
endpointId: number;
gadgetUri?: string;
}
export interface MsgLostEndpoint
{
endpointId: number;
}
export interface MsgGetAardvarkManifest
{
gadgetUri: string;
}
export interface MsgGeAardvarkManifestResponse
{
error?: string;
manifest?: AardvarkManifest;
gadgetUri?: string;
}
export interface MsgUpdateSceneGraph
{
root?: AvNode;
gadgetUrl?: string;
origin?: string;
userAgent?: string;
}
export function isUserAgentAardvark( userAgent: string )
{
return userAgent.includes( "Aardvark" );
}
export function parseEnvelope( envString: string, parsePayload: boolean = true ): Envelope
{
try
{
let env = JSON.parse( envString ) as Envelope;
if( env.payload && parsePayload )
{
env.payloadUnpacked = JSON.parse( env.payload );
}
return env;
}
catch( e )
{
console.log( "failed to parse envelope", envString, e );
return null;
}
}
export interface MsgGadgetStarted
{
epToNotify: EndpointAddr;
startedGadgetEndpointId: number;
}
export interface MsgNodeHaptic
{
nodeId: EndpointAddr;
amplitude: number;
frequency: number;
duration: number;
}
export interface MsgInterfaceEvent
{
destination: EndpointAddr;
interface: string;
data: object;
}
export interface MsgSaveSettings
{
settings: any;
}
export interface MsgUpdateActionState
{
gadgetId: number;
hand: EHand;
actionState: AvActionState;
}
export interface MsgOverrideTransform
{
nodeId: EndpointAddr;
transform: AvNodeTransform;
}
export interface MsgGetInstalledGadgets
{
}
export interface MsgGetInstalledGadgetsResponse
{
installedGadgets: string[];
}
export interface MsgDestroyGadget
{
gadgetId: number;
}
export interface MsgInstallGadget
{
gadgetUri: string;
}
export interface MsgSetGadgetToAutoLaunch
{
gadgetUri: string;
}
export interface MsgResourceLoadFailed
{
nodeId: EndpointAddr;
resourceUri: string;
error: string;
}
// tx, ty, tz, rw, rx, ry, rz
export type MinimalPose = [ number, number, number, number, number, number, number ];
export interface MsgInterfaceStarted
{
transmitter: EndpointAddr;
transmitterOrigin: string;
transmitterUserAgent: string;
receiver: EndpointAddr;
receiverOrigin: string;
receiverUserAgent: string;
iface: string;
transmitterFromReceiver: AvNodeTransform;
intersectionPoint?: AvVector;
params?: object; // This will only be set for initial interface locks
reason?: string;
}
export interface MsgInterfaceEnded
{
transmitter: EndpointAddr;
receiver: EndpointAddr;
iface: string;
transmitterFromReceiver?: AvNodeTransform;
intersectionPoint?: AvVector;
reason?: string;
}
export interface MsgInterfaceLock
{
transmitter: EndpointAddr;
receiver: EndpointAddr;
iface: string;
}
export enum InterfaceLockResult
{
Success = 0,
AlreadyLocked = 1,
NotLocked = 2,
InterfaceNotFound = 3,
InterfaceNameMismatch = 4,
InterfaceReceiverMismatch = 5,
NewReceiverNotFound = 6,
}
export interface MsgInterfaceLockResponse
{
result: InterfaceLockResult;
}
export interface MsgInterfaceUnlock
{
transmitter: EndpointAddr;
receiver: EndpointAddr;
iface: string;
}
export interface MsgInterfaceUnlockResponse
{
result: InterfaceLockResult;
}
export interface MsgInterfaceRelock
{
transmitter: EndpointAddr;
oldReceiver: EndpointAddr;
newReceiver: EndpointAddr;
iface: string;
}
export interface MsgInterfaceRelockResponse
{
result: InterfaceLockResult;
}
export interface MsgInterfaceTransformUpdated
{
destination: EndpointAddr;
peer: EndpointAddr;
iface: string;
destinationFromPeer: AvNodeTransform;
intersectionPoint?: AvVector;
reason?: string;
}
export interface MsgInterfaceSendEvent
{
destination: EndpointAddr;
peer: EndpointAddr;
iface: string;
event: object;
}
export interface MsgInterfaceSendEventResponse
{
}
export interface MsgInterfaceReceiveEvent
{
destination: EndpointAddr;
peer: EndpointAddr;
iface: string;
event: object;
destinationFromPeer: AvNodeTransform;
intersectionPoint?: AvVector;
reason?: string;
}
export enum AvNodeType
{
Invalid = -1,
Container = 0,
Origin = 1,
Transform = 2,
Model = 3,
//Panel = 4,
//Poker = 5,
// Grabbable = 6,
// Handle = 7,
// Grabber = 8,
// Hook = 9,
Line = 10,
WeightedTransform = 11,
ParentTransform = 12,
HeadFacingTransform = 13,
// RemoteUniverse = 14,
// RemoteOrigin = 15,
// RoomMember = 16,
InterfaceEntity = 17,
Child = 18,
ModelTransform = 19,
}
export interface AvInterfaceEventProcessor
{
( iface: string, sender: EndpointAddr, data: object ): void;
}
export function interfaceToString( transmitter: EndpointAddr, receiver: EndpointAddr, iface: string )
{
return endpointAddrToString( transmitter ) + "->" + endpointAddrToString( receiver )
+ "(" + iface + ")";
}
export function interfaceStringFromMsg( m: { transmitter: EndpointAddr, receiver: EndpointAddr,
iface: string } )
{
return interfaceToString(m.transmitter, m.receiver, m.iface );
}
export interface AvVector
{
x: number;
y: number;
z: number;
}
export interface AvQuaternion
{
x: number;
y: number;
z: number;
w: number;
}
export interface AvNodeTransform
{
position?: AvVector;
rotation?: AvQuaternion;
scale?: AvVector;
}
export enum EVolumeType
{
Invalid = -1,
Sphere = 0,
ModelBox = 1,
AABB = 1,
Infinite = 3,
Empty = 4,
Ray = 5, // ray is always down the positive X axis from the origin
Skeleton = 6,
};
/** Volume context allows entities to specify volumes that
* only apply to starting an interface, only apply to
* continuing an interface, or always apply.
*/
export enum EVolumeContext
{
Always = 0,
StartOnly = 1,
ContinueOnly = 2,
};
export interface AABB
{
xMin: number;
xMax: number;
yMin: number;
yMax: number;
zMin: number;
zMax: number;
}
export interface AvVolume
{
type: EVolumeType;
nodeFromVolume?: AvNodeTransform;
context?: EVolumeContext;
radius?: number;
uri?: string;
aabb?: AABB;
skeletonPath?: string; // /user/hand/left or /user/hand/right
scale?: number; // Scales radius or AABB (after model box is resolved)
visualize?: boolean; // If this is true Aardvark will render the volume to the best of its ability
source?: string;
}
export function emptyVolume(): AvVolume
{
return { type: EVolumeType.Empty };
}
export function infiniteVolume(): AvVolume
{
return { type: EVolumeType.Infinite };
}
export function modelBoxVolume( uri: string, scale?: number )
{
return (
{
type: EVolumeType.ModelBox,
uri,
scale
} );
};
export function sphereVolume( radius: number ) : AvVolume
{
return (
{
type: EVolumeType.Sphere,
radius,
}
)
}
export function rayVolume( start: vec3, dir: vec3 )
{
let nodeFromVolume: mat4;
let back: vec3;
if( vec3.dot( vec3.up, dir ) > 0.999 )
{
back = vec3.forward;
}
else
{
back = vec3.cross( dir, vec3.up );
}
let up = vec3.cross( back, dir );
nodeFromVolume = new mat4([
dir.x,
dir.y,
dir.z,
0,
up.x,
up.y,
up.z,
0,
back.x,
back.y,
back.z,
0,
start.x, start.y, start.z, 1,
] );
return (
{
type: EVolumeType.Ray,
nodeFromVolume: nodeTransformFromMat4( nodeFromVolume ),
} as AvVolume );
}
export enum ENodeFlags
{
Visible = 1 << 0,
PreserveGrabTransform = 1 << 1,
NotifyOnTransformChange = 1 << 2,
NotifyProximityWithoutGrab = 1 << 3,
AllowDropOnHooks = 1 << 4,
AllowMultipleDrops = 1 << 5,
Tethered = 1 << 6,
ShowGrabIndicator = 1 << 7,
Remote = 1 << 8,
HighlightHooks = 1 << 9,
}
export interface AvConstraint
{
minX?: number;
maxX?: number;
minY?: number;
maxY?: number;
minZ?: number;
maxZ?: number;
gravityAligned?: boolean;
}
export interface AvColor
{
r: number;
g: number;
b: number;
a?: number;
}
export interface InitialInterfaceLock
{
iface: string;
receiver: EndpointAddr;
params?: object;
}
export interface WeightedParent
{
parent: EndpointAddr;
weight: number;
}
export interface AvNode
{
type: AvNodeType;
id: number;
persistentName?: string;
globalId?: EndpointAddr;
flags: ENodeFlags;
children?: AvNode[];
propOrigin?: string;
propUniverseName?: string;
propTransform?: AvNodeTransform;
propModelUri?: string;
propVolume?: AvVolume;
propOuterVolumeScale?: number;
propVolumes?: AvVolume[];
propPriority?: number;
propParentAddr?: EndpointAddr;
propInteractive?: boolean;
propCustomNodeType?: string;
propSharedTexture?: AvSharedTextureInfo;
propConstraint?: AvConstraint;
propColor?: AvColor;
propOverlayOnly?: boolean;
propAnimationSource?: string;
propEndAddr?: EndpointAddr;
propThickness?: number;
propStartGap?: number;
propEndGap?: number;
propScaleToFit?: AvVector;
propInterfaces?: string[];
propTransmits?: string[];
propReceives?: string[];
propInterfaceLocks?: InitialInterfaceLock[];
propChildAddr?: EndpointAddr;
propModelNodeId?: string;
propWeightedParents?: WeightedParent[];
}
export enum EHand
{
Invalid = -1,
Left = 0,
Right = 1,
};
export enum ETextureType
{
Invalid = 0,
D3D11Texture2D = 1,
TextureUrl = 2,
}
export enum ETextureFormat
{
R8G8B8A8 = 1,
B8G8R8A8 = 2,
}
export interface AvSharedTextureInfo
{
dxgiHandle?: string;
textureDataBase64?: string;
url?: string;
type: ETextureType;
format: ETextureFormat;
invertY?: boolean;
width?: number;
height?: number;
}
export interface AvRendererConfig
{
enableMixedReality: boolean;
mixedRealityFov: number;
clearColor: [number, number, number];
}
export enum Permission
{
Master = "master",
SceneGraph = "scenegraph",
Favorites = "favorites",
StartUrl = "starturl",
Input = "input",
Settings = "settings",
Application = "application",
}
export interface AardvarkManifestExtension
{
permissions: Permission[];
browserWidth: number;
browserHeight: number;
startAutomatically: boolean;
}
export interface AardvarkManifest extends WebAppManifest
{
xr_type: string;
aardvark: AardvarkManifestExtension;
}
export interface AvGadgetSettings
{
favorited: boolean,
autoLaunchEnabled: boolean
}
export enum EAction
{
A = 0,
B = 1,
Squeeze = 2,
Grab = 3,
Detach = 4,
GrabShowRay = 5,
GrabMove = 6,
Max
}
export function emptyActionState(): AvActionState
{
return (
{
a: false, b:false, squeeze: false,
grab: false, grabShowRay: false, detach: false,
grabMove: [ 0, 0 ]
} );
}
export function filterActionsForGadget( actionState: AvActionState ): AvActionState
{
// Don't actually filter for now.
return {
...actionState,
};
}
export function gadgetDetailsToId( gadgetName: string, gadgetUri: string, gadgetPersistenceUuid?: string )
{
let filteredName = ( gadgetName + gadgetUri ).replace( /\W/g, "_" ).toLowerCase();
if( filteredName.length > 24 )
{
filteredName = filteredName.substr( 0, 24 );
}
if( gadgetPersistenceUuid )
{
let keyToHash = gadgetUri + gadgetPersistenceUuid;
let hash = 0;
for ( let i = 0; i < keyToHash.length; i++)
{
let char = keyToHash.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
filteredName += hash.toString( 16 );
}
return filteredName;
}
export function manifestUriFromGadgetUri( gadgetUri: string )
{
if( gadgetUri.endsWith( "/" ) )
{
return gadgetUri + "manifest.webmanifest";
}
else
{
return gadgetUri + "/manifest.webmanifest";
}
} | the_stack |
import { ProtobufBroker, ProtobufClient, ProtobufStream } from '../../websocket/modules/proto';
import { TradeClient } from '../../websocket/TradeClient';
import { PlaceOrderOpt } from '../../websocket/types/trading';
import { getNumber } from '../../util/helpers';
import logger from '../../util/logger';
import { getConnOpts, getMockWebSocketServer, getTradeOpts, validToken } from './ws-test-server';
test('client-trade-session', () => {
function createClientWithoutSubscriptions(): TradeClient {
return new TradeClient(getConnOpts());
}
expect(createClientWithoutSubscriptions).toThrow('Missing parameter: tradeSubscriptions');
});
test('trade-sessions', async (done) => {
expect.assertions(25);
const wss = await getMockWebSocketServer();
const marketID = 1;
const tradeDate = new Date().getTime();
const trades: ProtobufBroker.PrivateTrade[] = [
ProtobufBroker.PrivateTrade.create({
externalId: '12345',
orderId: '12345',
timeMillis: tradeDate,
priceString: '1.09',
amountString: '2.03',
side: 1
})
];
const tradesParsed = [
{
amount: '2.03',
id: '12345',
orderID: '12345',
price: '1.09',
side: 'buy',
timestamp: new Date(tradeDate)
}
];
const positionTime = Math.floor(new Date().getTime() / 1000);
const positions: ProtobufBroker.PrivatePosition[] = [
ProtobufBroker.PrivatePosition.create({
id: '1234',
time: positionTime,
side: 0,
avgPriceString: '1.3',
amountOpenString: '1.0',
amountClosedString: '0',
orderIds: ['1234'],
tradeIds: ['4312']
})
];
const positionsParsed = [
{
amountClosed: '0',
amountOpen: '1.0',
avgPrice: '1.3',
id: '1234',
orderIDs: ['1234'],
tradeIDs: ['4312'],
side: 'sell',
timestamp: new Date(positionTime * 1000)
}
];
const order1Opts: PlaceOrderOpt = {
side: 'buy',
type: 'limit',
price: '1',
amount: '1',
marketID,
requestID: 'reqid1'
};
const order1ID = 'orderid1';
let orderTime: Date;
const cancelOrder1Opts = {
marketID,
orderID: order1ID,
requestID: 'cancelid1'
};
const order2Opts: PlaceOrderOpt = {
side: 'sell',
type: 'market',
amount: '1',
marketID,
requestID: 'reqid2'
};
let authHandled = false;
let order1Handled = false;
let order1Canceled = false;
const order2Handled = false;
wss.on('connection', (ws) => {
ws.on('message', (data: Uint8Array) => {
if (!authHandled) {
const msg = ProtobufClient.ClientMessage.decode(data);
if (
msg.apiAuthentication &&
msg.apiAuthentication.clientSubscriptions &&
msg.apiAuthentication.clientSubscriptions.length > 0 &&
msg.apiAuthentication.clientSubscriptions[0].tradeSubscription &&
msg.apiAuthentication.clientSubscriptions[0].tradeSubscription.marketId
) {
if (msg.apiAuthentication.token === validToken) {
ws.send(
ProtobufBroker.BrokerUpdateMessage.encode(
ProtobufBroker.BrokerUpdateMessage.create({
authenticationResult: ProtobufStream.AuthenticationResult.create({
status: ProtobufStream.AuthenticationResult.Status.AUTHENTICATED
})
})
).finish()
);
}
expect(msg.apiAuthentication.clientSubscriptions[0].tradeSubscription.marketId).toBe(
String(marketID)
);
// send syncing status
ws.send(
ProtobufBroker.BrokerUpdateMessage.encode(
ProtobufBroker.BrokerUpdateMessage.create({
marketId: marketID,
sessionStatusUpdate: ProtobufBroker.SessionStatusUpdate.create({
initialized: true,
syncing: true,
lastSyncTime: 0,
syncError: 0
})
})
).finish()
);
// orders update
ws.send(
ProtobufBroker.BrokerUpdateMessage.encode(
ProtobufBroker.BrokerUpdateMessage.create({
marketId: marketID,
ordersUpdate: ProtobufBroker.OrdersUpdate.create({
orders: []
})
})
).finish()
);
// trades update
ws.send(
ProtobufBroker.BrokerUpdateMessage.encode(
ProtobufBroker.BrokerUpdateMessage.create({
marketId: marketID,
tradesUpdate: ProtobufBroker.TradesUpdate.create({
trades
})
})
).finish()
);
// positions update
ws.send(
ProtobufBroker.BrokerUpdateMessage.encode(
ProtobufBroker.BrokerUpdateMessage.create({
marketId: marketID,
positionsUpdate: ProtobufBroker.PositionsUpdate.create({
positions
})
})
).finish()
);
authHandled = true;
return;
// TODO balances update
}
}
if (authHandled && !order1Handled) {
const br1 = ProtobufBroker.BrokerRequest.decode(data);
if (br1.placeOrderRequest && br1.placeOrderRequest.order) {
const newOrder = br1.placeOrderRequest.order;
expect(newOrder.amountParamString).toBe('1');
expect(newOrder.side).toBe(1); // buy
expect(newOrder.type).toBe(1); // limit
expect(newOrder.priceParams).toEqual([
{
valueString: String(order1Opts.price),
type: 0 // absolute value
}
]);
newOrder.amountFilledString = '0.0';
newOrder.id = order1ID;
// Truncate date to seconds
const t = Math.floor(new Date().getTime() / 1000);
orderTime = new Date(t * 1000);
newOrder.time = orderTime.getTime() / 1000;
ws.send(
ProtobufBroker.BrokerUpdateMessage.encode(
ProtobufBroker.BrokerUpdateMessage.create({
marketId: marketID,
requestResolutionUpdate: ProtobufBroker.RequestResolutionUpdate.create({
id: order1Opts.requestID,
error: 0,
message: '',
placeOrderResult: {
order: newOrder
}
})
})
).finish()
);
ws.send(
ProtobufBroker.BrokerUpdateMessage.encode(
ProtobufBroker.BrokerUpdateMessage.create({
marketId: marketID,
ordersUpdate: ProtobufBroker.OrdersUpdate.create({
orders: [newOrder]
})
})
).finish()
);
}
order1Handled = true;
return;
}
if (order1Handled && !order1Canceled) {
const br2 = ProtobufBroker.BrokerRequest.decode(data);
expect(getNumber(br2.marketId)).toBe(marketID);
expect(br2.cancelOrderRequest).toEqual({
orderId: order1ID
});
ws.send(
ProtobufBroker.BrokerUpdateMessage.encode(
ProtobufBroker.BrokerUpdateMessage.create({
marketId: marketID,
requestResolutionUpdate: ProtobufBroker.RequestResolutionUpdate.create({
id: cancelOrder1Opts.requestID,
error: 0,
message: '',
cancelOrderResult: {
orderId: order1ID
}
})
})
).finish()
);
order1Canceled = true;
return;
}
if (!order2Handled) {
const br3 = ProtobufBroker.BrokerRequest.decode(data);
if (!br3.placeOrderRequest || !br3.placeOrderRequest.order) {
done.fail();
return;
}
const newOrder = br3.placeOrderRequest.order;
expect(newOrder.side).toBe(0);
expect(newOrder.type).toBe(0);
expect(newOrder.fundingType).toBe(0);
expect(newOrder.amountParamString).toBe('1');
expect(getNumber(br3.marketId)).toBe(marketID);
// end test
wss.close();
done();
}
});
});
const client = new TradeClient(
getTradeOpts(
{
creds: {
url: wss.url
}
},
[{ marketID }]
)
);
client.onReady(() => {
expect(client.orders[marketID]).toStrictEqual([]);
expect(client.positions[marketID]).toStrictEqual(positionsParsed);
expect(client.trades[marketID]).toStrictEqual(tradesParsed);
logger.debug('placing order...');
client
// Limit order
.placeOrder(order1Opts)
.then((order) => {
logger.debug('place order resp %o', order);
expect(client.orders[marketID][0]).toStrictEqual(order);
logger.debug('cancelling order...');
client
.cancelOrder(cancelOrder1Opts)
.then(() => {
logger.debug('cancelled order');
logger.debug('placing order 2...');
// Market order
client
.placeOrder(order2Opts)
.then((order2) => {
logger.debug('place order 2 resp %o', order2);
wss.close();
done();
})
.catch((e) => {
done.fail(e);
});
})
.catch((e) => {
done.fail(e);
});
})
.catch((e) => {
done.fail(e);
});
});
// there should be two orders updates
let check = 1;
client.onOrdersUpdate((orders) => {
if (check === 1) {
expect(orders).toEqual([]);
check++;
return;
}
if (check === 2) {
const o = orders[0];
expect(o.id).toBe(order1ID);
expect(o.timestamp).toStrictEqual(orderTime);
expect(o.type).toBe('limit');
expect(o.side).toBe('buy');
expect(o.amount).toBe('1');
expect(o.price).toBe('1');
}
});
client.onTradesUpdate((tradesUpdate) => {
expect(tradesUpdate).toStrictEqual(tradesParsed);
});
client.onPositionsUpdate((positionsUpdate) => {
expect(positionsUpdate).toStrictEqual(positionsParsed);
});
client.connect();
}); | the_stack |
'use strict';
// tslint:disable no-unused-expression
import * as vscode from 'vscode';
import * as sinon from 'sinon';
import * as chai from 'chai';
import * as sinonChai from 'sinon-chai';
import * as fs from 'fs-extra';
import * as path from 'path';
import { TransactionView } from '../../extension/webview/TransactionView';
import { View } from '../../extension/webview/View';
import { TestUtil } from '../TestUtil';
import { GlobalState } from '../../extension/util/GlobalState';
import { ExtensionCommands } from '../../ExtensionCommands';
import IAssociatedTxData from '../../extension/interfaces/IAssociatedTxData';
import ITxDataFile from '../../extension/interfaces/ITxDataFile';
type ITransaction = any;
type ISmartContract = any;
chai.use(sinonChai);
const should: Chai.Should = chai.should();
interface IAppState {
gatewayName: string;
smartContracts: ISmartContract[];
associatedTxdata: IAssociatedTxData;
preselectedSmartContract: ISmartContract;
preselectedTransaction: ITransaction;
}
interface ICreateTransactionViewAndSendMessageParams {
mySandBox: sinon.SinonSandbox;
createWebviewPanelStub: sinon.SinonStub;
postMessageStub: sinon.SinonStub;
context: vscode.ExtensionContext;
mockAppState: IAppState;
command: string | undefined;
data: object | undefined;
}
async function createTransactionViewAndSendMessage({ mySandBox, createWebviewPanelStub, postMessageStub, context, mockAppState, command, data }: ICreateTransactionViewAndSendMessageParams): Promise<any> {
const onDidReceiveMessagePromises: any[] = [];
onDidReceiveMessagePromises.push(new Promise((resolve: any): void => {
createWebviewPanelStub.returns({
webview: {
postMessage: postMessageStub,
onDidReceiveMessage: async (callback: any): Promise<void> => {
await callback({
command,
data,
});
resolve();
},
asWebviewUri: mySandBox.stub()
},
reveal: (): void => {
return;
},
onDidDispose: mySandBox.stub(),
onDidChangeViewState: mySandBox.stub()
});
}));
const transactionCreateView: TransactionView = new TransactionView(context, mockAppState);
await transactionCreateView.openView(false);
return Promise.all(onDidReceiveMessagePromises);
}
describe('TransactionView', () => {
const mySandBox: sinon.SinonSandbox = sinon.createSandbox();
let context: vscode.ExtensionContext;
let createWebviewPanelStub: sinon.SinonStub;
let postMessageStub: sinon.SinonStub;
let executeCommandStub: sinon.SinonStub;
let fsReaddirStub: sinon.SinonStub;
let fsReadJsonStub: sinon.SinonStub;
let createTransactionViewAndSendMessageDefaults: ICreateTransactionViewAndSendMessageParams;
const transactionOne: ITransaction = {
name: 'transactionOne',
parameters: [{
description: '',
name: 'name',
schema: {}
}],
returns: {
type: ''
},
tag: ['submit']
};
const transactionTwo: ITransaction = {
name: 'transactionTwo',
parameters: [{
description: '',
name: 'size',
schema: {}
}],
returns: {
type: ''
},
tag: ['submit']
};
const greenContract: ISmartContract = {
name: 'greenContract',
version: '0.0.1',
channel: 'mychannel',
label: 'greenContract@0.0.1',
transactions: [transactionOne, transactionTwo],
namespace: 'GreenContract'
};
const mockAppState: IAppState = {
gatewayName: 'my gateway',
smartContracts: [greenContract],
preselectedSmartContract: greenContract,
preselectedTransaction: undefined,
associatedTxdata: {},
};
const transactionObject: any = {
smartContract: 'greenContract',
transactionName: 'transactionOne',
channelName: 'mychannel',
args: '["arg1", "arg2", "arg3"]',
namespace: 'GreenContract',
transientData: undefined,
peerTargetNames: undefined
};
const chaincodeDetails: {label: string, name: string, channel: string} = {
label: greenContract.label,
name: greenContract.name,
channel: greenContract.channel,
};
const dummyPath: string = '/dummyPath';
const dummyTxdataFile: string = 'file.txdata';
const badTxdataFile: string = 'throwerror.txdata';
const associateTransactionDataDirectoryResponse: {chaincodeName: string, channelName: string, transactionDataPath: string} = {
chaincodeName: chaincodeDetails.name,
channelName: chaincodeDetails.channel,
transactionDataPath: dummyPath,
};
const dummyTxdataFileContents: ITxDataFile[] = [
{transactionName: 'myTransaction', transactionLabel: 'This is my transaction', arguments: ['arg1', 'arg2'], transientData: {}, txDataFile: '' },
{transactionName: 'anotherTransaction', transactionLabel: 'This is another transaction', arguments: [JSON.stringify({ key: 'value' })], transientData: undefined, txDataFile: '' },
];
before(async () => {
await TestUtil.setupTests(mySandBox);
});
beforeEach(async () => {
context = GlobalState.getExtensionContext();
executeCommandStub = mySandBox.stub(vscode.commands, 'executeCommand');
executeCommandStub.callThrough();
executeCommandStub.withArgs(ExtensionCommands.SUBMIT_TRANSACTION).resolves();
executeCommandStub.withArgs(ExtensionCommands.EVALUATE_TRANSACTION).resolves();
executeCommandStub.withArgs(ExtensionCommands.ASSOCIATE_TRANSACTION_DATA_DIRECTORY).resolves(associateTransactionDataDirectoryResponse);
executeCommandStub.withArgs(ExtensionCommands.DISSOCIATE_TRANSACTION_DATA_DIRECTORY ).resolves(undefined);
fsReaddirStub = mySandBox.stub(fs, 'readdir');
fsReaddirStub.withArgs(dummyPath).resolves([dummyTxdataFile, badTxdataFile]);
fsReadJsonStub = mySandBox.stub(fs, 'readJSON').resolves();
createWebviewPanelStub = mySandBox.stub(vscode.window, 'createWebviewPanel');
postMessageStub = mySandBox.stub().resolves();
View['openPanels'].splice(0, View['openPanels'].length);
// Make sure this is last in the beforeEach loop
createTransactionViewAndSendMessageDefaults = {
mySandBox,
createWebviewPanelStub,
postMessageStub,
mockAppState,
context,
command: undefined,
data: undefined,
};
});
afterEach(() => {
mySandBox.restore();
});
it('should register and show the transaction page', async () => {
createWebviewPanelStub.returns({
title: 'Transaction Page',
webview: {
postMessage: postMessageStub,
onDidReceiveMessage: mySandBox.stub(),
asWebviewUri: mySandBox.stub()
},
reveal: mySandBox.stub(),
dispose: mySandBox.stub(),
onDidDispose: mySandBox.stub(),
onDidChangeViewState: mySandBox.stub()
});
const transactionView: TransactionView = new TransactionView(context, mockAppState);
await transactionView.openView(false);
createWebviewPanelStub.should.have.been.called;
postMessageStub.should.have.been.calledWith({
path: '/transaction',
transactionViewData: mockAppState
});
});
it(`should handle a 'submit' message`, async () => {
await createTransactionViewAndSendMessage({
...createTransactionViewAndSendMessageDefaults,
command: ExtensionCommands.SUBMIT_TRANSACTION,
data: transactionObject,
});
executeCommandStub.should.have.been.calledWith(ExtensionCommands.SUBMIT_TRANSACTION, undefined, undefined, undefined, transactionObject);
});
it(`should handle an 'evaluate' message`, async () => {
await createTransactionViewAndSendMessage({
...createTransactionViewAndSendMessageDefaults,
command: ExtensionCommands.EVALUATE_TRANSACTION,
data: transactionObject,
});
executeCommandStub.should.have.been.calledWith(ExtensionCommands.EVALUATE_TRANSACTION, undefined, undefined, undefined, transactionObject);
});
it(`should handle an 'ASSOCIATE_TRANSACTION_DATA_DIRECTORY' message and calls postMessage with associatedTxData`, async () => {
fsReadJsonStub.withArgs(path.join(dummyPath, dummyTxdataFile)).resolves(dummyTxdataFileContents);
await createTransactionViewAndSendMessage({
...createTransactionViewAndSendMessageDefaults,
command: ExtensionCommands.ASSOCIATE_TRANSACTION_DATA_DIRECTORY,
data: chaincodeDetails,
});
executeCommandStub.should.have.been.calledWith(ExtensionCommands.ASSOCIATE_TRANSACTION_DATA_DIRECTORY, undefined, chaincodeDetails);
const txDataFile: string = path.join(dummyPath, dummyTxdataFile);
const expectedParameters: { transactionViewData: IAppState } = {
transactionViewData: {
gatewayName: mockAppState.gatewayName,
smartContracts: mockAppState.smartContracts,
preselectedSmartContract: mockAppState.preselectedSmartContract,
preselectedTransaction: undefined,
associatedTxdata: {
[associateTransactionDataDirectoryResponse.chaincodeName]: {
channelName: associateTransactionDataDirectoryResponse.channelName,
transactionDataPath: associateTransactionDataDirectoryResponse.transactionDataPath,
transactions: [{
...dummyTxdataFileContents[0],
txDataFile,
},
{
...dummyTxdataFileContents[1],
txDataFile,
}],
}
},
},
};
postMessageStub.should.have.been.calledWith(expectedParameters);
});
it(`should handle an 'ASSOCIATE_TRANSACTION_DATA_DIRECTORY' message when the data directory is empty`, async () => {
fsReaddirStub.withArgs(dummyPath).resolves([]);
await createTransactionViewAndSendMessage({
...createTransactionViewAndSendMessageDefaults,
command: ExtensionCommands.ASSOCIATE_TRANSACTION_DATA_DIRECTORY,
data: chaincodeDetails,
});
executeCommandStub.should.have.been.calledWith(ExtensionCommands.ASSOCIATE_TRANSACTION_DATA_DIRECTORY, undefined, chaincodeDetails);
const expectedParameters: { transactionViewData: IAppState } = {
transactionViewData: {
gatewayName: mockAppState.gatewayName,
smartContracts: mockAppState.smartContracts,
preselectedSmartContract: mockAppState.preselectedSmartContract,
preselectedTransaction: undefined,
associatedTxdata: {
[associateTransactionDataDirectoryResponse.chaincodeName]: {
channelName: associateTransactionDataDirectoryResponse.channelName,
transactionDataPath: associateTransactionDataDirectoryResponse.transactionDataPath,
transactions: [],
}
},
},
};
postMessageStub.should.have.been.calledWith(expectedParameters);
});
it(`should handle an 'ASSOCIATE_TRANSACTION_DATA_DIRECTORY' message when no .txdata files are found in the transaction directory`, async () => {
fsReaddirStub.withArgs(dummyPath).resolves(['invalidfile.txt']);
await createTransactionViewAndSendMessage({
...createTransactionViewAndSendMessageDefaults,
command: ExtensionCommands.ASSOCIATE_TRANSACTION_DATA_DIRECTORY,
data: chaincodeDetails,
});
executeCommandStub.should.have.been.calledWith(ExtensionCommands.ASSOCIATE_TRANSACTION_DATA_DIRECTORY, undefined, chaincodeDetails);
const expectedParameters: { transactionViewData: IAppState } = {
transactionViewData: {
gatewayName: mockAppState.gatewayName,
smartContracts: mockAppState.smartContracts,
preselectedSmartContract: mockAppState.preselectedSmartContract,
preselectedTransaction: undefined,
associatedTxdata: {
[associateTransactionDataDirectoryResponse.chaincodeName]: {
channelName: associateTransactionDataDirectoryResponse.channelName,
transactionDataPath: associateTransactionDataDirectoryResponse.transactionDataPath,
transactions: [],
}
},
},
};
postMessageStub.should.have.been.calledWith(expectedParameters);
});
it(`should handle an 'DISSOCIATE_TRANSACTION_DATA_DIRECTORY' message and calls postMessage with no associatedTxData`, async () => {
await createTransactionViewAndSendMessage({
...createTransactionViewAndSendMessageDefaults,
command: ExtensionCommands.DISSOCIATE_TRANSACTION_DATA_DIRECTORY,
data: chaincodeDetails,
});
executeCommandStub.should.have.been.calledWith(ExtensionCommands.DISSOCIATE_TRANSACTION_DATA_DIRECTORY, undefined, chaincodeDetails);
const expectedParameters: { transactionViewData: IAppState } = {
transactionViewData: {
gatewayName: mockAppState.gatewayName,
smartContracts: mockAppState.smartContracts,
preselectedSmartContract: mockAppState.preselectedSmartContract,
preselectedTransaction: undefined,
associatedTxdata: {},
},
};
postMessageStub.should.have.been.calledWith(expectedParameters);
});
it(`should handle an unexpected command and pass through the parameters`, async () => {
const command: string = ExtensionCommands.OPEN_TUTORIAL_PAGE;
executeCommandStub.withArgs(command).resolves();
const data: string[] = ['Basic Tutorials', 'A4: A Tutorial'];
await createTransactionViewAndSendMessage({
...createTransactionViewAndSendMessageDefaults,
command,
data,
});
executeCommandStub.should.have.been.calledWith(command, ...data);
});
it('should get txdataTransactions when there is a transaction data directory in the appState in loadComponent', async () => {
fsReadJsonStub.withArgs(path.join(dummyPath, dummyTxdataFile)).resolves(dummyTxdataFileContents);
createWebviewPanelStub.returns({
webview: {
postMessage: postMessageStub,
onDidReceiveMessage: mySandBox.stub().resolves(),
asWebviewUri: mySandBox.stub()
},
reveal: (): void => {
return;
},
onDidDispose: mySandBox.stub(),
onDidChangeViewState: mySandBox.stub()
});
const txDataFile: string = path.join(dummyPath, dummyTxdataFile);
const transactionCreateView: TransactionView = new TransactionView(context, {
...mockAppState,
associatedTxdata: {
[associateTransactionDataDirectoryResponse.chaincodeName]: {
channelName: associateTransactionDataDirectoryResponse.channelName,
transactionDataPath: associateTransactionDataDirectoryResponse.transactionDataPath,
transactions: [{
...dummyTxdataFileContents[0],
txDataFile,
},
{
...dummyTxdataFileContents[1],
txDataFile,
}],
}
},
});
await transactionCreateView.openView(false);
const expectedParameters: { path: string, transactionViewData: IAppState } = {
path: '/transaction',
transactionViewData: {
gatewayName: mockAppState.gatewayName,
smartContracts: mockAppState.smartContracts,
preselectedSmartContract: mockAppState.preselectedSmartContract,
preselectedTransaction: undefined,
associatedTxdata: {
[associateTransactionDataDirectoryResponse.chaincodeName]: {
channelName: associateTransactionDataDirectoryResponse.channelName,
transactionDataPath: associateTransactionDataDirectoryResponse.transactionDataPath,
transactions: [{
...dummyTxdataFileContents[0],
txDataFile,
},
{
...dummyTxdataFileContents[1],
txDataFile,
}],
}
},
},
};
postMessageStub.should.have.been.calledWith(expectedParameters);
});
it('should update a smartContract', async () => {
createWebviewPanelStub.returns({
title: 'Transaction Page',
webview: {
postMessage: postMessageStub,
onDidReceiveMessage: mySandBox.stub(),
asWebviewUri: mySandBox.stub()
},
reveal: mySandBox.stub(),
dispose: mySandBox.stub(),
onDidDispose: mySandBox.stub(),
onDidChangeViewState: mySandBox.stub()
});
const transactionView: TransactionView = new TransactionView(context, mockAppState);
await transactionView.openView(false);
createWebviewPanelStub.should.have.been.called;
postMessageStub.should.have.been.calledWith({
path: '/transaction',
transactionViewData: mockAppState,
});
const updatedContract: ISmartContract = { ...greenContract, name: 'updatedContract' };
await TransactionView.updateSmartContracts([updatedContract]);
postMessageStub.should.have.been.calledWith({
path: '/transaction',
transactionViewData: { ...mockAppState, smartContracts: [updatedContract] },
});
});
it('should dispose of the TransactionView', async () => {
const disposeStub: sinon.SinonStub = mySandBox.stub();
createWebviewPanelStub.returns({
title: 'Transaction Page',
webview: {
postMessage: postMessageStub,
onDidReceiveMessage: mySandBox.stub(),
asWebviewUri: mySandBox.stub()
},
reveal: mySandBox.stub(),
dispose: disposeStub,
onDidDispose: mySandBox.stub(),
onDidChangeViewState: mySandBox.stub()
});
const transactionView: TransactionView = new TransactionView(context, mockAppState);
await transactionView.openView(false);
TransactionView.closeView();
disposeStub.should.have.been.called;
});
it('should set panel to undefined if disposed', async () => {
const disposeStub: sinon.SinonStub = mySandBox.stub().yields();
createWebviewPanelStub.returns({
title: 'Deploy Smart Contract',
webview: {
postMessage: postMessageStub,
onDidReceiveMessage: mySandBox.stub(),
asWebviewUri: mySandBox.stub()
},
reveal: (): void => {
return;
},
onDidDispose: disposeStub,
onDidChangeViewState: mySandBox.stub(),
_isDisposed: false
});
const deployView: TransactionView = new TransactionView(context, mockAppState);
await deployView.openView(false);
should.not.exist(TransactionView.panel);
});
it('Should call postMessage when openView is called and TransactionView.panel exists', async () => {
createWebviewPanelStub.returns({
title: 'Transaction Page',
webview: {
postMessage: postMessageStub,
onDidReceiveMessage: mySandBox.stub(),
asWebviewUri: mySandBox.stub()
},
reveal: mySandBox.stub(),
dispose: mySandBox.stub(),
onDidDispose: mySandBox.stub(),
onDidChangeViewState: mySandBox.stub()
});
const transactionView: TransactionView = new TransactionView(context, mockAppState);
await transactionView.openView(false);
createWebviewPanelStub.should.have.been.called;
postMessageStub.should.have.been.calledWith({
path: '/transaction',
transactionViewData: mockAppState,
});
const updatedContract: ISmartContract = { ...greenContract, name: 'updatedContract' };
const newTransactionView: TransactionView = new TransactionView(context, { ...mockAppState, smartContracts: [updatedContract] });
await newTransactionView.openView(false);
createWebviewPanelStub.should.have.been.called;
postMessageStub.should.have.been.calledWith({
path: '/transaction',
transactionViewData: { ...mockAppState, smartContracts: [updatedContract] },
});
});
}); | the_stack |
'use strict';
// original source: https://github.com/rgrove/parse-xml
import { Document } from "./types";
import * as Syntax from './syntax';
const emptyArray = Object.freeze([]);
const emptyObject = Object.freeze(Object.create(null));
const namedEntities: any = Object.freeze({
'&': '&',
''': "'",
'>': '>',
'<': '<',
'"': '"'
});
const NODE_TYPE_CDATA = 'cdata';
const NODE_TYPE_COMMENT = 'comment';
const NODE_TYPE_DOCUMENT = 'document';
const NODE_TYPE_ELEMENT = 'element';
const NODE_TYPE_TEXT = 'text';
// let Syntax: any;
export class ParseXml {
parse(xml: any, options = emptyObject): Document {
// if (Syntax === void 0) {
// // Lazy require to defer regex parsing until first use.
// Syntax = require('./syntax');
// }
if (xml[0] === '\uFEFF') {
// Strip byte order mark.
xml = xml.slice(1);
}
xml = xml.replace(/\r\n?/g, '\n'); // Normalize CRLF and CR to LF.
let doc: any = {
type: NODE_TYPE_DOCUMENT,
children: [],
parent: null
};
doc.toJSON = this.nodeToJson.bind(doc);
let state: any = {
length: xml.length,
options,
parent: doc,
pos: 0,
prevPos: 0,
slice: null,
xml
};
this.consumeProlog(state);
if (!this.consumeElement(state)) {
this.error(state, 'Root element is missing or invalid');
}
while (this.consumeMisc(state)) { }
if (!this.isEof(state)) {
this.error(state, `Extra content at the end of the document`);
}
return doc;
}
// -- Private Functions --------------------------------------------------------
addNode(state: any, node: any) {
node.parent = state.parent;
node.toJSON = this.nodeToJson.bind(node);
state.parent.children.push(node);
}
addText(state: any, text: any) {
let { children } = state.parent;
let prevNode = children[children.length - 1];
if (prevNode !== void 0 && prevNode.type === NODE_TYPE_TEXT) {
// The previous node is a text node, so we can append to it and avoid
// creating another node.
prevNode.text += text;
} else {
this.addNode(state, {
type: NODE_TYPE_TEXT,
text
});
}
}
// Each `consume*` function takes the current state as an argument and returns
// `true` if `state.pos` was advanced (meaning some XML was consumed) or `false`
// if nothing was consumed.
consumeCDSect(state: any) {
let [match, text] = scan(state, Syntax.Anchored.CDSect);
if (match === void 0) {
return false;
}
if (state.options.preserveCdata) {
this.addNode(state, {
type: NODE_TYPE_CDATA,
text
});
} else {
this.addText(state, text);
}
return true;
}
consumeCharData(state: any) {
let [text] = scan(state, Syntax.Anchored.CharData);
if (text === void 0) {
return false;
}
let cdataCloseIndex = text.indexOf(']]>');
if (cdataCloseIndex !== -1) {
state.pos = state.prevPos + cdataCloseIndex;
this.error(state, 'Element content may not contain the CDATA section close delimiter `]]>`');
}
// Note: XML 1.0 5th ed. says `CharData` is "any string of characters which
// does not contain the start-delimiter of any markup and does not include the
// CDATA-section-close delimiter", but the conformance test suite and
// well-established parsers like libxml seem to restrict `CharData` to
// characters that match the `Char` symbol, so that's what I've done here.
if (!Syntax.CharOnly.test(text)) {
state.pos = state.prevPos + text.search(new RegExp(`(?!${Syntax.Char.source})`));
this.error(state, 'Element content contains an invalid character');
}
this.addText(state, text);
return true;
}
consumeComment(state: any) {
let [, content] = scan(state, Syntax.Anchored.Comment);
if (content === void 0) {
return false;
}
if (state.options.preserveComments) {
this.addNode(state, {
type: NODE_TYPE_COMMENT,
content: content.trim()
});
}
return true;
}
consumeDoctypeDecl(state: any) {
return scan(state, Syntax.Anchored.doctypedecl).length > 0;
}
consumeElement(state: any) {
let [tag, name, attrs] = scan(state, Syntax.Anchored.EmptyElemTag);
let isEmpty = tag !== void 0;
if (!isEmpty) {
[tag, name, attrs] = scan(state, Syntax.Anchored.STag);
if (tag === void 0) {
return false;
}
}
let { parent } = state;
let parsedAttrs = this.parseAttrs(state, attrs);
let node: any = {
type: NODE_TYPE_ELEMENT,
name,
attributes: parsedAttrs,
children: []
};
let xmlSpace = parsedAttrs['xml:space'];
if (xmlSpace === 'preserve'
|| (xmlSpace !== 'default' && parent.preserveWhitespace)) {
node.preserveWhitespace = true;
}
if (!isEmpty) {
state.parent = node;
this.consumeCharData(state);
while (
this.consumeElement(state)
|| this.consumeReference(state)
|| this.consumeCDSect(state)
|| this.consumePI(state)
|| this.consumeComment(state)
) {
this.consumeCharData(state);
}
let [, endName] = scan(state, Syntax.Anchored.ETag);
if (endName !== name) {
state.pos = state.prevPos;
this.error(state, `Missing end tag for element ${name}`);
}
state.parent = parent;
}
this.addNode(state, node);
return true;
}
consumeMisc(state: any) {
return this.consumeComment(state)
|| this.consumePI(state)
|| this.consumeWhitespace(state);
}
consumePI(state: any) {
let [match, target] = scan(state, Syntax.Anchored.PI);
if (match === void 0) {
return false;
}
if (target.toLowerCase() === 'xml') {
state.pos = state.prevPos;
this.error(state, 'XML declaration is only allowed at the start of the document');
}
return true;
}
consumeProlog(state: any) {
let { pos } = state;
scan(state, Syntax.Anchored.XMLDecl);
while (this.consumeMisc(state)) { }
if (this.consumeDoctypeDecl(state)) {
while (this.consumeMisc(state)) { }
}
return state.pos > pos;
}
consumeReference(state: any) {
let [ref] = scan(state, Syntax.Anchored.Reference);
if (ref === void 0) {
return false;
}
this.addText(state, this.replaceReference(ref, state));
return true;
}
consumeWhitespace(state: any) {
return scan(state, Syntax.Anchored.S).length > 0;
}
error(state: any, message: any) {
let { pos, xml } = state;
let column = 1;
let excerpt = '';
let line = 1;
// Find the line and column where the error occurred.
for (let i = 0; i < pos; ++i) {
let char = xml[i];
if (char === '\n') {
column = 1;
excerpt = '';
line += 1;
} else {
column += 1;
excerpt += char;
}
}
let eol = xml.indexOf('\n', pos);
excerpt += eol === -1
? xml.slice(pos)
: xml.slice(pos, eol);
let excerptStart = 0;
// Keep the excerpt below 50 chars, but always keep the error position in
// view.
if (excerpt.length > 50) {
if (column < 40) {
excerpt = excerpt.slice(0, 50);
} else {
excerptStart = column - 20;
excerpt = excerpt.slice(excerptStart, column + 30);
}
}
let err: any = new Error(
`${message} (line ${line}, column ${column})\n`
+ ` ${excerpt}\n`
+ ' '.repeat(column - excerptStart + 1) + '^\n'
);
err.column = column;
err.excerpt = excerpt;
err.line = line;
err.pos = pos;
throw err;
}
isEof(state: any) {
return state.pos >= state.length - 1;
}
nodeToJson() {
let json = Object.assign(Object.create(null), this);
delete json.parent;
return json;
}
normalizeAttrValue(state: any, value: any) {
return value
.replace(Syntax.Global.Reference, (ref: any) => this.replaceReference(ref, state))
.replace(Syntax.Global.S, ' ')
.trim();
}
parseAttrs(state: any, attrs: any) {
let parsedAttrs = Object.create(null);
if (!attrs) {
return parsedAttrs;
}
let attrPairs = attrs
.match(Syntax.Global.Attribute)
.sort();
for (let i = 0, len = attrPairs.length; i < len; ++i) {
let attrPair = attrPairs[i];
let name = attrPair.trim();
let value = '';
let eqMatch = attrPair.match(Syntax.Eq);
if (eqMatch && eqMatch.index > -1) {
name = attrPair.slice(0, eqMatch.index);
value = attrPair.slice(eqMatch.index + eqMatch[0].length);
}
if (name in parsedAttrs) {
state.pos = state.prevPos;
this.error(state, `Attribute \`${name}\` redefined`);
}
value = this.normalizeAttrValue(state, value.slice(1, -1));
if (name === 'xml:space') {
if (value !== 'default' && value !== 'preserve') {
state.pos = state.prevPos;
this.error(state, `Value of the \`xml:space\` attribute must be "default" or "preserve"`);
}
}
parsedAttrs[name] = value;
}
return parsedAttrs;
}
replaceReference(ref: any, state: any) {
// let state = this;
if (ref[1] === '#') {
// This is a character entity.
let codePoint;
if (ref[2] === 'x') {
codePoint = parseInt(ref.slice(3, -1), 16);
} else {
codePoint = parseInt(ref.slice(2, -1), 10);
}
if (isNaN(codePoint)) {
state.pos = state.prevPos;
this.error(state, `Invalid character entity \`${ref}\``);
}
let char = String.fromCodePoint(codePoint);
if (!Syntax.Char.test(char)) {
state.pos = state.prevPos;
this.error(state, `Invalid character entity \`${ref}\``);
}
return char;
}
// This is a named entity.
let value = namedEntities[ref];
if (value !== void 0) {
return value;
}
if (state.options.resolveUndefinedEntity) {
let resolvedValue = state.options.resolveUndefinedEntity(ref);
if (resolvedValue !== null && resolvedValue !== void 0) {
return resolvedValue;
}
}
if (state.options.ignoreUndefinedEntities) {
return ref;
}
state.pos = state.prevPos;
this.error(state, `Named entity isn't defined: \`${ref}\``);
}
}
export function scan(state: any, regex: any) {
let { pos, slice, xml } = state;
if (!slice) {
if (pos > 0) {
slice = xml.slice(pos);
state.slice = slice;
} else {
slice = xml;
}
}
let matches = slice.match(regex);
if (!matches) {
return emptyArray;
}
state.prevPos = state.pos;
state.pos += matches[0].length;
state.slice = null;
return matches;
} | the_stack |
import {
forwardRef,
useCallback,
useImperativeHandle,
useMemo,
useRef,
useState
} from 'react';
import { StyleSheet } from 'react-native';
import Animated, {
runOnJS,
useDerivedValue,
useSharedValue
} from 'react-native-reanimated';
import {
GestureHandlerRootView,
TapGestureHandler
} from 'react-native-gesture-handler';
import { DateTime } from 'luxon';
import { CalendarProvider } from './contexts/external';
import { CalendarInternalProvider } from './contexts/internal';
import { CalendarAnimatedProvider } from './contexts/animated';
import { CalendarDaysOfWeekHeader } from './components/CalendarDaysOfWeekHeader';
import { calendarYearAndMonthToMonths } from './helpers';
import { CalendarScrollableMonths } from './CalendarScrollableMonths';
import { calculateScrollProgress } from './worklets';
import { CalendarHeaderMonth } from './components/header/CalendarHeaderMonth';
import { CalendarHeaderYear } from './components/header/CalendarHeaderYear';
import { CalendarHeaderDecorator } from './components/header/CalendarHeaderDecorator';
import { CalendarDayKind } from './CalendarDay';
import { CalendarThemeProvider } from './contexts/theme';
import { useCalendarInterval, useSelectedDates } from './hooks';
import { CalendarThemeLight } from './themes';
import type { ForwardedRef } from 'react';
import type { FlatListProps } from 'react-native';
import type { FlatList as RNGestureHandlerFlatList } from 'react-native-gesture-handler';
import type { CalendarAnimatedContextInterface } from './contexts/animated';
import type {
CalendarCurrentAnimatedMonthFromCommonEra,
CalendarStartMonthFromCommonEra,
CalendarEndMonthFromCommonEra,
CalendarDate,
CalendarKind,
CalendarMethods,
CalendarYearAndMonth,
ViewStyleProp,
CalendarSelectionMode,
CalendarTheme,
CalendarPerformanceProps,
CalendarDisabledRange
} from './types';
import type { CalendarInternalContextInterface } from './contexts/internal';
// @ts-expect-error
const AnimatedTapGestureHandler: typeof TapGestureHandler =
Animated.createAnimatedComponent(
// @ts-ignore
TapGestureHandler
);
export type CalendarProps = {
/**
* Calendar kind (type).
* @defaultValue `gregorian`
*/
kind?: CalendarKind;
/**
* Initial month to be shown.
* If not provided, year and month of current local datetime will be selected.
*/
initialCalendarYearAndMonth?: CalendarYearAndMonth;
/**
* Initial selected dates.
*
* If `selectionMode` is `singleDay` only array with one date is allowed.
*
* If any date from this range falls into `disabledDateRanges` ranges,
* it **becomes disabled** and **will not be selected**.
* @defaultValue `[]`
*/
initialSelectedDates?: CalendarDate[];
/**
* Ranges of dates which will be shown as **disabled**.
* They appear with greyed color, unresponsive (can't be selected or unselected).
*
* If `startDateInclusive` is set as `undefined` all dates up until `endDateExclusive` **become disabled**.
*
* If `endDateExclusive` is set as `undefined` all dates after `startDateInclusive` (including this date) **become disabled**.
*
* If both `startDateInclusive` and `endDateExclusive` are set as `undefined` **all dates become disabled**.
* @defaultValue `[]`
*/
disabledDateRanges?: CalendarDisabledRange[];
/**
* Amount of months before initial year and month,
* which will be shown in a calendar.
* @defaultValue `50`
*/
monthsBefore?: number;
/**
* Amount of months after initial year and month,
* which will be shown in a calendar.
* @defaultValue `50`
*/
monthsAfter?: number;
/**
* How much days can be selected simultaneously.
* @defaultValue `singleDay`
*/
selectionMode?: CalendarSelectionMode;
/**
* If calendar has only one (last) selected date,
* can we unselect it by tapping on this date?
* @defaultValue `true`
*/
allowDeselectLastSelectedDate?: boolean;
/**
* How much months can be scrolled over.
* @defaultValue `multipleMonths`
*/
scrollMode?: 'oneMonth' | 'multipleMonths' | 'anyOffset';
/**
* How quickly the calendar scrolling decelerates after the user lifts their finger.
* @defaultValue `normal`
*/
scrollModeDeceleration?: FlatListProps<any>['decelerationRate'];
/**
* Active (current) calendar day.
* If provided, it will be highlighted in active color.
*
* If date falls into `disabledDateRanges` ranges,
* it **becomes disabled** and **will not be active**.
*/
activeCalendarDay?: CalendarDate;
/**
* Theme object to customize calendar appearance
*/
theme?: CalendarTheme;
/**
* Properties to customize performance characteristics
*/
performanceProps?: CalendarPerformanceProps;
/**
* Reference to internal animated FlatList
*/
animatedFlatListRef?: ForwardedRef<RNGestureHandlerFlatList<any>>;
/**
* Callback is called when state of a day changes,
* i.e. it's selected / unselected.
*
* **Note:** for `singleDay` selection mode day unselected by
* other selected day is not notified.
* You can understand it was unselected by checking
* current `selectionMode`.
*/
onDayStateChange?: (day: CalendarDate, kind: CalendarDayKind) => void;
} & ViewStyleProp;
export const Calendar = forwardRef<CalendarMethods, CalendarProps>(
(
{
initialCalendarYearAndMonth: _initialCalendarYearAndMonth,
initialSelectedDates = [],
disabledDateRanges = [],
monthsBefore = 50,
monthsAfter = 50,
selectionMode = 'singleDay',
scrollMode = 'oneMonth',
scrollModeDeceleration = 'normal',
activeCalendarDay: _activeCalendarDay,
allowDeselectLastSelectedDate = true,
theme = CalendarThemeLight,
performanceProps,
style: _containerStyle,
animatedFlatListRef,
onDayStateChange
}: CalendarProps,
ref
) => {
const [activeCalendarDay] = useMemo<[CalendarDate]>(() => {
const nowTime = DateTime.local();
return [
_activeCalendarDay ?? {
year: nowTime.year,
month: nowTime.month,
day: nowTime.day
}
];
}, [_activeCalendarDay]);
const initialCalendarYearAndMonth = useMemo<CalendarYearAndMonth>(() => {
const nowTime = DateTime.local();
return (
_initialCalendarYearAndMonth ?? {
year: nowTime.year,
month: nowTime.month
}
);
}, [_initialCalendarYearAndMonth]);
const [startCalendarYearAndMonth, endCalendarYearAndMonth] = useMemo<
[CalendarYearAndMonth, CalendarYearAndMonth]
>(() => {
const currentYearAndMonth = DateTime.fromObject(
initialCalendarYearAndMonth
);
const startDateTime = currentYearAndMonth
.minus({ months: monthsBefore })
.startOf('month');
const endDateTime = currentYearAndMonth
.plus({ months: monthsAfter })
.startOf('month');
const startYearAndMonth: CalendarYearAndMonth = {
year: startDateTime.year,
month: startDateTime.month
};
const endYearAndMonth: CalendarYearAndMonth = {
year: endDateTime.year,
month: endDateTime.month
};
return [startYearAndMonth, endYearAndMonth];
}, [initialCalendarYearAndMonth, monthsBefore, monthsAfter]);
const calendarInterval = useCalendarInterval(
startCalendarYearAndMonth,
endCalendarYearAndMonth
);
const [calendarStartMonthFromCommonEra, calendarEndMonthFromCommonEra] =
useMemo<
readonly [
CalendarStartMonthFromCommonEra,
CalendarEndMonthFromCommonEra
]
>(() => {
return [
calendarYearAndMonthToMonths(startCalendarYearAndMonth),
calendarYearAndMonthToMonths(endCalendarYearAndMonth)
] as const;
}, [startCalendarYearAndMonth, endCalendarYearAndMonth]);
const calendarAnimatedCommonEraMonth: CalendarCurrentAnimatedMonthFromCommonEra =
useDerivedValue(() => {
return (
initialCalendarYearAndMonth.year * 12 +
initialCalendarYearAndMonth.month
);
}, [initialCalendarYearAndMonth]);
const calendarCurrentAnimatedMonthInYear = useDerivedValue(() => {
return initialCalendarYearAndMonth.month;
}, [initialCalendarYearAndMonth]);
const calendarInitialScrollProgress = useMemo(() => {
return runOnJS(calculateScrollProgress)(calendarAnimatedCommonEraMonth, [
calendarStartMonthFromCommonEra,
calendarEndMonthFromCommonEra
]) as unknown as number;
}, [calendarStartMonthFromCommonEra, calendarEndMonthFromCommonEra]);
const calendarAnimatedScrollProgress = useSharedValue(
calendarInitialScrollProgress
);
const animatedContextVariables = useMemo<CalendarAnimatedContextInterface>(
() => ({
calendarAnimatedCommonEraMonth: calendarAnimatedCommonEraMonth,
calendarCurrentAnimatedMonthInYear: calendarCurrentAnimatedMonthInYear,
calendarAnimatedScrollProgress: calendarAnimatedScrollProgress,
calendarStartMonthFromCommonEra: calendarStartMonthFromCommonEra,
calendarEndMonthFromCommonEra: calendarEndMonthFromCommonEra
}),
[
calendarAnimatedCommonEraMonth,
calendarCurrentAnimatedMonthInYear,
calendarAnimatedScrollProgress,
calendarStartMonthFromCommonEra,
calendarEndMonthFromCommonEra
]
);
const [selectedDates, isLastSelectedDate, selectDate, deselectDate] =
useSelectedDates(selectionMode, initialSelectedDates);
const onCalendarDayStateChange = useCallback(
(day: CalendarDate, calendarKind: CalendarDayKind) => {
if (calendarKind === CalendarDayKind.SELECTED) {
selectDate(day);
onDayStateChange?.(day, calendarKind);
} else if (calendarKind === CalendarDayKind.DEFAULT) {
deselectDate(day, allowDeselectLastSelectedDate);
if (allowDeselectLastSelectedDate || !isLastSelectedDate) {
onDayStateChange?.(day, calendarKind);
}
}
},
[
allowDeselectLastSelectedDate,
isLastSelectedDate,
selectDate,
deselectDate,
onDayStateChange
]
);
useImperativeHandle(
ref,
() => ({
select: selectDate,
deselect: deselectDate
}),
[selectDate, deselectDate]
);
const contentWrapperRef = useRef<typeof AnimatedTapGestureHandler>(null);
// const contentWrapperVariables = useMemo<ContentWrapperContextInterface>(
// () => ({
// contentWrapperRef: contentWrapperRef
// }),
// [contentWrapperRef]
// );
const internalContextVariables = useMemo<CalendarInternalContextInterface>(
() => ({
activeAnimatedMonth: calendarAnimatedCommonEraMonth,
activeCalendarDay: activeCalendarDay,
activeCalendarYearAndMonth: initialCalendarYearAndMonth,
selectDate: selectDate,
deselectDate: deselectDate,
selectedDates: selectedDates,
disabledDateRanges: disabledDateRanges,
allowDeselectLastSelectedDate: allowDeselectLastSelectedDate,
monthsBefore,
monthsAfter,
startCalendarYearAndMonth: startCalendarYearAndMonth,
endCalendarYearAndMonth: endCalendarYearAndMonth,
calendarInterval: calendarInterval,
contentWrapperRef: contentWrapperRef,
onCalendarDayStateChange: onCalendarDayStateChange
}),
[
calendarAnimatedCommonEraMonth,
activeCalendarDay,
initialCalendarYearAndMonth,
selectDate,
deselectDate,
selectedDates,
disabledDateRanges,
allowDeselectLastSelectedDate,
monthsBefore,
monthsAfter,
startCalendarYearAndMonth,
endCalendarYearAndMonth,
calendarInterval,
contentWrapperRef,
onCalendarDayStateChange
]
);
const externalContextVariables = useMemo<CalendarMethods>(
() => ({
select: selectDate,
deselect: deselectDate
}),
[selectDate, deselectDate]
);
const [calendarHeader] = useState(40);
return (
<GestureHandlerRootView style={theme.sheet}>
<CalendarThemeProvider value={theme}>
<CalendarProvider value={externalContextVariables}>
<CalendarInternalProvider value={internalContextVariables}>
<CalendarAnimatedProvider value={animatedContextVariables}>
<CalendarHeaderDecorator style={styles.headerDecoratorStyle}>
<CalendarHeaderMonth
style={styles.headerMonthStyle}
height={calendarHeader}
/>
<CalendarHeaderYear height={calendarHeader} />
</CalendarHeaderDecorator>
<CalendarDaysOfWeekHeader />
<CalendarScrollableMonths
ref={animatedFlatListRef}
scrollMode={scrollMode}
scrollModeDeceleration={scrollModeDeceleration}
activeCalendarDay={activeCalendarDay}
selectedDates={selectedDates}
performanceProps={performanceProps}
onCalendarDayPress={onCalendarDayStateChange}
/>
</CalendarAnimatedProvider>
</CalendarInternalProvider>
</CalendarProvider>
</CalendarThemeProvider>
</GestureHandlerRootView>
);
}
);
const styles = StyleSheet.create({
headerDecoratorStyle: {
marginBottom: 4,
marginTop: 4
},
headerMonthStyle: { marginRight: 8 },
gestureView: {
flexGrow: 1
}
}); | the_stack |
import chalk from "chalk";
import inquirer from "inquirer";
import L from "lodash";
import path from "upath";
import { CommonArgs } from "..";
import { logger } from "../deps";
import { getOrStartAuth } from "../utils/auth-utils";
import {
CONFIG_FILE_NAME,
DEFAULT_CONFIG,
DEFAULT_PUBLIC_FILES_CONFIG,
fillDefaults,
findConfigFile,
isPageAwarePlatform,
PlasmicConfig,
writeConfig,
} from "../utils/config-utils";
import {
detectCreateReactApp,
detectGatsby,
detectNextJs,
detectTypescript,
} from "../utils/envdetect";
import { existsBuffered } from "../utils/file-utils";
import { ensure, ensureString } from "../utils/lang-utils";
import {
findPackageJsonDir,
getCliVersion,
installUpgrade,
} from "../utils/npm-utils";
import { confirmWithUser } from "../utils/user-utils";
export interface InitArgs extends CommonArgs {
host: string;
platform: "" | "react" | "nextjs" | "gatsby";
codeLang: "" | "ts" | "js";
codeScheme: "" | "blackbox" | "direct";
styleScheme: "" | "css" | "css-modules";
imagesScheme: "" | "inlined" | "files" | "public-files";
imagesPublicDir: string;
imagesPublicUrlPrefix: string;
srcDir: string;
plasmicDir: string;
pagesDir?: string;
enableSkipAuth?: boolean;
reactRuntime?: "classic" | "automatic";
}
export async function initPlasmic(
opts: InitArgs & { enableSkipAuth?: boolean }
) {
if (!opts.baseDir) opts.baseDir = process.cwd();
await getOrStartAuth(opts);
const configFile =
opts.config || findConfigFile(opts.baseDir, { traverseParents: false });
if (configFile && existsBuffered(configFile)) {
logger.error(
"You already have a plasmic.json file! Please either delete or edit it directly."
);
return;
}
// path to plasmic.json
const newConfigFile =
opts.config || path.join(opts.baseDir, CONFIG_FILE_NAME);
const answers = await deriveInitAnswers(opts);
await writeConfig(newConfigFile, createInitConfig(answers), opts.baseDir);
if (!process.env.QUIET) {
logger.info("Successfully created plasmic.json.\n");
}
const answer = await confirmWithUser(
"@plasmicapp/react-web is a small runtime required by Plasmic-generated code.\n Do you want to add it now?",
opts.yes
);
if (answer) {
installUpgrade("@plasmicapp/react-web", opts.baseDir);
}
}
function createInitConfig(opts: Omit<InitArgs, "baseDir">): PlasmicConfig {
return fillDefaults({
srcDir: opts.srcDir,
defaultPlasmicDir: opts.plasmicDir,
...(opts.platform === "nextjs" && {
nextjsConfig: {
pagesDir: opts.pagesDir,
},
}),
...(opts.platform === "gatsby" && {
gatsbyConfig: {
pagesDir: opts.pagesDir,
},
}),
code: {
...(opts.codeLang && { lang: opts.codeLang }),
...(opts.codeScheme && { scheme: opts.codeScheme }),
...(opts.reactRuntime && { reactRuntime: opts.reactRuntime }),
},
style: {
...(opts.styleScheme && { scheme: opts.styleScheme }),
},
images: {
...(opts.imagesScheme && { scheme: opts.imagesScheme }),
...(opts.imagesScheme && { publicDir: opts.imagesPublicDir }),
...(opts.imagesScheme && { publicUrlPrefix: opts.imagesPublicUrlPrefix }),
},
...(opts.platform && { platform: opts.platform }),
cliVersion: getCliVersion(),
});
}
type DefaultDeriver = {
[T in keyof Omit<InitArgs, "baseDir">]?:
| string
| ((srcDir: string) => string);
} & {
alwaysDerived: (keyof Omit<InitArgs, "baseDir">)[];
};
/**
* A simpler subset of the DistinctQuestion interface that we actually use.
*/
interface SimpleQuestion {
name: string;
message: string;
type?: "list";
choices?: () => { name: string; value: string }[];
}
/**
* Pretty-print the question along with the default answer, as if that was the choice
* being made. Don't actually interactively prompt for a response.
*/
function simulatePrompt(
question: SimpleQuestion,
defaultAnswer: string | boolean | undefined,
bold = false
) {
const message = question.message.endsWith(">")
? question.message
: question.message + ">";
process.stdout.write((bold ? chalk.bold(message) : message) + " ");
logger.info(
chalk.cyan(
question.choices?.().find((choice) => choice.value === defaultAnswer)
?.name ?? defaultAnswer
)
);
}
async function deriveInitAnswers(
opts: Partial<InitArgs> & { baseDir: string }
) {
const plasmicRootDir = opts.config ? path.dirname(opts.config) : opts.baseDir;
const platform = !!opts.platform
? opts.platform
: detectNextJs()
? "nextjs"
: detectGatsby()
? "gatsby"
: "react";
const isCra = detectCreateReactApp();
const isNext = platform === "nextjs";
const isGatsby = platform === "gatsby";
const isGeneric = !isCra && !isNext && !isGatsby;
const isTypescript = detectTypescript();
if (isNext) {
logger.info("Detected Next.js...");
} else if (isGatsby) {
logger.info("Detected Gatsby...");
} else if (isCra) {
logger.info("Detected create-react-app...");
}
// Platform-specific defaults that take precedent
const deriver = isNext
? getNextDefaults(plasmicRootDir)
: isGatsby
? getGatsbyDefaults(plasmicRootDir)
: isCra
? getCraDefaults(plasmicRootDir)
: getGenericDefaults(plasmicRootDir);
const srcDir = ensureString(deriver.srcDir);
const getDefaultAnswer = (
name: keyof Omit<InitArgs, "baseDir">,
defaultAnswer?: string
) => {
// Try to get the user CLI arg override first
if (opts[name]) {
return opts[name];
} else if (deriver[name]) {
// Then get the platform-specific default
if (L.isFunction(deriver[name])) {
const fn = deriver[name] as (s: string) => string;
return fn(srcDir);
}
return deriver[name];
} else {
// Other specified default
return defaultAnswer;
}
};
// Start with a complete set of defaults. Some of these are not worth displaying.
const answers: Omit<InitArgs, "baseDir"> = {
host: getDefaultAnswer("host", "") as any,
platform,
codeLang: getDefaultAnswer("codeLang", isTypescript ? "ts" : "js") as any,
codeScheme: getDefaultAnswer(
"codeScheme",
DEFAULT_CONFIG.code.scheme
) as any,
styleScheme: getDefaultAnswer(
"styleScheme",
DEFAULT_CONFIG.style.scheme
) as any,
imagesScheme: getDefaultAnswer(
"imagesScheme",
DEFAULT_CONFIG.images.scheme
) as any,
imagesPublicDir: getDefaultAnswer(
"imagesPublicDir",
ensure(DEFAULT_PUBLIC_FILES_CONFIG.publicDir)
) as any,
imagesPublicUrlPrefix: getDefaultAnswer(
"imagesPublicUrlPrefix",
ensure(DEFAULT_PUBLIC_FILES_CONFIG.publicUrlPrefix)
) as any,
srcDir: getDefaultAnswer("srcDir", DEFAULT_CONFIG.srcDir) as any,
plasmicDir: getDefaultAnswer(
"plasmicDir",
DEFAULT_CONFIG.defaultPlasmicDir
) as any,
pagesDir: getDefaultAnswer("pagesDir", undefined) as any,
reactRuntime: getDefaultAnswer("reactRuntime", "classic") as any,
};
const prominentAnswers = L.omit(answers, "codeScheme");
if (process.env.QUIET) {
return answers;
}
logger.info(
chalk.bold(
"Plasmic Express Setup -- Here are the default settings we recommend:\n"
)
);
await performAsks(true);
// Allow a user to short-circuit
const useExpressQuestion: SimpleQuestion = {
name: "continue",
message: `Would you like to accept these defaults?`,
type: "list",
choices: () => [
{
value: "yes",
name: "Accept these defaults",
},
{
value: "no",
name: "Customize the choices",
},
],
};
logger.info("");
if (opts.yes) {
simulatePrompt(useExpressQuestion, "yes", true);
return answers;
} else {
const useExpress = await inquirer.prompt([useExpressQuestion]);
if (useExpress.continue === "yes") {
return answers;
}
}
/**
* @param express When true, we pretty-print the question along with the default answer, as if that was the choice
* being made. This is for displaying the default choices in the express setup.
*/
async function performAsks(express: boolean) {
// Proceed with platform-specific prompts
async function maybePrompt(question: SimpleQuestion) {
const name = ensure(question.name) as keyof Omit<InitArgs, "baseDir">;
const message = ensure(question.message) as string;
if (opts[name]) {
logger.info(message + answers[name] + "(specified in CLI arg)");
} else if (express) {
const defaultAnswer = answers[name];
simulatePrompt(question, defaultAnswer);
} else if (!opts.yes && !deriver.alwaysDerived.includes(name)) {
const ans = await inquirer.prompt({
...question,
default: answers[name],
});
// Not sure why TS complains here without this cast.
(answers as any)[name] = ans[name];
}
// Other questions are silently skipped
}
await maybePrompt({
name: "srcDir",
message: `${getInitArgsQuestion("srcDir")}\n>`,
});
await maybePrompt({
name: "plasmicDir",
message: `${getInitArgsQuestion("plasmicDir")} (This is relative to "${
answers.srcDir
}")\n>`,
});
if (isPageAwarePlatform(platform)) {
await maybePrompt({
name: "pagesDir",
message: `${getInitArgsQuestion("pagesDir")} (This is relative to "${
answers.srcDir
}")\n>`,
});
}
await maybePrompt({
name: "codeLang",
message: `${getInitArgsQuestion("codeLang")}\n`,
type: "list",
choices: () => [
{
name: `Typescript${isTypescript ? " (tsconfig.json detected)" : ""}`,
value: "ts",
},
{
name: `Javascript${
!isTypescript ? " (no tsconfig.json detected)" : ""
}`,
value: "js",
},
],
});
await maybePrompt({
name: "styleScheme",
message: `${getInitArgsQuestion("styleScheme")}\n`,
type: "list",
choices: () => [
{
name: `CSS modules, imported as "import sty from './plasmic.module.css'"`,
value: "css-modules",
},
{
name: `Plain CSS stylesheets, imported as "import './plasmic.css'"`,
value: "css",
},
],
});
await maybePrompt({
name: "imagesScheme",
message: `${getInitArgsQuestion("imagesScheme")}\n`,
type: "list",
choices: () => [
{
name: `Imported as files, like "import img from './image.png'". ${
isGeneric ? "Not all bundlers support this." : ""
}`,
value: "files",
},
{
name: `Images stored in a public folder, referenced like <img src="/static/image.png"/>`,
value: "public-files",
},
{
name: `Inlined as base64-encoded data URIs`,
value: "inlined",
},
],
});
if (answers.imagesScheme === "public-files") {
await maybePrompt({
name: "imagesPublicDir",
message: `${getInitArgsQuestion(
"imagesPublicDir"
)} (This is relative to "${answers.srcDir}")\n>`,
});
await maybePrompt({
name: "imagesPublicUrlPrefix",
message: `${getInitArgsQuestion("imagesPublicUrlPrefix")} ${
isNext ? `(for Next.js, this is usually "/")` : ""
}\n>`,
});
}
}
await performAsks(false);
return answers as InitArgs;
}
function getNextDefaults(plasmicRootDir: string): DefaultDeriver {
const projectRootDir = findPackageJsonDir(plasmicRootDir) ?? plasmicRootDir;
return {
srcDir: path.relative(
plasmicRootDir,
path.join(projectRootDir, "components")
),
pagesDir: (srcDir: string) =>
path.relative(
path.join(plasmicRootDir, srcDir),
path.join(projectRootDir, "pages")
),
styleScheme: "css-modules",
imagesScheme: "public-files",
imagesPublicDir: (srcDir: string) =>
path.relative(
path.join(plasmicRootDir, srcDir),
path.join(projectRootDir, "public")
),
imagesPublicUrlPrefix: "/",
alwaysDerived: [
"styleScheme",
"imagesScheme",
"imagesPublicDir",
"pagesDir",
],
};
}
function getGatsbyDefaults(plasmicRootDir: string): DefaultDeriver {
const projectRootDir = findPackageJsonDir(plasmicRootDir) ?? plasmicRootDir;
return {
srcDir: path.relative(
plasmicRootDir,
path.join(projectRootDir, "src", "components")
),
pagesDir: (srcDir: string) => {
const absSrcDir = path.join(plasmicRootDir, srcDir);
const absPagesDir = path.join(projectRootDir, "src", "pages");
const relDir = path.relative(absSrcDir, absPagesDir);
return relDir;
},
styleScheme: "css-modules",
imagesScheme: "files",
imagesPublicDir: (srcDir: string) =>
path.relative(
path.join(plasmicRootDir, srcDir),
path.join(projectRootDir, "static")
),
imagesPublicUrlPrefix: "/",
alwaysDerived: ["imagesScheme", "pagesDir"],
};
}
function getCraDefaults(plasmicRootDir: string): DefaultDeriver {
const projectRootDir = findPackageJsonDir(plasmicRootDir) ?? plasmicRootDir;
return {
srcDir: path.relative(
plasmicRootDir,
path.join(projectRootDir, "src", "components")
),
styleScheme: "css-modules",
imagesScheme: "files",
imagesPublicDir: (srcDir: string) =>
path.relative(
path.join(plasmicRootDir, srcDir),
path.join(projectRootDir, "public")
),
alwaysDerived: [],
};
}
function getGenericDefaults(plasmicRootDir: string): DefaultDeriver {
const projectRootDir = findPackageJsonDir(plasmicRootDir) ?? plasmicRootDir;
const srcDir = existsBuffered(path.join(projectRootDir, "src"))
? path.join(projectRootDir, "src", "components")
: path.join(projectRootDir, "components");
return {
srcDir: path.relative(plasmicRootDir, srcDir),
alwaysDerived: [],
};
}
/**
* Consolidating where we are specifying the descriptions of InitArgs
*/
const INIT_ARGS_DESCRIPTION: {
[T in keyof Omit<InitArgs, "baseDir">]: {
shortDescription: string;
longDescription?: string;
question?: string;
choices?: string[];
};
} = {
host: {
shortDescription: "Plasmic host to use",
},
platform: {
shortDescription: "Target platform",
longDescription: "Target platform to generate code for",
choices: ["react", "nextjs", "gatsby"],
},
codeLang: {
shortDescription: "Target language",
longDescription: "Target language to generate code for",
question: `What target language should Plasmic generate code in?`,
choices: ["js", "ts"],
},
codeScheme: {
shortDescription: "Code generation scheme",
longDescription: "Code generation scheme to use",
choices: ["blackbox", "direct"],
},
styleScheme: {
shortDescription: "Styling framework",
longDescription: "Styling framework to use",
question: "How should we generate css for Plasmic components?",
choices: ["css", "css-modules"],
},
imagesScheme: {
shortDescription: "Image scheme",
longDescription: "How to reference used image files",
question: "How should we reference image files used in Plasmic components?",
choices: ["inlined", "files", "public-files"],
},
imagesPublicDir: {
shortDescription: "Directory of public static files",
longDescription: "Default directory to put public static files",
question: "What directory should static image files be put into?",
},
imagesPublicUrlPrefix: {
shortDescription: "URL prefix for static files",
longDescription: "URL prefix from which the app will serve static files",
question:
"What's the URL prefix from which the app will serve static files?",
},
srcDir: {
shortDescription: "Source directory",
longDescription:
"Default directory to put React component files (that you edit) into",
question:
"What directory should React component files (that you edit) be put into?",
},
plasmicDir: {
shortDescription: "Plasmic-managed directory",
longDescription:
"Default directory to put Plasmic-managed files into; relative to src-dir",
question:
"What directory should Plasmic-managed files (that you should not edit) be put into?",
},
pagesDir: {
shortDescription: "Pages directory",
longDescription: "Default directory to put page files (that you edit) into",
question: "What directory should pages be put into?",
},
};
/**
* Get the short description, which exists for all args
* @param key
* @returns
*/
export function getInitArgsShortDescription(
key: keyof Omit<InitArgs, "baseDir">
) {
return INIT_ARGS_DESCRIPTION[key]?.shortDescription;
}
/**
* Try to get a long description, falling back to the short description
* @param key
* @returns
*/
export function getInitArgsLongDescription(
key: keyof Omit<InitArgs, "baseDir">
) {
return (
INIT_ARGS_DESCRIPTION[key]?.longDescription ??
INIT_ARGS_DESCRIPTION[key]?.shortDescription
);
}
/**
* Try to get a question form, falling back to the description
* @param key
* @returns
*/
export function getInitArgsQuestion(key: keyof Omit<InitArgs, "baseDir">) {
return (
INIT_ARGS_DESCRIPTION[key]?.question ??
INIT_ARGS_DESCRIPTION[key]?.longDescription ??
INIT_ARGS_DESCRIPTION[key]?.shortDescription
);
}
/**
* Get the possible choices for an arg
* @param key
* @returns
*/
export function getInitArgsChoices(key: keyof Omit<InitArgs, "baseDir">) {
return INIT_ARGS_DESCRIPTION[key]?.choices;
}
/**
* Get a `opt` object for use with the `yargs` library.
* If no choices are specified, assume it's freeform string input
* All options use "" as the default, unless overridden
* @param key
* @param defaultOverride
* @returns
*/
export function getYargsOption(
key: keyof Omit<InitArgs, "baseDir">,
defaultOverride?: string
) {
const arg = ensure(INIT_ARGS_DESCRIPTION[key]);
return !arg.choices
? {
describe: ensure(getInitArgsLongDescription(key)),
string: true,
default: defaultOverride ?? "",
}
: {
describe: ensure(getInitArgsLongDescription(key)),
choices: ["", ...ensure(getInitArgsChoices(key))],
default: defaultOverride ?? "",
};
} | the_stack |
import {
MarginCalculatorInstance,
MockERC20Instance,
MockOracleInstance,
MockWhitelistModuleInstance,
MarginPoolInstance,
ControllerInstance,
AddressBookInstance,
OwnedUpgradeabilityProxyInstance,
MockOtokenInstance,
} from '../../build/types/truffle-types'
import BigNumber from 'bignumber.js'
import {
createScaledNumber as scaleNum,
createScaledBigNumber as scaleBigNum,
createScaledNumber,
createTokenAmount,
calcRelativeDiff,
} from '../utils'
const { expectRevert, time } = require('@openzeppelin/test-helpers')
const CallTester = artifacts.require('CallTester.sol')
const MockERC20 = artifacts.require('MockERC20.sol')
const MockOtoken = artifacts.require('MockOtoken.sol')
const MockOracle = artifacts.require('MockOracle.sol')
const OwnedUpgradeabilityProxy = artifacts.require('OwnedUpgradeabilityProxy.sol')
const MarginCalculator = artifacts.require('MarginCalculator.sol')
const MockWhitelistModule = artifacts.require('MockWhitelistModule.sol')
const AddressBook = artifacts.require('AddressBook.sol')
const MarginPool = artifacts.require('MarginPool.sol')
const Controller = artifacts.require('Controller.sol')
const MarginVault = artifacts.require('MarginVault.sol')
// address(0)
const ZERO_ADDR = '0x0000000000000000000000000000000000000000'
enum ActionType {
OpenVault,
MintShortOption,
BurnShortOption,
DepositLongOption,
WithdrawLongOption,
DepositCollateral,
WithdrawCollateral,
SettleVault,
Redeem,
Call,
Liquidate,
InvalidAction,
}
contract('Controller: naked margin', ([owner, accountOwner1, liquidator, random]) => {
// ERC20 mock
let usdc: MockERC20Instance
let weth: MockERC20Instance
let weth2: MockERC20Instance
// Oracle module
let oracle: MockOracleInstance
// calculator module
let calculator: MarginCalculatorInstance
// margin pool module
let marginPool: MarginPoolInstance
// whitelist module mock
let whitelist: MockWhitelistModuleInstance
// addressbook module mock
let addressBook: AddressBookInstance
// controller module
let controllerImplementation: ControllerInstance
let controllerProxy: ControllerInstance
const usdcDecimals = 6
const wethDecimals = 18
const oracleDeviation = 0.05
const oracleDeviationValue = scaleNum(oracleDeviation, 27)
const productSpotShockValue = scaleBigNum(0.75, 27)
// array of time to expiry
const day = 60 * 24
const timeToExpiry = [day * 7, day * 14, day * 28, day * 42, day * 56]
// array of upper bound value correspond to time to expiry
const expiryToValue = [
scaleNum(0.1678, 27),
scaleNum(0.237, 27),
scaleNum(0.3326, 27),
scaleNum(0.4032, 27),
scaleNum(0.4603, 27),
]
const wethDust = scaleNum(0.1, wethDecimals)
const usdcDust = scaleNum(1, usdcDecimals)
const wethCap = scaleNum(50000, wethDecimals)
const usdcCap = scaleNum(1000000, wethDecimals)
const errorDelta = 0.1
before('Deployment', async () => {
// addressbook deployment
addressBook = await AddressBook.new()
// ERC20 deployment
usdc = await MockERC20.new('USDC', 'USDC', usdcDecimals)
weth = await MockERC20.new('WETH', 'WETH', wethDecimals)
weth2 = await MockERC20.new('WETH', 'WETH', wethDecimals)
// deploy Oracle module
oracle = await MockOracle.new(addressBook.address, { from: owner })
// calculator deployment
calculator = await MarginCalculator.new(oracle.address)
// margin pool deployment
marginPool = await MarginPool.new(addressBook.address)
// whitelist module
whitelist = await MockWhitelistModule.new()
// set margin pool in addressbook
await addressBook.setMarginPool(marginPool.address)
// set calculator in addressbook
await addressBook.setMarginCalculator(calculator.address)
// set oracle in AddressBook
await addressBook.setOracle(oracle.address)
// set whitelist module address
await addressBook.setWhitelist(whitelist.address)
// deploy Controller module
const lib = await MarginVault.new()
await Controller.link('MarginVault', lib.address)
controllerImplementation = await Controller.new()
// set controller address in AddressBook
await addressBook.setController(controllerImplementation.address, { from: owner })
// check controller deployment
const controllerProxyAddress = await addressBook.getController()
controllerProxy = await Controller.at(controllerProxyAddress)
const proxy: OwnedUpgradeabilityProxyInstance = await OwnedUpgradeabilityProxy.at(controllerProxyAddress)
assert.equal(await proxy.proxyOwner(), addressBook.address, 'Proxy owner address mismatch')
assert.equal(await controllerProxy.owner(), owner, 'Controller owner address mismatch')
assert.equal(await controllerProxy.systemPartiallyPaused(), false, 'system is partially paused')
// set max cap
await controllerProxy.setNakedCap(usdc.address, usdcCap, { from: owner })
await controllerProxy.setNakedCap(weth.address, wethCap, { from: owner })
// make everyone rich
await usdc.mint(accountOwner1, createTokenAmount(10000000, usdcDecimals))
await weth.mint(accountOwner1, createTokenAmount(10000, wethDecimals))
// set calculator configs
// whitelist collateral
await whitelist.whitelistCollateral(usdc.address)
await whitelist.whitelistCollateral(weth.address)
// set product spot shock value
await calculator.setSpotShock(weth.address, usdc.address, usdc.address, true, productSpotShockValue)
await calculator.setSpotShock(weth.address, usdc.address, weth.address, false, productSpotShockValue)
// set oracle deviation
await calculator.setOracleDeviation(oracleDeviationValue, { from: owner })
// set WETH dust amount
await calculator.setCollateralDust(weth.address, wethDust, { from: owner })
// set USDC dust amount
await calculator.setCollateralDust(usdc.address, usdcDust, { from: owner })
// set product upper bound values
await calculator.setUpperBoundValues(weth.address, usdc.address, usdc.address, true, timeToExpiry, expiryToValue, {
from: owner,
})
await calculator.setUpperBoundValues(weth.address, usdc.address, weth.address, false, timeToExpiry, expiryToValue, {
from: owner,
})
})
describe('settle naked margin vault', async () => {
before('open position, and set time past expiry', async () => {
const shortAmount = 1
const shortStrike = 100
const underlyingPrice = 150
const scaledUnderlyingPrice = scaleBigNum(underlyingPrice, 8)
const isPut = true
const optionExpiry = new BigNumber(await time.latest()).plus(timeToExpiry[0])
const shortOtoken = await MockOtoken.new()
await shortOtoken.init(
addressBook.address,
weth.address,
usdc.address,
usdc.address,
scaleNum(shortStrike),
optionExpiry,
isPut,
)
// whitelist otoken
await whitelist.whitelistOtoken(shortOtoken.address)
// set underlying price in oracle
await oracle.setRealTimePrice(weth.address, scaledUnderlyingPrice)
// open position
const vaultCounter = new BigNumber(await controllerProxy.getAccountVaultCounter(accountOwner1)).plus(1)
const vaultType = web3.eth.abi.encodeParameter('uint256', 1)
// const collateralAmount = createTokenAmount(shortStrike, usdcDecimals)
const collateralAmount = await calculator.getNakedMarginRequired(
weth.address,
usdc.address,
usdc.address,
createTokenAmount(shortAmount),
createTokenAmount(shortStrike),
scaledUnderlyingPrice,
optionExpiry,
usdcDecimals,
isPut,
)
const mintArgs = [
{
actionType: ActionType.OpenVault,
owner: accountOwner1,
secondAddress: accountOwner1,
asset: ZERO_ADDR,
vaultId: vaultCounter.toString(),
amount: '0',
index: '0',
data: vaultType,
},
{
actionType: ActionType.MintShortOption,
owner: accountOwner1,
secondAddress: accountOwner1,
asset: shortOtoken.address,
vaultId: vaultCounter.toString(),
amount: createTokenAmount(shortAmount),
index: '0',
data: ZERO_ADDR,
},
{
actionType: ActionType.DepositCollateral,
owner: accountOwner1,
secondAddress: accountOwner1,
asset: usdc.address,
vaultId: vaultCounter.toString(),
amount: collateralAmount.toString(),
index: '0',
data: ZERO_ADDR,
},
]
await usdc.approve(marginPool.address, collateralAmount.toString(), { from: accountOwner1 })
await controllerProxy.operate(mintArgs, { from: accountOwner1 })
const nakedMarginPool = new BigNumber(await controllerProxy.getNakedPoolBalance(usdc.address))
assert.equal(nakedMarginPool.toString(), collateralAmount.toString(), 'Naked margin colalteral tracking mismatch')
// go to expiry
await time.increase(optionExpiry.plus(10).toString())
const ethPriceAtExpiry = 70
await oracle.setExpiryPriceFinalizedAllPeiodOver(usdc.address, optionExpiry, createScaledNumber(1), true)
await oracle.setExpiryPriceFinalizedAllPeiodOver(
weth.address,
optionExpiry,
createScaledNumber(ethPriceAtExpiry),
true,
)
})
it('should revert settling an expired undercollateralized naked margin vault', async () => {
const vaultCounter = new BigNumber(await controllerProxy.getAccountVaultCounter(accountOwner1))
// settle the second vault (with only long otoken in it)
const settleArgs = [
{
actionType: ActionType.SettleVault,
owner: accountOwner1,
secondAddress: accountOwner1,
asset: ZERO_ADDR,
vaultId: vaultCounter.toString(),
amount: '0',
index: '0',
data: ZERO_ADDR,
},
]
await expectRevert(controllerProxy.operate(settleArgs, { from: accountOwner1 }), 'C32')
})
})
describe('Naked margin position: full liquidation put position', () => {
const shortAmount = 1
const shortStrike = 100
const isPut = true
let shortOtoken: MockOtokenInstance
let requiredMargin: BigNumber
let vaultCounter: BigNumber
before('Deploy new short otoken, and open naked position', async () => {
const underlyingPrice = 150
const scaledUnderlyingPrice = scaleBigNum(underlyingPrice, 8)
const optionExpiry = new BigNumber(await time.latest()).plus(timeToExpiry[0])
shortOtoken = await MockOtoken.new()
await shortOtoken.init(
addressBook.address,
weth.address,
usdc.address,
usdc.address,
scaleNum(shortStrike),
optionExpiry,
isPut,
)
// whitelist otoken
await whitelist.whitelistOtoken(shortOtoken.address)
// set underlying price in oracle
await oracle.setRealTimePrice(weth.address, scaledUnderlyingPrice)
// open position
vaultCounter = new BigNumber(await controllerProxy.getAccountVaultCounter(accountOwner1)).plus(1)
const vaultType = web3.eth.abi.encodeParameter('uint256', 1)
requiredMargin = new BigNumber(
await calculator.getNakedMarginRequired(
weth.address,
usdc.address,
usdc.address,
createTokenAmount(shortAmount),
createTokenAmount(shortStrike),
scaledUnderlyingPrice,
optionExpiry,
usdcDecimals,
isPut,
),
)
const mintArgs = [
{
actionType: ActionType.OpenVault,
owner: accountOwner1,
secondAddress: accountOwner1,
asset: ZERO_ADDR,
vaultId: vaultCounter.toString(),
amount: '0',
index: '0',
data: vaultType,
},
{
actionType: ActionType.MintShortOption,
owner: accountOwner1,
secondAddress: accountOwner1,
asset: shortOtoken.address,
vaultId: vaultCounter.toString(),
amount: createTokenAmount(shortAmount),
index: '0',
data: ZERO_ADDR,
},
{
actionType: ActionType.DepositCollateral,
owner: accountOwner1,
secondAddress: accountOwner1,
asset: usdc.address,
vaultId: vaultCounter.toString(),
amount: requiredMargin.toString(),
index: '0',
data: ZERO_ADDR,
},
]
const nakedMarginPoolBefore = new BigNumber(await controllerProxy.getNakedPoolBalance(usdc.address))
await usdc.approve(marginPool.address, requiredMargin.toString(), { from: accountOwner1 })
await controllerProxy.operate(mintArgs, { from: accountOwner1 })
const nakedMarginPoolAfter = new BigNumber(await controllerProxy.getNakedPoolBalance(usdc.address))
assert.equal(
nakedMarginPoolAfter.toString(),
nakedMarginPoolBefore.plus(requiredMargin).toString(),
'Naked margin colalteral tracking mismatch',
)
const latestVaultUpdateTimestamp = new BigNumber(
(await controllerProxy.getVaultWithDetails(accountOwner1, vaultCounter.toString()))[2],
)
assert.equal(
latestVaultUpdateTimestamp.toString(),
(await time.latest()).toString(),
'Vault latest update timestamp mismatch',
)
// mint short otoken
await shortOtoken.mintOtoken(liquidator, createTokenAmount(shortAmount))
})
it('should fully liquidate undercollateralized vault', async () => {
// advance time
await time.increase(1500)
// set round id and price
const roundId = new BigNumber(1)
const roundPrice = 130
const scaledRoundPrice = createTokenAmount(roundPrice)
const auctionStartingTime = (await time.latest()).toString()
await oracle.setChainlinkRoundData(weth.address, roundId, scaledRoundPrice, auctionStartingTime)
// advance time
await time.increase(1500)
const isLiquidatable = await controllerProxy.isLiquidatable(accountOwner1, vaultCounter.toString(), roundId)
assert.equal(isLiquidatable[0], true, 'Vault liquidation state mismatch')
assert.isTrue(new BigNumber(isLiquidatable[1]).isGreaterThan(0), 'Liquidation price is equal to zero')
const vaultBeforeLiquidation = (
await controllerProxy.getVaultWithDetails(accountOwner1, vaultCounter.toString())
)[0]
const liquidateArgs = [
{
actionType: ActionType.Liquidate,
owner: accountOwner1,
secondAddress: liquidator,
asset: ZERO_ADDR,
vaultId: vaultCounter.toString(),
amount: createTokenAmount(shortAmount),
index: '0',
data: web3.eth.abi.encodeParameter('uint256', roundId.toString()),
},
]
const liquidatorCollateralBalanceBefore = new BigNumber(await usdc.balanceOf(liquidator))
const nakedMarginPoolBefore = new BigNumber(await controllerProxy.getNakedPoolBalance(usdc.address))
await controllerProxy.operate(liquidateArgs, { from: liquidator })
const liquidatorCollateralBalanceAfter = new BigNumber(await usdc.balanceOf(liquidator))
const vaultAfterLiquidation = (
await controllerProxy.getVaultWithDetails(accountOwner1, vaultCounter.toString())
)[0]
const nakedMarginPoolAfter = new BigNumber(await controllerProxy.getNakedPoolBalance(usdc.address))
assert.equal(
nakedMarginPoolAfter.toString(),
nakedMarginPoolBefore
.minus(liquidatorCollateralBalanceAfter.minus(liquidatorCollateralBalanceBefore))
.toString(),
'Naked margin colalteral tracking mismatch',
)
assert.equal(vaultAfterLiquidation.shortAmounts[0].toString(), '0', 'Vault was not fully liquidated')
assert.isAtMost(
calcRelativeDiff(
vaultAfterLiquidation.collateralAmounts[0],
new BigNumber(vaultBeforeLiquidation.collateralAmounts[0]).minus(isLiquidatable[1]),
)
.dividedBy(10 ** usdcDecimals)
.toNumber(),
errorDelta,
'Vault collateral mismatch after liquidation',
)
assert.isAtMost(
calcRelativeDiff(liquidatorCollateralBalanceAfter, liquidatorCollateralBalanceBefore.plus(isLiquidatable[1]))
.dividedBy(10 ** usdcDecimals)
.toNumber(),
errorDelta,
'Liquidator collateral balance mismatch after liquidation',
)
})
it('should be able to withdraw remaining collateral', async () => {
const vaultAfterLiquidation = (await controllerProxy.getVaultWithDetails(accountOwner1, vaultCounter))[0]
const withdrawArgs = [
{
actionType: ActionType.WithdrawCollateral,
owner: accountOwner1,
secondAddress: accountOwner1,
asset: usdc.address,
vaultId: vaultCounter.toString(),
amount: vaultAfterLiquidation.collateralAmounts[0],
index: '0',
data: ZERO_ADDR,
},
]
const userCollateralBefore = new BigNumber(await usdc.balanceOf(accountOwner1))
const nakedMarginPoolBefore = new BigNumber(await controllerProxy.getNakedPoolBalance(usdc.address))
await controllerProxy.operate(withdrawArgs, { from: accountOwner1 })
const nakedMarginPoolAfter = new BigNumber(await controllerProxy.getNakedPoolBalance(usdc.address))
const userCollateralAfter = new BigNumber(await usdc.balanceOf(accountOwner1))
assert.equal(
nakedMarginPoolAfter.toString(),
nakedMarginPoolBefore.minus(new BigNumber(vaultAfterLiquidation.collateralAmounts[0])).toString(),
'Naked margin colalteral tracking mismatch',
)
assert.equal(
userCollateralAfter.toString(),
userCollateralBefore.plus(vaultAfterLiquidation.collateralAmounts[0]).toString(),
'User collateral after withdraw remaining collateral mismatch',
)
})
})
describe('Naked margin position: full liquidation call position', () => {
const shortAmount = 1
const shortStrike = 1500
const isPut = false
let shortOtoken: MockOtokenInstance
let requiredMargin: BigNumber
let vaultCounter: BigNumber
before('Deploy new short otoken, and open naked position', async () => {
const underlyingPrice = 1000
const scaledUnderlyingPrice = scaleBigNum(underlyingPrice, 8)
const optionExpiry = new BigNumber(await time.latest()).plus(timeToExpiry[0])
shortOtoken = await MockOtoken.new()
await shortOtoken.init(
addressBook.address,
weth.address,
usdc.address,
weth.address,
scaleNum(shortStrike),
optionExpiry,
isPut,
)
// whitelist otoken
await whitelist.whitelistOtoken(shortOtoken.address)
// set underlying price in oracle
await oracle.setRealTimePrice(weth.address, scaledUnderlyingPrice)
// open position
vaultCounter = new BigNumber(await controllerProxy.getAccountVaultCounter(accountOwner1)).plus(1)
const vaultType = web3.eth.abi.encodeParameter('uint256', 1)
requiredMargin = new BigNumber(
await calculator.getNakedMarginRequired(
weth.address,
usdc.address,
weth.address,
createTokenAmount(shortAmount),
createTokenAmount(shortStrike),
scaledUnderlyingPrice,
optionExpiry,
wethDecimals,
isPut,
),
)
const mintArgs = [
{
actionType: ActionType.OpenVault,
owner: accountOwner1,
secondAddress: accountOwner1,
asset: ZERO_ADDR,
vaultId: vaultCounter.toString(),
amount: '0',
index: '0',
data: vaultType,
},
{
actionType: ActionType.MintShortOption,
owner: accountOwner1,
secondAddress: accountOwner1,
asset: shortOtoken.address,
vaultId: vaultCounter.toString(),
amount: createTokenAmount(shortAmount),
index: '0',
data: ZERO_ADDR,
},
{
actionType: ActionType.DepositCollateral,
owner: accountOwner1,
secondAddress: accountOwner1,
asset: weth.address,
vaultId: vaultCounter.toString(),
amount: requiredMargin.toString(),
index: '0',
data: ZERO_ADDR,
},
]
const nakedMarginPoolBefore = new BigNumber(await controllerProxy.getNakedPoolBalance(weth.address))
await weth.approve(marginPool.address, requiredMargin.toString(), { from: accountOwner1 })
await controllerProxy.operate(mintArgs, { from: accountOwner1 })
const nakedMarginPoolAfter = new BigNumber(await controllerProxy.getNakedPoolBalance(weth.address))
assert.equal(
nakedMarginPoolAfter.toString(),
nakedMarginPoolBefore.plus(requiredMargin).toString(),
'Naked margin colalteral tracking mismatch',
)
const latestVaultUpdateTimestamp = new BigNumber(
(await controllerProxy.getVaultWithDetails(accountOwner1, vaultCounter.toString()))[2],
)
assert.equal(
latestVaultUpdateTimestamp.toString(),
(await time.latest()).toString(),
'Vault latest update timestamp mismatch',
)
// mint short otoken
await shortOtoken.mintOtoken(liquidator, createTokenAmount(shortAmount))
})
it('should fully liquidate undercollateralized vault', async () => {
// advance time
await time.increase(600)
// set round id and price
const roundId = new BigNumber(1)
const roundPrice = 1150
const scaledRoundPrice = createTokenAmount(roundPrice)
const auctionStartingTime = (await time.latest()).toString()
await oracle.setChainlinkRoundData(weth.address, roundId, scaledRoundPrice, auctionStartingTime)
// advance time
await time.increase(600)
const isLiquidatable = await controllerProxy.isLiquidatable(accountOwner1, vaultCounter.toString(), roundId)
assert.equal(isLiquidatable[0], true, 'Vault liquidation state mismatch')
assert.isTrue(new BigNumber(isLiquidatable[1]).isGreaterThan(0), 'Liquidation price is equal to zero')
const vaultBeforeLiquidation = (
await controllerProxy.getVaultWithDetails(accountOwner1, vaultCounter.toString())
)[0]
const liquidateArgs = [
{
actionType: ActionType.Liquidate,
owner: accountOwner1,
secondAddress: liquidator,
asset: ZERO_ADDR,
vaultId: vaultCounter.toString(),
amount: createTokenAmount(shortAmount),
index: '0',
data: web3.eth.abi.encodeParameter('uint256', roundId.toString()),
},
]
const liquidatorCollateralBalanceBefore = new BigNumber(await weth.balanceOf(liquidator))
const nakedMarginPoolBefore = new BigNumber(await controllerProxy.getNakedPoolBalance(weth.address))
await controllerProxy.operate(liquidateArgs, { from: liquidator })
const liquidatorCollateralBalanceAfter = new BigNumber(await weth.balanceOf(liquidator))
const vaultAfterLiquidation = (
await controllerProxy.getVaultWithDetails(accountOwner1, vaultCounter.toString())
)[0]
const nakedMarginPoolAfter = new BigNumber(await controllerProxy.getNakedPoolBalance(weth.address))
assert.equal(
nakedMarginPoolAfter.toString(),
nakedMarginPoolBefore
.minus(liquidatorCollateralBalanceAfter.minus(liquidatorCollateralBalanceBefore))
.toString(),
'Naked margin colalteral tracking mismatch',
)
assert.equal(vaultAfterLiquidation.shortAmounts[0].toString(), '0', 'Vault was not fully liquidated')
assert.isAtMost(
calcRelativeDiff(
vaultAfterLiquidation.collateralAmounts[0],
new BigNumber(vaultBeforeLiquidation.collateralAmounts[0]).minus(isLiquidatable[1]),
)
.dividedBy(10 ** wethDecimals)
.toNumber(),
errorDelta,
'Vault collateral mismatch after liquidation',
)
assert.isAtMost(
calcRelativeDiff(liquidatorCollateralBalanceAfter, liquidatorCollateralBalanceBefore.plus(isLiquidatable[1]))
.dividedBy(10 ** wethDecimals)
.toNumber(),
errorDelta,
'Liquidator collateral balance mismatch after liquidation',
)
})
it('should be able to withdraw remaining collateral', async () => {
const vaultAfterLiquidation = (await controllerProxy.getVaultWithDetails(accountOwner1, vaultCounter))[0]
const withdrawArgs = [
{
actionType: ActionType.WithdrawCollateral,
owner: accountOwner1,
secondAddress: accountOwner1,
asset: weth.address,
vaultId: vaultCounter.toString(),
amount: vaultAfterLiquidation.collateralAmounts[0],
index: '0',
data: ZERO_ADDR,
},
]
const userCollateralBefore = new BigNumber(await weth.balanceOf(accountOwner1))
const nakedMarginPoolBefore = new BigNumber(await controllerProxy.getNakedPoolBalance(weth.address))
await controllerProxy.operate(withdrawArgs, { from: accountOwner1 })
const userCollateralAfter = new BigNumber(await weth.balanceOf(accountOwner1))
const nakedMarginPoolAfter = new BigNumber(await controllerProxy.getNakedPoolBalance(weth.address))
assert.equal(
nakedMarginPoolAfter.toString(),
nakedMarginPoolBefore.minus(new BigNumber(vaultAfterLiquidation.collateralAmounts[0])).toString(),
'Naked margin colalteral tracking mismatch',
)
assert.equal(
userCollateralAfter.toString(),
userCollateralBefore.plus(vaultAfterLiquidation.collateralAmounts[0]).toString(),
'User collateral after withdraw remaining collateral mismatch',
)
})
})
describe('Naked margin position: partial liquidation put position', () => {
const shortAmount = 2
const shortStrike = 100
const isPut = true
let shortOtoken: MockOtokenInstance
let requiredMargin: BigNumber
let vaultCounter: BigNumber
let optionExpiry: BigNumber
before('Deploy new short otoken, and open naked position', async () => {
const underlyingPrice = 150
const scaledUnderlyingPrice = scaleBigNum(underlyingPrice, 8)
optionExpiry = new BigNumber(await time.latest()).plus(timeToExpiry[0])
shortOtoken = await MockOtoken.new()
await shortOtoken.init(
addressBook.address,
weth.address,
usdc.address,
usdc.address,
scaleNum(shortStrike),
optionExpiry,
isPut,
)
// whitelist otoken
await whitelist.whitelistOtoken(shortOtoken.address)
// set underlying price in oracle
await oracle.setRealTimePrice(weth.address, scaledUnderlyingPrice)
// open position
vaultCounter = new BigNumber(await controllerProxy.getAccountVaultCounter(accountOwner1)).plus(1)
const vaultType = web3.eth.abi.encodeParameter('uint256', 1)
requiredMargin = new BigNumber(
await calculator.getNakedMarginRequired(
weth.address,
usdc.address,
usdc.address,
createTokenAmount(shortAmount),
createTokenAmount(shortStrike),
scaledUnderlyingPrice,
optionExpiry,
usdcDecimals,
isPut,
),
)
const mintArgs = [
{
actionType: ActionType.OpenVault,
owner: accountOwner1,
secondAddress: accountOwner1,
asset: ZERO_ADDR,
vaultId: vaultCounter.toString(),
amount: '0',
index: '0',
data: vaultType,
},
{
actionType: ActionType.MintShortOption,
owner: accountOwner1,
secondAddress: accountOwner1,
asset: shortOtoken.address,
vaultId: vaultCounter.toString(),
amount: createTokenAmount(shortAmount),
index: '0',
data: ZERO_ADDR,
},
{
actionType: ActionType.DepositCollateral,
owner: accountOwner1,
secondAddress: accountOwner1,
asset: usdc.address,
vaultId: vaultCounter.toString(),
amount: requiredMargin.toString(),
index: '0',
data: ZERO_ADDR,
},
]
await usdc.approve(marginPool.address, requiredMargin.toString(), { from: accountOwner1 })
await controllerProxy.operate(mintArgs, { from: accountOwner1 })
const latestVaultUpdateTimestamp = new BigNumber(
(await controllerProxy.getVaultWithDetails(accountOwner1, vaultCounter.toString()))[2],
)
assert.equal(
latestVaultUpdateTimestamp.toString(),
(await time.latest()).toString(),
'Vault latest update timestamp mismatch',
)
// mint short otoken
await shortOtoken.mintOtoken(liquidator, createTokenAmount(shortAmount))
})
it('should partially liquidate undercollateralized vault', async () => {
// advance time
await time.increase(600)
const shortToLiquidate = 1
// set round id and price
const roundId = new BigNumber(1)
const roundPrice = 130
const scaledRoundPrice = createTokenAmount(roundPrice)
const auctionStartingTime = (await time.latest()).toString()
await oracle.setChainlinkRoundData(weth.address, roundId, scaledRoundPrice, auctionStartingTime)
// advance time
await time.increase(600)
const isLiquidatable = await controllerProxy.isLiquidatable(accountOwner1, vaultCounter.toString(), roundId)
assert.equal(isLiquidatable[0], true, 'Vault liquidation state mismatch')
assert.isTrue(new BigNumber(isLiquidatable[1]).isGreaterThan(0), 'Liquidation price is equal to zero')
const vaultBeforeLiquidation = (
await controllerProxy.getVaultWithDetails(accountOwner1, vaultCounter.toString())
)[0]
const liquidateArgs = [
{
actionType: ActionType.Liquidate,
owner: accountOwner1,
secondAddress: liquidator,
asset: ZERO_ADDR,
vaultId: vaultCounter.toString(),
amount: createTokenAmount(shortToLiquidate),
index: '0',
data: web3.eth.abi.encodeParameter('uint256', roundId.toString()),
},
]
const liquidatorCollateralBalanceBefore = new BigNumber(await usdc.balanceOf(liquidator))
await controllerProxy.operate(liquidateArgs, { from: liquidator })
const liquidatorCollateralBalanceAfter = new BigNumber(await usdc.balanceOf(liquidator))
const vaultAfterLiquidation = (
await controllerProxy.getVaultWithDetails(accountOwner1, vaultCounter.toString())
)[0]
assert.equal(
vaultAfterLiquidation.shortAmounts[0].toString(),
createTokenAmount(shortToLiquidate),
'Vault was not partially liquidated',
)
assert.isAtMost(
calcRelativeDiff(
vaultAfterLiquidation.collateralAmounts[0],
new BigNumber(vaultBeforeLiquidation.collateralAmounts[0]).minus(isLiquidatable[1]),
)
.dividedBy(10 ** usdcDecimals)
.toNumber(),
errorDelta,
'Vault collateral mismatch after liquidation',
)
assert.isAtMost(
calcRelativeDiff(liquidatorCollateralBalanceAfter, liquidatorCollateralBalanceBefore.plus(isLiquidatable[1]))
.dividedBy(10 ** usdcDecimals)
.toNumber(),
errorDelta,
'Liquidator collateral balance mismatch after liquidation',
)
})
it('should revert liquidating the rest of debt when vault is back overcollateralized', async () => {
const shortToLiquidate = 1
// set round id and price
const roundId = new BigNumber(1)
const roundPrice = 130
const scaledRoundPrice = createTokenAmount(roundPrice)
const auctionStartingTime = (await time.latest()).toString()
await oracle.setChainlinkRoundData(weth.address, roundId, scaledRoundPrice, auctionStartingTime)
// advance time
await time.increase(600)
const isLiquidatable = await controllerProxy.isLiquidatable(accountOwner1, vaultCounter.toString(), roundId)
assert.equal(isLiquidatable[0], false, 'Vault liquidation state mismatch')
// const vaultCollateral = requiredMargin.dividedBy(10 ** usdcDecimals).toString()
const liquidateArgs = [
{
actionType: ActionType.Liquidate,
owner: accountOwner1,
secondAddress: liquidator,
asset: ZERO_ADDR,
vaultId: vaultCounter.toString(),
amount: createTokenAmount(shortToLiquidate),
index: '0',
data: web3.eth.abi.encodeParameter('uint256', roundId.toString()),
},
]
await expectRevert(controllerProxy.operate(liquidateArgs, { from: liquidator }), 'C33')
})
it('should be able to remove excess collateral after partially liquidating', async () => {
const vaultAfterLiquidation = (await controllerProxy.getVaultWithDetails(accountOwner1, vaultCounter))[0]
const requiredVaultMargin = await calculator.getNakedMarginRequired(
weth.address,
usdc.address,
usdc.address,
createTokenAmount(1),
createTokenAmount(shortStrike),
createTokenAmount(130),
optionExpiry,
usdcDecimals,
isPut,
)
const amountAbleToWithdraw = new BigNumber(vaultAfterLiquidation.collateralAmounts[0]).minus(requiredVaultMargin)
const withdrawArgs = [
{
actionType: ActionType.WithdrawCollateral,
owner: accountOwner1,
secondAddress: accountOwner1,
asset: usdc.address,
vaultId: vaultCounter.toString(),
amount: amountAbleToWithdraw.toString(),
index: '0',
data: ZERO_ADDR,
},
]
const userCollateralBefore = new BigNumber(await usdc.balanceOf(accountOwner1))
await controllerProxy.operate(withdrawArgs, { from: accountOwner1 })
const userCollateralAfter = new BigNumber(await usdc.balanceOf(accountOwner1))
assert.equal(
userCollateralAfter.toString(),
userCollateralBefore.plus(amountAbleToWithdraw).toString(),
'User collateral after withdraw available remaining collateral mismatch',
)
})
})
describe('Collateral cap', async () => {
it('only owner should be able to set naked cap amount', async () => {
const wethCap = scaleNum(50000, wethDecimals)
await controllerProxy.setNakedCap(weth.address, wethCap, { from: owner })
const capAmount = new BigNumber(await controllerProxy.getNakedCap(weth.address))
assert.equal(capAmount.toString(), wethCap.toString(), 'Weth naked cap amount mismatch')
})
it('should revert setting collateral cap from address other than owner', async () => {
const wethCap = scaleNum(50000, wethDecimals)
await expectRevert(
controllerProxy.setNakedCap(weth.address, wethCap, { from: random }),
'Ownable: caller is not the owner',
)
})
it('should revert setting collateral cap amount equal to zero', async () => {
const wethCap = scaleNum(0, wethDecimals)
await expectRevert(controllerProxy.setNakedCap(weth.address, wethCap, { from: owner }), 'C36')
})
it('should revert depositing collateral in vault that that hit naked cap', async () => {
const vaultType = web3.eth.abi.encodeParameter('uint256', 1)
const vaultCounter = new BigNumber(await controllerProxy.getAccountVaultCounter(accountOwner1)).plus(1)
const capAmount = new BigNumber(await controllerProxy.getNakedCap(usdc.address))
const mintArgs = [
{
actionType: ActionType.OpenVault,
owner: accountOwner1,
secondAddress: accountOwner1,
asset: ZERO_ADDR,
vaultId: vaultCounter.toString(),
amount: '0',
index: '0',
data: vaultType,
},
{
actionType: ActionType.DepositCollateral,
owner: accountOwner1,
secondAddress: accountOwner1,
asset: usdc.address,
vaultId: vaultCounter.toString(),
amount: capAmount.toString(),
index: '0',
data: ZERO_ADDR,
},
]
await usdc.approve(marginPool.address, capAmount.toString(), { from: accountOwner1 })
await expectRevert(controllerProxy.operate(mintArgs, { from: accountOwner1 }), 'C37')
})
})
}) | the_stack |
import * as Immutable from 'immutable';
import { TypedRecord } from 'typed-immutable-record';
import {
addEntityToCollection,
EntityCollection,
entityCollectionFromJSON,
EntityCollectionRecord,
} from '../entity-collections';
import { assertTrue, exhaustiveCheck, makeRecordFactory } from '../util';
import {
GameDataActionClasses,
GameDataAddSheetAction,
GameDataFetchAction,
GameDataFetchFailAction,
GameDataFetchSuccessAction,
GameDataRemoveSheetAction,
IGameDataAddPayload,
} from './game-data.actions';
import {
ITemplateArmor,
ITemplateBaseItem,
ITemplateClass,
ITemplateEnemy,
ITemplateFixedEncounter,
ITemplateId,
ITemplateMagic,
ITemplateRandomEncounter,
ITemplateWeapon,
} from './game-data.model';
// Weapons
//
/** @internal */
export interface EntityWeaponsRecord
extends TypedRecord<EntityWeaponsRecord>,
EntityCollection<ITemplateWeapon> {}
/** @internal */
const entityWeaponsCollectionFactory = makeRecordFactory<
EntityCollection<ITemplateWeapon>,
EntityWeaponsRecord
>({
byId: Immutable.Map<string, ITemplateWeapon>(),
allIds: Immutable.List<string>(),
});
// Items
//
/** @internal */
export interface EntityItemsRecord
extends TypedRecord<EntityItemsRecord>,
EntityCollection<ITemplateBaseItem> {}
/** @internal */
const entityItemsCollectionFactory = makeRecordFactory<
EntityCollection<ITemplateBaseItem>,
EntityItemsRecord
>({
byId: Immutable.Map<string, ITemplateBaseItem>(),
allIds: Immutable.List<string>(),
});
// Armors
//
/** @internal */
export interface EntityArmorsRecord
extends TypedRecord<EntityArmorsRecord>,
EntityCollection<ITemplateArmor> {}
/** @internal */
const entityArmorsCollectionFactory = makeRecordFactory<
EntityCollection<ITemplateArmor>,
EntityArmorsRecord
>({
byId: Immutable.Map<string, ITemplateArmor>(),
allIds: Immutable.List<string>(),
});
// Enemies
//
/** @internal */
export interface EntityEnemiesRecord
extends TypedRecord<EntityEnemiesRecord>,
EntityCollection<ITemplateEnemy> {}
/** @internal */
const entityEnemiesCollectionFactory = makeRecordFactory<
EntityCollection<ITemplateEnemy>,
EntityEnemiesRecord
>({
byId: Immutable.Map<string, ITemplateEnemy>(),
allIds: Immutable.List<string>(),
});
// Magics
//
/** @internal */
export interface EntityMagicsRecord
extends TypedRecord<EntityMagicsRecord>,
EntityCollection<ITemplateMagic> {}
/** @internal */
const entityMagicsCollectionFactory = makeRecordFactory<
EntityCollection<ITemplateMagic>,
EntityMagicsRecord
>({
byId: Immutable.Map<string, ITemplateMagic>(),
allIds: Immutable.List<string>(),
});
// Classes
//
/** @internal */
export interface EntityClassesRecord
extends TypedRecord<EntityClassesRecord>,
EntityCollection<ITemplateClass> {}
/** @internal */
const entityClassesCollectionFactory = makeRecordFactory<
EntityCollection<ITemplateClass>,
EntityClassesRecord
>({
byId: Immutable.Map<string, ITemplateClass>(),
allIds: Immutable.List<string>(),
});
// Fixed Encounters
//
/** @internal */
export interface EntityFixedEncountersRecord
extends TypedRecord<EntityFixedEncountersRecord>,
EntityCollection<ITemplateFixedEncounter> {}
/** @internal */
const entityFixedEncountersCollectionFactory = makeRecordFactory<
EntityCollection<ITemplateFixedEncounter>,
EntityFixedEncountersRecord
>({
byId: Immutable.Map<string, ITemplateFixedEncounter>(),
allIds: Immutable.List<string>(),
});
// Random Encounters
//
/** @internal */
export interface EntityRandomEncountersRecord
extends TypedRecord<EntityRandomEncountersRecord>,
EntityCollection<ITemplateRandomEncounter> {}
/** @internal */
const entityRandomEncountersCollectionFactory = makeRecordFactory<
EntityCollection<ITemplateRandomEncounter>,
EntityRandomEncountersRecord
>({
byId: Immutable.Map<string, ITemplateRandomEncounter>(),
allIds: Immutable.List<string>(),
});
// Game Data state
/** @internal */
export interface GameDataStateRecord
extends TypedRecord<GameDataStateRecord>,
GameDataState {}
/** @internal */
export const gameDataFactory = makeRecordFactory<GameDataState, GameDataStateRecord>({
loaded: false,
weapons: entityWeaponsCollectionFactory(),
items: entityItemsCollectionFactory(),
armor: entityArmorsCollectionFactory(),
enemies: entityEnemiesCollectionFactory(),
magic: entityMagicsCollectionFactory(),
classes: entityClassesCollectionFactory(),
fixedEncounters: entityFixedEncountersCollectionFactory(),
randomEncounters: entityRandomEncountersCollectionFactory(),
});
/** Collection of game data template objects */
export interface GameDataState {
loaded: boolean;
weapons: EntityCollection<ITemplateWeapon>;
items: EntityCollection<ITemplateBaseItem>;
armor: EntityCollection<ITemplateArmor>;
enemies: EntityCollection<ITemplateEnemy>;
magic: EntityCollection<ITemplateMagic>;
classes: EntityCollection<ITemplateClass>;
fixedEncounters: EntityCollection<ITemplateFixedEncounter>;
randomEncounters: EntityCollection<ITemplateRandomEncounter>;
}
/**
* Convert input Plain JSON object into an Immutable.js representation with the correct records.
* @param object The input values.
*/
export function gameDataFromJSON(object: GameDataState): GameDataState {
const result = gameDataFactory({
loaded: object.loaded,
weapons: entityWeaponsCollectionFactory(entityCollectionFromJSON(object.weapons)),
items: entityItemsCollectionFactory(entityCollectionFromJSON(object.items)),
armor: entityArmorsCollectionFactory(entityCollectionFromJSON(object.armor)),
enemies: entityEnemiesCollectionFactory(entityCollectionFromJSON(object.enemies)),
magic: entityMagicsCollectionFactory(entityCollectionFromJSON(object.magic)),
classes: entityClassesCollectionFactory(entityCollectionFromJSON(object.classes)),
fixedEncounters: entityFixedEncountersCollectionFactory(
entityCollectionFromJSON(object.fixedEncounters)
),
randomEncounters: entityRandomEncountersCollectionFactory(
entityCollectionFromJSON(object.randomEncounters)
),
});
return result;
}
/**
* Manage shared state for game-design data. Items for sale, monsters that exist in a fixed combat
* encounter, base attributes for each class, etc.
*/
export function gameDataReducer(
state: GameDataState = gameDataFactory(),
action: GameDataActionClasses
): GameDataState {
const stateRecord = state as GameDataStateRecord;
switch (action.type) {
case GameDataFetchAction.typeId:
case GameDataFetchFailAction.typeId: {
return state;
}
case GameDataFetchSuccessAction.typeId: {
return stateRecord.merge({
loaded: true,
});
}
case GameDataAddSheetAction.typeId: {
const addSheet: IGameDataAddPayload = action.payload;
assertTrue(
!!state[addSheet.sheet],
'unknown collection cannot be added with sheet name: ' + addSheet.sheet
);
return stateRecord.updateIn(
[addSheet.sheet],
(record: EntityCollectionRecord) => {
addSheet.data.forEach((data: ITemplateId) => {
record = addEntityToCollection(record, data, data.id);
});
return record;
}
);
}
case GameDataRemoveSheetAction.typeId: {
const removeId: string = action.payload;
assertTrue(
stateRecord.has(removeId),
'cannot remove sheet that does not exist: ' + removeId
);
return stateRecord.updateIn([removeId], (e: EntityCollectionRecord) => {
return e.set('byId', e.byId.clear()).set('allIds', e.allIds.clear());
});
}
default:
exhaustiveCheck(action);
return state;
}
}
/** @internal {@see sliceGameDataState} */
export const sliceGameDataType = (type: string) => {
return (state: GameDataState) => state[type].byId;
};
/** @internal {@see sliceGameDataState} */
export const sliceGameDataTypeIds = (type: string) => {
return (state: GameDataState) => state[type].allIds;
};
/** @internal {@see sliceGameDataState} */
export const sliceGameDataLoaded = (state: GameDataState) => state.loaded;
/** @internal {@see sliceGameDataState} */
export const sliceWeaponIds = (state: GameDataState) => state.weapons.allIds;
/** @internal {@see sliceGameDataState} */
export const sliceWeapons = (state: GameDataState) => state.weapons.byId;
/** @internal {@see sliceGameDataState} */
export const sliceArmorIds = (state: GameDataState) => state.armor.allIds;
/** @internal {@see sliceGameDataState} */
export const sliceArmors = (state: GameDataState) => state.armor.byId;
/** @internal {@see sliceGameDataState} */
export const sliceItemIds = (state: GameDataState) => state.items.allIds;
/** @internal {@see sliceGameDataState} */
export const sliceItems = (state: GameDataState) => state.items.byId;
/** @internal {@see sliceGameDataState} */
export const sliceEnemiesIds = (state: GameDataState) => state.enemies.allIds;
/** @internal {@see sliceGameDataState} */
export const sliceEnemies = (state: GameDataState) => state.enemies.byId;
/** @internal {@see sliceGameDataState} */
export const sliceMagicIds = (state: GameDataState) => state.magic.allIds;
/** @internal {@see sliceGameDataState} */
export const sliceMagics = (state: GameDataState) => state.magic.byId;
/** @internal {@see sliceGameDataState} */
export const sliceClassesIds = (state: GameDataState) => state.classes.allIds;
/** @internal {@see sliceGameDataState} */
export const sliceClasses = (state: GameDataState) => state.classes.byId;
/** @internal {@see sliceGameDataState} */
export const sliceRandomEncounterIds = (state: GameDataState) =>
state.randomEncounters.allIds;
/** @internal {@see sliceGameDataState} */
export const sliceRandomEncounters = (state: GameDataState) =>
state.randomEncounters.byId;
/** @internal {@see sliceGameDataState} */
export const sliceFixedEncounterIds = (state: GameDataState) =>
state.fixedEncounters.allIds;
/** @internal {@see sliceGameDataState} */
export const sliceFixedEncounters = (state: GameDataState) =>
state.fixedEncounters.byId; | the_stack |
import { HttpRequest } from "../web/httprequest";
import { InstanceFactory } from "../main/instancefactory";
import { SecurityFilter } from "../web/filter/securityfilter";
import { NoomiError } from "./errorfactory";
import { NCache } from "./ncache";
import { Session,SessionFactory } from "../web/sessionfactory";
import { DBManager } from "../database/dbmanager";
import { IConnectionManager } from "../database/connectionmanager";
import { App } from "./application";
import { FilterFactory } from "../web/filterfactory";
/**
* 安全工厂
* @remarks
* 用于管理安全对象
*/
class SecurityFactory{
/**
* @exclude
* 存储在session中的名字
*/
static sessionName:string = 'NOOMI_SECURITY_OBJECT';
/**
* 数据表对象
*/
static dbOptions:any;
/**
* 认证类型 0 session 1 token
*/
static authType:number = 0;
/**
* 数据存储类型,0内存 1redis
*/
static saveType:number = 0;
/**
* redis名,必须在redis.json中已定义,saveType=1时有效
*/
static redis:string='default';
/**
* 最大size,saveType=0时有效
*/
static maxSize:number;
/**
* 缓存对象
*/
static cache:NCache;
/**
* 安全相关页面map
*/
static securityPages:Map<string,string> = new Map();
//资源列表
// static resources:Map<number,ResourceObj> = new Map();
/**
* 登录用户map
*/
static users:Map<number,Array<number>> = new Map();
/**
* 组map
*/
static groups:Map<number,Array<number>> = new Map();
/**
* @exclude
* 缓存时用户key前缀
*/
static USERKEY:string = 'USER';
/**
* @exclude
* 缓存时组key前缀
*/
static GROUPKEY:string = 'GROUP';
/**
* @exclude
* 缓存时资源key前缀
*/
static RESKEY:string = 'RESOURCE';
/**
* @exclude
* 用户id对应session键
*/
static USERID:string='NSECURITY_USERID';
/**
* 认证前url在session中的名字
*/
static PRELOGIN:string='NSECURITY_PRELOGIN';
/**
* users在cache的key
*/
static redisUserKey:string = "NOOMI_SECURITY_USERS";
/**
* groups在cache的key
*/
static redisGroupKey:string = "NOOMI_SECURITY_GROUPS";
/**
* resource在cache的key
*/
static redisResourceKey:string = "NOOMI_SECURITY_RESOURCES";
/**
* 初始化配置
* @config 配置项
*/
static async init(config){
//鉴权失败页面
if(config.hasOwnProperty('auth_fail_url')){
this.securityPages.set('auth_fail_url',config['auth_fail_url']);
}
//登录页面
if(config.hasOwnProperty('login_url')){
this.securityPages.set('login_url',config['login_url']);
}
if(config.hasOwnProperty('auth_type')){
this.authType = config['auth_type'];
}
if(config.hasOwnProperty('save_type')){
this.saveType = config['save_type'];
}
if(config.hasOwnProperty('redis')){
this.redis = config['redis'];
}
if(config.hasOwnProperty('max_size')){
this.maxSize = config['max_size'];
}
//数据库解析
if(config.hasOwnProperty('dboption')){
this.dbOptions = config.dboption;
}
//初始化security filter
// InstanceFactory.addInstance({
// name:'NoomiSecurityFilter', //filter实例名
// instance:new SecurityFilter(),
// class:SecurityFilter
// });
InstanceFactory.addInstance({
name:'NoomiSecurityFilter', //filter实例名
instance:new SecurityFilter(),
class:SecurityFilter
});
FilterFactory.registFilter({
className:'NoomiSecurityFilter',
pattern:config['expressions'],
order:1
});
//创建cache
this.cache = new NCache({
name:'NSECURITY',
saveType:this.saveType,
maxSize:this.maxSize,
redis:this.redis
});
//初始化表名和字段名
let tResource:string;
let tGroupAuth:string;
let tResourceAuth:string;
let authId:string;
let groupId:string;
let resourceId:string;
let resourceUrl:string;
if(this.dbOptions){
if(this.dbOptions.tables){
tResource = this.dbOptions.tables['resource'];
tGroupAuth = this.dbOptions.tables['groupAuthority'] ;
tResourceAuth = this.dbOptions.tables['resourceAuthority'];
}
if(this.dbOptions.columns){
authId = this.dbOptions.columns['authorityId'];
groupId = this.dbOptions.columns['groupId'];
resourceId = this.dbOptions.columns['resourceId'];
resourceUrl = this.dbOptions.columns['resourceUrl'];
}
}
let ids = {
tGroupAuth:tGroupAuth || "t_group_authority",
tResource:tResource || "t_resource",
tResourceAuth:tResourceAuth || "t_resource_authority",
authId:authId || "authority_id",
groupId:groupId || "group_id",
resourceId:resourceId || "resource_id",
resourceUrl:resourceUrl || "url"
}
let results:Array<any>;
let product:string = this.dbOptions.product || DBManager.product;
let connCfg = this.dbOptions?this.dbOptions.conn_cfg:null;
//从表中加载数据
switch(product){
case "mysql":
results = await handleMysql(connCfg,ids);
break;
case "mssql":
results = await handleMssql(connCfg,ids);
break;
case "oracle":
results = await handleOracle(connCfg,ids);
break;
}
//组权限
let gaMap:Map<number,Array<number>> = new Map(); //{groupdId1:[authId1,authId2,..],...}
for(let r of results[0]){
let aids:Array<number>;
if(gaMap.has(r.gid)){
aids = gaMap.get(r.gid);
}else{
aids = [];
}
aids.push(r.aid);
gaMap.set(r.gid,aids);
}
//更新组权限
for(let p of gaMap){
await this.updGroupAuths(p[0],p[1]);
}
//资源
for(let r of results[1]){
let a = [];
for(let r1 of results[2]){
if(r1.rid === r.rid){
let aid = r1.aid;
if(a.includes(aid)){
continue;
}
a.push(aid);
}
}
await this.updResourceAuths(r.url,a);
}
/**
* 处理mysql
* @param cfg
*/
async function handleMysql(cfg:any,ids:any):Promise<Array<any>>{
let conn;
let arr:Array<any> = [];
let cm:IConnectionManager = null;
try{
if(!cfg){ //cfg为空,直接使用dbmanager的connection manager
cm = DBManager.getConnectionManager();
if(!cm){
throw new NoomiError("2800");
}
conn = await cm.getConnection();
}else{
conn = require('mysql').createConnection(cfg);
await conn.connect();
}
//组权限
let results:Array<any> = await new Promise((resolve,reject)=>{
conn.query("select " + ids.groupId + "," + ids.authId + " from " + ids.tGroupAuth,
(error,results,fields)=>{
if(error){
reject(error);
}
resolve(results);
});
});
let a:Array<any> = [];
for(let r of results){
a.push({
gid:r[ids.groupId],
aid:r[ids.authId]
});
}
arr.push(a);
//资源
results = await new Promise((resolve,reject)=>{
conn.query("select " + ids.resourceId + "," + ids.resourceUrl + " from " + ids.tResource,
(error,results,fields)=>{
if(error){
reject(error);
}
resolve(results);
});
});
let a1:Array<any> = [];
for(let r of results){
a1.push({
rid:r[ids.resourceId],
url:r[ids.resourceUrl]
});
}
arr.push(a1);
//资源权限
results = await new Promise((resolve,reject)=>{
conn.query("select " + ids.resourceId + "," + ids.authId + " from " + ids.tResourceAuth,
(error,results,fields)=>{
if(error){
reject(error);
}
resolve(results);
});
});
let a2:Array<any> = [];
for(let r of results){
a2.push({
rid:r[ids.resourceId],
aid:r[ids.authId]
});
}
arr.push(a2);
}catch(e){
throw e;
}finally{
//关闭连接
if (conn) {
if(cm !== null){
await cm.release(conn);
}else{
try {
conn.end();
} catch (err) {
throw err;
}
}
}
}
return arr;
}
/**
* 处理mssql
* @param cfg
* @param ids
*/
async function handleMssql(cfg:any,ids:any):Promise<Array<any>>{
let conn;
let arr:Array<any> = [];
let cm:IConnectionManager = null;
if(!cfg){
cm = DBManager.getConnectionManager();
if(!cm){
throw new NoomiError("2800");
}
conn = await cm.getConnection();
}else{
conn = await require('mssql').getConnection(cfg);
}
try{
//组权限
let result = await conn.query("select " + ids.groupId + "," + ids.authId + " from " + ids.tgroupauth);
let a:Array<any> = [];
for(let r of result.recordset){
a.push({
gid:r[ids.groupId],
aid:r[ids.authId]
});
}
arr.push(a);
//资源
result = await conn.query("select " + ids.resourceId + "," + ids.resourceUrl + " from " + ids.tresource);
let a1:Array<any> = [];
for(let r of result.recordset){
a1.push({
rid:r[ids.resourceId],
url:r[ids.resourceUrl]
});
}
arr.push(a1);
//资源权限
result = await conn.query("select " + ids.resourceId + "," + ids.authId + " from " + ids.tresourceauth);
let a2:Array<any> = [];
for(let r of result.recordset){
a2.push({
rid:r[ids.resourceId],
aid:r[ids.authId]
});
}
arr.push(a2);
}catch(e){
throw e;
}finally{
//关闭连接
if (conn) {
if(cm !== null){
await cm.release(conn);
}else{
try {
conn.close();
} catch (err) {
throw err;
}
}
}
}
return arr;
}
/**
* 处理oracle
* @param cfg
* @param ids
*/
async function handleOracle(cfg:any,ids:any):Promise<Array<any>>{
let conn;
let arr:Array<any> = [];
let cm:IConnectionManager = null;
if(!cfg){
cm = DBManager.getConnectionManager();
if(!cm){
throw new NoomiError("2800");
}
conn = await cm.getConnection();
}else{
conn = await require('oracledb').getConnection(cfg);
}
try{
//组权限
let result = await conn.execute("select " + ids.groupId + "," + ids.authId + " from " + ids.tgroupauth);
let a:Array<any> = [];
for(let r of result.rows){
a.push({
gid:r[0],
aid:r[1]
});
}
arr.push(a);
//资源
result = await conn.execute("select " + ids.resourceId + "," + ids.resourceUrl + " from " + ids.tresource);
let a1:Array<any> = [];
for(let r of result.rows){
a1.push({
rid:r[0],
url:r[1]
});
}
arr.push(a1);
//资源权限
result = await conn.execute("select " + ids.resourceId + "," + ids.authId + " from " + ids.tresourceauth);
let a2:Array<any> = [];
for(let r of result.rows){
a2.push({
rid:r[0],
aid:r[1]
});
}
arr.push(a2);
}catch(e){
throw e;
}finally{
//关闭连接
if (conn) {
if(cm !== null){
await cm.release(conn);
}else{
try {
await conn.close();
} catch (err) {
throw err;
}
}
}
}
return arr;
}
}
/**
* 添加用户组
* @param userId 用户id
* @param groupId 组id
*/
static async addUserGroup(userId:number,groupId:number){
let key:string = this.USERKEY + userId;
let s = await this.cache.get(key);
let arr:Array<number>;
if(s !== null){
arr = JSON.parse(s);
}else{
arr = [];
}
if(arr.includes(groupId)){
return;
}
arr.push(groupId);
await this.cache.set({
key:key,
value:JSON.stringify(arr)
});
}
/**
* 添加用户组(多个组)
* @param userId 用户id
* @param groups 组id 数组
*/
static async addUserGroups(userId:number,groups:Array<number>,request?:HttpRequest){
//保存userId 到session object
if(request){
let session:Session = await SessionFactory.getSession(request);
if(session){
await session.set(this.USERID,userId);
}
}
//保存用户组
await this.cache.set({
key:this.USERKEY + userId,
value:JSON.stringify(groups)
});
}
/**
* 添加组权限
* @param groupId 组id
* @param authId 权限id
*/
static async addGroupAuthority(groupId:number,authId:number){
let key:string = this.GROUPKEY + groupId;
let s = await this.cache.get(key);
let arr:Array<number>;
if(s !== null){
arr = JSON.parse(s);
}else{
arr = [];
}
if(arr.includes(authId)){
return;
}
arr.push(authId);
await this.cache.set({
key:key,
value:JSON.stringify(arr)
});
}
/**
* 更新组权限
* @param groupId 组id
* @param authIds 权限id数组
*/
static async updGroupAuths(groupId:number,authIds:Array<number>){
let key:string = this.GROUPKEY + groupId;
await this.cache.del(key);
await this.cache.set({
key:key,
value:JSON.stringify(authIds)
});
}
/**
* 添加资源权限
* @param url 资源url
* @param authId 权限id
*/
static async addResourceAuth(url:string,authId:number){
let key:string = this.RESKEY + url;
let s = await this.cache.get(key);
let arr:Array<number>;
if(s !== null){
arr = JSON.parse(s);
}else{
arr = [];
}
if(arr.includes(authId)){
return;
}
arr.push(authId);
await this.cache.set({
key:key,
value:JSON.stringify(arr)
});
}
/**
* 添加资源权限(多个权限)
* @param url 资源id
* @param auths 权限id数组
*/
static async updResourceAuths(url:string,auths:Array<number>){
let key:string = this.RESKEY + url;
await this.cache.del(key);
let s = await this.cache.set({
key:key,
value:JSON.stringify(auths)
});
}
/**
* 删除用户
* @param userId 用户id
* @param request request对象
*/
static async deleteUser(userId:number,request?:HttpRequest){
//保存userId 到session object
if(request){
let session:Session = await SessionFactory.getSession(request);
if(session){
await SessionFactory.delSession(session.id);
}
}
//从cache删除
this.cache.del(this.USERKEY + userId);
}
/**
* 删除用户组
* @param userId 用户id
* @param groupId 组id
*/
static async deleteUserGroup(userId:number,groupId:number){
let key:string = this.USERKEY + userId;
let astr:string = await this.cache.get(key);
if(astr === null){
return;
}
let a:Array<number> = JSON.parse(astr);
if(!a.includes(groupId)){
return;
}
a.splice(a.indexOf(groupId),1);
await this.cache.set({
key:key,
value:JSON.stringify(a)
});
}
/**
* 删除组
* @param groupId 组id
*/
static async deleteGroup(groupId:number){
await this.cache.del(this.GROUPKEY+groupId);
}
/**
* 删除组权限
* @param groupId 组id
* @param authId 权限id
*/
static async deleteGroupAuthority(groupId:number,authId:number){
let key:string = this.GROUPKEY + groupId;
let astr:string = await this.cache.get(key);
if(astr === null){
return;
}
let a:Array<number> = JSON.parse(astr);
if(!a.includes(authId)){
return;
}
a.splice(a.indexOf(authId),1);
await this.cache.set({
key:key,
value:JSON.stringify(a)
});
}
/**
* 删除资源
* @param resourceId 资源id
*/
static async deleteResource(url:string){
await this.cache.del(this.RESKEY + url);
}
/**
* 删除资源权限
* @param resourceId 资源id
* @param authId 权限id
*/
static async deleteResourceAuthority(url:string,authId:number){
let key:string = this.RESKEY + url;
let astr:string = await this.cache.get(key);
if(astr === null){
return;
}
let a:Array<number> = JSON.parse(astr);
if(!a.includes(authId)){
return;
}
a.splice(a.indexOf(authId),1);
await this.cache.set({
key:key,
value:JSON.stringify(a)
});
}
/**
* 删除权限
* @param authId 权限Id
*/
static async deleteAuthority(authId:number){
//遍历资源权限并清除
let arr:Array<string> = await this.cache.getKeys(this.RESKEY + '*');
if(arr !== null){
for(let item of arr){
let astr:string = await this.cache.get(item);
if(astr === null){
return;
}
let a:Array<number> = JSON.parse(astr);
if(!a.includes(authId)){
return;
}
a.splice(a.indexOf(authId),1);
await this.cache.set({
key:item,
value:JSON.stringify(a)
});
}
}
//遍历组权限并清除
arr = await this.cache.getKeys(this.GROUPKEY + '*');
if(arr !== null){
for(let item of arr){
let astr:string = await this.cache.get(item);
if(astr === null){
return;
}
let a:Array<number> = JSON.parse(astr);
if(!a.includes(authId)){
return;
}
a.splice(a.indexOf(authId),1);
await this.cache.set({
key:item,
value:JSON.stringify(a)
});
}
}
}
/**
* 鉴权
* @param url 资源url
* @param session session对象
* @return 0 通过 1未登录 2无权限
*/
static async check(url:string,session:Session):Promise<number>{
//获取路径
url = App.url.parse(url).pathname;
let astr:string = await this.cache.get(this.RESKEY + url);
if(astr === null){
return 0;
}
let resAuthArr:Array<number> = JSON.parse(astr);
//资源不存在,则直接返回true
if(!Array.isArray(resAuthArr) || resAuthArr.length === 0){
return 0;
}
// sesion 不存在,返回1
if(!session){
return 1;
}
let userId:any = await session.get(this.USERID);
if(userId === null){
return 1;
}
if(typeof userId === 'string'){
userId = parseInt(userId);
}
let groupIds:Array<number>;
let gids:string = await this.cache.get(this.USERKEY + userId);
if(gids !== null){
groupIds = JSON.parse(gids);
}
//无组权限,返回无权
if(!Array.isArray(groupIds) || groupIds.length === 0){
return 2;
}
//用户权限
let authArr = [];
for(let id of groupIds){
//组对应权限
let a:Array<number>;
let s:string = await this.cache.get(this.GROUPKEY + id);
if(!s){
continue;
}
a = JSON.parse(s);
if(Array.isArray(a) && a.length > 0){
a.forEach(item=>{
if(!authArr.includes(item)){
authArr.push(item);
}
});
}
}
if(authArr.length === 0){
return 2;
}
//资源权限包含用户组权限
for(let au of authArr){
if(resAuthArr.includes(au)){
return 0;
}
}
return 2;
}
/**
* 获取安全配置页面
* @param name 配置项名
* @return 页面url
*/
static getSecurityPage(name:string){
return this.securityPages.get(name);
}
/**
* 获取登录前页面
* @param session session对象
* @return page url
*/
static async getPreLoginInfo(request:HttpRequest):Promise<string>{
let session:Session = await request.getSession();
if(!session){
return null;
}
let info:string = await session.get(this.PRELOGIN);
await session.del(this.PRELOGIN);
if(!info){
return null;
}
let json = JSON.parse(info);
if(!json.page){
return null;
}
let url = App.url.parse(json.page).pathname;
// 处理参数
if(json.params){
let pstr:string = '';
for(let p in json.params){
let o:any = json.params[p];
if(typeof o === 'object'){
o = JSON.stringify(o);
}
pstr += p + '=' + o + '&';
}
if(pstr !== ''){
pstr = encodeURI(pstr);
url += '?' + pstr;
}
}
return url;
}
/**
* 设置认证前页面
* @param session session对象
* @param page page url
*/
static async setPreLoginInfo(session:Session,request:HttpRequest){
await session.set(this.PRELOGIN,JSON.stringify({
page:request.url,
params:request.parameters
}));
}
/**
* @exclude
* 文件解析
* @param path 文件路径
*/
static async parseFile(path){
//读取文件
let json:any = null;
try{
let jsonStr:string = App.fs.readFileSync(path,'utf-8');
json = App.JSON.parse(jsonStr);
}catch(e){
throw new NoomiError("2700") + '\n' + e;
}
await this.init(json);
}
}
export{SecurityFactory} | the_stack |
import { EntitiesCacheManager, Message, MessageResolvable } from '@src/api'
import { Client } from '@src/core'
import { ChannelResolvable } from '@src/api/entities/channel/interfaces/ChannelResolvable'
import { MessageContent } from '@src/api/entities/message/interfaces/MessageContent'
import { MessageCreateOptions } from '@src/api/entities/message/interfaces/MessageCreateOptions'
import {
resolveChannelId,
resolveEmbedToRaw,
resolveFile,
resolveFiles,
resolveGuildId,
resolveMessageId, resolveMessageReferenceToRaw,
resolveStickerId
} from '@src/utils/resolve'
import { MessageCreateData } from '@src/api/entities/message/interfaces/MessageCreateData'
import { StickerResolvable } from '@src/api/entities/sticker'
import { Keyspaces, MessageEmbedTypes, StickerFormatTypes } from '@src/constants'
import { DiscordooError, idToTimestamp } from '@src/utils'
import { DataResolver } from '@src/utils/DataResolver'
import { inspect } from 'util'
import { filterAndMap } from '@src/utils/filterAndMap'
import { EntitiesManager } from '@src/api/managers/EntitiesManager'
import { makeCachePointer } from '@src/utils/cachePointer'
import { DeleteManyMessagesOptions } from '@src/api/managers/messages/DeleteManyMessagesOptions'
import { FetchOneMessageOptions } from '@src/api/managers/messages/FetchOneMessageOptions'
import { FetchManyMessagesQuery } from '@src/api/managers/messages/FetchManyMessagesQuery'
import { is } from 'typescript-is'
import { EntitiesUtil } from '@src/api/entities/EntitiesUtil'
export class ClientMessagesManager extends EntitiesManager {
public cache: EntitiesCacheManager<Message>
constructor(client: Client) {
super(client)
this.cache = new EntitiesCacheManager<Message>(this.client, {
keyspace: Keyspaces.MESSAGES,
storage: 'global',
entity: 'Message',
policy: 'messages'
})
}
async pin(channel: ChannelResolvable, message: MessageResolvable, reason?: string): Promise<boolean> {
const channelId = resolveChannelId(channel),
messageId = resolveMessageId(message)
if (!channelId) throw new DiscordooError('ClientMessagesManager#pin', 'Cannot pin message without channel id.')
if (!messageId) throw new DiscordooError('ClientMessagesManager#pin', 'Cannot pin message without message id.')
const response = await this.client.internals.actions.pinMessage(channelId, messageId, reason)
return response.success
}
async unpin(channel: ChannelResolvable, message: MessageResolvable, reason?: string): Promise<boolean> {
const channelId = resolveChannelId(channel),
messageId = resolveMessageId(message)
if (!channelId) throw new DiscordooError('ClientMessagesManager#unpin', 'Cannot unpin message without channel id.')
if (!messageId) throw new DiscordooError('ClientMessagesManager#unpin', 'Cannot unpin message without message id.')
const response = await this.client.internals.actions.unpinMessage(channelId, messageId, reason)
return response.success
}
async fetchPinned(channel: ChannelResolvable): Promise<Message[] | undefined> {
const channelId = resolveChannelId(channel)
if (!channelId) {
throw new DiscordooError('ClientMessagesManager#fetchPinned', 'Cannot fetch pinned messages without channel id.')
}
const response = await this.client.internals.actions.getPinnedMessages(channelId)
const Message = EntitiesUtil.get('Message')
if (response.success) {
const result: Message[] = []
await this.client.internals.cache.clear(Keyspaces.PINNED_MESSAGES, channelId)
for await (const messageData of response.result) {
const message = await new Message(this.client).init(messageData)
await this.cache.set(message.id, message, { storage: channelId })
await this.client.internals.cache.set(
Keyspaces.PINNED_MESSAGES,
channelId,
'Message',
'messages',
message.id,
makeCachePointer(Keyspaces.MESSAGES, channelId, message.id)
)
result.push(message)
}
return result
}
return undefined
}
async fetchOne<R = Message>(
channel: ChannelResolvable, message: MessageResolvable, options?: FetchOneMessageOptions
): Promise<R | undefined> {
const channelId = resolveChannelId(channel),
messageId = resolveMessageId(message)
if (!channelId) throw new DiscordooError('ClientMessagesManager#fetchOne', 'Cannot fetch message without channel id.')
if (!messageId) throw new DiscordooError('ClientMessagesManager#fetchOne', 'Cannot fetch message without message id.')
const response = await this.client.internals.actions.getMessage(channelId, messageId)
const Message = EntitiesUtil.get('Message')
if (response.success) {
if (options?.patchEntity) {
return await options.patchEntity.init(response.result) as any
} else {
const msg = await new Message(this.client).init(response.result)
await this.cache.set(msg.id, msg, { storage: channelId })
return msg as any
}
}
return undefined
}
async fetchMany(channel: ChannelResolvable, query: FetchManyMessagesQuery): Promise<Message[] | undefined> {
const channelId = resolveChannelId(channel)
if (!channelId) throw new DiscordooError('ClientMessagesManager#fetchMany', 'Cannot fetch messages without channel id.')
if (!is<FetchManyMessagesQuery>(query)) {
throw new DiscordooError('ClientMessagesManager#fetchMany', 'Incorrect fetch query provided:', query)
}
const response = await this.client.internals.actions.getMessages(channelId, query)
const Message = EntitiesUtil.get('Message')
if (response.success) {
const result: Message[] = []
for await (const messageData of response.result) {
const message = await new Message(this.client).init(messageData)
await this.cache.set(message.id, message, { storage: channelId })
result.push(message)
}
return result
}
return undefined
}
fetch(
channel: ChannelResolvable, message: MessageResolvable | FetchManyMessagesQuery, options?: FetchOneMessageOptions
): Promise<Message | Message[] | undefined> {
return is<FetchManyMessagesQuery>(message) ? this.fetchMany(channel, message) : this.fetchOne(channel, message, options)
}
async create(channel: ChannelResolvable, content: MessageContent = '', options: MessageCreateOptions = {}): Promise<Message | undefined> {
const channelId = resolveChannelId(channel)
if (!channelId) throw new DiscordooError('ClientMessagesManager#create', 'Cannot create message without channel id.')
let contentResolved = false
if (!content) {
if (
!options.file && !options.embed && !options.sticker && !options.content &&
!options.files?.length && !options.embeds?.length && !options.stickers?.length
) {
throw new DiscordooError(
'MessagesManager#create',
'Incorrect content:', inspect(content) + '.',
'If content not specified, options must be provided: at least one of options.embeds/embed/files/file/stickers/sticker/content.')
} else {
contentResolved = true
}
}
const data: any /* MessageContent */ = content
const payload: MessageCreateData = {
content: '',
allowed_mentions: undefined,
message_reference: undefined,
tts: false,
embeds: [],
files: [],
stickers: [],
components: [],
}
const embedTypes = Object.values<any>(MessageEmbedTypes).filter(v => typeof v === 'string'),
stickerFormatTypes = Object.values<any>(StickerFormatTypes).filter(v => typeof v === 'number')
if (Array.isArray(data)) {
const target: /* MessageEmbedResolvable | StickerResolvable | MessageAttachmentResolvable */ any = content[0]
if (embedTypes.includes(target.type)) { // content = embeds
payload.embeds.push(...data.map(resolveEmbedToRaw))
} else if (stickerFormatTypes.includes(target.formatType ?? target.format_type)) { // content = stickers
const stickers = filterAndMap<StickerResolvable, string>(
data,
(s) => resolveStickerId(s) !== undefined,
(s) => resolveStickerId(s)
)
payload.stickers.push(...stickers)
} else { // content = files or unexpected things
try {
payload.files.push(...await resolveFiles(data))
} catch (e: any) {
throw new DiscordooError(
'MessagesManager#create',
'Tried to resolve array of attachments as message content, but got', (e.name ?? 'Error'),
'with message:', (e.message ?? 'unknown error') + '.',
'Check if you are pass the message content array correctly. Do not mix content types in this array.',
'Allowed types is MessageEmbedResolvable, StickerResolvable, MessageAttachmentResolvable.',
'If you pass anything other than these types to the message content array, you will get this error.'
)
}
}
contentResolved = true
}
if (!contentResolved) {
if (embedTypes.includes(data.type)) {
payload.embeds.push(resolveEmbedToRaw(data))
} else if (stickerFormatTypes.includes(data.formatType ?? data.format_type)) {
const id = resolveStickerId(data)
if (id) payload.stickers.push(id)
} else if (typeof data === 'object' && DataResolver.isMessageAttachmentResolvable(data)) {
payload.files.push(await resolveFile(data))
} else {
payload.content = content.toString()
}
}
payload.tts = !!options.tts
if (options.content) payload.content = options.content
if (options.messageReference) {
payload.message_reference = resolveMessageReferenceToRaw(options.messageReference)
}
// TODO: allowed mentions
// TODO: components
if (options.embed) payload.embeds.push(resolveEmbedToRaw(options.embed))
if (options.embeds?.length) payload.embeds.push(...options.embeds.map(resolveEmbedToRaw))
if (options.file) payload.files.push(await resolveFile(options.file))
if (options.files?.length) payload.files.push(...await resolveFiles(options.files))
if (options.sticker) {
const id = resolveStickerId(data.stickers)
if (id) payload.stickers.push(id)
}
if (options.stickers?.length) {
const stickers = filterAndMap<StickerResolvable, string>(
options.stickers,
(s) => resolveStickerId(s) !== undefined,
(s) => resolveStickerId(s)
)
payload.stickers.push(...stickers)
}
const response = await this.client.internals.actions.createMessage(channelId, payload)
const Message = EntitiesUtil.get('Message')
if (response.success) {
return await new Message(this.client).init(response.result)
}
return undefined
}
async deleteOne(channel: ChannelResolvable, message: MessageResolvable, reason?: string): Promise<boolean> {
const channelId = resolveChannelId(channel),
messageId = resolveMessageId(message)
if (!channelId) throw new DiscordooError('ClientMessagesManager#deleteOne', 'Cannot delete message without channel id.')
if (!messageId) throw new DiscordooError('ClientMessagesManager#deleteOne', 'Cannot delete message without message id.')
const response = await this.client.internals.actions.deleteMessage(channelId, messageId, reason)
return response.success
}
async deleteMany(
channel: ChannelResolvable, messages: MessageResolvable[] | number, options?: DeleteManyMessagesOptions
): Promise<string[] | undefined> {
const channelId = resolveChannelId(channel)
if (!channelId) throw new DiscordooError('ClientMessagesManager#deleteMany', 'Cannot delete messages without channel id.')
let ids: string[] = []
if (Array.isArray(messages)) {
const twoWeeksAgo = Date.now() - 1209600000
const filter = (message: MessageResolvable, filtered: string[]) => {
const id = resolveMessageId(message)
if (!id) return false
if (filtered.includes(id)) return false
return options?.filterOld ? idToTimestamp(id) >= twoWeeksAgo : true
}
ids = filterAndMap<MessageResolvable, string>(messages, filter, (m) => resolveMessageId(m))
if (ids.length === 0) return ids
if (ids.length === 1) {
const result = await this.deleteOne(channel, ids[0], options?.reason)
return result ? ids : undefined
}
const response = await this.client.internals.actions.deleteMessagesBulk(channelId, ids, options?.reason)
if (response.success) return ids
} else if (!isNaN(messages)) {
const msgs = await this.fetchMany(channelId, { limit: messages })
if (msgs) return this.deleteMany(channelId, msgs, options)
}
return undefined
}
async delete(
channel: ChannelResolvable, messages: MessageResolvable | MessageResolvable[] | number, options?: DeleteManyMessagesOptions | string
): Promise<boolean | string[] | undefined> {
if (Array.isArray(messages) || typeof messages === 'number') {
return this.deleteMany(channel, messages, options as DeleteManyMessagesOptions)
} else {
return this.deleteOne(channel, messages, options as string)
}
}
} | the_stack |
import * as vscode from 'vscode';
import {DebugSessionClass} from '../debugadapter';
import {RemoteFactory} from '../remotes/remotefactory';
import {Remote, RemoteBreakpoint} from '../remotes/remotebase';
import {Labels, SourceFileEntry} from '../labels/labels';
import {Settings} from '../settings';
import {Utility} from '../misc/utility';
import {Decoration} from '../decoration';
import {StepHistory, CpuHistory, CpuHistoryClass} from '../remotes/cpuhistory';
import {Z80RegistersClass, Z80Registers} from '../remotes/z80registers';
import {StepHistoryClass} from '../remotes/stephistory';
import {ZSimRemote} from '../remotes/zsimulator/zsimremote';
import {UnitTestCaseBase, UnitTestCase, RootTestSuite, UnitTestSuiteConfig, UnitTestSuite} from './unittestcase';
import {PromiseCallbacks} from '../misc/promisecallbacks';
import {DiagnosticsHandler} from '../diagnosticshandler';
import {GenericWatchpoint} from '../genericwatchpoint';
import {ZxNextSocketRemote} from '../remotes/dzrpbuffer/zxnextsocketremote';
/**
* This class takes care of executing the unit tests.
* It basically
* 1. Reads the list file to find the unit test labels.
* 2. Loads the binary into the emulator.
* 3. Manipulates memory and PC register to call a specific unit test.
* 4. Loops over all found unit tests.
*/
export class Z80UnitTestRunner {
/// The unit test initialization routine. The user has to provide
/// it and the label.
protected static addrStart: number;
/// The start address of the unit test wrapper.
/// This is called to start the unit test.
protected static addrTestWrapper: number;
/// Here is the address of the unit test written.
protected static addrCall: number;
/// At the end of the test this address is reached on success.
protected static addrTestReadySuccess: number;
/// The address below the stack. Used for checking stack overflow.
protected static stackBottom: number;
/// The address above the stack. Used for checking stack overflow.
protected static stackTop: number;
/// Is set if the current test case fails.
protected static currentFail: boolean;
/// Debug mode or run mode.
protected static debug = false;
/// For debugging. Pointer to debug adapter class.
protected static debugAdapter: DebugSessionClass;
// The root of all test cases.
protected static rootTestSuite: RootTestSuite;
// Pointer to the test controller.
protected static testController: vscode.TestController;
// The currently used (and setup) test configuration.
protected static testConfig: UnitTestSuiteConfig | undefined;
// Used for returning test cases from the debugger.
protected static waitOnDebugger: PromiseCallbacks<void> | undefined;
// The current test run.
protected static currentTestRun: vscode.TestRun | undefined;
// The current test item.
protected static currentTestItem: vscode.TestItem | undefined;
// The current test start time.
protected static currentTestStart: number;
// Remembers if the current test case was failed.
protected static currentTestFailed: boolean;
// Is true during test case setup (assembler) code
protected static testCaseSetup: boolean;
// Set to true if test timeout occurs.
protected static timedOut: boolean;
// Set to true while tests are executed.
protected static testRunActive: boolean;
// Set to true during cancelling unit tests.
protected static stoppingTests: boolean;
/**
* Called to initialize the test controller.
*/
public static Init() {
// Init
this.testConfig = undefined;
this.testRunActive = false;
// Create test controller
this.testController = vscode.tests.createTestController(
'maziac.dezog.z80unittest.controller',
'Z80 Unit Tests'
);
// For test case discovery
this.rootTestSuite = new RootTestSuite(this.testController);
// Add profiles for test case execution
this.testController.createRunProfile('Run', vscode.TestRunProfileKind.Run, (request, token) => {
this.runHandler(request, token);
});
this.testController.createRunProfile('Debug', vscode.TestRunProfileKind.Debug, (request, token) => {
this.runDebugHandler(request, token);
});
}
/**
* Runs one or several test cases. (Not debug)
*/
protected static async runHandler(request: vscode.TestRunRequest, token: vscode.CancellationToken) {
this.debug = false;
await this.runOrDebugHandler(request, token);
}
/**
* Runs one or several test cases. (debug)
*/
protected static async runDebugHandler(request: vscode.TestRunRequest, token: vscode.CancellationToken) {
// Start with debugger
this.debug = true;
await this.runOrDebugHandler(request, token);
}
/**
* The run or debug handler.
* Uses 'run' if the debug adapter is undefined.
* Otherwise a debug session is started.
* @param request The original request from vscode.
*/
protected static async runOrDebugHandler(request: vscode.TestRunRequest, token: vscode.CancellationToken) {
// Clear any diagnostics
DiagnosticsHandler.clear();
// Only allow one test run at a time
if (this.testRunActive) {
// Cancel unit tests
await this.stopUnitTests();
return;
}
this.stoppingTests = false;
this.testRunActive = true;
// Create test run
const run = this.testController.createTestRun(request);
this.currentTestRun = run;
const queue: vscode.TestItem[] = [];
// Register function to terminate if requested
token.onCancellationRequested(async () => {
await this.stopUnitTests(); // Will also terminate the debug adapter.
});
// Init
this.testConfig = undefined;
// Loop through all included tests, or all known tests, and add them to our queue
if (request.include) {
request.include.forEach(test => queue.push(test));
} else {
this.testController.items.forEach(test => queue.push(test));
}
// For every test that was queued, try to run it. Call run.passed() or run.failed().
// The `TestMessage` can contain extra information, like a failing location or
// a diff output. But here we'll just give it a textual message.
while (!this.stoppingTests && queue.length > 0 && !token.isCancellationRequested) {
const test = queue.shift()!;
// Skip tests the user asked to exclude
if (request.exclude?.includes(test))
continue;
// Check if there are children
if (test.children.size > 0) {
// Run child tests
const tmp: vscode.TestItem[] = [];
test.children.forEach(item => tmp.push(item));
queue.unshift(...tmp);
}
// Get "real" unit test
const ut = UnitTestCaseBase.getUnitTestCase(test) as UnitTestCase;
if (!(ut instanceof UnitTestSuite)) {
let timeoutHandle;
this.timedOut = false;
this.currentTestStart = Date.now();
try {
// Setup the test config
if (this.debug)
await this.setupDebugTestCase(ut);
else
await this.setupRunTestCase(ut);
}
catch (e) {
// Output error
vscode.window.showErrorMessage(e.message);
// Leave loop
break;
}
try {
// Set timeout
if (!this.debug && !(Remote instanceof ZxNextSocketRemote)) {
// Timeout/break not possible with ZXNext.
const toMs = 1000 * Settings.launch.unitTestTimeout;
if (toMs > 0) {
timeoutHandle = setTimeout(() => {
this.timedOut = true;
// Failure: Timeout. Send a break.
Remote.pause();
}, toMs);
}
}
// Run the test case
this.currentTestItem = test;
this.currentTestStart = Date.now();
run.started(test);
//await Utility.timeout(1000);
await this.runTestCase(ut);
}
catch (e) {
if (!this.stoppingTests) {
// Some unspecified test failure
this.testFailed(e.message, e.position);
}
}
finally {
clearTimeout(timeoutHandle);
this.currentTestItem = undefined;
}
}
}
// Make sure to end the run after all tests have been executed:
run.end();
// Stop debugger
if (Remote) {
await this.stopUnitTests();
}
// Test run finished
this.stoppingTests = true;
this.testRunActive = false;
}
/**
* Sets up the test case.
* Goes up the parents until it finds the unit test config.
* Then (if not yet done before) it starts up the Remote to be
* able to execute a single test case.
*/
protected static async setupRunTestCase(ut: UnitTestCase) {
// Check for parent config
const testConfig = ut.getConfigParent();
if (!testConfig)
throw Error("No test config found.");
// Check if already setup
if (this.testConfig == testConfig)
return;
this.testConfig = testConfig;
// Terminate any probably runnning instance
await this.terminateRemote();
this.debugAdapter = undefined as any;
// Prepare running of the test case
// Get unit test launch config
const configuration = this.testConfig.config;
// Setup settings
Settings.launch = Settings.Init(configuration);
Settings.CheckSettings();
Utility.setRootPath(Settings.launch.rootFolder);
// Reset all decorations
Decoration.clearAllDecorations();
// Create the registers
Z80RegistersClass.createRegisters();
// Start emulator.
RemoteFactory.createRemote(configuration.remoteType);
// Check if a cpu history object has been created. (Note: this is only required for debug but done for both)
if (!(CpuHistory as any)) {
// If not create a lite (step) history
CpuHistoryClass.setCpuHistory(new StepHistoryClass());
StepHistory.decoder = Z80Registers.decoder;
}
// Reads the list file and also retrieves all occurrences of WPMEM, ASSERTION and LOGPOINT.
Labels.init(configuration.smallValuesMaximum);
Remote.readListFiles(configuration);
return new Promise<void>(async (resolve, reject) => {
// Events
Remote.once('initialized', async () => {
try {
// Initialize Cpu- or StepHistory.
StepHistory.init(); // might call the socket
// Execute command to enable wpmem, logpoints, assertions.
await Remote.enableLogpointGroup(undefined, true);
try {
await Remote.enableWPMEM(true);
}
catch (e) {
// It's not essential anymore to have watchpoints running.
// So catch this error from CSpect and show a warning instead
vscode.window.showWarningMessage(e.message);
}
await Remote.enableAssertionBreakpoints(true);
if (this.debug) {
// After initialization vscode might send breakpoint requests
// to set the breakpoints.
// Unfortunately this request is sent only if breakpoints exist.
// I.e. there is no safe way to wait for something to
// know when vscode is ready.
// So just wait some time:
if (Settings.launch.startAutomatically)
await Utility.timeout(500);
}
// Initialize
await this.initUnitTests();
// End
resolve();
}
catch (e) {
// Some error occurred
reject(e);
}
});
Remote.on('coverage', coveredAddresses => {
Decoration.showCodeCoverage(coveredAddresses);
});
Remote.on('warning', message => {
// Some problem occurred
vscode.window.showWarningMessage(message);
});
Remote.on('debug_console', message => {
// Show the message in the debug console
vscode.debug.activeDebugConsole.appendLine(message);
});
Remote.once('error', e => {
// Some error occurred
Remote?.dispose();
reject(e);
});
// Connect to debugger.
try {
await Remote.init();
}
catch (e) {
// Some error occurred
reject(e);
}
});
}
/**
* Sets up the test case.
* Goes up the parents until it finds the unit test config.
* Then (if not yet done before) it starts up the debug adapter.
*/
protected static async setupDebugTestCase(ut: UnitTestCase): Promise<void> {
// Check for parent config
const testConfig = ut.getConfigParent();
if (!testConfig)
throw Error("No test config found.");
// Check if already setup
if (this.testConfig == testConfig)
return;
this.testConfig = testConfig;
// Terminate any probably running instance
await this.terminateRemote();
// Setup root folder
Utility.setRootPath(testConfig.wsFolder);
// Start debugger
this.debugAdapter = undefined as any;
try {
const configName = testConfig.testItem.label;
this.debugAdapter = await DebugSessionClass.unitTestsStart(configName);
}
catch (e) { // NOSONAR
throw e;
}
try {
// Execute command to enable wpmem, logpoints, assertions.
await Remote.enableLogpointGroup(undefined, true);
try {
await Remote.enableWPMEM(true);
}
catch (e) {
// It's not essential anymore to have watchpoints running.
// So catch this error from CSpect and show a warning instead
vscode.window.showWarningMessage(e.message);
}
await Remote.enableAssertionBreakpoints(true);
// We need to give vscode a little time to set the breakpoints.
// Unfortunately there is no way to tell when vscode is finished or that it even has started.
await Utility.timeout(500);
// Init unit tests
await this.initUnitTests();
// Start unit tests after a short while
await Remote.waitForBeingQuietFor(1000);
}
catch (e) { // NOSONAR
throw e;
}
}
/**
* Checks if the debugger is active. If yes terminates it and
* executes the unit tests.
*/
protected static async terminateRemote(): Promise<void> {
return new Promise<void>(async resolve => {
// Wait until vscode debugger has stopped.
if (Remote) {
// Terminate emulator
await Remote.terminate();
RemoteFactory.removeRemote();
}
// (Unfortunately there is no event for this, so we need to wait)
Utility.delayedCall(time => {
// After 5 secs give up
if (time >= 5.0) {
// Give up
vscode.window.showErrorMessage('Could not terminate active debug session. Please try manually.');
resolve();
return true;
}
// Check for active debug session
if (vscode.debug.activeDebugSession)
return false; // Try again
resolve();
return true; // Stop
});
});
}
/**
* Runs a single test case.
* Throws an exception on failure.
* Np exception if passed correctly.
* @param test The TestItem.
*/
protected static async runTestCase(ut: UnitTestCase) {
const utLabel = ut.utLabel;
// Special handling for zsim: Re-init custom code.
if (Remote instanceof ZSimRemote) {
const zsim = Remote;
zsim.customCode?.execute(utLabel);
}
// Start the part that is executed before each unit test
this.testCaseSetup = true;
this.currentTestFailed = false;
await this.execAddr(this.addrStart);
if (this.currentTestFailed)
return;
// Check if timeout already expired (can only happen during dezog debugging)
if (this.timedOut) {
this.testFailed('Timeout during test case setup.');
return;
}
// If not 'startAutomatically' then set a BP at the start of the unit test
const utAddr = this.getLongAddressForLabel(utLabel);
let breakpoint;
if (this.debug && !Settings.launch.startAutomatically) {
// Set breakpoint
breakpoint = {bpId: 0, filePath: '', lineNr: -1, address: utAddr, condition: '', log: undefined};
await Remote.setBreakpoint(breakpoint);
}
// Start the unit test
this.testCaseSetup = false;
await this.execAddr(utAddr);
// Remove breakpoint
if (breakpoint) {
if (Remote)
await Remote.removeBreakpoint(breakpoint);
}
}
/**
* Initializes the unit tests. Is called after the Remote/the emulator has been setup.
*/
protected static async initUnitTests(): Promise<void> {
// Get the unit test code
this.addrStart = this.getLongAddressForLabel("UNITTEST_START");
this.addrTestWrapper = this.getLongAddressForLabel("UNITTEST_TEST_WRAPPER");
this.addrCall = this.getLongAddressForLabel("UNITTEST_CALL_ADDR");
this.addrCall++;
this.addrTestReadySuccess = this.getLongAddressForLabel("UNITTEST_TEST_READY_SUCCESS");
this.stackTop = this.getLongAddressForLabel("UNITTEST_STACK");
try {
this.stackBottom = this.getLongAddressForLabel("UNITTEST_STACK_BOTTOM");
}
catch (e) {
throw Error("An error occurred with the 'UNITTEST_INITIALIZE' macro. Did you forget to update it for DeZog version 2.4?");
}
// The Z80 binary has been loaded.
// The debugger stopped before starting the program.
// Now read all the unit tests.
this.currentFail = true;
// Check if code for unit tests is really present
// (In case labels are present but the actual code was not loaded.)
const opcode = await Remote.readMemory(this.addrTestWrapper & 0xFFFF);
// Should start with DI (=0xF3)
if (opcode != 0xF3)
throw Error("Code for unit tests is not present.");
// Labels not yet known.
//this.utLabels = undefined as unknown as Array<string>;
// Success and failure breakpoints
const successBp: RemoteBreakpoint = {bpId: 0, filePath: '', lineNr: -1, address: Z80UnitTestRunner.addrTestReadySuccess, condition: '', log: undefined};
await Remote.setBreakpoint(successBp);
// Stack watchpoints
try {
const stackMinWp: GenericWatchpoint = {address: this.stackBottom, size: 2, access: 'rw', condition: ''};
const stackMaxWp: GenericWatchpoint = {address: this.stackTop, size: 2, access: 'rw', condition: ''};
await Remote.setWatchpoint(stackMinWp);
await Remote.setWatchpoint(stackMaxWp);
}
catch (e) {
// CSpect does not implement watchpoints.
// Silently ignore.
}
}
/**
* Returns the long address for a label. Checks it and throws an error if it does not exist.
* @param label The label eg. "UNITTEST_TEST_WRAPPER"
* @returns An address.
*/
protected static getLongAddressForLabel(label: string): number {
const loc = Labels.getLocationOfLabel(label);
let addr;
if (loc)
addr = loc.address;
if (addr == undefined) {
throw Error("Unit tests are not enabled in the enabled sources. Label " + label + " is not found. Did you forget to use the 'UNITTEST_INITIALIZE' macro ?");
}
return addr;
}
/**
* Executes the sub routine at 'addr'.
* Used to call the unit test initialization subroutine and the unit
* tests.
* @param address The (long) address to call.
*/
protected static async execAddr(address: number) {
// Set memory values to test case address.
const callAddr = new Uint8Array([address & 0xFF, (address >>> 8) & 0xFF]);
await Remote.writeMemoryDump(this.addrCall & 0xFFFF, callAddr);
// Set slot/bank to Unit test address
const bank = Z80Registers.getBankFromAddress(address);
if (bank >= 0) {
const slot = Z80Registers.getSlotFromAddress(address)
await Remote.setSlot(slot, bank);
}
// Set PC
const addr64k = this.addrTestWrapper & 0xFFFF;
await Remote.setRegisterValue("PC", addr64k);
// Init
StepHistory.clear();
await Remote.getRegistersFromEmulator();
await Remote.getCallStackFromEmulator();
// Run or Debug
await this.RemoteContinue();
}
/**
* Starts Continue directly or through the debug adapter.
*/
protected static async RemoteContinue(): Promise<void> {
// Init
Remote.startProcessing();
// Run or Debug
if (this.debugAdapter) {
// With vscode UI
this.debugAdapter.sendEventContinued();
// Debug: Continue
const finish = new Promise<void>((resolve, reject) => {
new PromiseCallbacks<void>(this, 'waitOnDebugger', resolve, reject); // NOSONAR
});
await this.debugAdapter.remoteContinue();
if (Remote)
Remote.stopProcessing();
// Note: after the first call to debugAdapter.remoteContinue the vscode will take over until dbgCheckUnitTest will finally return (in 'finish')
await finish;
console.log();
}
else {
// Run: Continue
let reasonString = await Remote.continue();
Remote.stopProcessing();
// There are 2 possibilities to get here:
// a) the test case is passed
// b) the test case stopped because of an ASSERTION or WPMEM, i.e. it is failed
const pc = Remote.getPCLong();
// OK or failure
if (pc == this.addrTestReadySuccess) {
// Passed
this.testPassed();
}
else {
// Failure
if (this.timedOut) {
reasonString = "Timeout (" + Settings.launch.unitTestTimeout + "s)";
}
this.testFailed(reasonString);
}
}
}
/**
* Checks if the test case was OK or a fail.
* Or undetermined.
* There are 3 possibilities to get here:
* a) the test case is passed
* b) the test case stopped because of an ASSERTION, i.e. it is failed
* c) a user breakpoint was hit or the user paused the execution
* The c) is the ricky one because the Promise is not fulfilled in this situation.
* @param breakReasonString Contains the break reason, e.g. the assert.
* @returns true If test case has been finished.
*/
public static async dbgCheckUnitTest(breakReasonString: string): Promise<boolean> {
Utility.assert(this.waitOnDebugger);
// Check if test case ended successfully or not
const pc = Remote.getPCLong();
// OK or failure
if (pc == this.addrTestReadySuccess) {
// Success
if (!this.currentTestFailed)
this.testPassed();
this.waitOnDebugger!.resolve();
return true;
}
else {
// The pass/fail is distinguished by the breakReasonString text.
if (breakReasonString?.toLowerCase().startsWith('assertion')) {
this.testFailed(breakReasonString);
}
return false;
}
}
/**
* Make the test item fail. Create a TestMessage. I.e. an error occurred now create the failure
* which contains the line number.
* Note: vscode will only display the first of the test messages.
* @param reason The text to show.
* @param position (Optional) if error was located already it is set here. Otherwise the pc is used for locating.
*/
protected static testFailed(reason?: string, position?: {filename, line, column}) {
const testMsg = new vscode.TestMessage(reason || "Failure.");
if (position) {
// Use existing position
const uri = vscode.Uri.file(position.filename);
const line = position.line;
const column = position.column;
const range = new vscode.Range(line, column, line, column);
testMsg.location = new vscode.Location(uri, range);
}
else {
// Get pc for position
const pc = Remote?.getPCLong();
if (pc != undefined) {
const positionPc: SourceFileEntry = Labels.getFileAndLineForAddress(pc);
if (positionPc) {
const uri = vscode.Uri.file(positionPc.fileName);
const line = positionPc.lineNr;
const range = new vscode.Range(line, 10000, line, 10000);
testMsg.location = new vscode.Location(uri, range);
}
}
}
// "Normal" test case failure
this.currentTestRun?.failed(this.currentTestItem!, testMsg, Date.now() - this.currentTestStart);
// Remember
this.currentTestFailed = true;
}
/**
* Make the test item pass.
*/
protected static testPassed() {
// Don't allow passing during test case setup
if (!this.testCaseSetup) {
this.currentTestRun?.passed(this.currentTestItem!, Date.now() - this.currentTestStart);
}
}
/**
* Command to cancel the unit tests.
* Called from the debug adapter.
*/
public static async cancelUnitTests(): Promise<void> {
this.stoppingTests = true;
if (this.waitOnDebugger)
this.waitOnDebugger.reject(Error("Unit test cancelled."));
}
/**
* Stops all unit tests.
* Called by the test runner.
*/
protected static async stopUnitTests(): Promise<void> {
// Async
return new Promise<void>(async resolve => {
this.stoppingTests = true;
// Call reject if on.
if (this.waitOnDebugger)
this.waitOnDebugger.reject(Error("Unit tests cancelled"));
// Wait a little bit for pending messages (The vscode could hang on waiting on a response for getRegisters)
if (this.debugAdapter) {
//Remote.stopProcessing(); // To show the coverage after continue to end
//this.debugAdapter.sendEventBreakAndUpdate();
//await Utility.timeout(1);
if (Remote)
await Remote.waitForBeingQuietFor(300);
}
// For reverse debugging.
StepHistory.clear();
if (Remote) {
// Exit
await Remote.terminate();
// Remove event handling for the emulator
Remote.removeAllListeners();
Remote.dispose();
}
resolve();
});
}
} | the_stack |
export function createConferenceEvent(action: string, attributes: any): {
type: string;
source: string;
action: string;
attributes: object;
};
/**
* Creates an event which contains information about the audio output problem (the user id of the affected participant,
* the local audio levels and the remote audio levels that triggered the event).
*
* @param {string} userID - The user id of the affected participant.
* @param {*} localAudioLevels - The local audio levels.
* @param {*} remoteAudioLevels - The audio levels received from the participant.
*/
export function createAudioOutputProblemEvent(userID: string, localAudioLevels: any, remoteAudioLevels: any): {
type: string;
action: string;
attributes: {
userID: string;
localAudioLevels: any;
remoteAudioLevels: any;
};
};
/**
* This class exports constants and factory methods related to the analytics
* API provided by AnalyticsAdapter. In order for entries in a database to be
* somewhat easily traceable back to the code which produced them, events sent
* through analytics should be defined here.
*
* Since the AnalyticsAdapter API can be used in different ways, for some events
* it is more convenient to just define the event name as a constant. For other
* events a factory function is easier.
*
* A general approach for adding a new event:
* 1. Determine the event type: track, UI, page, or operational. If in doubt use
* operational.
* 2. Determine whether the event is related to other existing events, and
* which fields are desired to be set: name, action, actionSubject, source.
* 3. If the name is sufficient (the other fields are not important), use a
* constant. Otherwise use a factory function.
*
* Note that the AnalyticsAdapter uses the events passed to its functions for
* its own purposes, and might modify them. Because of this, factory functions
* should create new objects.
*
*/
/**
* The constant which identifies an event of type "operational".
* @type {string}
*/
export const TYPE_OPERATIONAL: string;
/**
* The constant which identifies an event of type "page".
* @type {string}
*/
export const TYPE_PAGE: string;
/**
* The constant which identifies an event of type "track".
* @type {string}
*/
export const TYPE_TRACK: string;
/**
* The constant which identifies an event of type "ui".
* @type {string}
*/
export const TYPE_UI: string;
/**
* The "action" value for Jingle events which indicates that the Jingle session
* was restarted (TODO: verify/fix the documentation)
* @type {string}
*/
export const ACTION_JINGLE_RESTART: string;
/**
* The "action" value for Jingle events which indicates that a session-accept
* timed out (TODO: verify/fix the documentation)
* @type {string}
*/
export const ACTION_JINGLE_SA_TIMEOUT: string;
/**
* The "action" value for Jingle events which indicates that a session-initiate
* was received.
* @type {string}
*/
export const ACTION_JINGLE_SI_RECEIVED: string;
/**
* The "action" value for Jingle events which indicates that a session-initiate
* not arrived within a timeout (the value is specified in
* the {@link JingleSessionPC}.
* @type {string}
*/
export const ACTION_JINGLE_SI_TIMEOUT: string;
/**
* A constant for the "terminate" action for Jingle events. TODO: verify/fix
* the documentation)
* @type {string}
*/
export const ACTION_JINGLE_TERMINATE: string;
/**
* The "action" value for Jingle events which indicates that a transport-replace
* was received.
* @type {string}
*/
export const ACTION_JINGLE_TR_RECEIVED: string;
/**
* The "action" value for Jingle events which indicates that a transport-replace
* succeeded (TODO: verify/fix the documentation)
* @type {string}
*/
export const ACTION_JINGLE_TR_SUCCESS: string;
/**
* The "action" value for P2P events which indicates that P2P session initiate message has been rejected by the client
* because the mandatory requirements were not met.
* @type {string}
*/
export const ACTION_P2P_DECLINED: string;
/**
* The "action" value for P2P events which indicates that a connection was
* established (TODO: verify/fix the documentation)
* @type {string}
*/
export const ACTION_P2P_ESTABLISHED: string;
/**
* The "action" value for P2P events which indicates that something failed.
* @type {string}
*/
export const ACTION_P2P_FAILED: string;
/**
* The "action" value for P2P events which indicates that a switch to
* jitsi-videobridge happened.
* @type {string}
*/
export const ACTION_P2P_SWITCH_TO_JVB: string;
/**
* The name of an event which indicates an available device. We send one such
* event per available device once when the available devices are first known,
* and every time that they change
* @type {string}
*
* Properties:
* audio_input_device_count: the number of audio input devices available at
* the time the event was sent.
* audio_output_device_count: the number of audio output devices available
* at the time the event was sent.
* video_input_device_count: the number of video input devices available at
* the time the event was sent.
* video_output_device_count: the number of video output devices available
* at the time the event was sent.
* device_id: an identifier of the device described in this event.
* device_group_id:
* device_kind: one of 'audioinput', 'audiooutput', 'videoinput' or
* 'videooutput'.
* device_label: a string which describes the device.
*/
export const AVAILABLE_DEVICE: string;
/**
* This appears to be fired only in certain cases when the XMPP connection
* disconnects (and it was intentional?). It is currently never observed to
* fire in production.
*
* TODO: document
*
* Properties:
* message: an error message
*/
export const CONNECTION_DISCONNECTED: "connection.disconnected";
/**
* Indicates that the user of the application provided feedback in terms of a
* rating (an integer from 1 to 5) and an optional comment.
* Properties:
* value: the user's rating (an integer from 1 to 5)
* comment: the user's comment
*/
export const FEEDBACK: "feedback";
/**
* Indicates the duration of a particular phase of the ICE connectivity
* establishment.
*
* Properties:
* phase: the ICE phase (e.g. 'gathering', 'checking', 'establishment')
* value: the duration in milliseconds.
* p2p: whether the associated ICE connection is p2p or towards a
* jitsi-videobridge
* initiator: whether the local Jingle peer is the initiator or responder
* in the Jingle session. XXX we probably actually care about the ICE
* role (controlling vs controlled), and we assume that this correlates
* with the Jingle initiator.
*/
export const ICE_DURATION: "ice.duration";
/**
* Indicates the difference in milliseconds between the ICE establishment time
* for the P2P and JVB connections (e.g. a value of 10 would indicate that the
* P2P connection took 10ms more than JVB connection to establish).
*
* Properties:
* value: the difference in establishment durations in milliseconds.
*
*/
export const ICE_ESTABLISHMENT_DURATION_DIFF: "ice.establishment.duration.diff";
/**
* Indicates that the ICE state has changed.
*
* Properties:
* state: the ICE state which was entered (e.g. 'checking', 'connected',
* 'completed', etc).
* value: the time in milliseconds (as reported by
* window.performance.now()) that the state change occurred.
* p2p: whether the associated ICE connection is p2p or towards a
* jitsi-videobridge
* signalingState: The signaling state of the associated PeerConnection
* reconnect: whether the associated Jingle session is in the process of
* reconnecting (or is it ICE? TODO: verify/fix the documentation)
*/
export const ICE_STATE_CHANGED: "ice.state.changed";
/**
* Indicates that no bytes have been sent for the track.
*
* Properties:
* mediaType: the media type of the local track ('audio' or 'video').
*/
export const NO_BYTES_SENT: "track.no-bytes-sent";
/**
* Indicates that a track was unmuted (?).
*
* Properties:
* mediaType: the media type of the local track ('audio' or 'video').
* trackType: the type of the track ('local' or 'remote').
* value: TODO: document
*/
export const TRACK_UNMUTED: "track.unmuted";
export function createBridgeDownEvent(): {
action: string;
actionSubject: string;
type: string;
};
export function createConnectionFailedEvent(errorType: any, errorMessage: any, details: any): {
type: string;
action: string;
attributes: any;
};
export function createConnectionStageReachedEvent(stage: any, attributes: any): {
action: string;
actionSubject: any;
attributes: any;
source: string;
type: string;
};
export function createE2eRttEvent(participantId: any, region: any, rtt: any): {
attributes: {
participant_id: any;
region: any;
rtt: any;
};
name: string;
type: string;
};
export function createFocusLeftEvent(): {
action: string;
actionSubject: string;
type: string;
};
export function createGetUserMediaEvent(action: any, attributes?: {}): {
type: string;
source: string;
name: string;
};
export function createParticipantConnectionStatusEvent(attributes?: {}): {
type: string;
source: string;
name: string;
};
export function createJingleEvent(action: any, attributes?: {}): {
type: string;
action: any;
source: string;
attributes: {};
};
export function createNoDataFromSourceEvent(mediaType: string, value: any): {
attributes: {
media_type: string;
value: any;
};
action: string;
type: string;
};
export function createP2PEvent(action: any, attributes?: {}): {
type: string;
action: any;
source: string;
attributes: {};
};
export function createRemotelyMutedEvent(): {
type: string;
action: string;
};
export function createRtpStatsEvent(attributes: any): {
type: string;
action: string;
attributes: any;
};
export function createRttByRegionEvent(attributes: any): {
type: string;
action: string;
attributes: any;
};
export function createTransportStatsEvent(attributes: any): {
type: string;
action: string;
attributes: any;
};
export function createBridgeChannelClosedEvent(code: string, reason: string): {
type: string;
action: string;
attributes: {
code: string;
reason: string;
};
};
export function createTtfmEvent(attributes: any): {
action: string;
actionSubject: any;
attributes: any;
source: string;
type: string;
}; | the_stack |
import {
hasOwnProperty,
getTypeOf,
isPlainObject,
PlainObject,
assertIsFunction
} from 'core-helpers';
import omit from 'lodash/omit';
import cloneDeep from 'lodash/cloneDeep';
import isEmpty from 'lodash/isEmpty';
import type {Attribute} from './attribute';
import {isComponentClassOrInstance} from '../utilities';
export type AttributeSelector = boolean | PlainObject;
/**
* @typedef AttributeSelector
*
* An `AttributeSelector` allows you to select some attributes of a component.
*
* The simplest `AttributeSelector` is `true`, which means that all the attributes are selected.
* Another possible `AttributeSelector` is `false`, which means that no attributes are selected.
*
* To select some specific attributes, you can use a plain object where:
*
* * The keys are the name of the attributes you want to select.
* * The values are a boolean or a nested object to select some attributes of a nested component.
*
* **Examples:**
*
* ```
* // Selects all the attributes
* true
*
* // Excludes all the attributes
* false
*
* // Selects `title`
* {title: true}
*
* // Selects also `title` (`summary` is not selected)
* {title: true, summary: false}
*
* // Selects `title` and `summary`
* {title: true, summary: true}
*
* // Selects `title`, `movieDetails.duration`, and `movieDetails.aspectRatio`
* {
* title: true,
* movieDetails: {
* duration: true,
* aspectRatio: true
* }
* }
* ```
*/
/**
* Creates an `AttributeSelector` from the specified names.
*
* @param names An array of strings.
*
* @returns An `AttributeSelector`.
*
* @example
* ```
* createAttributeSelectorFromNames(['title', 'summary']);
* // => {title: true, summary: true}
* ```
*
* @category Functions
*/
export function createAttributeSelectorFromNames(names: string[]) {
const attributeSelector: AttributeSelector = {};
for (const name of names) {
attributeSelector[name] = true;
}
return attributeSelector;
}
/**
* Creates an `AttributeSelector` from an attribute iterator.
*
* @param attributes An [`Attribute`](https://layrjs.com/docs/v2/reference/attribute) iterator.
*
* @returns An `AttributeSelector`.
*
* @example
* ```
* createAttributeSelectorFromAttributes(Movie.prototype.getAttributes());
* // => {title: true, summary: true, movieDetails: true}
* ```
*
* @category Functions
*/
export function createAttributeSelectorFromAttributes(attributes: Iterable<Attribute>) {
const attributeSelector: AttributeSelector = {};
for (const attribute of attributes) {
attributeSelector[attribute.getName()] = true;
}
return attributeSelector;
}
/**
* Gets an entry of an `AttributeSelector`.
*
* @param attributeSelector An `AttributeSelector`.
* @param name The name of the entry to get.
*
* @returns An `AttributeSelector`.
*
* @example
* ```
* getFromAttributeSelector(true, 'title');
* // => true
*
* getFromAttributeSelector(false, 'title');
* // => false
*
* getFromAttributeSelector({title: true}, 'title');
* // => true
*
* getFromAttributeSelector({title: true}, 'summary');
* // => false
*
* getFromAttributeSelector({movieDetails: {duration: true}}, 'movieDetails');
* // => {duration: true}
* ```
*
* @category Functions
*/
export function getFromAttributeSelector(
attributeSelector: AttributeSelector,
name: string
): AttributeSelector {
attributeSelector = normalizeAttributeSelector(attributeSelector);
if (typeof attributeSelector === 'boolean') {
return attributeSelector;
}
return normalizeAttributeSelector(attributeSelector[name]);
}
/**
* Returns an `AttributeSelector` where an entry of the specified `AttributeSelector` is set with another `AttributeSelector`.
*
* @param attributeSelector An `AttributeSelector`.
* @param name The name of the entry to set.
* @param subattributeSelector Another `AttributeSelector`.
*
* @returns A new `AttributeSelector`.
*
* @example
* ```
* setWithinAttributeSelector({title: true}, 'summary', true);
* // => {title: true, summary: true}
*
* setWithinAttributeSelector({title: true}, 'summary', false);
* // => {title: true}
*
* setWithinAttributeSelector({title: true, summary: true}, 'summary', false);
* // => {title: true}
*
* setWithinAttributeSelector({title: true}, 'movieDetails', {duration: true});
* // => {title: true, movieDetails: {duration: true}}
* ```
*
* @category Functions
*/
export function setWithinAttributeSelector(
attributeSelector: AttributeSelector,
name: string,
subattributeSelector: AttributeSelector
): AttributeSelector {
attributeSelector = normalizeAttributeSelector(attributeSelector);
if (typeof attributeSelector === 'boolean') {
return attributeSelector;
}
subattributeSelector = normalizeAttributeSelector(subattributeSelector);
if (subattributeSelector === false) {
return omit(attributeSelector, name);
}
return {...attributeSelector, [name]: subattributeSelector};
}
/**
* Clones an `AttributeSelector`.
*
* @param attributeSelector An `AttributeSelector`.
*
* @returns A new `AttributeSelector`.
*
* @example
* ```
* cloneAttributeSelector(true);
* // => true
*
* cloneAttributeSelector(false);
* // => false
*
* cloneAttributeSelector({title: true, movieDetails: {duration: true});
* // => {title: true, movieDetails: {duration: true}
* ```
*
* @category Functions
*/
export function cloneAttributeSelector(attributeSelector: AttributeSelector) {
return cloneDeep(attributeSelector);
}
/**
* Returns whether an `AttributeSelector` is equal to another `AttributeSelector`.
*
* @param attributeSelector An `AttributeSelector`.
* @param otherAttributeSelector Another `AttributeSelector`.
*
* @returns A boolean.
*
* @example
* ```
* attributeSelectorsAreEqual({title: true}, {title: true});
* // => true
*
* attributeSelectorsAreEqual({title: true, summary: false}, {title: true});
* // => true
*
* attributeSelectorsAreEqual({title: true}, {summary: true});
* // => false
* ```
*
* @category Functions
*/
export function attributeSelectorsAreEqual(
attributeSelector: AttributeSelector,
otherAttributeSelector: AttributeSelector
) {
return (
attributeSelector === otherAttributeSelector ||
(attributeSelectorIncludes(attributeSelector, otherAttributeSelector) &&
attributeSelectorIncludes(otherAttributeSelector, attributeSelector))
);
}
/**
* Returns whether an `AttributeSelector` includes another `AttributeSelector`.
*
* @param attributeSelector An `AttributeSelector`.
* @param otherAttributeSelector Another `AttributeSelector`.
*
* @returns A boolean.
*
* @example
* ```
* attributeSelectorIncludes({title: true}, {title: true});
* // => true
*
* attributeSelectorIncludes({title: true, summary: true}, {title: true});
* // => true
*
* attributeSelectorIncludes({title: true}, {summary: true});
* // => false
* ```
*
* @category Functions
*/
export function attributeSelectorIncludes(
attributeSelector: AttributeSelector,
otherAttributeSelector: AttributeSelector
) {
attributeSelector = normalizeAttributeSelector(attributeSelector);
otherAttributeSelector = normalizeAttributeSelector(otherAttributeSelector);
if (attributeSelector === otherAttributeSelector) {
return true;
}
if (typeof attributeSelector === 'boolean') {
return attributeSelector;
}
if (typeof otherAttributeSelector === 'boolean') {
return !otherAttributeSelector;
}
for (const [name, otherSubattributeSelector] of Object.entries(otherAttributeSelector)) {
const subattributeSelector = attributeSelector[name];
if (!attributeSelectorIncludes(subattributeSelector, otherSubattributeSelector)) {
return false;
}
}
return true;
}
/**
* Returns an `AttributeSelector` which is the result of merging an `AttributeSelector` with another `AttributeSelector`.
*
* @param attributeSelector An `AttributeSelector`.
* @param otherAttributeSelector Another `AttributeSelector`.
*
* @returns A new `AttributeSelector`.
*
* @example
* ```
* mergeAttributeSelectors({title: true}, {title: true});
* // => {title: true}
*
* mergeAttributeSelectors({title: true}, {summary: true});
* // => {title: true, summary: true}
*
* mergeAttributeSelectors({title: true, summary: true}, {summary: false});
* // => {title: true}
* ```
*
* @category Functions
*/
export function mergeAttributeSelectors(
attributeSelector: AttributeSelector,
otherAttributeSelector: AttributeSelector
): AttributeSelector {
attributeSelector = normalizeAttributeSelector(attributeSelector);
otherAttributeSelector = normalizeAttributeSelector(otherAttributeSelector);
if (attributeSelector === true) {
return true;
}
if (attributeSelector === false) {
return otherAttributeSelector;
}
if (otherAttributeSelector === true) {
return true;
}
if (otherAttributeSelector === false) {
return attributeSelector;
}
for (const [name, otherSubattributeSelector] of Object.entries(otherAttributeSelector)) {
const subattributeSelector = (attributeSelector as PlainObject)[name];
attributeSelector = setWithinAttributeSelector(
attributeSelector,
name,
mergeAttributeSelectors(subattributeSelector, otherSubattributeSelector)
);
}
return attributeSelector;
}
/**
* Returns an `AttributeSelector` which is the result of the intersection of an `AttributeSelector` with another `AttributeSelector`.
*
* @param attributeSelector An `AttributeSelector`.
* @param otherAttributeSelector Another `AttributeSelector`.
*
* @returns A new `AttributeSelector`.
*
* @example
* ```
* intersectAttributeSelectors({title: true, summary: true}, {title: true});
* // => {title: true}
*
* intersectAttributeSelectors({title: true}, {summary: true});
* // => {}
* ```
*
* @category Functions
*/
export function intersectAttributeSelectors(
attributeSelector: AttributeSelector,
otherAttributeSelector: AttributeSelector
): AttributeSelector {
attributeSelector = normalizeAttributeSelector(attributeSelector);
otherAttributeSelector = normalizeAttributeSelector(otherAttributeSelector);
if (attributeSelector === false || otherAttributeSelector === false) {
return false;
}
if (attributeSelector === true) {
return otherAttributeSelector;
}
if (otherAttributeSelector === true) {
return attributeSelector;
}
let intersectedAttributeSelector = {};
for (const [name, otherSubattributeSelector] of Object.entries(otherAttributeSelector)) {
const subattributeSelector = (attributeSelector as PlainObject)[name];
intersectedAttributeSelector = setWithinAttributeSelector(
intersectedAttributeSelector,
name,
intersectAttributeSelectors(subattributeSelector, otherSubattributeSelector)
);
}
return intersectedAttributeSelector;
}
/**
* Returns an `AttributeSelector` which is the result of removing an `AttributeSelector` from another `AttributeSelector`.
*
* @param attributeSelector An `AttributeSelector`.
* @param otherAttributeSelector Another `AttributeSelector`.
*
* @returns A new `AttributeSelector`.
*
* @example
* ```
* removeFromAttributeSelector({title: true, summary: true}, {summary: true});
* // => {title: true}
*
* removeFromAttributeSelector({title: true}, {title: true});
* // => {}
* ```
*
* @category Functions
*/
export function removeFromAttributeSelector(
attributeSelector: AttributeSelector,
otherAttributeSelector: AttributeSelector
): AttributeSelector {
attributeSelector = normalizeAttributeSelector(attributeSelector);
otherAttributeSelector = normalizeAttributeSelector(otherAttributeSelector);
if (otherAttributeSelector === true) {
return false;
}
if (otherAttributeSelector === false) {
return attributeSelector;
}
if (attributeSelector === true) {
throw new Error(
"Cannot remove an 'object' attribute selector from a 'true' attribute selector"
);
}
if (attributeSelector === false) {
return false;
}
for (const [name, otherSubattributeSelector] of Object.entries(otherAttributeSelector)) {
const subattributeSelector = (attributeSelector as PlainObject)[name];
attributeSelector = setWithinAttributeSelector(
attributeSelector,
name,
removeFromAttributeSelector(subattributeSelector, otherSubattributeSelector)
);
}
return attributeSelector;
}
export function iterateOverAttributeSelector(attributeSelector: AttributeSelector) {
return {
*[Symbol.iterator]() {
for (const [name, subattributeSelector] of Object.entries(attributeSelector)) {
const normalizedSubattributeSelector = normalizeAttributeSelector(subattributeSelector);
if (normalizedSubattributeSelector !== false) {
yield [name, normalizedSubattributeSelector] as [string, AttributeSelector];
}
}
}
};
}
type PickFromAttributeSelectorResult<Value> = Value extends Array<infer Element>
? Array<PickFromAttributeSelectorResult<Element>>
: Value extends object
? object
: Value;
export function pickFromAttributeSelector<Value>(
value: Value,
attributeSelector: AttributeSelector,
options?: {includeAttributeNames?: string[]}
): PickFromAttributeSelectorResult<Value>;
export function pickFromAttributeSelector(
value: unknown,
attributeSelector: AttributeSelector,
options: {includeAttributeNames?: string[]} = {}
) {
attributeSelector = normalizeAttributeSelector(attributeSelector);
if (attributeSelector === false) {
throw new Error(
`Cannot pick attributes from a value when the specified attribute selector is 'false'`
);
}
const {includeAttributeNames = []} = options;
return _pick(value, attributeSelector, {includeAttributeNames});
}
function _pick(
value: unknown,
attributeSelector: AttributeSelector,
{includeAttributeNames}: {includeAttributeNames: string[]}
): unknown {
if (attributeSelector === true) {
return value;
}
if (value === undefined) {
return undefined;
}
if (Array.isArray(value)) {
const array = value;
return array.map((value) => _pick(value, attributeSelector, {includeAttributeNames}));
}
const isComponent = isComponentClassOrInstance(value);
if (!(isComponent || isPlainObject(value))) {
throw new Error(
`Cannot pick attributes from a value that is not a component, a plain object, or an array (value type: '${getTypeOf(
value
)}')`
);
}
const componentOrObject = value as PlainObject;
const result: PlainObject = {};
if (!isComponent) {
for (const name of includeAttributeNames) {
if (hasOwnProperty(componentOrObject, name)) {
result[name] = componentOrObject[name];
}
}
}
for (const [name, subattributeSelector] of iterateOverAttributeSelector(attributeSelector)) {
const value = isComponent
? componentOrObject.getAttribute(name).getValue()
: componentOrObject[name];
result[name] = _pick(value, subattributeSelector, {includeAttributeNames});
}
return result;
}
type TraverseIteratee = (
value: any,
attributeSelector: AttributeSelector,
context: TraverseContext
) => void;
type TraverseContext = {name?: string; object?: object; isArray?: boolean};
type TraverseOptions = {includeSubtrees?: boolean; includeLeafs?: boolean};
export function traverseAttributeSelector(
value: any,
attributeSelector: AttributeSelector,
iteratee: TraverseIteratee,
options: TraverseOptions = {}
) {
attributeSelector = normalizeAttributeSelector(attributeSelector);
assertIsFunction(iteratee);
const {includeSubtrees = false, includeLeafs = true} = options;
if (attributeSelector === false) {
return;
}
_traverse(value, attributeSelector, iteratee, {
includeSubtrees,
includeLeafs,
_context: {},
_isDeep: false
});
}
function _traverse(
value: any,
attributeSelector: AttributeSelector,
iteratee: TraverseIteratee,
{
includeSubtrees,
includeLeafs,
_context,
_isDeep
}: TraverseOptions & {_context: TraverseContext; _isDeep: boolean}
) {
if (attributeSelector === true || value === undefined) {
if (includeLeafs) {
iteratee(value, attributeSelector, _context);
}
return;
}
if (Array.isArray(value)) {
const array = value;
for (const value of array) {
_traverse(value, attributeSelector, iteratee, {
includeSubtrees,
includeLeafs,
_context: {..._context, isArray: true},
_isDeep
});
}
return;
}
const isComponent = isComponentClassOrInstance(value);
if (!(isComponent || isPlainObject(value))) {
throw new Error(
`Cannot traverse attributes from a value that is not a component, a plain object, or an array (value type: '${getTypeOf(
value
)}')`
);
}
const componentOrObject = value;
if (_isDeep && includeSubtrees) {
iteratee(componentOrObject, attributeSelector, _context);
}
for (const [name, subattributeSelector] of iterateOverAttributeSelector(attributeSelector)) {
if (isComponent && !componentOrObject.getAttribute(name).isSet()) {
continue;
}
const value = componentOrObject[name];
_traverse(value, subattributeSelector, iteratee, {
includeSubtrees,
includeLeafs,
_context: {name, object: componentOrObject},
_isDeep: true
});
}
}
export function trimAttributeSelector(attributeSelector: AttributeSelector): AttributeSelector {
attributeSelector = normalizeAttributeSelector(attributeSelector);
if (typeof attributeSelector === 'boolean') {
return attributeSelector;
}
for (const [name, subattributeSelector] of Object.entries(attributeSelector)) {
attributeSelector = setWithinAttributeSelector(
attributeSelector,
name,
trimAttributeSelector(subattributeSelector)
);
}
if (isEmpty(attributeSelector)) {
return false;
}
return attributeSelector;
}
export function normalizeAttributeSelector(attributeSelector: any): AttributeSelector {
if (attributeSelector === undefined) {
return false;
}
if (typeof attributeSelector === 'boolean') {
return attributeSelector;
}
if (isPlainObject(attributeSelector)) {
return attributeSelector;
}
throw new Error(
`Expected a valid attribute selector, but received a value of type '${getTypeOf(
attributeSelector
)}'`
);
} | the_stack |
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest';
import * as models from '../models';
/**
* @class
* Operations
* __NOTE__: An instance of this class is automatically created for an
* instance of the AzureMachineLearningWorkspaces.
*/
export interface Operations {
/**
* Lists all of the available Azure Machine Learning Workspaces REST API
* operations.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>;
/**
* Lists all of the available Azure Machine Learning Workspaces REST API
* operations.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {OperationListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {OperationListResult} [result] - The deserialized result object if an error did not occur.
* See {@link OperationListResult} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>;
list(callback: ServiceCallback<models.OperationListResult>): void;
list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void;
}
/**
* @class
* Workspaces
* __NOTE__: An instance of this class is automatically created for an
* instance of the AzureMachineLearningWorkspaces.
*/
export interface Workspaces {
/**
* Gets the properties of the specified machine learning workspace.
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Workspace>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Workspace>>;
/**
* Gets the properties of the specified machine learning workspace.
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {Workspace} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {Workspace} [result] - The deserialized result object if an error did not occur.
* See {@link Workspace} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceGroupName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Workspace>;
get(resourceGroupName: string, workspaceName: string, callback: ServiceCallback<models.Workspace>): void;
get(resourceGroupName: string, workspaceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Workspace>): void;
/**
* Creates or updates a workspace with the specified parameters.
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {object} parameters The parameters for creating or updating a machine
* learning workspace.
*
* @param {string} [parameters.description] The description of this workspace.
*
* @param {string} [parameters.friendlyName] The friendly name for this
* workspace. This name in mutable
*
* @param {string} [parameters.batchaiWorkspace] ARM id of the Batch AI
* workspace associated with this workspace. This cannot be changed once the
* workspace has been created
*
* @param {string} [parameters.keyVault] ARM id of the key vault associated
* with this workspace. This cannot be changed once the workspace has been
* created
*
* @param {string} [parameters.applicationInsights] ARM id of the application
* insights associated with this workspace. This cannot be changed once the
* workspace has been created
*
* @param {string} [parameters.containerRegistry] ARM id of the container
* registry associated with this workspace. This cannot be changed once the
* workspace has been created
*
* @param {string} [parameters.storageAccount] ARM id of the storage account
* associated with this workspace. This cannot be changed once the workspace
* has been created
*
* @param {string} [parameters.discoveryUrl] Url for the discovery service to
* identify regional endpoints for machine learning experimentation services
*
* @param {string} [parameters.location] Specifies the location of the
* resource.
*
* @param {object} [parameters.tags] Contains resource tags defined as
* key/value pairs.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Workspace>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, parameters: models.Workspace, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Workspace>>;
/**
* Creates or updates a workspace with the specified parameters.
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {object} parameters The parameters for creating or updating a machine
* learning workspace.
*
* @param {string} [parameters.description] The description of this workspace.
*
* @param {string} [parameters.friendlyName] The friendly name for this
* workspace. This name in mutable
*
* @param {string} [parameters.batchaiWorkspace] ARM id of the Batch AI
* workspace associated with this workspace. This cannot be changed once the
* workspace has been created
*
* @param {string} [parameters.keyVault] ARM id of the key vault associated
* with this workspace. This cannot be changed once the workspace has been
* created
*
* @param {string} [parameters.applicationInsights] ARM id of the application
* insights associated with this workspace. This cannot be changed once the
* workspace has been created
*
* @param {string} [parameters.containerRegistry] ARM id of the container
* registry associated with this workspace. This cannot be changed once the
* workspace has been created
*
* @param {string} [parameters.storageAccount] ARM id of the storage account
* associated with this workspace. This cannot be changed once the workspace
* has been created
*
* @param {string} [parameters.discoveryUrl] Url for the discovery service to
* identify regional endpoints for machine learning experimentation services
*
* @param {string} [parameters.location] Specifies the location of the
* resource.
*
* @param {object} [parameters.tags] Contains resource tags defined as
* key/value pairs.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {Workspace} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {Workspace} [result] - The deserialized result object if an error did not occur.
* See {@link Workspace} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
createOrUpdate(resourceGroupName: string, workspaceName: string, parameters: models.Workspace, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Workspace>;
createOrUpdate(resourceGroupName: string, workspaceName: string, parameters: models.Workspace, callback: ServiceCallback<models.Workspace>): void;
createOrUpdate(resourceGroupName: string, workspaceName: string, parameters: models.Workspace, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Workspace>): void;
/**
* Deletes a machine learning workspace.
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Deletes a machine learning workspace.
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteMethod(resourceGroupName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(resourceGroupName: string, workspaceName: string, callback: ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, workspaceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Updates a machine learning workspace with the specified parameters.
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {object} parameters The parameters for updating a machine learning
* workspace.
*
* @param {object} [parameters.tags] The resource tags for the machine learning
* workspace.
*
* @param {string} [parameters.description] The description of this workspace.
*
* @param {string} [parameters.friendlyName] The friendly name for this
* workspace.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<Workspace>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
updateWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, parameters: models.WorkspaceUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Workspace>>;
/**
* Updates a machine learning workspace with the specified parameters.
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {object} parameters The parameters for updating a machine learning
* workspace.
*
* @param {object} [parameters.tags] The resource tags for the machine learning
* workspace.
*
* @param {string} [parameters.description] The description of this workspace.
*
* @param {string} [parameters.friendlyName] The friendly name for this
* workspace.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {Workspace} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {Workspace} [result] - The deserialized result object if an error did not occur.
* See {@link Workspace} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
update(resourceGroupName: string, workspaceName: string, parameters: models.WorkspaceUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Workspace>;
update(resourceGroupName: string, workspaceName: string, parameters: models.WorkspaceUpdateParameters, callback: ServiceCallback<models.Workspace>): void;
update(resourceGroupName: string, workspaceName: string, parameters: models.WorkspaceUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Workspace>): void;
/**
* Lists all the available machine learning workspaces under the specified
* resource group.
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.skiptoken] Continuation token for pagination.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<WorkspaceListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WorkspaceListResult>>;
/**
* Lists all the available machine learning workspaces under the specified
* resource group.
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.skiptoken] Continuation token for pagination.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {WorkspaceListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {WorkspaceListResult} [result] - The deserialized result object if an error did not occur.
* See {@link WorkspaceListResult} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByResourceGroup(resourceGroupName: string, options?: { skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.WorkspaceListResult>;
listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.WorkspaceListResult>): void;
listByResourceGroup(resourceGroupName: string, options: { skiptoken? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WorkspaceListResult>): void;
/**
* Lists all the keys associated with this workspace. This includes keys for
* the storage account, app insights and password for container registry
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ListWorkspaceKeysResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listKeysWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ListWorkspaceKeysResult>>;
/**
* Lists all the keys associated with this workspace. This includes keys for
* the storage account, app insights and password for container registry
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ListWorkspaceKeysResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ListWorkspaceKeysResult} [result] - The deserialized result object if an error did not occur.
* See {@link ListWorkspaceKeysResult} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listKeys(resourceGroupName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ListWorkspaceKeysResult>;
listKeys(resourceGroupName: string, workspaceName: string, callback: ServiceCallback<models.ListWorkspaceKeysResult>): void;
listKeys(resourceGroupName: string, workspaceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ListWorkspaceKeysResult>): void;
/**
* Resync all the keys associated with this workspace. This includes keys for
* the storage account, app insights and password for container registry
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
resyncKeysWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Resync all the keys associated with this workspace. This includes keys for
* the storage account, app insights and password for container registry
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
resyncKeys(resourceGroupName: string, workspaceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
resyncKeys(resourceGroupName: string, workspaceName: string, callback: ServiceCallback<void>): void;
resyncKeys(resourceGroupName: string, workspaceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Lists all the available machine learning workspaces under the specified
* subscription.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.skiptoken] Continuation token for pagination.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<WorkspaceListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listBySubscriptionWithHttpOperationResponse(options?: { skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WorkspaceListResult>>;
/**
* Lists all the available machine learning workspaces under the specified
* subscription.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.skiptoken] Continuation token for pagination.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {WorkspaceListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {WorkspaceListResult} [result] - The deserialized result object if an error did not occur.
* See {@link WorkspaceListResult} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listBySubscription(options?: { skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.WorkspaceListResult>;
listBySubscription(callback: ServiceCallback<models.WorkspaceListResult>): void;
listBySubscription(options: { skiptoken? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WorkspaceListResult>): void;
/**
* Lists all the available machine learning workspaces under the specified
* resource group.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<WorkspaceListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WorkspaceListResult>>;
/**
* Lists all the available machine learning workspaces under the specified
* resource group.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {WorkspaceListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {WorkspaceListResult} [result] - The deserialized result object if an error did not occur.
* See {@link WorkspaceListResult} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByResourceGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WorkspaceListResult>;
listByResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.WorkspaceListResult>): void;
listByResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WorkspaceListResult>): void;
/**
* Lists all the available machine learning workspaces under the specified
* subscription.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<WorkspaceListResult>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listBySubscriptionNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.WorkspaceListResult>>;
/**
* Lists all the available machine learning workspaces under the specified
* subscription.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {WorkspaceListResult} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {WorkspaceListResult} [result] - The deserialized result object if an error did not occur.
* See {@link WorkspaceListResult} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listBySubscriptionNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.WorkspaceListResult>;
listBySubscriptionNext(nextPageLink: string, callback: ServiceCallback<models.WorkspaceListResult>): void;
listBySubscriptionNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.WorkspaceListResult>): void;
}
/**
* @class
* MachineLearningCompute
* __NOTE__: An instance of this class is automatically created for an
* instance of the AzureMachineLearningWorkspaces.
*/
export interface MachineLearningCompute {
/**
* Gets computes in specified workspace.
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.skiptoken] Continuation token for pagination.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<PaginatedComputeResourcesList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByWorkspaceWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, options?: { skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PaginatedComputeResourcesList>>;
/**
* Gets computes in specified workspace.
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.skiptoken] Continuation token for pagination.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {PaginatedComputeResourcesList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {PaginatedComputeResourcesList} [result] - The deserialized result object if an error did not occur.
* See {@link PaginatedComputeResourcesList} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByWorkspace(resourceGroupName: string, workspaceName: string, options?: { skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.PaginatedComputeResourcesList>;
listByWorkspace(resourceGroupName: string, workspaceName: string, callback: ServiceCallback<models.PaginatedComputeResourcesList>): void;
listByWorkspace(resourceGroupName: string, workspaceName: string, options: { skiptoken? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PaginatedComputeResourcesList>): void;
/**
* Gets compute definition by its name. Any secrets (storage keys, service
* credentials, etc) are not returned - use 'keys' nested resource to get them.
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {string} computeName Name of the Azure Machine Learning compute.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ComputeResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, computeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ComputeResource>>;
/**
* Gets compute definition by its name. Any secrets (storage keys, service
* credentials, etc) are not returned - use 'keys' nested resource to get them.
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {string} computeName Name of the Azure Machine Learning compute.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ComputeResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ComputeResource} [result] - The deserialized result object if an error did not occur.
* See {@link ComputeResource} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
get(resourceGroupName: string, workspaceName: string, computeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ComputeResource>;
get(resourceGroupName: string, workspaceName: string, computeName: string, callback: ServiceCallback<models.ComputeResource>): void;
get(resourceGroupName: string, workspaceName: string, computeName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ComputeResource>): void;
/**
* Creates or updates compute. This call will overwrite a compute if it exists.
* This is a nonrecoverable operation. If your intent is to create a new
* compute, do a GET first to verify that it does not exist yet.
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {string} computeName Name of the Azure Machine Learning compute.
*
* @param {object} parameters Payload with Machine Learning compute definition.
*
* @param {object} [parameters.properties] Compute properties
*
* @param {string} [parameters.properties.computeLocation] Location for the
* underlying compute
*
* @param {string} [parameters.properties.description] The description of the
* Machine Learning compute.
*
* @param {string} [parameters.properties.resourceId] ARM resource id of the
* compute
*
* @param {string} parameters.properties.computeType Polymorphic Discriminator
*
* @param {string} [parameters.location] Specifies the location of the
* resource.
*
* @param {object} [parameters.tags] Contains resource tags defined as
* key/value pairs.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ComputeResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
createOrUpdateWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, computeName: string, parameters: models.ComputeResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ComputeResource>>;
/**
* Creates or updates compute. This call will overwrite a compute if it exists.
* This is a nonrecoverable operation. If your intent is to create a new
* compute, do a GET first to verify that it does not exist yet.
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {string} computeName Name of the Azure Machine Learning compute.
*
* @param {object} parameters Payload with Machine Learning compute definition.
*
* @param {object} [parameters.properties] Compute properties
*
* @param {string} [parameters.properties.computeLocation] Location for the
* underlying compute
*
* @param {string} [parameters.properties.description] The description of the
* Machine Learning compute.
*
* @param {string} [parameters.properties.resourceId] ARM resource id of the
* compute
*
* @param {string} parameters.properties.computeType Polymorphic Discriminator
*
* @param {string} [parameters.location] Specifies the location of the
* resource.
*
* @param {object} [parameters.tags] Contains resource tags defined as
* key/value pairs.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ComputeResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ComputeResource} [result] - The deserialized result object if an error did not occur.
* See {@link ComputeResource} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
createOrUpdate(resourceGroupName: string, workspaceName: string, computeName: string, parameters: models.ComputeResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ComputeResource>;
createOrUpdate(resourceGroupName: string, workspaceName: string, computeName: string, parameters: models.ComputeResource, callback: ServiceCallback<models.ComputeResource>): void;
createOrUpdate(resourceGroupName: string, workspaceName: string, computeName: string, parameters: models.ComputeResource, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ComputeResource>): void;
/**
* Deletes specified Machine Learning compute.
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {string} computeName Name of the Azure Machine Learning compute.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, computeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Deletes specified Machine Learning compute.
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {string} computeName Name of the Azure Machine Learning compute.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
deleteMethod(resourceGroupName: string, workspaceName: string, computeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteMethod(resourceGroupName: string, workspaceName: string, computeName: string, callback: ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, workspaceName: string, computeName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* System Update On Machine Learning compute.
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {string} computeName Name of the Azure Machine Learning compute.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
systemUpdateWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, computeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* System Update On Machine Learning compute.
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {string} computeName Name of the Azure Machine Learning compute.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
systemUpdate(resourceGroupName: string, workspaceName: string, computeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
systemUpdate(resourceGroupName: string, workspaceName: string, computeName: string, callback: ServiceCallback<void>): void;
systemUpdate(resourceGroupName: string, workspaceName: string, computeName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Gets secrets related to Machine Learning compute (storage keys, service
* credentials, etc).
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {string} computeName Name of the Azure Machine Learning compute.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ComputeSecrets>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listKeysWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, computeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ComputeSecrets>>;
/**
* Gets secrets related to Machine Learning compute (storage keys, service
* credentials, etc).
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {string} computeName Name of the Azure Machine Learning compute.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ComputeSecrets} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ComputeSecrets} [result] - The deserialized result object if an error did not occur.
* See {@link ComputeSecrets} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listKeys(resourceGroupName: string, workspaceName: string, computeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ComputeSecrets>;
listKeys(resourceGroupName: string, workspaceName: string, computeName: string, callback: ServiceCallback<models.ComputeSecrets>): void;
listKeys(resourceGroupName: string, workspaceName: string, computeName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ComputeSecrets>): void;
/**
* Creates or updates compute. This call will overwrite a compute if it exists.
* This is a nonrecoverable operation. If your intent is to create a new
* compute, do a GET first to verify that it does not exist yet.
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {string} computeName Name of the Azure Machine Learning compute.
*
* @param {object} parameters Payload with Machine Learning compute definition.
*
* @param {object} [parameters.properties] Compute properties
*
* @param {string} [parameters.properties.computeLocation] Location for the
* underlying compute
*
* @param {string} [parameters.properties.description] The description of the
* Machine Learning compute.
*
* @param {string} [parameters.properties.resourceId] ARM resource id of the
* compute
*
* @param {string} parameters.properties.computeType Polymorphic Discriminator
*
* @param {string} [parameters.location] Specifies the location of the
* resource.
*
* @param {object} [parameters.tags] Contains resource tags defined as
* key/value pairs.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<ComputeResource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
beginCreateOrUpdateWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, computeName: string, parameters: models.ComputeResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ComputeResource>>;
/**
* Creates or updates compute. This call will overwrite a compute if it exists.
* This is a nonrecoverable operation. If your intent is to create a new
* compute, do a GET first to verify that it does not exist yet.
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {string} computeName Name of the Azure Machine Learning compute.
*
* @param {object} parameters Payload with Machine Learning compute definition.
*
* @param {object} [parameters.properties] Compute properties
*
* @param {string} [parameters.properties.computeLocation] Location for the
* underlying compute
*
* @param {string} [parameters.properties.description] The description of the
* Machine Learning compute.
*
* @param {string} [parameters.properties.resourceId] ARM resource id of the
* compute
*
* @param {string} parameters.properties.computeType Polymorphic Discriminator
*
* @param {string} [parameters.location] Specifies the location of the
* resource.
*
* @param {object} [parameters.tags] Contains resource tags defined as
* key/value pairs.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {ComputeResource} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {ComputeResource} [result] - The deserialized result object if an error did not occur.
* See {@link ComputeResource} for more information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
beginCreateOrUpdate(resourceGroupName: string, workspaceName: string, computeName: string, parameters: models.ComputeResource, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ComputeResource>;
beginCreateOrUpdate(resourceGroupName: string, workspaceName: string, computeName: string, parameters: models.ComputeResource, callback: ServiceCallback<models.ComputeResource>): void;
beginCreateOrUpdate(resourceGroupName: string, workspaceName: string, computeName: string, parameters: models.ComputeResource, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ComputeResource>): void;
/**
* Deletes specified Machine Learning compute.
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {string} computeName Name of the Azure Machine Learning compute.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
beginDeleteMethodWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, computeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Deletes specified Machine Learning compute.
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {string} computeName Name of the Azure Machine Learning compute.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
beginDeleteMethod(resourceGroupName: string, workspaceName: string, computeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
beginDeleteMethod(resourceGroupName: string, workspaceName: string, computeName: string, callback: ServiceCallback<void>): void;
beginDeleteMethod(resourceGroupName: string, workspaceName: string, computeName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* System Update On Machine Learning compute.
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {string} computeName Name of the Azure Machine Learning compute.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
beginSystemUpdateWithHttpOperationResponse(resourceGroupName: string, workspaceName: string, computeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* System Update On Machine Learning compute.
*
* @param {string} resourceGroupName Name of the resource group in which
* workspace is located.
*
* @param {string} workspaceName Name of Azure Machine Learning workspace.
*
* @param {string} computeName Name of the Azure Machine Learning compute.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
beginSystemUpdate(resourceGroupName: string, workspaceName: string, computeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
beginSystemUpdate(resourceGroupName: string, workspaceName: string, computeName: string, callback: ServiceCallback<void>): void;
beginSystemUpdate(resourceGroupName: string, workspaceName: string, computeName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Gets computes in specified workspace.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<PaginatedComputeResourcesList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listByWorkspaceNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PaginatedComputeResourcesList>>;
/**
* Gets computes in specified workspace.
*
* @param {string} nextPageLink The NextLink from the previous successful call
* to List operation.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {ServiceCallback} [optionalCallback] - The optional callback.
*
* @returns {ServiceCallback|Promise} If a callback was passed as the last
* parameter then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned.
*
* @resolve {PaginatedComputeResourcesList} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*
* {ServiceCallback} optionalCallback(err, result, request, response)
*
* {Error|ServiceError} err - The Error object if an error occurred, null otherwise.
*
* {PaginatedComputeResourcesList} [result] - The deserialized result object if an error did not occur.
* See {@link PaginatedComputeResourcesList} for more
* information.
*
* {WebResource} [request] - The HTTP Request object if an error did not occur.
*
* {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur.
*/
listByWorkspaceNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.PaginatedComputeResourcesList>;
listByWorkspaceNext(nextPageLink: string, callback: ServiceCallback<models.PaginatedComputeResourcesList>): void;
listByWorkspaceNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PaginatedComputeResourcesList>): void;
} | the_stack |
import {LOCALES} from '../locales';
export default {
property: {
weight: 'peso',
label: 'etiqueta',
fillColor: 'color de relleno',
color: 'color',
coverage: 'cobertura',
strokeColor: 'color de trazo',
radius: 'radio',
outline: 'contorno',
stroke: 'trazo',
density: 'densidad',
height: 'altura',
sum: 'suma',
pointCount: 'Recuento de puntos'
},
placeholder: {
search: 'Busqueda',
selectField: 'Selecciona un campo',
yAxis: 'Eje Y',
selectType: 'Selecciona un Tipo',
selectValue: 'Selecciona un Valor',
enterValue: 'Entra un valor',
empty: 'vacio'
},
misc: {
by: '',
valuesIn: 'Valores en',
valueEquals: 'Valor igual a',
dataSource: 'Fuente de datos',
brushRadius: 'Radio del pincel (km)',
empty: ' '
},
mapLayers: {
title: 'Capas del mapa',
label: 'Etiqueta',
road: 'Carretera',
border: 'Frontera',
building: 'Edificio',
water: 'Agua',
land: 'Tierra',
'3dBuilding': 'Edificio 3D'
},
panel: {
text: {
label: 'etiqueta',
labelWithId: 'Etiqueta {labelId}',
fontSize: 'Tamaño de fuente',
fontColor: 'Color de fuente',
textAnchor: 'Anclaje del texto',
alignment: 'Alineación',
addMoreLabel: 'Añadir más etiquetas'
}
},
sidebar: {
panels: {
layer: 'Capas',
filter: 'Filtros',
interaction: 'Interacciones',
basemap: 'Mapa base'
}
},
layer: {
required: 'Requerido*',
radius: 'Radio',
color: 'Color',
fillColor: 'Color de relleno',
outline: 'Contorno',
weight: 'Grueso',
propertyBasedOn: '{property} basado en',
coverage: 'Cobertura',
stroke: 'Trazo',
strokeWidth: 'Grosor de trazo',
strokeColor: 'Color de trazo',
basic: 'Básico',
trailLength: 'Longitud de pista',
trailLengthDescription: 'Numero de segundos hasta que desaparezca el camino',
newLayer: 'nueva capa',
elevationByDescription: 'Si desactivado, la altura se basa en el recuento de puntos',
colorByDescription: 'Si desactivado, el color se basa en el recuento de puntos',
aggregateBy: '{field} agregado por',
'3DModel': 'Modelo 3D',
'3DModelOptions': 'Opciones del modelo 3D',
type: {
point: 'punto',
arc: 'arco',
line: 'línea',
grid: 'malla',
hexbin: 'hexbin',
polygon: 'polígono',
geojson: 'geojson',
cluster: 'cluster',
icon: 'icono',
heatmap: 'concentración',
hexagon: 'hexágono',
hexagonid: 'H3',
trip: 'viaje',
s2: 'S2',
'3d': '3D'
}
},
layerVisConfigs: {
angle: 'Ángulo',
strokeWidth: 'Ancho del trazo',
strokeWidthRange: 'Rango del ancho del trazo',
radius: 'Radio',
fixedRadius: 'Radio fijo a medir',
fixedRadiusDescription: 'Ajustar el radio al radio absoluto en metros, p.e. 5 a 5 metros',
radiusRange: 'Rango de radio',
clusterRadius: 'Radio del cluster en píxeles',
radiusRangePixels: 'Rango del radio en píxeles',
opacity: 'Opacidad',
coverage: 'Cobertura',
outline: 'Contorno',
colorRange: 'Rango de color',
stroke: 'Trazo',
strokeColor: 'Color de trazo',
strokeColorRange: 'Rango de color de trazo',
targetColor: 'Color destino',
colorAggregation: 'Agregación de color',
heightAggregation: 'Agregación de la altura',
resolutionRange: 'Rango de resolución',
sizeScale: 'Medida de escala',
worldUnitSize: 'Medida de la unidad mundial',
elevationScale: 'Escala de elevación',
enableElevationZoomFactor: 'Usar factor de zoom de elevación',
enableElevationZoomFactorDescription:
'Ajuste la altura / elevación según el factor de zoom actual',
enableHeightZoomFactor: 'Usar factor de zoom de altura',
heightScale: 'Escala de altura',
coverageRange: 'Rango de cobertura',
highPrecisionRendering: 'Representación de alta precisión',
highPrecisionRenderingDescription: 'La precisión alta tendrá un rendimiento más bajo',
height: 'Altura',
heightDescription:
'Haz clic en el botón de arriba a la derecha del mapa per cambiar a vista 3D',
fill: 'Rellenar',
enablePolygonHeight: 'Activar la altura del polígono',
showWireframe: 'Muestra esquemàtico',
weightIntensity: 'Intensidad de peso',
zoomScale: 'Escala de zoom',
heightRange: 'Rango de alturas',
heightMultiplier: 'Multiplicador de altura'
},
layerManager: {
addData: 'Añadir datos',
addLayer: 'Añadir capa',
layerBlending: 'Combinar capas'
},
mapManager: {
mapStyle: 'Estilo de mapa',
addMapStyle: 'Añadir estilo de mapa',
'3dBuildingColor': 'Color edificios 3D'
},
layerConfiguration: {
defaultDescription: 'Calcular {property} según el campo seleccionado',
howTo: 'How to'
},
filterManager: {
addFilter: 'Añadir filtro'
},
datasetTitle: {
showDataTable: 'Mostar la tabla de datos',
removeDataset: 'Eliminar conjunto de datos'
},
datasetInfo: {
rowCount: '{rowCount} files'
},
tooltip: {
hideLayer: 'Ocultar la capa',
showLayer: 'Mostrar la capa',
hideFeature: 'Ocultar el objeto',
showFeature: 'Mostrar el objeto',
hide: 'Ocultar',
show: 'Mostrar',
removeLayer: 'Eliminar capa',
layerSettings: 'Configuración de capa',
closePanel: 'Cerrar el panel actual',
switchToDualView: 'Cambiar a la vista de mapa dual',
showLegend: 'Mostrar leyenda',
disable3DMap: 'Desactivar mapa 3D',
DrawOnMap: 'Dibujar en el mapa',
selectLocale: 'Seleccionar configuración regional',
hideLayerPanel: 'Ocultar la tabla de capas',
showLayerPanel: 'Mostrar la tabla de capas',
moveToTop: 'Desplazar arriba de las capas de datos',
selectBaseMapStyle: 'Seleccionar estilo de mapa base',
delete: 'Borrar',
timePlayback: 'Reproducción de tiempo',
cloudStorage: 'Almacenaje en la nube',
'3DMap': 'Mapa 3D',
animationByWindow: 'Ventana Temporal Móvil',
animationByIncremental: 'Ventana Temporal Incremental',
speed: 'velocidad',
play: 'iniciar',
pause: 'pausar',
reset: 'reiniciar'
},
toolbar: {
exportImage: 'Exportar imagen',
exportData: 'Exportar datos',
exportMap: 'Exportar mapa',
shareMapURL: 'Compartir el enlace del mapa',
saveMap: 'Guardar mapa',
select: 'selecciona',
polygon: 'polígono',
rectangle: 'rectángulo',
hide: 'esconder',
show: 'mostrar',
...LOCALES
},
modal: {
title: {
deleteDataset: 'Borrar conjunto de datos',
addDataToMap: 'Añadir datos al mapa',
exportImage: 'Exportar imagen',
exportData: 'Exportar datos',
exportMap: 'Exportar mapa',
addCustomMapboxStyle: 'Añadir estilo de Mapbox propio',
saveMap: 'Guardar mapa',
shareURL: 'Compartir enlace'
},
button: {
delete: 'Borrar',
download: 'Descargar',
export: 'Exportar',
addStyle: 'Añadir estilo',
save: 'Guardar',
defaultCancel: 'Cancelar',
defaultConfirm: 'Confirmar'
},
exportImage: {
ratioTitle: 'Ratio',
ratioDescription: 'Esoger ratio por diversos usos.',
ratioOriginalScreen: 'Pantalla original',
ratioCustom: 'Personalizado',
ratio4_3: '4:3',
ratio16_9: '16:9',
resolutionTitle: 'Resolución',
resolutionDescription: 'Una alta resolución es mejor para las impresiones.',
mapLegendTitle: 'Leyenda del mapa',
mapLegendAdd: 'Añadir leyenda al mapa'
},
exportData: {
datasetTitle: 'Conjunto de datos',
datasetSubtitle: 'Escoger los conjuntos de datos a exportar',
allDatasets: 'Todos',
dataTypeTitle: 'Tipo de datos',
dataTypeSubtitle: 'Escoger el tipo de datos a exportar',
filterDataTitle: 'Filtrar datos',
filterDataSubtitle: 'Se puede escoger exportar los datos originales o filtrados',
filteredData: 'Datos filtrados',
unfilteredData: 'Datos sin filtrar',
fileCount: '{fileCount} Archivos',
rowCount: '{rowCount} Files'
},
deleteData: {
warning: 'estás a punto de borrar este conjunto de datos. Afectará a {length} capas'
},
addStyle: {
publishTitle: '1. Publicar tu estilo en Mapbox o proporcionar el token de acceso',
publishSubtitle1: 'Puedes crear el tu propio estilo de mapa en',
publishSubtitle2: 'y',
publishSubtitle3: 'publicar',
publishSubtitle4: 'lo.',
publishSubtitle5: 'Para utilizar un estilo privado, engancha tu',
publishSubtitle6: 'token de acceso',
publishSubtitle7:
'aquí. *kepler.gl es una aplicación cliente, los datos quedan en tu navegador..',
exampleToken: 'p.e. pk.abcdefg.xxxxxx',
pasteTitle: '2. Engancha el enlace del estilo',
pasteSubtitle1: 'Qué es un',
pasteSubtitle2: 'enlace del estilo',
namingTitle: '3. Poner nombre a tu estilo'
},
shareMap: {
shareUriTitle: 'Compartir el enlace del mapa',
shareUriSubtitle: 'Generar un enlace del mapa para compartir con otros',
cloudTitle: 'Almacenage en la nube',
cloudSubtitle: 'Acceder y cargar datos del mapa a tu almacenage a la nube personal',
shareDisclaimer:
'kepler.gl guardará los datos del mapa en el almacenage de tu nube personal, sólo quien tenga el enlace podra acceder al mapa y a los datos . ' +
'Puedes editar/borrar el archivo de datos en tu cuenta en la nube en cualquier momento.',
gotoPage: 'Ves a la página de {currentProvider} de Kepler.gl'
},
statusPanel: {
mapUploading: 'Cargar un mapa',
error: 'Error'
},
saveMap: {
title: 'Almacentage en la nube',
subtitle: 'Acceder para guardar el mapa en teu almacenage en la nube'
},
exportMap: {
formatTitle: 'Formato de mapa',
formatSubtitle: 'Escoger el formato al que se desea exportar el mapa',
html: {
selection: 'Exportar tu mapa como un archivo HTML interactivo.',
tokenTitle: 'Token de acceso de Mapbox',
tokenSubtitle: 'Utilizar tu token de acceso a Mapbox al archivo HTML (opcional)',
tokenPlaceholder: 'Enganchar tu token de acceso a Mapbox',
tokenMisuseWarning:
'* Si no proporcionas tu propio token, el mapa podría fallar en cualquier momento cuando reemplacemos nuestro token para evitar abusos. ',
tokenDisclaimer:
'Puedes cambiar el token de Mapbox posteriormente utilizando estas instrucciones: ',
tokenUpdate: 'Como actualitzar un token preexistente.',
modeTitle: 'Modo mapa',
modeSubtitle1: 'Seleccionar modo app. Más ',
modeSubtitle2: 'información',
modeDescription: 'Permmite a los usuarios {modo} el mapa',
read: 'leer',
edit: 'editar'
},
json: {
configTitle: 'Configuración del mapa',
configDisclaimer:
'La configuración del mapa será incluida en el archivo Json. Si utilitzas kepler.gl en tu propia app puedes copiar esta configuración y pasarla a ',
selection:
'Exportar los datos del mapa y la configuración en un solo archivo Json. Posteriormente puedes abrir este mismo mapa cargando este mismo archivo a kepler.gl.',
disclaimer:
'* La configuración del mapa se combina con los conjuntos de datos cargados. ‘dataId’ se utiliza para vincular capas, filtros y sugerencias a un conjunto de datos específico. ' +
'Cuando pases esta configuración a addDataToMap, asegura que el identificador del conjunto de datos coincida con los ‘dataId’ de esta configuración.'
}
},
loadingDialog: {
loading: 'Cargando...'
},
loadData: {
upload: 'Cargar archivos',
storage: 'Cargar desde almacenage'
},
tripInfo: {
title: 'Como habilitar la animación de viaje',
description1:
'Para animar la ruta, los datos geoJSON han de contener `LineString` en su geometría y las coordenadas de LineString deben tener 4 elementos en los formats de ',
code: ' [longitude, latitude, altitude, timestamp] ',
description2:
'y el último elemento debe ser la marca del tiempo. Los formatos válidos para la marca de tiempo incluyen Unix en segundos como `1564184363` o en milisegundos como `1564184363000`.',
example: 'Ejemplo:'
},
iconInfo: {
title: 'Como dibujar íconos',
description1:
'En tu CSV crea una columna y pon el nombre del ícono que quieres dibujar. Puedes dejar la celda vacía cuando no quieras que se muestre para ciertos puntos. Cuando la columna se llama',
code: 'ícono',
description2: ' kepler.gl automáticamente creará una capa de ícono.',
example: 'Ejemplo:',
icons: 'Iconos'
},
storageMapViewer: {
lastModified: 'Última modificación hace {lastUpdated}',
back: 'Atrás'
},
overwriteMap: {
title: 'Guardando el mapa...',
alreadyExists: 'ja existe en {mapSaved}. Lo quieres sobreescrivir?'
},
loadStorageMap: {
back: 'Atrás',
goToPage: 'Ves a la página {displayName} de Kepler.gl',
storageMaps: 'Almancenage / Mapas',
noSavedMaps: 'No hay ningún mapa guardado todavía'
}
},
header: {
visibleLayers: 'Capas visibles',
layerLegend: 'Capa de leyenda'
},
interactions: {
tooltip: 'Sugerencias',
brush: 'Pincel',
coordinate: 'Coordenadas',
geocoder: 'Geocodificador'
},
layerBlending: {
title: 'Combinación de capas',
additive: 'aditiva',
normal: 'normal',
subtractive: 'substractiva'
},
columns: {
title: 'Columnas',
lat: 'lat',
lng: 'lon',
altitude: 'altura',
icon: 'ícono',
geojson: 'geojson',
arc: {
lat0: 'lat origen',
lng0: 'lng origen ',
lat1: 'lat destino',
lng1: 'lng destino'
},
line: {
alt0: 'altura origen',
alt1: 'altura destino'
},
grid: {
worldUnitSize: 'Tamaño de la malla (km)'
},
hexagon: {
worldUnitSize: 'Radio de hexágono (km)'
},
hex_id: 'id hex'
},
color: {
customPalette: 'Paleta personalizada',
steps: 'pasos',
type: 'tipo',
reversed: 'invertida'
},
scale: {
colorScale: 'Escala de color',
sizeScale: 'Escala de medidas',
strokeScale: 'Escala de trazo',
scale: 'Escala'
},
fileUploader: {
message: 'Arrastra y suelta el archivo aquí',
chromeMessage:
'*usuario de Chrome: la medida máxima son 250mb, si debes cargar un archivo más grande utiliza Safari',
disclaimer:
'*kepler.gl es una aplicación al lado cliente que no utiliza ningún servidor. Los datos sólo existen en tu máquina/navegador. ' +
'No se envian datos ni mapas a ningún servidor.',
configUploadMessage:
'Cargar {fileFormatNames} o un mapa guardado en **Json**. Más información sobre [**supported file formats**]',
browseFiles: 'navega por tus archivos',
uploading: 'Cargando',
fileNotSupported: 'El archivo {errorFiles} no es compatible.',
or: 'o'
},
geocoder: {
title: 'Introduce una dirección'
},
fieldSelector: {
clearAll: 'Quitar todos',
formatting: 'Formato'
},
compare: {
modeLabel: 'Modo Comparación',
typeLabel: 'Tipo de Comparación',
types: {
absolute: 'Absoluta',
relative: 'Relativa'
}
},
mapPopover: {
primary: 'Principal'
},
density: 'densidad',
'Bug Report': 'Informe de errores',
'User Guide': 'Guía de usuario',
Save: 'Guadar',
Share: 'Compartir'
}; | the_stack |
import { Scheme } from 'ayu'
export default (scheme: Scheme, kind: string) => [
// WINDOWS
{
"class": "title_bar",
"settings": ["!ui_native_titlebar"],
"bg": scheme.editor.bg.hex(),
"fg": scheme.editor.fg.hex()
},
{
"class": "title_bar",
"settings": ["!ui_native_titlebar", "ui_separator"],
"bg": scheme.ui.bg.hex()
},
// SIDEBAR
{
"class": "sidebar_container",
"content_margin": [0, 6, 0, 0],
"layer0.opacity": 1,
"layer0.tint": scheme.editor.bg.hex()
},
{
"class": "sidebar_container",
"settings": ["ui_separator"],
"layer0.tint": scheme.ui.bg.hex(),
"layer1.texture": "ayu/assets/separator-sidebar.png",
"layer1.inner_margin": [0, 38, 2, 1],
"layer1.opacity": 1,
"layer1.tint": scheme.ui.line.hex()
},
{
"class": "sidebar_tree",
"indent_top_level": false,
"row_padding": [20, 5],
"dark_content": false,
"spacer_rows": true,
"indent_offset": 2,
"indent": 8
},
{
"class": "sidebar_heading",
"color": scheme.ui.fg.hex(),
"font.bold": true,
"font.size": 11,
},
{
"class": "tree_row",
"layer0.texture": "ayu/assets/tree-highlight.png",
"layer0.tint": scheme.ui.selection.active.alpha(0).hex(),
"layer0.inner_margin": [8, 4],
"layer0.opacity": 1,
"layer1.texture": "ayu/assets/tree-highlight-border.png",
"layer1.tint": scheme.ui.selection.active.hex(),
"layer1.inner_margin": [8, 4],
"layer1.opacity": 0
},
{
"class": "tree_row",
"attributes": ["selectable", "hover"],
"layer0.tint": scheme.ui.selection.active.hex(),
"layer1.opacity": 1
},
{
"class": "tree_row",
"attributes": ["selectable", "selected"],
"layer0.tint": scheme.ui.selection.normal.hex(),
},
{
"class": "tree_row",
"attributes": ["selectable", "selected", "hover"],
"layer0.tint": scheme.ui.selection.active.hex(),
},
{
"class": "sidebar_label",
"fg": scheme.ui.fg.hex(),
"font.size": 12
},
{
"class": "sidebar_label",
"parents": [{ "class": "tree_row", "attributes": ["hover"] }],
"fg": scheme.editor.fg.hex()
},
{
"class": "sidebar_label",
"parents": [{ "class": "tree_row", "attributes": ["selected"] }],
"fg": scheme.editor.fg.hex()
},
{
"class": "sidebar_label",
"parents": [{ "class": "tree_row", "attributes": ["expandable"] }],
"fg": scheme.ui.fg.hex(),
"font.bold": false
},
{
"class": "sidebar_label",
"parents": [{ "class": "tree_row", "attributes": ["expandable"] }],
"settings": ["bold_folder_labels"],
"font.bold": true
},
{
"class": "sidebar_label",
"parents": [{ "class": "tree_row", "attributes": ["expandable", "hover"] }],
"fg": scheme.editor.fg.hex()
},
{
"class": "sidebar_label",
"parents": [{ "class": "tree_row", "attributes": ["expanded"] }],
"fg": scheme.editor.fg.hex()
},
{
"class": "sidebar_label",
"parents": [{ "class": "tree_row", "attributes": ["expanded"] }],
"settings": ["bold_folder_labels"],
"font.bold": true
},
{
"class": "sidebar_label",
"attributes": ["transient"],
"font.italic": false
},
// {
// "class": "sidebar_label",
// "parents": [{"class": "tree_row", "attributes": ["expanded", "selected"]}],
// "color": scheme.editor.fg.hex()
// },
{
"class": "sidebar_label",
"parents": [{ "class": "file_system_entry", "attributes": ["ignored"] }],
"fg": scheme.ui.fg.alpha(.5).hex()
},
{
"class": "disclosure_button_control",
"content_margin": [0, 0, 0, 0]
},
{
"class": "close_button",
"content_margin": [6, 8],
"layer0.texture": "ayu/assets/close.png",
"layer0.opacity": 0,
"layer0.inner_margin": [0, 0],
"layer0.tint": scheme.ui.fg.hex()
},
{
"class": "close_button",
"parents": [{ "class": "tree_row", "attributes": ["hover"] }],
"layer0.opacity": 1
},
{
"class": "close_button",
"attributes": ["dirty"],
"layer0.texture": "ayu/assets/dirty.png",
"layer0.tint": scheme.ui.fg.hex(),
"layer0.opacity": 1.0
},
{
"class": "close_button",
"attributes": ["hover"],
"layer0.opacity": 1.0,
"layer0.tint": scheme.common.accent.hex()
},
{
"class": "icon_folder",
"content_margin": [9, 9],
"layer0.tint": scheme.ui.bg.hex(),
"layer0.opacity": 0,
"layer1.texture": "ayu/assets/folder.png",
"layer1.tint": scheme.ui.fg.alpha(.75).hex(),
"layer1.opacity": 1,
"layer2.texture": "ayu/assets/folder-open.png",
"layer2.tint": scheme.common.accent.hex(),
"layer2.opacity": 0.0
},
{
"class": "icon_folder",
"parents": [{ "class": "tree_row", "attributes": ["expanded"] }],
"layer1.opacity": 0.0,
"layer2.opacity": 1.0
},
{
"class": "icon_folder",
"parents": [{ "class": "tree_row", "attributes": ["hover"] }],
"layer1.tint": scheme.common.accent.hex()
},
{
"class": "icon_folder",
"parents": [{ "class": "tree_row", "attributes": ["expanded", "hover"] }],
"layer2.texture": {
"keyframes": [
"ayu/assets/folder-open-1.png",
"ayu/assets/folder-open-1.png",
"ayu/assets/folder-open-2.png",
"ayu/assets/folder-open-3.png",
"ayu/assets/folder-open-4.png",
"ayu/assets/folder-open-5.png",
"ayu/assets/folder-open-5.png",
"ayu/assets/folder-open-5.png",
"ayu/assets/folder-open-6.png",
"ayu/assets/folder-open-6.png",
"ayu/assets/folder-open-6.png",
"ayu/assets/folder-open-6.png",
"ayu/assets/folder-open.png"
],
"loop": false,
"frame_time": 0.020
},
"layer1.opacity": 0.0,
"layer2.opacity": 1.0
},
{
"class": "icon_folder",
"parents": [{ "class": "tree_row", "attributes": ["selected"] }],
"layer1.tint": scheme.common.accent.hex()
},
{
"class": "icon_folder_loading",
"layer1.texture": {
"keyframes": [
"ayu/assets/spinner11.png",
"ayu/assets/spinner10.png",
"ayu/assets/spinner9.png",
"ayu/assets/spinner8.png",
"ayu/assets/spinner7.png",
"ayu/assets/spinner6.png",
"ayu/assets/spinner5.png",
"ayu/assets/spinner4.png",
"ayu/assets/spinner3.png",
"ayu/assets/spinner2.png",
"ayu/assets/spinner1.png",
"ayu/assets/spinner.png"
],
"loop": true,
"frame_time": 0.075
},
"layer1.tint": scheme.common.accent.hex(),
"layer0.opacity": 0.0,
"content_margin": [8, 8]
},
{
"class": "icon_folder_dup",
"content_margin": [9, 9],
"layer0.texture": "ayu/assets/folder.png",
"layer0.tint": scheme.ui.fg.hex(),
"layer0.opacity": 1.0,
"layer1.texture": "ayu/assets/folder-symlink.png",
"layer1.tint": scheme.ui.fg.hex(),
"layer1.opacity": 0.3
},
{
"class": "icon_folder_dup",
"parents": [{ "class": "tree_row", "attributes": ["hover"] }],
"layer0.tint": scheme.common.accent.hex()
},
{
"class": "icon_folder_dup",
"parents": [{ "class": "tree_row", "attributes": ["expanded"] }],
"layer0.tint": scheme.common.accent.hex()
},
{
"class": "icon_file_type",
"content_margin": [8, 8]
},
{
"class": "vcs_status_badge",
"attributes": ["ignored"],
"layer0.tint": scheme.ui.fg.alpha(.3).hex(),
},
{
"class": "vcs_status_badge",
"attributes": ["added"],
"layer0.tint": scheme.vcs.added.alpha(.4).hex(),
},
{
"class": "vcs_status_badge",
"attributes": ["modified"],
"layer0.tint": scheme.vcs.modified.alpha(.4).hex(),
},
{
"class": "vcs_status_badge",
"attributes": ["deleted"],
"layer0.tint": scheme.vcs.removed.alpha(.4).hex(),
},
// Sheets
{
"class": "sheet_contents",
"background_modifier": ""
},
{
"class": "sheet_contents",
"settings": { "inactive_sheet_dimming": true, },
"attributes": ["!highlighted"],
"background_modifier": `blend(${scheme.ui.bg.hex()} 0%)`
},
// TABS
{
"class": "tabset_control",
"mouse_wheel_switch": false,
"tab_min_width": 50,
"tab_overlap": 0,
"tab_height": 38,
"tab_width": 100,
"layer0.tint": scheme.editor.bg.hex(),
"layer0.opacity": 1.0,
"content_margin": [10, 0]
},
{
"class": "tabset_control",
"settings": ["mouse_wheel_switches_tabs", "!enable_tab_scrolling"],
"mouse_wheel_switch": true
},
{
"class": "tabset_control",
"settings": ["ui_separator"],
"tab_overlap": 8,
"connector_height": 2,
"content_margin": [0, 0, 0, 0],
"layer0.tint": scheme.ui.bg.hex(),
"layer1.texture": "ayu/assets/tabset-border.png",
"layer1.tint": scheme.ui.line.hex(),
"layer1.inner_margin": [1, 1, 1, 6],
"layer1.opacity": 1,
},
{
"class": "tab_connector",
"layer0.texture": "",
"layer0.opacity": 1.0,
"tint_index": 0,
},
// {
// "class": "tab_connector",
// "settings": { "file_tab_style": ["", "rounded"] },
// "attributes": ["left_overhang"],
// "layer0.texture": "Theme - Default/common/tab_connector_rounded_left_overhang.png",
// "layer0.inner_margin": [12, 0, 0, 0],
// },
// {
// "class": "tab_connector",
// "settings": { "file_tab_style": ["", "rounded"] },
// "attributes": ["right_overhang"],
// "layer0.texture": "Theme - Default/common/tab_connector_rounded_right_overhang.png",
// "layer0.inner_margin": [0, 0, 12, 0],
// },
{
"class": "tab_control",
"settings": ["!ui_separator"],
"layer0.texture": "ayu/assets/separator-bottom.png",
"layer0.tint": scheme.ui.line.hex(),
"layer0.inner_margin": [0, 0, 0, 2],
"layer0.opacity": 0.0,
"content_margin": [15, -2, 15, 0],
"max_margin_trim": 12
},
{
"class": "tab_control",
"settings": ["ui_separator"],
"layer1.texture": "ayu/assets/tab.png",
"layer1.inner_margin": [9, 0, 9, 0],
"layer1.opacity": 0,
"layer2.texture": "ayu/assets/tab-border.png",
"layer2.inner_margin": [9, 0, 9, 0],
"layer2.tint": scheme.ui.line.hex(),
"layer2.opacity": 0,
"content_margin": [16, 5, 11, 4],
"hit_test_level": 0
},
// Selected current tab
{
"class": "tab_control", "attributes": ["selected"],
"settings": ["!ui_separator"],
"layer0.tint": scheme.common.accent.hex(),
"layer0.opacity": 1.0
},
{
"class": "tab_control", "attributes": ["selected", "!highlighted"],
"settings": ["ui_separator"],
"layer1.opacity": 1,
"layer1.tint": scheme.ui.bg.hex(),
"layer2.opacity": 1,
},
{
"class": "tab_control", "attributes": ["selected", "highlighted"],
"settings": ["ui_separator"],
"layer1.opacity": { "target": 1, "speed": 1.0, "interpolation": "smoothstep" },
"layer1.tint": scheme.editor.bg.hex(),
"layer2.opacity": 1,
},
// Hovered current tab
{
"class": "tab_control", "attributes": ["hover"],
"settings": ["!ui_separator"],
"layer0.tint": scheme.common.accent.hex(),
"layer0.opacity": 1.0
},
{
"class": "tab_control", "attributes": ["hover"],
"settings": ["ui_separator"],
// "layer0.tint": scheme.ui.bg.hex(),
},
// Selected current tab
{
"class": "tab_control", "attributes": ["selected", "hover"],
"settings": ["!ui_separator"],
"layer0.opacity": 1.0
},
{
"class": "tab_control", "attributes": ["selected", "hover"],
"settings": ["ui_separator"],
// "layer0.tint": scheme.ui.bg.hex()
},
{
"class": "tab_label",
"fg": scheme.ui.fg.hex(),
"font.italic": false,
"font.bold": false,
"font.size": 12
},
{
"class": "tab_label",
"settings": ["highlight_modified_tabs"],
"font.italic": true,
"attributes": ["dirty"],
"fg": scheme.common.accent.hex()
},
// Tab selected label color
{
"class": "tab_label",
"parents": [{ "class": "tab_control", "attributes": ["selected", "highlighted"] }],
"fg": scheme.editor.fg.hex()
},
{
"class": "tab_label",
"parents": [{ "class": "tab_control", "attributes": ["hover"] }],
"fg": scheme.editor.fg.hex()
},
{
"class": "tab_label",
"attributes": ["transient"],
"font.italic": true
},
{
"class": "tab_close_button",
"content_margin": [0, 0],
// Close Icon
"layer0.texture": "ayu/assets/close.png",
"layer0.tint": scheme.ui.fg.hex(),
"layer0.opacity": 1.0,
// Dirty Icon
"layer1.texture": "ayu/assets/dirty.png",
"layer1.tint": scheme.ui.fg.hex(),
"layer1.opacity": 0,
},
// Default
{
"class": "tab_close_button",
"settings": ["show_tab_close_buttons"],
"content_margin": [6, 8]
},
// Hover
{
"class": "tab_close_button",
"settings": ["show_tab_close_buttons", "highlight_modified_tabs"],
"attributes": ["hover"],
"layer0.tint": scheme.common.accent.hex()
},
// Dirty tab
{
"class": "tab_close_button",
"parents": [{ "class": "tab_control", "attributes": ["dirty"] }],
"layer0.opacity": 0, // Close Icon
"layer1.opacity": 1.0, // dirty Icon
"content_margin": [6, 8]
},
// Dirty tab on hover
{
"class": "tab_close_button",
"parents": [{ "class": "tab_control", "attributes": ["dirty"] }],
"attributes": ["hover"],
"layer0.opacity": 1.0, // Close Icon
"layer1.opacity": 0 // Close Icon
},
// Selected dirty tab
{
"class": "tab_close_button",
"parents": [{ "class": "tab_control", "attributes": ["selected", "dirty"] }],
"layer0.opacity": 0, // Close Icon
"layer1.opacity": 1.0, // Dirty Icon
"layer1.tint": scheme.common.accent.hex()
},
// Selected dirty tab on hover
{
"class": "tab_close_button",
"parents": [{ "class": "tab_control", "attributes": ["selected", "dirty"] }],
"attributes": ["hover"],
"layer0.opacity": 1.0,
"layer1.opacity": 0
},
{
"class": "scroll_tabs_left_button",
"content_margin": [12, 15],
"layer0.texture": "ayu/assets/arrow-left.png",
"layer0.tint": scheme.ui.fg.hex(),
"layer0.opacity": 1.0
},
{
"class": "scroll_tabs_left_button",
"attributes": ["hover"],
"layer0.tint": scheme.common.accent.hex()
},
{
"class": "scroll_tabs_right_button",
"content_margin": [12, 15],
"layer0.texture": "ayu/assets/arrow-right.png",
"layer0.tint": scheme.ui.fg.hex(),
"layer0.opacity": 1.0
},
{
"class": "scroll_tabs_right_button",
"attributes": ["hover"],
"layer0.tint": scheme.common.accent.hex()
},
{
"class": "show_tabs_dropdown_button",
"content_margin": [12, 12],
"layer0.texture": "ayu/assets/overflow-menu.png",
"layer0.tint": scheme.ui.fg.hex(),
"layer0.opacity": 1.0,
"layer0.inner_margin": [0, 0]
},
{
"class": "show_tabs_dropdown_button",
"attributes": ["hover"],
"layer0.tint": scheme.common.accent.hex()
},
// QUICK PANEL
{
"class": "overlay_control",
"layer0.texture": "ayu/assets/overlay-shadow.png",
"layer0.inner_margin": [15, 35, 15, 25],
"layer0.opacity": 1,
"layer0.tint": scheme.ui.popup.shadow.hex(),
"layer1.texture": "ayu/assets/overlay-border.png",
"layer1.inner_margin": [15, 35, 15, 25],
"layer1.opacity": 1.0,
"layer1.tint": scheme.ui.line.hex(),
"layer2.texture": "ayu/assets/overlay-bg.png",
"layer2.inner_margin": [15, 35, 15, 25],
"layer2.opacity": 1.0,
"layer2.tint": scheme.ui.popup.bg.hex(),
"content_margin": [10, 35, 10, 20]
},
{
"class": "quick_panel",
"row_padding": [13, 7],
"layer0.tint": scheme.ui.popup.bg.hex(),
"layer0.opacity": 1.0
},
{
"class": "quick_panel",
"parents": [{ "class": "overlay_control" }],
"row_padding": [13, 7],
"layer0.tint": scheme.ui.popup.bg.hex(),
"layer0.opacity": 1.0
},
{
"class": "mini_quick_panel_row",
"layer0.texture": "ayu/assets/tree-highlight.png",
"layer0.tint": scheme.ui.selection.active.hex(),
"layer0.inner_margin": [8, 4],
"layer0.opacity": 0,
"layer1.texture": "ayu/assets/tree-highlight-border.png",
"layer1.tint": scheme.ui.selection.active.hex(),
"layer1.inner_margin": [8, 4],
"layer1.opacity": 0
},
{
"class": "mini_quick_panel_row",
"attributes": ["selected"],
"layer0.opacity": 1,
"layer1.opacity": 1
},
{
"class": "quick_panel_row",
"layer0.texture": "ayu/assets/tree-highlight.png",
"layer0.tint": scheme.ui.selection.active.hex(),
"layer0.inner_margin": [8, 4],
"layer0.opacity": 0,
"layer1.texture": "ayu/assets/tree-highlight-border.png",
"layer1.tint": scheme.ui.selection.active.hex(),
"layer1.inner_margin": [8, 4],
"layer1.opacity": 0
},
{
"class": "quick_panel_row",
"attributes": ["selected"],
"layer0.opacity": 1,
"layer1.opacity": 1
},
{
"class": "quick_panel_label",
"fg": scheme.ui.fg.hex(),
"match_fg": scheme.common.accent.hex(),
"selected_fg": scheme.editor.fg.hex(),
"selected_match_fg": scheme.common.accent.hex()
},
{
"class": "quick_panel_label",
"parents": [{ "class": "overlay_control" }],
"fg": scheme.ui.fg.hex(),
"match_fg": scheme.common.accent.hex(),
"selected_fg": scheme.editor.fg.hex(),
"selected_match_fg": scheme.common.accent.hex()
},
{
"class": "quick_panel_path_label",
"fg": scheme.ui.fg.hex(),
"match_fg": scheme.editor.fg.hex(),
"selected_fg": scheme.ui.fg.hex(),
"selected_match_fg": scheme.editor.fg.hex()
},
{
"class": "quick_panel_detail_label",
"link_color": scheme.syntax.entity.hex()
},
// VIEWS
{
"class": "grid_layout_control",
"border_size": 0,
"border_color": scheme.ui.line.hex('blend')
},
{
"class": "grid_layout_control",
"settings": ["ui_separator"],
"border_size": 0
},
{
"class": "minimap_control",
"settings": ["always_show_minimap_viewport"],
"viewport_color": scheme.ui.fg.hex(),
"viewport_opacity": 0.3
},
{
"class": "minimap_control",
"settings": ["!always_show_minimap_viewport"],
"viewport_color": scheme.ui.fg.hex(),
"viewport_opacity": { "target": 0, "speed": 4.0, "interpolation": "smoothstep" }
},
{
"class": "minimap_control",
"attributes": ["hover"],
"settings": ["!always_show_minimap_viewport"],
"viewport_opacity": { "target": 0.3, "speed": 4.0, "interpolation": "smoothstep" }
},
{
"class": "fold_button_control",
"layer0.texture": "ayu/assets/unfold.png",
"layer0.opacity": 1.0,
"layer0.inner_margin": 0,
"layer0.tint": scheme.ui.fg.hex(),
"content_margin": [8, 6, 8, 6]
},
{
"class": "fold_button_control",
"attributes": ["hover"],
"layer0.tint": scheme.common.accent.hex(),
},
{
"class": "fold_button_control",
"attributes": ["expanded"],
"layer0.texture": "ayu/assets/fold.png"
},
{
"class": "popup_shadow",
"layer0.texture": "ayu/assets/popup-shadow.png",
"layer0.inner_margin": [14, 11, 14, 15],
"layer0.opacity": 1,
"layer0.tint": scheme.ui.popup.shadow.hex(),
"layer0.draw_center": false,
"layer1.texture": "ayu/assets/popup-border.png",
"layer1.inner_margin": [14, 11, 14, 15],
"layer1.opacity": 1,
"layer1.tint": scheme.ui.line.hex(),
"layer1.draw_center": false,
"content_margin": [10, 7, 10, 13]
},
{
"class": "popup_control",
"layer0.texture": "ayu/assets/popup-bg.png",
"layer0.inner_margin": [4, 4, 4, 4],
"layer0.opacity": 1,
"layer0.tint": scheme.ui.popup.bg.hex(),
"content_margin": [0, 4]
},
{
"class": "auto_complete",
"row_padding": [5, 0]
},
{
"class": "table_row",
"layer0.texture": "ayu/assets/tree-highlight.png",
"layer0.tint": scheme.ui.selection.active.hex(),
"layer0.inner_margin": [8, 4],
"layer0.opacity": 0,
"layer1.texture": "ayu/assets/tree-highlight-border.png",
"layer1.tint": scheme.ui.selection.active.hex(),
"layer1.inner_margin": [8, 4],
"layer1.opacity": 0
},
{
"class": "table_row",
"attributes": ["selected"],
"layer0.opacity": 1.0,
"layer1.opacity": 1.0
},
{
"class": "auto_complete_label",
"fg": "transparent",
"match_fg": scheme.common.accent.hex(),
"selected_fg": "transparent",
"selected_match_fg": scheme.common.accent.hex(),
"fg_blend": true
},
{
"class": "auto_complete_hint",
"opacity": 0.7,
"font.italic": true
},
{
"class": "kind_container",
"layer0.texture": "ayu/assets/kind-bg.png",
"layer0.tint": scheme.ui.popup.bg.hex(),
"layer0.inner_margin": [4, 4, 7, 4],
"layer0.opacity": 0,
"layer1.texture": "ayu/assets/kind-bg.png",
"layer1.tint": scheme.ui.popup.bg.alpha(0).hex(),
"layer1.inner_margin": [4, 4, 7, 4],
"layer1.opacity": 0.3,
"layer2.texture": "ayu/assets/kind-border.png",
"layer2.tint": scheme.ui.popup.bg.alpha(0).hex(),
"layer2.inner_margin": [4, 4, 7, 4],
"layer2.opacity": 0.1,
"content_margin": [4, 0, 6, 0]
},
{
"class": "kind_label",
"font.size": "1rem",
"font.bold": true,
"font.italic": true,
"color": scheme.ui.fg.hex(),
},
{
"class": "kind_label",
"parents": [{ "class": "quick_panel" }],
"font.size": "1.1rem"
},
{
"class": "kind_container kind_function",
"layer0.opacity": 1,
"layer1.tint": scheme.syntax.func.hex(),
"layer2.tint": scheme.syntax.func.hex(),
},
{
"class": "kind_label",
"parents": [{ "class": "kind_container kind_function" }],
"color": scheme.syntax.func.hex(),
},
{
"class": "kind_container kind_keyword",
"layer0.opacity": 1,
"layer1.tint": scheme.syntax.keyword.hex(),
"layer2.tint": scheme.syntax.keyword.hex(),
},
{
"class": "kind_label",
"parents": [{ "class": "kind_container kind_keyword" }],
"color": scheme.syntax.keyword.hex(),
},
{
"class": "kind_container kind_markup",
"layer0.opacity": 1,
"layer1.tint": scheme.syntax.tag.hex(),
"layer2.tint": scheme.syntax.tag.hex(),
},
{
"class": "kind_label",
"parents": [{ "class": "kind_container kind_markup" }],
"color": scheme.syntax.tag.hex()
},
{
"class": "kind_container kind_namespace",
"layer0.opacity": 1,
"layer1.tint": scheme.syntax.entity.hex(),
"layer2.tint": scheme.syntax.entity.hex(),
},
{
"class": "kind_label",
"parents": [{ "class": "kind_container kind_namespace" }],
"color": scheme.syntax.entity.hex()
},
{
"class": "kind_container kind_navigation",
"layer0.opacity": 1,
"layer1.tint": scheme.syntax.special.hex(),
"layer2.tint": scheme.syntax.special.hex(),
},
{
"class": "kind_label",
"parents": [{ "class": "kind_container kind_navigation" }],
"color": scheme.syntax.special.hex()
},
{
"class": "kind_container kind_snippet",
"layer0.opacity": 1,
"layer1.tint": scheme.syntax.markup.hex(),
"layer2.tint": scheme.syntax.markup.hex(),
},
{
"class": "kind_label",
"parents": [{ "class": "kind_container kind_snippet" }],
"color": scheme.syntax.markup.hex()
},
{
"class": "kind_container kind_type",
"layer0.opacity": 1,
"layer1.tint": scheme.syntax.entity.hex(),
"layer2.tint": scheme.syntax.entity.hex(),
},
{
"class": "kind_label",
"parents": [{ "class": "kind_container kind_type" }],
"color": scheme.syntax.entity.hex()
},
{
"class": "kind_container kind_variable",
"layer0.opacity": 1,
"layer1.tint": scheme.syntax.comment.hex(),
"layer2.tint": scheme.syntax.comment.hex(),
},
{
"class": "kind_label",
"parents": [{ "class": "kind_container kind_variable" }],
"color": scheme.syntax.comment.hex(),
},
{
"class": "kind_container kind_color_redish",
"layer0.opacity": 1,
"layer1.tint": scheme.syntax.markup.hex(),
"layer2.tint": scheme.syntax.markup.hex(),
},
{
"class": "kind_label",
"parents": [{ "class": "kind_container kind_color_redish" }],
"color": scheme.syntax.markup.hex()
},
{
"class": "kind_container kind_color_orangish",
"layer0.opacity": 1,
"layer1.tint": scheme.syntax.keyword.hex(),
"layer2.tint": scheme.syntax.keyword.hex(),
},
{
"class": "kind_label",
"parents": [{ "class": "kind_container kind_color_orangish" }],
"color": scheme.syntax.keyword.hex()
},
{
"class": "kind_container kind_color_yellowish",
"layer0.opacity": 1,
"layer1.tint": scheme.syntax.func.hex(),
"layer2.tint": scheme.syntax.func.hex(),
},
{
"class": "kind_label",
"parents": [{ "class": "kind_container kind_color_yellowish" }],
"color": scheme.syntax.func.hex()
},
{
"class": "kind_container kind_color_greenish",
"layer0.opacity": 1,
"layer1.tint": scheme.syntax.string.hex(),
"layer2.tint": scheme.syntax.string.hex(),
},
{
"class": "kind_label",
"parents": [{ "class": "kind_container kind_color_greenish" }],
"color": scheme.syntax.string.hex()
},
{
"class": "kind_container kind_color_cyanish",
"layer0.opacity": 1,
"layer1.tint": scheme.syntax.regexp.hex(),
"layer2.tint": scheme.syntax.regexp.hex(),
},
{
"class": "kind_label",
"parents": [{ "class": "kind_container kind_color_cyanish" }],
"color": scheme.syntax.regexp.hex()
},
{
"class": "kind_container kind_color_bluish",
"layer0.opacity": 1,
"layer1.tint": scheme.syntax.tag.hex(),
"layer2.tint": scheme.syntax.tag.hex(),
},
{
"class": "kind_label",
"parents": [{ "class": "kind_container kind_color_bluish" }],
"color": scheme.syntax.tag.hex()
},
{
"class": "kind_container kind_color_purplish",
"layer0.opacity": 1,
"layer1.tint": scheme.syntax.constant.hex(),
"layer2.tint": scheme.syntax.constant.hex(),
},
{
"class": "kind_label",
"parents": [{ "class": "kind_container kind_color_purplish" }],
"color": scheme.syntax.constant.hex()
},
{
"class": "kind_container kind_color_pinkish",
"layer0.opacity": 1,
"layer1.tint": scheme.syntax.operator.hex(),
"layer2.tint": scheme.syntax.operator.hex(),
},
{
"class": "kind_label",
"parents": [{ "class": "kind_container kind_color_pinkish" }],
"color": scheme.syntax.operator.hex()
},
{
"class": "kind_container kind_color_dark",
"layer0.opacity": 1,
"layer1.tint": scheme.ui.fg.hex(),
"layer2.tint": scheme.ui.fg.hex(),
},
{
"class": "kind_label",
"parents": [{ "class": "kind_container kind_color_dark" }],
"color": scheme.ui.fg.hex()
},
{
"class": "kind_container kind_color_light",
"layer0.opacity": 1,
"layer1.tint": "white",
"layer2.tint": "white",
},
{
"class": "kind_label",
"parents": [{ "class": "kind_container kind_color_light" }],
"color": "#555"
},
{
"class": "symbol_container",
"content_margin": [4, 3, 4, 3]
},
{
"class": "trigger_container",
"content_margin": [4, 3, 4, 3]
},
{
"class": "auto_complete_detail_pane",
"layer0.opacity": 1.0,
"layer0.tint": scheme.ui.popup.bg.hex(),
"layer1.opacity": 1,
"layer1.tint": scheme.ui.popup.bg.hex(),
"content_margin": [8, 10, 8, 5]
},
{
"class": "auto_complete_kind_name_label",
"font.size": "0.9rem",
"font.italic": true,
"border_color": scheme.ui.fg.hex()
},
{
"class": "auto_complete_details",
"background_color": scheme.ui.popup.bg.hex(),
"monospace_background_color": scheme.ui.popup.bg.hex()
},
// PANELS
{
"class": "panel_control",
"layer0.tint": scheme.editor.bg.hex(),
"layer0.opacity": 1.0,
"content_margin": [0, 5]
},
{
"class": "panel_control",
"settings": ["ui_separator"],
"layer0.tint": scheme.ui.bg.hex(),
"layer1.texture": "ayu/assets/separator-top.png",
"layer1.tint": scheme.ui.line.hex(),
"layer1.inner_margin": [1, 2, 1, 0],
"layer1.opacity": 1
},
{
"class": "panel_grid_control"
},
{
"class": "panel_close_button",
"layer0.texture": "ayu/assets/close.png",
"layer0.opacity": 1.0,
"layer0.tint": scheme.ui.fg.hex(),
"content_margin": [0, 0] // 8,8 to show
},
{
"class": "panel_close_button",
"attributes": ["hover"],
"layer0.tint": scheme.common.accent.hex()
},
// STATUS BAR
{
"class": "status_bar",
"layer0.texture": "",
"layer0.tint": scheme.editor.bg.hex(),
"layer0.opacity": 1,
"layer1.texture": "ayu/assets/separator-top.png",
"layer1.tint": scheme.ui.line.hex(),
"layer1.inner_margin": [1, 2, 1, 0],
"content_margin": [10, 2]
},
{
"class": "status_bar",
"settings": ["ui_separator"],
"layer0.tint": scheme.ui.bg.hex(),
"layer1.opacity": 1
},
{
"class": "panel_button_control",
"layer0.texture": "ayu/assets/switch-panel.png",
"layer0.tint": scheme.ui.fg.hex(),
"layer0.opacity": 1.0
},
{
"class": "panel_button_control",
"attributes": ["hover"],
"layer0.tint": scheme.common.accent.hex()
},
{
"class": "status_container",
"content_margin": [0, 5]
},
{
"class": "status_button",
"min_size": [100, 0]
},
{
"class": "vcs_branch_icon",
"layer0.tint": scheme.ui.fg.hex()
},
{
"class": "vcs_changes_annotation",
"border_color": scheme.ui.fg.alpha(0.7).hex()
},
// DIALOGS
{
"class": "dialog",
"layer0.tint": scheme.ui.bg.hex(),
"layer0.opacity": 1.0
},
{
"class": "progress_bar_control",
"layer0.tint": scheme.ui.bg.hex(),
"layer0.opacity": 1.0
},
{
"class": "progress_gauge_control",
"layer0.tint": scheme.common.accent.hex(),
"layer0.opacity": 1.0,
"content_margin": [0, 6]
},
// SCROLL BARS
{
"class": "scroll_area_control",
"settings": ["overlay_scroll_bars"],
"overlay": true
},
{
"class": "scroll_area_control",
"settings": ["!overlay_scroll_bars"],
"overlay": false
},
{
"class": "scroll_bar_control",
"layer0.tint": scheme.ui.bg.hex(),
"layer0.opacity": 1.0,
"layer1.texture": "ayu/assets/scrollbar-vertical-wide.png",
"layer1.tint": scheme.ui.fg.hex(),
"layer1.opacity": 0.1,
"layer1.inner_margin": [0, 10]
},
{
"class": "scroll_bar_control",
"parents": [{ "class": "overlay_control" }],
"layer0.tint": scheme.ui.popup.bg.hex()
},
{
"class": "scroll_bar_control",
"attributes": ["horizontal"],
"layer1.texture": "ayu/assets/scrollbar-horizontal-wide.png",
"layer1.inner_margin": [10, 0]
},
{
"class": "scroll_bar_control",
"settings": ["overlay_scroll_bars"],
"layer0.opacity": 0,
"layer1.texture": "ayu/assets/scrollbar-vertical.png",
"layer1.inner_margin": [4, 6, 6, 6]
},
{
"class": "scroll_bar_control",
"settings": ["overlay_scroll_bars", "ui_wide_scrollbars"],
"layer0.texture": "ayu/assets/scrollbar-vertical-wide.png"
},
{
"class": "scroll_bar_control",
"settings": ["overlay_scroll_bars"],
"attributes": ["horizontal"],
"layer0.opacity": 0,
"layer1.texture": "ayu/assets/scrollbar-horizontal.png",
"layer1.inner_margin": [6, 4, 6, 6]
},
{
"class": "scroll_bar_control",
"attributes": ["horizontal"],
"settings": ["overlay_scroll_bars", "ui_wide_scrollbars"],
"layer0.texture": "ayu/assets/scrollbar-horizontal-wide.png"
},
{
"class": "scroll_track_control",
"layer0.tint": scheme.ui.bg.hex(),
"layer0.opacity": 1.0
},
{
"class": "scroll_corner_control",
"layer0.tint": scheme.ui.bg.hex(),
"layer0.opacity": 1.0
},
{
"class": "puck_control",
"layer0.texture": "ayu/assets/scrollbar-vertical-wide.png",
"layer0.tint": scheme.ui.fg.hex(),
"layer0.opacity": 0.3,
"layer0.inner_margin": [0, 10],
"content_margin": [6, 12]
},
{
"class": "puck_control",
"attributes": ["horizontal"],
"layer0.texture": "ayu/assets/scrollbar-horizontal-wide.png",
"layer0.inner_margin": [10, 0],
"content_margin": [12, 6]
},
{
"class": "puck_control",
"settings": ["overlay_scroll_bars"],
"layer0.texture": "ayu/assets/scrollbar-vertical.png",
"layer0.inner_margin": [4, 6, 6, 6],
"content_margin": [5, 20]
},
{
"class": "puck_control",
"settings": ["overlay_scroll_bars", "ui_wide_scrollbars"],
"layer0.texture": "ayu/assets/scrollbar-vertical-wide.png"
},
{
"class": "puck_control",
"settings": ["overlay_scroll_bars"],
"attributes": ["horizontal"],
"layer0.texture": "ayu/assets/scrollbar-horizontal.png",
"layer0.inner_margin": [6, 4, 6, 6],
"content_margin": [20, 5]
},
{
"class": "puck_control",
"attributes": ["horizontal"],
"settings": ["overlay_scroll_bars", "ui_wide_scrollbars"],
"layer0.texture": "ayu/assets/scrollbar-horizontal-wide.png"
},
// INPUTS
{
"class": "text_line_control",
"layer0.texture": "ayu/assets/input-bg.png",
"layer0.opacity": 1,
"layer0.inner_margin": [10, 8],
"layer0.tint": scheme.ui.popup.bg.hex(),
"layer1.texture": "ayu/assets/input-border.png",
"layer1.opacity": 1,
"layer1.inner_margin": [10, 8],
"layer1.tint": scheme.ui.line.hex(),
"content_margin": [10, 7, 10, 5]
},
// Textline input inside overlay panels
{
"class": "text_line_control",
"parents": [{ "class": "overlay_control" }],
"layer0.texture": "",
"layer0.opacity": 0,
"layer1.texture": "ayu/assets/input-prompt.png",
"layer1.opacity": 1,
"layer1.tint": scheme.ui.fg.alpha(1).hex(),
"layer1.inner_margin": [36, 26, 0, 0],
"content_margin": [38, 5, 10, 5]
},
{
"class": "text_line_control",
"parents": [{ "class": "overlay_control goto_file" }],
"layer1.texture": "ayu/assets/input-search.png"
},
{
"class": "text_line_control",
"parents": [{ "class": "overlay_control command_palette" }],
"layer1.texture": "ayu/assets/input-command.png"
},
{
"class": "text_line_control",
"parents": [{ "class": "overlay_control goto_symbol" }],
"layer1.texture": "ayu/assets/input-symbol.png"
},
{
"class": "text_line_control",
"parents": [{ "class": "overlay_control goto_symbol_in_project" }],
"layer1.texture": "ayu/assets/input-symbol.png"
},
{
"class": "text_line_control",
"parents": [{ "class": "overlay_control goto_word" }],
"layer1.texture": "ayu/assets/input-word.png"
},
{
"class": "dropdown_button_control",
"content_margin": [12, 12],
"layer0.texture": "ayu/assets/overflow-menu.png",
"layer0.tint": scheme.ui.fg.hex(),
"layer0.opacity": 1.0
},
{
"class": "dropdown_button_control",
"attributes": ["hover"],
"layer0.tint": scheme.common.accent.hex()
},
// BUTTONS
{
"class": "button_control",
"content_margin": [15, 9, 15, 10],
"min_size": [60, 0],
"layer0.tint": scheme.common.accent.hex(),
"layer0.texture": "ayu/assets/input-bg.png",
"layer0.inner_margin": [10, 8],
"layer0.opacity": 0
},
{
"class": "button_control",
"attributes": ["hover"],
"layer0.opacity": 1
},
{
"class": "icon_button_control",
"layer0.tint": [0, 0, 0],
"layer0.opacity": 0,
"layer2.tint": scheme.editor.fg.hex(),
"layer2.opacity": { "target": 0.0, "speed": 10.0, "interpolation": "smoothstep" },
"content_margin": [10, 5]
},
{
"class": "icon_regex",
"layer0.texture": "ayu/assets/regex.png",
"layer0.tint": scheme.ui.fg.hex(),
"layer0.opacity": 1.0,
"content_margin": [12, 12]
},
{
"class": "icon_regex",
"parents": [{ "class": "icon_button_control", "attributes": ["selected"] }],
"layer0.tint": scheme.common.accent.hex()
},
{
"class": "icon_case",
"layer0.texture": "ayu/assets/matchcase.png",
"layer0.tint": scheme.ui.fg.hex(),
"layer0.opacity": 1.0,
"content_margin": [12, 12]
},
{
"class": "icon_case",
"parents": [{ "class": "icon_button_control", "attributes": ["selected"] }],
"layer0.tint": scheme.common.accent.hex()
},
{
"class": "icon_whole_word",
"layer0.texture": "ayu/assets/word.png",
"layer0.tint": scheme.ui.fg.hex(),
"layer0.opacity": 1.0,
"content_margin": [12, 12]
},
{
"class": "icon_whole_word",
"parents": [{ "class": "icon_button_control", "attributes": ["selected"] }],
"layer0.tint": scheme.common.accent.hex()
},
{
"class": "icon_wrap",
"layer0.texture": "ayu/assets/wrap.png",
"layer0.tint": scheme.ui.fg.hex(),
"layer0.opacity": 1.0,
"content_margin": [12, 12]
},
{
"class": "icon_wrap",
"parents": [{ "class": "icon_button_control", "attributes": ["selected"] }],
"layer0.tint": scheme.common.accent.hex()
},
{
"class": "icon_in_selection",
"layer0.texture": "ayu/assets/inselection.png",
"layer0.tint": scheme.ui.fg.hex(),
"layer0.opacity": 1.0,
"content_margin": [12, 12]
},
{
"class": "icon_in_selection",
"parents": [{ "class": "icon_button_control", "attributes": ["selected"] }],
"layer0.tint": scheme.common.accent.hex()
},
{
"class": "icon_highlight",
"layer0.texture": "ayu/assets/highlight.png",
"layer0.tint": scheme.ui.fg.hex(),
"layer0.opacity": 1.0,
"content_margin": [12, 12]
},
{
"class": "icon_highlight",
"parents": [{ "class": "icon_button_control", "attributes": ["selected"] }],
"layer0.tint": scheme.common.accent.hex()
},
{
"class": "icon_preserve_case",
"layer0.texture": "ayu/assets/replace-preserve-case.png",
"layer0.tint": scheme.ui.fg.hex(),
"layer0.opacity": 1.0,
"content_margin": [12, 12]
},
{
"class": "icon_preserve_case",
"parents": [{ "class": "icon_button_control", "attributes": ["selected"] }],
"layer0.tint": scheme.common.accent.hex()
},
{
"class": "icon_context",
"layer0.texture": "ayu/assets/context.png",
"layer0.tint": scheme.ui.fg.hex(),
"layer0.opacity": 1.0,
"content_margin": [12, 12]
},
{
"class": "icon_context",
"parents": [{ "class": "icon_button_control", "attributes": ["selected"] }],
"layer0.tint": scheme.common.accent.hex()
},
{
"class": "icon_use_buffer",
"layer0.texture": "ayu/assets/buffer.png",
"layer0.tint": scheme.ui.fg.hex(),
"layer0.opacity": 1.0,
"content_margin": [12, 12]
},
{
"class": "icon_use_buffer",
"parents": [{ "class": "icon_button_control", "attributes": ["selected"] }],
"layer0.tint": scheme.common.accent.hex()
},
{
"class": "icon_use_gitignore",
"layer0.texture": "ayu/assets/gitignore.png",
"layer0.tint": scheme.ui.fg.hex(),
"layer0.opacity": 1.0,
"content_margin": [12, 12]
},
{
"class": "icon_use_gitignore",
"parents": [{ "class": "icon_button_control", "attributes": ["selected"] }],
"layer0.tint": scheme.common.accent.hex()
},
{
"class": "sidebar_button_control",
"layer0.texture": "ayu/assets/sidebar.png",
"layer0.tint": scheme.ui.fg.hex(),
"layer0.opacity": 1.0,
"content_margin": [12, 12]
},
{
"class": "sidebar_button_control",
"attributes": ["hover"],
"layer0.tint": scheme.common.accent.hex(),
},
// LABELS
{
"class": "label_control",
"color": scheme.ui.fg.hex(),
"shadow_color": [0, 0, 0, 0],
"shadow_offset": [0, 0],
"font.bold": false,
"font.size": 12
},
{
"class": "label_control",
"parents": [{ "class": "status_bar" }],
"color": scheme.ui.fg.hex(),
"font.bold": false
},
{
"class": "label_control",
"parents": [{ "class": "button_control" }],
"color": scheme.ui.fg.hex()
},
{
"class": "label_control",
"parents": [{ "class": "button_control", "attributes": ["hover"] }],
"color": scheme.common.accentFg.hex()
},
{
"class": "title_label_control",
"color": scheme.common.accent.hex()
},
// TOOL TIPS
{
"class": "tool_tip_control",
"layer0.tint": scheme.ui.fg.hex(),
"layer0.inner_margin": [0, 0],
"layer0.opacity": 1.0,
"content_margin": [6, 3]
},
{
"class": "tool_tip_label_control",
"color": scheme.ui.bg.hex(),
"font.size": 12
},
] | the_stack |
import { ConfigurationReference, getConf } from '@jbrowse/core/configuration'
import { InternetAccount } from '@jbrowse/core/pluggableElementTypes/models'
import { isElectron } from '@jbrowse/core/util'
import sha256 from 'crypto-js/sha256'
import Base64 from 'crypto-js/enc-base64'
import { Instance, types } from 'mobx-state-tree'
import { RemoteFileWithRangeCache } from '@jbrowse/core/util/io'
import { UriLocation } from '@jbrowse/core/util/types'
// locals
import { OAuthInternetAccountConfigModel } from './configSchema'
interface OAuthData {
client_id: string
redirect_uri: string
response_type: 'token' | 'code'
scope?: string
code_challenge?: string
code_challenge_method?: string
token_access_type?: string
}
const inWebWorker = typeof sessionStorage === 'undefined'
const stateModelFactory = (configSchema: OAuthInternetAccountConfigModel) => {
return types
.compose(
'OAuthInternetAccount',
InternetAccount,
types.model('OAuthModel', {
id: 'OAuth',
type: types.literal('OAuthInternetAccount'),
configuration: ConfigurationReference(configSchema),
}),
)
.volatile(() => ({
codeVerifierPKCE: '',
errorMessage: '',
}))
.views(self => ({
get authHeader(): string {
return getConf(self, 'authHeader') || 'Authorization'
},
get tokenType(): string {
return getConf(self, 'tokenType') || 'Bearer'
},
get internetAccountType() {
return 'OAuthInternetAccount'
},
handlesLocation(location: UriLocation): boolean {
const validDomains = self.accountConfig.domains || []
return validDomains.some((domain: string) =>
location?.uri.includes(domain),
)
},
generateAuthInfo() {
const generatedInfo = {
internetAccountType: this.internetAccountType,
authInfo: {
authHeader: this.authHeader,
tokenType: this.tokenType,
configuration: self.accountConfig,
redirectUri: window.location.origin + window.location.pathname,
},
}
return generatedInfo
},
}))
.actions(self => ({
setCodeVerifierPKCE(codeVerifier: string) {
self.codeVerifierPKCE = codeVerifier
},
setErrorMessage(message: string) {
self.errorMessage = message
},
async fetchFile(locationUri: string, accessToken: string) {
if (!locationUri || !accessToken) {
return
}
return locationUri
},
}))
.volatile(() => ({
uriToPreAuthInfoMap: new Map(),
}))
.actions(self => {
let resolve: Function = () => {}
let reject: Function = () => {}
let openLocationPromise: Promise<string> | undefined = undefined
return {
// opens external OAuth flow, popup for web and new browser window for desktop
async useEndpointForAuthorization(location: UriLocation) {
const determineRedirectUri = () => {
if (!inWebWorker) {
if (isElectron) {
return 'http://localhost/auth'
} else {
return window.location.origin + window.location.pathname
}
} else {
return self.uriToPreAuthInfoMap.get(location.uri)?.authInfo
?.redirectUri
}
}
const config = self.accountConfig
const data: OAuthData = {
client_id: config.clientId,
redirect_uri: determineRedirectUri(),
response_type: config.responseType || 'code',
}
if (config.scopes) {
data.scope = config.scopes
}
if (config.needsPKCE) {
const fixup = (buf: string) => {
return buf
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '')
}
const array = new Uint8Array(32)
window.crypto.getRandomValues(array)
const codeVerifier = fixup(Buffer.from(array).toString('base64'))
const codeChallenge = fixup(Base64.stringify(sha256(codeVerifier)))
data.code_challenge = codeChallenge
data.code_challenge_method = 'S256'
self.setCodeVerifierPKCE(codeVerifier)
}
if (config.hasRefreshToken) {
data.token_access_type = 'offline'
}
const params = Object.entries(data)
.map(([key, val]) => `${key}=${encodeURIComponent(val)}`)
.join('&')
const url = `${config.authEndpoint}?${params}`
if (isElectron) {
const model = self
const electron = require('electron')
const { ipcRenderer } = electron
const redirectUri = await ipcRenderer.invoke('openAuthWindow', {
internetAccountId: self.internetAccountId,
data: data,
url: url,
})
const eventFromDesktop = new MessageEvent('message', {
data: {
name: `JBrowseAuthWindow-${self.internetAccountId}`,
redirectUri: redirectUri,
},
})
// @ts-ignore
model.finishOAuthWindow(eventFromDesktop)
return
} else {
const options = `width=500,height=600,left=0,top=0`
return window.open(
url,
`JBrowseAuthWindow-${self.internetAccountId}`,
options,
)
}
},
async setAccessTokenInfo(token: string, generateNew = false) {
if (generateNew && token) {
sessionStorage.setItem(`${self.internetAccountId}-token`, token)
}
if (!token) {
reject()
} else {
resolve(token)
}
resolve = () => {}
reject = () => {}
this.deleteMessageChannel()
},
async checkToken(
authInfo: { token: string; refreshToken: string },
location: UriLocation,
) {
let token =
authInfo?.token ||
(!inWebWorker
? (sessionStorage.getItem(
`${self.internetAccountId}-token`,
) as string)
: '')
const refreshToken =
authInfo?.refreshToken ||
(!inWebWorker
? (localStorage.getItem(
`${self.internetAccountId}-refreshToken`,
) as string)
: '')
if (!token) {
if (refreshToken) {
token = await this.exchangeRefreshForAccessToken(location)
} else {
if (!openLocationPromise) {
openLocationPromise = new Promise(async (r, x) => {
this.addMessageChannel()
this.useEndpointForAuthorization(location)
resolve = r
reject = x
})
token = await openLocationPromise
}
}
}
resolve()
openLocationPromise = undefined
return { token, refreshToken }
},
setRefreshToken(token: string) {
const refreshTokenKey = `${self.internetAccountId}-refreshToken`
const existingToken = localStorage.getItem(refreshTokenKey)
if (!existingToken) {
localStorage.setItem(
`${self.internetAccountId}-refreshToken`,
token,
)
}
},
async exchangeAuthorizationForAccessToken(
token: string,
redirectUri: string,
) {
const config = self.accountConfig
const data = {
code: token,
grant_type: 'authorization_code',
client_id: config.clientId,
code_verifier: self.codeVerifierPKCE,
redirect_uri: redirectUri,
}
const params = Object.entries(data)
.map(([key, val]) => `${key}=${encodeURIComponent(val)}`)
.join('&')
const response = await fetch(`${config.tokenEndpoint}`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: params,
})
if (!response.ok) {
resolve()
await this.handleError('Failed to obtain token from endpoint')
}
const accessToken = await response.json()
if (!inWebWorker) {
this.setAccessTokenInfo(accessToken.access_token, true)
if (accessToken.refresh_token) {
this.setRefreshToken(accessToken.refresh_token)
}
}
},
async exchangeRefreshForAccessToken(location: UriLocation) {
const foundRefreshToken =
self.uriToPreAuthInfoMap.get(location.uri)?.authInfo
?.refreshToken ||
(!inWebWorker
? localStorage.getItem(`${self.internetAccountId}-refreshToken`)
: null)
if (foundRefreshToken) {
const config = self.accountConfig
const data = {
grant_type: 'refresh_token',
refresh_token: foundRefreshToken,
client_id: config.clientId,
}
const params = Object.entries(data)
.map(([key, val]) => `${key}=${encodeURIComponent(val)}`)
.join('&')
const response = await fetch(`${config.tokenEndpoint}`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: params,
})
if (!response.ok) {
if (!inWebWorker) {
localStorage.removeItem(
`${self.internetAccountId}-refreshToken`,
)
}
throw new Error(
`Network response failure: ${
response.status
} (${await response.text()})`,
)
}
const accessToken = await response.json()
if (!inWebWorker) {
this.setAccessTokenInfo(accessToken.access_token, true)
}
return accessToken.access_token
} else {
throw new Error(
`Malformed or expired access token, and refresh token not found`,
)
}
},
// used to listen to child window for auth code/token
addMessageChannel() {
window.addEventListener('message', this.finishOAuthWindow)
},
deleteMessageChannel() {
window.removeEventListener('message', this.finishOAuthWindow)
},
finishOAuthWindow(event: MessageEvent) {
if (
event.data.name === `JBrowseAuthWindow-${self.internetAccountId}`
) {
const redirectUriWithInfo = event.data.redirectUri
if (redirectUriWithInfo.includes('access_token')) {
const fixedQueryString = redirectUriWithInfo.replace('#', '?')
const queryStringSearch = new URL(fixedQueryString).search
const urlParams = new URLSearchParams(queryStringSearch)
const token = urlParams.get('access_token')
if (!token) {
self.setErrorMessage('Error with token endpoint')
reject(self.errorMessage)
openLocationPromise = undefined
return
}
this.setAccessTokenInfo(token, true)
}
if (redirectUriWithInfo.includes('code')) {
const redirectUri = new URL(redirectUriWithInfo)
const queryString = redirectUri.search
const urlParams = new URLSearchParams(queryString)
const code = urlParams.get('code')
if (!code) {
self.setErrorMessage('Error with authorization endpoint')
reject(self.errorMessage)
openLocationPromise = undefined
return
}
this.exchangeAuthorizationForAccessToken(
code,
redirectUri.origin + redirectUri.pathname,
)
}
if (redirectUriWithInfo.includes('access_denied')) {
self.setErrorMessage('OAuth flow was cancelled')
reject(self.errorMessage)
openLocationPromise = undefined
return
}
}
},
// modified fetch that includes the headers
async getFetcher(
url: RequestInfo,
opts?: RequestInit,
): Promise<Response> {
const preAuthInfo = self.uriToPreAuthInfoMap.get(url)
if (!preAuthInfo || !preAuthInfo.authInfo) {
throw new Error(
`Failed to obtain authorization information needed to fetch ${
inWebWorker ? '. Try reloading the page' : ''
}`,
)
}
let fileUrl = preAuthInfo.authInfo.fileUrl
let foundTokens = {
token: '',
refreshToken: '',
}
try {
foundTokens = await this.checkToken(preAuthInfo.authInfo, {
uri: String(url),
locationType: 'UriLocation',
})
} catch (e) {
await this.handleError(e as string)
}
let newOpts = opts
if (foundTokens.token) {
if (!fileUrl) {
try {
fileUrl = await self.fetchFile(String(url), foundTokens.token)
} catch (e) {
await this.handleError(e as string)
}
}
const tokenInfoString = self.tokenType
? `${self.tokenType} ${foundTokens.token}`
: `${foundTokens.token}`
const newHeaders = {
...opts?.headers,
[self.authHeader]: `${tokenInfoString}`,
}
newOpts = {
...opts,
headers: newHeaders,
}
}
return fetch(fileUrl, {
method: 'GET',
credentials: 'same-origin',
...newOpts,
})
},
openLocation(location: UriLocation) {
const preAuthInfo =
location.internetAccountPreAuthorization || self.generateAuthInfo()
self.uriToPreAuthInfoMap.set(location.uri, preAuthInfo)
return new RemoteFileWithRangeCache(String(location.uri), {
fetch: this.getFetcher,
})
},
// fills in a locations preauth information with all necessary information
async getPreAuthorizationInformation(
location: UriLocation,
retried = false,
) {
if (!self.uriToPreAuthInfoMap.get(location.uri)) {
self.uriToPreAuthInfoMap.set(location.uri, self.generateAuthInfo())
}
if (inWebWorker && !location.internetAccountPreAuthorization) {
throw new Error(
'Failed to obtain authorization information needed to fetch',
)
}
let foundTokens = {
token: '',
refreshToken: '',
}
try {
foundTokens = await this.checkToken(
self.uriToPreAuthInfoMap.get(location.uri).authInfo,
location,
)
self.uriToPreAuthInfoMap.set(location.uri, {
...self.uriToPreAuthInfoMap.get(location.uri),
authInfo: {
...self.uriToPreAuthInfoMap.get(location.uri).authInfo,
token: foundTokens.token,
refreshToken: foundTokens.refreshToken,
},
})
} catch (error) {
await this.handleError(error as string, retried)
}
if (foundTokens.token) {
let fileUrl = self.uriToPreAuthInfoMap.get(location.uri).authInfo
?.fileUrl
if (!fileUrl) {
try {
fileUrl = await self.fetchFile(location.uri, foundTokens.token)
self.uriToPreAuthInfoMap.set(location.uri, {
...self.uriToPreAuthInfoMap.get(location.uri),
authInfo: {
...self.uriToPreAuthInfoMap.get(location.uri).authInfo,
fileUrl: fileUrl,
},
})
} catch (error) {
await this.handleError(error as string, retried, location)
if (!retried) {
await this.getPreAuthorizationInformation(location, true)
}
}
}
}
return self.uriToPreAuthInfoMap.get(location.uri)
},
// in the error message to the flow above, add a conditional that is like
// if inWebWorker try to reload the page
async handleError(
error: string,
triedRefreshToken = false,
location?: UriLocation,
) {
if (!inWebWorker && location) {
sessionStorage.removeItem(`${self.internetAccountId}-token`)
self.uriToPreAuthInfoMap.set(location.uri, self.generateAuthInfo()) // if it reaches here the token was bad
}
if (!triedRefreshToken && location) {
await this.exchangeRefreshForAccessToken(location)
} else {
throw error
}
},
}
})
}
export default stateModelFactory
export type OAuthStateModel = ReturnType<typeof stateModelFactory>
export type OAuthModel = Instance<OAuthStateModel> | the_stack |
import { useXarrowPropsResType } from '../useXarrowProps';
import React from 'react';
import { calcAnchors } from '../anchors';
import { getShortestLine, getSvgPos } from './index';
import _ from 'lodash';
import { cPaths } from '../../constants';
import { buzzierMinSols, bzFunction } from './buzzier';
/**
* The Main logic of path calculation for the arrow.
* calculate new path, adjusting canvas, and set state based on given properties.
* */
export const getPosition = (xProps: useXarrowPropsResType, mainRef: React.MutableRefObject<any>) => {
let [propsRefs, valVars] = xProps;
let {
startAnchor,
endAnchor,
strokeWidth,
showHead,
headSize,
showTail,
tailSize,
path,
curveness,
gridBreak,
headShape,
tailShape,
_extendSVGcanvas,
_cpx1Offset,
_cpy1Offset,
_cpx2Offset,
_cpy2Offset,
} = propsRefs;
const { startPos, endPos } = valVars;
const { svgRef, lineRef } = mainRef.current;
let headOrient: number = 0;
let tailOrient: number = 0;
// convert startAnchor and endAnchor to list of objects represents allowed anchors.
let startPoints = calcAnchors(startAnchor, startPos);
let endPoints = calcAnchors(endAnchor, endPos);
// choose the smallest path for 2 points from these possibilities.
let { chosenStart, chosenEnd } = getShortestLine(startPoints, endPoints);
let startAnchorPosition = chosenStart.anchor.position,
endAnchorPosition = chosenEnd.anchor.position;
let startPoint = _.pick(chosenStart, ['x', 'y']),
endPoint = _.pick(chosenEnd, ['x', 'y']);
let mainDivPos = getSvgPos(svgRef);
let cx0 = Math.min(startPoint.x, endPoint.x) - mainDivPos.x;
let cy0 = Math.min(startPoint.y, endPoint.y) - mainDivPos.y;
let dx = endPoint.x - startPoint.x;
let dy = endPoint.y - startPoint.y;
let absDx = Math.abs(endPoint.x - startPoint.x);
let absDy = Math.abs(endPoint.y - startPoint.y);
let xSign = dx > 0 ? 1 : -1;
let ySign = dy > 0 ? 1 : -1;
let [headOffset, tailOffset] = [headShape.offsetForward, tailShape.offsetForward];
let fHeadSize = headSize * strokeWidth; //factored head size
let fTailSize = tailSize * strokeWidth; //factored head size
// const { current: _headBox } = headBox;
let xHeadOffset = 0;
let yHeadOffset = 0;
let xTailOffset = 0;
let yTailOffset = 0;
let _headOffset = fHeadSize * headOffset;
let _tailOffset = fTailSize * tailOffset;
let cu = Number(curveness);
// gridRadius = Number(gridRadius);
if (!cPaths.includes(path)) path = 'smooth';
if (path === 'straight') {
cu = 0;
path = 'smooth';
}
let biggerSide = headSize > tailSize ? headSize : tailSize;
let _calc = strokeWidth + (strokeWidth * biggerSide) / 2;
let excRight = _calc;
let excLeft = _calc;
let excUp = _calc;
let excDown = _calc;
excLeft += Number(_extendSVGcanvas);
excRight += Number(_extendSVGcanvas);
excUp += Number(_extendSVGcanvas);
excDown += Number(_extendSVGcanvas);
////////////////////////////////////
// arrow point to point calculations
let x1 = 0,
x2 = absDx,
y1 = 0,
y2 = absDy;
if (dx < 0) [x1, x2] = [x2, x1];
if (dy < 0) [y1, y2] = [y2, y1];
////////////////////////////////////
// arrow curviness and arrowhead placement calculations
if (cu === 0) {
// in case of straight path
let headAngel = Math.atan(absDy / absDx);
if (showHead) {
x2 -= fHeadSize * (1 - headOffset) * xSign * Math.cos(headAngel);
y2 -= fHeadSize * (1 - headOffset) * ySign * Math.sin(headAngel);
headAngel *= ySign;
if (xSign < 0) headAngel = (Math.PI - headAngel * xSign) * xSign;
xHeadOffset = Math.cos(headAngel) * _headOffset - (Math.sin(headAngel) * fHeadSize) / 2;
yHeadOffset = (Math.cos(headAngel) * fHeadSize) / 2 + Math.sin(headAngel) * _headOffset;
headOrient = (headAngel * 180) / Math.PI;
}
let tailAngel = Math.atan(absDy / absDx);
if (showTail) {
x1 += fTailSize * (1 - tailOffset) * xSign * Math.cos(tailAngel);
y1 += fTailSize * (1 - tailOffset) * ySign * Math.sin(tailAngel);
tailAngel *= -ySign;
if (xSign > 0) tailAngel = (Math.PI - tailAngel * xSign) * xSign;
xTailOffset = Math.cos(tailAngel) * _tailOffset - (Math.sin(tailAngel) * fTailSize) / 2;
yTailOffset = (Math.cos(tailAngel) * fTailSize) / 2 + Math.sin(tailAngel) * _tailOffset;
tailOrient = (tailAngel * 180) / Math.PI;
}
} else {
// in case of smooth path
if (endAnchorPosition === 'middle') {
// in case a middle anchor is chosen for endAnchor choose from which side to attach to the middle of the element
if (absDx > absDy) {
endAnchorPosition = xSign ? 'left' : 'right';
} else {
endAnchorPosition = ySign ? 'top' : 'bottom';
}
}
if (showHead) {
if (['left', 'right'].includes(endAnchorPosition)) {
xHeadOffset += _headOffset * xSign;
x2 -= fHeadSize * (1 - headOffset) * xSign; //same!
yHeadOffset += (fHeadSize * xSign) / 2;
if (endAnchorPosition === 'left') {
headOrient = 0;
if (xSign < 0) headOrient += 180;
} else {
headOrient = 180;
if (xSign > 0) headOrient += 180;
}
} else if (['top', 'bottom'].includes(endAnchorPosition)) {
xHeadOffset += (fHeadSize * -ySign) / 2;
yHeadOffset += _headOffset * ySign;
y2 -= fHeadSize * ySign - yHeadOffset;
if (endAnchorPosition === 'top') {
headOrient = 270;
if (ySign > 0) headOrient += 180;
} else {
headOrient = 90;
if (ySign < 0) headOrient += 180;
}
}
}
}
if (showTail && cu !== 0) {
if (['left', 'right'].includes(startAnchorPosition)) {
xTailOffset += _tailOffset * -xSign;
x1 += fTailSize * xSign + xTailOffset;
yTailOffset += -(fTailSize * xSign) / 2;
if (startAnchorPosition === 'left') {
tailOrient = 180;
if (xSign < 0) tailOrient += 180;
} else {
tailOrient = 0;
if (xSign > 0) tailOrient += 180;
}
} else if (['top', 'bottom'].includes(startAnchorPosition)) {
yTailOffset += _tailOffset * -ySign;
y1 += fTailSize * ySign + yTailOffset;
xTailOffset += (fTailSize * ySign) / 2;
if (startAnchorPosition === 'top') {
tailOrient = 90;
if (ySign > 0) tailOrient += 180;
} else {
tailOrient = 270;
if (ySign < 0) tailOrient += 180;
}
}
}
let arrowHeadOffset = { x: xHeadOffset, y: yHeadOffset };
let arrowTailOffset = { x: xTailOffset, y: yTailOffset };
let cpx1 = x1,
cpy1 = y1,
cpx2 = x2,
cpy2 = y2;
let curvesPossibilities = {};
if (path === 'smooth')
curvesPossibilities = {
hh: () => {
//horizontal - from right to left or the opposite
cpx1 += absDx * cu * xSign;
cpx2 -= absDx * cu * xSign;
},
vv: () => {
//vertical - from top to bottom or opposite
cpy1 += absDy * cu * ySign;
cpy2 -= absDy * cu * ySign;
},
hv: () => {
// start horizontally then vertically
// from v side to h side
cpx1 += absDx * cu * xSign;
cpy2 -= absDy * cu * ySign;
},
vh: () => {
// start vertically then horizontally
// from h side to v side
cpy1 += absDy * cu * ySign;
cpx2 -= absDx * cu * xSign;
},
};
else if (path === 'grid') {
curvesPossibilities = {
hh: () => {
cpx1 += (absDx * gridBreak.relative + gridBreak.abs) * xSign;
cpx2 -= (absDx * (1 - gridBreak.relative) - gridBreak.abs) * xSign;
if (showHead) {
cpx1 -= ((fHeadSize * (1 - headOffset)) / 2) * xSign;
cpx2 += ((fHeadSize * (1 - headOffset)) / 2) * xSign;
}
if (showTail) {
cpx1 -= ((fTailSize * (1 - tailOffset)) / 2) * xSign;
cpx2 += ((fTailSize * (1 - tailOffset)) / 2) * xSign;
}
},
vv: () => {
cpy1 += (absDy * gridBreak.relative + gridBreak.abs) * ySign;
cpy2 -= (absDy * (1 - gridBreak.relative) - gridBreak.abs) * ySign;
if (showHead) {
cpy1 -= ((fHeadSize * (1 - headOffset)) / 2) * ySign;
cpy2 += ((fHeadSize * (1 - headOffset)) / 2) * ySign;
}
if (showTail) {
cpy1 -= ((fTailSize * (1 - tailOffset)) / 2) * ySign;
cpy2 += ((fTailSize * (1 - tailOffset)) / 2) * ySign;
}
},
hv: () => {
cpx1 = x2;
},
vh: () => {
cpy1 = y2;
},
};
}
// smart select best curve for the current anchors
let selectedCurviness = '';
if (['left', 'right'].includes(startAnchorPosition)) selectedCurviness += 'h';
else if (['bottom', 'top'].includes(startAnchorPosition)) selectedCurviness += 'v';
else if (startAnchorPosition === 'middle') selectedCurviness += 'm';
if (['left', 'right'].includes(endAnchorPosition)) selectedCurviness += 'h';
else if (['bottom', 'top'].includes(endAnchorPosition)) selectedCurviness += 'v';
else if (endAnchorPosition === 'middle') selectedCurviness += 'm';
if (absDx > absDy) selectedCurviness = selectedCurviness.replace(/m/g, 'h');
else selectedCurviness = selectedCurviness.replace(/m/g, 'v');
curvesPossibilities[selectedCurviness]();
cpx1 += _cpx1Offset;
cpy1 += _cpy1Offset;
cpx2 += _cpx2Offset;
cpy2 += _cpy2Offset;
////////////////////////////////////
// canvas smart size adjustments
const [xSol1, xSol2] = buzzierMinSols(x1, cpx1, cpx2, x2);
const [ySol1, ySol2] = buzzierMinSols(y1, cpy1, cpy2, y2);
if (xSol1 < 0) excLeft += -xSol1;
if (xSol2 > absDx) excRight += xSol2 - absDx;
if (ySol1 < 0) excUp += -ySol1;
if (ySol2 > absDy) excDown += ySol2 - absDy;
if (path === 'grid') {
excLeft += _calc;
excRight += _calc;
excUp += _calc;
excDown += _calc;
}
x1 += excLeft;
x2 += excLeft;
y1 += excUp;
y2 += excUp;
cpx1 += excLeft;
cpx2 += excLeft;
cpy1 += excUp;
cpy2 += excUp;
const cw = absDx + excLeft + excRight,
ch = absDy + excUp + excDown;
cx0 -= excLeft;
cy0 -= excUp;
//labels
const bzx = bzFunction(x1, cpx1, cpx2, x2);
const bzy = bzFunction(y1, cpy1, cpy2, y2);
const labelStartPos = { x: bzx(0.01), y: bzy(0.01) };
const labelMiddlePos = { x: bzx(0.5), y: bzy(0.5) };
const labelEndPos = { x: bzx(0.99), y: bzy(0.99) };
let arrowPath;
if (path === 'grid') {
// todo: support gridRadius
// arrowPath = `M ${x1} ${y1} L ${cpx1 - 10} ${cpy1} a10,10 0 0 1 10,10
// L ${cpx2} ${cpy2 - 10} a10,10 0 0 0 10,10 L ${x2} ${y2}`;
arrowPath = `M ${x1} ${y1} L ${cpx1} ${cpy1} L ${cpx2} ${cpy2} ${x2} ${y2}`;
} else if (path === 'smooth') arrowPath = `M ${x1} ${y1} C ${cpx1} ${cpy1}, ${cpx2} ${cpy2}, ${x2} ${y2}`;
return {
cx0,
cy0,
x1,
x2,
y1,
y2,
cw,
ch,
cpx1,
cpy1,
cpx2,
cpy2,
dx,
dy,
absDx,
absDy,
headOrient,
tailOrient,
labelStartPos,
labelMiddlePos,
labelEndPos,
excLeft,
excRight,
excUp,
excDown,
headOffset: _headOffset,
arrowHeadOffset,
arrowTailOffset,
startPoints,
endPoints,
mainDivPos,
xSign,
ySign,
lineLength: lineRef.current?.getTotalLength() ?? 0,
fHeadSize,
fTailSize,
arrowPath,
};
}; | the_stack |
import { size } from '@antv/util';
import 'jest-extended';
import { getEngine, View } from '../../../../src';
import { createCanvas, createDiv } from '../../../util/dom';
const data = [
{ city: '杭州', sale: 100, category: '电脑' },
{ city: '广州', sale: 30, category: '电脑' },
{ city: '上海', sale: 200, category: '鼠标' },
{ city: '呼和浩特', sale: 10, category: '鼠标' },
];
const renderer = 'canvas';
describe('View', () => {
const div = createDiv();
const canvas = createCanvas({
container: div,
renderer,
});
const backgroundGroup = canvas.addGroup();
const middleGroup = canvas.addGroup();
const foregroundGroup = canvas.addGroup();
const view = new View({
id: 'onlyView',
parent: null,
canvas,
foregroundGroup,
middleGroup,
backgroundGroup,
padding: 5,
visible: false,
});
it('constructor', () => {
expect(view.canvas).toBeInstanceOf(getEngine(renderer).Canvas);
// @ts-ignore
expect(view.backgroundGroup).toBeInstanceOf(getEngine(renderer).Group);
// @ts-ignore
expect(view.middleGroup).toBeInstanceOf(getEngine(renderer).Group);
// @ts-ignore
expect(view.foregroundGroup).toBeInstanceOf(getEngine(renderer).Group);
expect(view.visible).toBeFalse();
expect(view.id).toBe('onlyView');
});
it('region', () => {
view.render();
// region -> view bbox
expect({
x: view.viewBBox.x,
y: view.viewBBox.y,
width: view.viewBBox.width,
height: view.viewBBox.height,
}).toEqual({
x: 0,
y: 0,
width: 800,
height: 600,
});
expect({
x: view.coordinateBBox.x,
y: view.coordinateBBox.y,
width: view.coordinateBBox.width,
height: view.coordinateBBox.height,
}).toEqual({
x: 5,
y: 5,
width: 790,
height: 590,
});
});
it('data', () => {
view.data(data);
expect(view.getOptions().data).toEqual(data);
});
it('source', () => {
// deperated method
view.source(data);
expect(view.getOptions().data).toEqual(data);
});
it('axis', () => {
view.axis(false);
expect(view.getOptions().axes).toBe(false);
});
it('legend', () => {
view.legend({
position: 'right',
});
expect(view.getOptions().legends).toEqual({
position: 'right',
});
view.legend(false);
expect(view.getOptions().legends).toBe(false);
});
it('tooltip', () => {
view.tooltip(false);
expect(view.getOptions().tooltip).toBe(false);
view.tooltip({
showTitle: false,
});
expect(view.getOptions().tooltip).toEqual({
showTitle: false,
});
});
it('filter', () => {
view.filter('sale', (sale: number) => sale <= 150);
expect(size(view.getOptions().filters)).toBe(1);
expect(view.getOptions().filters.sale).toBeDefined();
view.filter('sale', null);
expect(size(view.getOptions().filters)).toBe(0);
expect(view.getOptions().filters.sale).toBeUndefined();
view.filter('sale', (sale: number) => sale <= 150);
view.filter('city', (city: string) => city.length <= 2);
expect(size(view.getOptions().filters)).toEqual(2);
// @ts-ignore
view.doFilterData();
// @ts-ignore
expect(view.filteredData).toEqual([
{ city: '杭州', sale: 100, category: '电脑' },
{ city: '广州', sale: 30, category: '电脑' },
]);
});
it('coordinate', () => {
// @ts-ignore
view.createCoordinate();
expect(view.getCoordinate().type).toEqual('rect');
let c = view.coordinate({
type: 'theta',
});
expect(c.getOption().type).toEqual('theta');
c = view.coordinate();
expect(c.getOption().type).toBe('rect');
c = view.coordinate('rect');
expect(c.getOption().type).toEqual('rect');
view.render();
expect(view.getCoordinate().getWidth()).toEqual(790);
expect(view.getCoordinate().getHeight()).toEqual(590);
});
it('coord', () => {
const c = view.coord('rect');
expect(c.getOption().type).toEqual('rect');
});
it('animate', () => {
// @ts-ignore 默认执行动画
expect(view.options.animate).toBe(true);
view.animate(false);
// @ts-ignore
expect(view.options.animate).toBe(false);
});
it('theme', () => {
view.theme({ xxx: 1 });
// @ts-ignore
expect(view.getTheme().xxx).toBe(1);
expect(view.getTheme().defaultColor).toBe('#5B8FF9');
});
it('geometry', () => {
view.polygon().position('city*category').color('sale');
view.render();
expect(view.geometries.length).toEqual(1);
expect(size(view.geometries[0].scales)).toEqual(3);
expect(view.geometries[0].scales.city.ticks).toEqual(['杭州', '广州']);
expect(view.geometries[0].scales.sale.values).toEqual([100, 30, 200, 10]);
// @ts-ignore
expect(view.geometries[0].animateOption).toBe(false);
expect(view.getCoordinate().getWidth()).toBeWithin(780, 800);
expect(view.getCoordinate().getHeight()).toBeWithin(580, 600);
expect(view.geometries[0].visible).toBe(false);
expect(view.foregroundGroup.get('visible')).toBeFalse();
});
it('component', () => {
expect(view.getComponents().length).toEqual(0);
view.axis(true);
view.legend(true);
view.render();
expect(view.getComponents().length).toEqual(4);
expect(view.controllers[2].visible).toBe(false);
const bbox = view.getComponents()[0].component.getBBox();
expect(bbox.height).toEqual(20.5);
});
it('layout result', () => {
expect(view.coordinateBBox.x).toBeGreaterThanOrEqual(view.viewBBox.x);
expect(view.coordinateBBox.y).toBeGreaterThanOrEqual(view.viewBBox.y);
expect(view.getCoordinate().getWidth()).toBeLessThanOrEqual(view.viewBBox.width);
expect(view.getCoordinate().getHeight()).toBeLessThanOrEqual(view.viewBBox.height);
});
it('getXScale', () => {
expect(view.getXScale().field).toEqual('city');
});
it('getYScales', () => {
expect(view.getYScales().map((s) => s.field)).toEqual(['category']);
});
it('getGroupScales', () => {
expect(view.getGroupScales().map((s) => s.field)).toEqual([]);
});
it('getLegendAttributes', () => {
expect(
view
.getLegendAttributes()
.map((a) => a.getScale(a.type))
.map((s) => s.field)
).toEqual(['sale']);
});
it('getSnapRecords()', () => {
const point = view.getXY({ city: '杭州', sale: 100, category: '电脑' });
const snapRecords = view.getSnapRecords(point);
expect(snapRecords.length).toBe(1);
expect(snapRecords[0]._origin).toEqual({ city: '杭州', sale: 100, category: '电脑' });
});
it('changeData', () => {
const geometries = view.geometries;
view.changeData([
...data,
{ city: '杭州', sale: 40, category: '鼠标' },
{ city: '广州', sale: 90, category: '鼠标' },
]);
// @ts-ignore
expect(view.filteredData.length).toEqual(4);
// 几何标记是同一个实例
expect(geometries[0] === view.geometries[0]).toEqual(true);
});
it('show()', () => {
view.show();
expect(view.visible).toBe(true);
expect(view.geometries[0].visible).toBe(true);
expect(view.controllers[2].visible).toBe(true);
expect(view.foregroundGroup.get('visible')).toBeTrue();
});
it('hide()', () => {
view.hide();
expect(view.visible).toBe(false);
expect(view.geometries[0].visible).toBe(false);
expect(view.controllers[2].visible).toBe(false);
expect(view.foregroundGroup.get('visible')).toBe(false);
});
it('changeVisible', () => {
view.changeVisible(false);
expect(view.visible).toBe(false);
view.changeVisible(true);
expect(view.visible).toBe(true);
});
it('getXY', () => {
const position = view.getXY({ city: '杭州', sale: 40, category: '鼠标' });
expect(position.x).toBe(202.5);
});
it('showTooltip', () => {
let result;
let type;
view.on('tooltip:show', (ev) => {
result = ev.data;
type = ev.type;
});
const position = view.getXY({ city: '杭州', sale: 40, category: '鼠标' });
view.showTooltip(position);
expect(result).toBeDefined();
expect(result.items[0].data).toEqual({ city: '杭州', sale: 40, category: '鼠标' });
expect(type).toBe('tooltip:show');
});
it('tooltip:change', () => {
const fn = jest.fn();
view.on('tooltip:change', fn);
view.showTooltip(view.getXY({ city: '杭州', sale: 40, category: '鼠标' }));
expect(fn).not.toBeCalled();
view.showTooltip(view.getXY({ city: '广州', sale: 90, category: '鼠标' }));
expect(fn).toBeCalled();
});
it('hideTooltip', () => {
const fn = jest.fn();
view.on('tooltip:hide', fn);
view.hideTooltip();
expect(fn).toBeCalled();
});
it('lockTooltip', () => {
view.lockTooltip();
expect(view.isTooltipLocked()).toBeTrue();
// @ts-ignore
expect(div.getElementsByClassName('g2-tooltip')[0].style['pointer-events']).toBe('auto');
});
it('unlockTooltip', () => {
view.unlockTooltip();
expect(view.isTooltipLocked()).toBeFalse();
// @ts-ignore
expect(div.getElementsByClassName('g2-tooltip')[0].style['pointer-events']).toBe('none');
});
it('filtered group scale values', () => {
const dom = createDiv();
const canvas1 = createCanvas({
container: dom,
renderer,
});
const view1 = new View({
parent: null,
canvas: canvas1,
foregroundGroup: canvas.addGroup(),
middleGroup: canvas.addGroup(),
backgroundGroup: canvas.addGroup(),
padding: 5,
visible: false,
});
view1.data(data);
view1.filter('category', (category: string) => category === '电脑');
view1.filter('city', (city: string) => city === '杭州');
// 测试 filterData API
expect(
view1.filterData([
{ city: '杭州', category: '电脑' },
{ city: '杭州', category: 'xx' },
])
).toEqual([{ city: '杭州', category: '电脑' }]);
expect(view1.filterFieldData('city', [{ city: '杭州' }])).toEqual([{ city: '杭州' }]);
const geometry = view1.line().position('city*sale').color('category');
view1.render();
expect(geometry.scales.category.values).toEqual(['电脑', '鼠标']);
expect(geometry.scales.city.values).toEqual(['杭州']);
view1.filter('category', null);
view1.filter('city', null);
view1.render(true);
expect(geometry.scales.category.values).toEqual(['电脑', '鼠标']);
expect(geometry.scales.city.values).toEqual(['杭州', '广州', '上海', '呼和浩特']);
});
}); | the_stack |
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from "react"
import marked from "marked"
import { graphql, formatError, parse, typeFromAST } from "graphql"
class MiniGraphiQL extends React.Component {
// Lifecycle
constructor(props) {
super()
const query = props.query.replace(/^\s+/, "")
// Initialize state
this.state = {
query: query,
variables: props.variables,
response: null,
variableToType: getVariableToType(props.schema, query),
}
this._editorQueryID = 0
}
render() {
const editor = (
<QueryEditor
key="query-editor"
schema={this.props.schema}
value={this.state.query}
onEdit={this._handleEditQuery.bind(this)}
runQuery={this._runQueryFromEditor.bind(this)}
/>
)
return (
<div className="miniGraphiQL">
{Object.keys(this.state.variableToType).length > 0 ? (
<div className="hasVariables">
{editor}
<VariableEditor
value={this.state.variables}
variableToType={this.state.variableToType}
onEdit={this._handleEditVariables.bind(this)}
onRunQuery={this._runQuery.bind(this)}
/>
</div>
) : (
editor
)}
<ResultViewer value={this.state.response} />
</div>
)
}
componentDidMount() {
this._runQueryFromEditor()
}
// Private methods
_runQueryFromEditor() {
this.setState({
variableToType: getVariableToType(this.props.schema, this.state.query),
})
this._runQuery()
}
async _runQuery() {
this._editorQueryID++
var queryID = this._editorQueryID
try {
const result = await graphql({
schema: this.props.schema,
source: this.state.query,
variableValues: JSON.parse(this.state.variables || "{}"),
rootValue: this.props.rootValue,
})
if (result.errors) {
result.errors = result.errors.map(formatError)
}
if (queryID === this._editorQueryID) {
this.setState({ response: JSON.stringify(result, null, 2) })
}
} catch (error) {
if (queryID === this._editorQueryID) {
this.setState({ response: JSON.stringify(error, null, 2) })
}
}
}
_handleEditQuery(value) {
this.setState({ query: value })
}
_handleEditVariables(value) {
this.setState({ variables: value })
}
}
/**
* QueryEditor
*
* Maintains an instance of CodeMirror responsible for editing a GraphQL query.
*
* Props:
*
* - schema: A GraphQLSchema instance enabling editor linting and hinting.
* - value: The text of the editor.
* - onEdit: A function called when the editor changes, given the edited text.
*
*/
class QueryEditor extends React.Component {
constructor(props) {
super()
// Keep a cached version of the value, this cache will be updated when the
// editor is updated, which can later be used to protect the editor from
// unnecessary updates during the update lifecycle.
this.cachedValue = props.value || ""
}
/**
* Public API for retrieving the CodeMirror instance from this
* React component.
*/
getCodeMirror() {
return this.editor
}
componentDidMount() {
var CodeMirror = require("codemirror")
require("codemirror/addon/hint/show-hint")
require("codemirror/addon/comment/comment")
require("codemirror/addon/edit/matchbrackets")
require("codemirror/addon/edit/closebrackets")
require("codemirror/addon/lint/lint")
require("codemirror/keymap/sublime")
require("codemirror-graphql/hint")
require("codemirror-graphql/lint")
require("codemirror-graphql/mode")
this.editor = CodeMirror(this.domNode, {
value: this.props.value || "",
viewportMargin: Infinity,
tabSize: 2,
mode: "graphql",
theme: "graphiql",
keyMap: "sublime",
autoCloseBrackets: true,
matchBrackets: true,
showCursorWhenSelecting: true,
lint: {
schema: this.props.schema,
onUpdateLinting: this._didLint.bind(this),
},
hintOptions: {
schema: this.props.schema,
closeOnUnfocus: false,
completeSingle: false,
},
extraKeys: {
"Cmd-Space": () => this.editor.showHint({ completeSingle: false }),
"Ctrl-Space": () => this.editor.showHint({ completeSingle: false }),
"Alt-Space": () => this.editor.showHint({ completeSingle: false }),
"Shift-Space": () => this.editor.showHint({ completeSingle: false }),
"Cmd-Enter": () => {
if (this.props.onRunQuery) {
this.props.onRunQuery()
}
},
"Ctrl-Enter": () => {
if (this.props.onRunQuery) {
this.props.onRunQuery()
}
},
// Editor improvements
"Ctrl-Left": "goSubwordLeft",
"Ctrl-Right": "goSubwordRight",
"Alt-Left": "goGroupLeft",
"Alt-Right": "goGroupRight",
},
})
this.editor.on("change", this._onEdit.bind(this))
this.editor.on("keyup", this._onKeyUp.bind(this))
this.editor.on("hasCompletion", this._onHasCompletion.bind(this))
}
componentWillUnmount() {
this.editor = null
}
componentDidUpdate(prevProps) {
// Ensure the changes caused by this update are not interpretted as
// user-input changes which could otherwise result in an infinite
// event loop.
this.ignoreChangeEvent = true
if (this.props.schema !== prevProps.schema) {
this.editor.options.lint.schema = this.props.schema
this.editor.options.hintOptions.schema = this.props.schema
CodeMirror.signal(this.editor, "change", this.editor)
}
if (
this.props.value !== prevProps.value &&
this.props.value !== this.cachedValue
) {
this.cachedValue = this.props.value
this.editor.setValue(this.props.value)
}
this.ignoreChangeEvent = false
}
_didLint(annotations) {
if (annotations.length === 0) {
this.props.runQuery()
}
}
_onKeyUp(cm, event) {
var code = event.keyCode
if (
(code >= 65 && code <= 90) || // letters
(!event.shiftKey && code >= 48 && code <= 57) || // numbers
(event.shiftKey && code === 189) || // underscore
(event.shiftKey && code === 50) || // @
(event.shiftKey && code === 57) // (
) {
this.editor.execCommand("autocomplete")
}
}
_onEdit() {
if (!this.ignoreChangeEvent) {
this.cachedValue = this.editor.getValue()
if (this.props.onEdit) {
this.props.onEdit(this.cachedValue)
}
}
}
_onHasCompletion(cm, data) {
onHasCompletion(cm, data, this.props.onHintInformationRender)
}
render() {
return <div className="query-editor" ref={e => (this.domNode = e)} />
}
}
/**
* ResultViewer
*
* Maintains an instance of CodeMirror for viewing a GraphQL response.
*
* Props:
*
* - value: The text of the editor.
*
*/
class ResultViewer extends React.Component {
componentDidMount() {
var CodeMirror = require("codemirror")
require("codemirror-graphql/results/mode")
this.viewer = CodeMirror(this.domNode, {
value: this.props.value || "",
viewportMargin: Infinity,
readOnly: true,
theme: "graphiql",
mode: "graphql-results",
keyMap: "sublime",
extraKeys: {
// Editor improvements
"Ctrl-Left": "goSubwordLeft",
"Ctrl-Right": "goSubwordRight",
"Alt-Left": "goGroupLeft",
"Alt-Right": "goGroupRight",
},
})
}
componentWillUnmount() {
this.viewer = null
}
shouldComponentUpdate(nextProps) {
return this.props.value !== nextProps.value
}
componentDidUpdate() {
this.viewer.setValue(this.props.value || "")
}
render() {
return <div className="result-window" ref={e => (this.domNode = e)} />
}
}
/**
* VariableEditor
*
* An instance of CodeMirror for editing variables defined in QueryEditor.
*
* Props:
*
* - variableToType: A mapping of variable name to GraphQLType.
* - value: The text of the editor.
* - onEdit: A function called when the editor changes, given the edited text.
*
*/
class VariableEditor extends React.Component {
constructor(props) {
super()
// Keep a cached version of the value, this cache will be updated when the
// editor is updated, which can later be used to protect the editor from
// unnecessary updates during the update lifecycle.
this.cachedValue = props.value || ""
this._onKeyUp = this.onKeyUp.bind(this)
this._onEdit = this.onEdit.bind(this)
this._onHasCompletion = this.onHasCompletion.bind(this)
}
componentDidMount() {
// Lazily require to ensure requiring GraphiQL outside of a Browser context
// does not produce an error.
const CodeMirror = require("codemirror")
require("codemirror/addon/hint/show-hint")
require("codemirror/addon/edit/matchbrackets")
require("codemirror/addon/edit/closebrackets")
require("codemirror/addon/lint/lint")
require("codemirror/keymap/sublime")
require("codemirror-graphql/variables/hint")
require("codemirror-graphql/variables/lint")
require("codemirror-graphql/variables/mode")
this.editor = CodeMirror(this.domNode, {
value: this.props.value || "",
viewportMargin: Infinity,
tabSize: 2,
mode: "graphql-variables",
theme: "graphiql",
keyMap: "sublime",
autoCloseBrackets: true,
matchBrackets: true,
showCursorWhenSelecting: true,
lint: {
variableToType: this.props.variableToType,
onUpdateLinting: this._didLint.bind(this),
},
hintOptions: {
variableToType: this.props.variableToType,
},
extraKeys: {
"Cmd-Space": () => this.editor.showHint({ completeSingle: false }),
"Ctrl-Space": () => this.editor.showHint({ completeSingle: false }),
"Alt-Space": () => this.editor.showHint({ completeSingle: false }),
"Shift-Space": () => this.editor.showHint({ completeSingle: false }),
"Cmd-Enter": () => {
if (this.props.onRunQuery) {
this.props.onRunQuery()
}
},
"Ctrl-Enter": () => {
if (this.props.onRunQuery) {
this.props.onRunQuery()
}
},
// Editor improvements
"Ctrl-Left": "goSubwordLeft",
"Ctrl-Right": "goSubwordRight",
"Alt-Left": "goGroupLeft",
"Alt-Right": "goGroupRight",
},
})
this.editor.on("change", this._onEdit)
this.editor.on("keyup", this._onKeyUp)
this.editor.on("hasCompletion", this._onHasCompletion)
}
componentDidUpdate(prevProps) {
const CodeMirror = require("codemirror")
// Ensure the changes caused by this update are not interpretted as
// user-input changes which could otherwise result in an infinite
// event loop.
this.ignoreChangeEvent = true
if (this.props.variableToType !== prevProps.variableToType) {
this.editor.options.lint.variableToType = this.props.variableToType
this.editor.options.hintOptions.variableToType = this.props.variableToType
CodeMirror.signal(this.editor, "change", this.editor)
}
if (
this.props.value !== prevProps.value &&
this.props.value !== this.cachedValue
) {
this.cachedValue = this.props.value
this.editor.setValue(this.props.value)
}
this.ignoreChangeEvent = false
}
componentWillUnmount() {
this.editor.off("change", this._onEdit)
this.editor.off("keyup", this._onKeyUp)
this.editor.off("hasCompletion", this._onHasCompletion)
this.editor = null
}
render() {
return <div className="variable-editor" ref={e => (this.domNode = e)} />
}
_didLint(annotations) {
if (annotations.length === 0) {
this.props.onRunQuery()
}
}
onKeyUp(cm, event) {
const code = event.keyCode
if (
(code >= 65 && code <= 90) || // letters
(!event.shiftKey && code >= 48 && code <= 57) || // numbers
(event.shiftKey && code === 189) || // underscore
(event.shiftKey && code === 222) // "
) {
this.editor.execCommand("autocomplete")
}
}
onEdit() {
if (!this.ignoreChangeEvent) {
this.cachedValue = this.editor.getValue()
if (this.props.onEdit) {
this.props.onEdit(this.cachedValue)
}
}
}
onHasCompletion(cm, data) {
onHasCompletion(cm, data, this.props.onHintInformationRender)
}
}
/**
* Render a custom UI for CodeMirror's hint which includes additional info
* about the type and description for the selected context.
*/
function onHasCompletion(cm, data, onHintInformationRender) {
var CodeMirror = require("codemirror")
var wrapper
var information
// When a hint result is selected, we touch the UI.
CodeMirror.on(data, "select", (ctx, el) => {
// Only the first time (usually when the hint UI is first displayed)
// do we create the wrapping node.
if (!wrapper) {
// Wrap the existing hint UI, so we have a place to put information.
var hintsUl = el.parentNode
var container = hintsUl.parentNode
wrapper = document.createElement("div")
container.appendChild(wrapper)
// CodeMirror vertically inverts the hint UI if there is not enough
// space below the cursor. Since this modified UI appends to the bottom
// of CodeMirror's existing UI, it could cover the cursor. This adjusts
// the positioning of the hint UI to accomodate.
var top = hintsUl.style.top
var bottom = ""
var cursorTop = cm.cursorCoords().top
if (parseInt(top, 10) < cursorTop) {
top = ""
bottom = window.innerHeight - cursorTop + 3 + "px"
}
// Style the wrapper, remove positioning from hints. Note that usage
// of this option will need to specify CSS to remove some styles from
// the existing hint UI.
wrapper.className = "CodeMirror-hints-wrapper"
wrapper.style.left = hintsUl.style.left
wrapper.style.top = top
wrapper.style.bottom = bottom
hintsUl.style.left = ""
hintsUl.style.top = ""
// This "information" node will contain the additional info about the
// highlighted typeahead option.
information = document.createElement("div")
information.className = "CodeMirror-hint-information"
if (bottom) {
wrapper.appendChild(information)
wrapper.appendChild(hintsUl)
} else {
wrapper.appendChild(hintsUl)
wrapper.appendChild(information)
}
// When CodeMirror attempts to remove the hint UI, we detect that it was
// removed from our wrapper and in turn remove the wrapper from the
// original container.
var onRemoveFn
wrapper.addEventListener(
"DOMNodeRemoved",
(onRemoveFn = event => {
if (event.target === hintsUl) {
wrapper.removeEventListener("DOMNodeRemoved", onRemoveFn)
wrapper.parentNode.removeChild(wrapper)
wrapper = null
information = null
onRemoveFn = null
}
})
)
}
// Now that the UI has been set up, add info to information.
var description = ctx.description
? marked(ctx.description, { smartypants: true })
: "Self descriptive."
var type = ctx.type
? '<span class="infoType">' + String(ctx.type) + "</span>"
: ""
information.innerHTML =
'<div class="content">' +
(description.slice(0, 3) === "<p>"
? "<p>" + type + description.slice(3)
: type + description) +
"</div>"
// Additional rendering?
if (onHintInformationRender) {
onHintInformationRender(information)
}
})
}
function getVariableToType(schema, documentStr) {
if (!documentStr || !schema) {
return {}
}
try {
const documentAST = parse(documentStr)
const variableToType = Object.create(null)
documentAST.definitions.forEach(definition => {
if (definition.kind === "OperationDefinition") {
const variableDefinitions = definition.variableDefinitions
if (variableDefinitions) {
variableDefinitions.forEach(({ variable, type }) => {
const inputType = typeFromAST(schema, type)
if (inputType) {
variableToType[variable.name.value] = inputType
}
})
}
}
})
return variableToType
} catch (e) {
// ignore
}
return {}
}
export default MiniGraphiQL | the_stack |
export const cacheDir = './.alm';
export const title = "Application Lifecycle Management tools for TypeScript";
export enum TriState {
Unknown,
True,
False,
}
export const errors = {
CALLED_WHEN_NO_ACTIVE_PROJECT_FOR_FILE_PATH: "A query *that needs an active project* was made when there is no active project for given filePath",
CALLED_WHEN_NO_ACTIVE_PROJECT_GLOBAL: "A query *that needs an active project* was made when there is no active project"
}
/**
* Some session constants
*/
/** When a new server stats up */
export const urlHashNormal = "root";
/** When user requests a new window */
export const urlHashNewSession = "new-session";
/** When alm is started ni debug mode */
export const urlHashDebugSession = "debug";
/**
* FARM : Don't want to crash by running out of memory / ui preference
*/
export const maxCountFindAndReplaceMultiResults = 1000;
export interface FilePathPosition {
filePath: string;
position: EditorPosition;
}
/**
* Session related types
*/
export interface SessionsFileContents {
sessions: SessionOnDisk[];
/** Relative path to tsconfig.json including file name */
relativePathToTsconfig?: string;
}
export interface SessionOnDisk {
/** unique to each session */
id: string;
/** the tabs the user has open */
tabLayout: TabLayoutOnDisk;
selectedTabId: string | null;
/** Duration since epoch */
lastUsed: number;
/**
* NOTE: there can be any number of other settings that are type checked only at the client
*/
}
/**
* Same as a `TabInstance` but works with `relativeUrl`
*/
export interface TabInstanceOnDisk {
id: string;
relativeUrl: string;
/** Any additional data that the tab wants to serialize */
additionalData: any;
}
/**
* What the main application tab container knows about a tab
*/
export interface TabInstance {
id: string;
url: string;
/** Any additional data that the tab wants to serialize */
additionalData: any;
}
/**
* Just the layout information we serialize
* A recursive structure for re-storing tab information
*/
export type TabLayout = {
type: 'stack' | 'row' | 'column' | string;
/** out of 100 */
width: number;
/** out of 100 */
height: number;
/** Only exist on a `stack` */
tabs: TabInstance[];
activeItemIndex: number;
/** Only exists if type is not `stack` */
subItems: TabLayout[];
}
/** Same as above with `ui` stuff replaced with `disk` stuff */
export type TabLayoutOnDisk = {
type: 'stack' | 'row' | 'column' | string;
/** out of 100 */
width: number;
/** out of 100 */
height: number;
/** Only exist on a `stack` */
tabs: TabInstanceOnDisk[];
activeItemIndex: number;
/** Only exists if type is not `stack` */
subItems: TabLayoutOnDisk[];
}
/**
* Refactoring related stuff
*/
export interface Refactoring extends ts.TextChange {
filePath: string;
}
/**
* Because you generally want to transact per file
* You don't need to create this manually. Just use `getRefactoringsByFilePath`
*/
export interface RefactoringsByFilePath {
[filePath: string]: Refactoring[];
}
/**
* Reason is we want to transact by file path
* Also, this function sorts per file so you can apply refactorings in order 🌹
*/
export function getRefactoringsByFilePath(refactorings: Refactoring[]) {
var loc: RefactoringsByFilePath = {};
for (let refac of refactorings) {
if (!loc[refac.filePath]) loc[refac.filePath] = [];
loc[refac.filePath].push(refac);
}
// sort each of these in descending by start location
for (let filePath in loc) {
let refactorings = loc[filePath];
refactorings.sort((a: Refactoring, b: Refactoring) => {
return (b.span.start - a.span.start);
});
}
return loc;
}
/**
* For file listing we like to know if its a dir or file
*/
export enum FilePathType {
File,
Dir
}
export interface FilePath {
filePath: string;
type: FilePathType
}
/** For incremental buffered file listing changes */
export interface FileListingDelta {
addedFilePaths: FilePath[];
removedFilePaths: FilePath[];
}
/**
* File model stuff
*/
export interface FileStatus {
filePath: string;
saved: boolean;
eol: string;
}
/**
* Project JS File status stuff
*/
export interface JSOutputStatus {
/** Its convinient to have it hare */
inputFilePath: string;
/** One of the various states */
state: JSOutputState;
/** Only if the state is for some JS file */
outputFilePath?: string;
}
/** The JS file can only be in one of these states */
export enum JSOutputState {
/** If emit skipped (Either emit is blocked or compiler options are noEmit) or perhaps there isn't a JS file emit for this (e.g .d.ts files) */
NoJSFile = 1,
/** If JS file then its one of these */
JSUpToDate,
JSOutOfDate,
}
export type JSOutputStatusCache = { [inputFilePath: string]: JSOutputStatus }
export type LiveBuildResults = {
builtCount: number;
totalCount: number;
}
/** Query response for individual file query */
export type GetJSOutputStatusResponse = {
inActiveProject: boolean,
/** Only present if the file as in active project */
outputStatus?: JSOutputStatus
};
/**
* Complete related stuff
*/
/** Some constants */
export const completionKindSnippet = "snippet";
export const completionKindPath = "path";
/** A completion */
export interface Completion {
/** stuff like ("var"|"method"etc) | "snippet" | "path" etc */
kind: string;
/** stuff like "toString", "./relativePath" */
name: string;
/**
* This is displayParts (for functions). Empty for `var` etc.
*/
display?: string;
/**
* the docComment if any
* Also: `fullPath` for path ;)
*/
comment?: string;
/** Only valid if `kind` is snippet */
insertText?: string;
/** Only valid if `kind` is path completion */
textEdit?: CodeEdit;
}
/**
* Really only used when moving data around.
* We still map it to `Completion` before we handing it over for *autocomplete*
*/
export interface PathCompletion {
fileName: string;
relativePath: string;
fullPath: string;
}
export interface PathCompletionForAutocomplete extends PathCompletion {
pathStringRange: {
from: number,
to: number,
}
}
/**
* Editor Config stuff
*/
export interface EditorOptions {
tabSize: number;
newLineCharacter: string;
convertTabsToSpaces: boolean;
trimTrailingWhitespace: boolean;
insertFinalNewline: boolean;
}
/**
* TSConfig details
*/
/**
* These are the projects that the user can select from.
* Just the name and config path really
*/
export interface AvailableProjectConfig {
name: string;
/** Virtual projects are projects rooted at some `.ts`/`.js` file */
isVirtual: boolean;
/** If the project is virtual than this will point to a `.ts`/`.js` file */
tsconfigFilePath: string;
}
/**
* Project Data : the config file + all the file path contents
*/
export interface FilePathWithContent {
filePath: string;
contents: string;
}
export interface ProjectDataLoaded {
configFile: TypeScriptConfigFileDetails;
filePathWithContents: FilePathWithContent[];
}
/**
* Our analysis of stuff we want from package.json
*/
export interface PackageJsonParsed {
/** We need this as this is the name the user is going to import **/
name: string;
/** we need this to figure out the basePath (will depend on how `outDir` is relative to this directory) */
directory: string;
/** This is going to be typescript.definition */
definition: string;
main: string;
}
/**
* This is `TypeScriptProjectRawSpecification` parsed further
* Designed for use throughout out code base
*/
export interface TsconfigJsonParsed {
compilerOptions: ts.CompilerOptions;
files: string[];
typings: string[]; // These are considered externs for .d.ts. Note : duplicated in files
formatCodeOptions: ts.FormatCodeOptions;
compileOnSave: boolean;
buildOnSave: boolean;
package?: PackageJsonParsed;
}
export interface TypeScriptConfigFileDetails {
/** The path to the project file. This acts as the baseDIR */
projectFileDirectory: string;
/** The actual path of the project file (including tsconfig.json) or srcFile if `inMemory` is true */
projectFilePath: string;
project: TsconfigJsonParsed;
inMemory: boolean;
}
/**
* Git types
*/
/** Note : 0,2 means lines 0,1,2 */
export type GitDiffSpan = {
from: number;
to: number;
}
export type GitDiff = {
added: GitDiffSpan[];
removed: number[];
modified: GitDiffSpan[];
}
export type GitAddAllCommitAndPushQuery = {
message: string;
}
export type GitAddAllCommitAndPushResult
= {
type: 'error';
error: string;
}
| {
type: 'success'
log: string;
};
/**
* Errors
*/
export enum ErrorsDisplayMode {
all = 1,
openFiles = 2,
}
/**
* Documentation related stuff
*/
/** for project symbols view */
export interface NavigateToItem {
name: string;
kind: string;
filePath: string;
position: EditorPosition;
fileName: string;
}
export interface GetNavigateToItemsResponse {
items: NavigateToItem[];
}
/**
* The TypeDoc icons a pretty expansive 🌹 with a few ideas that I disagree with / or think are too difficult.
* E.g the type `event`. The "grey" coloring of the global functions. The following is a simpler subset.
*
* Places that need to be kept in sync:
* - typeIcon.tsx: the location in typeIcons.svg
* - the legend component
* - the server responses
*/
export enum IconType {
/**
* There can be only one global
* Any of the remaining things can be either in a module or global
*/
Global,
Namespace, // same for module
Variable,
Function,
FunctionGeneric,
Enum,
EnumMember,
Interface,
InterfaceGeneric,
InterfaceConstructor,
InterfaceProperty,
InterfaceMethod,
InterfaceMethodGeneric,
InterfaceIndexSignature,
Class,
ClassGeneric,
ClassConstructor,
ClassProperty,
ClassMethod,
ClassMethodGeneric,
ClassIndexSignature,
}
/**
* The documentation model
* We have
* - global
* - modules
*
* These are just "name" + containers for OtherThings
*
* OtherThings are just:
* - class
* - namespace
* - interface / type
* - enum
*
* Where Namespace is just a "name" container for OtherThings
*/
export interface DocumentedType {
name: string;
icon: IconType,
comment: string,
subItems: DocumentedType[];
location: DocumentedTypeLocation;
}
export type DocumentedTypeLocation = FilePathPosition;
/** For top level module names */
export interface GetTopLevelModuleNamesResponse {
/** Present in our project */
files: DocumentedType[];
}
/**
*
*
*
* UML View
*
*
*
*/
/** Class */
export interface UMLClass {
// Similar to Documented type.
name: string;
icon: IconType
location: DocumentedTypeLocation;
// Unlike DocumentedType.subItems we have `members`
members: UMLClassMember[];
// Also extends if any
extends?: UMLClass;
}
export enum UMLClassMemberVisibility {
Public = 1,
Private,
Protected
}
export enum UMLClassMemberLifetime {
Instance = 1,
Static
}
export interface UMLClassMember {
name: string
icon: IconType;
location: DocumentedTypeLocation;
visibility: UMLClassMemberVisibility;
lifetime: UMLClassMemberLifetime;
/** Default is false */
override?: UMLClassMember;
}
/**
* Ts Flow types
*/
/**
* Get the root ts flow points
*/
export interface TsFlowRootQuery {
filePath: string;
}
export interface TsFlowPoint {
filePath: string;
from: EditorPosition;
to: EditorPosition;
displayName: string;
}
export interface TsFlowRootResponse {
flowPoints: TsFlowPoint[];
}
/**
* Live Analysis
* e.g. when a member overrides a parent we show a hint.
*/
export interface LiveAnalysisQuery {
filePath: string;
}
export interface LiveAnalysisResponse {
overrides: LiveAnalysisOverrideInfo[]
}
export interface LiveAnalysisOverrideInfo {
line: number;
overrides: UMLClassMember;
}
/**
* Monaco command pallete support
*/
export interface MonacoActionInformation {
label: string,
id: string;
kbd: string | null;
}
/**
* When a worker is *working* it can send us a message
*/
export type Working = {
working: boolean
}
/**
* Tested
*/
export enum TestStatus {
NotRunYet = 1,
Fail,
Success,
Skipped,
}
export type TestErrorStack = FilePathPosition[];
export type TestLogPosition = {
lastPositionInFile: EditorPosition;
isActualLastInFile: boolean;
stack: TestErrorStack;
}
export type TestError = {
testLogPosition: TestLogPosition;
message: string;
stack: TestErrorStack;
}
export type TestResult = {
description: string;
status: TestStatus;
testLogPosition: TestLogPosition;
/** None if skipped */
durationMs?: number;
/** Only in case of test failure */
error?: TestError;
}
export type TestSuiteResult = {
description: string;
testLogPosition: TestLogPosition;
stats: TestContainerStats;
/** Can have other TestSuites or Tests */
suites: TestSuiteResult[];
tests: TestResult[];
}
export type TestLog = {
/**
* The log might not be pointing to the same file. We should still show it against
* `this` spec execution
*/
testLogPosition: TestLogPosition;
/**
* Arguments.
* Note: they will be stringified and unstringified by the time they make it to the UI
*/
args: any[];
}
/** The root of any testing system is a test file */
export type TestModule = {
filePath: string;
/** From instrumentation */
logs: TestLog[];
/**
* Also contained in the `suites`
* But raised up for better module level overview
*/
testResults: TestResult[];
/** Present once its been run */
suites: TestSuiteResult[];
stats: TestContainerStats;
}
/** Both modules and suites are test containers and have these stats */
export type TestContainerStats = {
testCount: number;
passCount: number;
failCount: number;
skipCount: number;
/** milliseconds */
durationMs: number;
};
export type TestSuitesByFilePath = {
[filePath: string]: TestModule;
}
/** We just push the modules that have updated */
export type TestResultsDelta = {
updatedModuleMap: TestSuitesByFilePath,
clearedModules: string[];
initial: boolean;
}
export type TestSuitePosition = {
title: string;
/**
* The last origin in the file
*/
testLogPosition: TestLogPosition;
}
export type TestItPosition = {
title: string;
/**
* The last origin in the file
*/
testLogPosition: TestLogPosition;
}
//////////////////////
// Error cache
//////////////////////
export type CodeErrorSource =
'tsconfig'
| 'projectService'
| 'linter'
| 'tested'
export interface CodeError {
source: CodeErrorSource;
filePath: string;
from: EditorPosition;
to: EditorPosition;
message: string;
preview: string;
level: 'warning' | 'error';
}
export interface ErrorsByFilePath {
[filePath: string]: CodeError[];
}
/**
* We don't send all the errors to front end continuously.
* But we do still tell the total count.
*/
export interface LimitedErrorsUpdate {
errorsByFilePath: ErrorsByFilePath;
totalCount: number;
syncCount: number;
tooMany: boolean;
}
/**
* Allows true syncing of one cache with another
*/
export type ErrorCacheDelta = {
added: ErrorsByFilePath;
removed: ErrorsByFilePath;
initial: boolean;
}
/** Lots of things don't have a good error. But we would like to be consistent even with simple errors */
export function makeBlandError(filePath: string, error: string, source: CodeErrorSource): CodeError {
return {
source,
filePath,
from: {
line: 0,
ch: 0
},
to: {
line: 0,
ch: 0
},
message: error,
preview: null,
level: 'error'
}
}
//////////////////////
// Live Demo
//////////////////////
export type LiveDemoData =
| {
type: 'start'
}
| {
type: 'data'
data: string
}
| {
type: 'end'
code: number
};
//////////////////////
// Live react demo
//////////////////////
export const liveDemoMountUrl = '/demo';
export type LiveDemoBundleResult =
| {
type: 'bundling'
}
| {
type: 'success'
}
| {
type: 'error',
error: string
} | the_stack |
import { expect } from 'chai';
import { shallow } from 'enzyme';
import * as React from 'react';
import MemberPage from '../memberPage';
import MemberEntity from '../../../api/memberEntity';
import MemberForm from '../memberForm';
import MemberErrors from '../../../validations/memberFormErrors';
import * as toastr from 'toastr';
import { hashHistory } from 'react-router';
describe('MemberPage presentational component', () => {
it('should renders a div with text equals "No data" and calls to initializeNewMember' +
'passing required properties with default values', () => {
let initializeNewMemberMock = sinon.spy();
let properties = {
initializeNewMember: initializeNewMemberMock
};
let memberPageWrapper = shallow(
<MemberPage {...properties} />
);
expect(memberPageWrapper.type()).to.be.equals('div');
expect(memberPageWrapper.text()).to.be.equals('No data');
expect(initializeNewMemberMock.called).to.be.true;
});
//"sinson.test" make automatic cleanup instead of use sinon.restore
//https://semaphoreci.com/community/tutorials/best-practices-for-spies-stubs-and-mocks-in-sinon-js
it('should calls to componentWillMount' +
'passing required properties with default values', sinon.test(() => {
//Just to get tsd instellisense
let sinon: Sinon.SinonStatic = this;
let initializeNewMemberMock = sinon.spy();
let componentWillMountMock = sinon.stub(MemberPage.prototype, 'componentWillMount');
let properties = {
initializeNewMember: initializeNewMemberMock
};
let memberPageWrapper = shallow(
<MemberPage {...properties} />
);
expect(componentWillMountMock.calledOnce).to.be.true;
}).bind(this));
it('should renders a div with text equals "No data" and calls to initializeNewMember' +
'passing params property equals 1', () => {
let initializeNewMemberMock = sinon.spy();
let loadMemberMock = sinon.spy();
let properties = {
params: 1,
initializeNewMember: initializeNewMemberMock,
loadMember: loadMemberMock
};
let memberPageWrapper = shallow(
<MemberPage {...properties} />
);
expect(memberPageWrapper.type()).to.be.equals('div');
expect(memberPageWrapper.text()).to.be.equals('No data');
expect(initializeNewMemberMock.called).to.be.true;
expect(loadMemberMock.called).to.be.false;
expect(loadMemberMock.calledWith(1)).to.be.false;
});
it('should renders a div with text equals "No data" and calls to initializeNewMember' +
'passing params property equals "test"', () => {
let initializeNewMemberMock = sinon.spy();
let loadMemberMock = sinon.spy();
let properties = {
params: "test",
initializeNewMember: initializeNewMemberMock,
loadMember: loadMemberMock
};
let memberPageWrapper = shallow(
<MemberPage {...properties} />
);
expect(memberPageWrapper.type()).to.be.equals('div');
expect(memberPageWrapper.text()).to.be.equals('No data');
expect(initializeNewMemberMock.called).to.be.true;
expect(loadMemberMock.called).to.be.false;
expect(loadMemberMock.calledWith(1)).to.be.false;
});
it('should renders a div with text equals "No data" and calls to initializeNewMember' +
'passing params property equals { id: "test" }', () => {
let initializeNewMemberMock = sinon.spy();
let loadMemberMock = sinon.spy();
let properties = {
params: {
id: "test"
},
initializeNewMember: initializeNewMemberMock,
loadMember: loadMemberMock
};
let memberPageWrapper = shallow(
<MemberPage {...properties} />
);
expect(memberPageWrapper.type()).to.be.equals('div');
expect(memberPageWrapper.text()).to.be.equals('No data');
expect(initializeNewMemberMock.called).to.be.true;
expect(loadMemberMock.called).to.be.false;
expect(loadMemberMock.calledWith(1)).to.be.false;
});
it('should renders a div with text equals "No data" and calls to loadMember' +
'passing params property equals { id: 1 }', () => {
let initializeNewMemberMock = sinon.spy();
let loadMemberMock = sinon.spy();
let properties = {
params: {
id: 1
},
initializeNewMember: initializeNewMemberMock,
loadMember: loadMemberMock
};
let memberPageWrapper = shallow(
<MemberPage {...properties} />
);
expect(memberPageWrapper.type()).to.be.equals('div');
expect(memberPageWrapper.text()).to.be.equals('No data');
expect(initializeNewMemberMock.called).to.be.false;
expect(loadMemberMock.called).to.be.true;
expect(loadMemberMock.calledWith(1)).to.be.true;
});
it('should renders a MemberForm with member equals { id: 1 } and calls to initializeNewMember' +
'passing member equals { id: 1 } and params equals undefined', () => {
let initializeNewMemberMock = sinon.spy();
let member = new MemberEntity();
member.id = 1;
let properties = {
initializeNewMember: initializeNewMemberMock,
member: member,
params: undefined
};
let memberPageWrapper = shallow(
<MemberPage {...properties} />
);
expect(memberPageWrapper.type()).to.be.equals(MemberForm);
expect(memberPageWrapper.prop('member')).not.to.be.undefined;
expect(memberPageWrapper.prop('member').id).to.be.equals(member.id);
expect(initializeNewMemberMock.called).to.be.true;
});
it('should renders a MemberForm with errors property equals undefined' +
'passing errors equals undefined', () => {
let initializeNewMemberMock = sinon.spy();
let member = new MemberEntity();
member.id = 1;
let properties = {
initializeNewMember: initializeNewMemberMock,
member: member,
errors: undefined
};
let memberPageWrapper = shallow(
<MemberPage {...properties} />
);
expect(memberPageWrapper.type()).to.be.equals(MemberForm);
expect(memberPageWrapper.prop('errors')).to.be.undefined;
});
it('should renders a MemberForm with errors property equals { login: "test" }' +
'passing errors equals { login: "test" }', () => {
let initializeNewMemberMock = sinon.spy();
let member = new MemberEntity();
member.id = 1;
let errors = new MemberErrors();
errors.login = "test";
let properties = {
initializeNewMember: initializeNewMemberMock,
member: member,
errors: errors
};
let memberPageWrapper = shallow(
<MemberPage {...properties} />
);
expect(memberPageWrapper.type()).to.be.equals(MemberForm);
expect(memberPageWrapper.prop('errors')).not.to.be.undefined;
expect(memberPageWrapper.prop('errors').login).to.be.equals('test');
});
it('should renders a MemberForm and calls to fireValidationFieldValueChanged with ' +
'arguments field equals "testField" and value equals "testValue" ' +
'when user write in element with name property equals "testField" and ' +
'value property equals "testValue"', () => {
let initializeNewMemberMock = sinon.spy();
let member = new MemberEntity();
member.id = 1;
let fireValidationMock = sinon.spy();
let properties = {
initializeNewMember: initializeNewMemberMock,
member: member,
fireValidationFieldValueChanged: fireValidationMock
};
let memberPageWrapper = shallow(
<MemberPage {...properties} />
);
memberPageWrapper.simulate('change', {
target: {
name: "testField",
value: "testValue"
}
})
expect(fireValidationMock.called).to.be.true;
expect(fireValidationMock.calledWith("testField", "testValue")).to.be.true;
});
it('should renders a MemberForm and calls to saveMember with arguments ' +
'member equals member property and calls to preventDefault ' +
'when user click on save button', () => {
let initializeNewMemberMock = sinon.spy();
let member = new MemberEntity();
member.id = 1;
let saveMemberMock = sinon.spy();
let eventPreventDefaultMock = sinon.spy();
let properties = {
initializeNewMember: initializeNewMemberMock,
member: member,
saveMember: saveMemberMock
};
let memberPageWrapper = shallow(
<MemberPage {...properties} />
);
memberPageWrapper.simulate('save', {
preventDefault: eventPreventDefaultMock
})
expect(saveMemberMock.called).to.be.true;
expect(saveMemberMock.calledWith(member)).to.be.true;
expect(eventPreventDefaultMock.called).to.be.true;
});
it('should does not call to componentWillReceiveProps' +
'passing required properties with default values', sinon.test(() => {
let sinon: Sinon.SinonStatic = this;
let initializeNewMemberMock = sinon.spy();
let componentWillReceivePropsMock = sinon.stub(MemberPage.prototype, 'componentWillReceiveProps');
let properties = {
initializeNewMember: initializeNewMemberMock
};
let memberPageWrapper = shallow(
<MemberPage {...properties} />
);
expect(componentWillReceivePropsMock.calledOnce).to.be.false;
}).bind(this));
it('should does not call to componentWillReceiveProps' +
'passing saveCompleted equals false', sinon.test(() => {
let sinon: Sinon.SinonStatic = this;
let initializeNewMemberMock = sinon.spy();
let componentWillReceivePropsMock = sinon.stub(MemberPage.prototype, 'componentWillReceiveProps');
let properties = {
saveCompleted: false,
initializeNewMember: initializeNewMemberMock
};
let memberPageWrapper = shallow(
<MemberPage {...properties} />
);
expect(componentWillReceivePropsMock.calledOnce).to.be.false;
}).bind(this));
it('should calls to componentWillReceiveProps but does not calls to toastr.success()' +
'passing saveCompleted equals false and setting root component props with ' +
'saveCompleted property equals false', sinon.test(() => {
let sinon: Sinon.SinonStatic = this;
let initializeNewMemberMock = sinon.spy();
let componentWillReceivePropsMock = sinon.stub(MemberPage.prototype, 'componentWillReceiveProps');
let toastrMock = sinon.stub(toastr, 'success');
let properties = {
saveCompleted: false,
initializeNewMember: initializeNewMemberMock
};
let memberPageWrapper = shallow(
<MemberPage {...properties} />
);
memberPageWrapper.setProps({
saveCompleted: false
});
expect(componentWillReceivePropsMock.calledOnce).to.be.true;
expect(toastrMock.calledOnce).to.be.false;
}).bind(this));
it('should calls to componentWillReceiveProps but does not calls to toastr.success()' +
'passing saveCompleted equals true and setting root component props with ' +
'saveCompleted property equals true', sinon.test(() => {
let sinon: Sinon.SinonStatic = this;
let initializeNewMemberMock = sinon.spy();
let toastrMock = sinon.stub(toastr, 'success');
let properties = {
saveCompleted: true,
initializeNewMember: initializeNewMemberMock
};
let memberPageWrapper = shallow(
<MemberPage {...properties} />
);
memberPageWrapper.setProps({
saveCompleted: true
});
expect(toastrMock.calledOnce).to.be.false;
}).bind(this));
it('should calls to componentWillReceiveProps but does not calls to toastr.success()' +
'passing saveCompleted equals true and setting root component props with ' +
'saveCompleted property equals false', sinon.test(() => {
let sinon: Sinon.SinonStatic = this;
let initializeNewMemberMock = sinon.spy();
let toastrMock = sinon.stub(toastr, 'success');
let properties = {
saveCompleted: true,
initializeNewMember: initializeNewMemberMock
};
let memberPageWrapper = shallow(
<MemberPage {...properties} />
);
memberPageWrapper.setProps({
saveCompleted: false
});
expect(toastrMock.calledOnce).to.be.false;
}).bind(this));
it('should calls to componentWillReceiveProps and toastr.success("Author saved.")' +
'passing saveCompleted equals false and setting root component props with ' +
'saveCompleted property equals true', sinon.test(() => {
let sinon: Sinon.SinonStatic = this;
let initializeNewMemberMock = sinon.spy();
let resetSaveCompletedFlagMock = sinon.spy();
let toastrMock = sinon.stub(toastr, 'success');
let properties = {
saveCompleted: false,
resetSaveCompletedFlag: resetSaveCompletedFlagMock,
initializeNewMember: initializeNewMemberMock
};
let memberPageWrapper = shallow(
<MemberPage {...properties} />
);
memberPageWrapper.setProps({
saveCompleted: true
});
expect(toastrMock.calledOnce).to.be.true;
expect(toastrMock.calledWith('Author saved.')).to.be.true;
}).bind(this));
it('should calls to hashHistory.push("/members")' +
'passing saveCompleted equals false and setting root component props with ' +
'saveCompleted property equals true', sinon.test(() => {
let sinon: Sinon.SinonStatic = this;
let initializeNewMemberMock = sinon.spy();
let resetSaveCompletedFlagMock = sinon.spy();
let hashHistoryMock = sinon.stub(hashHistory, 'push');
let properties = {
saveCompleted: false,
resetSaveCompletedFlag: resetSaveCompletedFlagMock,
initializeNewMember: initializeNewMemberMock
};
let memberPageWrapper = shallow(
<MemberPage {...properties} />
);
memberPageWrapper.setProps({
saveCompleted: true
});
expect(hashHistoryMock.calledOnce).to.be.true;
expect(hashHistoryMock.calledWith('/members')).to.be.true;
}).bind(this));
it('should calls to resetSaveCompletedFlag' +
'passing saveCompleted equals false and setting root component props with ' +
'saveCompleted property equals true', () => {
let initializeNewMemberMock = sinon.spy();
let resetSaveCompletedFlagMock = sinon.spy();
let properties = {
saveCompleted: false,
resetSaveCompletedFlag: resetSaveCompletedFlagMock,
initializeNewMember: initializeNewMemberMock
};
let memberPageWrapper = shallow(
<MemberPage {...properties} />
);
memberPageWrapper.setProps({
saveCompleted: true
});
expect(resetSaveCompletedFlagMock.calledOnce).to.be.true;
});
}); | the_stack |
import { formatStats } from './formatStats';
import { select } from 'd3-selection';
import { symbolCircle, symbolCross, symbolSquare, symbolStar, symbolTriangle, symbolDiamond } from 'd3-shape';
import { resolveLabelCollision } from './collisionDetection';
export function formatDataLabel(d, labelAccessor, format, normalized?) {
const modifier = normalized ? d.getSum() : 1;
return format
? formatStats(d[labelAccessor] / modifier, format === 'normalized' ? '0[.][0]%' : format)
: d[labelAccessor] / modifier;
}
export const placeDataLabels = ({
root,
xScale,
yScale,
ordinalAccessor,
valueAccessor,
placement,
layout,
labelOffset,
radius,
chartType,
normalized,
avoidCollision
}: {
root?: any;
xScale?: any;
yScale?: any;
ordinalAccessor?: any;
valueAccessor?: any;
placement?: any;
layout?: any;
labelOffset?: any;
radius?: any;
chartType?: any;
normalized?: any;
avoidCollision?: {
runOccupancyBitmap: boolean;
bitmaps: any;
labelSelection: any;
avoidMarks: any;
validPositions: string[];
offsets: number[];
accessors: string[];
size: [number, number];
boundsScope?: string;
hideOnly?: boolean;
removeOnly?: boolean;
suppressMarkDraw?: boolean;
};
}) => {
let xPlacement;
let yPlacement;
let offset;
let offset2;
let textAnchor;
// console.log('placing data labels', root.size(), avoidCollision, placement);
if (chartType === 'bar') {
switch (placement) {
case 'auto':
if (layout === 'vertical') {
xPlacement = d => xScale(d[ordinalAccessor]) + xScale.bandwidth() / 2;
yPlacement = d => yScale(Math.max(0, d[valueAccessor]));
offset2 = '0.25em';
textAnchor = 'middle';
} else if (layout === 'horizontal') {
yPlacement = d => yScale(d[ordinalAccessor]) + yScale.bandwidth() / 2;
xPlacement = d => xScale(Math.max(0, d[valueAccessor]));
offset2 = '0.25em';
textAnchor = 'middle';
}
break;
case 'top':
xPlacement = d => xScale(d[ordinalAccessor]) + xScale.bandwidth() / 2;
yPlacement = d => yScale(Math.max(0, d[valueAccessor]));
offset = '-.3em';
textAnchor = 'middle';
break;
case 'bottom':
xPlacement = d => xScale(d[ordinalAccessor]) + xScale.bandwidth() / 2;
yPlacement = d => yScale(Math.min(0, d[valueAccessor]));
offset = '-.3em';
textAnchor = 'middle';
break;
case 'left':
yPlacement = d => yScale(d[ordinalAccessor]) + yScale.bandwidth() / 2;
xPlacement = d => xScale(Math.min(0, d[valueAccessor]));
offset = '.2em';
offset2 = '.3em';
textAnchor = 'start';
break;
case 'right':
yPlacement = d => yScale(d[ordinalAccessor]) + yScale.bandwidth() / 2;
xPlacement = d => xScale(Math.max(0, d[valueAccessor]));
offset = '.3em';
offset2 = '.3em';
textAnchor = 'start';
break;
case 'top-left':
yPlacement = d => yScale(d[ordinalAccessor]);
xPlacement = d => xScale(Math.min(0, d[valueAccessor]));
offset = '.2em';
offset2 = '-.2em';
textAnchor = 'start';
break;
case 'top-right':
yPlacement = d => yScale(d[ordinalAccessor]);
xPlacement = d => xScale(Math.max(0, d[valueAccessor]));
offset = '-3em';
offset2 = '-.2em';
textAnchor = 'start';
break;
case 'bottom-left':
yPlacement = d => yScale(d[ordinalAccessor]) + yScale.bandwidth();
xPlacement = d => xScale(Math.min(0, d[valueAccessor]));
offset = '.2em';
offset2 = '1em';
textAnchor = 'start';
break;
case 'bottom-right':
yPlacement = d => yScale(d[ordinalAccessor]) + yScale.bandwidth();
xPlacement = d => xScale(Math.max(0, d[valueAccessor]));
offset = '-3em';
offset2 = '1em';
textAnchor = 'start';
break;
}
} else if (chartType === 'stacked') {
const getMod = d => (normalized ? d.getSum() : 1);
if (layout === 'vertical') {
switch (placement) {
case 'auto':
xPlacement = d => xScale(d[ordinalAccessor]) + xScale.bandwidth() / 2;
yPlacement = d => (yScale(d.stackStart / getMod(d)) + yScale(d.stackEnd / getMod(d))) / 2;
offset2 = '0.25em';
textAnchor = 'middle';
break;
case 'bottom':
xPlacement = d => xScale(d[ordinalAccessor]) + xScale.bandwidth() / 2;
yPlacement = d => yScale(d.stackEnd / getMod(d));
offset = '-.3em';
textAnchor = 'middle';
break;
case 'top':
xPlacement = d => xScale(d[ordinalAccessor]) + xScale.bandwidth() / 2;
yPlacement = d => yScale(d.stackStart / getMod(d));
offset = '1em';
textAnchor = 'middle';
break;
case 'middle':
xPlacement = d => xScale(d[ordinalAccessor]) + xScale.bandwidth() / 2;
yPlacement = d => (yScale(d.stackStart / getMod(d)) + yScale(d.stackEnd / getMod(d))) / 2;
offset = '.3em';
textAnchor = 'middle';
break;
}
} else {
switch (placement) {
case 'auto':
yPlacement = d => yScale(d[ordinalAccessor]) + yScale.bandwidth() / 2 + 4;
xPlacement = d => (xScale(d.stackStart) + xScale(d.stackEnd)) / 2;
offset = '0em';
textAnchor = 'middle';
break;
case 'base':
yPlacement = d => yScale(d[ordinalAccessor]) + yScale.bandwidth() / 2 + 4;
xPlacement = d => (d.stackEnd < 0 ? xScale(d.stackStart / getMod(d)) : xScale(d.stackEnd / getMod(d)));
offset = d => (d.stackEnd < 0 ? '-.3em' : '.3em');
textAnchor = d => (d.stackEnd < 0 ? 'end' : 'start');
break;
case 'end':
yPlacement = d => yScale(d[ordinalAccessor]) + yScale.bandwidth() / 2 + 4;
xPlacement = d => (d.stackEnd < 0 ? xScale(d.stackEnd / getMod(d)) : xScale(d.stackStart / getMod(d)));
offset = d => (d.stackEnd < 0 ? '.3em' : '-.3em');
textAnchor = d => (d.stackEnd < 0 ? 'start' : 'end');
break;
case 'middle':
yPlacement = d => yScale(d[ordinalAccessor]) + yScale.bandwidth() / 2 + 4;
xPlacement = d => (xScale(d.stackStart) + xScale(d.stackEnd)) / 2;
offset = '0em';
textAnchor = 'middle';
break;
}
}
} else if (chartType === 'line') {
switch (placement) {
case 'auto':
xPlacement = d => xScale(d[ordinalAccessor]);
yPlacement = d => yScale(d[valueAccessor]);
offset2 = '-0.6em';
textAnchor = 'middle';
break;
case 'top':
xPlacement = d => xScale(d[ordinalAccessor]);
yPlacement = d => yScale(d[valueAccessor]);
offset2 = '-0.6em';
textAnchor = 'middle';
break;
case 'bottom':
xPlacement = d => xScale(d[ordinalAccessor]);
yPlacement = d => yScale(d[valueAccessor]) + 20;
textAnchor = 'middle';
break;
case 'left':
yPlacement = d => yScale(d[ordinalAccessor]);
xPlacement = d => xScale(d[valueAccessor]);
offset = '.2em';
textAnchor = 'start';
break;
case 'right':
yPlacement = d => yScale(d[ordinalAccessor]);
xPlacement = d => xScale(d[valueAccessor]) + 4;
offset = '.2em';
textAnchor = 'start';
break;
}
} else if (chartType === 'parallel') {
switch (placement) {
case 'auto':
xPlacement = d => xScale(d[ordinalAccessor]);
yPlacement = d => yScale(d);
offset = '0em';
offset2 = '0em';
textAnchor = 'middle';
break;
case 'bottom-right':
xPlacement = d => xScale(d[ordinalAccessor]);
yPlacement = d => yScale(d);
offset = '0.45em';
offset2 = '1.1em';
textAnchor = 'start';
break;
case 'top-right':
xPlacement = d => xScale(d[ordinalAccessor]);
yPlacement = d => yScale(d);
offset = '0.45em';
offset2 = '-0.3em';
textAnchor = 'start';
break;
case 'bottom-left':
xPlacement = d => xScale(d[ordinalAccessor]);
yPlacement = d => yScale(d);
offset = '-0.45em';
offset2 = '1.1em';
textAnchor = 'end';
break;
case 'top-left':
xPlacement = d => xScale(d[ordinalAccessor]);
yPlacement = d => yScale(d);
offset = '-0.45em';
offset2 = '-0.3em';
textAnchor = 'end';
break;
}
} else if (chartType === 'dumbbell') {
switch (placement) {
case 'ends':
xPlacement = d => (layout === 'vertical' ? xScale(d[ordinalAccessor]) : xScale(d[valueAccessor]) - d.offset);
yPlacement = d => (layout === 'vertical' ? yScale(d[valueAccessor]) + d.offset : yScale(d[ordinalAccessor]));
offset = d => {
return layout === 'vertical' && d.offset >= 0
? '0.9em'
: layout === 'vertical'
? '-0.3em'
: d.offset >= 0
? '-0.3em'
: '0.3em';
};
offset2 = layout === 'vertical' ? '0.0em' : '0.3em';
textAnchor = d => {
return layout === 'vertical' ? 'middle' : d.offset >= 0 ? 'end' : 'start';
};
break;
case 'auto': // copy of ends for auto collision
xPlacement = d => (layout === 'vertical' ? xScale(d[ordinalAccessor]) : xScale(d[valueAccessor]) - d.offset);
yPlacement = d => (layout === 'vertical' ? yScale(d[valueAccessor]) + d.offset : yScale(d[ordinalAccessor]));
offset = d => {
return layout === 'vertical' && d.offset >= 0
? '0.9em'
: layout === 'vertical'
? '-0.3em'
: d.offset >= 0
? '-0.3em'
: '0.3em';
};
offset2 = layout === 'vertical' ? '0.0em' : '0.3em';
textAnchor = d => {
return layout === 'vertical' ? 'middle' : d.offset >= 0 ? 'end' : 'start';
};
break;
case 'top':
yPlacement = d => yScale(d[ordinalAccessor]) - Math.abs(d.offset);
xPlacement = d => xScale(d[valueAccessor]);
offset2 = '-0.3em'; // d => -Math.abs(d.offset);
offset = '0.0em';
textAnchor = 'middle';
break;
case 'bottom':
yPlacement = d => yScale(d[ordinalAccessor]) + Math.abs(d.offset);
xPlacement = d => xScale(d[valueAccessor]) + 4;
offset2 = '0.9em'; // d => Math.abs(d.offset);
offset = '0.0em';
textAnchor = 'middle';
break;
case 'left':
yPlacement = d => yScale(d[valueAccessor]);
xPlacement = d => xScale(d[ordinalAccessor]) - 4 - Math.abs(d.offset);
offset2 = '0.0em'; // d => -Math.abs(d.offset);
offset = '0.3em';
textAnchor = 'end';
break;
case 'right':
yPlacement = d => yScale(d[valueAccessor]);
xPlacement = d => xScale(d[ordinalAccessor]) + 4 + Math.abs(d.offset);
offset2 = '0.0em'; // d => Math.abs(d.offset);
offset = '0.3em';
textAnchor = 'start';
break;
}
} else if (chartType === 'pie') {
switch (placement) {
case 'inside':
offset2 = '0.1em';
textAnchor = 'middle';
break;
case 'outside':
textAnchor = (d, i) => (d.endAngle < Math.PI || i === 0 ? 'start' : 'end');
xPlacement = d => (radius + 5) * Math.sin((d.startAngle + d.endAngle) / 2);
yPlacement = d => -(radius + 5) * Math.cos((d.startAngle + d.endAngle) / 2);
offset = d => (d.endAngle < Math.PI ? -labelOffset : labelOffset);
offset2 = d => (d.endAngle < Math.PI ? labelOffset : -labelOffset);
break;
case 'edge':
xPlacement = d => (radius + 10) * Math.sin(d.endAngle);
yPlacement = d => -(radius + 10) * Math.cos(d.endAngle);
offset = d => (d.endAngle < Math.PI ? -labelOffset : labelOffset);
offset2 = d => (d.endAngle < Math.PI ? labelOffset : -labelOffset);
textAnchor = (d, i) => (d.endAngle < Math.PI || i === 0 ? 'start' : 'end');
break;
case 'note':
textAnchor = (d, i) => (d.endAngle < Math.PI || i === 0 ? 'start' : 'end');
xPlacement = d => (radius + 5) * Math.sin((d.startAngle + d.endAngle) / 2);
yPlacement = d => -(radius + 5) * Math.cos((d.startAngle + d.endAngle) / 2);
offset = d => (d.endAngle < Math.PI ? -labelOffset : labelOffset);
offset2 = d => (d.endAngle < Math.PI ? labelOffset + 15 : -labelOffset + 15);
break;
case 'note_edge':
xPlacement = d => (radius + 10) * Math.sin(d.endAngle);
yPlacement = d => -(radius + 10) * Math.cos(d.endAngle);
offset = d => (d.endAngle < Math.PI ? -labelOffset : labelOffset);
offset2 = d => (d.endAngle < Math.PI ? labelOffset + 15 : -labelOffset + 15);
textAnchor = (d, i) => (d.endAngle < Math.PI || i === 0 ? 'start' : 'end');
break;
}
} else if (chartType === 'scatter') {
switch (placement) {
case 'auto':
xPlacement = d => xScale(d[ordinalAccessor]);
yPlacement = d => yScale(d[valueAccessor]);
offset2 = '0.25em';
textAnchor = 'middle';
break;
case 'middle':
xPlacement = d => xScale(d[ordinalAccessor]);
yPlacement = d => yScale(d[valueAccessor]);
offset2 = '0.25em';
textAnchor = 'middle';
break;
case 'top':
xPlacement = d => xScale(d[ordinalAccessor]);
yPlacement = d => yScale(d[valueAccessor]) - labelOffset;
offset2 = '-0.35em';
textAnchor = 'middle';
break;
case 'bottom':
xPlacement = d => xScale(d[ordinalAccessor]);
yPlacement = d => yScale(d[valueAccessor]) + labelOffset;
offset2 = '1.1em';
textAnchor = 'middle';
break;
case 'left':
xPlacement = d => xScale(d[ordinalAccessor]) - labelOffset;
yPlacement = d => yScale(d[valueAccessor]);
offset = '-.4em';
offset2 = '0.3em';
textAnchor = 'end';
break;
case 'right':
xPlacement = d => xScale(d[ordinalAccessor]) + labelOffset;
yPlacement = d => yScale(d[valueAccessor]);
offset = '.35em';
offset2 = '0.3em';
textAnchor = 'start';
break;
}
} else if (chartType === 'heat-map') {
xPlacement = d => xScale(d[ordinalAccessor]) + xScale.bandwidth() / 2;
yPlacement = d => yScale(d[valueAccessor]) + yScale.bandwidth() / 2;
offset2 = '.5em';
textAnchor = 'middle';
} else if (chartType === 'world-map') {
xPlacement = d => xScale([+d[ordinalAccessor], +d[valueAccessor]])[0];
yPlacement = d => xScale([+d[ordinalAccessor], +d[valueAccessor]])[1];
}
// we run bitmap if passed, not heat-map and whether we pass "auto" OR hideOnly with reg placement
const autoPlacementIndicator = avoidCollision && avoidCollision.runOccupancyBitmap && placement === 'auto';
const hideNoPlaceIndicator = avoidCollision && avoidCollision.hideOnly && !autoPlacementIndicator;
if (chartType !== 'heat-map' && autoPlacementIndicator && !hideNoPlaceIndicator) {
const bitmaps = resolveLabelCollision({
bitmaps: avoidCollision.bitmaps,
labelSelection: avoidCollision.labelSelection, // this should be root everytime basically...
avoidMarks: avoidCollision.avoidMarks,
validPositions: avoidCollision.validPositions,
offsets: avoidCollision.offsets,
accessors: avoidCollision.accessors,
size: avoidCollision.size,
boundsScope: avoidCollision.boundsScope,
hideOnly: hideNoPlaceIndicator, // should be false always
removeOnly: avoidCollision.removeOnly,
suppressMarkDraw: avoidCollision.suppressMarkDraw
});
// now that the collision check is done we apply original placement to anything hidden (not placed) by it
// this is needed because the marks will otherwise be placed at [0, 0], this util is expected to place them
// checking for data-label-hidden !== false will capture anything that didn't go through collision and/or
// was hidden by it, though we need to ignore this if we are in the setLabelOpacity interaction updates
// thus we use the class temporarily added to each label to handle that
// update during label interaction updates, we are excluding hidden labels that we moved from this now as well
root
.filter((_, i, n) => select(n[i]).attr('data-label-moved') !== 'true' && !select(n[i]).classed('collision-added'))
.attr('x', xPlacement)
.attr('y', yPlacement)
.attr(layout === 'vertical' ? 'dy' : 'dx', offset)
.attr(layout === 'vertical' ? 'dx' : 'dy', offset2)
.attr('text-anchor', textAnchor);
return bitmaps;
} else if (chartType !== 'heat-map' && hideNoPlaceIndicator) {
root.each((_, i, n) => {
// doing an each.select will make sure we jump the transition passed in
// in our mark item bounds we need to pass the result of original dataLabel util
select(n[i])
.attr('data-x', xPlacement)
.attr('data-use-dx', true)
.attr('dx', layout === 'vertical' ? offset2 : offset)
.attr('data-y', yPlacement)
.attr('data-use-dy', true)
.attr('dy', layout === 'vertical' ? offset : offset2)
.attr('text-anchor', textAnchor);
});
// next we draw the bitmap with only the marks
let bitmaps;
if (!avoidCollision.suppressMarkDraw) {
bitmaps = resolveLabelCollision({
bitmaps: avoidCollision.bitmaps,
labelSelection: select('.empty-stuff-vcc-do-not-use'), // this should be root everytime basically...
avoidMarks: avoidCollision.avoidMarks,
validPositions: ['middle'],
offsets: [1],
accessors: avoidCollision.accessors,
size: avoidCollision.size
});
}
// next we try to place labels based on the util placed positions
bitmaps = resolveLabelCollision({
bitmaps: bitmaps || avoidCollision.bitmaps,
labelSelection: root,
avoidMarks: [],
validPositions: ['middle'],
offsets: [1],
accessors: avoidCollision.accessors,
size: avoidCollision.size,
hideOnly: hideNoPlaceIndicator, // should be true always
removeOnly: avoidCollision.removeOnly,
suppressMarkDraw: avoidCollision.suppressMarkDraw
});
// hideOnly is passed, we need to place everything as we usually would
root
.attr('x', xPlacement)
.attr('y', yPlacement)
.attr(layout === 'vertical' ? 'dy' : 'dx', offset)
.attr(layout === 'vertical' ? 'dx' : 'dy', offset2)
.attr('text-anchor', textAnchor);
return bitmaps;
} else {
// NOTE: heatmap has shortcut collision detection already for labels
// (the accessibility.showSmallLabels prop handles this automatically and more efficiently due to the algorithmic concerns)
root
.attr('x', xPlacement)
.attr('y', yPlacement)
.attr(layout === 'vertical' ? 'dy' : 'dx', offset)
.attr(layout === 'vertical' ? 'dx' : 'dy', offset2)
.attr('text-anchor', textAnchor);
return null;
}
};
export function getDataSymbol(symbolFunc, symbolType) {
const symbolMap = {
cross: symbolCross,
circle: symbolCircle,
square: symbolSquare,
star: symbolStar,
triangle: symbolTriangle,
diamond: symbolDiamond
};
return symbolMap[symbolType] ? symbolFunc.type(symbolMap[symbolType])() : symbolFunc.type(symbolCircle)();
} | the_stack |
import { KubeConfig, V1EnvVar, V1PodSpec } from "@kubernetes/client-node";
import { DockerImages, getImagePullSecrets } from "@opstrace/controller-config";
import {
ConfigMap,
Deployment,
K8sResource,
ResourceCollection,
Secret,
Service,
V1ServicemonitorResource
} from "@opstrace/kubernetes";
import { Integration } from "../../reducers/graphql/integrations";
import { toTenantName, toTenantNamespace } from "../../helpers";
import { State } from "../../reducer";
import { log } from "@opstrace/utils";
export function IntegrationResources(
state: State,
kubeConfig: KubeConfig
): ResourceCollection {
const collection = new ResourceCollection();
// Get all integrations from GraphQL/Postgres
state.graphql.Integrations.resources.forEach(integration => {
toKubeResources(state, integration, kubeConfig).forEach(resource =>
collection.add(resource)
);
});
return collection;
}
type BlackboxConfig = {
// Probes, each entry in the array is a set of key value pairs to be set as params in the HTTP url.
// Passed to the prometheus operator as endpoints to monitor.
// For example {target: "example.com", module: "http_2xx"} -> "/probe?target=example.com&module=http_2xx"
probes: { [key: string]: string }[];
// Config listing modules that may be referenced by probes.
// Passed to the blackbox integration configuration, or the default configuration is used if this is undefined.
// For example this may configure an "http_2xx" module to be referenced by the probes.
configFile: string | null;
};
type BlackboxIntegrationData = {
// config: nested JSON object
// These are processed by the controller:
// - need to configure prometheus with the probe URLs
// - need to configure labeling for each of the probes
config: BlackboxConfig;
// Blackbox doesn't use credentials, but we still nest the config under 'config' to allow later expansion if needed.
};
type CloudwatchIntegrationData = {
// config: raw yaml file content passthrough
config: string;
// credentials: Envvar passthrough
// In practice this is expected to contain AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
credentials: { [key: string]: string };
};
type StackdriverIntegrationData = {
// config: nested JSON object
// The keys are expected to be strings like "google.project-id" which is converted to an "STACKDRIVER_EXPORTER_GOOGLE_PROJECT_ID" envvar.
// The values are expected to either be strings or arrays of strings.
config: Record<string, unknown>;
// credentials: json file content passthrough
credentials: string;
};
type AzureIntegrationData = {
// config: raw yaml file content passthrough
config: string;
// credentials: Envvar passthrough
// In practice this is expected to contain AZURE_SUBSCRIPTION_ID, AZURE_TENANT_ID, AZURE_CLIENT_ID, and AZURE_CLIENT_SECRET
credentials: { [key: string]: string } | null;
};
const toKubeResources = (
state: State,
integration: Integration,
kubeConfig: KubeConfig
): K8sResource[] => {
// Name for any k8s objects like Deployment, ConfigMap, and/or Secret associated with this secret
const k8sName = `integration-${integration.key}`;
// Look up tenant name from the id
const tenantName = toTenantName(
integration.tenant_id,
state.tenants.list.tenants
);
if (tenantName == null) {
log.warning(
"Skipping deployment of %s integration '%s': missing tenant_id=%s in local state: %s",
integration.kind,
integration.name,
integration.tenant_id,
state.tenants.list.tenants
);
return [];
}
const k8sLabels = {
app: k8sName,
// DO NOT remove tenant label: used by Prometheus operator to filter the ServiceMonitors
tenant: tenantName,
// DO NOT use user-provided integration.name: label values cannot contain e.g. spaces or symbols
"opstrace.com/integration-key": integration.key,
"opstrace.com/integration-kind": integration.kind
};
const k8sMetadata = {
name: k8sName,
namespace: toTenantNamespace(tenantName),
labels: k8sLabels
};
const resources: Array<K8sResource> = [];
let podSpec: V1PodSpec;
const customMonitorEndpoints: Array<Record<string, unknown>> = [];
// If the integration needs a configmap (named k8sName), the data is set here
let configMapData: { [key: string]: string } | null = null;
// If the integration needs a secret (named k8sName), the base64-encoded data is set here
let secretData: { [key: string]: string } | null = null;
if (integration.kind == "exporter-cloudwatch") {
const integrationData = integration.data as CloudwatchIntegrationData;
configMapData = { "config.yml": integrationData.config };
secretData = integrationData.credentials;
podSpec = {
containers: [
{
name: "exporter",
image: DockerImages.exporterCloudwatch,
// Import all of the key/value pairs from the credentials as secrets.
// For example this may include AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
envFrom: [{ secretRef: { name: k8sName } }],
ports: [{ name: "metrics", containerPort: 9106 }],
volumeMounts: [{ name: "config", mountPath: "/config" }],
// Use the 'healthy' endpoint
// See https://github.com/prometheus/cloudwatch_exporter/blob/f0e84d6/src/main/java/io/prometheus/cloudwatch/WebServer.java#L43
startupProbe: {
httpGet: {
path: "/-/healthy",
// eslint-disable-next-line @typescript-eslint/no-explicit-any
port: "metrics" as any
},
failureThreshold: 3,
initialDelaySeconds: 10,
periodSeconds: 30,
successThreshold: 1,
timeoutSeconds: 5
}
}
],
volumes: [
{
name: "config",
configMap: {
name: k8sName
}
}
]
};
} else if (integration.kind == "exporter-cloud-monitoring") {
const integrationData = integration.data as StackdriverIntegrationData;
secretData = { "secret.json": integrationData.credentials };
// We do not support changing the following envvars, because they are part of the integration:
// - GOOGLE_APPLICATION_CREDENTIALS must be "/credential/secret.json"
// - STACKDRIVER_EXPORTER_WEB_LISTEN_ADDRESS must be ":9255" (default)
// - STACKDRIVER_EXPORTER_WEB_TELEMETRY_PATH must be "/metrics" (default)
// To enforce this, we always set these envvars, and block the user from overriding them.
const env: Array<V1EnvVar> = [];
env.push({
name: "GOOGLE_APPLICATION_CREDENTIALS",
value: "/credential/secret.json"
});
env.push({
name: "STACKDRIVER_EXPORTER_WEB_LISTEN_ADDRESS",
value: ":9255"
});
env.push({
name: "STACKDRIVER_EXPORTER_WEB_TELEMETRY_PATH",
value: "/metrics"
});
const bannedEnv = new Set<string>();
env.forEach(e => bannedEnv.add(e.name));
// For now we just pass through all configuration options as envvars.
// However, changing some of thees options might cause problems.
// For example we assume that the following are left with their defaults:
Object.entries(integrationData.config).forEach(([k, v]) => {
// Env name: Add prefix, uppercase, and replace any punctuation with '_'
// Example: google.project-id => STACKDRIVER_EXPORTER_GOOGLE_PROJECT_ID
const name =
"STACKDRIVER_EXPORTER_" + k.toUpperCase().replace(/\W/g, "_");
if (bannedEnv.has(name)) {
// Disallow user override of this env setting
return;
}
// Env value: Original string as-is, or array converted to comma-separated string.
const value =
v instanceof Array
? v.toString() // convert array to comma-separated string (e.g. ["foo","bar"] => "foo,bar" without [])
: (v as string); // plain string conversion, but for arrays this would include the []
env.push({ name, value });
});
podSpec = {
containers: [
{
name: "exporter",
image: DockerImages.exporterStackdriver,
env,
ports: [{ name: "metrics", containerPort: 9255 }],
volumeMounts: [{ name: "credential", mountPath: "/credential" }],
// Use the root path, which just returns a stub HTML page
// see https://github.com/prometheus-community/stackdriver_exporter/blob/42badeb/stackdriver_integration.go#L178
startupProbe: {
httpGet: {
path: "/",
// eslint-disable-next-line @typescript-eslint/no-explicit-any
port: "metrics" as any
},
failureThreshold: 3,
initialDelaySeconds: 10,
periodSeconds: 30,
successThreshold: 1,
timeoutSeconds: 5
}
}
],
volumes: [
{
name: "credential",
secret: {
secretName: k8sName
}
}
]
};
} else if (integration.kind == "exporter-azure") {
const integrationData = integration.data as AzureIntegrationData;
configMapData = { "azure.yml": integrationData.config };
secretData = integrationData.credentials;
podSpec = {
containers: [
{
name: "exporter",
image: DockerImages.exporterAzure,
command: [
"/bin/azure_metrics_exporter",
"--config.file=/config/azure.yml"
],
// Import all of the key/value pairs from the credentials as secrets.
// For example create AZURE_TENANT_ID and AZURE_CLIENT_ID envvars.
envFrom: [{ secretRef: { name: k8sName } }],
ports: [{ name: "metrics", containerPort: 9276 }],
volumeMounts: [{ name: "config", mountPath: "/config" }],
// Use the root path, which just returns a stub HTML page
// see https://github.com/RobustPerception/azure_metrics_exporter/blob/f5baabe/main.go#L363
startupProbe: {
httpGet: {
path: "/",
// eslint-disable-next-line @typescript-eslint/no-explicit-any
port: "metrics" as any
},
failureThreshold: 3,
initialDelaySeconds: 10,
periodSeconds: 30,
successThreshold: 1,
timeoutSeconds: 5
}
}
],
volumes: [
{
name: "config",
configMap: { name: k8sName }
}
]
};
} else if (integration.kind == "exporter-blackbox") {
const integrationData = integration.data as BlackboxIntegrationData;
const exporterConfig = integrationData.config;
// modules: Override the default exporter module configuration yaml file (optional)
if (exporterConfig.configFile) {
configMapData = { "config.yml": exporterConfig.configFile };
}
// If modules is defined, configure configmap volume.
// Line things up so that the config ends up at the default path of /etc/blackbox_exporter/config.yml
podSpec = {
imagePullSecrets: getImagePullSecrets(),
containers: [
{
name: "exporter",
image: DockerImages.exporterBlackbox,
ports: [{ name: "metrics", containerPort: 9115 }],
// Enable configmap mount if modules override is provided
volumeMounts: exporterConfig.configFile
? [{ name: "config", mountPath: "/etc/blackbox_exporter" }]
: [],
// Use the 'healthy' endpoint
// See https://github.com/prometheus/blackbox_exporter/blob/70bce1a/main.go#L312
startupProbe: {
httpGet: {
path: "/-/healthy",
// eslint-disable-next-line @typescript-eslint/no-explicit-any
port: "metrics" as any
},
failureThreshold: 3,
initialDelaySeconds: 10,
periodSeconds: 30,
successThreshold: 1,
timeoutSeconds: 5
}
}
],
// Enable configmap mount if modules override is provided
volumes: exporterConfig.configFile
? [{ name: "config", configMap: { name: k8sName } }]
: []
};
// probes: List of probes to run against exporter modules (required)
// We need to configure Prometheus to hit each of the specified probes.
// Add the probes to the ServiceMonitor object as HTTP /probe queries
if (!exporterConfig.probes) {
log.warning(
"Skipping deployment of blackbox integration %s/'%s': missing required 'probes' in config",
integration.tenant_id,
integration.name
);
return [];
}
for (const probeIdx in exporterConfig.probes) {
// Convert the object values to be arrays to match ServiceMonitor schema:
// {module: "http_2xx", target: "example.com"} => {module: ["http_2xx"], target: ["example.com"]}
const params = Object.fromEntries(
Object.entries(exporterConfig.probes[probeIdx]).map(([k, v]) => [
k,
[v]
])
);
// Ensure that the per-probe metrics are each labeled with the probe info.
// In practice this means that 'module' and 'target' labels should be included in the probe metrics.
const relabelings = Object.entries(exporterConfig.probes[probeIdx]).map(
([k, v]) => ({
sourceLabels: [],
targetLabel: k,
replacement: v
})
);
// Ensure the default integration_id label is also being assigned.
relabelings.push({
sourceLabels: [],
targetLabel: "integration_id",
replacement: integration.id
});
customMonitorEndpoints.push({
interval: "30s",
port: "metrics",
path: "/probe",
// HTTP GET params must be provided as separate object field, not as part of path:
params,
relabelings
});
}
} else {
// Ignore unsupported integration, may not even be relevant to the controller.
log.debug(
"Ignoring integration %s/%s with kind: %s",
integration.tenant_id,
integration.id,
integration.kind
);
return [];
}
resources.push(
new Deployment(
{
apiVersion: "apps/v1",
kind: "Deployment",
metadata: k8sMetadata,
spec: {
replicas: 1,
selector: {
matchLabels: { app: k8sName }
},
template: {
metadata: { labels: k8sLabels },
spec: podSpec
}
}
},
kubeConfig
)
);
// Service is (only) required by the ServiceMonitor
resources.push(
new Service(
{
apiVersion: "v1",
kind: "Service",
metadata: k8sMetadata,
spec: {
ports: [
{
name: "metrics",
port: 9000,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
targetPort: "metrics" as any
}
],
selector: { app: k8sName }
}
},
kubeConfig
)
);
resources.push(
new V1ServicemonitorResource(
{
apiVersion: "monitoring.coreos.com/v1",
kind: "ServiceMonitor",
metadata: k8sMetadata,
spec: {
// Use the name-derived integration key (value of this label) for the "job" annotation in metrics
// Intent is to uniquely identify integrations in a user-friendly way, while avoiding weird issues around symbols/etc in the name.
jobLabel: "opstrace.com/integration-key",
endpoints:
customMonitorEndpoints.length != 0
? customMonitorEndpoints
: [
{
// Increase the timeout (default 10s).
// AWS/Cloudwatch exporter in particular was found to take ~16s
scrapeTimeout: "45s",
// Go with 60s so that it's at least larger than the above timeout
interval: "60s",
port: "metrics",
path: "/metrics",
// Inject an "integration_id" annotation in metrics
relabelings: [
{
sourceLabels: [],
targetLabel: "integration_id",
replacement: integration.id
}
]
}
],
selector: {
matchLabels: { app: k8sName }
}
}
},
kubeConfig
)
);
if (configMapData) {
resources.push(
new ConfigMap(
{
apiVersion: "v1",
kind: "ConfigMap",
metadata: k8sMetadata,
data: configMapData
},
kubeConfig
)
);
}
if (secretData) {
// K8s wants Secret values to be base64-encoded
const datab64 = Object.fromEntries(
Object.entries(secretData).map(([k, v]) => [
k,
Buffer.from(v).toString("base64")
])
);
resources.push(
new Secret(
{
apiVersion: "v1",
kind: "Secret",
metadata: k8sMetadata,
data: datab64
},
kubeConfig
)
);
}
return resources;
}; | the_stack |
import * as React from 'react';
import { Dimmer, Loader } from 'semantic-ui-react';
import { bind } from '../../utils';
import moment from 'moment';
interface IAmpPlayerProps {
sourceUrl: string;
startTime: string;
duration: number;
skin?: string;
onVideoStarted: () => void;
onVideoEnded: () => void;
onVideoError: (error: string) => void;
}
interface IAmpPlayerState {
ampPlayer: any;
}
const ampPlayerStyle = 'https://amp.azure.net/libs/amp/2.3.4/skins/###SKIN/azuremediaplayer.min.css';
const ampPlayerUrl = 'https://amp.azure.net/libs/amp/2.3.4/azuremediaplayer.min.js';
export class AmpPlayer extends React.Component<IAmpPlayerProps, IAmpPlayerState> {
public static defaultProps = {
skin: 'amp-default'
};
private videoElement: any = React.createRef();
constructor(props: any, context?: any) {
super(props, context);
this.state = {
ampPlayer: null
};
}
public setPlayerSize(clientRect: any) {
const {
ampPlayer
} = this.state;
if (ampPlayer) {
ampPlayer.c.width = clientRect.width;
ampPlayer.c.height = clientRect.height;
}
}
public async componentDidMount() {
const {
sourceUrl,
startTime,
skin
} = this.props;
await this.loadScript(ampPlayerUrl, skin);
const ampOptions = {
techOrder: ['azureHtml5JS', 'html5FairPlayHLS', 'html5'],
wallClockDisplaySettings: {
enabled: true,
useLocalTimeZone: true
},
nativeControlsForTouch: false,
autoplay: false,
controls: true,
fluid: true
// width: '640',
// height: '400',
};
this.createAmpPlayer(ampOptions);
}
public componentWillUnmount() {
const {
ampPlayer
} = this.state;
if (ampPlayer) {
ampPlayer.dispose();
}
this.setState({
ampPlayer: null
});
}
public render() {
const {
ampPlayer
} = this.state;
return (
<div className="amp-player-container">
<Dimmer active={!ampPlayer} inverted>
<Loader size="large">
<p>Connecting to video stream...</p>
</Loader>
</Dimmer>
<video
id="amp-player"
ref={this.videoElement}
className="azuremediaplayer amp-default-skin"
style={{ width: '100%' }}
/>
</div>
);
}
@bind
private async loadScript(url: string, skin: string): Promise<void> {
return new Promise((resolve) => {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = ampPlayerStyle.replace('###SKIN', skin);
document.head.insertBefore(link, document.head.firstChild);
const script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.async = false;
script.onload = () => {
return resolve();
};
document.body.appendChild(script);
});
}
private createAmpPlayer(options: any) {
const {
sourceUrl,
startTime,
duration,
onVideoError
} = this.props;
try {
const player = window['amp'](
this.videoElement.current, options, () => {
player.addEventListener('playing', this.videoStarted);
player.addEventListener('ended', this.videoEnded);
player.addEventListener('error', this.videoError);
player.src([
{
src: `${sourceUrl}(starttime=${startTime},endtime=${moment(startTime).add(duration, 'seconds').toISOString()})`,
type: 'application/vnd.ms-sstr+xml',
// type: 'video/mp4',
disableUrlRewriter: false
}
]);
// player.play();
this.setState({
ampPlayer: player
});
});
}
catch (ex) {
onVideoError(`An error occurred trying to create the Azure Media Player control: ${ex.message}`);
}
}
@bind
private videoStarted() {
const {
onVideoStarted
} = this.props;
onVideoStarted();
}
@bind
private videoEnded() {
const {
onVideoEnded
} = this.props;
onVideoEnded();
}
@bind
private videoError() {
const {
onVideoError
} = this.props;
const {
ampPlayer
} = this.state;
const error = ampPlayer.error();
const errorMessage = this.getAmpErrorMessageFromErrorCode(error.code);
onVideoError(errorMessage);
ampPlayer.dispose();
this.setState({
ampPlayer: null
});
}
private getAmpErrorMessageFromErrorCode(errorCode: number): string {
let errorMessage;
// tslint:disable-next-line: no-bitwise
switch (errorCode & 0x00FFFFFF) {
// MEDIA_ERR_ABORTED
case 1048576: // 0x0100000, abortedErrUnknown
case 1048577: // 0x0100001, abortedErrNotImplemented
errorMessage = 'The video content was aborted.';
break;
case 1048578: // 0x0100002, abortedErrHttpMixedContentBlocked
errorMessage = 'The video content was aborted.\nIt may be due to mixed content (http:// vs. https://).';
break;
// MEDIA_ERR_NETWORK
case 2097152: // 0x0200000, networkErrUnknown
errorMessage = 'A network error occurred while trying to play the video content.';
break;
case 2097552: // 0x0200190, networkErrHttpBadUrlFormat
errorMessage = 'An error occurred while playing the video content.';
break;
case 2097553: // 0x0200191, networkErrHttpUserAuthRequired
case 2097555: // 0x0200193, networkErrHttpUserForbidden
case 2097557: // 0x0200195, networkErrHttpNotAllowed
errorMessage = 'An error occurred while playing the video content.\nAuthorization may be required.';
break;
case 2097556: // 0x0200194, networkErrHttpUrlNotFound
case 2097562: // 0x020019A, networkErrHttpGone
errorMessage = 'An error occurred while playing the video content.\nThe resource could not be found.';
break;
case 2097564: // 0x020019C, networkErrHttpPreconditionFailed
errorMessage = 'An error occurred while playing the video content.';
break;
case 2097652: // 0x02001F4, networkErrHttpInternalServerFailure
errorMessage = 'An error occurred while playing the video content.\nThere was an internal server error.';
break;
case 2097654: // 0x02001F6, networkErrHttpBadGateway
case 2097655: // 0x02001F7, networkErrHttpServiceUnavailable
case 2097656: // 0x02001F8, networkErrHttpGatewayTimeout
case 2097752: // 0x0200258, networkErrTimeout
case 2097753: // 0x0200259, networkErrErr
errorMessage = 'An error occurred while playing the video content.\nThe resource could not be reached on the service.';
break;
// MEDIA_ERR_DECODE
case 3145728: // 0x0300000, decodeErrUnknown
errorMessage = 'An error occurred while playing the video content.\nThe content format caused an error.';
break;
// MEDIA_ERR_SRC_NOT_SUPPORTED
case 4194304: // 0x0400000, srcErrUnknown
errorMessage = 'An error occurred while playing the video content.\nThe content format is not supported.';
break;
case 4194305: // 0x0400001, srcErrParsePresentation
case 4194306: // 0x0400003, srcErrUnsupportedPresentation
case 4194307: // 0x0400004, srcErrInvalidSegment
errorMessage = 'An error occurred while playing the video content.';
break;
// MEDIA_ERR_ENCRYPTED
case 5242880: // 0x0500000, encryptErrUnknown
case 5242881: // 0x0500001, encryptErrDecrypterNotFound
case 5242882: // 0x0500002, encryptErrDecrypterInit
case 5242883: // 0x0500003, encryptErrDecrypterNotSupported
case 5242884: // 0x0500004, encryptErrKeyAcquire
case 5242885: // 0x0500005, encryptErrDecryption
case 5242886: // 0x0500006, encryptErrLicenseAcquire
errorMessage = 'An error occurred while playing the video content.\nThe content encryption or license key caused an error.';
break;
// SRC_PLAYER_MISMATCH
case 6291456: // 0x0600000, srcPlayerMismatchUnknown
errorMessage = 'An error occurred while playing the video content.\nThe specified tech parameter cannot play the source content.';
break;
case 6291457: // 0x0600001, srcPlayerMismatchFlashNotInstalled
errorMessage = 'An error occurred while playing the video content.\nThe Flash plugin is required to play this content.';
break;
case 6291458: // 0x0600002, srcPlayerMismatchSilverlightNotInstalled
errorMessage = 'An error occurred while playing the video content.\nThe Silverlight plugin is required to play this content.';
break;
case 6291459: // 0x0600003
errorMessage = 'An error occurred while playing the video content.\nBoth the Flash plugin and Silverlight plugin are specified but are not installed.';
break;
// Unknown errors
case 267386880: // 0x0FF00000, errUnknown
default:
errorMessage = 'An unknown error occurred.';
break;
}
return errorMessage;
}
} | the_stack |
import { Cache } from "@siteimprove/alfa-cache";
import { Cascade } from "@siteimprove/alfa-cascade";
import { Lexer, Keyword, Component, Token } from "@siteimprove/alfa-css";
import { Device } from "@siteimprove/alfa-device";
import { Element, Declaration, Document, Shadow } from "@siteimprove/alfa-dom";
import { Iterable } from "@siteimprove/alfa-iterable";
import { Serializable } from "@siteimprove/alfa-json";
import { Option, None } from "@siteimprove/alfa-option";
import { Parser } from "@siteimprove/alfa-parser";
import { Result } from "@siteimprove/alfa-result";
import { Context } from "@siteimprove/alfa-selector";
import { Set } from "@siteimprove/alfa-set";
import { Slice } from "@siteimprove/alfa-slice";
import * as json from "@siteimprove/alfa-json";
import { Property } from "./property";
import { Value } from "./value";
// Properties are registered by means of a side effect that is executed when the
// properties are imported. To ensure that all properties are registered when
// this module is imported, we import the index module which in turn imports the
// individual properties.
import ".";
const { delimited, left, map, option, pair, right, takeUntil } = Parser;
type Name = Property.Name;
/**
* @public
*/
export class Style implements Serializable<Style.JSON> {
public static of(
declarations: Iterable<Declaration>,
device: Device,
parent: Option<Style> = None
): Style {
// First pass: Resolve cascading variables which will be used in the second
// pass.
const variables = new Map<string, Value<Slice<Token>>>();
for (const declaration of declarations) {
const { name, value } = declaration;
if (name.startsWith("--")) {
const previous = variables.get(name);
if (
previous === undefined ||
shouldOverride(previous.source, declaration)
) {
variables.set(
name,
Value.of(Lexer.lex(value), Option.of(declaration))
);
}
}
}
// Pre-substitute the resolved cascading variables from above, replacing
// any `var()` function references with their substituted tokens.
for (const [name, variable] of variables) {
const substitution = substitute(variable.value, variables, parent);
// If the replaced value is invalid, remove the variable entirely.
if (substitution.isNone()) {
variables.delete(name);
}
// Otherwise, use the replaced value as the new value of the variable.
else {
const [tokens] = substitution.get();
variables.set(name, Value.of(tokens, variable.source));
}
}
// Second pass: Resolve cascading properties using the cascading variables
// from the first pass.
const properties = new Map<Name, Value>();
for (const declaration of declarations) {
const { name, value } = declaration;
if (Property.isName(name)) {
const previous = properties.get(name);
if (
previous === undefined ||
shouldOverride(previous.source, declaration)
) {
for (const result of parseLonghand(
Property.get(name),
value,
variables,
parent
)) {
properties.set(name, Value.of(result, Option.of(declaration)));
}
}
} else if (Property.Shorthand.isName(name)) {
for (const result of parseShorthand(
Property.Shorthand.get(name),
value,
variables,
parent
)) {
for (const [name, value] of result) {
const previous = properties.get(name);
if (
previous === undefined ||
shouldOverride(previous.source, declaration)
) {
properties.set(name, Value.of(value, Option.of(declaration)));
}
}
}
}
}
return new Style(device, parent, variables, properties);
}
private static _empty = new Style(
Device.standard(),
None,
new Map(),
new Map()
);
public static empty(): Style {
return this._empty;
}
private readonly _device: Device;
private readonly _parent: Option<Style>;
private readonly _variables: ReadonlyMap<string, Value<Slice<Token>>>;
private readonly _properties: ReadonlyMap<Name, Value>;
// We cache computed properties but not specified properties as these are
// inexpensive to resolve from cascaded and computed properties.
private readonly _computed = new Map<Name, Value>();
private constructor(
device: Device,
parent: Option<Style>,
variables: ReadonlyMap<string, Value<Slice<Token>>>,
properties: ReadonlyMap<Name, Value>
) {
this._device = device;
this._parent = parent;
this._variables = variables;
this._properties = properties;
}
public get device(): Device {
return this._device;
}
public get parent(): Style {
return this._parent.getOrElse(() => Style._empty);
}
public get variables(): ReadonlyMap<string, Value<Slice<Token>>> {
return this._variables;
}
public get properties(): ReadonlyMap<string, Value> {
return this._properties;
}
public root(): Style {
return this._parent.map((parent) => parent.root()).getOr(this);
}
public cascaded<N extends Name>(name: N): Option<Value<Style.Cascaded<N>>> {
return Option.from(this._properties.get(name)) as Option<
Value<Style.Cascaded<N>>
>;
}
public specified<N extends Name>(name: N): Value<Style.Specified<N>> {
const {
options: { inherits },
} = Property.get(name);
return this.cascaded(name)
.map((cascaded) => {
const { value, source } = cascaded;
if (Keyword.isKeyword(value)) {
switch (value.value) {
// https://drafts.csswg.org/css-cascade/#initial
case "initial":
return this.initial(name, source);
// https://drafts.csswg.org/css-cascade/#inherit
case "inherit":
return this.inherited(name);
// https://drafts.csswg.org/css-cascade/#inherit-initial
case "unset":
return inherits
? this.inherited(name)
: this.initial(name, source);
}
}
return cascaded as Value<Style.Specified<N>>;
})
.getOrElse(() => {
if (inherits === false) {
return this.initial(name);
}
return this._parent
.map((parent) => parent.computed(name))
.getOrElse(() => this.initial(name));
});
}
public computed<N extends Name>(name: N): Value<Style.Computed<N>> {
if (this === Style._empty) {
return this.initial(name);
}
let value = this._computed.get(name);
if (value === undefined) {
value = Property.get(name).compute(
this.specified(name) as Value<Style.Specified<Name>>,
this
);
this._computed.set(name, value);
}
return value as Value<Style.Computed<N>>;
}
public initial<N extends Name>(
name: N,
source: Option<Declaration> = None
): Value<Style.Initial<N>> {
return Value.of(Property.get(name).initial as Style.Computed<N>, source);
}
public inherited<N extends Name>(name: N): Value<Style.Inherited<N>> {
return this.parent.computed(name);
}
public toJSON(): Style.JSON {
return {
device: this._device.toJSON(),
variables: [...this._variables].map(([name, value]) => [
name,
value.toJSON(),
]),
properties: [...this._properties].map(([name, value]) => [
name,
value.toJSON(),
]),
};
}
}
/**
* @public
*/
export namespace Style {
export interface JSON {
[key: string]: json.JSON;
device: Device.JSON;
variables: Array<[string, Value.JSON]>;
properties: Array<[string, Value.JSON]>;
}
const cache = Cache.empty<Device, Cache<Element, Cache<Context, Style>>>();
export function from(
element: Element,
device: Device,
context: Context = Context.empty()
): Style {
return cache
.get(device, Cache.empty)
.get(element.freeze(), Cache.empty)
.get(context, () => {
const declarations: Array<Declaration> = element.style
.map((block) => [...block.declarations].reverse())
.getOr([]);
const root = element.root();
if (Document.isDocument(root) || Shadow.isShadow(root)) {
const cascade = Cascade.of(root, device);
let next = cascade.get(element, context);
while (next.isSome()) {
const node = next.get();
declarations.push(...[...node.declarations].reverse());
next = node.parent;
}
}
return Style.of(
declarations,
device,
element
.parent({ flattened: true })
.filter(Element.isElement)
.map((parent) => from(parent, device, context))
);
});
}
export type Declared<N extends Name> = Property.Value.Declared<N>;
export type Cascaded<N extends Name> = Property.Value.Cascaded<N>;
export type Specified<N extends Name> = Property.Value.Specified<N>;
export type Computed<N extends Name> = Property.Value.Computed<N>;
export type Initial<N extends Name> = Property.Value.Initial<N>;
export type Inherited<N extends Name> = Property.Value.Inherited<N>;
}
function shouldOverride(
previous: Option<Declaration>,
next: Declaration
): boolean {
return (
next.important && previous.every((declaration) => !declaration.important)
);
}
function parseLonghand<N extends Property.Name>(
property: Property.WithName<N>,
value: string,
variables: ReadonlyMap<string, Value<Slice<Token>>>,
parent: Option<Style>
) {
const substitution = substitute(Lexer.lex(value), variables, parent);
if (substitution.isNone()) {
return Result.of(Keyword.of("unset"));
}
const [tokens, substituted] = substitution.get();
const parse = property.parse as Property.Parser;
const result = parse(trim(tokens)).map(([, value]) => value);
if (result.isErr() && substituted) {
return Result.of(Keyword.of("unset"));
}
return result;
}
function parseShorthand<N extends Property.Shorthand.Name>(
shorthand: Property.Shorthand.WithName<N>,
value: string,
variables: ReadonlyMap<string, Value<Slice<Token>>>,
parent: Option<Style>
) {
const substitution = substitute(Lexer.lex(value), variables, parent);
if (substitution.isNone()) {
return Result.of(
Iterable.map(
shorthand.properties,
(property) => [property, Keyword.of("unset")] as const
)
);
}
const [tokens, substituted] = substitution.get();
const parse = shorthand.parse as Property.Shorthand.Parser;
const result = parse(trim(tokens)).map(([, value]) => {
if (Keyword.isKeyword(value)) {
return Iterable.map(
shorthand.properties,
(property) => [property, value] as const
);
}
return value;
});
if (result.isErr() && substituted) {
return Result.of(
Iterable.map(
shorthand.properties,
(property) => [property, Keyword.of("unset")] as const
)
);
}
return result;
}
const parseInitial = Keyword.parse("initial");
/**
* Resolve a cascading variable with an optional fallback. The value of the
* variable, if defined, will have `var()` functions fully substituted.
*
* @remarks
* This method uses a set of visited names to detect cyclic dependencies
* between cascading variables. The set is local to each `Style` instance as
* cyclic references can only occur between cascading variables defined on the
* same element.
*/
function resolve(
name: string,
variables: ReadonlyMap<string, Value<Slice<Token>>>,
parent: Option<Style>,
fallback: Option<Slice<Token>> = None,
visited = Set.empty<string>()
): Option<Slice<Token>> {
return (
Option.from(variables.get(name))
.map((value) =>
// The initial value of a custom property is the "guaranteed-invalid"
// value. We therefore reject the value of the variable if it's the
// keyword `initial`.
// https://drafts.csswg.org/css-variables/#guaranteed-invalid
Option.of(value.value).reject((tokens) => parseInitial(tokens).isOk())
)
// If the value of the variable is invalid, as indicated by it being
// `None`, we instead use the fallback value, if available.
// https://drafts.csswg.org/css-variables/#invalid-variables
.orElse(() =>
fallback
// Substitute any additional cascading variables within the fallback
// value.
.map((tokens) =>
substitute(tokens, variables, parent, visited.add(name)).map(
([tokens]) => tokens
)
)
)
.getOrElse(() =>
parent.flatMap((parent) => {
const variables = parent.variables;
const grandparent =
parent.parent === Style.empty() ? None : Option.of(parent.parent);
return resolve(name, variables, grandparent).flatMap((tokens) =>
substitute(tokens, variables, grandparent).map(([tokens]) => tokens)
);
})
)
);
}
/**
* The maximum allowed number of tokens that declaration values with `var()`
* functions may expand to.
*
* {@link https://drafts.csswg.org/css-variables/#long-variables}
*/
const substitutionLimit = 1024;
/**
* Substitute `var()` functions in an array of tokens. If any syntactically
* invalid `var()` functions are encountered, `None` is returned.
*
* {@link https://drafts.csswg.org/css-variables/#substitute-a-var}
*
* @remarks
* This method uses a set of visited names to detect cyclic dependencies
* between cascading variables. The set is local to each `Style` instance as
* cyclic references can only occur between cascading variables defined on the
* same element.
*/
function substitute(
tokens: Slice<Token>,
variables: ReadonlyMap<string, Value<Slice<Token>>>,
parent: Option<Style>,
visited = Set.empty<string>()
): Option<[tokens: Slice<Token>, substituted: boolean]> {
const replaced: Array<Token> = [];
let substituted = false;
while (tokens.length > 0) {
const next = tokens.array[tokens.offset];
if (next.type === "function" && next.value === "var") {
const result = parseVar(tokens);
if (result.isErr()) {
return None;
}
let name: string;
let fallback: Option<Slice<Token>>;
[tokens, [name, fallback]] = result.get();
if (visited.has(name)) {
return None;
}
const value = resolve(name, variables, parent, fallback, visited);
if (value.isNone()) {
return None;
}
replaced.push(...value.get());
substituted = true;
} else {
replaced.push(next);
tokens = tokens.slice(1);
}
}
// If substitution occurred and the number of replaced tokens has exceeded
// the substitution limit, bail out.
if (substituted && replaced.length > substitutionLimit) {
return None;
}
return Option.of([Slice.of(replaced), substituted]);
}
function trim(tokens: Slice<Token>): Slice<Token> {
return tokens.trim(Token.isWhitespace);
}
/**
* {@link https://drafts.csswg.org/css-variables/#funcdef-var}
*/
const parseVar = right(
Token.parseFunction("var"),
pair(
map(
delimited(
option(Token.parseWhitespace),
Token.parseIdent((ident) => ident.value.startsWith("--"))
),
(ident) => ident.value
),
left(
option(
right(
pair(Token.parseComma, option(Token.parseWhitespace)),
map(
takeUntil(Component.consume, Token.parseCloseParenthesis),
(components) => Slice.of([...Iterable.flatten(components)])
)
)
),
Token.parseCloseParenthesis
)
)
); | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.