text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { EventTarget } from "./event-target" // Used as only type, so no circular.
import { Global } from "./global"
import { assertType } from "./misc"
import {
CanceledInPassiveListener,
FalsyWasAssignedToCancelBubble,
InitEventWasCalledWhileDispatching,
NonCancelableEventWasCanceled,
TruthyWasAssignedToReturnValue,
} from "./warnings"
/*eslint-disable class-methods-use-this */
/**
* An implementation of `Event` interface, that wraps a given event object.
* `EventTarget` shim can control the internal state of this `Event` objects.
* @see https://dom.spec.whatwg.org/#event
*/
export class Event<TEventType extends string = string> {
/**
* @see https://dom.spec.whatwg.org/#dom-event-none
*/
static get NONE(): number {
return NONE
}
/**
* @see https://dom.spec.whatwg.org/#dom-event-capturing_phase
*/
static get CAPTURING_PHASE(): number {
return CAPTURING_PHASE
}
/**
* @see https://dom.spec.whatwg.org/#dom-event-at_target
*/
static get AT_TARGET(): number {
return AT_TARGET
}
/**
* @see https://dom.spec.whatwg.org/#dom-event-bubbling_phase
*/
static get BUBBLING_PHASE(): number {
return BUBBLING_PHASE
}
/**
* Initialize this event instance.
* @param type The type of this event.
* @param eventInitDict Options to initialize.
* @see https://dom.spec.whatwg.org/#dom-event-event
*/
constructor(type: TEventType, eventInitDict?: Event.EventInit) {
Object.defineProperty(this, "isTrusted", {
value: false,
enumerable: true,
})
const opts = eventInitDict ?? {}
internalDataMap.set(this, {
type: String(type),
bubbles: Boolean(opts.bubbles),
cancelable: Boolean(opts.cancelable),
composed: Boolean(opts.composed),
target: null,
currentTarget: null,
stopPropagationFlag: false,
stopImmediatePropagationFlag: false,
canceledFlag: false,
inPassiveListenerFlag: false,
dispatchFlag: false,
timeStamp: Date.now(),
})
}
/**
* The type of this event.
* @see https://dom.spec.whatwg.org/#dom-event-type
*/
get type(): TEventType {
return $(this).type as TEventType
}
/**
* The event target of the current dispatching.
* @see https://dom.spec.whatwg.org/#dom-event-target
*/
get target(): EventTarget | null {
return $(this).target
}
/**
* The event target of the current dispatching.
* @deprecated Use the `target` property instead.
* @see https://dom.spec.whatwg.org/#dom-event-srcelement
*/
get srcElement(): EventTarget | null {
return $(this).target
}
/**
* The event target of the current dispatching.
* @see https://dom.spec.whatwg.org/#dom-event-currenttarget
*/
get currentTarget(): EventTarget | null {
return $(this).currentTarget
}
/**
* The event target of the current dispatching.
* This doesn't support node tree.
* @see https://dom.spec.whatwg.org/#dom-event-composedpath
*/
composedPath(): EventTarget[] {
const currentTarget = $(this).currentTarget
if (currentTarget) {
return [currentTarget]
}
return []
}
/**
* @see https://dom.spec.whatwg.org/#dom-event-none
*/
get NONE(): number {
return NONE
}
/**
* @see https://dom.spec.whatwg.org/#dom-event-capturing_phase
*/
get CAPTURING_PHASE(): number {
return CAPTURING_PHASE
}
/**
* @see https://dom.spec.whatwg.org/#dom-event-at_target
*/
get AT_TARGET(): number {
return AT_TARGET
}
/**
* @see https://dom.spec.whatwg.org/#dom-event-bubbling_phase
*/
get BUBBLING_PHASE(): number {
return BUBBLING_PHASE
}
/**
* The current event phase.
* @see https://dom.spec.whatwg.org/#dom-event-eventphase
*/
get eventPhase(): number {
return $(this).dispatchFlag ? 2 : 0
}
/**
* Stop event bubbling.
* Because this shim doesn't support node tree, this merely changes the `cancelBubble` property value.
* @see https://dom.spec.whatwg.org/#dom-event-stoppropagation
*/
stopPropagation(): void {
$(this).stopPropagationFlag = true
}
/**
* `true` if event bubbling was stopped.
* @deprecated
* @see https://dom.spec.whatwg.org/#dom-event-cancelbubble
*/
get cancelBubble(): boolean {
return $(this).stopPropagationFlag
}
/**
* Stop event bubbling if `true` is set.
* @deprecated Use the `stopPropagation()` method instead.
* @see https://dom.spec.whatwg.org/#dom-event-cancelbubble
*/
set cancelBubble(value: boolean) {
if (value) {
$(this).stopPropagationFlag = true
} else {
FalsyWasAssignedToCancelBubble.warn()
}
}
/**
* Stop event bubbling and subsequent event listener callings.
* @see https://dom.spec.whatwg.org/#dom-event-stopimmediatepropagation
*/
stopImmediatePropagation(): void {
const data = $(this)
data.stopPropagationFlag = data.stopImmediatePropagationFlag = true
}
/**
* `true` if this event will bubble.
* @see https://dom.spec.whatwg.org/#dom-event-bubbles
*/
get bubbles(): boolean {
return $(this).bubbles
}
/**
* `true` if this event can be canceled by the `preventDefault()` method.
* @see https://dom.spec.whatwg.org/#dom-event-cancelable
*/
get cancelable(): boolean {
return $(this).cancelable
}
/**
* `true` if the default behavior will act.
* @deprecated Use the `defaultPrevented` proeprty instead.
* @see https://dom.spec.whatwg.org/#dom-event-returnvalue
*/
get returnValue(): boolean {
return !$(this).canceledFlag
}
/**
* Cancel the default behavior if `false` is set.
* @deprecated Use the `preventDefault()` method instead.
* @see https://dom.spec.whatwg.org/#dom-event-returnvalue
*/
set returnValue(value: boolean) {
if (!value) {
setCancelFlag($(this))
} else {
TruthyWasAssignedToReturnValue.warn()
}
}
/**
* Cancel the default behavior.
* @see https://dom.spec.whatwg.org/#dom-event-preventdefault
*/
preventDefault(): void {
setCancelFlag($(this))
}
/**
* `true` if the default behavior was canceled.
* @see https://dom.spec.whatwg.org/#dom-event-defaultprevented
*/
get defaultPrevented(): boolean {
return $(this).canceledFlag
}
/**
* @see https://dom.spec.whatwg.org/#dom-event-composed
*/
get composed(): boolean {
return $(this).composed
}
/**
* @see https://dom.spec.whatwg.org/#dom-event-istrusted
*/
//istanbul ignore next
get isTrusted(): boolean {
return false
}
/**
* @see https://dom.spec.whatwg.org/#dom-event-timestamp
*/
get timeStamp(): number {
return $(this).timeStamp
}
/**
* @deprecated Don't use this method. The constructor did initialization.
*/
initEvent(type: string, bubbles = false, cancelable = false) {
const data = $(this)
if (data.dispatchFlag) {
InitEventWasCalledWhileDispatching.warn()
return
}
internalDataMap.set(this, {
...data,
type: String(type),
bubbles: Boolean(bubbles),
cancelable: Boolean(cancelable),
target: null,
currentTarget: null,
stopPropagationFlag: false,
stopImmediatePropagationFlag: false,
canceledFlag: false,
})
}
}
/*eslint-enable class-methods-use-this */
export namespace Event {
/**
* The options of the `Event` constructor.
* @see https://dom.spec.whatwg.org/#dictdef-eventinit
*/
export interface EventInit {
bubbles?: boolean
cancelable?: boolean
composed?: boolean
}
}
export { $ as getEventInternalData }
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const NONE = 0
const CAPTURING_PHASE = 1
const AT_TARGET = 2
const BUBBLING_PHASE = 3
/**
* Private data.
*/
interface EventInternalData {
/**
* The value of `type` attribute.
*/
readonly type: string
/**
* The value of `bubbles` attribute.
*/
readonly bubbles: boolean
/**
* The value of `cancelable` attribute.
*/
readonly cancelable: boolean
/**
* The value of `composed` attribute.
*/
readonly composed: boolean
/**
* The value of `timeStamp` attribute.
*/
readonly timeStamp: number
/**
* @see https://dom.spec.whatwg.org/#dom-event-target
*/
target: EventTarget | null
/**
* @see https://dom.spec.whatwg.org/#dom-event-currenttarget
*/
currentTarget: EventTarget | null
/**
* @see https://dom.spec.whatwg.org/#stop-propagation-flag
*/
stopPropagationFlag: boolean
/**
* @see https://dom.spec.whatwg.org/#stop-immediate-propagation-flag
*/
stopImmediatePropagationFlag: boolean
/**
* @see https://dom.spec.whatwg.org/#canceled-flag
*/
canceledFlag: boolean
/**
* @see https://dom.spec.whatwg.org/#in-passive-listener-flag
*/
inPassiveListenerFlag: boolean
/**
* @see https://dom.spec.whatwg.org/#dispatch-flag
*/
dispatchFlag: boolean
}
/**
* Private data for event wrappers.
*/
const internalDataMap = new WeakMap<any, EventInternalData>()
/**
* Get private data.
* @param event The event object to get private data.
* @param name The variable name to report.
* @returns The private data of the event.
*/
function $(event: unknown, name = "this"): EventInternalData {
const retv = internalDataMap.get(event)
assertType(
retv != null,
"'%s' must be an object that Event constructor created, but got another one: %o",
name,
event,
)
return retv
}
/**
* https://dom.spec.whatwg.org/#set-the-canceled-flag
* @param data private data.
*/
function setCancelFlag(data: EventInternalData) {
if (data.inPassiveListenerFlag) {
CanceledInPassiveListener.warn()
return
}
if (!data.cancelable) {
NonCancelableEventWasCanceled.warn()
return
}
data.canceledFlag = true
}
// Set enumerable
Object.defineProperty(Event, "NONE", { enumerable: true })
Object.defineProperty(Event, "CAPTURING_PHASE", { enumerable: true })
Object.defineProperty(Event, "AT_TARGET", { enumerable: true })
Object.defineProperty(Event, "BUBBLING_PHASE", { enumerable: true })
const keys = Object.getOwnPropertyNames(Event.prototype)
for (let i = 0; i < keys.length; ++i) {
if (keys[i] === "constructor") {
continue
}
Object.defineProperty(Event.prototype, keys[i], { enumerable: true })
}
// Ensure `event instanceof window.Event` is `true`.
if (typeof Global !== "undefined" && typeof Global.Event !== "undefined") {
Object.setPrototypeOf(Event.prototype, Global.Event.prototype)
} | the_stack |
import path from 'path';
import assert from 'assert';
import sinon from 'sinon';
import rewire from 'rewire';
import mock from 'mock-fs';
const cabinetNonDefault = rewire('./');
const cabinet = cabinetNonDefault.default;
const fixtures = `${__dirname}/../../../../../../fixtures/filing-cabinet`;
// eslint-disable-next-line import/no-dynamic-require, global-require
const mockedFiles = require(`${fixtures}/mockedJSFiles`);
// eslint-disable-next-line import/no-dynamic-require, global-require
const mockAST = require(`${fixtures}/ast`);
const mockRootDir = path.join(__dirname, '..', '..', '..', '..', '..', '..');
// needed for the lazy loading
require('resolve-dependency-path');
require('sass-lookup');
require('app-module-path');
require('module-definition');
try {
// eslint-disable-next-line global-require
require('module-lookup-amd');
} catch (err) {
// eslint-disable-next-line no-console
console.log(`mocha suppresses the error, so console.error is needed to show the error on the screen.
the problem is with module-lookup-amd that calls requirejs package and uses rewire package.
see https://github.com/jhnns/rewire/issues/178 for more details.
the error occurs since node v12.16.0. for the time being, to run the tests, use an earlier version.
`);
// eslint-disable-next-line no-console
console.error(err);
throw err;
}
describe('filing-cabinet', () => {
describe('JavaScript', () => {
beforeEach(() => {
mock(mockedFiles);
});
afterEach(() => {
mock.restore();
});
it('dangles off its supported file extensions', () => {
assert.deepEqual(cabinetNonDefault.supportedFileExtensions, [
'.js',
'.jsx',
'.ts',
'.tsx',
'.scss',
'.sass',
'.styl',
'.less',
'.vue'
]);
});
it('uses a generic resolve for unsupported file extensions', () => {
const resolvedFile = cabinet({
dependency: './bar',
filename: 'js/commonjs/foo.baz',
directory: 'js/commonjs/'
});
assert.ok(resolvedFile.endsWith('bar.baz'));
});
describe('when given an ast for a JS file', () => {
it('reuses the ast when trying to determine the module type', () => {
const ast = {};
const result = cabinet({
dependency: './bar',
filename: 'js/es6/foo.js',
directory: 'js/es6/',
ast
});
assert.ok(result.endsWith('es6/bar.js'));
});
it('resolves the dependency successfully', () => {
const result = cabinet({
dependency: './bar',
filename: 'js/es6/foo.js',
directory: 'js/es6/',
ast: mockAST
});
assert.equal(result, path.join(mockRootDir, 'js/es6/bar.js'));
});
});
describe('when not given an ast', () => {
it('uses the filename to look for the module type', () => {
const options = {
dependency: './bar',
filename: 'js/es6/foo.js',
directory: 'js/es6/'
};
const result = cabinet(options);
assert.equal(result, path.join(mockRootDir, 'js/es6/bar.js'));
});
});
describe('es6', () => {
it('assumes commonjs for es6 modules with no requirejs/webpack config', () => {
const stub = sinon.stub();
const revert = cabinetNonDefault.__set__('commonJSLookup', stub);
cabinet({
dependency: './bar',
filename: 'js/es6/foo.js',
directory: 'js/es6/'
});
assert.ok(stub.called);
revert();
});
});
describe('jsx', () => {
it('resolves files with the .jsx extension', () => {
const result = cabinet({
dependency: './bar',
filename: 'js/es6/foo.jsx',
directory: 'js/es6/'
});
assert.equal(result, `${path.join(mockRootDir, 'js/es6/bar.js')}`);
});
});
describe('amd', () => {
it('uses the amd resolver', () => {
const resolvedFile = cabinet({
dependency: './bar',
filename: 'js/amd/foo.js',
directory: 'js/amd/'
});
assert.ok(resolvedFile.endsWith('amd/bar.js'));
});
// skipped as part of lazy loading fix. not seems to be super helpful test
it.skip('passes along arguments', () => {
const stub = sinon.stub();
const revert = cabinet.__set__('amdLookup', stub);
const config = { baseUrl: 'js' };
cabinet({
dependency: 'bar',
config,
configPath: 'config.js',
filename: 'js/amd/foo.js',
directory: 'js/amd/'
});
const args = stub.getCall(0).args[0];
assert.equal(args.dependency, 'bar');
assert.equal(args.config, config);
assert.equal(args.configPath, 'config.js');
assert.equal(args.filename, 'js/amd/foo.js');
assert.equal(args.directory, 'js/amd/');
assert.ok(stub.called);
revert();
});
});
describe('commonjs', () => {
it("uses require's resolver", () => {
const stub = sinon.stub();
const revert = cabinetNonDefault.__set__('commonJSLookup', stub);
cabinet({
dependency: './bar',
filename: 'js/commonjs/foo.js',
directory: 'js/commonjs/'
});
assert.ok(stub.called);
revert();
});
it('returns an empty string for an unresolved module', () => {
const result = cabinet({
dependency: 'foobar',
filename: 'js/commonjs/foo.js',
directory: 'js/commonjs/'
});
assert.equal(result, '');
});
it('adds the directory to the require resolution paths', () => {
const directory = 'js/commonjs/';
cabinet({
dependency: 'foobar',
filename: 'js/commonjs/foo.js',
directory
});
assert.ok(
// @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX!
require.main.paths.some(function(p) {
return p.indexOf(path.normalize(directory)) !== -1;
})
);
});
it('resolves a relative dependency about the filename', () => {
const directory = 'js/commonjs/';
const filename = `${directory}foo.js`;
const result = cabinet({
dependency: './bar',
filename,
directory
});
assert.equal(result, path.join(path.resolve(directory), 'bar.js'));
});
it("resolves a .. dependency to its parent directory's index.js file", () => {
const directory = 'js/commonjs/';
const filename = `${directory}subdir/module.js`;
const result = cabinet({
dependency: '../',
filename,
directory
});
assert.equal(result, path.join(path.resolve(directory), 'index.js'));
});
// @todo: fix
it.skip('resolves a dependency within a directory outside of the given file', () => {
const directory = 'js/commonjs/';
const filename = `${directory}test/index.spec.js`;
const result = cabinet({
dependency: 'subdir',
filename,
directory
});
assert.equal(result, path.join(path.resolve(directory), 'subdir/index.js'));
});
// @todo: fix
it.skip('resolves a node module with module entry in package.json', () => {
const directory = 'js/commonjs/';
const filename = `${directory}module.entry.js`;
const result = cabinet({
dependency: 'module.entry',
filename,
directory,
nodeModulesConfig: {
entry: 'module'
}
});
assert.equal(
result,
path.join(path.resolve(directory), '..', 'node_modules', 'module.entry', 'index.module.js')
);
});
it('resolves a nested module', () => {
const directory = 'js/node_modules/nested/';
const filename = `${directory}index.js`;
const result = cabinet({
dependency: 'lodash.assign',
filename,
directory
});
assert.equal(result, path.join(path.resolve(directory), 'node_modules', 'lodash.assign', 'index.js'));
});
it('resolves to the index.js file of a directory', () => {
const directory = 'js/withIndex';
const filename = `${directory}/index.js`;
const result = cabinet({
dependency: './subdir',
filename,
directory
});
assert.equal(result, path.normalize(`${path.resolve(directory)}/subdir/index.js`));
});
it('resolves implicit .jsx requires', () => {
const result = cabinet({
dependency: './bar',
filename: 'js/cjs/foo.js',
directory: 'js/cjs/'
});
assert.equal(result, `${path.join(mockRootDir, 'js/cjs/bar.jsx')}`);
});
it('resolves implicit .scss requires', () => {
const result = cabinet({
dependency: './baz',
filename: 'js/cjs/foo.js',
directory: 'js/cjs/'
});
assert.equal(result, `${path.join(mockRootDir, 'js/cjs/baz.scss')}`);
});
it('resolves implicit .json requires', () => {
const result = cabinet({
dependency: './pkg',
filename: 'js/cjs/foo.js',
directory: 'js/cjs/'
});
assert.equal(result, `${path.join(mockRootDir, 'js/cjs/pkg.json')}`);
});
});
describe('typescript', () => {
it('resolves an import', () => {
const directory = 'js/ts';
const filename = `${directory}/index.ts`;
const result = cabinet({
dependency: './foo',
filename,
directory
});
assert.equal(result, path.join(path.resolve(directory), 'foo.ts'));
});
describe('when a dependency does not exist', () => {
it('returns an empty result', () => {
const directory = 'js/ts';
const filename = `${directory}/index.ts`;
const result = cabinet({
dependency: './barbar',
filename,
directory
});
assert.equal(result, '');
});
});
});
});
describe('CSS', () => {
beforeEach(() => {
mock({
stylus: {
'foo.styl': '',
'bar.styl': ''
},
sass: {
'foo.scss': '',
'bar.scss': '',
'foo.sass': '',
'bar.sass': ''
},
less: {
'foo.less': '',
'bar.less': '',
'bar.css': ''
}
});
// mockJSDir = path.resolve(__dirname, '../');
});
afterEach(() => {
mock.restore();
});
describe('sass', () => {
it('uses the sass resolver for .scss files', () => {
const result = cabinet({
dependency: 'bar',
filename: 'sass/foo.scss',
directory: 'sass/'
});
assert.equal(result, path.normalize(`${mockRootDir}/sass/bar.scss`));
});
it('uses the sass resolver for .sass files', () => {
const result = cabinet({
dependency: 'bar',
filename: 'sass/foo.sass',
directory: 'sass/'
});
assert.equal(result, path.normalize(`${mockRootDir}/sass/bar.sass`));
});
});
describe('stylus', () => {
it('uses the stylus resolver', () => {
const result = cabinet({
dependency: 'bar',
filename: 'stylus/foo.styl',
directory: 'stylus/'
});
assert.equal(result, path.normalize(`${mockRootDir}/stylus/bar.styl`));
});
});
describe('less', () => {
it('resolves extensionless dependencies', () => {
const result = cabinet({
dependency: 'bar',
filename: 'less/foo.less',
directory: 'less/'
});
assert.equal(result, path.normalize(`${mockRootDir}/less/bar.less`));
});
it('resolves dependencies with a less extension', () => {
const result = cabinet({
dependency: 'bar.less',
filename: 'less/foo.less',
directory: 'less/'
});
assert.equal(result, path.normalize(`${mockRootDir}/less/bar.less`));
});
it('resolves dependencies with a css extension', () => {
const result = cabinet({
dependency: 'bar.css',
filename: 'less/foo.less',
directory: 'less/'
});
assert.equal(result, path.normalize(`${mockRootDir}/less/bar.css`));
});
});
});
describe('unrecognized extension', () => {
it('uses a generic resolve for unsupported file extensions', () => {
const result = cabinet({
dependency: './bar',
filename: 'barbazim/foo.baz',
directory: 'barbazim/'
});
assert.equal(result, path.normalize(`${mockRootDir}/barbazim/bar.baz`));
});
});
describe('.register', () => {
it('registers a custom resolver for a given extension', () => {
const stub = sinon.stub().returns('foo.foobar');
cabinetNonDefault.register('.foobar', stub);
const pathResult = cabinet({
dependency: './bar',
filename: 'js/amd/foo.foobar',
directory: 'js/amd/'
});
assert.ok(stub.called);
assert.equal(pathResult, 'foo.foobar');
});
it('allows does not break default resolvers', () => {
mock({
stylus: {
'foo.styl': '',
'bar.styl': ''
}
});
const stub = sinon.stub().returns('foo');
cabinetNonDefault.register('.foobar', stub);
cabinet({
dependency: './bar',
filename: 'js/amd/foo.foobar',
directory: 'js/amd/'
});
const result = cabinet({
dependency: './bar',
filename: 'stylus/foo.styl',
directory: 'stylus/'
});
assert.ok(stub.called);
assert.ok(result);
mock.restore();
});
it('can be called multiple times', () => {
const stub = sinon.stub().returns('foo');
const stub2 = sinon.stub().returns('foo');
cabinetNonDefault.register('.foobar', stub);
cabinetNonDefault.register('.barbar', stub2);
cabinet({
dependency: './bar',
filename: 'js/amd/foo.foobar',
directory: 'js/amd/'
});
cabinet({
dependency: './bar',
filename: 'js/amd/foo.barbar',
directory: 'js/amd/'
});
assert.ok(stub.called);
assert.ok(stub2.called);
});
it('does not add redundant extensions to supportedFileExtensions', () => {
const stub = sinon.stub;
const newExt = '.foobar';
cabinetNonDefault.register(newExt, stub);
cabinetNonDefault.register(newExt, stub);
const { supportedFileExtensions } = cabinetNonDefault;
assert.equal(supportedFileExtensions.indexOf(newExt), supportedFileExtensions.lastIndexOf(newExt));
});
});
describe('.scss with a dependency prefix with a tilda', () => {
it('should resolve the dependency to a node_module package (using webpack under the hood)', () => {
const result = cabinet({
dependency: '~bootstrap/index',
filename: `${fixtures}/foo.scss`,
directory: fixtures
});
assert.equal(result, path.resolve(`${fixtures}/node_modules/bootstrap/index.scss`));
});
});
describe('.scss with a dependency prefix with a tilda and resolve config', () => {
describe('when the alias in resolve-config is resolved to an existing file', () => {
it('should resolve the dependency according to the resolve-config', () => {
const resolveConfig = { aliases: { '~bootstrap': path.normalize(fixtures) } };
const result = cabinet({
resolveConfig,
dependency: '~bootstrap/foo2',
filename: `${fixtures}/foo.scss`,
directory: fixtures
});
assert.equal(result, path.resolve(`${fixtures}/foo2.scss`));
});
});
describe('when the alias in resolve-config does not match the dependency', () => {
it('should fallback to the node-module resolution', () => {
const resolveConfig = { aliases: { '~non-exist': 'some-dir' } };
const result = cabinet({
resolveConfig,
dependency: '~bootstrap/index',
filename: `${fixtures}/foo.scss`,
directory: fixtures
});
assert.equal(result, path.resolve(`${fixtures}/node_modules/bootstrap/index.scss`));
});
});
});
// @todo: fix.
describe.skip('webpack', () => {
let directory;
beforeEach(() => {
directory = path.resolve(__dirname, '../../../');
});
function testResolution(dependency, expected) {
const resolved = cabinet({
dependency,
filename: `${__dirname}/index.js`,
directory,
webpackConfig: `${fixtures}/webpack.config.js`
});
assert.equal(resolved, path.normalize(expected));
}
it('resolves an aliased path', () => {
testResolution('R', `${directory}/node_modules/resolve/index.js`);
});
it('resolves a non-aliased path', () => {
testResolution('resolve', `${directory}/node_modules/resolve/index.js`);
});
it('resolves a relative path', () => {
testResolution('./test/ast', `${fixtures}/test/ast.js`);
});
it('resolves an absolute path from a file within a subdirectory', () => {
const resolved = cabinet({
dependency: 'R',
filename: `${fixtures}/test/ast.js`,
directory,
webpackConfig: `${fixtures}/webpack.config.js`
});
assert.equal(resolved, `${directory}/node_modules/resolve/index.js`);
});
it('resolves a path using resolve.root', () => {
const resolved = cabinet({
dependency: 'mod1',
filename: `${directory}/index.js`,
directory,
webpackConfig: `${directory}/webpack-root.config.js`
});
assert.equal(resolved, `${directory}/test/root1/mod1.js`);
});
it('resolves NPM module when using resolve.root', () => {
const resolved = cabinet({
dependency: 'resolve',
filename: `${directory}/index.js`,
directory,
webpackConfig: `${directory}/webpack-root.config.js`
});
assert.equal(resolved, `${directory}/node_modules/resolve/index.js`);
});
it('resolves NPM module when using resolve.modulesDirectories', () => {
const resolved = cabinet({
dependency: 'resolve',
filename: `${directory}/index.js`,
directory,
webpackConfig: `${directory}/webpack-root.config.js`
});
assert.equal(resolved, `${directory}/node_modules/resolve/index.js`);
});
it('resolves a path using resolve.modulesDirectories', () => {
const resolved = cabinet({
dependency: 'mod2',
filename: `${directory}/index.js`,
directory,
webpackConfig: `${directory}/webpack-root.config.js`
});
assert.equal(resolved, `${directory}/test/root2/mod2.js`);
});
it('resolves a path using webpack config that exports a function', () => {
const resolved = cabinet({
dependency: 'R',
filename: `${directory}/index.js`,
directory,
webpackConfig: `${directory}/webpack-env.config.js`
});
assert.equal(resolved, `${directory}/node_modules/resolve/index.js`);
});
it('resolves files with a .jsx extension', () => {
testResolution('./test/foo.jsx', `${directory}/test/foo.jsx`);
});
describe('when the dependency contains a loader', () => {
it('still works', () => {
testResolution('hgn!resolve', `${directory}/node_modules/resolve/index.js`);
});
});
});
}); | the_stack |
'use strict';
import invariant from 'invariant';
import * as React from 'react';
import { Platform, UIManager } from 'react-native';
import { BlurEvent, FocusEvent, MouseEvent, PressEvent } from './CoreEventTypes';
import { isHoverEnabled } from './HoverState';
import { HostComponent, normalizeRect, Rect } from './InternalTypes';
import { PressabilityConfig, PressabilityEventHandlers } from './Pressability.types';
type TouchState =
| 'NOT_RESPONDER'
| 'RESPONDER_INACTIVE_PRESS_IN'
| 'RESPONDER_INACTIVE_PRESS_OUT'
| 'RESPONDER_ACTIVE_PRESS_IN'
| 'RESPONDER_ACTIVE_PRESS_OUT'
| 'RESPONDER_ACTIVE_LONG_PRESS_IN'
| 'RESPONDER_ACTIVE_LONG_PRESS_OUT'
| 'ERROR';
type TouchSignal =
| 'DELAY'
| 'RESPONDER_GRANT'
| 'RESPONDER_RELEASE'
| 'RESPONDER_TERMINATED'
| 'ENTER_PRESS_RECT'
| 'LEAVE_PRESS_RECT'
| 'LONG_PRESS_DETECTED';
const Transitions: { [K in TouchState]: { [T in TouchSignal]: TouchState } } = {
NOT_RESPONDER: {
DELAY: 'ERROR',
RESPONDER_GRANT: 'RESPONDER_INACTIVE_PRESS_IN',
RESPONDER_RELEASE: 'ERROR',
RESPONDER_TERMINATED: 'ERROR',
ENTER_PRESS_RECT: 'ERROR',
LEAVE_PRESS_RECT: 'ERROR',
LONG_PRESS_DETECTED: 'ERROR',
},
RESPONDER_INACTIVE_PRESS_IN: {
DELAY: 'RESPONDER_ACTIVE_PRESS_IN',
RESPONDER_GRANT: 'ERROR',
RESPONDER_RELEASE: 'NOT_RESPONDER',
RESPONDER_TERMINATED: 'NOT_RESPONDER',
ENTER_PRESS_RECT: 'RESPONDER_INACTIVE_PRESS_IN',
LEAVE_PRESS_RECT: 'RESPONDER_INACTIVE_PRESS_OUT',
LONG_PRESS_DETECTED: 'ERROR',
},
RESPONDER_INACTIVE_PRESS_OUT: {
DELAY: 'RESPONDER_ACTIVE_PRESS_OUT',
RESPONDER_GRANT: 'ERROR',
RESPONDER_RELEASE: 'NOT_RESPONDER',
RESPONDER_TERMINATED: 'NOT_RESPONDER',
ENTER_PRESS_RECT: 'RESPONDER_INACTIVE_PRESS_IN',
LEAVE_PRESS_RECT: 'RESPONDER_INACTIVE_PRESS_OUT',
LONG_PRESS_DETECTED: 'ERROR',
},
RESPONDER_ACTIVE_PRESS_IN: {
DELAY: 'ERROR',
RESPONDER_GRANT: 'ERROR',
RESPONDER_RELEASE: 'NOT_RESPONDER',
RESPONDER_TERMINATED: 'NOT_RESPONDER',
ENTER_PRESS_RECT: 'RESPONDER_ACTIVE_PRESS_IN',
LEAVE_PRESS_RECT: 'RESPONDER_ACTIVE_PRESS_OUT',
LONG_PRESS_DETECTED: 'RESPONDER_ACTIVE_LONG_PRESS_IN',
},
RESPONDER_ACTIVE_PRESS_OUT: {
DELAY: 'ERROR',
RESPONDER_GRANT: 'ERROR',
RESPONDER_RELEASE: 'NOT_RESPONDER',
RESPONDER_TERMINATED: 'NOT_RESPONDER',
ENTER_PRESS_RECT: 'RESPONDER_ACTIVE_PRESS_IN',
LEAVE_PRESS_RECT: 'RESPONDER_ACTIVE_PRESS_OUT',
LONG_PRESS_DETECTED: 'ERROR',
},
RESPONDER_ACTIVE_LONG_PRESS_IN: {
DELAY: 'ERROR',
RESPONDER_GRANT: 'ERROR',
RESPONDER_RELEASE: 'NOT_RESPONDER',
RESPONDER_TERMINATED: 'NOT_RESPONDER',
ENTER_PRESS_RECT: 'RESPONDER_ACTIVE_LONG_PRESS_IN',
LEAVE_PRESS_RECT: 'RESPONDER_ACTIVE_LONG_PRESS_OUT',
LONG_PRESS_DETECTED: 'RESPONDER_ACTIVE_LONG_PRESS_IN',
},
RESPONDER_ACTIVE_LONG_PRESS_OUT: {
DELAY: 'ERROR',
RESPONDER_GRANT: 'ERROR',
RESPONDER_RELEASE: 'NOT_RESPONDER',
RESPONDER_TERMINATED: 'NOT_RESPONDER',
ENTER_PRESS_RECT: 'RESPONDER_ACTIVE_LONG_PRESS_IN',
LEAVE_PRESS_RECT: 'RESPONDER_ACTIVE_LONG_PRESS_OUT',
LONG_PRESS_DETECTED: 'ERROR',
},
ERROR: {
DELAY: 'NOT_RESPONDER',
RESPONDER_GRANT: 'RESPONDER_INACTIVE_PRESS_IN',
RESPONDER_RELEASE: 'NOT_RESPONDER',
RESPONDER_TERMINATED: 'NOT_RESPONDER',
ENTER_PRESS_RECT: 'NOT_RESPONDER',
LEAVE_PRESS_RECT: 'NOT_RESPONDER',
LONG_PRESS_DETECTED: 'NOT_RESPONDER',
},
};
const isActiveSignal = (signal) => signal === 'RESPONDER_ACTIVE_PRESS_IN' || signal === 'RESPONDER_ACTIVE_LONG_PRESS_IN';
const isActivationSignal = (signal) => signal === 'RESPONDER_ACTIVE_PRESS_OUT' || signal === 'RESPONDER_ACTIVE_PRESS_IN';
const isPressInSignal = (signal) =>
signal === 'RESPONDER_INACTIVE_PRESS_IN' || signal === 'RESPONDER_ACTIVE_PRESS_IN' || signal === 'RESPONDER_ACTIVE_LONG_PRESS_IN';
const isTerminalSignal = (signal) => signal === 'RESPONDER_TERMINATED' || signal === 'RESPONDER_RELEASE';
const DEFAULT_LONG_PRESS_DELAY_MS = 370; // 500 - 130
const DEFAULT_PRESS_DELAY_MS = 130;
const DEFAULT_PRESS_RECT_OFFSETS: Rect = {
bottom: 30,
left: 20,
right: 20,
top: 20,
};
function normalizeDelay(delay?: number, min: number = 0, fallback: number = 0): number {
return Math.max(min, delay ?? fallback);
}
const getTouchFromPressEvent = (event: PressEvent) => {
const { changedTouches, touches } = event.nativeEvent;
if (touches != null && touches.length > 0) {
return touches[0];
}
if (changedTouches != null && changedTouches.length > 0) {
return changedTouches[0];
}
return event.nativeEvent;
};
/**
* Pressability implements press handling capabilities.
*
* =========================== Pressability Tutorial ===========================
*
* The `Pressability` class helps you create press interactions by analyzing the
* geometry of elements and observing when another responder (e.g. ScrollView)
* has stolen the touch lock. It offers hooks for your component to provide
* interaction feedback to the user:
*
* - When a press has activated (e.g. highlight an element)
* - When a press has deactivated (e.g. un-highlight an element)
* - When a press sould trigger an action, meaning it activated and deactivated
* while within the geometry of the element without the lock being stolen.
*
* A high quality interaction isn't as simple as you might think. There should
* be a slight delay before activation. Moving your finger beyond an element's
* bounds should trigger deactivation, but moving the same finger back within an
* element's bounds should trigger reactivation.
*
* In order to use `Pressability`, do the following:
*
* 1. Instantiate `Pressability` and store it on your component's state.
*
* state = {
* pressability: new Pressability({
* // ...
* }),
* };
*
* 2. Choose the rendered component who should collect the press events. On that
* element, spread `pressability.getEventHandlers()` into its props.
*
* return (
* <View {...this.state.pressability.getEventHandlers()} />
* );
*
* 3. Reset `Pressability` when your component unmounts.
*
* componentWillUnmount() {
* this.state.pressability.reset();
* }
*
* ==================== Pressability Implementation Details ====================
*
* `Pressability` only assumes that there exists a `HitRect` node. The `PressRect`
* is an abstract box that is extended beyond the `HitRect`.
*
* # Geometry
*
* โโโโโโโโโโโโโโโโโโโโโโโโโโ
* โ โโโโโโโโโโโโโโโโโโโโ โ - Presses start anywhere within `HitRect`, which
* โ โ โโโโโโโโโโโโโโ โ โ is expanded via the prop `hitSlop`.
* โ โ โ VisualRect โ โ โ
* โ โ โโโโโโโโโโโโโโ โ โ - When pressed down for sufficient amount of time
* โ โ HitRect โ โ before letting up, `VisualRect` activates for
* โ โโโโโโโโโโโโโโโโโโโโ โ as long as the press stays within `PressRect`.
* โ PressRect o โ
* โโโโโโโโโโโโโโโโโโโโโโโโโโ
* Out Region โโโโโโโ `PressRect`, which is expanded via the prop
* `pressRectOffset`, allows presses to move
* beyond `HitRect` while maintaining activation
* and being eligible for a "press".
*
* # State Machine
*
* โโโโโโโโโโโโโโโโโ โโโโโ RESPONDER_RELEASE
* โ NOT_RESPONDER โ
* โโโโโฌโโโโโโโโโโโโ โโโโโ RESPONDER_TERMINATED
* โ
* โ RESPONDER_GRANT (HitRect)
* โ
* โผ
* โโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโ
* โ RESPONDER_INACTIVE_ โ DELAY โ RESPONDER_ACTIVE_ โ T + DELAY โ RESPONDER_ACTIVE_ โ
* โ PRESS_IN โโโโโโโโโโถ โ PRESS_IN โโโโโโโโโโโโโโถ โ LONG_PRESS_IN โ
* โโโฌโโโโโโโโโโโโโโโโโโโโ โโโฌโโโโโโโโโโโโโโโโโโ โโโฌโโโโโโโโโโโโโโโโโโ
* โ โฒ โ โฒ โ โฒ
* โLEAVE_ โ โLEAVE_ โ โLEAVE_ โ
* โPRESS_RECT โENTER_ โPRESS_RECT โENTER_ โPRESS_RECT โENTER_
* โ โPRESS_RECT โ โPRESS_RECT โ โPRESS_RECT
* โผ โ โผ โ โผ โ
* โโโโโโโโโโโโโโโดโโโโโโโโ โโโโโโโโโโโโโโโดโโโโโโ โโโโโโโโโโโโโโโดโโโโโโ
* โ RESPONDER_INACTIVE_ โ DELAY โ RESPONDER_ACTIVE_ โ โ RESPONDER_ACTIVE_ โ
* โ PRESS_OUT โโโโโโโโโโถ โ PRESS_OUT โ โ LONG_PRESS_OUT โ
* โโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโ
*
* T + DELAY => LONG_PRESS_DELAY + DELAY
*
* Not drawn are the side effects of each transition. The most important side
* effect is the invocation of `onPress` and `onLongPress` that occur when a
* responder is release while in the "press in" states.
*/
export class Pressability {
private _config: PressabilityConfig;
private _eventHandlers: PressabilityEventHandlers = null;
private _hoverInDelayTimeout: any /* TimeoutID */ = null;
private _hoverOutDelayTimeout: any /* TimeoutID */ = null;
private _isHovered: boolean = false;
private _longPressDelayTimeout: any /* TimeoutID */ = null;
private _pressDelayTimeout: any /* TimeoutID */ = null;
private _pressOutDelayTimeout: any /* TimeoutID */ = null;
private _responderID: number | React.ElementRef<HostComponent<any>> = null;
private _responderRegion: Rect = null;
private _touchActivatePosition: Readonly<{
pageX: number;
pageY: number;
}>;
private _touchState: TouchState = 'NOT_RESPONDER';
constructor(config: PressabilityConfig) {
this.configure(config);
}
public configure(config: PressabilityConfig): void {
this._config = config;
}
/**
* Resets any pending timers. This should be called on unmount.
*/
public reset(): void {
this._cancelHoverInDelayTimeout();
this._cancelHoverOutDelayTimeout();
this._cancelLongPressDelayTimeout();
this._cancelPressDelayTimeout();
this._cancelPressOutDelayTimeout();
}
/**
* Returns a set of props to spread into the interactive element.
*/
public getEventHandlers(): PressabilityEventHandlers {
if (this._eventHandlers == null) {
this._eventHandlers = this._createEventHandlers();
}
return this._eventHandlers;
}
private _createEventHandlers(): PressabilityEventHandlers {
const focusEventHandlers = {
onBlur: (event: BlurEvent): void => {
const { onBlur } = this._config;
if (onBlur != null) {
onBlur(event);
}
},
onFocus: (event: FocusEvent): void => {
const { onFocus } = this._config;
if (onFocus != null) {
onFocus(event);
}
},
};
const responderEventHandlers = {
onStartShouldSetResponder: (): boolean => {
const { disabled } = this._config;
if (disabled == null) {
return true;
}
return !disabled;
},
onResponderGrant: (event: PressEvent): void => {
event.persist();
this._cancelPressOutDelayTimeout();
this._responderID = event.currentTarget;
this._touchState = 'NOT_RESPONDER';
this._receiveSignal('RESPONDER_GRANT', event);
const delayPressIn = normalizeDelay(this._config.delayPressIn, 0, DEFAULT_PRESS_DELAY_MS);
if (delayPressIn > 0) {
this._pressDelayTimeout = setTimeout(() => {
this._receiveSignal('DELAY', event);
}, delayPressIn);
} else {
this._receiveSignal('DELAY', event);
}
const delayLongPress = normalizeDelay(this._config.delayLongPress, 10, DEFAULT_LONG_PRESS_DELAY_MS);
this._longPressDelayTimeout = setTimeout(() => {
this._handleLongPress(event);
}, delayLongPress + delayPressIn);
},
onResponderMove: (event: PressEvent): void => {
if (this._config.onPressMove != null) {
this._config.onPressMove(event);
}
// Region may not have finished being measured, yet.
const responderRegion = this._responderRegion;
if (responderRegion == null) {
return;
}
const touch = getTouchFromPressEvent(event);
if (touch == null) {
this._cancelLongPressDelayTimeout();
this._receiveSignal('LEAVE_PRESS_RECT', event);
return;
}
if (this._touchActivatePosition != null) {
const deltaX = this._touchActivatePosition.pageX - touch.pageX;
const deltaY = this._touchActivatePosition.pageY - touch.pageY;
if (Math.hypot(deltaX, deltaY) > 10) {
this._cancelLongPressDelayTimeout();
}
}
if (this._isTouchWithinResponderRegion(touch, responderRegion)) {
this._receiveSignal('ENTER_PRESS_RECT', event);
} else {
this._cancelLongPressDelayTimeout();
this._receiveSignal('LEAVE_PRESS_RECT', event);
}
},
onResponderRelease: (event: PressEvent): void => {
this._receiveSignal('RESPONDER_RELEASE', event);
},
onResponderTerminate: (event: PressEvent): void => {
this._receiveSignal('RESPONDER_TERMINATED', event);
},
onResponderTerminationRequest: (): boolean => {
const { cancelable } = this._config;
return cancelable || true;
},
onClick: (event): void => {
const { onPress } = this._config;
if (onPress != null) {
onPress(event);
}
},
};
const mouseEventHandlers =
Platform.OS === 'ios' || Platform.OS === 'android'
? null
: {
onMouseEnter: (event: MouseEvent): void => {
if (isHoverEnabled()) {
this._isHovered = true;
this._cancelHoverOutDelayTimeout();
const { onHoverIn } = this._config;
if (onHoverIn != null) {
const delayHoverIn = normalizeDelay(this._config.delayHoverIn);
if (delayHoverIn > 0) {
this._hoverInDelayTimeout = setTimeout(() => {
onHoverIn(event);
}, delayHoverIn);
} else {
onHoverIn(event);
}
}
}
},
onMouseLeave: (event: MouseEvent): void => {
if (this._isHovered) {
this._isHovered = false;
this._cancelHoverInDelayTimeout();
const { onHoverOut } = this._config;
if (onHoverOut != null) {
const delayHoverOut = normalizeDelay(this._config.delayHoverOut);
if (delayHoverOut > 0) {
this._hoverInDelayTimeout = setTimeout(() => {
onHoverOut(event);
}, delayHoverOut);
} else {
onHoverOut(event);
}
}
}
},
};
return {
...focusEventHandlers,
...responderEventHandlers,
...mouseEventHandlers,
};
}
/**
* Receives a state machine signal, performs side effects of the transition
* and stores the new state. Validates the transition as well.
*/
private _receiveSignal(signal: TouchSignal, event: PressEvent): void {
const prevState = this._touchState;
const nextState: TouchState = Transitions[prevState][signal];
if (this._responderID == null && signal === 'RESPONDER_RELEASE') {
return;
}
invariant(
nextState != null && nextState !== 'ERROR',
'Pressability: Invalid signal `%s` for state `%s` on responder: %s',
signal,
prevState,
typeof this._responderID === 'number' ? this._responderID : '<<host component>>',
);
if (prevState !== nextState) {
this._performTransitionSideEffects(prevState, nextState, signal, event);
this._touchState = nextState;
}
}
/**
* Performs a transition between touchable states and identify any activations
* or deactivations (and callback invocations).
*/
private _performTransitionSideEffects(prevState: TouchState, nextState: TouchState, signal: TouchSignal, event): void {
if (isTerminalSignal(signal)) {
this._touchActivatePosition = null;
this._cancelLongPressDelayTimeout();
}
const isInitialTransition = prevState === 'NOT_RESPONDER' && nextState === 'RESPONDER_INACTIVE_PRESS_IN';
const isActivationTransiton = !isActivationSignal(prevState) && isActivationSignal(nextState);
if (isInitialTransition || isActivationTransiton) {
this._measureResponderRegion();
}
if (isPressInSignal(prevState) && signal === 'LONG_PRESS_DETECTED') {
const { onLongPress } = this._config;
if (onLongPress != null) {
onLongPress(event);
}
}
const isPrevActive = isActiveSignal(prevState);
const isNextActive = isActiveSignal(nextState);
if (!isPrevActive && isNextActive) {
this._activate(event);
} else if (isPrevActive && !isNextActive) {
this._deactivate(event);
}
if (isPressInSignal(prevState) && signal === 'RESPONDER_RELEASE') {
const { onLongPress, onPress /*, android_disableSound */ } = this._config;
if (onPress != null) {
const isPressCanceledByLongPress =
onLongPress != null && prevState === 'RESPONDER_ACTIVE_LONG_PRESS_IN' && this._shouldLongPressCancelPress();
if (!isPressCanceledByLongPress) {
// If we never activated (due to delays), activate and deactivate now.
if (!isNextActive && !isPrevActive) {
this._activate(event);
this._deactivate(event);
}
/*
if (Platform.OS === 'android' && android_disableSound !== true) {
SoundManager.playTouchSound();
}
*/
onPress(event);
}
}
}
this._cancelPressDelayTimeout();
}
private _activate(event): void {
const { onPressIn } = this._config;
const touch = getTouchFromPressEvent(event);
this._touchActivatePosition = {
pageX: touch.pageX,
pageY: touch.pageY,
};
if (onPressIn != null) {
onPressIn(event);
}
}
private _deactivate(event): void {
const { onPressOut } = this._config;
if (onPressOut != null) {
const delayPressOut = normalizeDelay(this._config.delayPressOut);
if (delayPressOut > 0) {
this._pressOutDelayTimeout = setTimeout(() => {
onPressOut(event);
}, delayPressOut);
} else {
onPressOut(event);
}
}
}
private _measureResponderRegion(): void {
if (this._responderID == null) {
return;
}
if (typeof this._responderID === 'number') {
UIManager.measure(this._responderID, this._measureCallback);
} else {
const measure = (this as any)?._responderID?.measure;
if (typeof measure === 'function' && this._measureCallback) {
(this as any)?._responderID?.measure(this._measureCallback);
}
}
}
private _measureCallback = (left, top, width, height, pageX, pageY) => {
if (!left && !top && !width && !height && !pageX && !pageY) {
return;
}
this._responderRegion = {
bottom: pageY + height,
left: pageX,
right: pageX + width,
top: pageY,
};
};
private _isTouchWithinResponderRegion(touch: any /* PropertyType<PressEvent, 'nativeEvent'> */, responderRegion: Rect): boolean {
const hitSlop = normalizeRect(this._config.hitSlop);
const pressRectOffset = normalizeRect(this._config.pressRectOffset);
let regionBottom = responderRegion.bottom;
let regionLeft = responderRegion.left;
let regionRight = responderRegion.right;
let regionTop = responderRegion.top;
if (hitSlop != null) {
if (hitSlop.bottom != null) {
regionBottom += hitSlop.bottom;
}
if (hitSlop.left != null) {
regionLeft -= hitSlop.left;
}
if (hitSlop.right != null) {
regionRight += hitSlop.right;
}
if (hitSlop.top != null) {
regionTop -= hitSlop.top;
}
}
regionBottom += pressRectOffset?.bottom ?? DEFAULT_PRESS_RECT_OFFSETS.bottom;
regionLeft -= pressRectOffset?.left ?? DEFAULT_PRESS_RECT_OFFSETS.left;
regionRight += pressRectOffset?.right ?? DEFAULT_PRESS_RECT_OFFSETS.right;
regionTop -= pressRectOffset?.top ?? DEFAULT_PRESS_RECT_OFFSETS.top;
return touch.pageX > regionLeft && touch.pageX < regionRight && touch.pageY > regionTop && touch.pageY < regionBottom;
}
private _handleLongPress(event: PressEvent): void {
if (this._touchState === 'RESPONDER_ACTIVE_PRESS_IN' || this._touchState === 'RESPONDER_ACTIVE_LONG_PRESS_IN') {
this._receiveSignal('LONG_PRESS_DETECTED', event);
}
}
private _shouldLongPressCancelPress(): boolean {
return true;
}
private _cancelHoverInDelayTimeout(): void {
if (this._hoverInDelayTimeout != null) {
clearTimeout(this._hoverInDelayTimeout);
this._hoverInDelayTimeout = null;
}
}
private _cancelHoverOutDelayTimeout(): void {
if (this._hoverOutDelayTimeout != null) {
clearTimeout(this._hoverOutDelayTimeout);
this._hoverOutDelayTimeout = null;
}
}
private _cancelLongPressDelayTimeout(): void {
if (this._longPressDelayTimeout != null) {
clearTimeout(this._longPressDelayTimeout);
this._longPressDelayTimeout = null;
}
}
private _cancelPressDelayTimeout(): void {
if (this._pressDelayTimeout != null) {
clearTimeout(this._pressDelayTimeout);
this._pressDelayTimeout = null;
}
}
private _cancelPressOutDelayTimeout(): void {
if (this._pressOutDelayTimeout != null) {
clearTimeout(this._pressOutDelayTimeout);
this._pressOutDelayTimeout = null;
}
}
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
export const ConfigurationMetrics: msRest.CompositeMapper = {
serializedName: "ConfigurationMetrics",
type: {
name: "Composite",
className: "ConfigurationMetrics",
modelProperties: {
results: {
serializedName: "results",
type: {
name: "Dictionary",
value: {
type: {
name: "Number"
}
}
}
},
queries: {
serializedName: "queries",
type: {
name: "Dictionary",
value: {
type: {
name: "String"
}
}
}
}
}
}
};
export const ConfigurationContent: msRest.CompositeMapper = {
serializedName: "ConfigurationContent",
type: {
name: "Composite",
className: "ConfigurationContent",
modelProperties: {
deviceContent: {
serializedName: "deviceContent",
type: {
name: "Dictionary",
value: {
type: {
name: "Object"
}
}
}
},
modulesContent: {
serializedName: "modulesContent",
type: {
name: "Dictionary",
value: {
type: {
name: "Dictionary",
value: {
type: {
name: "Object"
}
}
}
}
}
},
moduleContent: {
serializedName: "moduleContent",
type: {
name: "Dictionary",
value: {
type: {
name: "Object"
}
}
}
}
}
}
};
export const Configuration: msRest.CompositeMapper = {
serializedName: "Configuration",
type: {
name: "Composite",
className: "Configuration",
modelProperties: {
id: {
serializedName: "id",
type: {
name: "String"
}
},
schemaVersion: {
serializedName: "schemaVersion",
type: {
name: "String"
}
},
labels: {
serializedName: "labels",
type: {
name: "Dictionary",
value: {
type: {
name: "String"
}
}
}
},
content: {
serializedName: "content",
type: {
name: "Composite",
className: "ConfigurationContent"
}
},
targetCondition: {
serializedName: "targetCondition",
type: {
name: "String"
}
},
createdTimeUtc: {
serializedName: "createdTimeUtc",
type: {
name: "DateTime"
}
},
lastUpdatedTimeUtc: {
serializedName: "lastUpdatedTimeUtc",
type: {
name: "DateTime"
}
},
priority: {
serializedName: "priority",
type: {
name: "Number"
}
},
systemMetrics: {
serializedName: "systemMetrics",
type: {
name: "Composite",
className: "ConfigurationMetrics"
}
},
metrics: {
serializedName: "metrics",
type: {
name: "Composite",
className: "ConfigurationMetrics"
}
},
etag: {
serializedName: "etag",
type: {
name: "String"
}
}
}
}
};
export const ConfigurationQueriesTestInput: msRest.CompositeMapper = {
serializedName: "ConfigurationQueriesTestInput",
type: {
name: "Composite",
className: "ConfigurationQueriesTestInput",
modelProperties: {
targetCondition: {
serializedName: "targetCondition",
type: {
name: "String"
}
},
customMetricQueries: {
serializedName: "customMetricQueries",
type: {
name: "Dictionary",
value: {
type: {
name: "String"
}
}
}
}
}
}
};
export const ConfigurationQueriesTestResponse: msRest.CompositeMapper = {
serializedName: "ConfigurationQueriesTestResponse",
type: {
name: "Composite",
className: "ConfigurationQueriesTestResponse",
modelProperties: {
targetConditionError: {
serializedName: "targetConditionError",
type: {
name: "String"
}
},
customMetricQueryErrors: {
serializedName: "customMetricQueryErrors",
type: {
name: "Dictionary",
value: {
type: {
name: "String"
}
}
}
}
}
}
};
export const RegistryStatistics: msRest.CompositeMapper = {
serializedName: "RegistryStatistics",
type: {
name: "Composite",
className: "RegistryStatistics",
modelProperties: {
totalDeviceCount: {
serializedName: "totalDeviceCount",
type: {
name: "Number"
}
},
enabledDeviceCount: {
serializedName: "enabledDeviceCount",
type: {
name: "Number"
}
},
disabledDeviceCount: {
serializedName: "disabledDeviceCount",
type: {
name: "Number"
}
}
}
}
};
export const ServiceStatistics: msRest.CompositeMapper = {
serializedName: "ServiceStatistics",
type: {
name: "Composite",
className: "ServiceStatistics",
modelProperties: {
connectedDeviceCount: {
serializedName: "connectedDeviceCount",
type: {
name: "Number"
}
}
}
}
};
export const SymmetricKey: msRest.CompositeMapper = {
serializedName: "SymmetricKey",
type: {
name: "Composite",
className: "SymmetricKey",
modelProperties: {
primaryKey: {
serializedName: "primaryKey",
type: {
name: "String"
}
},
secondaryKey: {
serializedName: "secondaryKey",
type: {
name: "String"
}
}
}
}
};
export const X509Thumbprint: msRest.CompositeMapper = {
serializedName: "X509Thumbprint",
type: {
name: "Composite",
className: "X509Thumbprint",
modelProperties: {
primaryThumbprint: {
serializedName: "primaryThumbprint",
type: {
name: "String"
}
},
secondaryThumbprint: {
serializedName: "secondaryThumbprint",
type: {
name: "String"
}
}
}
}
};
export const AuthenticationMechanism: msRest.CompositeMapper = {
serializedName: "AuthenticationMechanism",
type: {
name: "Composite",
className: "AuthenticationMechanism",
modelProperties: {
symmetricKey: {
serializedName: "symmetricKey",
type: {
name: "Composite",
className: "SymmetricKey"
}
},
x509Thumbprint: {
serializedName: "x509Thumbprint",
type: {
name: "Composite",
className: "X509Thumbprint"
}
},
type: {
serializedName: "type",
type: {
name: "String"
}
}
}
}
};
export const DeviceCapabilities: msRest.CompositeMapper = {
serializedName: "DeviceCapabilities",
type: {
name: "Composite",
className: "DeviceCapabilities",
modelProperties: {
iotEdge: {
serializedName: "iotEdge",
type: {
name: "Boolean"
}
}
}
}
};
export const Device: msRest.CompositeMapper = {
serializedName: "Device",
type: {
name: "Composite",
className: "Device",
modelProperties: {
deviceId: {
serializedName: "deviceId",
type: {
name: "String"
}
},
generationId: {
serializedName: "generationId",
type: {
name: "String"
}
},
etag: {
serializedName: "etag",
type: {
name: "String"
}
},
connectionState: {
serializedName: "connectionState",
type: {
name: "String"
}
},
status: {
serializedName: "status",
type: {
name: "String"
}
},
statusReason: {
serializedName: "statusReason",
type: {
name: "String"
}
},
connectionStateUpdatedTime: {
serializedName: "connectionStateUpdatedTime",
type: {
name: "DateTime"
}
},
statusUpdatedTime: {
serializedName: "statusUpdatedTime",
type: {
name: "DateTime"
}
},
lastActivityTime: {
serializedName: "lastActivityTime",
type: {
name: "DateTime"
}
},
cloudToDeviceMessageCount: {
serializedName: "cloudToDeviceMessageCount",
type: {
name: "Number"
}
},
authentication: {
serializedName: "authentication",
type: {
name: "Composite",
className: "AuthenticationMechanism"
}
},
capabilities: {
serializedName: "capabilities",
type: {
name: "Composite",
className: "DeviceCapabilities"
}
},
deviceScope: {
serializedName: "deviceScope",
type: {
name: "String"
}
},
parentScopes: {
serializedName: "parentScopes",
type: {
name: "Sequence",
element: {
type: {
name: "String"
}
}
}
}
}
}
};
export const PropertyContainer: msRest.CompositeMapper = {
serializedName: "PropertyContainer",
type: {
name: "Composite",
className: "PropertyContainer",
modelProperties: {
desired: {
serializedName: "desired",
type: {
name: "Dictionary",
value: {
type: {
name: "Object"
}
}
}
},
reported: {
serializedName: "reported",
type: {
name: "Dictionary",
value: {
type: {
name: "Object"
}
}
}
}
}
}
};
export const ExportImportDevice: msRest.CompositeMapper = {
serializedName: "ExportImportDevice",
type: {
name: "Composite",
className: "ExportImportDevice",
modelProperties: {
id: {
serializedName: "id",
type: {
name: "String"
}
},
moduleId: {
serializedName: "moduleId",
type: {
name: "String"
}
},
eTag: {
serializedName: "eTag",
type: {
name: "String"
}
},
importMode: {
serializedName: "importMode",
type: {
name: "String"
}
},
status: {
serializedName: "status",
type: {
name: "String"
}
},
statusReason: {
serializedName: "statusReason",
type: {
name: "String"
}
},
authentication: {
serializedName: "authentication",
type: {
name: "Composite",
className: "AuthenticationMechanism"
}
},
twinETag: {
serializedName: "twinETag",
type: {
name: "String"
}
},
tags: {
serializedName: "tags",
type: {
name: "Dictionary",
value: {
type: {
name: "Object"
}
}
}
},
properties: {
serializedName: "properties",
type: {
name: "Composite",
className: "PropertyContainer"
}
},
capabilities: {
serializedName: "capabilities",
type: {
name: "Composite",
className: "DeviceCapabilities"
}
},
deviceScope: {
serializedName: "deviceScope",
type: {
name: "String"
}
},
parentScopes: {
serializedName: "parentScopes",
type: {
name: "Sequence",
element: {
type: {
name: "String"
}
}
}
}
}
}
};
export const DeviceRegistryOperationError: msRest.CompositeMapper = {
serializedName: "DeviceRegistryOperationError",
type: {
name: "Composite",
className: "DeviceRegistryOperationError",
modelProperties: {
deviceId: {
serializedName: "deviceId",
type: {
name: "String"
}
},
errorCode: {
serializedName: "errorCode",
type: {
name: "String"
}
},
errorStatus: {
serializedName: "errorStatus",
type: {
name: "String"
}
},
moduleId: {
serializedName: "moduleId",
type: {
name: "String"
}
},
operation: {
serializedName: "operation",
type: {
name: "String"
}
}
}
}
};
export const DeviceRegistryOperationWarning: msRest.CompositeMapper = {
serializedName: "DeviceRegistryOperationWarning",
type: {
name: "Composite",
className: "DeviceRegistryOperationWarning",
modelProperties: {
deviceId: {
serializedName: "deviceId",
type: {
name: "String"
}
},
warningCode: {
serializedName: "warningCode",
type: {
name: "String"
}
},
warningStatus: {
serializedName: "warningStatus",
type: {
name: "String"
}
}
}
}
};
export const BulkRegistryOperationResult: msRest.CompositeMapper = {
serializedName: "BulkRegistryOperationResult",
type: {
name: "Composite",
className: "BulkRegistryOperationResult",
modelProperties: {
isSuccessful: {
serializedName: "isSuccessful",
type: {
name: "Boolean"
}
},
errors: {
serializedName: "errors",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "DeviceRegistryOperationError"
}
}
}
},
warnings: {
serializedName: "warnings",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "DeviceRegistryOperationWarning"
}
}
}
}
}
}
};
export const QuerySpecification: msRest.CompositeMapper = {
serializedName: "QuerySpecification",
type: {
name: "Composite",
className: "QuerySpecification",
modelProperties: {
query: {
serializedName: "query",
type: {
name: "String"
}
}
}
}
};
export const TwinProperties: msRest.CompositeMapper = {
serializedName: "TwinProperties",
type: {
name: "Composite",
className: "TwinProperties",
modelProperties: {
desired: {
serializedName: "desired",
type: {
name: "Dictionary",
value: {
type: {
name: "Object"
}
}
}
},
reported: {
serializedName: "reported",
type: {
name: "Dictionary",
value: {
type: {
name: "Object"
}
}
}
}
}
}
};
export const Twin: msRest.CompositeMapper = {
serializedName: "Twin",
type: {
name: "Composite",
className: "Twin",
modelProperties: {
deviceId: {
serializedName: "deviceId",
type: {
name: "String"
}
},
moduleId: {
serializedName: "moduleId",
type: {
name: "String"
}
},
tags: {
serializedName: "tags",
type: {
name: "Dictionary",
value: {
type: {
name: "Object"
}
}
}
},
properties: {
serializedName: "properties",
type: {
name: "Composite",
className: "TwinProperties"
}
},
etag: {
serializedName: "etag",
type: {
name: "String"
}
},
version: {
serializedName: "version",
type: {
name: "Number"
}
},
deviceEtag: {
serializedName: "deviceEtag",
type: {
name: "String"
}
},
status: {
serializedName: "status",
type: {
name: "String"
}
},
statusReason: {
serializedName: "statusReason",
type: {
name: "String"
}
},
statusUpdateTime: {
serializedName: "statusUpdateTime",
type: {
name: "DateTime"
}
},
connectionState: {
serializedName: "connectionState",
type: {
name: "String"
}
},
lastActivityTime: {
serializedName: "lastActivityTime",
type: {
name: "DateTime"
}
},
cloudToDeviceMessageCount: {
serializedName: "cloudToDeviceMessageCount",
type: {
name: "Number"
}
},
authenticationType: {
serializedName: "authenticationType",
type: {
name: "String"
}
},
x509Thumbprint: {
serializedName: "x509Thumbprint",
type: {
name: "Composite",
className: "X509Thumbprint"
}
},
capabilities: {
serializedName: "capabilities",
type: {
name: "Composite",
className: "DeviceCapabilities"
}
},
deviceScope: {
serializedName: "deviceScope",
type: {
name: "String"
}
},
parentScopes: {
serializedName: "parentScopes",
type: {
name: "Sequence",
element: {
type: {
name: "String"
}
}
}
}
}
}
};
export const JobProperties: msRest.CompositeMapper = {
serializedName: "JobProperties",
type: {
name: "Composite",
className: "JobProperties",
modelProperties: {
jobId: {
serializedName: "jobId",
type: {
name: "String"
}
},
startTimeUtc: {
serializedName: "startTimeUtc",
type: {
name: "DateTime"
}
},
endTimeUtc: {
serializedName: "endTimeUtc",
type: {
name: "DateTime"
}
},
type: {
serializedName: "type",
type: {
name: "String"
}
},
status: {
serializedName: "status",
type: {
name: "String"
}
},
progress: {
serializedName: "progress",
type: {
name: "Number"
}
},
inputBlobContainerUri: {
serializedName: "inputBlobContainerUri",
type: {
name: "String"
}
},
inputBlobName: {
serializedName: "inputBlobName",
type: {
name: "String"
}
},
outputBlobContainerUri: {
serializedName: "outputBlobContainerUri",
type: {
name: "String"
}
},
outputBlobName: {
serializedName: "outputBlobName",
type: {
name: "String"
}
},
excludeKeysInExport: {
serializedName: "excludeKeysInExport",
type: {
name: "Boolean"
}
},
storageAuthenticationType: {
serializedName: "storageAuthenticationType",
type: {
name: "String"
}
},
failureReason: {
serializedName: "failureReason",
type: {
name: "String"
}
},
includeConfigurations: {
serializedName: "includeConfigurations",
type: {
name: "Boolean"
}
},
configurationsBlobName: {
serializedName: "configurationsBlobName",
type: {
name: "String"
}
}
}
}
};
export const PurgeMessageQueueResult: msRest.CompositeMapper = {
serializedName: "PurgeMessageQueueResult",
type: {
name: "Composite",
className: "PurgeMessageQueueResult",
modelProperties: {
totalMessagesPurged: {
serializedName: "totalMessagesPurged",
type: {
name: "Number"
}
},
deviceId: {
serializedName: "deviceId",
type: {
name: "String"
}
},
moduleId: {
serializedName: "moduleId",
type: {
name: "String"
}
}
}
}
};
export const CloudToDeviceMethod: msRest.CompositeMapper = {
serializedName: "CloudToDeviceMethod",
type: {
name: "Composite",
className: "CloudToDeviceMethod",
modelProperties: {
methodName: {
serializedName: "methodName",
type: {
name: "String"
}
},
payload: {
serializedName: "payload",
type: {
name: "Object"
}
},
responseTimeoutInSeconds: {
serializedName: "responseTimeoutInSeconds",
type: {
name: "Number"
}
},
connectTimeoutInSeconds: {
serializedName: "connectTimeoutInSeconds",
type: {
name: "Number"
}
}
}
}
};
export const JobRequest: msRest.CompositeMapper = {
serializedName: "JobRequest",
type: {
name: "Composite",
className: "JobRequest",
modelProperties: {
jobId: {
serializedName: "jobId",
type: {
name: "String"
}
},
type: {
serializedName: "type",
type: {
name: "String"
}
},
cloudToDeviceMethod: {
serializedName: "cloudToDeviceMethod",
type: {
name: "Composite",
className: "CloudToDeviceMethod"
}
},
updateTwin: {
serializedName: "updateTwin",
type: {
name: "Composite",
className: "Twin"
}
},
queryCondition: {
serializedName: "queryCondition",
type: {
name: "String"
}
},
startTime: {
serializedName: "startTime",
type: {
name: "DateTime"
}
},
maxExecutionTimeInSeconds: {
serializedName: "maxExecutionTimeInSeconds",
type: {
name: "Number"
}
}
}
}
};
export const DeviceJobStatistics: msRest.CompositeMapper = {
serializedName: "DeviceJobStatistics",
type: {
name: "Composite",
className: "DeviceJobStatistics",
modelProperties: {
deviceCount: {
serializedName: "deviceCount",
type: {
name: "Number"
}
},
failedCount: {
serializedName: "failedCount",
type: {
name: "Number"
}
},
succeededCount: {
serializedName: "succeededCount",
type: {
name: "Number"
}
},
runningCount: {
serializedName: "runningCount",
type: {
name: "Number"
}
},
pendingCount: {
serializedName: "pendingCount",
type: {
name: "Number"
}
}
}
}
};
export const JobResponse: msRest.CompositeMapper = {
serializedName: "JobResponse",
type: {
name: "Composite",
className: "JobResponse",
modelProperties: {
jobId: {
serializedName: "jobId",
type: {
name: "String"
}
},
queryCondition: {
serializedName: "queryCondition",
type: {
name: "String"
}
},
createdTime: {
serializedName: "createdTime",
type: {
name: "DateTime"
}
},
startTime: {
serializedName: "startTime",
type: {
name: "DateTime"
}
},
endTime: {
serializedName: "endTime",
type: {
name: "DateTime"
}
},
maxExecutionTimeInSeconds: {
serializedName: "maxExecutionTimeInSeconds",
type: {
name: "Number"
}
},
type: {
serializedName: "type",
type: {
name: "String"
}
},
cloudToDeviceMethod: {
serializedName: "cloudToDeviceMethod",
type: {
name: "Composite",
className: "CloudToDeviceMethod"
}
},
updateTwin: {
serializedName: "updateTwin",
type: {
name: "Composite",
className: "Twin"
}
},
status: {
serializedName: "status",
type: {
name: "String"
}
},
failureReason: {
serializedName: "failureReason",
type: {
name: "String"
}
},
statusMessage: {
serializedName: "statusMessage",
type: {
name: "String"
}
},
deviceJobStatistics: {
serializedName: "deviceJobStatistics",
type: {
name: "Composite",
className: "DeviceJobStatistics"
}
}
}
}
};
export const QueryResult: msRest.CompositeMapper = {
serializedName: "QueryResult",
type: {
name: "Composite",
className: "QueryResult",
modelProperties: {
type: {
serializedName: "type",
type: {
name: "String"
}
},
items: {
serializedName: "items",
type: {
name: "Sequence",
element: {
type: {
name: "Object"
}
}
}
},
continuationToken: {
serializedName: "continuationToken",
type: {
name: "String"
}
}
}
}
};
export const Module: msRest.CompositeMapper = {
serializedName: "Module",
type: {
name: "Composite",
className: "Module",
modelProperties: {
moduleId: {
serializedName: "moduleId",
type: {
name: "String"
}
},
managedBy: {
serializedName: "managedBy",
type: {
name: "String"
}
},
deviceId: {
serializedName: "deviceId",
type: {
name: "String"
}
},
generationId: {
serializedName: "generationId",
type: {
name: "String"
}
},
etag: {
serializedName: "etag",
type: {
name: "String"
}
},
connectionState: {
serializedName: "connectionState",
type: {
name: "String"
}
},
connectionStateUpdatedTime: {
serializedName: "connectionStateUpdatedTime",
type: {
name: "DateTime"
}
},
lastActivityTime: {
serializedName: "lastActivityTime",
type: {
name: "DateTime"
}
},
cloudToDeviceMessageCount: {
serializedName: "cloudToDeviceMessageCount",
type: {
name: "Number"
}
},
authentication: {
serializedName: "authentication",
type: {
name: "Composite",
className: "AuthenticationMechanism"
}
}
}
}
};
export const CloudToDeviceMethodResult: msRest.CompositeMapper = {
serializedName: "CloudToDeviceMethodResult",
type: {
name: "Composite",
className: "CloudToDeviceMethodResult",
modelProperties: {
status: {
serializedName: "status",
type: {
name: "Number"
}
},
payload: {
serializedName: "payload",
type: {
name: "Object"
}
}
}
}
};
export const QueryGetTwinsHeaders: msRest.CompositeMapper = {
serializedName: "query-gettwins-headers",
type: {
name: "Composite",
className: "QueryGetTwinsHeaders",
modelProperties: {
xMsItemType: {
serializedName: "x-ms-item-type",
type: {
name: "String"
}
},
xMsContinuation: {
serializedName: "x-ms-continuation",
type: {
name: "String"
}
}
}
}
};
export const DigitalTwinGetDigitalTwinHeaders: msRest.CompositeMapper = {
serializedName: "digitaltwin-getdigitaltwin-headers",
type: {
name: "Composite",
className: "DigitalTwinGetDigitalTwinHeaders",
modelProperties: {
eTag: {
serializedName: "etag",
type: {
name: "String"
}
}
}
}
};
export const DigitalTwinUpdateDigitalTwinHeaders: msRest.CompositeMapper = {
serializedName: "digitaltwin-updatedigitaltwin-headers",
type: {
name: "Composite",
className: "DigitalTwinUpdateDigitalTwinHeaders",
modelProperties: {
eTag: {
serializedName: "etag",
type: {
name: "String"
}
},
location: {
serializedName: "location",
type: {
name: "String"
}
}
}
}
};
export const DigitalTwinInvokeRootLevelCommandHeaders: msRest.CompositeMapper = {
serializedName: "digitaltwin-invokerootlevelcommand-headers",
type: {
name: "Composite",
className: "DigitalTwinInvokeRootLevelCommandHeaders",
modelProperties: {
xMsCommandStatuscode: {
serializedName: "x-ms-command-statuscode",
type: {
name: "Number"
}
},
xMsRequestId: {
serializedName: "x-ms-request-id",
type: {
name: "String"
}
}
}
}
};
export const DigitalTwinInvokeComponentCommandHeaders: msRest.CompositeMapper = {
serializedName: "digitaltwin-invokecomponentcommand-headers",
type: {
name: "Composite",
className: "DigitalTwinInvokeComponentCommandHeaders",
modelProperties: {
xMsCommandStatuscode: {
serializedName: "x-ms-command-statuscode",
type: {
name: "Number"
}
},
xMsRequestId: {
serializedName: "x-ms-request-id",
type: {
name: "String"
}
}
}
}
}; | the_stack |
import { HttpHeaders, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { Observable, iif, throwError } from 'rxjs';
import { concatMap, filter, map, switchMap, take } from 'rxjs/operators';
import { Attribute } from 'ish-core/models/attribute/attribute.model';
import { Link } from 'ish-core/models/link/link.model';
import { ApiService, unpackEnvelope } from 'ish-core/services/api/api.service';
import { getUserPermissions } from 'ish-core/store/customer/authorization';
import { getCurrentBasketId } from 'ish-core/store/customer/basket';
import { getLoggedInCustomer } from 'ish-core/store/customer/user';
import { CookiesService } from 'ish-core/utils/cookies/cookies.service';
import { whenTruthy } from 'ish-core/utils/operators';
import { PunchoutSession } from '../../models/punchout-session/punchout-session.model';
import { PunchoutType, PunchoutUser } from '../../models/punchout-user/punchout-user.model';
// tslint:disable: force-jsdoc-comments
@Injectable({ providedIn: 'root' })
export class PunchoutService {
constructor(private apiService: ApiService, private cookiesService: CookiesService, private store: Store) {}
private currentCustomer$ = this.store.pipe(select(getLoggedInCustomer), whenTruthy(), take(1));
/**
* http header for Punchout API v2
*/
private punchoutHeaders = new HttpHeaders({
Accept: 'application/vnd.intershop.punchout.v2+json',
});
private getResourceType(punchoutType: PunchoutType): string {
return punchoutType === 'oci' ? 'oci5' : 'cxml1.2';
}
/**
* Gets all supported punchout formats.
* @returns An array of punchout types.
*/
getPunchoutTypes(): Observable<PunchoutType[]> {
return this.currentCustomer$.pipe(
switchMap(customer =>
this.apiService.get(`customers/${customer.customerNo}/punchouts`, { headers: this.punchoutHeaders }).pipe(
unpackEnvelope<Link>(),
this.apiService.resolveLinks<{ punchoutType: PunchoutType; version: string }>({
headers: this.punchoutHeaders,
}),
map(types => types?.map(type => type.punchoutType))
)
)
);
}
// PUNCHOUT USER MANAGEMENT
/**
* Gets the list of punchout users.
* @param punchoutType The user's punchout type.
* @returns An array of punchout users.
*/
getUsers(punchoutType: PunchoutType): Observable<PunchoutUser[]> {
if (!punchoutType) {
return throwError('getUsers() of the punchout service called without punchout type');
}
return this.currentCustomer$.pipe(
switchMap(customer =>
this.apiService
.get(`customers/${customer.customerNo}/punchouts/${this.getResourceType(punchoutType)}/users`, {
headers: this.punchoutHeaders,
})
.pipe(
unpackEnvelope<Link>(),
this.apiService.resolveLinks<PunchoutUser>({ headers: this.punchoutHeaders }),
map(users => users.map(user => ({ ...user, punchoutType, password: undefined })))
)
)
);
}
/**
* Creates a punchout user.
* @param user The punchout user.
* @returns The created punchout user.
*/
createUser(user: PunchoutUser): Observable<PunchoutUser> {
if (!user) {
return throwError('createUser() of the punchout service called without punchout user');
}
return this.currentCustomer$.pipe(
switchMap(customer =>
this.apiService
.post(`customers/${customer.customerNo}/punchouts/${this.getResourceType(user.punchoutType)}/users`, user, {
headers: this.punchoutHeaders,
})
.pipe(
this.apiService.resolveLink<PunchoutUser>({ headers: this.punchoutHeaders }),
map(createdUser => ({ ...createdUser, punchoutType: user.punchoutType, password: undefined }))
)
)
);
}
/**
* Updates a punchout user.
* @param user The punchout user.
* @returns The updated punchout user.
*/
updateUser(user: PunchoutUser): Observable<PunchoutUser> {
if (!user) {
return throwError('updateUser() of the punchout service called without punchout user');
}
return this.currentCustomer$.pipe(
switchMap(customer =>
this.apiService
.put<PunchoutUser>(
`customers/${customer.customerNo}/punchouts/${this.getResourceType(
user.punchoutType
)}/users/${encodeURIComponent(user.login)}`,
user,
{
headers: this.punchoutHeaders,
}
)
.pipe(map(updatedUser => ({ ...updatedUser, punchoutType: user.punchoutType, password: undefined })))
)
);
}
/**
* Deletes a punchout user.
* @param user The punchout user.
*/
deleteUser(user: PunchoutUser): Observable<void> {
if (!user) {
return throwError('deleteUser() of the punchout service called without user');
}
return this.currentCustomer$.pipe(
switchMap(customer =>
this.apiService.delete<void>(
`customers/${customer.customerNo}/punchouts/${this.getResourceType(user.punchoutType)}/users/${user.login}`,
{
headers: this.punchoutHeaders,
}
)
)
);
}
// PUNCHOUT SHOPPING FUNCTIONALITY
/**
* Initiates the punchout basket transfer depending on the user permission with the fitting punchout type (cXML or OCI).
*/
transferPunchoutBasket() {
return this.store.pipe(select(getUserPermissions)).pipe(
whenTruthy(),
switchMap(permissions =>
iif(
() => permissions.includes('APP_B2B_SEND_CXML_BASKET'),
this.transferCxmlPunchoutBasket(),
iif(() => permissions.includes('APP_B2B_SEND_OCI_BASKET'), this.transferOciPunchoutBasket())
)
)
);
}
/**
* Submits the punchout data via HTML form to the punchout system configured in the given form.
* @param form The prepared HTML form to submit the punchout data.
* @param submit Controls whether the HTML form is actually submitted (default) or not (only created in the document body).
*/
private submitPunchoutForm(form: HTMLFormElement, submit = true) {
if (!form) {
return throwError('submitPunchoutForm() of the punchout service called without a form');
}
// replace the document content with the form and submit the form
document.body.innerHTML = '';
document.body.appendChild(form);
if (submit) {
form.submit();
}
}
// cXML SPECIFIC PUNCHOUT SHOPPING FUNCTIONALITY
/**
* getCxmlPunchoutSession
*/
getCxmlPunchoutSession(sid: string): Observable<PunchoutSession> {
return this.currentCustomer$.pipe(
switchMap(customer =>
this.apiService.get<PunchoutSession>(
`customers/${customer.customerNo}/punchouts/${this.getResourceType('cxml')}/sessions/${sid}`,
{
headers: this.punchoutHeaders,
}
)
)
);
}
/**
* transferCxmlPunchoutBasket
*/
private transferCxmlPunchoutBasket() {
const punchoutSID = this.cookiesService.get('punchout_SID');
if (!punchoutSID) {
return throwError('no punchout_SID available in cookies for cXML punchout basket transfer');
}
const returnURL = this.cookiesService.get('punchout_ReturnURL');
if (!returnURL) {
return throwError('no punchout_ReturnURL available in cookies for cXML punchout basket transfer');
}
return this.currentCustomer$.pipe(
switchMap(customer =>
this.apiService
.post<string>(
`customers/${customer.customerNo}/punchouts/${this.getResourceType('cxml')}/transfer`,
undefined,
{
headers: new HttpHeaders({ Accept: 'text/xml' }),
params: new HttpParams().set('sid', punchoutSID),
responseType: 'text',
}
)
.pipe(map(data => this.submitPunchoutForm(this.createCxmlPunchoutForm(data, returnURL))))
)
);
// TODO: cleanup punchout cookies?
}
/**
* Creates an cXML punchout compatible form with the given BrowserFormPostURL
* and a hidden input field that contains the cXML PunchOutOrderMessage.
* @param punchOutOrderMessage
* @param browserFormPostUrl
* @returns The cXML punchout form
*/
private createCxmlPunchoutForm(punchOutOrderMessage: string, browserFormPostUrl: string): HTMLFormElement {
const cXmlForm = document.createElement('form');
cXmlForm.method = 'post';
cXmlForm.action = browserFormPostUrl;
cXmlForm.enctype = 'application/x-www-form-urlencoded';
const input = document.createElement('input'); // set the returnURL
input.setAttribute('name', 'cXML-urlencoded');
input.setAttribute('value', punchOutOrderMessage); // set the cXML value
input.setAttribute('type', 'hidden');
cXmlForm.appendChild(input);
return cXmlForm;
}
// OCI PUNCHOUT SHOPPING FUNCTIONALITY
private transferOciPunchoutBasket() {
return this.store.pipe(
select(getCurrentBasketId),
filter(basketId => !!basketId),
concatMap(basketId => this.getOciPunchoutBasketData(basketId).pipe(map(data => this.submitOciPunchoutData(data))))
);
}
/**
* Gets a JSON object with the necessary OCI punchout data for the basket transfer.
* @param basketId The basket id for the punchout.
*/
private getOciPunchoutBasketData(basketId: string): Observable<Attribute<string>[]> {
if (!basketId) {
return throwError('getOciPunchoutBasketData() of the punchout service called without basketId');
}
return this.currentCustomer$.pipe(
switchMap(customer =>
this.apiService
.post<{ data: Attribute<string>[] }>(
`customers/${customer.customerNo}/punchouts/${this.getResourceType('oci')}/transfer`,
undefined,
{
headers: this.punchoutHeaders,
params: new HttpParams().set('basketId', basketId),
}
)
.pipe(map(data => data.data))
)
);
}
/**
* Gets a JSON object with the necessary OCI punchout data for the product validation.
* @param productId The product id (SKU) of the product to validate.
* @param quantity The quantity for the validation (default: '1').
*/
getOciPunchoutProductData(productId: string, quantity = '1'): Observable<Attribute<string>[]> {
if (!productId) {
return throwError('getOciPunchoutProductData() of the punchout service called without productId');
}
return this.currentCustomer$.pipe(
switchMap(customer =>
this.apiService
.get<{ data: Attribute<string>[] }>(
`customers/${customer.customerNo}/punchouts/${this.getResourceType('oci')}/validate`,
{
headers: this.punchoutHeaders,
params: new HttpParams().set('productId', productId).set('quantity', quantity),
}
)
.pipe(map(data => data.data))
)
);
}
/**
* Gets a JSON object with the necessary OCI punchout data for the background search.
* @param searchString The search string to search punchout products.
*/
getOciPunchoutSearchData(searchString: string): Observable<Attribute<string>[]> {
if (!searchString) {
return throwError('getOciPunchoutSearchData() of the punchout service called without searchString');
}
return this.currentCustomer$.pipe(
switchMap(customer =>
this.apiService
.get<{ data: Attribute<string>[] }>(
`customers/${customer.customerNo}/punchouts/${this.getResourceType('oci')}/background-search`,
{
headers: this.punchoutHeaders,
params: new HttpParams().set('searchString', searchString),
}
)
.pipe(map(data => data.data))
)
);
}
/**
* Submits the OCI punchout data via HTML form to the OCI punchout system configured in the HOOK_URL
* @param data The punchout data retrieved from ICM.
* @param submit Controls whether the HTML form is actually submitted (default) or not (only created in the document body).
*/
submitOciPunchoutData(data: Attribute<string>[], submit = true) {
if (!data || !data.length) {
return throwError('submitOciPunchoutData() of the punchout service called without data');
}
const hookUrl = this.cookiesService.get('punchout_HookURL');
if (!hookUrl) {
return throwError('no punchout_HookURL available in cookies for OCI Punchout submitPunchoutData()');
}
this.submitPunchoutForm(this.createOciForm(data, hookUrl), submit);
}
/**
* Creates an OCI punchout compatible form with hidden input fields that reflect the attributes of the punchout data.
* @param data Attributes (key value pair) array
* @param hookUrl The hook URL
* @returns The OCI punchout form
*/
private createOciForm(data: Attribute<string>[], hookUrl: string): HTMLFormElement {
const ociForm = document.createElement('form');
ociForm.method = 'post';
ociForm.action = hookUrl;
data.forEach(inputData => {
const input = document.createElement('input'); // prepare a new input DOM element
input.setAttribute('name', inputData.name); // set the param name
input.setAttribute('value', inputData.value); // set the value
input.setAttribute('type', 'hidden'); // set the type "hidden"
ociForm.appendChild(input); // add the input to the OCI form
});
return ociForm;
}
} | the_stack |
import { GridStackEngine } from '../src/gridstack-engine';
import { GridStackNode } from '../src/types';
describe('gridstack engine', function() {
'use strict';
let engine: GridStackEngine;
// old hacky JS code that's not happy in TS. just cast to `any` and skip warnings
let e: any = GridStackEngine;
let w: any = window;
let findNode = function(engine, id) {
return engine.nodes.find((i) => i.id === id);
};
it('should exist setup function.', function() {
expect(e).not.toBeNull();
expect(typeof e).toBe('function');
});
describe('test constructor', function() {
it('should be setup properly', function() {
engine = new GridStackEngine();
expect(engine.column).toEqual(12);
expect(engine.float).toEqual(false);
expect(engine.maxRow).toEqual(undefined);
expect(engine.nodes).toEqual([]);
expect(engine.onChange).toEqual(undefined);
expect(engine.batchMode).toEqual(undefined);
});
it('should set params correctly.', function() {
let fkt = function() { };
let arr: any = [1,2,3];
engine = new GridStackEngine({column: 1, onChange:fkt, float:true, maxRow:2, nodes:arr});
expect(engine.column).toEqual(1);
expect(engine.float).toBe(true);
expect(engine.maxRow).toEqual(2);
expect(engine.nodes).toEqual(arr);
expect(engine.onChange).toEqual(fkt);
expect(engine.batchMode).toEqual(undefined);
});
});
describe('batch update', function() {
it('should set float and batchMode when calling batchUpdate.', function() {
engine = new GridStackEngine({float: true});
engine.batchUpdate();
expect(engine.float).toBe(true);
expect(engine.batchMode).toBeTrue();
});
});
describe('test prepareNode', function() {
beforeAll(function() {
engine = new GridStackEngine();
});
it('should prepare a node', function() {
expect(engine.prepareNode({}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, h: 1}));
expect(engine.prepareNode({x: 10}, false)).toEqual(jasmine.objectContaining({x: 10, y: 0, h: 1}));
expect(engine.prepareNode({x: -10}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, h: 1}));
expect(engine.prepareNode({y: 10}, false)).toEqual(jasmine.objectContaining({x: 0, y: 10, h: 1}));
expect(engine.prepareNode({y: -10}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, h: 1}));
expect(engine.prepareNode({w: 3}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, w: 3, h: 1}));
expect(engine.prepareNode({w: 100}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, w: 12, h: 1}));
expect(engine.prepareNode({w: 0}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, h: 1}));
expect(engine.prepareNode({w: -190}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, h: 1}));
expect(engine.prepareNode({h: 3}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, h: 3}));
expect(engine.prepareNode({h: 0}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, h: 1}));
expect(engine.prepareNode({h: -10}, false)).toEqual(jasmine.objectContaining({x: 0, y: 0, h: 1}));
expect(engine.prepareNode({x: 4, w: 10}, false)).toEqual(jasmine.objectContaining({x: 2, y: 0, w: 10, h: 1}));
expect(engine.prepareNode({x: 4, w: 10}, true)).toEqual(jasmine.objectContaining({x: 4, y: 0, w: 8, h: 1}));
});
});
describe('sorting of nodes', function() {
// Note: legacy weird call on global window to hold data
it('should sort ascending with 12 columns.', function() {
w.column = 12;
w.nodes = [{x: 7, y: 0}, {x: 4, y: 4}, {x: 9, y: 0}, {x: 0, y: 1}];
e.prototype._sortNodes.call(w, 1);
expect(w.nodes).toEqual([{x: 7, y: 0}, {x: 9, y: 0}, {x: 0, y: 1}, {x: 4, y: 4}]);
});
it('should sort descending with 12 columns.', function() {
w.column = 12;
w.nodes = [{x: 7, y: 0}, {x: 4, y: 4}, {x: 9, y: 0}, {x: 0, y: 1}];
e.prototype._sortNodes.call(w, -1);
expect(w.nodes).toEqual([{x: 4, y: 4}, {x: 0, y: 1}, {x: 9, y: 0}, {x: 7, y: 0}]);
});
it('should sort ascending with 1 columns.', function() {
w.column = 1;
w.nodes = [{x: 7, y: 0}, {x: 4, y: 4}, {x: 9, y: 0}, {x: 0, y: 1}];
e.prototype._sortNodes.call(w, 1);
expect(w.nodes).toEqual([{x: 0, y: 1}, {x: 7, y: 0}, {x: 4, y: 4}, {x: 9, y: 0}]);
});
it('should sort descending with 1 columns.', function() {
w.column = 1;
w.nodes = [{x: 7, y: 0}, {x: 4, y: 4}, {x: 9, y: 0}, {x: 0, y: 1}];
e.prototype._sortNodes.call(w, -1);
expect(w.nodes).toEqual([{x: 9, y: 0}, {x: 4, y: 4}, {x: 7, y: 0}, {x: 0, y: 1}]);
});
it('should sort ascending without columns.', function() {
w.column = undefined;
w.nodes = [{x: 7, y: 0, w: 1}, {x: 4, y: 4, w: 1}, {x: 9, y: 0, w: 1}, {x: 0, y: 1, w: 1}];
e.prototype._sortNodes.call(w, 1);
expect(w.nodes).toEqual([{x: 7, y: 0, w: 1}, {x: 9, y: 0, w: 1}, {x: 0, y: 1, w: 1}, {x: 4, y: 4, w: 1}]);
});
it('should sort descending without columns.', function() {
w.column = undefined;
w.nodes = [{x: 7, y: 0, w: 1}, {x: 4, y: 4, w: 1}, {x: 9, y: 0, w: 1}, {x: 0, y: 1, w: 1}];
e.prototype._sortNodes.call(w, -1);
expect(w.nodes).toEqual([{x: 4, y: 4, w: 1}, {x: 0, y: 1, w: 1}, {x: 9, y: 0, w: 1}, {x: 7, y: 0, w: 1}]);
});
});
describe('test isAreaEmpty', function() {
beforeAll(function() {
engine = new GridStackEngine({float:true});
engine.nodes = [
engine.prepareNode({x: 3, y: 2, w: 3, h: 2})
];
});
it('should be true', function() {
expect(engine.isAreaEmpty(0, 0, 3, 2)).toEqual(true);
expect(engine.isAreaEmpty(3, 4, 3, 2)).toEqual(true);
});
it('should be false', function() {
expect(engine.isAreaEmpty(1, 1, 3, 2)).toEqual(false);
expect(engine.isAreaEmpty(2, 3, 3, 2)).toEqual(false);
});
});
describe('test cleanNodes/getDirtyNodes', function() {
beforeAll(function() {
engine = new GridStackEngine({float:true});
engine.nodes = [
engine.prepareNode({x: 0, y: 0, id: 1, _dirty: true}),
engine.prepareNode({x: 3, y: 2, w: 3, h: 2, id: 2, _dirty: true}),
engine.prepareNode({x: 3, y: 7, w: 3, h: 2, id: 3})
];
});
beforeEach(function() {
delete engine.batchMode;
});
it('should return all dirty nodes', function() {
let nodes = engine.getDirtyNodes();
expect(nodes.length).toEqual(2);
expect(nodes[0].id).toEqual(1);
expect(nodes[1].id).toEqual(2);
});
it('should\'n clean nodes if batchMode true', function() {
engine.batchMode = true;
engine.cleanNodes();
expect(engine.getDirtyNodes().length).toBeGreaterThan(0);
});
it('should clean all dirty nodes', function() {
engine.cleanNodes();
expect(engine.getDirtyNodes().length).toEqual(0);
});
});
describe('test batchUpdate/commit', function() {
beforeAll(function() {
engine = new GridStackEngine();
});
it('should work on not float grids', function() {
expect(engine.float).toEqual(false);
engine.batchUpdate();
engine.batchUpdate(); // double for code coverage
expect(engine.batchMode).toBeTrue();
expect(engine.float).toEqual(true);
engine.commit();
engine.commit();
expect(engine.batchMode).not.toBeTrue();
expect(engine.float).not.toBeTrue;
});
it('should work on float grids', function() {
engine.float = true;
engine.batchUpdate();
expect(engine.batchMode).toBeTrue();
expect(engine.float).toEqual(true);
engine.commit();
expect(engine.batchMode).not.toBeTrue();
expect(engine.float).toEqual(true);
});
});
describe('test batchUpdate/commit', function() {
beforeAll(function() {
engine = new GridStackEngine({float:true});
});
it('should work on float grids', function() {
expect(engine.float).toEqual(true);
engine.batchUpdate();
expect(engine.batchMode).toBeTrue();
expect(engine.float).toEqual(true);
engine.commit();
expect(engine.batchMode).not.toBeTrue();
expect(engine.float).toEqual(true);
});
});
describe('test _notify', function() {
let spy;
beforeEach(function() {
spy = {
callback: function() {}
};
spyOn(spy, 'callback');
engine = new GridStackEngine({float:true, onChange: spy.callback});
engine.nodes = [
engine.prepareNode({x: 0, y: 0, id: 1, _dirty: true}),
engine.prepareNode({x: 3, y: 2, w: 3, h: 2, id: 2, _dirty: true}),
engine.prepareNode({x: 3, y: 7, w: 3, h: 2, id: 3})
];
});
it('should\'n be called if batchMode true', function() {
engine.batchMode = true;
(engine as any)._notify();
expect(spy.callback).not.toHaveBeenCalled();
});
it('should by called with dirty nodes', function() {
(engine as any)._notify();
expect(spy.callback).toHaveBeenCalledWith([
engine.nodes[0],
engine.nodes[1]
], true);
});
it('should by called with extra passed node to be removed', function() {
let n1 = {id: -1};
(engine as any)._notify(n1);
expect(spy.callback).toHaveBeenCalledWith([
n1,
engine.nodes[0],
engine.nodes[1]
], true);
});
it('should by called with extra passed node to be removed and should maintain false parameter', function() {
let n1 = {id: -1};
(engine as any)._notify(n1, false);
expect(spy.callback).toHaveBeenCalledWith([
n1,
engine.nodes[0],
engine.nodes[1]
], false);
});
});
describe('test _packNodes', function() {
describe('using not float mode', function() {
beforeEach(function() {
engine = new GridStackEngine({float:false});
});
it('shouldn\'t pack one node with y coord eq 0', function() {
engine.nodes = [
{x: 0, y: 0, w:1, h:1, id: 1},
];
(engine as any)._packNodes();
expect(findNode(engine, 1)).toEqual(jasmine.objectContaining({x: 0, y: 0, h: 1}));
expect(findNode(engine, 1)._dirty).toBeFalsy();
});
it('should pack one node correctly', function() {
engine.nodes = [
{x: 0, y: 1, w:1, h:1, id: 1},
];
(engine as any)._packNodes();
expect(findNode(engine, 1)).toEqual(jasmine.objectContaining({x: 0, y: 0, _dirty: true}));
});
it('should pack nodes correctly', function() {
engine.nodes = [
{x: 0, y: 1, w:1, h:1, id: 1},
{x: 0, y: 5, w:1, h:1, id: 2},
];
(engine as any)._packNodes();
expect(findNode(engine, 1)).toEqual(jasmine.objectContaining({x: 0, y: 0, _dirty: true}));
expect(findNode(engine, 2)).toEqual(jasmine.objectContaining({x: 0, y: 1, _dirty: true}));
});
it('should pack nodes correctly', function() {
engine.nodes = [
{x: 0, y: 5, w:1, h:1, id: 1},
{x: 0, y: 1, w:1, h:1, id: 2},
];
(engine as any)._packNodes();
expect(findNode(engine, 2)).toEqual(jasmine.objectContaining({x: 0, y: 0, _dirty: true}));
expect(findNode(engine, 1)).toEqual(jasmine.objectContaining({x: 0, y: 1, _dirty: true}));
});
it('should respect locked nodes', function() {
engine.nodes = [
{x: 0, y: 1, w:1, h:1, id: 1, locked: true},
{x: 0, y: 5, w:1, h:1, id: 2},
];
(engine as any)._packNodes();
expect(findNode(engine, 1)).toEqual(jasmine.objectContaining({x: 0, y: 1, h: 1}));
expect(findNode(engine, 1)._dirty).toBeFalsy();
expect(findNode(engine, 2)).toEqual(jasmine.objectContaining({x: 0, y: 2, _dirty: true}));
});
});
});
describe('test changedPos', function() {
beforeAll(function() {
engine = new GridStackEngine();
});
it('should return true for changed x', function() {
let widget = { x: 1, y: 2, w: 3, h: 4 };
expect(engine.changedPosConstrain(widget, {x:2, y:2})).toEqual(true);
});
it('should return true for changed y', function() {
let widget = { x: 1, y: 2, w: 3, h: 4 };
expect(engine.changedPosConstrain(widget, {x:1, y:1})).toEqual(true);
});
it('should return true for changed width', function() {
let widget = { x: 1, y: 2, w: 3, h: 4 };
expect(engine.changedPosConstrain(widget, {x:2, y:2, w:4, h:4})).toEqual(true);
});
it('should return true for changed height', function() {
let widget = { x: 1, y: 2, w: 3, h: 4 };
expect(engine.changedPosConstrain(widget, {x:1, y:2, w:3, h:3})).toEqual(true);
});
it('should return false for unchanged position', function() {
let widget = { x: 1, y: 2, w: 3, h: 4 };
expect(engine.changedPosConstrain(widget, {x:1, y:2, w:3, h:4})).toEqual(false);
});
});
describe('test locked widget', function() {
beforeAll(function() {
engine = new GridStackEngine();
});
it('should add widgets around locked one', function() {
let nodes: GridStackNode[] = [
{x: 0, y: 1, w: 12, h: 1, locked: true, noMove: true, noResize: true, id: 0},
{x: 1, y: 0, w: 2, h: 3, id: 1}
];
// add locked item
engine.addNode(nodes[0])
expect(findNode(engine, 0)).toEqual(jasmine.objectContaining({x: 0, y: 1, w: 12, h: 1, locked: true}));
// add item that moves past locked one
engine.addNode(nodes[1])
expect(findNode(engine, 0)).toEqual(jasmine.objectContaining({x: 0, y: 1, w: 12, h: 1, locked: true}));
expect(findNode(engine, 1)).toEqual(jasmine.objectContaining({x: 1, y: 2, h: 3}));
// locked item can still be moved directly (what user does)
let node0 = findNode(engine, 0);
expect(engine.moveNode(node0, {y:6})).toEqual(true);
expect(findNode(engine, 0)).toEqual(jasmine.objectContaining({x: 0, y: 6, h: 1, locked: true}));
// but moves regular one past it
let node1 = findNode(engine, 1);
expect(engine.moveNode(node1, {x:6, y:6})).toEqual(true);
expect(node1).toEqual(jasmine.objectContaining({x: 6, y: 7, w: 2, h: 3}));
// but moves regular one before (gravity ON)
engine.float = false;
expect(engine.moveNode(node1, {x:7, y:3})).toEqual(true);
expect(node1).toEqual(jasmine.objectContaining({x: 7, y: 0, w: 2, h: 3}));
// but moves regular one before (gravity OFF)
engine.float = true;
expect(engine.moveNode(node1, {x:7, y:3})).toEqual(true);
expect(node1).toEqual(jasmine.objectContaining({x: 7, y: 3, w: 2, h: 3}));
});
});
describe('test compact', function() {
beforeAll(function() {
engine = new GridStackEngine();
});
it('do nothing', function() {
engine.compact();
});
});
}); | the_stack |
import { ContextualMenu, DefaultButton, DetailsList, DetailsListLayoutMode, Dialog, DialogFooter, DialogType, Dropdown, Fabric, IColumn, IDropdownOption, IObjectWithKey, Label, Link, MarqueeSelection, PrimaryButton, SearchBox, Selection, Stack } from '@fluentui/react'
import { useBoolean, useForceUpdate } from '@uifabric/react-hooks'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { useHistory } from 'react-router-dom'
import { StepWizardChildProps, StepWizardProps } from 'react-step-wizard'
import { StackGap10 } from '../components/StackStyle'
import { StepPanel } from '../components/StepPanel'
import { useWindowSize } from '../components/UseWindowSize'
import { WizardNavBar } from '../components/WizardNavBar'
import { getNavSteps } from '../model/DefaultNavSteps'
import { ConfigurationsDataSrv } from '../services/Configurations'
import { TestSuitesDataSrv } from '../services/TestSuites'
import { SelectedTestCasesDataSrv } from '../services/SelectedTestCases'
import { AppState } from '../store/configureStore'
import { TestCase } from '../model/TestCase'
import { ContextualMenuControl, ContextualMenuItemProps } from '../components/ContextualMenuControl'
import { FileUploader, IFile } from '../components/FileUploader'
import { InvalidAppStateNotification } from '../components/InvalidAppStateNotification'
interface ListItem extends IObjectWithKey {
Name: string;
FullName: string
}
const getListItems = (testCases: TestCase[]): ListItem[] => {
return testCases.map(testCase => {
return {
key: testCase.FullName,
Name: testCase.Name,
FullName: testCase.FullName
}
})
}
function copyAndSort<T>(items: T[], columnKey: string, isSortedDescending?: boolean): T[] {
const key = columnKey as keyof T
return items.slice(0).sort((a: T, b: T) => ((isSortedDescending ? a[key] < b[key] : a[key] > b[key]) ? 1 : -1))
}
interface FilterByDropdownOption extends IDropdownOption {
filterFunc: (filterPhrase: string | undefined) => (item: ListItem) => boolean;
filterPlaceholder: string;
}
const isValidFilterPhrase = (filterPhrase: string | undefined) => {
return filterPhrase !== undefined && filterPhrase !== null && filterPhrase !== ''
}
const filterByNameFunc = (filterPhrase: string | undefined) => (item: ListItem) => {
return isValidFilterPhrase(filterPhrase)
? item.Name.toLocaleLowerCase().includes(filterPhrase!.toLocaleLowerCase())
: true
}
const filterByDropdownOptions: FilterByDropdownOption[] = [
{
key: 'Name',
text: 'Name',
filterFunc: filterByNameFunc,
filterPlaceholder: 'Filter by Name...'
}
]
type FilterByDropdownProps = {
options: FilterByDropdownOption[],
onOptionChange: (newOption: FilterByDropdownOption) => void
}
function FilterByDropdown(props: FilterByDropdownProps) {
return (
props.options.length > 0
? <Stack horizontal tokens={StackGap10}>
<Label style={{ alignSelf: 'center' }}>Filter By</Label>
<Dropdown
style={{ alignSelf: 'center', minWidth: 80 }}
defaultSelectedKey={props.options[0].key}
options={props.options}
onChange={(_, newValue, __) => props.onOptionChange(newValue as FilterByDropdownOption)}
/>
</Stack>
: null
)
}
const downloadPlaylist = (pageHTML: string) => {
const currentDate = new Date()
const blob = new Blob([pageHTML], { type: 'data:attachment/text' })
if (blob === undefined) {
return
}
const url = window.URL.createObjectURL(new Blob([blob]))
const link = document.createElement('a')
link.href = url
const dateStr = currentDate.toISOString().replace(/:/g, '-').replace('T', '-').replace('Z', '').replace('.', '-').replace(/ /g, '-')
link.setAttribute('download', 'ptmservice-' + dateStr + '.playlist')
link.click()
}
const exportPlaylist = (items: string[]) => {
let pageHTML: string = '<?xml version="1.0" encoding="utf-8"?><Playlist Version="1.0">'
items.forEach((item) => {
pageHTML += '<Add Test="' + item + '" />'
})
pageHTML += '</Playlist>'
downloadPlaylist(pageHTML)
}
export function RunSelectedCase(props: StepWizardProps) {
const dispatch = useDispatch()
const testSuiteInfo = useSelector((state: AppState) => state.testSuiteInfo)
const configuration = useSelector((state: AppState) => state.configurations)
const filterInfo = useSelector((state: AppState) => state.filterInfo)
const selectedTestCases = useSelector((state: AppState) => state.selectedTestCases)
const configureMethod = useSelector((state: AppState) => state.configureMethod)
const [filterPhrase, setFilterPhrase] = useState<string | undefined>(undefined)
const [filterByDropdownOption, setFilterByDropdownOption] = useState<FilterByDropdownOption>(filterByDropdownOptions[0])
const [filteredTestCases, setFilteredTestCases] = useState<ListItem[]>([])
const [listColumns, setListColumns] = useState<IColumn[]>(() => [
{
key: 'Name',
name: 'Name',
fieldName: 'Name',
minWidth: 360,
isRowHeader: true,
isResizable: true,
isSorted: false,
isSortedDescending: false,
data: 'string',
onColumnClick: (_, column) => onColumnHeaderClick(column)
}
])
const [selectedItems, setSelectedItems] = useState<string[]>([])
const [selection, setSelection] = useState(() => {
const s: Selection<IObjectWithKey> = new Selection({
onSelectionChanged: () => {
setSelectedItems(s.getSelection().map(item => item.key as string))
setSelection(s)
forceUpdate()
}
})
s.setItems(filteredTestCases, true)
return s
})
const [runAllClicked, setRunAllClicked] = useState(false)
const [runSelectedClicked, setRunSelectedClicked] = useState(false)
const [hideDialog, { toggle: toggleHideDialog }] = useBoolean(true)
const [isUploadingPlaylist, setIsUploadingPlaylist] = useState(false)
const [showSuccess, setShowSuccess] = useState(false)
const [importingErrMsg, setImportingErrMsg] = useState<string | undefined>(undefined)
const [file, setFile] = useState<IFile>()
const onFileUploadSuccess = (files: IFile[]): void => {
if (files.length > 0) {
setFile(files[0])
}
}
const onImportPlaylist = () => {
if (file != null) {
setIsUploadingPlaylist(true)
const reader = new FileReader()
const parser = new DOMParser()
reader.onloadend = (event) => {
const tests: string[] = []
const readerData = event.target?.result?.toString()
const playlistData = parser.parseFromString(readerData ?? '', 'text/xml')
playlistData.querySelectorAll('Add').forEach((i) => {
const selectedKey: string = i.getAttribute('Test')?.toString() ?? ''
if (selectedKey !== '') tests.push(selectedKey)
})
// Disable onSelectionChanged to avoid long rendering time.
selection.setChangeEvents(false, true)
// Select the imported items.
const selectionItems = selection.getItems().map(item => item.key)
tests.forEach(test => { if (selectionItems.includes(test)) selection.setKeySelected(test, true, false); })
// Enable onSelectionChanged.
selection.setChangeEvents(true, false)
// Update selection.
setSelectedItems(selection.getSelection().map(item => item.key as string))
setSelection(selection)
// Update states.
setShowSuccess(true)
setImportingErrMsg(undefined)
setIsUploadingPlaylist(false)
// Force update.
forceUpdate()
}
reader.readAsText(file.File)
} else {
setImportingErrMsg('Playlist file cannot be empty')
}
}
const dialogContentProps = {
type: DialogType.normal,
title: 'Import Playlist'
}
const modalProps = {
isBlocking: true,
styles: { main: { innerWidth: 600, maxWidth: 650 } },
dragOptions: {
moveMenuItemText: 'Move',
closeMenuItemText: 'Close',
menu: ContextualMenu
}
}
const listColumnsRef = useRef<IColumn[]>()
listColumnsRef.current = listColumns
const filteredTestCasesRef = useRef<ListItem[]>()
filteredTestCasesRef.current = filteredTestCases
const allListItems = useMemo(() => getListItems(filterInfo.listSelectedCases), [filterInfo.listSelectedCases])
const forceUpdate = useForceUpdate()
const wizardProps: StepWizardChildProps = props as StepWizardChildProps
const navSteps = getNavSteps(wizardProps, configureMethod)
const wizard = WizardNavBar(wizardProps, navSteps)
const winSize = useWindowSize()
const history = useHistory()
useEffect(() => {
dispatch(ConfigurationsDataSrv.getRules())
dispatch(TestSuitesDataSrv.getTestSuiteTestCases())
}, [dispatch])
useEffect(() => {
if (!isValidFilterPhrase(filterPhrase)) {
setFilteredTestCases(allListItems)
}
}, [filterPhrase, allListItems])
if (testSuiteInfo.selectedTestSuite === undefined || configuration.selectedConfiguration === undefined) {
return <InvalidAppStateNotification
testSuite={testSuiteInfo.selectedTestSuite}
configuration={configuration.selectedConfiguration}
wizard={wizard}
wizardProps={wizardProps} />
}
const onColumnHeaderClick = useCallback((column: IColumn) => {
const currColumn: IColumn = listColumnsRef.current!.filter(currCol => column.key === currCol.key)[0]
const newColumns = listColumnsRef.current!.map((newCol: IColumn) => {
if (newCol.key === currColumn.key) {
return {
...currColumn,
isSorted: true,
isSortedDescending: !currColumn.isSortedDescending
}
} else {
return {
...newCol,
isSorted: false,
isSortedDescending: true
}
}
})
const newItems = copyAndSort(filteredTestCasesRef.current!, currColumn.fieldName!, !currColumn.isSortedDescending)
setListColumns(newColumns)
setFilteredTestCases(newItems)
}, [])
const onFilterPhraseChanged = (filterPhrase: string | undefined) => {
setFilterPhrase(filterPhrase)
selection.setAllSelected(false)
setFilteredTestCases(allListItems.filter(filterByDropdownOption.filterFunc(filterPhrase)))
}
const onFilterPhraseClear = () => {
setFilterPhrase(undefined)
selection.setAllSelected(false)
setFilteredTestCases(allListItems)
}
const onRunAllCasesClick = () => {
if (filterInfo.listSelectedCases.length === 0) {
return
}
setRunAllClicked(true)
dispatch(SelectedTestCasesDataSrv.createRunRequest(filterInfo.listSelectedCases.map(e => e.FullName), undefined, () => {
history.push('/Tasks/History', { from: 'RunSelectedCase' })
}))
}
const getRunAllButtonText = () => {
if (runAllClicked && selectedTestCases.isPosting) {
return 'Processing...'
} else {
return 'Run all cases'
}
}
const onRunSelectedCasesClick = () => {
if (selectedItems.length === 0) {
return
}
setRunSelectedClicked(true)
dispatch(SelectedTestCasesDataSrv.createRunRequest(selectedItems, undefined, () => {
history.push('/Tasks/History', { from: 'RunSelectedCase' })
}))
}
const getRunSelectedButtonText = () => {
if (runSelectedClicked && selectedTestCases.isPosting) {
return 'Processing...'
} else {
return `Run selected cases (${selectedItems.length}/${filterInfo.listSelectedCases.length})`
}
}
const onShowImportDialog = () => {
setImportingErrMsg(undefined)
setIsUploadingPlaylist(false)
setShowSuccess(false)
toggleHideDialog()
setFile(undefined)
}
const exportTestCases = () => {
if (filterInfo.listSelectedCases.length === 0) {
return
}
exportPlaylist(filterInfo.listSelectedCases.map(e => e.FullName))
}
const exportCheckedTestCases = () => {
if (selectedItems.length === 0) {
return
}
exportPlaylist(selectedItems)
}
const getMenuItems = (): ContextualMenuItemProps[] => {
return [
{
key: 'ExportAll',
text: 'Export All Test Cases to Playlist',
disabled: filterInfo.listSelectedCases.length === 0,
menuAction: exportTestCases
},
{
key: 'ExportSelected',
text: 'Export Selected Test Cases to Playlist',
disabled: selectedItems.length === 0,
menuAction: exportCheckedTestCases
},
{
key: 'Import',
text: 'Import Playlist...',
disabled: false,
menuAction: onShowImportDialog
}
]
}
return (
<StepPanel leftNav={wizard} isLoading={filterInfo.isCasesLoading} errorMsg={filterInfo.errorMsg ?? selectedTestCases.errorMsg}>
<Stack style={{ paddingLeft: 10 }}>
<Fabric>
<Stack horizontal tokens={StackGap10}>
<FilterByDropdown
options={filterByDropdownOptions}
onOptionChange={(newValue) => setFilterByDropdownOption(newValue)} />
<SearchBox
style={{ width: 280 }}
placeholder={filterByDropdownOption.filterPlaceholder}
onChange={(_, newValue) => onFilterPhraseChanged(newValue)}
onReset={onFilterPhraseClear}
/>
{
!isValidFilterPhrase(filterPhrase)
? null
: <Label>{`Number of test cases after filter applied: ${filteredTestCases.length}`}</Label>
}
</Stack>
<hr style={{ border: '1px solid #d9d9d9' }} />
<div style={{ height: winSize.height - 170, overflowY: 'auto' }}>
<MarqueeSelection selection={selection}>
<DetailsList
items={filteredTestCases}
setKey="set"
columns={listColumns}
layoutMode={DetailsListLayoutMode.justified}
selection={selection}
selectionPreservedOnEmptyClick={true}
compact
/>
</MarqueeSelection>
</div>
</Fabric>
<div className='buttonPanel'>
<Stack horizontal horizontalAlign='end' tokens={StackGap10}>
<PrimaryButton text={getRunAllButtonText()} disabled={selectedTestCases.isPosting || filterInfo.listSelectedCases.length === 0} onClick={onRunAllCasesClick} />
<PrimaryButton style={{ width: 240 }} text={getRunSelectedButtonText()} disabled={selectedTestCases.isPosting || selectedItems.length === 0} onClick={onRunSelectedCasesClick} />
<ContextualMenuControl text="Import/Export Playlist" shouldFocusOnMount={true} menuItems={getMenuItems()} />
<PrimaryButton text='Previous' disabled={selectedTestCases.isPosting} onClick={() => wizardProps.previousStep()} />
</Stack>
</div>
</Stack>
<Dialog
hidden={hideDialog}
onDismiss={toggleHideDialog}
dialogContentProps={dialogContentProps}
modalProps={modalProps}
>
{
showSuccess
? <div>Import playlist successfully!</div>
: <Stack tokens={StackGap10}>
<p style={{ color: 'red', padding: 3 }}>{importingErrMsg}</p>
<FileUploader
label="Package"
onSuccess={onFileUploadSuccess}
maxFileCount={1}
disabled={isUploadingPlaylist}
suffix={['.playlist']}
placeholder="Select .playlist file"
/>
</Stack>
}
<DialogFooter>
{!showSuccess &&
<PrimaryButton onClick={onImportPlaylist} text={isUploadingPlaylist ? 'Uploading...' : 'Import Playlist'} disabled={isUploadingPlaylist} />}
<DefaultButton onClick={toggleHideDialog} text="Close" disabled={isUploadingPlaylist} />
</DialogFooter>
</Dialog>
</StepPanel>
)
}; | the_stack |
import {Timeline} from '@luma.gl/core';
import {LIFECYCLE} from '../lifecycle/constants';
import log from '../utils/log';
import debug from '../debug';
import {flatten} from '../utils/flatten';
import {Stats} from '@probe.gl/stats';
import ResourceManager from './resource/resource-manager';
import Viewport from '../viewports/viewport';
import {createProgramManager} from '../shaderlib';
import type Layer from './layer';
import type CompositeLayer from './composite-layer';
import type Deck from './deck';
import type {ProgramManager} from '@luma.gl/engine';
const TRACE_SET_LAYERS = 'layerManager.setLayers';
const TRACE_ACTIVATE_VIEWPORT = 'layerManager.activateViewport';
export type LayerContext = {
layerManager: LayerManager;
resourceManager: ResourceManager;
deck?: Deck;
gl: WebGLRenderingContext;
programManager: ProgramManager;
stats: Stats;
viewport: Viewport;
timeline: Timeline;
mousePosition: [number, number] | null;
userData: any;
onError?: (error: Error, source: Layer) => void;
};
export type LayersList = (Layer | undefined | false | null | LayersList)[];
export default class LayerManager {
layers: Layer[];
context: LayerContext;
resourceManager: ResourceManager;
private _lastRenderedLayers: LayersList = [];
private _needsRedraw: string | false = false;
private _needsUpdate: string | false = false;
private _nextLayers: LayersList | null = null;
private _debug: boolean = false;
// eslint-disable-next-line
constructor(
gl,
{
deck,
stats,
viewport,
timeline
}: {
deck?: Deck;
stats?: Stats;
viewport?: Viewport;
timeline?: Timeline;
} = {}
) {
// Currently deck.gl expects the DeckGL.layers array to be different
// whenever React rerenders. If the same layers array is used, the
// LayerManager's diffing algorithm will generate a fatal error and
// break the rendering.
// `this._lastRenderedLayers` stores the UNFILTERED layers sent
// down to LayerManager, so that `layers` reference can be compared.
// If it's the same across two React render calls, the diffing logic
// will be skipped.
this.layers = [];
this.resourceManager = new ResourceManager({gl, protocol: 'deck://'});
this.context = {
mousePosition: null,
userData: {},
layerManager: this,
gl,
deck,
// Enabling luma.gl Program caching using private API (_cachePrograms)
programManager: gl && createProgramManager(gl),
stats: stats || new Stats({id: 'deck.gl'}),
// Make sure context.viewport is not empty on the first layer initialization
viewport: viewport || new Viewport({id: 'DEFAULT-INITIAL-VIEWPORT'}), // Current viewport, exposed to layers for project* function
timeline: timeline || new Timeline(),
resourceManager: this.resourceManager,
onError: undefined
};
Object.seal(this);
}
/** Method to call when the layer manager is not needed anymore. */
finalize() {
this.resourceManager.finalize();
// Finalize all layers
for (const layer of this.layers) {
this._finalizeLayer(layer);
}
}
/** Check if a redraw is needed */
needsRedraw(
opts: {
/** Reset redraw flags to false after the call */
clearRedrawFlags: boolean;
} = {clearRedrawFlags: false}
): string | false {
let redraw = this._needsRedraw;
if (opts.clearRedrawFlags) {
this._needsRedraw = false;
}
// This layers list doesn't include sublayers, relying on composite layers
for (const layer of this.layers) {
// Call every layer to clear their flags
const layerNeedsRedraw = layer.getNeedsRedraw(opts);
redraw = redraw || layerNeedsRedraw;
}
return redraw;
}
/** Check if a deep update of all layers is needed */
needsUpdate(): string | false {
if (this._nextLayers && this._nextLayers !== this._lastRenderedLayers) {
// New layers array may be the same as the old one if `setProps` is called by React
return 'layers changed';
}
return this._needsUpdate;
}
/** Layers will be redrawn (in next animation frame) */
setNeedsRedraw(reason: string): void {
this._needsRedraw = this._needsRedraw || reason;
}
/** Layers will be updated deeply (in next animation frame)
Potentially regenerating attributes and sub layers */
setNeedsUpdate(reason: string): void {
this._needsUpdate = this._needsUpdate || reason;
}
/** Gets a list of currently rendered layers. Optionally filter by id. */
getLayers({layerIds}: {layerIds?: string[]} = {}): Layer[] {
// Filtering by layerId compares beginning of strings, so that sublayers will be included
// Dependes on the convention of adding suffixes to the parent's layer name
return layerIds
? this.layers.filter(layer => layerIds.find(layerId => layer.id.indexOf(layerId) === 0))
: this.layers;
}
/** Set props needed for layer rendering and picking. */
setProps(props: any): void {
if ('debug' in props) {
this._debug = props.debug;
}
// A way for apps to add data to context that can be accessed in layers
if ('userData' in props) {
this.context.userData = props.userData;
}
// New layers will be processed in `updateLayers` in the next update cycle
if ('layers' in props) {
this._nextLayers = props.layers;
}
if ('onError' in props) {
this.context.onError = props.onError;
}
}
/** Supply a new layer list, initiating sublayer generation and layer matching */
setLayers(newLayers: LayersList, reason?: string): void {
debug(TRACE_SET_LAYERS, this, reason, newLayers);
this._lastRenderedLayers = newLayers;
const flatLayers = flatten(newLayers, Boolean) as Layer[];
for (const layer of flatLayers) {
layer.context = this.context;
}
this._updateLayers(this.layers, flatLayers);
}
/** Update layers from last cycle if `setNeedsUpdate()` has been called */
updateLayers(): void {
// NOTE: For now, even if only some layer has changed, we update all layers
// to ensure that layer id maps etc remain consistent even if different
// sublayers are rendered
const reason = this.needsUpdate();
if (reason) {
this.setNeedsRedraw(`updating layers: ${reason}`);
// Force a full update
this.setLayers(this._nextLayers || this._lastRenderedLayers, reason);
}
// Updated, clear the backlog
this._nextLayers = null;
}
//
// INTERNAL METHODS
//
/** Make a viewport "current" in layer context, updating viewportChanged flags */
activateViewport = (viewport: Viewport) => {
debug(TRACE_ACTIVATE_VIEWPORT, this, viewport);
if (viewport) {
this.context.viewport = viewport;
}
};
private _handleError(stage: string, error: Error, layer: Layer) {
layer.raiseError(error, `${stage} of ${layer}`);
}
// TODO - mark layers with exceptions as bad and remove from rendering cycle?
/** Match all layers, checking for caught errors
to avoid having an exception in one layer disrupt other layers */
private _updateLayers(oldLayers: Layer[], newLayers: Layer[]): void {
// Create old layer map
const oldLayerMap: {[layerId: string]: Layer | null} = {};
for (const oldLayer of oldLayers) {
if (oldLayerMap[oldLayer.id]) {
log.warn(`Multiple old layers with same id ${oldLayer.id}`)();
} else {
oldLayerMap[oldLayer.id] = oldLayer;
}
}
// Allocate array for generated layers
const generatedLayers: Layer[] = [];
// Match sublayers
this._updateSublayersRecursively(newLayers, oldLayerMap, generatedLayers);
// Finalize unmatched layers
this._finalizeOldLayers(oldLayerMap);
let needsUpdate: string | false = false;
for (const layer of generatedLayers) {
if (layer.hasUniformTransition()) {
needsUpdate = `Uniform transition in ${layer}`;
break;
}
}
this._needsUpdate = needsUpdate;
this.layers = generatedLayers;
}
/* eslint-disable complexity,max-statements */
// Note: adds generated layers to `generatedLayers` array parameter
private _updateSublayersRecursively(
newLayers: Layer[],
oldLayerMap: {[layerId: string]: Layer | null},
generatedLayers: Layer[]
) {
for (const newLayer of newLayers) {
newLayer.context = this.context;
// Given a new coming layer, find its matching old layer (if any)
const oldLayer = oldLayerMap[newLayer.id];
if (oldLayer === null) {
// null, rather than undefined, means this id was originally there
log.warn(`Multiple new layers with same id ${newLayer.id}`)();
}
// Remove the old layer from candidates, as it has been matched with this layer
oldLayerMap[newLayer.id] = null;
let sublayers: Layer[] | null = null;
// We must not generate exceptions until after layer matching is complete
try {
if (this._debug && oldLayer !== newLayer) {
newLayer.validateProps();
}
if (!oldLayer) {
this._initializeLayer(newLayer);
} else {
this._transferLayerState(oldLayer, newLayer);
this._updateLayer(newLayer);
}
generatedLayers.push(newLayer);
// Call layer lifecycle method: render sublayers
sublayers = newLayer.isComposite ? (newLayer as CompositeLayer).getSubLayers() : null;
// End layer lifecycle method: render sublayers
} catch (err) {
this._handleError('matching', err as Error, newLayer); // Record first exception
}
if (sublayers) {
this._updateSublayersRecursively(sublayers, oldLayerMap, generatedLayers);
}
}
}
/* eslint-enable complexity,max-statements */
// Finalize any old layers that were not matched
private _finalizeOldLayers(oldLayerMap: {[layerId: string]: Layer | null}): void {
for (const layerId in oldLayerMap) {
const layer = oldLayerMap[layerId];
if (layer) {
this._finalizeLayer(layer);
}
}
}
// / EXCEPTION SAFE LAYER ACCESS
/** Safely initializes a single layer, calling layer methods */
private _initializeLayer(layer: Layer): void {
try {
layer._initialize();
layer.lifecycle = LIFECYCLE.INITIALIZED;
} catch (err) {
this._handleError('initialization', err as Error, layer);
// TODO - what should the lifecycle state be here? LIFECYCLE.INITIALIZATION_FAILED?
}
}
/** Transfer state from one layer to a newer version */
private _transferLayerState(oldLayer: Layer, newLayer: Layer): void {
newLayer._transferState(oldLayer);
newLayer.lifecycle = LIFECYCLE.MATCHED;
if (newLayer !== oldLayer) {
oldLayer.lifecycle = LIFECYCLE.AWAITING_GC;
}
}
/** Safely updates a single layer, cleaning all flags */
private _updateLayer(layer: Layer): void {
try {
layer._update();
} catch (err) {
this._handleError('update', err as Error, layer);
}
}
/** Safely finalizes a single layer, removing all resources */
private _finalizeLayer(layer: Layer): void {
this._needsRedraw = this._needsRedraw || `finalized ${layer}`;
layer.lifecycle = LIFECYCLE.AWAITING_FINALIZATION;
try {
layer._finalize();
layer.lifecycle = LIFECYCLE.FINALIZED;
} catch (err) {
this._handleError('finalization', err as Error, layer);
}
}
} | the_stack |
import Card from '@material-ui/core/Card'
import CardContent from '@material-ui/core/CardContent'
import CardHeader from '@material-ui/core/CardHeader'
import Grid from '@material-ui/core/Grid'
import InputLabel from '@material-ui/core/InputLabel'
import MenuItem from '@material-ui/core/MenuItem'
import Select, { SelectProps } from '@material-ui/core/Select'
import { makeStyles } from '@material-ui/core/styles'
import * as React from 'react'
import * as api from '../api'
import { DistributedGraph, GpuInfo, Graph } from '../api'
import { firstOrUndefined } from '../utils'
import { ColumnChart } from './charts/ColumnChart'
import { TableChart } from './charts/TableChart'
import { DataLoading } from './DataLoading'
import { GpuInfoTable } from './GpuInfoTable'
import { makeChartHeaderRenderer, useTooltipCommonStyles } from './helpers'
import {
DistributedCommopsTableTooltip,
DistributedGpuInfoTableTooltip,
DistributedOverlapGraphTooltip,
DistributedWaittimeGraphTooltip
} from './TooltipDescriptions'
export interface IProps {
run: string
worker: string
span: string
}
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1
},
verticalInput: {
display: 'flex',
alignItems: 'center'
},
inputWidth: {
width: '4em'
},
inputWidthOverflow: {
minWidth: '15em',
whiteSpace: 'nowrap'
},
description: {
marginLeft: theme.spacing(1)
}
}))
export const DistributedView: React.FC<IProps> = (props) => {
const tooltipCommonClasses = useTooltipCommonStyles()
const chartHeaderRenderer = React.useMemo(
() => makeChartHeaderRenderer(tooltipCommonClasses),
[tooltipCommonClasses]
)
let { run, worker, span } = props
const classes = useStyles()
const [overlapGraph, setOverlapGraph] = React.useState<
DistributedGraph | undefined
>(undefined)
const [waittimeGraph, setWaittimeGraph] = React.useState<
DistributedGraph | undefined
>(undefined)
const [commopsTableData, setCommopsTableData] = React.useState<
any | undefined
>(undefined)
const [gpuInfo, setGpuInfo] = React.useState<GpuInfo | undefined>(undefined)
const [commopsTableTitle, setCommopsTableTitle] = React.useState('')
const [commopsWorkers, setCommopsWorkers] = React.useState<string[]>([])
const [overlapSteps, setOverlapSteps] = React.useState<string[]>([])
const [waittimeSteps, setWaittimeSteps] = React.useState<string[]>([])
const [overlapStep, setOverlapStep] = React.useState('')
const [waittimeStep, setWaittimeStep] = React.useState('')
const [commopsWorker, setCommopsWorker] = React.useState('')
React.useEffect(() => {
if (waittimeSteps.includes('all')) {
setWaittimeStep('all')
} else {
setWaittimeStep(firstOrUndefined(waittimeSteps) ?? '')
}
}, [waittimeSteps])
React.useEffect(() => {
if (overlapSteps.includes('all')) {
setOverlapStep('all')
} else {
setOverlapStep(firstOrUndefined(overlapSteps) ?? '')
}
}, [overlapSteps])
React.useEffect(() => {
setCommopsWorker(firstOrUndefined(commopsWorkers) ?? '')
}, [commopsWorkers])
React.useEffect(() => {
api.defaultApi.distributedOverlapGet(run, 'All', span).then((resp) => {
setOverlapGraph(resp)
setOverlapSteps(Object.keys(resp.data))
})
api.defaultApi.distributedWaittimeGet(run, 'All', span).then((resp) => {
setWaittimeGraph(resp)
setWaittimeSteps(Object.keys(resp.data))
})
api.defaultApi.distributedCommopsGet(run, 'All', span).then((resp) => {
setCommopsTableData(resp.data)
setCommopsWorkers(Object.keys(resp.data))
setCommopsTableTitle(resp.metadata.title)
})
api.defaultApi.distributedGpuinfoGet(run, 'All', span).then((resp) => {
setGpuInfo(resp)
})
}, [run, worker, span])
const onCommopsWorkerChanged: SelectProps['onChange'] = (event) => {
setCommopsWorker(event.target.value as string)
}
const onOverlapStepChanged: SelectProps['onChange'] = (event) => {
setOverlapStep(event.target.value as string)
}
const onWaittimeStepChanged: SelectProps['onChange'] = (event) => {
setWaittimeStep(event.target.value as string)
}
const getColumnChartData = (
distributedGraph?: DistributedGraph,
step?: string
) => {
if (!distributedGraph || !step) return undefined
const barLabels = Object.keys(distributedGraph.data[step])
return {
legends: distributedGraph.metadata.legends,
barLabels,
barHeights: barLabels.map((label) => distributedGraph.data[step][label])
}
}
const overlapData = React.useMemo(
() => getColumnChartData(overlapGraph, overlapStep),
[overlapGraph, overlapStep]
)
const waittimeData = React.useMemo(
() => getColumnChartData(waittimeGraph, waittimeStep),
[waittimeGraph, waittimeStep]
)
const getTableData = (tableData?: any, worker?: string) => {
if (!tableData || !worker) return undefined
return tableData[worker] as Graph
}
const commopsTable = getTableData(commopsTableData, commopsWorker)
return (
<div className={classes.root}>
<Card variant="outlined">
<CardHeader title="Distributed View" />
<CardContent>
<Grid container spacing={1}>
{gpuInfo && (
<Grid item sm={12}>
<Card elevation={0}>
<CardHeader
title={chartHeaderRenderer(
gpuInfo.metadata.title,
DistributedGpuInfoTableTooltip
)}
/>
<CardContent>
<GpuInfoTable gpuInfo={gpuInfo} />
</CardContent>
</Card>
</Grid>
)}
<Grid item sm={6}>
<DataLoading value={overlapData}>
{(chartData) => (
<Card elevation={0}>
<CardContent>
<Grid container spacing={1} alignItems="center">
<Grid item>
<InputLabel id="overlap-step">Step</InputLabel>
</Grid>
<Grid item>
<Select
labelId="overlap-step"
value={overlapStep}
onChange={onOverlapStepChanged}
>
{overlapSteps.map((step) => (
<MenuItem value={step}>{step}</MenuItem>
))}
</Select>
</Grid>
</Grid>
</CardContent>
{overlapGraph?.metadata?.title && (
<CardHeader
title={chartHeaderRenderer(
overlapGraph?.metadata?.title,
DistributedOverlapGraphTooltip
)}
/>
)}
<ColumnChart
units={overlapGraph?.metadata?.units}
chartData={chartData}
/>
</Card>
)}
</DataLoading>
</Grid>
<Grid item sm={6}>
<DataLoading value={waittimeData}>
{(chartData) => (
<Card elevation={0}>
<CardContent>
<Grid container spacing={1} alignItems="center">
<Grid item>
<InputLabel id="waittime-step">Step</InputLabel>
</Grid>
<Grid item>
<Select
labelId="waittime-step"
value={waittimeStep}
onChange={onWaittimeStepChanged}
>
{waittimeSteps.map((step) => (
<MenuItem value={step}>{step}</MenuItem>
))}
</Select>
</Grid>
</Grid>
</CardContent>
{waittimeGraph?.metadata?.title && (
<CardHeader
title={chartHeaderRenderer(
waittimeGraph?.metadata?.title,
DistributedWaittimeGraphTooltip
)}
/>
)}
<ColumnChart
units={waittimeGraph?.metadata?.units}
colors={['#0099C6', '#DD4477', '#66AA00', '#B82E2E']}
chartData={chartData}
/>
</Card>
)}
</DataLoading>
</Grid>
<Grid item sm={12}>
<Grid container direction="column" spacing={0}>
<CardHeader
title={chartHeaderRenderer(
commopsTableTitle,
DistributedCommopsTableTooltip
)}
/>
<Card elevation={0}>
<CardContent>
<Grid item container spacing={1} alignItems="center">
<Grid item>
<InputLabel id="table-worker">Worker</InputLabel>
</Grid>
<Grid item>
<Select
labelId="table-worker"
value={commopsWorker}
onChange={onCommopsWorkerChanged}
>
{commopsWorkers.map((worker) => (
<MenuItem value={worker}>{worker}</MenuItem>
))}
</Select>
</Grid>
</Grid>
</CardContent>
</Card>
<Grid item>
<DataLoading value={commopsTable}>
{(graph) => <TableChart graph={graph} />}
</DataLoading>
</Grid>
</Grid>
</Grid>
</Grid>
</CardContent>
</Card>
</div>
)
} | the_stack |
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types";
import {
AcceptInvitationCommand,
AcceptInvitationCommandInput,
AcceptInvitationCommandOutput,
} from "./commands/AcceptInvitationCommand";
import {
ArchiveFindingsCommand,
ArchiveFindingsCommandInput,
ArchiveFindingsCommandOutput,
} from "./commands/ArchiveFindingsCommand";
import {
CreateDetectorCommand,
CreateDetectorCommandInput,
CreateDetectorCommandOutput,
} from "./commands/CreateDetectorCommand";
import {
CreateFilterCommand,
CreateFilterCommandInput,
CreateFilterCommandOutput,
} from "./commands/CreateFilterCommand";
import { CreateIPSetCommand, CreateIPSetCommandInput, CreateIPSetCommandOutput } from "./commands/CreateIPSetCommand";
import {
CreateMembersCommand,
CreateMembersCommandInput,
CreateMembersCommandOutput,
} from "./commands/CreateMembersCommand";
import {
CreatePublishingDestinationCommand,
CreatePublishingDestinationCommandInput,
CreatePublishingDestinationCommandOutput,
} from "./commands/CreatePublishingDestinationCommand";
import {
CreateSampleFindingsCommand,
CreateSampleFindingsCommandInput,
CreateSampleFindingsCommandOutput,
} from "./commands/CreateSampleFindingsCommand";
import {
CreateThreatIntelSetCommand,
CreateThreatIntelSetCommandInput,
CreateThreatIntelSetCommandOutput,
} from "./commands/CreateThreatIntelSetCommand";
import {
DeclineInvitationsCommand,
DeclineInvitationsCommandInput,
DeclineInvitationsCommandOutput,
} from "./commands/DeclineInvitationsCommand";
import {
DeleteDetectorCommand,
DeleteDetectorCommandInput,
DeleteDetectorCommandOutput,
} from "./commands/DeleteDetectorCommand";
import {
DeleteFilterCommand,
DeleteFilterCommandInput,
DeleteFilterCommandOutput,
} from "./commands/DeleteFilterCommand";
import {
DeleteInvitationsCommand,
DeleteInvitationsCommandInput,
DeleteInvitationsCommandOutput,
} from "./commands/DeleteInvitationsCommand";
import { DeleteIPSetCommand, DeleteIPSetCommandInput, DeleteIPSetCommandOutput } from "./commands/DeleteIPSetCommand";
import {
DeleteMembersCommand,
DeleteMembersCommandInput,
DeleteMembersCommandOutput,
} from "./commands/DeleteMembersCommand";
import {
DeletePublishingDestinationCommand,
DeletePublishingDestinationCommandInput,
DeletePublishingDestinationCommandOutput,
} from "./commands/DeletePublishingDestinationCommand";
import {
DeleteThreatIntelSetCommand,
DeleteThreatIntelSetCommandInput,
DeleteThreatIntelSetCommandOutput,
} from "./commands/DeleteThreatIntelSetCommand";
import {
DescribeOrganizationConfigurationCommand,
DescribeOrganizationConfigurationCommandInput,
DescribeOrganizationConfigurationCommandOutput,
} from "./commands/DescribeOrganizationConfigurationCommand";
import {
DescribePublishingDestinationCommand,
DescribePublishingDestinationCommandInput,
DescribePublishingDestinationCommandOutput,
} from "./commands/DescribePublishingDestinationCommand";
import {
DisableOrganizationAdminAccountCommand,
DisableOrganizationAdminAccountCommandInput,
DisableOrganizationAdminAccountCommandOutput,
} from "./commands/DisableOrganizationAdminAccountCommand";
import {
DisassociateFromMasterAccountCommand,
DisassociateFromMasterAccountCommandInput,
DisassociateFromMasterAccountCommandOutput,
} from "./commands/DisassociateFromMasterAccountCommand";
import {
DisassociateMembersCommand,
DisassociateMembersCommandInput,
DisassociateMembersCommandOutput,
} from "./commands/DisassociateMembersCommand";
import {
EnableOrganizationAdminAccountCommand,
EnableOrganizationAdminAccountCommandInput,
EnableOrganizationAdminAccountCommandOutput,
} from "./commands/EnableOrganizationAdminAccountCommand";
import { GetDetectorCommand, GetDetectorCommandInput, GetDetectorCommandOutput } from "./commands/GetDetectorCommand";
import { GetFilterCommand, GetFilterCommandInput, GetFilterCommandOutput } from "./commands/GetFilterCommand";
import { GetFindingsCommand, GetFindingsCommandInput, GetFindingsCommandOutput } from "./commands/GetFindingsCommand";
import {
GetFindingsStatisticsCommand,
GetFindingsStatisticsCommandInput,
GetFindingsStatisticsCommandOutput,
} from "./commands/GetFindingsStatisticsCommand";
import {
GetInvitationsCountCommand,
GetInvitationsCountCommandInput,
GetInvitationsCountCommandOutput,
} from "./commands/GetInvitationsCountCommand";
import { GetIPSetCommand, GetIPSetCommandInput, GetIPSetCommandOutput } from "./commands/GetIPSetCommand";
import {
GetMasterAccountCommand,
GetMasterAccountCommandInput,
GetMasterAccountCommandOutput,
} from "./commands/GetMasterAccountCommand";
import {
GetMemberDetectorsCommand,
GetMemberDetectorsCommandInput,
GetMemberDetectorsCommandOutput,
} from "./commands/GetMemberDetectorsCommand";
import { GetMembersCommand, GetMembersCommandInput, GetMembersCommandOutput } from "./commands/GetMembersCommand";
import {
GetThreatIntelSetCommand,
GetThreatIntelSetCommandInput,
GetThreatIntelSetCommandOutput,
} from "./commands/GetThreatIntelSetCommand";
import {
GetUsageStatisticsCommand,
GetUsageStatisticsCommandInput,
GetUsageStatisticsCommandOutput,
} from "./commands/GetUsageStatisticsCommand";
import {
InviteMembersCommand,
InviteMembersCommandInput,
InviteMembersCommandOutput,
} from "./commands/InviteMembersCommand";
import {
ListDetectorsCommand,
ListDetectorsCommandInput,
ListDetectorsCommandOutput,
} from "./commands/ListDetectorsCommand";
import { ListFiltersCommand, ListFiltersCommandInput, ListFiltersCommandOutput } from "./commands/ListFiltersCommand";
import {
ListFindingsCommand,
ListFindingsCommandInput,
ListFindingsCommandOutput,
} from "./commands/ListFindingsCommand";
import {
ListInvitationsCommand,
ListInvitationsCommandInput,
ListInvitationsCommandOutput,
} from "./commands/ListInvitationsCommand";
import { ListIPSetsCommand, ListIPSetsCommandInput, ListIPSetsCommandOutput } from "./commands/ListIPSetsCommand";
import { ListMembersCommand, ListMembersCommandInput, ListMembersCommandOutput } from "./commands/ListMembersCommand";
import {
ListOrganizationAdminAccountsCommand,
ListOrganizationAdminAccountsCommandInput,
ListOrganizationAdminAccountsCommandOutput,
} from "./commands/ListOrganizationAdminAccountsCommand";
import {
ListPublishingDestinationsCommand,
ListPublishingDestinationsCommandInput,
ListPublishingDestinationsCommandOutput,
} from "./commands/ListPublishingDestinationsCommand";
import {
ListTagsForResourceCommand,
ListTagsForResourceCommandInput,
ListTagsForResourceCommandOutput,
} from "./commands/ListTagsForResourceCommand";
import {
ListThreatIntelSetsCommand,
ListThreatIntelSetsCommandInput,
ListThreatIntelSetsCommandOutput,
} from "./commands/ListThreatIntelSetsCommand";
import {
StartMonitoringMembersCommand,
StartMonitoringMembersCommandInput,
StartMonitoringMembersCommandOutput,
} from "./commands/StartMonitoringMembersCommand";
import {
StopMonitoringMembersCommand,
StopMonitoringMembersCommandInput,
StopMonitoringMembersCommandOutput,
} from "./commands/StopMonitoringMembersCommand";
import { TagResourceCommand, TagResourceCommandInput, TagResourceCommandOutput } from "./commands/TagResourceCommand";
import {
UnarchiveFindingsCommand,
UnarchiveFindingsCommandInput,
UnarchiveFindingsCommandOutput,
} from "./commands/UnarchiveFindingsCommand";
import {
UntagResourceCommand,
UntagResourceCommandInput,
UntagResourceCommandOutput,
} from "./commands/UntagResourceCommand";
import {
UpdateDetectorCommand,
UpdateDetectorCommandInput,
UpdateDetectorCommandOutput,
} from "./commands/UpdateDetectorCommand";
import {
UpdateFilterCommand,
UpdateFilterCommandInput,
UpdateFilterCommandOutput,
} from "./commands/UpdateFilterCommand";
import {
UpdateFindingsFeedbackCommand,
UpdateFindingsFeedbackCommandInput,
UpdateFindingsFeedbackCommandOutput,
} from "./commands/UpdateFindingsFeedbackCommand";
import { UpdateIPSetCommand, UpdateIPSetCommandInput, UpdateIPSetCommandOutput } from "./commands/UpdateIPSetCommand";
import {
UpdateMemberDetectorsCommand,
UpdateMemberDetectorsCommandInput,
UpdateMemberDetectorsCommandOutput,
} from "./commands/UpdateMemberDetectorsCommand";
import {
UpdateOrganizationConfigurationCommand,
UpdateOrganizationConfigurationCommandInput,
UpdateOrganizationConfigurationCommandOutput,
} from "./commands/UpdateOrganizationConfigurationCommand";
import {
UpdatePublishingDestinationCommand,
UpdatePublishingDestinationCommandInput,
UpdatePublishingDestinationCommandOutput,
} from "./commands/UpdatePublishingDestinationCommand";
import {
UpdateThreatIntelSetCommand,
UpdateThreatIntelSetCommandInput,
UpdateThreatIntelSetCommandOutput,
} from "./commands/UpdateThreatIntelSetCommand";
import { GuardDutyClient } from "./GuardDutyClient";
/**
* <p>Amazon GuardDuty is a continuous security monitoring service that analyzes and processes
* the following data sources: VPC Flow Logs, AWS CloudTrail event logs, and DNS logs. It uses
* threat intelligence feeds (such as lists of malicious IPs and domains) and machine learning to
* identify unexpected, potentially unauthorized, and malicious activity within your AWS
* environment. This can include issues like escalations of privileges, uses of exposed
* credentials, or communication with malicious IPs, URLs, or domains. For example, GuardDuty can
* detect compromised EC2 instances that serve malware or mine bitcoin. </p>
* <p>GuardDuty also monitors AWS account access behavior for signs of compromise. Some examples
* of this are unauthorized infrastructure deployments such as EC2 instances deployed in a Region
* that has never been used, or unusual API calls like a password policy change to reduce
* password strength. </p>
* <p>GuardDuty informs you of the status of your AWS environment by producing security findings
* that you can view in the GuardDuty console or through Amazon CloudWatch events. For more
* information, see the <i>
* <a href="https://docs.aws.amazon.com/guardduty/latest/ug/what-is-guardduty.html">Amazon
* GuardDuty User Guide</a>
* </i>. </p>
*/
export class GuardDuty extends GuardDutyClient {
/**
* <p>Accepts the invitation to be monitored by a GuardDuty administrator account.</p>
*/
public acceptInvitation(
args: AcceptInvitationCommandInput,
options?: __HttpHandlerOptions
): Promise<AcceptInvitationCommandOutput>;
public acceptInvitation(
args: AcceptInvitationCommandInput,
cb: (err: any, data?: AcceptInvitationCommandOutput) => void
): void;
public acceptInvitation(
args: AcceptInvitationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: AcceptInvitationCommandOutput) => void
): void;
public acceptInvitation(
args: AcceptInvitationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: AcceptInvitationCommandOutput) => void),
cb?: (err: any, data?: AcceptInvitationCommandOutput) => void
): Promise<AcceptInvitationCommandOutput> | void {
const command = new AcceptInvitationCommand(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>Archives GuardDuty findings that are specified by the list of finding IDs.</p>
* <note>
* <p>Only the administrator account can archive findings. Member accounts don't have permission to
* archive findings from their accounts.</p>
* </note>
*/
public archiveFindings(
args: ArchiveFindingsCommandInput,
options?: __HttpHandlerOptions
): Promise<ArchiveFindingsCommandOutput>;
public archiveFindings(
args: ArchiveFindingsCommandInput,
cb: (err: any, data?: ArchiveFindingsCommandOutput) => void
): void;
public archiveFindings(
args: ArchiveFindingsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ArchiveFindingsCommandOutput) => void
): void;
public archiveFindings(
args: ArchiveFindingsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ArchiveFindingsCommandOutput) => void),
cb?: (err: any, data?: ArchiveFindingsCommandOutput) => void
): Promise<ArchiveFindingsCommandOutput> | void {
const command = new ArchiveFindingsCommand(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 single Amazon GuardDuty detector. A detector is a resource that represents the
* GuardDuty service. To start using GuardDuty, you must create a detector in each Region where
* you enable the service. You can have only one detector per account per Region. All data
* sources are enabled in a new detector by default.</p>
*/
public createDetector(
args: CreateDetectorCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateDetectorCommandOutput>;
public createDetector(
args: CreateDetectorCommandInput,
cb: (err: any, data?: CreateDetectorCommandOutput) => void
): void;
public createDetector(
args: CreateDetectorCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateDetectorCommandOutput) => void
): void;
public createDetector(
args: CreateDetectorCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateDetectorCommandOutput) => void),
cb?: (err: any, data?: CreateDetectorCommandOutput) => void
): Promise<CreateDetectorCommandOutput> | void {
const command = new CreateDetectorCommand(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 filter using the specified finding criteria.</p>
*/
public createFilter(
args: CreateFilterCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateFilterCommandOutput>;
public createFilter(args: CreateFilterCommandInput, cb: (err: any, data?: CreateFilterCommandOutput) => void): void;
public createFilter(
args: CreateFilterCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateFilterCommandOutput) => void
): void;
public createFilter(
args: CreateFilterCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateFilterCommandOutput) => void),
cb?: (err: any, data?: CreateFilterCommandOutput) => void
): Promise<CreateFilterCommandOutput> | void {
const command = new CreateFilterCommand(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 IPSet, which is called a trusted IP list in the console user interface. An
* IPSet is a list of IP addresses that are trusted for secure communication with AWS
* infrastructure and applications. GuardDuty doesn't generate findings for IP addresses that are
* included in IPSets. Only users from the administrator account can use this operation.</p>
*/
public createIPSet(args: CreateIPSetCommandInput, options?: __HttpHandlerOptions): Promise<CreateIPSetCommandOutput>;
public createIPSet(args: CreateIPSetCommandInput, cb: (err: any, data?: CreateIPSetCommandOutput) => void): void;
public createIPSet(
args: CreateIPSetCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateIPSetCommandOutput) => void
): void;
public createIPSet(
args: CreateIPSetCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateIPSetCommandOutput) => void),
cb?: (err: any, data?: CreateIPSetCommandOutput) => void
): Promise<CreateIPSetCommandOutput> | void {
const command = new CreateIPSetCommand(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 member accounts of the current AWS account by specifying a list of AWS account
* IDs. This step is a prerequisite for managing the associated member accounts either by
* invitation or through an organization.</p>
* <p>When using <code>Create Members</code> as an organizations delegated administrator this
* action will enable GuardDuty in the added member accounts, with the exception of the
* organization delegated administrator account, which must enable GuardDuty prior to being added as a
* member.</p>
* <p>If you are adding accounts by invitation use this action after GuardDuty has been enabled
* in potential member accounts and before using <a href="https://docs.aws.amazon.com/guardduty/latest/APIReference/API_InviteMembers.html">
* <code>Invite
* Members</code>
* </a>.</p>
*/
public createMembers(
args: CreateMembersCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateMembersCommandOutput>;
public createMembers(
args: CreateMembersCommandInput,
cb: (err: any, data?: CreateMembersCommandOutput) => void
): void;
public createMembers(
args: CreateMembersCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateMembersCommandOutput) => void
): void;
public createMembers(
args: CreateMembersCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateMembersCommandOutput) => void),
cb?: (err: any, data?: CreateMembersCommandOutput) => void
): Promise<CreateMembersCommandOutput> | void {
const command = new CreateMembersCommand(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 publishing destination to export findings to. The resource to export findings to
* must exist before you use this operation.</p>
*/
public createPublishingDestination(
args: CreatePublishingDestinationCommandInput,
options?: __HttpHandlerOptions
): Promise<CreatePublishingDestinationCommandOutput>;
public createPublishingDestination(
args: CreatePublishingDestinationCommandInput,
cb: (err: any, data?: CreatePublishingDestinationCommandOutput) => void
): void;
public createPublishingDestination(
args: CreatePublishingDestinationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreatePublishingDestinationCommandOutput) => void
): void;
public createPublishingDestination(
args: CreatePublishingDestinationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreatePublishingDestinationCommandOutput) => void),
cb?: (err: any, data?: CreatePublishingDestinationCommandOutput) => void
): Promise<CreatePublishingDestinationCommandOutput> | void {
const command = new CreatePublishingDestinationCommand(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 example findings of types specified by the list of finding types. If 'NULL' is
* specified for <code>findingTypes</code>, the API generates example findings of all supported
* finding types.</p>
*/
public createSampleFindings(
args: CreateSampleFindingsCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateSampleFindingsCommandOutput>;
public createSampleFindings(
args: CreateSampleFindingsCommandInput,
cb: (err: any, data?: CreateSampleFindingsCommandOutput) => void
): void;
public createSampleFindings(
args: CreateSampleFindingsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateSampleFindingsCommandOutput) => void
): void;
public createSampleFindings(
args: CreateSampleFindingsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateSampleFindingsCommandOutput) => void),
cb?: (err: any, data?: CreateSampleFindingsCommandOutput) => void
): Promise<CreateSampleFindingsCommandOutput> | void {
const command = new CreateSampleFindingsCommand(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 ThreatIntelSet. ThreatIntelSets consist of known malicious IP addresses.
* GuardDuty generates findings based on ThreatIntelSets. Only users of the administrator account can
* use this operation.</p>
*/
public createThreatIntelSet(
args: CreateThreatIntelSetCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateThreatIntelSetCommandOutput>;
public createThreatIntelSet(
args: CreateThreatIntelSetCommandInput,
cb: (err: any, data?: CreateThreatIntelSetCommandOutput) => void
): void;
public createThreatIntelSet(
args: CreateThreatIntelSetCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateThreatIntelSetCommandOutput) => void
): void;
public createThreatIntelSet(
args: CreateThreatIntelSetCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateThreatIntelSetCommandOutput) => void),
cb?: (err: any, data?: CreateThreatIntelSetCommandOutput) => void
): Promise<CreateThreatIntelSetCommandOutput> | void {
const command = new CreateThreatIntelSetCommand(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>Declines invitations sent to the current member account by AWS accounts specified by their
* account IDs.</p>
*/
public declineInvitations(
args: DeclineInvitationsCommandInput,
options?: __HttpHandlerOptions
): Promise<DeclineInvitationsCommandOutput>;
public declineInvitations(
args: DeclineInvitationsCommandInput,
cb: (err: any, data?: DeclineInvitationsCommandOutput) => void
): void;
public declineInvitations(
args: DeclineInvitationsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeclineInvitationsCommandOutput) => void
): void;
public declineInvitations(
args: DeclineInvitationsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeclineInvitationsCommandOutput) => void),
cb?: (err: any, data?: DeclineInvitationsCommandOutput) => void
): Promise<DeclineInvitationsCommandOutput> | void {
const command = new DeclineInvitationsCommand(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 Amazon GuardDuty detector that is specified by the detector ID.</p>
*/
public deleteDetector(
args: DeleteDetectorCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteDetectorCommandOutput>;
public deleteDetector(
args: DeleteDetectorCommandInput,
cb: (err: any, data?: DeleteDetectorCommandOutput) => void
): void;
public deleteDetector(
args: DeleteDetectorCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteDetectorCommandOutput) => void
): void;
public deleteDetector(
args: DeleteDetectorCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteDetectorCommandOutput) => void),
cb?: (err: any, data?: DeleteDetectorCommandOutput) => void
): Promise<DeleteDetectorCommandOutput> | void {
const command = new DeleteDetectorCommand(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 filter specified by the filter name.</p>
*/
public deleteFilter(
args: DeleteFilterCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteFilterCommandOutput>;
public deleteFilter(args: DeleteFilterCommandInput, cb: (err: any, data?: DeleteFilterCommandOutput) => void): void;
public deleteFilter(
args: DeleteFilterCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteFilterCommandOutput) => void
): void;
public deleteFilter(
args: DeleteFilterCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteFilterCommandOutput) => void),
cb?: (err: any, data?: DeleteFilterCommandOutput) => void
): Promise<DeleteFilterCommandOutput> | void {
const command = new DeleteFilterCommand(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 invitations sent to the current member account by AWS accounts specified by their
* account IDs.</p>
*/
public deleteInvitations(
args: DeleteInvitationsCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteInvitationsCommandOutput>;
public deleteInvitations(
args: DeleteInvitationsCommandInput,
cb: (err: any, data?: DeleteInvitationsCommandOutput) => void
): void;
public deleteInvitations(
args: DeleteInvitationsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteInvitationsCommandOutput) => void
): void;
public deleteInvitations(
args: DeleteInvitationsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteInvitationsCommandOutput) => void),
cb?: (err: any, data?: DeleteInvitationsCommandOutput) => void
): Promise<DeleteInvitationsCommandOutput> | void {
const command = new DeleteInvitationsCommand(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 IPSet specified by the <code>ipSetId</code>. IPSets are called trusted IP
* lists in the console user interface.</p>
*/
public deleteIPSet(args: DeleteIPSetCommandInput, options?: __HttpHandlerOptions): Promise<DeleteIPSetCommandOutput>;
public deleteIPSet(args: DeleteIPSetCommandInput, cb: (err: any, data?: DeleteIPSetCommandOutput) => void): void;
public deleteIPSet(
args: DeleteIPSetCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteIPSetCommandOutput) => void
): void;
public deleteIPSet(
args: DeleteIPSetCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteIPSetCommandOutput) => void),
cb?: (err: any, data?: DeleteIPSetCommandOutput) => void
): Promise<DeleteIPSetCommandOutput> | void {
const command = new DeleteIPSetCommand(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 GuardDuty member accounts (to the current GuardDuty administrator account) specified by
* the account IDs.</p>
*/
public deleteMembers(
args: DeleteMembersCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteMembersCommandOutput>;
public deleteMembers(
args: DeleteMembersCommandInput,
cb: (err: any, data?: DeleteMembersCommandOutput) => void
): void;
public deleteMembers(
args: DeleteMembersCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteMembersCommandOutput) => void
): void;
public deleteMembers(
args: DeleteMembersCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteMembersCommandOutput) => void),
cb?: (err: any, data?: DeleteMembersCommandOutput) => void
): Promise<DeleteMembersCommandOutput> | void {
const command = new DeleteMembersCommand(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 publishing definition with the specified <code>destinationId</code>.</p>
*/
public deletePublishingDestination(
args: DeletePublishingDestinationCommandInput,
options?: __HttpHandlerOptions
): Promise<DeletePublishingDestinationCommandOutput>;
public deletePublishingDestination(
args: DeletePublishingDestinationCommandInput,
cb: (err: any, data?: DeletePublishingDestinationCommandOutput) => void
): void;
public deletePublishingDestination(
args: DeletePublishingDestinationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeletePublishingDestinationCommandOutput) => void
): void;
public deletePublishingDestination(
args: DeletePublishingDestinationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeletePublishingDestinationCommandOutput) => void),
cb?: (err: any, data?: DeletePublishingDestinationCommandOutput) => void
): Promise<DeletePublishingDestinationCommandOutput> | void {
const command = new DeletePublishingDestinationCommand(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 ThreatIntelSet specified by the ThreatIntelSet ID.</p>
*/
public deleteThreatIntelSet(
args: DeleteThreatIntelSetCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteThreatIntelSetCommandOutput>;
public deleteThreatIntelSet(
args: DeleteThreatIntelSetCommandInput,
cb: (err: any, data?: DeleteThreatIntelSetCommandOutput) => void
): void;
public deleteThreatIntelSet(
args: DeleteThreatIntelSetCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteThreatIntelSetCommandOutput) => void
): void;
public deleteThreatIntelSet(
args: DeleteThreatIntelSetCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteThreatIntelSetCommandOutput) => void),
cb?: (err: any, data?: DeleteThreatIntelSetCommandOutput) => void
): Promise<DeleteThreatIntelSetCommandOutput> | void {
const command = new DeleteThreatIntelSetCommand(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 information about the account selected as the delegated administrator for
* GuardDuty.</p>
*/
public describeOrganizationConfiguration(
args: DescribeOrganizationConfigurationCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeOrganizationConfigurationCommandOutput>;
public describeOrganizationConfiguration(
args: DescribeOrganizationConfigurationCommandInput,
cb: (err: any, data?: DescribeOrganizationConfigurationCommandOutput) => void
): void;
public describeOrganizationConfiguration(
args: DescribeOrganizationConfigurationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeOrganizationConfigurationCommandOutput) => void
): void;
public describeOrganizationConfiguration(
args: DescribeOrganizationConfigurationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeOrganizationConfigurationCommandOutput) => void),
cb?: (err: any, data?: DescribeOrganizationConfigurationCommandOutput) => void
): Promise<DescribeOrganizationConfigurationCommandOutput> | void {
const command = new DescribeOrganizationConfigurationCommand(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 information about the publishing destination specified by the provided
* <code>destinationId</code>.</p>
*/
public describePublishingDestination(
args: DescribePublishingDestinationCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribePublishingDestinationCommandOutput>;
public describePublishingDestination(
args: DescribePublishingDestinationCommandInput,
cb: (err: any, data?: DescribePublishingDestinationCommandOutput) => void
): void;
public describePublishingDestination(
args: DescribePublishingDestinationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribePublishingDestinationCommandOutput) => void
): void;
public describePublishingDestination(
args: DescribePublishingDestinationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribePublishingDestinationCommandOutput) => void),
cb?: (err: any, data?: DescribePublishingDestinationCommandOutput) => void
): Promise<DescribePublishingDestinationCommandOutput> | void {
const command = new DescribePublishingDestinationCommand(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>Disables an AWS account within the Organization as the GuardDuty delegated
* administrator.</p>
*/
public disableOrganizationAdminAccount(
args: DisableOrganizationAdminAccountCommandInput,
options?: __HttpHandlerOptions
): Promise<DisableOrganizationAdminAccountCommandOutput>;
public disableOrganizationAdminAccount(
args: DisableOrganizationAdminAccountCommandInput,
cb: (err: any, data?: DisableOrganizationAdminAccountCommandOutput) => void
): void;
public disableOrganizationAdminAccount(
args: DisableOrganizationAdminAccountCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DisableOrganizationAdminAccountCommandOutput) => void
): void;
public disableOrganizationAdminAccount(
args: DisableOrganizationAdminAccountCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DisableOrganizationAdminAccountCommandOutput) => void),
cb?: (err: any, data?: DisableOrganizationAdminAccountCommandOutput) => void
): Promise<DisableOrganizationAdminAccountCommandOutput> | void {
const command = new DisableOrganizationAdminAccountCommand(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>Disassociates the current GuardDuty member account from its administrator account.</p>
*/
public disassociateFromMasterAccount(
args: DisassociateFromMasterAccountCommandInput,
options?: __HttpHandlerOptions
): Promise<DisassociateFromMasterAccountCommandOutput>;
public disassociateFromMasterAccount(
args: DisassociateFromMasterAccountCommandInput,
cb: (err: any, data?: DisassociateFromMasterAccountCommandOutput) => void
): void;
public disassociateFromMasterAccount(
args: DisassociateFromMasterAccountCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DisassociateFromMasterAccountCommandOutput) => void
): void;
public disassociateFromMasterAccount(
args: DisassociateFromMasterAccountCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DisassociateFromMasterAccountCommandOutput) => void),
cb?: (err: any, data?: DisassociateFromMasterAccountCommandOutput) => void
): Promise<DisassociateFromMasterAccountCommandOutput> | void {
const command = new DisassociateFromMasterAccountCommand(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>Disassociates GuardDuty member accounts (to the current GuardDuty administrator account)
* specified by the account IDs.</p>
*/
public disassociateMembers(
args: DisassociateMembersCommandInput,
options?: __HttpHandlerOptions
): Promise<DisassociateMembersCommandOutput>;
public disassociateMembers(
args: DisassociateMembersCommandInput,
cb: (err: any, data?: DisassociateMembersCommandOutput) => void
): void;
public disassociateMembers(
args: DisassociateMembersCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DisassociateMembersCommandOutput) => void
): void;
public disassociateMembers(
args: DisassociateMembersCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DisassociateMembersCommandOutput) => void),
cb?: (err: any, data?: DisassociateMembersCommandOutput) => void
): Promise<DisassociateMembersCommandOutput> | void {
const command = new DisassociateMembersCommand(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 an AWS account within the organization as the GuardDuty delegated
* administrator.</p>
*/
public enableOrganizationAdminAccount(
args: EnableOrganizationAdminAccountCommandInput,
options?: __HttpHandlerOptions
): Promise<EnableOrganizationAdminAccountCommandOutput>;
public enableOrganizationAdminAccount(
args: EnableOrganizationAdminAccountCommandInput,
cb: (err: any, data?: EnableOrganizationAdminAccountCommandOutput) => void
): void;
public enableOrganizationAdminAccount(
args: EnableOrganizationAdminAccountCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: EnableOrganizationAdminAccountCommandOutput) => void
): void;
public enableOrganizationAdminAccount(
args: EnableOrganizationAdminAccountCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: EnableOrganizationAdminAccountCommandOutput) => void),
cb?: (err: any, data?: EnableOrganizationAdminAccountCommandOutput) => void
): Promise<EnableOrganizationAdminAccountCommandOutput> | void {
const command = new EnableOrganizationAdminAccountCommand(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>Retrieves an Amazon GuardDuty detector specified by the detectorId.</p>
*/
public getDetector(args: GetDetectorCommandInput, options?: __HttpHandlerOptions): Promise<GetDetectorCommandOutput>;
public getDetector(args: GetDetectorCommandInput, cb: (err: any, data?: GetDetectorCommandOutput) => void): void;
public getDetector(
args: GetDetectorCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetDetectorCommandOutput) => void
): void;
public getDetector(
args: GetDetectorCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetDetectorCommandOutput) => void),
cb?: (err: any, data?: GetDetectorCommandOutput) => void
): Promise<GetDetectorCommandOutput> | void {
const command = new GetDetectorCommand(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 filter specified by the filter name.</p>
*/
public getFilter(args: GetFilterCommandInput, options?: __HttpHandlerOptions): Promise<GetFilterCommandOutput>;
public getFilter(args: GetFilterCommandInput, cb: (err: any, data?: GetFilterCommandOutput) => void): void;
public getFilter(
args: GetFilterCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetFilterCommandOutput) => void
): void;
public getFilter(
args: GetFilterCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetFilterCommandOutput) => void),
cb?: (err: any, data?: GetFilterCommandOutput) => void
): Promise<GetFilterCommandOutput> | void {
const command = new GetFilterCommand(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>Describes Amazon GuardDuty findings specified by finding IDs.</p>
*/
public getFindings(args: GetFindingsCommandInput, options?: __HttpHandlerOptions): Promise<GetFindingsCommandOutput>;
public getFindings(args: GetFindingsCommandInput, cb: (err: any, data?: GetFindingsCommandOutput) => void): void;
public getFindings(
args: GetFindingsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetFindingsCommandOutput) => void
): void;
public getFindings(
args: GetFindingsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetFindingsCommandOutput) => void),
cb?: (err: any, data?: GetFindingsCommandOutput) => void
): Promise<GetFindingsCommandOutput> | void {
const command = new GetFindingsCommand(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 Amazon GuardDuty findings statistics for the specified detector ID.</p>
*/
public getFindingsStatistics(
args: GetFindingsStatisticsCommandInput,
options?: __HttpHandlerOptions
): Promise<GetFindingsStatisticsCommandOutput>;
public getFindingsStatistics(
args: GetFindingsStatisticsCommandInput,
cb: (err: any, data?: GetFindingsStatisticsCommandOutput) => void
): void;
public getFindingsStatistics(
args: GetFindingsStatisticsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetFindingsStatisticsCommandOutput) => void
): void;
public getFindingsStatistics(
args: GetFindingsStatisticsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetFindingsStatisticsCommandOutput) => void),
cb?: (err: any, data?: GetFindingsStatisticsCommandOutput) => void
): Promise<GetFindingsStatisticsCommandOutput> | void {
const command = new GetFindingsStatisticsCommand(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 count of all GuardDuty membership invitations that were sent to the current
* member account except the currently accepted invitation.</p>
*/
public getInvitationsCount(
args: GetInvitationsCountCommandInput,
options?: __HttpHandlerOptions
): Promise<GetInvitationsCountCommandOutput>;
public getInvitationsCount(
args: GetInvitationsCountCommandInput,
cb: (err: any, data?: GetInvitationsCountCommandOutput) => void
): void;
public getInvitationsCount(
args: GetInvitationsCountCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetInvitationsCountCommandOutput) => void
): void;
public getInvitationsCount(
args: GetInvitationsCountCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetInvitationsCountCommandOutput) => void),
cb?: (err: any, data?: GetInvitationsCountCommandOutput) => void
): Promise<GetInvitationsCountCommandOutput> | void {
const command = new GetInvitationsCountCommand(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>Retrieves the IPSet specified by the <code>ipSetId</code>.</p>
*/
public getIPSet(args: GetIPSetCommandInput, options?: __HttpHandlerOptions): Promise<GetIPSetCommandOutput>;
public getIPSet(args: GetIPSetCommandInput, cb: (err: any, data?: GetIPSetCommandOutput) => void): void;
public getIPSet(
args: GetIPSetCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetIPSetCommandOutput) => void
): void;
public getIPSet(
args: GetIPSetCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetIPSetCommandOutput) => void),
cb?: (err: any, data?: GetIPSetCommandOutput) => void
): Promise<GetIPSetCommandOutput> | void {
const command = new GetIPSetCommand(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 details for the GuardDuty administrator account associated with the current
* GuardDuty member account.</p>
*/
public getMasterAccount(
args: GetMasterAccountCommandInput,
options?: __HttpHandlerOptions
): Promise<GetMasterAccountCommandOutput>;
public getMasterAccount(
args: GetMasterAccountCommandInput,
cb: (err: any, data?: GetMasterAccountCommandOutput) => void
): void;
public getMasterAccount(
args: GetMasterAccountCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetMasterAccountCommandOutput) => void
): void;
public getMasterAccount(
args: GetMasterAccountCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetMasterAccountCommandOutput) => void),
cb?: (err: any, data?: GetMasterAccountCommandOutput) => void
): Promise<GetMasterAccountCommandOutput> | void {
const command = new GetMasterAccountCommand(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>Describes which data sources are enabled for the member account's detector.</p>
*/
public getMemberDetectors(
args: GetMemberDetectorsCommandInput,
options?: __HttpHandlerOptions
): Promise<GetMemberDetectorsCommandOutput>;
public getMemberDetectors(
args: GetMemberDetectorsCommandInput,
cb: (err: any, data?: GetMemberDetectorsCommandOutput) => void
): void;
public getMemberDetectors(
args: GetMemberDetectorsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetMemberDetectorsCommandOutput) => void
): void;
public getMemberDetectors(
args: GetMemberDetectorsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetMemberDetectorsCommandOutput) => void),
cb?: (err: any, data?: GetMemberDetectorsCommandOutput) => void
): Promise<GetMemberDetectorsCommandOutput> | void {
const command = new GetMemberDetectorsCommand(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>Retrieves GuardDuty member accounts (of the current GuardDuty administrator account) specified by
* the account IDs.</p>
*/
public getMembers(args: GetMembersCommandInput, options?: __HttpHandlerOptions): Promise<GetMembersCommandOutput>;
public getMembers(args: GetMembersCommandInput, cb: (err: any, data?: GetMembersCommandOutput) => void): void;
public getMembers(
args: GetMembersCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetMembersCommandOutput) => void
): void;
public getMembers(
args: GetMembersCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetMembersCommandOutput) => void),
cb?: (err: any, data?: GetMembersCommandOutput) => void
): Promise<GetMembersCommandOutput> | void {
const command = new GetMembersCommand(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>Retrieves the ThreatIntelSet that is specified by the ThreatIntelSet ID.</p>
*/
public getThreatIntelSet(
args: GetThreatIntelSetCommandInput,
options?: __HttpHandlerOptions
): Promise<GetThreatIntelSetCommandOutput>;
public getThreatIntelSet(
args: GetThreatIntelSetCommandInput,
cb: (err: any, data?: GetThreatIntelSetCommandOutput) => void
): void;
public getThreatIntelSet(
args: GetThreatIntelSetCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetThreatIntelSetCommandOutput) => void
): void;
public getThreatIntelSet(
args: GetThreatIntelSetCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetThreatIntelSetCommandOutput) => void),
cb?: (err: any, data?: GetThreatIntelSetCommandOutput) => void
): Promise<GetThreatIntelSetCommandOutput> | void {
const command = new GetThreatIntelSetCommand(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 Amazon GuardDuty usage statistics over the last 30 days for the specified detector
* ID. For newly enabled detectors or data sources the cost returned will include only the usage
* so far under 30 days, this may differ from the cost metrics in the console, which projects
* usage over 30 days to provide a monthly cost estimate. For more information see <a href="https://docs.aws.amazon.com/guardduty/latest/ug/monitoring_costs.html#usage-calculations">Understanding How Usage Costs are Calculated</a>.</p>
*/
public getUsageStatistics(
args: GetUsageStatisticsCommandInput,
options?: __HttpHandlerOptions
): Promise<GetUsageStatisticsCommandOutput>;
public getUsageStatistics(
args: GetUsageStatisticsCommandInput,
cb: (err: any, data?: GetUsageStatisticsCommandOutput) => void
): void;
public getUsageStatistics(
args: GetUsageStatisticsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetUsageStatisticsCommandOutput) => void
): void;
public getUsageStatistics(
args: GetUsageStatisticsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetUsageStatisticsCommandOutput) => void),
cb?: (err: any, data?: GetUsageStatisticsCommandOutput) => void
): Promise<GetUsageStatisticsCommandOutput> | void {
const command = new GetUsageStatisticsCommand(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>Invites other AWS accounts (created as members of the current AWS account by
* CreateMembers) to enable GuardDuty, and allow the current AWS account to view and manage these
* accounts' findings on their behalf as the GuardDuty administrator account.</p>
*/
public inviteMembers(
args: InviteMembersCommandInput,
options?: __HttpHandlerOptions
): Promise<InviteMembersCommandOutput>;
public inviteMembers(
args: InviteMembersCommandInput,
cb: (err: any, data?: InviteMembersCommandOutput) => void
): void;
public inviteMembers(
args: InviteMembersCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: InviteMembersCommandOutput) => void
): void;
public inviteMembers(
args: InviteMembersCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: InviteMembersCommandOutput) => void),
cb?: (err: any, data?: InviteMembersCommandOutput) => void
): Promise<InviteMembersCommandOutput> | void {
const command = new InviteMembersCommand(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 detectorIds of all the existing Amazon GuardDuty detector resources.</p>
*/
public listDetectors(
args: ListDetectorsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListDetectorsCommandOutput>;
public listDetectors(
args: ListDetectorsCommandInput,
cb: (err: any, data?: ListDetectorsCommandOutput) => void
): void;
public listDetectors(
args: ListDetectorsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListDetectorsCommandOutput) => void
): void;
public listDetectors(
args: ListDetectorsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListDetectorsCommandOutput) => void),
cb?: (err: any, data?: ListDetectorsCommandOutput) => void
): Promise<ListDetectorsCommandOutput> | void {
const command = new ListDetectorsCommand(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 paginated list of the current filters.</p>
*/
public listFilters(args: ListFiltersCommandInput, options?: __HttpHandlerOptions): Promise<ListFiltersCommandOutput>;
public listFilters(args: ListFiltersCommandInput, cb: (err: any, data?: ListFiltersCommandOutput) => void): void;
public listFilters(
args: ListFiltersCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListFiltersCommandOutput) => void
): void;
public listFilters(
args: ListFiltersCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListFiltersCommandOutput) => void),
cb?: (err: any, data?: ListFiltersCommandOutput) => void
): Promise<ListFiltersCommandOutput> | void {
const command = new ListFiltersCommand(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 Amazon GuardDuty findings for the specified detector ID.</p>
*/
public listFindings(
args: ListFindingsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListFindingsCommandOutput>;
public listFindings(args: ListFindingsCommandInput, cb: (err: any, data?: ListFindingsCommandOutput) => void): void;
public listFindings(
args: ListFindingsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListFindingsCommandOutput) => void
): void;
public listFindings(
args: ListFindingsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListFindingsCommandOutput) => void),
cb?: (err: any, data?: ListFindingsCommandOutput) => void
): Promise<ListFindingsCommandOutput> | void {
const command = new ListFindingsCommand(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 all GuardDuty membership invitations that were sent to the current AWS
* account.</p>
*/
public listInvitations(
args: ListInvitationsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListInvitationsCommandOutput>;
public listInvitations(
args: ListInvitationsCommandInput,
cb: (err: any, data?: ListInvitationsCommandOutput) => void
): void;
public listInvitations(
args: ListInvitationsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListInvitationsCommandOutput) => void
): void;
public listInvitations(
args: ListInvitationsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListInvitationsCommandOutput) => void),
cb?: (err: any, data?: ListInvitationsCommandOutput) => void
): Promise<ListInvitationsCommandOutput> | void {
const command = new ListInvitationsCommand(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 IPSets of the GuardDuty service specified by the detector ID. If you use this
* operation from a member account, the IPSets returned are the IPSets from the associated administrator
* account.</p>
*/
public listIPSets(args: ListIPSetsCommandInput, options?: __HttpHandlerOptions): Promise<ListIPSetsCommandOutput>;
public listIPSets(args: ListIPSetsCommandInput, cb: (err: any, data?: ListIPSetsCommandOutput) => void): void;
public listIPSets(
args: ListIPSetsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListIPSetsCommandOutput) => void
): void;
public listIPSets(
args: ListIPSetsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListIPSetsCommandOutput) => void),
cb?: (err: any, data?: ListIPSetsCommandOutput) => void
): Promise<ListIPSetsCommandOutput> | void {
const command = new ListIPSetsCommand(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 details about all member accounts for the current GuardDuty administrator account.</p>
*/
public listMembers(args: ListMembersCommandInput, options?: __HttpHandlerOptions): Promise<ListMembersCommandOutput>;
public listMembers(args: ListMembersCommandInput, cb: (err: any, data?: ListMembersCommandOutput) => void): void;
public listMembers(
args: ListMembersCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListMembersCommandOutput) => void
): void;
public listMembers(
args: ListMembersCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListMembersCommandOutput) => void),
cb?: (err: any, data?: ListMembersCommandOutput) => void
): Promise<ListMembersCommandOutput> | void {
const command = new ListMembersCommand(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 accounts configured as GuardDuty delegated administrators.</p>
*/
public listOrganizationAdminAccounts(
args: ListOrganizationAdminAccountsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListOrganizationAdminAccountsCommandOutput>;
public listOrganizationAdminAccounts(
args: ListOrganizationAdminAccountsCommandInput,
cb: (err: any, data?: ListOrganizationAdminAccountsCommandOutput) => void
): void;
public listOrganizationAdminAccounts(
args: ListOrganizationAdminAccountsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListOrganizationAdminAccountsCommandOutput) => void
): void;
public listOrganizationAdminAccounts(
args: ListOrganizationAdminAccountsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListOrganizationAdminAccountsCommandOutput) => void),
cb?: (err: any, data?: ListOrganizationAdminAccountsCommandOutput) => void
): Promise<ListOrganizationAdminAccountsCommandOutput> | void {
const command = new ListOrganizationAdminAccountsCommand(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 publishing destinations associated with the specified
* <code>dectectorId</code>.</p>
*/
public listPublishingDestinations(
args: ListPublishingDestinationsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListPublishingDestinationsCommandOutput>;
public listPublishingDestinations(
args: ListPublishingDestinationsCommandInput,
cb: (err: any, data?: ListPublishingDestinationsCommandOutput) => void
): void;
public listPublishingDestinations(
args: ListPublishingDestinationsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListPublishingDestinationsCommandOutput) => void
): void;
public listPublishingDestinations(
args: ListPublishingDestinationsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListPublishingDestinationsCommandOutput) => void),
cb?: (err: any, data?: ListPublishingDestinationsCommandOutput) => void
): Promise<ListPublishingDestinationsCommandOutput> | void {
const command = new ListPublishingDestinationsCommand(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 tags for a resource. Tagging is currently supported for detectors, finding filters,
* IP sets, and threat intel sets, with a limit of 50 tags per resource. When invoked, this
* operation returns all assigned tags for a given resource.</p>
*/
public listTagsForResource(
args: ListTagsForResourceCommandInput,
options?: __HttpHandlerOptions
): Promise<ListTagsForResourceCommandOutput>;
public listTagsForResource(
args: ListTagsForResourceCommandInput,
cb: (err: any, data?: ListTagsForResourceCommandOutput) => void
): void;
public listTagsForResource(
args: ListTagsForResourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListTagsForResourceCommandOutput) => void
): void;
public listTagsForResource(
args: ListTagsForResourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTagsForResourceCommandOutput) => void),
cb?: (err: any, data?: ListTagsForResourceCommandOutput) => void
): Promise<ListTagsForResourceCommandOutput> | void {
const command = new ListTagsForResourceCommand(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 ThreatIntelSets of the GuardDuty service specified by the detector ID. If you
* use this operation from a member account, the ThreatIntelSets associated with the administrator
* account are returned.</p>
*/
public listThreatIntelSets(
args: ListThreatIntelSetsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListThreatIntelSetsCommandOutput>;
public listThreatIntelSets(
args: ListThreatIntelSetsCommandInput,
cb: (err: any, data?: ListThreatIntelSetsCommandOutput) => void
): void;
public listThreatIntelSets(
args: ListThreatIntelSetsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListThreatIntelSetsCommandOutput) => void
): void;
public listThreatIntelSets(
args: ListThreatIntelSetsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListThreatIntelSetsCommandOutput) => void),
cb?: (err: any, data?: ListThreatIntelSetsCommandOutput) => void
): Promise<ListThreatIntelSetsCommandOutput> | void {
const command = new ListThreatIntelSetsCommand(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>Turns on GuardDuty monitoring of the specified member accounts. Use this operation to
* restart monitoring of accounts that you stopped monitoring with the
* <code>StopMonitoringMembers</code> operation.</p>
*/
public startMonitoringMembers(
args: StartMonitoringMembersCommandInput,
options?: __HttpHandlerOptions
): Promise<StartMonitoringMembersCommandOutput>;
public startMonitoringMembers(
args: StartMonitoringMembersCommandInput,
cb: (err: any, data?: StartMonitoringMembersCommandOutput) => void
): void;
public startMonitoringMembers(
args: StartMonitoringMembersCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: StartMonitoringMembersCommandOutput) => void
): void;
public startMonitoringMembers(
args: StartMonitoringMembersCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: StartMonitoringMembersCommandOutput) => void),
cb?: (err: any, data?: StartMonitoringMembersCommandOutput) => void
): Promise<StartMonitoringMembersCommandOutput> | void {
const command = new StartMonitoringMembersCommand(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>Stops GuardDuty monitoring for the specified member accounts. Use the
* <code>StartMonitoringMembers</code> operation to restart monitoring for those
* accounts.</p>
*/
public stopMonitoringMembers(
args: StopMonitoringMembersCommandInput,
options?: __HttpHandlerOptions
): Promise<StopMonitoringMembersCommandOutput>;
public stopMonitoringMembers(
args: StopMonitoringMembersCommandInput,
cb: (err: any, data?: StopMonitoringMembersCommandOutput) => void
): void;
public stopMonitoringMembers(
args: StopMonitoringMembersCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: StopMonitoringMembersCommandOutput) => void
): void;
public stopMonitoringMembers(
args: StopMonitoringMembersCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: StopMonitoringMembersCommandOutput) => void),
cb?: (err: any, data?: StopMonitoringMembersCommandOutput) => void
): Promise<StopMonitoringMembersCommandOutput> | void {
const command = new StopMonitoringMembersCommand(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 tags to a resource.</p>
*/
public tagResource(args: TagResourceCommandInput, options?: __HttpHandlerOptions): Promise<TagResourceCommandOutput>;
public tagResource(args: TagResourceCommandInput, cb: (err: any, data?: TagResourceCommandOutput) => void): void;
public tagResource(
args: TagResourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: TagResourceCommandOutput) => void
): void;
public tagResource(
args: TagResourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: TagResourceCommandOutput) => void),
cb?: (err: any, data?: TagResourceCommandOutput) => void
): Promise<TagResourceCommandOutput> | void {
const command = new TagResourceCommand(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>Unarchives GuardDuty findings specified by the <code>findingIds</code>.</p>
*/
public unarchiveFindings(
args: UnarchiveFindingsCommandInput,
options?: __HttpHandlerOptions
): Promise<UnarchiveFindingsCommandOutput>;
public unarchiveFindings(
args: UnarchiveFindingsCommandInput,
cb: (err: any, data?: UnarchiveFindingsCommandOutput) => void
): void;
public unarchiveFindings(
args: UnarchiveFindingsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UnarchiveFindingsCommandOutput) => void
): void;
public unarchiveFindings(
args: UnarchiveFindingsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UnarchiveFindingsCommandOutput) => void),
cb?: (err: any, data?: UnarchiveFindingsCommandOutput) => void
): Promise<UnarchiveFindingsCommandOutput> | void {
const command = new UnarchiveFindingsCommand(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>Removes tags from a resource.</p>
*/
public untagResource(
args: UntagResourceCommandInput,
options?: __HttpHandlerOptions
): Promise<UntagResourceCommandOutput>;
public untagResource(
args: UntagResourceCommandInput,
cb: (err: any, data?: UntagResourceCommandOutput) => void
): void;
public untagResource(
args: UntagResourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UntagResourceCommandOutput) => void
): void;
public untagResource(
args: UntagResourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UntagResourceCommandOutput) => void),
cb?: (err: any, data?: UntagResourceCommandOutput) => void
): Promise<UntagResourceCommandOutput> | void {
const command = new UntagResourceCommand(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 Amazon GuardDuty detector specified by the detectorId.</p>
*/
public updateDetector(
args: UpdateDetectorCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateDetectorCommandOutput>;
public updateDetector(
args: UpdateDetectorCommandInput,
cb: (err: any, data?: UpdateDetectorCommandOutput) => void
): void;
public updateDetector(
args: UpdateDetectorCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateDetectorCommandOutput) => void
): void;
public updateDetector(
args: UpdateDetectorCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateDetectorCommandOutput) => void),
cb?: (err: any, data?: UpdateDetectorCommandOutput) => void
): Promise<UpdateDetectorCommandOutput> | void {
const command = new UpdateDetectorCommand(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 filter specified by the filter name.</p>
*/
public updateFilter(
args: UpdateFilterCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateFilterCommandOutput>;
public updateFilter(args: UpdateFilterCommandInput, cb: (err: any, data?: UpdateFilterCommandOutput) => void): void;
public updateFilter(
args: UpdateFilterCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateFilterCommandOutput) => void
): void;
public updateFilter(
args: UpdateFilterCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateFilterCommandOutput) => void),
cb?: (err: any, data?: UpdateFilterCommandOutput) => void
): Promise<UpdateFilterCommandOutput> | void {
const command = new UpdateFilterCommand(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>Marks the specified GuardDuty findings as useful or not useful.</p>
*/
public updateFindingsFeedback(
args: UpdateFindingsFeedbackCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateFindingsFeedbackCommandOutput>;
public updateFindingsFeedback(
args: UpdateFindingsFeedbackCommandInput,
cb: (err: any, data?: UpdateFindingsFeedbackCommandOutput) => void
): void;
public updateFindingsFeedback(
args: UpdateFindingsFeedbackCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateFindingsFeedbackCommandOutput) => void
): void;
public updateFindingsFeedback(
args: UpdateFindingsFeedbackCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateFindingsFeedbackCommandOutput) => void),
cb?: (err: any, data?: UpdateFindingsFeedbackCommandOutput) => void
): Promise<UpdateFindingsFeedbackCommandOutput> | void {
const command = new UpdateFindingsFeedbackCommand(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 IPSet specified by the IPSet ID.</p>
*/
public updateIPSet(args: UpdateIPSetCommandInput, options?: __HttpHandlerOptions): Promise<UpdateIPSetCommandOutput>;
public updateIPSet(args: UpdateIPSetCommandInput, cb: (err: any, data?: UpdateIPSetCommandOutput) => void): void;
public updateIPSet(
args: UpdateIPSetCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateIPSetCommandOutput) => void
): void;
public updateIPSet(
args: UpdateIPSetCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateIPSetCommandOutput) => void),
cb?: (err: any, data?: UpdateIPSetCommandOutput) => void
): Promise<UpdateIPSetCommandOutput> | void {
const command = new UpdateIPSetCommand(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>Contains information on member accounts to be updated.</p>
*/
public updateMemberDetectors(
args: UpdateMemberDetectorsCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateMemberDetectorsCommandOutput>;
public updateMemberDetectors(
args: UpdateMemberDetectorsCommandInput,
cb: (err: any, data?: UpdateMemberDetectorsCommandOutput) => void
): void;
public updateMemberDetectors(
args: UpdateMemberDetectorsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateMemberDetectorsCommandOutput) => void
): void;
public updateMemberDetectors(
args: UpdateMemberDetectorsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateMemberDetectorsCommandOutput) => void),
cb?: (err: any, data?: UpdateMemberDetectorsCommandOutput) => void
): Promise<UpdateMemberDetectorsCommandOutput> | void {
const command = new UpdateMemberDetectorsCommand(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 delegated administrator account with the values provided.</p>
*/
public updateOrganizationConfiguration(
args: UpdateOrganizationConfigurationCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateOrganizationConfigurationCommandOutput>;
public updateOrganizationConfiguration(
args: UpdateOrganizationConfigurationCommandInput,
cb: (err: any, data?: UpdateOrganizationConfigurationCommandOutput) => void
): void;
public updateOrganizationConfiguration(
args: UpdateOrganizationConfigurationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateOrganizationConfigurationCommandOutput) => void
): void;
public updateOrganizationConfiguration(
args: UpdateOrganizationConfigurationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateOrganizationConfigurationCommandOutput) => void),
cb?: (err: any, data?: UpdateOrganizationConfigurationCommandOutput) => void
): Promise<UpdateOrganizationConfigurationCommandOutput> | void {
const command = new UpdateOrganizationConfigurationCommand(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 information about the publishing destination specified by the
* <code>destinationId</code>.</p>
*/
public updatePublishingDestination(
args: UpdatePublishingDestinationCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdatePublishingDestinationCommandOutput>;
public updatePublishingDestination(
args: UpdatePublishingDestinationCommandInput,
cb: (err: any, data?: UpdatePublishingDestinationCommandOutput) => void
): void;
public updatePublishingDestination(
args: UpdatePublishingDestinationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdatePublishingDestinationCommandOutput) => void
): void;
public updatePublishingDestination(
args: UpdatePublishingDestinationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdatePublishingDestinationCommandOutput) => void),
cb?: (err: any, data?: UpdatePublishingDestinationCommandOutput) => void
): Promise<UpdatePublishingDestinationCommandOutput> | void {
const command = new UpdatePublishingDestinationCommand(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 ThreatIntelSet specified by the ThreatIntelSet ID.</p>
*/
public updateThreatIntelSet(
args: UpdateThreatIntelSetCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateThreatIntelSetCommandOutput>;
public updateThreatIntelSet(
args: UpdateThreatIntelSetCommandInput,
cb: (err: any, data?: UpdateThreatIntelSetCommandOutput) => void
): void;
public updateThreatIntelSet(
args: UpdateThreatIntelSetCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateThreatIntelSetCommandOutput) => void
): void;
public updateThreatIntelSet(
args: UpdateThreatIntelSetCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateThreatIntelSetCommandOutput) => void),
cb?: (err: any, data?: UpdateThreatIntelSetCommandOutput) => void
): Promise<UpdateThreatIntelSetCommandOutput> | void {
const command = new UpdateThreatIntelSetCommand(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 Application = require("application");
var BitmapFactory = require("./BitmapFactory");
import ImageSource = require('image-source');
import TypeUtils = require("utils/types");
/**
* Describes an object that stores ARGB color data.
*/
export interface IArgb {
/**
* Gets the alpha value.
*/
a: number;
/**
* Gets the red value.
*/
r: number;
/**
* Gets the green value.
*/
g: number;
/**
* Gets the blue value.
*/
b: number;
}
/**
* Describes bitmap data.
*/
export interface IBitmapData {
/**
* Gets the data as Base64 string.
*/
base64: string;
/**
* Gets the mime type.
*/
mime: string;
}
/**
* Describes an object that stores a font.
*/
export interface IFont {
/**
* Anti alias or not.
*/
antiAlias?: boolean;
/**
* Gets the custom forground color.
*/
color?: string | number | IArgb;
/**
* Gets the name.
*/
name?: string;
/**
* Gets the size.
*/
size?: number;
}
/**
* Options for 'makeMutable()' functon.
*/
export interface IMakeMutableOptions {
/**
* Dispose current bitmap or not.
*
* Default: (false)
*/
disposeCurrent?: boolean;
/**
* Options for handling temp data / files.
*/
temp?: {
/**
* This is only used if stradegy is 'Custom' and
* is used to define the custom temp directory.
*
* This can be a string or a native object that represents a file
* like java.lang.File on Android.
*/
directory?: any;
/**
* The stradegy.
*
* Default: Memory
*/
stradegy?: TempFileStradegy;
}
}
/**
* A 2D point.
*/
export interface IPoint2D {
/**
* Gets the X coordinate.
*/
x: number;
/**
* Gets the X coordinate.
*/
y: number;
}
/**
* Describes an object that stores a size.
*/
export interface ISize {
/**
* Gets the height.
*/
height: number;
/**
* Gets the width.
*/
width: number;
}
/**
* List of outout formats.
*/
export enum OutputFormat {
/**
* PNG
*/
PNG = 1,
/**
* JPEG
*/
JPEG = 2,
}
/**
* List of temp file stradegies.
*/
export enum TempFileStradegy {
/**
* Memory
*/
Memory = 1,
/**
* Cache directory
*/
CacheDir = 2,
/**
* External directory
*/
ExternalCacheDir = 3,
/**
* Custom directory
*/
Custom = 4,
}
/**
* Describes a bitmap.
*/
export interface IBitmap {
/**
* Get the android specific object provided by 'application' module.
*/
android: Application.AndroidApplication;
/**
* Clones that bitmap.
*
* @return {IBitmap} Cloned bitmap.
*/
clone(): IBitmap;
/**
* Crops that bitmap and returns its copy.
*
* @param {IPoint2D} [leftTop] The coordinates of the left/top corner.
* @param {ISize} [size] The size.
*
* @return {IBitmap} The cropped bitmap.
*
* @throws At least one input value is invalid.
*/
crop(leftTop?: IPoint2D | string,
size?: ISize | string): IBitmap;
/**
* Gets or sets the default color.
*/
defaultColor: IPoint2D | string | number;
/**
* Disposes the bitmap. Similar to the IDisposable pattern of .NET Framework.
*
* @param {Function} [action] The action to invoke BEFORE bitmap is disposed.
* @param {T} [tag] An optional value for the action.
*
* @return {TResult} The result of the action (if defined).
*/
dispose<T, TResult>(action?: (bmp: IBitmap, tag?: T) => TResult,
tag?: T): TResult;
/**
* Draws a circle.
*
* @chainable
*
* @param {number} [radius] The radius.
* @param any [center] The center coordinates.
* @param any [color] The line color.
* @param any [fillColor] The fill color.
*
* @throws At least one input value is invalid.
*/
drawCircle(radius?: number,
center?: IPoint2D | string,
color?: string | number | IArgb, fillColor?: string | number | IArgb): IBitmap;
/**
* Draws an arc.
*
* @chainable
*
* @param {ISize} [size] The size.
* @param {IPoint2D} [leftTop] The coordinates of the left/top corner.
* @param {number} [startAngle] The starting angle (in degrees) where the arc begins.
* @param {number} [sweepAngle] The sweep angle (in degrees) measured clockwise.
* @param any [color] The line color.
* @param any [fillColor] The fill color.
*
* @throws At least one input value is invalid.
*/
drawArc(size?: ISize | string,
leftTop?: IPoint2D | string,
startAngle?: number,
sweepAngle?: number,
color?: string | number | IArgb, fillColor?: string | number | IArgb): IBitmap;
/**
* Draws a line.
*
* @chainable
*
* @param {IPoint2D} start The coordinates of the start point.
* @param {IPoint2D} end The coordinates of the end point.
* @param {IArgb} [color] The color to use. Default is black.
*
* @throws At least one input value is invalid.
*/
drawLine(start: IPoint2D | string, end: IPoint2D | string,
color?: string | number | IArgb): IBitmap;
/**
* Draws an oval circle.
*
* @chainable
*
* @param {ISize} [size] The size.
* @param {IPoint2D} [leftTop] The coordinates of the left/top corner.
* @param {IArgb} [color] The line color.
* @param {IArgb} [fillColor] The fill color.
*
* @throws At least one input value is invalid.
*/
drawOval(size?: ISize | string,
leftTop?: IPoint2D | string,
color?: string | number | IArgb, fillColor?: string | number | IArgb): IBitmap;
/**
* Draws a rectangle.
*
* @chainable
*
* @param {ISize} [size] The size.
* @param {IPoint2D} [leftTop] The coordinates of the left/top corner.
* @param {IArgb} [color] The line color.
* @param {IArgb} [fillColor] The fill color.
*
* @throws At least one input value is invalid.
*/
drawRect(size?: ISize | string,
leftTop?: IPoint2D | string,
color?: string | number | IArgb, fillColor?: string | number | IArgb): IBitmap;
/**
* Gets the color of a point.
*
* @param {IPoint2D} [coordinates] The coordinates of the point.
*
* @return {IArgb} The color.
*
* @throws At least one input value is invalid.
*/
getPoint(coordinates?: IPoint2D | string): IArgb;
/**
* Gets the height of the bitmap.
*/
height: number;
/**
* Get the iOS specific object provided by 'application' module.
*/
ios: Application.iOSApplication;
/**
* Inserts another image into that bitmap.
*
* @chainable
*
* @param {IBitmap} other The other image.
* @param {IPoint2D} [leftTop] The coordinates of the left/top corner.
*
* @throws At least one input value is invalid.
*/
insert(other: any,
leftTop?: IPoint2D | string): IBitmap;
/**
* Gets if the object has been disposed or not.
*/
isDisposed: boolean;
/**
* Gets the native platform specific object that represents that bitmap.
*/
nativeObject: any;
/**
* Normalizes a color value.
*
* @param any value The input value.
*
* @return {IArgb} The output value.
*
* @throws At least one input value is invalid.
*/
normalizeColor(value: string | number | IArgb): IArgb;
/**
* Creates a copy of that bitmap with a new size.
*
* @param {ISize} newSize The new size.
*
* @return {IBitmap] The new bitmap.
*/
resize(newSize: ISize | string): IBitmap;
/**
* Resizes that image by defining a new height by keeping ratio.
*
* @param {Number} newHeight The new height.
*
* @return {IBitmap} The resized image.
*/
resizeHeight(newHeight: number): IBitmap;
/**
* Resizes that image by defining a new (maximum) size by keeping ratio.
*
* @param {Number} maxSize The maximum width or height.
*
* @return {IBitmap} The resized image.
*/
resizeMax(maxSize: number): IBitmap;
/**
* Resizes that image by defining a new width by keeping ratio.
*
* @param {Number} newWidth The new width.
*
* @return {IBitmap} The resized image.
*/
resizeWidth(newWidth: number): IBitmap;
/**
* Rotates the image.
*
* @param {number} [degrees] The number of degrees to rotate. Default: 90.
*
* @return {IBitmap} The rotated image.
*/
rotate(degrees?: number): IBitmap;
/**
* Sets a pixel / point.
*
* @chainable
*
* @param {IPoint2D} [coordinates] The coordinate where to draw the point.
* @param {IArgb} [color] The color of the point.
*
* @throws At least one input value is invalid.
*/
setPoint(coordinates?: IPoint2D | string,
color?: string | number | IArgb): IBitmap;
/**
* Gets the size.
*/
size: ISize;
/**
* Converts that image to a Base64 string.
*
* @param {OutputFormat} format The output format. Default is: PNG
* @param {Number} quality A value between 0 (0%) and 100 (100%) for the output quality.
*
* @return {String} The bitmap a Base64 string.
*
* @throws At least one input value is invalid.
*/
toBase64(format?: OutputFormat, quality?: number): string;
/**
* Converts that image to a data URL.
*
* @param {OutputFormat} format The output format. Default is: PNG
* @param {Number} quality A value between 0 (0%) and 100 (100%) for the output quality.
*
* @return {String} The bitmap as data url.
*
* @throws At least one input value is invalid.
*/
toDataUrl(format?: OutputFormat, quality?: number): string;
/**
* Returns that image as ImageSource.
*
* @return {ImageSource} The bitmap as ImageSource.
*/
toImageSource(): ImageSource.ImageSource;
/**
* Converts that image to an object.
*
* @param {OutputFormat} format The output format. Default is: PNG
* @param {Number} quality A value between 0 (0%) and 100 (100%) for the output quality.
*
* @return {IBitmapData} The bitmap as object.
*
* @throws At least one input value is invalid.
*/
toObject(format?: OutputFormat, quality?: number): IBitmapData;
/**
* Writes a text.
*
* @chainable
*
* @param {any} txt The text /value to write.
* @param {IPoint2D} [leftTop] The left/top corner.
* @param {IFont} [font] The custom font to use.
*
* @throws At least one input value is invalid.
*/
writeText(txt: any,
leftTop?: IPoint2D | string, font?: IFont | string): IBitmap;
/**
* Gets the width of the bitmap.
*/
width: number;
}
/**
* Additional options for creating a bitmap.
*/
export interface ICreateBitmapOptions {
/**
* iOS specific options.
*/
ios?: {
/**
* Let iOS auto release the underlying CGImage (true) or let
* the object call CGImageRelease() manually (false).
*
* Default: (true)
*/
autoRelease?: boolean;
},
}
/**
* Returns a value as bitmap object.
*
* @param any v The input value.
* @param {Boolean} [throwException] Throw exception if 'v' is invalid or return (false).
*
* @throws Input value is invalid.
*
* @return {IBitmap} The output value or (false) if input value is invalid.
*/
export function asBitmap(v: any, throwException: boolean = true): IBitmap {
var result = BitmapFactory.asBitmapObject(v);
if (throwException && (false === result)) {
throw "No valid value for a bitmap!";
}
return result;
}
/**
* Creates a new bitmap.
*
* @param {Number} width The width of the new image.
* @param {Number} [height] The optional height of the new image. If not defined, the width is taken as value.
* @param {ICreateBitmapOptions} [opts] Additional options for creating the bitmap.
*
* @return {IBitmap} The new bitmap.
*/
export function create(width: number, height?: number, opts?: ICreateBitmapOptions): IBitmap {
if (TypeUtils.isNullOrUndefined(height)) {
height = width;
}
if (arguments.length < 3) {
opts = getDefaultOptions();
}
if (TypeUtils.isNullOrUndefined(opts)) {
opts = {};
}
return BitmapFactory.createBitmap(width, height, opts);
}
/**
* Returns the default options for creating a new bitmap.
*
* @return {ICreateBitmapOptions} The options.
*/
export function getDefaultOptions(): ICreateBitmapOptions {
let opts = BitmapFactory.getDefaultOpts();
if (!opts) {
opts = {};
}
return opts;
}
/**
* Makes a (native) image / bitmap mutable.
*
* @param {any} v The (native) object.
* @param {IMakeMutableOptions} [opts] The custom options.
*
* @return {any} The mutable object.
*
* @throws Native object is invalid.
*/
export function makeMutable(v: any, opts?: IMakeMutableOptions): any {
if (TypeUtils.isNullOrUndefined(v)) {
return v;
}
if (!opts) {
opts = {};
}
return BitmapFactory.makeBitmapMutable(v, opts);
}
/**
* Sets the default options for creating a new bitmap.
*
* @param {ICreateBitmapOptions} The new options.
*/
export function setDefaultOptions(opts: ICreateBitmapOptions) {
if (!opts) {
opts = {};
}
BitmapFactory.setDefaultOpts(opts);
} | the_stack |
import React, { useCallback, useMemo, useRef, forwardRef, ElementRef, useEffect } from 'react';
import classNames from 'classnames';
import type { TdTreeSelectProps, TreeSelectValue } from './type';
import type { StyledProps } from '../common';
import useConfig from '../_util/useConfig';
import useDefault from '../_util/useDefault';
import Tree, { TreeProps } from '../tree';
import SelectInput, { SelectInputProps } from '../select-input/SelectInput';
import { usePersistFn } from '../_util/usePersistFn';
import useSwitch from '../_util/useSwitch';
import noop from '../_util/noop';
import { useTreeSelectUtils } from './useTreeSelectUtils';
import { SelectArrow } from './SelectArrow';
import { useTreeSelectPassThroughProps } from './useTreeSelectPassthoughProps';
import { useTreeSelectLocale } from './useTreeSelectLocale';
export interface TreeSelectProps extends TdTreeSelectProps, StyledProps {}
export interface NodeOptions {
label: string;
value: string | number;
}
const useMergeFn = <T extends any[]>(...fns: Array<(...args: T) => void>) =>
usePersistFn((...args: T) => fns.forEach((fn) => fn?.(...args)));
const TreeSelect = forwardRef((props: TreeSelectProps, ref: React.Ref<HTMLDivElement>) => {
/* ---------------------------------config---------------------------------------- */
// ๅฝ้
ๅๆๆฌๅๅงๅ
const { placeholder, empty, loadingItem } = useTreeSelectLocale(props);
const { classPrefix } = useConfig();
/* ---------------------------------state---------------------------------------- */
const {
className,
inputValue,
defaultInputValue,
onInputChange,
readonly,
disabled,
multiple,
prefixIcon,
loading,
size,
max,
data,
filter = (text, option) => option.label.includes(text),
filterable: rawFilterable,
onClear,
valueDisplay,
treeProps,
inputProps,
onBlur,
onFocus,
onSearch,
onRemove,
} = props;
const selectInputProps = useTreeSelectPassThroughProps(props);
const [value, onChange] = useDefault(props.value, props.defaultValue ?? multiple ? [] : null, props.onChange);
const [popupVisible, setPopupVisible] = useDefault(props.popupVisible, false, props.onPopupVisibleChange);
const [hover, hoverAction] = useSwitch();
const [filterInput, setFilterInput] = useDefault(inputValue, defaultInputValue, onInputChange);
const treeRef = useRef<ElementRef<typeof Tree>>();
const { normalizeValue, formatValue, getNodeItem } = useTreeSelectUtils(props, treeRef);
/* ---------------------------------computed value---------------------------------------- */
const filterable = rawFilterable || !!props.filter;
const normalizedValue = useMemo(
() =>
(multiple ? (value as TreeSelectValue[]) : [value]).reduce<NodeOptions[]>((result, value) => {
const normalized = normalizeValue(value);
normalized.value && result.push(normalized);
return result;
}, []),
[multiple, normalizeValue, value],
);
const filterText = String(filterInput);
const internalInputValue = useMemo(() => {
if (multiple) return normalizedValue;
// ๅฏ็ญ้ใๅ้ใๅผนๆกๆถๅ
ๅฎนไธบ่ฟๆปคๅผ
return filterable && popupVisible ? filterText : normalizedValue[0];
}, [multiple, normalizedValue, filterable, popupVisible, filterText]);
const inputPlaceholader = useMemo(() => {
// ๅฏ็ญ้ใๅ้ใๅผนๆกไธๆๅผๆถๆ็คบๅฝๅๅผ
if (filterable && !multiple && popupVisible && normalizedValue.length) {
return typeof normalizedValue[0].label === 'string' ? normalizedValue[0].label : String(normalizedValue[0].value);
}
return placeholder;
}, [filterable, multiple, popupVisible, normalizedValue, placeholder]);
const showLoading = !disabled && loading;
// ๅค้ไธ่ฝ่ฟๆปคๆถ้่ฆๅฑ็คบๅ็ placeholder
const showFakePlaceholder = multiple && !filterable && !normalizedValue.length;
/* ---------------------------------handler---------------------------------------- */
const handleFilter = useCallback<TreeProps['filter']>(
(node) => (filterable ? filter(filterText, node) : true),
[filter, filterText, filterable],
);
const handleSingleChange = usePersistFn<TreeProps['onActive']>((value, context) => {
const $value = value.length ? value[0] : null;
onChange(formatValue($value, context.node.label), { ...context, trigger: $value === null ? 'uncheck' : 'check' });
// ๅ้้ๆฉๅๆถ่ตทๅผนๆก
setPopupVisible(false, { trigger: 'trigger-element-click' });
});
const handleMultiChange = usePersistFn<TreeProps['onChange']>((value, context) => {
(max === 0 || value.length <= max) &&
onChange(
value.map((value) => formatValue(value, getNodeItem(value)?.label)),
{ ...context, trigger: value.length > normalizedValue.length ? 'check' : 'uncheck' },
);
});
const handleClear = usePersistFn<SelectInputProps['onClear']>((ctx) => {
ctx.e.stopPropagation();
onChange(multiple ? [] : formatValue(null), {
node: null,
trigger: 'clear',
e: ctx.e as React.MouseEvent<any, any>,
});
onClear?.(ctx);
// ๆธ
็ฉบๅๆถ่ตทๅผนๆก
setPopupVisible(false, { trigger: 'trigger-element-click' });
});
const handleRemove = usePersistFn((index: number, e?: React.MouseEvent<any, any>) => {
const node = getNodeItem(normalizedValue[index].value);
onChange(
normalizedValue.filter((value, i) => i !== index).map(({ value, label }) => formatValue(value, label)),
{ node, trigger: 'tag-remove', e },
);
onRemove?.({ value: node.value, data: { value: node.value, label: node.label }, e });
});
const handleTagChange = usePersistFn<SelectInputProps['onTagChange']>((tags, ctx) => {
switch (ctx.trigger) {
case 'clear':
handleClear({ e: ctx.e as React.MouseEvent<SVGElement, MouseEvent> });
break;
case 'tag-remove':
handleRemove(ctx.index, ctx.e as React.MouseEvent<SVGElement, MouseEvent>);
break;
case 'backspace':
handleRemove(ctx.index);
}
});
const handleBlur = usePersistFn<SelectInputProps['onBlur']>((v, ctx) => {
onBlur?.({ value: multiple ? normalizedValue : normalizedValue[0], e: ctx.e });
});
const handleFocus = usePersistFn<SelectInputProps['onFocus']>((v, ctx) => {
onFocus?.({ value: multiple ? normalizedValue : normalizedValue[0], e: ctx.e });
});
const handleEnter = usePersistFn<SelectInputProps['onEnter']>((text) => {
onSearch?.(text as string);
});
const handleFilterChange = usePersistFn<SelectInputProps['onInputChange']>((value) => setFilterInput(value));
/* ---------------------------------effect---------------------------------------- */
useEffect(() => {
// ๆพ็คบๆถๆธ
็ฉบ่ฟๆปค๏ผ้่ๆถๆธ
็ฉบๆๅจ็ปไผๅฏผ่ด้ชๅจ
popupVisible && setFilterInput('');
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [popupVisible]);
useEffect(() => {
// ้ไธญๅผๆถๆธ
็ฉบ่ฟๆปค้กน
setFilterInput('');
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [value]);
/* ---------------------------------render---------------------------------------- */
const renderTree = () => {
if (readonly) return empty;
if (showLoading) return loadingItem;
return (
<Tree
ref={treeRef}
hover
transition
expandAll
filter={handleFilter}
data={data}
disabled={disabled}
empty={empty}
allowFoldNodeOnFilter={true}
{...(multiple
? {
checkable: true,
onChange: handleMultiChange,
value: normalizedValue.map(({ value }) => value),
}
: {
activable: true,
actived: normalizedValue.map(({ value }) => value),
onActive: handleSingleChange,
})}
{...treeProps}
/>
);
};
const renderCollapsedItems = useMemo(
() =>
props.collapsedItems
? () =>
props.collapsedItems({
value: normalizedValue,
collapsedSelectedItems: normalizedValue.slice(props.minCollapsedNum, normalizedValue.length),
count: normalizedValue.length - props.minCollapsedNum,
})
: null,
[normalizedValue, props],
);
const renderLabel = () =>
showFakePlaceholder ? (
<>
{prefixIcon}
<span className={`${classPrefix}-tree-select--placeholder`}>{placeholder}</span>
</>
) : (
prefixIcon
);
const normalizedValueDisplay = () => {
if (typeof valueDisplay === 'string') return valueDisplay;
if (multiple) return ({ onClose }) => valueDisplay({ value: normalizedValue, onClose });
return normalizedValue.length ? (valueDisplay({ value: normalizedValue[0], onClose: noop }) as string) : '';
};
return (
<SelectInput
{...props.selectInputProps}
{...selectInputProps}
ref={ref}
className={classNames(
`${classPrefix}-tree-select`,
{
[`${classPrefix}-tree-select--without-input`]: multiple && !filterable,
},
className,
)}
value={internalInputValue}
inputValue={popupVisible ? filterText : ''}
panel={renderTree()}
allowInput={multiple || filterable}
inputProps={{ ...inputProps, size }}
tagInputProps={{ size, excessTagsDisplayType: 'break-line', inputProps, tagProps: props.tagProps }}
placeholder={inputPlaceholader}
popupVisible={popupVisible && !disabled}
onInputChange={handleFilterChange}
onPopupVisibleChange={useMergeFn(setPopupVisible)}
onFocus={useMergeFn(handleFocus, () => setPopupVisible(true, { trigger: 'trigger-element-click' }))}
onBlur={useMergeFn(handleBlur)}
onClear={handleClear}
onTagChange={handleTagChange}
onEnter={handleEnter}
onMouseenter={hoverAction.on}
onMouseleave={hoverAction.off}
suffixIcon={
readonly ? null : (
<SelectArrow isActive={popupVisible} isHighlight={hover || popupVisible} disabled={disabled} />
)
}
collapsedItems={renderCollapsedItems}
label={renderLabel()}
valueDisplay={valueDisplay && normalizedValueDisplay()}
/>
);
});
TreeSelect.displayName = 'TreeSelect';
TreeSelect.defaultProps = {
clearable: false,
data: [],
disabled: false,
filterable: false,
loading: false,
max: 0,
multiple: false,
size: 'medium',
valueType: 'value',
minCollapsedNum: 0,
};
export default TreeSelect; | the_stack |
import { ApplicationOptions } from './parameterized-operations-client';
import { Collection } from './collection';
import { Application } from './models/Application';
import { Response } from 'node-fetch';
import { Csr } from './models/Csr';
import { CsrMetadataOptions } from './models/CsrMetadata';
import { JsonWebKey } from './models/JsonWebKey';
import { OAuth2ScopeConsentGrant } from './models/OAuth2ScopeConsentGrant';
import { OAuth2ScopeConsentGrantOptions } from './models/OAuth2ScopeConsentGrant';
import { ApplicationGroupAssignment } from './models/ApplicationGroupAssignment';
import { ApplicationGroupAssignmentOptions } from './models/ApplicationGroupAssignment';
import { OAuth2Token } from './models/OAuth2Token';
import { AppUser } from './models/AppUser';
import { AppUserOptions } from './models/AppUser';
import { AuthorizationServer } from './models/AuthorizationServer';
import { AuthorizationServerOptions } from './models/AuthorizationServer';
import { OAuth2Claim } from './models/OAuth2Claim';
import { OAuth2ClaimOptions } from './models/OAuth2Claim';
import { OAuth2Client } from './models/OAuth2Client';
import { OAuth2RefreshToken } from './models/OAuth2RefreshToken';
import { JwkUseOptions } from './models/JwkUse';
import { AuthorizationServerPolicy } from './models/AuthorizationServerPolicy';
import { AuthorizationServerPolicyOptions } from './models/AuthorizationServerPolicy';
import { AuthorizationServerPolicyRule } from './models/AuthorizationServerPolicyRule';
import { AuthorizationServerPolicyRuleOptions } from './models/AuthorizationServerPolicyRule';
import { OAuth2Scope } from './models/OAuth2Scope';
import { OAuth2ScopeOptions } from './models/OAuth2Scope';
import { DomainListResponse } from './models/DomainListResponse';
import { DomainOptions } from './models/Domain';
import { Domain } from './models/Domain';
import { DomainCertificateOptions } from './models/DomainCertificate';
import { EventHook } from './models/EventHook';
import { EventHookOptions } from './models/EventHook';
import { Feature } from './models/Feature';
import { Group } from './models/Group';
import { GroupOptions } from './models/Group';
import { GroupRule } from './models/GroupRule';
import { GroupRuleOptions } from './models/GroupRule';
import { Role } from './models/Role';
import { AssignRoleRequestOptions } from './models/AssignRoleRequest';
import { CatalogApplication } from './models/CatalogApplication';
import { User } from './models/User';
import { IdentityProvider } from './models/IdentityProvider';
import { IdentityProviderOptions } from './models/IdentityProvider';
import { JsonWebKeyOptions } from './models/JsonWebKey';
import { IdentityProviderApplicationUser } from './models/IdentityProviderApplicationUser';
import { UserIdentityProviderLinkRequestOptions } from './models/UserIdentityProviderLinkRequest';
import { SocialAuthToken } from './models/SocialAuthToken';
import { InlineHook } from './models/InlineHook';
import { InlineHookOptions } from './models/InlineHook';
import { InlineHookPayloadOptions } from './models/InlineHookPayload';
import { InlineHookResponse } from './models/InlineHookResponse';
import { LogEvent } from './models/LogEvent';
import { ProfileMapping } from './models/ProfileMapping';
import { ProfileMappingOptions } from './models/ProfileMapping';
import { UserSchema } from './models/UserSchema';
import { UserSchemaOptions } from './models/UserSchema';
import { GroupSchema } from './models/GroupSchema';
import { GroupSchemaOptions } from './models/GroupSchema';
import { LinkedObject } from './models/LinkedObject';
import { LinkedObjectOptions } from './models/LinkedObject';
import { UserType } from './models/UserType';
import { UserTypeOptions } from './models/UserType';
import { OrgSetting } from './models/OrgSetting';
import { OrgSettingOptions } from './models/OrgSetting';
import { OrgContactTypeObj } from './models/OrgContactTypeObj';
import { OrgContactUser } from './models/OrgContactUser';
import { UserIdStringOptions } from './models/UserIdString';
import { OrgPreferences } from './models/OrgPreferences';
import { OrgOktaCommunicationSetting } from './models/OrgOktaCommunicationSetting';
import { OrgOktaSupportSettingsObj } from './models/OrgOktaSupportSettingsObj';
import { Policy } from './models/Policy';
import { PolicyOptions } from './models/Policy';
import { PolicyRule } from './models/PolicyRule';
import { PolicyRuleOptions } from './models/PolicyRule';
import { CreateSessionRequestOptions } from './models/CreateSessionRequest';
import { Session } from './models/Session';
import { SmsTemplate } from './models/SmsTemplate';
import { SmsTemplateOptions } from './models/SmsTemplate';
import { ThreatInsightConfiguration } from './models/ThreatInsightConfiguration';
import { ThreatInsightConfigurationOptions } from './models/ThreatInsightConfiguration';
import { TrustedOrigin } from './models/TrustedOrigin';
import { TrustedOriginOptions } from './models/TrustedOrigin';
import { CreateUserRequestOptions } from './models/CreateUserRequest';
import { UserOptions } from './models/User';
import { AppLink } from './models/AppLink';
import { ChangePasswordRequestOptions } from './models/ChangePasswordRequest';
import { UserCredentials } from './models/UserCredentials';
import { UserCredentialsOptions } from './models/UserCredentials';
import { ForgotPasswordResponse } from './models/ForgotPasswordResponse';
import { UserFactor } from './models/UserFactor';
import { UserFactorOptions } from './models/UserFactor';
import { SecurityQuestion } from './models/SecurityQuestion';
import { ActivateFactorRequestOptions } from './models/ActivateFactorRequest';
import { VerifyUserFactorResponse } from './models/VerifyUserFactorResponse';
import { VerifyFactorRequestOptions } from './models/VerifyFactorRequest';
import { UserActivationToken } from './models/UserActivationToken';
import { TempPassword } from './models/TempPassword';
import { ResetPasswordToken } from './models/ResetPasswordToken';
import { ResponseLinks } from './models/ResponseLinks';
import { NetworkZone } from './models/NetworkZone';
import { NetworkZoneOptions } from './models/NetworkZone';
export declare class GeneratedApiClient {
listApplications(queryParameters?: {
q?: string,
after?: string,
limit?: number,
filter?: string,
expand?: string,
includeNonDeleted?: boolean,
}): Collection<Application>;
createApplication(application: ApplicationOptions, queryParameters?: {
activate?: boolean,
}): Promise<Application>;
deleteApplication(appId: string): Promise<Response>;
getApplication(appId: string, queryParameters?: {
expand?: string,
}): Promise<Application>;
updateApplication(appId: string, application: ApplicationOptions): Promise<Application>;
listCsrsForApplication(appId: string): Collection<Csr>;
generateCsrForApplication(appId: string, csrMetadata: CsrMetadataOptions): Promise<Csr>;
revokeCsrFromApplication(appId: string, csrId: string): Promise<Response>;
getCsrForApplication(appId: string, csrId: string): Promise<Csr>;
publishCerCert(appId: string, csrId: string, certificate: string): Promise<JsonWebKey>;
publishBinaryCerCert(appId: string, csrId: string, certificate: string): Promise<JsonWebKey>;
publishDerCert(appId: string, csrId: string, certificate: string): Promise<JsonWebKey>;
publishBinaryDerCert(appId: string, csrId: string, certificate: string): Promise<JsonWebKey>;
publishBinaryPemCert(appId: string, csrId: string, certificate: string): Promise<JsonWebKey>;
listApplicationKeys(appId: string): Collection<JsonWebKey>;
generateApplicationKey(appId: string, queryParameters?: {
validityYears?: number,
}): Promise<JsonWebKey>;
getApplicationKey(appId: string, keyId: string): Promise<JsonWebKey>;
cloneApplicationKey(appId: string, keyId: string, queryParameters: {
targetAid: string,
}): Promise<JsonWebKey>;
listScopeConsentGrants(appId: string, queryParameters?: {
expand?: string,
}): Collection<OAuth2ScopeConsentGrant>;
grantConsentToScope(appId: string, oAuth2ScopeConsentGrant: OAuth2ScopeConsentGrantOptions): Promise<OAuth2ScopeConsentGrant>;
revokeScopeConsentGrant(appId: string, grantId: string): Promise<Response>;
getScopeConsentGrant(appId: string, grantId: string, queryParameters?: {
expand?: string,
}): Promise<OAuth2ScopeConsentGrant>;
listApplicationGroupAssignments(appId: string, queryParameters?: {
q?: string,
after?: string,
limit?: number,
expand?: string,
}): Collection<ApplicationGroupAssignment>;
deleteApplicationGroupAssignment(appId: string, groupId: string): Promise<Response>;
getApplicationGroupAssignment(appId: string, groupId: string, queryParameters?: {
expand?: string,
}): Promise<ApplicationGroupAssignment>;
createApplicationGroupAssignment(appId: string, groupId: string, applicationGroupAssignment?: ApplicationGroupAssignmentOptions): Promise<ApplicationGroupAssignment>;
activateApplication(appId: string): Promise<Response>;
deactivateApplication(appId: string): Promise<Response>;
revokeOAuth2TokensForApplication(appId: string): Promise<Response>;
listOAuth2TokensForApplication(appId: string, queryParameters?: {
expand?: string,
after?: string,
limit?: number,
}): Collection<OAuth2Token>;
revokeOAuth2TokenForApplication(appId: string, tokenId: string): Promise<Response>;
getOAuth2TokenForApplication(appId: string, tokenId: string, queryParameters?: {
expand?: string,
}): Promise<OAuth2Token>;
listApplicationUsers(appId: string, queryParameters?: {
q?: string,
query_scope?: string,
after?: string,
limit?: number,
filter?: string,
expand?: string,
}): Collection<AppUser>;
assignUserToApplication(appId: string, appUser: AppUserOptions): Promise<AppUser>;
deleteApplicationUser(appId: string, userId: string, queryParameters?: {
sendEmail?: boolean,
}): Promise<Response>;
getApplicationUser(appId: string, userId: string, queryParameters?: {
expand?: string,
}): Promise<AppUser>;
updateApplicationUser(appId: string, userId: string, appUser: AppUserOptions): Promise<AppUser>;
listAuthorizationServers(queryParameters?: {
q?: string,
limit?: string,
after?: string,
}): Collection<AuthorizationServer>;
createAuthorizationServer(authorizationServer: AuthorizationServerOptions): Promise<AuthorizationServer>;
deleteAuthorizationServer(authServerId: string): Promise<Response>;
getAuthorizationServer(authServerId: string): Promise<AuthorizationServer>;
updateAuthorizationServer(authServerId: string, authorizationServer: AuthorizationServerOptions): Promise<AuthorizationServer>;
listOAuth2Claims(authServerId: string): Collection<OAuth2Claim>;
createOAuth2Claim(authServerId: string, oAuth2Claim: OAuth2ClaimOptions): Promise<OAuth2Claim>;
deleteOAuth2Claim(authServerId: string, claimId: string): Promise<Response>;
getOAuth2Claim(authServerId: string, claimId: string): Promise<OAuth2Claim>;
updateOAuth2Claim(authServerId: string, claimId: string, oAuth2Claim: OAuth2ClaimOptions): Promise<OAuth2Claim>;
listOAuth2ClientsForAuthorizationServer(authServerId: string): Collection<OAuth2Client>;
revokeRefreshTokensForAuthorizationServerAndClient(authServerId: string, clientId: string): Promise<Response>;
listRefreshTokensForAuthorizationServerAndClient(authServerId: string, clientId: string, queryParameters?: {
expand?: string,
after?: string,
limit?: number,
}): Collection<OAuth2RefreshToken>;
revokeRefreshTokenForAuthorizationServerAndClient(authServerId: string, clientId: string, tokenId: string): Promise<Response>;
getRefreshTokenForAuthorizationServerAndClient(authServerId: string, clientId: string, tokenId: string, queryParameters?: {
expand?: string,
}): Promise<OAuth2RefreshToken>;
listAuthorizationServerKeys(authServerId: string): Collection<JsonWebKey>;
rotateAuthorizationServerKeys(authServerId: string, jwkUse: JwkUseOptions): Collection<JsonWebKey>;
activateAuthorizationServer(authServerId: string): Promise<Response>;
deactivateAuthorizationServer(authServerId: string): Promise<Response>;
listAuthorizationServerPolicies(authServerId: string): Collection<AuthorizationServerPolicy>;
createAuthorizationServerPolicy(authServerId: string, authorizationServerPolicy: AuthorizationServerPolicyOptions): Promise<AuthorizationServerPolicy>;
deleteAuthorizationServerPolicy(authServerId: string, policyId: string): Promise<Response>;
getAuthorizationServerPolicy(authServerId: string, policyId: string): Promise<AuthorizationServerPolicy>;
updateAuthorizationServerPolicy(authServerId: string, policyId: string, authorizationServerPolicy: AuthorizationServerPolicyOptions): Promise<AuthorizationServerPolicy>;
activateAuthorizationServerPolicy(authServerId: string, policyId: string): Promise<Response>;
deactivateAuthorizationServerPolicy(authServerId: string, policyId: string): Promise<Response>;
listAuthorizationServerPolicyRules(policyId: string, authServerId: string): Collection<AuthorizationServerPolicyRule>;
createAuthorizationServerPolicyRule(policyId: string, authServerId: string, authorizationServerPolicyRule: AuthorizationServerPolicyRuleOptions): Promise<AuthorizationServerPolicyRule>;
deleteAuthorizationServerPolicyRule(policyId: string, authServerId: string, ruleId: string): Promise<Response>;
getAuthorizationServerPolicyRule(policyId: string, authServerId: string, ruleId: string): Promise<AuthorizationServerPolicyRule>;
updateAuthorizationServerPolicyRule(policyId: string, authServerId: string, ruleId: string, authorizationServerPolicyRule: AuthorizationServerPolicyRuleOptions): Promise<AuthorizationServerPolicyRule>;
activateAuthorizationServerPolicyRule(authServerId: string, policyId: string, ruleId: string): Promise<Response>;
deactivateAuthorizationServerPolicyRule(authServerId: string, policyId: string, ruleId: string): Promise<Response>;
listOAuth2Scopes(authServerId: string, queryParameters?: {
q?: string,
filter?: string,
cursor?: string,
limit?: number,
}): Collection<OAuth2Scope>;
createOAuth2Scope(authServerId: string, oAuth2Scope: OAuth2ScopeOptions): Promise<OAuth2Scope>;
deleteOAuth2Scope(authServerId: string, scopeId: string): Promise<Response>;
getOAuth2Scope(authServerId: string, scopeId: string): Promise<OAuth2Scope>;
updateOAuth2Scope(authServerId: string, scopeId: string, oAuth2Scope: OAuth2ScopeOptions): Promise<OAuth2Scope>;
listDomains(): Promise<DomainListResponse>;
createDomain(domain: DomainOptions): Promise<Domain>;
deleteDomain(domainId: string): Promise<Response>;
getDomain(domainId: string): Promise<Domain>;
createCertificate(domainId: string, domainCertificate: DomainCertificateOptions): Promise<Response>;
verifyDomain(domainId: string): Promise<Domain>;
listEventHooks(): Collection<EventHook>;
createEventHook(eventHook: EventHookOptions): Promise<EventHook>;
deleteEventHook(eventHookId: string): Promise<Response>;
getEventHook(eventHookId: string): Promise<EventHook>;
updateEventHook(eventHookId: string, eventHook: EventHookOptions): Promise<EventHook>;
activateEventHook(eventHookId: string): Promise<EventHook>;
deactivateEventHook(eventHookId: string): Promise<EventHook>;
verifyEventHook(eventHookId: string): Promise<EventHook>;
listFeatures(): Collection<Feature>;
getFeature(featureId: string): Promise<Feature>;
listFeatureDependencies(featureId: string): Collection<Feature>;
listFeatureDependents(featureId: string): Collection<Feature>;
updateFeatureLifecycle(featureId: string, lifecycle: string, queryParameters?: {
mode?: string,
}): Promise<Feature>;
listGroups(queryParameters?: {
q?: string,
search?: string,
after?: string,
limit?: number,
expand?: string,
}): Collection<Group>;
createGroup(group: GroupOptions): Promise<Group>;
listGroupRules(queryParameters?: {
limit?: number,
after?: string,
search?: string,
expand?: string,
}): Collection<GroupRule>;
createGroupRule(groupRule: GroupRuleOptions): Promise<GroupRule>;
deleteGroupRule(ruleId: string, queryParameters?: {
removeUsers?: boolean,
}): Promise<Response>;
getGroupRule(ruleId: string, queryParameters?: {
expand?: string,
}): Promise<GroupRule>;
updateGroupRule(ruleId: string, groupRule: GroupRuleOptions): Promise<GroupRule>;
activateGroupRule(ruleId: string): Promise<Response>;
deactivateGroupRule(ruleId: string): Promise<Response>;
deleteGroup(groupId: string): Promise<Response>;
getGroup(groupId: string): Promise<Group>;
updateGroup(groupId: string, group: GroupOptions): Promise<Group>;
listAssignedApplicationsForGroup(groupId: string, queryParameters?: {
after?: string,
limit?: number,
}): Collection<Application>;
listGroupAssignedRoles(groupId: string, queryParameters?: {
expand?: string,
}): Collection<Role>;
assignRoleToGroup(groupId: string, assignRoleRequest: AssignRoleRequestOptions, queryParameters?: {
disableNotifications?: string,
}): Promise<Role>;
removeRoleFromGroup(groupId: string, roleId: string): Promise<Response>;
getRole(groupId: string, roleId: string): Promise<Role>;
listApplicationTargetsForApplicationAdministratorRoleForGroup(groupId: string, roleId: string, queryParameters?: {
after?: string,
limit?: number,
}): Collection<CatalogApplication>;
removeApplicationTargetFromApplicationAdministratorRoleGivenToGroup(groupId: string, roleId: string, appName: string): Promise<Response>;
addApplicationTargetToAdminRoleGivenToGroup(groupId: string, roleId: string, appName: string): Promise<Response>;
removeApplicationTargetFromAdministratorRoleGivenToGroup(groupId: string, roleId: string, appName: string, applicationId: string): Promise<Response>;
addApplicationInstanceTargetToAppAdminRoleGivenToGroup(groupId: string, roleId: string, appName: string, applicationId: string): Promise<Response>;
listGroupTargetsForGroupRole(groupId: string, roleId: string, queryParameters?: {
after?: string,
limit?: number,
}): Collection<Group>;
removeGroupTargetFromGroupAdministratorRoleGivenToGroup(groupId: string, roleId: string, targetGroupId: string): Promise<Response>;
addGroupTargetToGroupAdministratorRoleForGroup(groupId: string, roleId: string, targetGroupId: string): Promise<Response>;
listGroupUsers(groupId: string, queryParameters?: {
after?: string,
limit?: number,
}): Collection<User>;
removeUserFromGroup(groupId: string, userId: string): Promise<Response>;
addUserToGroup(groupId: string, userId: string): Promise<Response>;
listIdentityProviders(queryParameters?: {
q?: string,
after?: string,
limit?: number,
type?: string,
}): Collection<IdentityProvider>;
createIdentityProvider(identityProvider: IdentityProviderOptions): Promise<IdentityProvider>;
listIdentityProviderKeys(queryParameters?: {
after?: string,
limit?: number,
}): Collection<JsonWebKey>;
createIdentityProviderKey(jsonWebKey: JsonWebKeyOptions): Promise<JsonWebKey>;
deleteIdentityProviderKey(keyId: string): Promise<Response>;
getIdentityProviderKey(keyId: string): Promise<JsonWebKey>;
deleteIdentityProvider(idpId: string): Promise<Response>;
getIdentityProvider(idpId: string): Promise<IdentityProvider>;
updateIdentityProvider(idpId: string, identityProvider: IdentityProviderOptions): Promise<IdentityProvider>;
listCsrsForIdentityProvider(idpId: string): Collection<Csr>;
generateCsrForIdentityProvider(idpId: string, csrMetadata: CsrMetadataOptions): Promise<Csr>;
revokeCsrForIdentityProvider(idpId: string, csrId: string): Promise<Response>;
getCsrForIdentityProvider(idpId: string, csrId: string): Promise<Csr>;
publishCerCertForIdentityProvider(idpId: string, csrId: string, certificate: string): Promise<JsonWebKey>;
publishBinaryCerCertForIdentityProvider(idpId: string, csrId: string, certificate: string): Promise<JsonWebKey>;
publishDerCertForIdentityProvider(idpId: string, csrId: string, certificate: string): Promise<JsonWebKey>;
publishBinaryDerCertForIdentityProvider(idpId: string, csrId: string, certificate: string): Promise<JsonWebKey>;
publishBinaryPemCertForIdentityProvider(idpId: string, csrId: string, certificate: string): Promise<JsonWebKey>;
listIdentityProviderSigningKeys(idpId: string): Collection<JsonWebKey>;
generateIdentityProviderSigningKey(idpId: string, queryParameters: {
validityYears: number,
}): Promise<JsonWebKey>;
getIdentityProviderSigningKey(idpId: string, keyId: string): Promise<JsonWebKey>;
cloneIdentityProviderKey(idpId: string, keyId: string, queryParameters: {
targetIdpId: string,
}): Promise<JsonWebKey>;
activateIdentityProvider(idpId: string): Promise<IdentityProvider>;
deactivateIdentityProvider(idpId: string): Promise<IdentityProvider>;
listIdentityProviderApplicationUsers(idpId: string): Collection<IdentityProviderApplicationUser>;
unlinkUserFromIdentityProvider(idpId: string, userId: string): Promise<Response>;
getIdentityProviderApplicationUser(idpId: string, userId: string): Promise<IdentityProviderApplicationUser>;
linkUserToIdentityProvider(idpId: string, userId: string, userIdentityProviderLinkRequest: UserIdentityProviderLinkRequestOptions): Promise<IdentityProviderApplicationUser>;
listSocialAuthTokens(idpId: string, userId: string): Collection<SocialAuthToken>;
listInlineHooks(queryParameters?: {
type?: string,
}): Collection<InlineHook>;
createInlineHook(inlineHook: InlineHookOptions): Promise<InlineHook>;
deleteInlineHook(inlineHookId: string): Promise<Response>;
getInlineHook(inlineHookId: string): Promise<InlineHook>;
updateInlineHook(inlineHookId: string, inlineHook: InlineHookOptions): Promise<InlineHook>;
executeInlineHook(inlineHookId: string, inlineHookPayload: InlineHookPayloadOptions): Promise<InlineHookResponse>;
activateInlineHook(inlineHookId: string): Promise<InlineHook>;
deactivateInlineHook(inlineHookId: string): Promise<InlineHook>;
getLogs(queryParameters?: {
since?: string,
until?: string,
filter?: string,
q?: string,
limit?: number,
sortOrder?: string,
after?: string,
}): Collection<LogEvent>;
listProfileMappings(queryParameters?: {
after?: string,
limit?: number,
sourceId?: string,
targetId?: string,
}): Collection<ProfileMapping>;
getProfileMapping(mappingId: string): Promise<ProfileMapping>;
updateProfileMapping(mappingId: string, profileMapping: ProfileMappingOptions): Promise<ProfileMapping>;
getApplicationUserSchema(appInstanceId: string): Promise<UserSchema>;
updateApplicationUserProfile(appInstanceId: string, userSchema?: UserSchemaOptions): Promise<UserSchema>;
getGroupSchema(): Promise<GroupSchema>;
updateGroupSchema(groupSchema?: GroupSchemaOptions): Promise<GroupSchema>;
listLinkedObjectDefinitions(): Collection<LinkedObject>;
addLinkedObjectDefinition(linkedObject: LinkedObjectOptions): Promise<LinkedObject>;
deleteLinkedObjectDefinition(linkedObjectName: string): Promise<Response>;
getLinkedObjectDefinition(linkedObjectName: string): Promise<LinkedObject>;
getUserSchema(schemaId: string): Promise<UserSchema>;
updateUserProfile(schemaId: string, userSchema: UserSchemaOptions): Promise<UserSchema>;
listUserTypes(): Collection<UserType>;
createUserType(userType: UserTypeOptions): Promise<UserType>;
deleteUserType(typeId: string): Promise<Response>;
getUserType(typeId: string): Promise<UserType>;
updateUserType(typeId: string, userType: UserTypeOptions): Promise<UserType>;
replaceUserType(typeId: string, userType: UserTypeOptions): Promise<UserType>;
getOrgSettings(): Promise<OrgSetting>;
partialUpdateOrgSetting(orgSetting: OrgSettingOptions): Promise<OrgSetting>;
updateOrgSetting(orgSetting: OrgSettingOptions): Promise<OrgSetting>;
getOrgContactTypes(): Collection<OrgContactTypeObj>;
getOrgContactUser(contactType: string): Promise<OrgContactUser>;
updateOrgContactUser(contactType: string, userIdString: UserIdStringOptions): Promise<OrgContactUser>;
getOrgPreferences(): Promise<OrgPreferences>;
hideOktaUIFooter(): Promise<OrgPreferences>;
showOktaUIFooter(): Promise<OrgPreferences>;
getOktaCommunicationSettings(): Promise<OrgOktaCommunicationSetting>;
optInUsersToOktaCommunicationEmails(): Promise<OrgOktaCommunicationSetting>;
optOutUsersFromOktaCommunicationEmails(): Promise<OrgOktaCommunicationSetting>;
getOrgOktaSupportSettings(): Promise<OrgOktaSupportSettingsObj>;
extendOktaSupport(): Promise<OrgOktaSupportSettingsObj>;
grantOktaSupport(): Promise<OrgOktaSupportSettingsObj>;
revokeOktaSupport(): Promise<OrgOktaSupportSettingsObj>;
listPolicies(queryParameters: {
type: string,
status?: string,
expand?: string,
}): Collection<Policy>;
createPolicy(policy: PolicyOptions, queryParameters?: {
activate?: boolean,
}): Promise<Policy>;
deletePolicy(policyId: string): Promise<Response>;
getPolicy(policyId: string, queryParameters?: {
expand?: string,
}): Promise<Policy>;
updatePolicy(policyId: string, policy: PolicyOptions): Promise<Policy>;
activatePolicy(policyId: string): Promise<Response>;
deactivatePolicy(policyId: string): Promise<Response>;
listPolicyRules(policyId: string): Collection<PolicyRule>;
createPolicyRule(policyId: string, policyRule: PolicyRuleOptions): Promise<PolicyRule>;
deletePolicyRule(policyId: string, ruleId: string): Promise<Response>;
getPolicyRule(policyId: string, ruleId: string): Promise<PolicyRule>;
updatePolicyRule(policyId: string, ruleId: string, policyRule: PolicyRuleOptions): Promise<PolicyRule>;
activatePolicyRule(policyId: string, ruleId: string): Promise<Response>;
deactivatePolicyRule(policyId: string, ruleId: string): Promise<Response>;
createSession(createSessionRequest: CreateSessionRequestOptions): Promise<Session>;
endSession(sessionId: string): Promise<Response>;
getSession(sessionId: string): Promise<Session>;
refreshSession(sessionId: string): Promise<Session>;
listSmsTemplates(queryParameters?: {
templateType?: string,
}): Collection<SmsTemplate>;
createSmsTemplate(smsTemplate: SmsTemplateOptions): Promise<SmsTemplate>;
deleteSmsTemplate(templateId: string): Promise<Response>;
getSmsTemplate(templateId: string): Promise<SmsTemplate>;
partialUpdateSmsTemplate(templateId: string, smsTemplate: SmsTemplateOptions): Promise<SmsTemplate>;
updateSmsTemplate(templateId: string, smsTemplate: SmsTemplateOptions): Promise<SmsTemplate>;
getCurrentConfiguration(): Promise<ThreatInsightConfiguration>;
updateConfiguration(threatInsightConfiguration: ThreatInsightConfigurationOptions): Promise<ThreatInsightConfiguration>;
listOrigins(queryParameters?: {
q?: string,
filter?: string,
after?: string,
limit?: number,
}): Collection<TrustedOrigin>;
createOrigin(trustedOrigin: TrustedOriginOptions): Promise<TrustedOrigin>;
deleteOrigin(trustedOriginId: string): Promise<Response>;
getOrigin(trustedOriginId: string): Promise<TrustedOrigin>;
updateOrigin(trustedOriginId: string, trustedOrigin: TrustedOriginOptions): Promise<TrustedOrigin>;
activateOrigin(trustedOriginId: string): Promise<TrustedOrigin>;
deactivateOrigin(trustedOriginId: string): Promise<TrustedOrigin>;
listUsers(queryParameters?: {
q?: string,
after?: string,
limit?: number,
filter?: string,
search?: string,
sortBy?: string,
sortOrder?: string,
}): Collection<User>;
createUser(createUserRequest: CreateUserRequestOptions, queryParameters?: {
activate?: boolean,
provider?: boolean,
nextLogin?: string,
}): Promise<User>;
setLinkedObjectForUser(associatedUserId: string, primaryRelationshipName: string, primaryUserId: string): Promise<Response>;
deactivateOrDeleteUser(userId: string, queryParameters?: {
sendEmail?: boolean,
}): Promise<Response>;
getUser(userId: string): Promise<User>;
partialUpdateUser(userId: string, user: UserOptions, queryParameters?: {
strict?: boolean,
}): Promise<User>;
updateUser(userId: string, user: UserOptions, queryParameters?: {
strict?: boolean,
}): Promise<User>;
listAppLinks(userId: string): Collection<AppLink>;
listUserClients(userId: string): Collection<OAuth2Client>;
revokeGrantsForUserAndClient(userId: string, clientId: string): Promise<Response>;
listGrantsForUserAndClient(userId: string, clientId: string, queryParameters?: {
expand?: string,
after?: string,
limit?: number,
}): Collection<OAuth2ScopeConsentGrant>;
revokeTokensForUserAndClient(userId: string, clientId: string): Promise<Response>;
listRefreshTokensForUserAndClient(userId: string, clientId: string, queryParameters?: {
expand?: string,
after?: string,
limit?: number,
}): Collection<OAuth2RefreshToken>;
revokeTokenForUserAndClient(userId: string, clientId: string, tokenId: string): Promise<Response>;
getRefreshTokenForUserAndClient(userId: string, clientId: string, tokenId: string, queryParameters?: {
expand?: string,
limit?: number,
after?: string,
}): Promise<OAuth2RefreshToken>;
changePassword(userId: string, changePasswordRequest: ChangePasswordRequestOptions, queryParameters?: {
strict?: boolean,
}): Promise<UserCredentials>;
changeRecoveryQuestion(userId: string, userCredentials: UserCredentialsOptions): Promise<UserCredentials>;
forgotPasswordGenerateOneTimeToken(userId: string, queryParameters?: {
sendEmail?: boolean,
}): Promise<ForgotPasswordResponse>;
forgotPasswordSetNewPassword(userId: string, userCredentials: UserCredentialsOptions, queryParameters?: {
sendEmail?: boolean,
}): Promise<ForgotPasswordResponse>;
listFactors(userId: string): Collection<UserFactor>;
enrollFactor(userId: string, userFactor: UserFactorOptions, queryParameters?: {
updatePhone?: boolean,
templateId?: string,
tokenLifetimeSeconds?: number,
activate?: boolean,
}): Promise<UserFactor>;
listSupportedFactors(userId: string): Collection<UserFactor>;
listSupportedSecurityQuestions(userId: string): Collection<SecurityQuestion>;
deleteFactor(userId: string, factorId: string): Promise<Response>;
getFactor(userId: string, factorId: string): Promise<UserFactor>;
activateFactor(userId: string, factorId: string, activateFactorRequest?: ActivateFactorRequestOptions): Promise<UserFactor>;
getFactorTransactionStatus(userId: string, factorId: string, transactionId: string): Promise<VerifyUserFactorResponse>;
verifyFactor(userId: string, factorId: string, verifyFactorRequest?: VerifyFactorRequestOptions, queryParameters?: {
templateId?: string,
tokenLifetimeSeconds?: number,
}): Promise<VerifyUserFactorResponse>;
revokeUserGrants(userId: string): Promise<Response>;
listUserGrants(userId: string, queryParameters?: {
scopeId?: string,
expand?: string,
after?: string,
limit?: number,
}): Collection<OAuth2ScopeConsentGrant>;
revokeUserGrant(userId: string, grantId: string): Promise<Response>;
getUserGrant(userId: string, grantId: string, queryParameters?: {
expand?: string,
}): Promise<OAuth2ScopeConsentGrant>;
listUserGroups(userId: string): Collection<Group>;
listUserIdentityProviders(userId: string): Collection<IdentityProvider>;
activateUser(userId: string, queryParameters: {
sendEmail: boolean,
}): Promise<UserActivationToken>;
deactivateUser(userId: string, queryParameters?: {
sendEmail?: boolean,
}): Promise<Response>;
expirePassword(userId: string): Promise<User>;
expirePasswordAndGetTemporaryPassword(userId: string): Promise<TempPassword>;
reactivateUser(userId: string, queryParameters?: {
sendEmail?: boolean,
}): Promise<UserActivationToken>;
resetFactors(userId: string): Promise<Response>;
resetPassword(userId: string, queryParameters: {
sendEmail: boolean,
}): Promise<ResetPasswordToken>;
suspendUser(userId: string): Promise<Response>;
unlockUser(userId: string): Promise<Response>;
unsuspendUser(userId: string): Promise<Response>;
removeLinkedObjectForUser(userId: string, relationshipName: string): Promise<Response>;
getLinkedObjectsForUser(userId: string, relationshipName: string, queryParameters?: {
after?: string,
limit?: number,
}): Collection<ResponseLinks>;
listAssignedRolesForUser(userId: string, queryParameters?: {
expand?: string,
}): Collection<Role>;
assignRoleToUser(userId: string, assignRoleRequest: AssignRoleRequestOptions, queryParameters?: {
disableNotifications?: string,
}): Promise<Role>;
removeRoleFromUser(userId: string, roleId: string): Promise<Response>;
getUserRole(userId: string, roleId: string): Promise<Role>;
listApplicationTargetsForApplicationAdministratorRoleForUser(userId: string, roleId: string, queryParameters?: {
after?: string,
limit?: number,
}): Collection<CatalogApplication>;
addAllAppsAsTargetToRole(userId: string, roleId: string): Promise<Response>;
removeApplicationTargetFromApplicationAdministratorRoleForUser(userId: string, roleId: string, appName: string): Promise<Response>;
addApplicationTargetToAdminRoleForUser(userId: string, roleId: string, appName: string): Promise<Response>;
removeApplicationTargetFromAdministratorRoleForUser(userId: string, roleId: string, appName: string, applicationId: string): Promise<Response>;
addApplicationTargetToAppAdminRoleForUser(userId: string, roleId: string, appName: string, applicationId: string): Promise<Response>;
listGroupTargetsForRole(userId: string, roleId: string, queryParameters?: {
after?: string,
limit?: number,
}): Collection<Group>;
removeGroupTargetFromRole(userId: string, roleId: string, groupId: string): Promise<Response>;
addGroupTargetToRole(userId: string, roleId: string, groupId: string): Promise<Response>;
clearUserSessions(userId: string, queryParameters?: {
oauthTokens?: boolean,
}): Promise<Response>;
listNetworkZones(queryParameters?: {
after?: string,
limit?: number,
filter?: string,
}): Collection<NetworkZone>;
createNetworkZone(networkZone: NetworkZoneOptions): Promise<NetworkZone>;
deleteNetworkZone(zoneId: string): Promise<Response>;
getNetworkZone(zoneId: string): Promise<NetworkZone>;
updateNetworkZone(zoneId: string, networkZone: NetworkZoneOptions): Promise<NetworkZone>;
activateNetworkZone(zoneId: string): Promise<NetworkZone>;
deactivateNetworkZone(zoneId: string): Promise<NetworkZone>;
} | the_stack |
import BoxClient from '../box-client';
import urlPath from '../util/url-path';
// -----------------------------------------------------------------------------
// Typedefs
// -----------------------------------------------------------------------------
/**
* Enum of valid access levels for groups, which are used to specify who can
* perform certain actions on the group.
* @enum {GroupAccessLevel}
*/
enum GroupAccessLevel {
ADMINS = 'admins_only',
MEMBERS = 'admins_and_members',
ALL_USERS = 'all_managed_users',
}
/**
* Enum of valid user roles within a group
* @enum {GroupUserRole}
*/
enum GroupUserRole {
MEMBER = 'member',
ADMIN = 'admin',
}
// -----------------------------------------------------------------------------
// Private
// -----------------------------------------------------------------------------
const BASE_PATH = '/groups',
MEMBERSHIPS_PATH = '/group_memberships',
MEMBERSHIPS_SUBRESOURCE = 'memberships',
COLLABORATIONS_SUBRESOURCE = 'collaborations';
// -----------------------------------------------------------------------------
// Public
// -----------------------------------------------------------------------------
/**
* Simple manager for interacting with all 'Groups' endpoints and actions.
*
* @constructor
* @param {BoxClient} client - The Box API Client that is responsible for making calls to the API
* @returns {void}
*/
class Groups {
client: BoxClient;
accessLevels!: typeof GroupAccessLevel;
userRoles!: typeof GroupUserRole;
constructor(client: BoxClient) {
this.client = client;
}
/**
* Used to create a new group
*
* API Endpoint: '/groups'
* Method: POST
*
* @param {string} name - The name for the new group
* @param {Object} [options] - Additional parameters
* @param {string} [options.provenance] - Used to track the external source where the group is coming from
* @param {string} [options.external_sync_identifier] - Used as a group identifier for groups coming from an external source
* @param {string} [options.description] - Description of the group
* @param {GroupAccessLevel} [options.invitability_level] - Specifies who can invite this group to collaborate on folders
* @param {GroupAccessLevel} [options.member_viewability_level] - Specifies who can view the members of this group
* @param {Function} [callback] - Passed the new group object if it was created successfully, error otherwise
* @returns {Promise<Object>} A promise resolving to the new group object
*/
create(
name: string,
options?: {
provenance?: string;
external_sync_identifier?: string;
description?: string;
invitability_level?: GroupAccessLevel;
member_viewability_level?: GroupAccessLevel;
},
callback?: Function
) {
var apiPath = urlPath(BASE_PATH),
params: Record<string, any> = {
body: options || {},
};
params.body.name = name;
return this.client.wrapWithDefaultHandler(this.client.post)(
apiPath,
params,
callback
);
}
/**
* Used to fetch information about a group
*
* API Endpoint: '/groups/:groupID'
* Method: GET
*
* @param {string} groupID - The ID of the group to retrieve
* @param {Object} [options] - Additional options for the request. Can be left null in most cases.
* @param {Function} [callback] - Passed the group object if successful, error otherwise
* @returns {Promise<Object>} A promise resolving to the group object
*/
get(groupID: string, options?: Record<string, any>, callback?: Function) {
var apiPath = urlPath(BASE_PATH, groupID),
params = {
qs: options,
};
return this.client.wrapWithDefaultHandler(this.client.get)(
apiPath,
params,
callback
);
}
/**
* Used to update or modify a group object
*
* API Endpoint: '/groups/:groupID'
* Method: PUT
*
* @param {string} groupID - The ID of the group to update
* @param {Object} updates - Group fields to update
* @param {Function} [callback] - Passed the updated group object if successful, error otherwise
* @returns {Promise<Object>} A promise resolving to the updated group object
*/
update(groupID: string, updates?: Record<string, any>, callback?: Function) {
var apiPath = urlPath(BASE_PATH, groupID),
params = {
body: updates,
};
return this.client.wrapWithDefaultHandler(this.client.put)(
apiPath,
params,
callback
);
}
/**
* Delete a group
*
* API Endpoint: '/groups/:groupID'
* Method: DELETE
*
* @param {string} groupID - The ID of the group to delete
* @param {Function} [callback] - Passed nothing if successful, error otherwise
* @returns {Promise<void>} A promise resolving to nothing
*/
delete(groupID: string, callback?: Function) {
var apiPath = urlPath(BASE_PATH, groupID);
return this.client.wrapWithDefaultHandler(this.client.del)(
apiPath,
null,
callback
);
}
/**
* Add a user to a group, which creates a membership record for the user
*
* API Endpoint: '/group_memberships'
* Method: POST
*
* @param {string} groupID - The ID of the group to add the user to
* @param {string} userID - The ID of the user to add the the group
* @param {Object} [options] - Optional parameters for adding the user, can be left null in most cases
* @param {GroupUserRole} [options.role] - The role of the user in the group
* @param {Function} [callback] - Passed the membership record if successful, error otherwise
* @returns {Promise<Object>} A promise resolving to the new membership object
*/
addUser(
groupID: string,
userID: string,
options?: {
role?: GroupUserRole;
},
callback?: Function
) {
var apiPath = urlPath(MEMBERSHIPS_PATH),
params = {
body: {
user: {
id: userID,
},
group: {
id: groupID,
},
},
};
Object.assign(params.body, options);
return this.client.wrapWithDefaultHandler(this.client.post)(
apiPath,
params,
callback
);
}
/**
* Fetch a specific membership record, which shows that a given user is a member
* of some group.
*
* API Endpoint: '/group_memberships/:membershipID'
* Method: GET
*
* @param {string} membershipID - The ID of the membership to fetch
* @param {Object} [options] - Additional options for the request. Can be left null in most cases.
* @param {Function} [callback] - Passed the membership record if successful, error otherwise
* @returns {Promise<Object>} A promise resolving to the membership object
*/
getMembership(
membershipID: string,
options?: Record<string, any>,
callback?: Function
) {
var apiPath = urlPath(MEMBERSHIPS_PATH, membershipID),
params = {
qs: options,
};
return this.client.wrapWithDefaultHandler(this.client.get)(
apiPath,
params,
callback
);
}
/**
* Used to update or modify a group object
*
* API Endpoint: '/group_memberships/:membershipID'
* Method: PUT
*
* @param {string} membershipID - The ID of the membership to update
* @param {Object} options - Membership record fields to update
* @param {Function} [callback] - Passed the updated membership object if successful, error otherwise
* @returns {Promise<Object>} A promise resolving to the updated membership object
*/
updateMembership(
membershipID: string,
options: Record<string, any>,
callback?: Function
) {
var apiPath = urlPath(MEMBERSHIPS_PATH, membershipID),
params = {
body: options,
};
return this.client.wrapWithDefaultHandler(this.client.put)(
apiPath,
params,
callback
);
}
/**
* Used to remove a group membership
*
* API Endpoint: '/group_memberships/:membershipID'
* Method: DELETE
*
* @param {string} membershipID - The ID of the membership to be removed
* @param {Function} [callback] - Passed nothing if successful, error otherwise
* @returns {Promise<void>} A promise resolving to nothing
*/
removeMembership(membershipID: string, callback?: Function) {
var apiPath = urlPath(MEMBERSHIPS_PATH, membershipID);
return this.client.wrapWithDefaultHandler(this.client.del)(
apiPath,
null,
callback
);
}
/**
* Retreieve a list of memberships for the group, which show which users
* belong to the group
*
* API Endpoint: '/groups/:groupID/memberships'
* Method: GET
*
* @param {string} groupID - The ID of the group to get memberships for
* @param {Object} [options] - Optional parameters, can be left null in most cases
* @param {int} [options.limit] - The number of memberships to retrieve
* @param {int} [options.offset] - Paging marker, retrieve records starting at this position in the list
* @param {Function} [callback] - Passed a list of memberships if successful, error otherwise
* @returns {Promise<Object>} A promise resolving to the collection of memberships
*/
getMemberships(
groupID: string,
options?: {
limit?: number;
offset?: number;
},
callback?: Function
) {
var apiPath = urlPath(BASE_PATH, groupID, MEMBERSHIPS_SUBRESOURCE),
params = {
qs: options,
};
return this.client.wrapWithDefaultHandler(this.client.get)(
apiPath,
params,
callback
);
}
/**
* Retreieve a list of groups in the caller's enterprise. This ability is
* restricted to certain users with permission to view groups.
*
* API Endpoint: '/groups'
* Method: GET
*
* @param {Object} [options] - Optional parameters, can be left null in most cases
* @param {string} [options.filter_term] - Limits the results to only groups whose name starts with the search term
* @param {int} [options.limit] - The number of memberships to retrieve
* @param {int} [options.offset] - Paging marker, retrieve records starting at this position in the list
* @param {Function} [callback] - Passed a list of groups if successful, error otherwise
* @returns {Promise<Object>} A promise resolving to the collection of groups
*/
getAll(
options?: {
filter_term?: string;
limit?: number;
offset?: number;
},
callback?: Function
) {
var apiPath = urlPath(BASE_PATH),
params = {
qs: options,
};
return this.client.wrapWithDefaultHandler(this.client.get)(
apiPath,
params,
callback
);
}
/**
* Retreieve a list of collaborations for the group, which show which items the
* group has access to.
*
* API Endpoint: '/groups/:groupID/collaborations'
* Method: GET
*
* @param {string} groupID - The ID of the group to get collaborations for
* @param {Object} [options] - Optional parameters, can be left null in most cases
* @param {int} [options.limit] - The number of memberships to retrieve
* @param {int} [options.offset] - Paging marker, retrieve records starting at this position in the list
* @param {Function} [callback] - Passed a list of collaborations if successful, error otherwise
* @returns {Promise<Object>} A promise resolving to the collection of collaborations for the group
*/
getCollaborations(
groupID: string,
options?: {
limit?: number;
offset?: number;
},
callback?: Function
) {
var apiPath = urlPath(BASE_PATH, groupID, COLLABORATIONS_SUBRESOURCE),
params = {
qs: options,
};
return this.client.wrapWithDefaultHandler(this.client.get)(
apiPath,
params,
callback
);
}
}
/**
* Enum of valid access levels for groups, which are used to specify who can
* perform certain actions on the group.
* @enum {GroupAccessLevel}
*/
Groups.prototype.accessLevels = GroupAccessLevel;
/**
* Enum of valid user roles within a group
* @enum {GroupUserRole}
*/
Groups.prototype.userRoles = GroupUserRole;
export = Groups; | the_stack |
import rule from '../../src/rules/typedef';
import { RuleTester, getFixturesRootDir, noFormat } from '../RuleTester';
const rootDir = getFixturesRootDir();
const ruleTester = new RuleTester({
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 2015,
tsconfigRootDir: rootDir,
project: './tsconfig.json',
},
});
ruleTester.run('typedef', rule, {
valid: [
// Array destructuring
{
code: 'function foo(...[a]: string[]) {}',
options: [
{
arrayDestructuring: true,
},
],
},
{
code: 'const foo = (...[a]: string[]) => {};',
options: [
{
arrayDestructuring: true,
},
],
},
{
code: 'const [a]: [number] = [1];',
options: [
{
arrayDestructuring: true,
},
],
},
{
code: 'const [a, b]: [number, number] = [1, 2];',
options: [
{
arrayDestructuring: true,
},
],
},
{
code: 'const [a] = 1;',
options: [
{
arrayDestructuring: false,
},
],
},
{
code: `
for (const [key, val] of new Map([['key', 1]])) {
}
`,
options: [
{
arrayDestructuring: true,
},
],
},
{
code: `
for (const [[key]] of [[['key']]]) {
}
`,
options: [
{
arrayDestructuring: true,
},
],
},
{
code: `
for (const [[{ key }]] of [[[{ key: 'value' }]]]) {
}
`,
options: [
{
arrayDestructuring: true,
},
],
},
`
let a: number;
[a] = [1];
`,
// Arrow parameters
'((a: number): void => {})();',
'((a: string, b: string): void => {})();',
{
code: '((a: number): void => {})();',
options: [
{
arrowParameter: false,
},
],
},
{
code: '((a: string, b: string): void => {})();',
options: [
{
arrowParameter: false,
},
],
},
// Member variable declarations
`
class Test {
state: number;
}
`,
`
class Test {
state: number = 1;
}
`,
{
code: `
class Test {
state = 1;
}
`,
options: [
{
memberVariableDeclaration: false,
},
],
},
// Object destructuring
{
code: 'const { a }: { a: number } = { a: 1 };',
options: [
{
objectDestructuring: true,
},
],
},
{
code: 'const { a, b }: { [i: string]: number } = { a: 1, b: 2 };',
options: [
{
objectDestructuring: true,
},
],
},
{
code: `
for (const {
p1: {
p2: { p3 },
},
} of [{ p1: { p2: { p3: 'value' } } }]) {
}
`,
options: [
{
objectDestructuring: true,
},
],
},
{
code: `
for (const {
p1: {
p2: {
p3: [key],
},
},
} of [{ p1: { p2: { p3: ['value'] } } }]) {
}
`,
options: [
{
objectDestructuring: true,
},
],
},
{
code: 'const { a } = { a: 1 };',
options: [
{
objectDestructuring: false,
},
],
},
{
code: `
for (const { key, val } of [{ key: 'key', val: 1 }]) {
}
`,
options: [
{
objectDestructuring: true,
},
],
},
// Function parameters
'function receivesNumber(a: number): void {}',
'function receivesStrings(a: string, b: string): void {}',
'function receivesNumber([a]: [number]): void {}',
'function receivesNumbers([a, b]: number[]): void {}',
'function receivesString({ a }: { a: string }): void {}',
'function receivesStrings({ a, b }: { [i: string]: string }): void {}',
'function receivesNumber(a: number = 123): void {}',
// Constructor parameters
`
class Test {
constructor() {}
}
`,
`
class Test {
constructor(param: string) {}
}
`,
`
class Test {
constructor(param: string = 'something') {}
}
`,
`
class Test {
constructor(private param: string = 'something') {}
}
`,
// Method parameters
`
class Test {
public method(x: number): number {
return x;
}
}
`,
`
class Test {
public method(x: number = 123): number {
return x;
}
}
`,
// Property declarations
`
type Test = {
member: number;
};
`,
`
type Test = {
[i: string]: number;
};
`,
`
interface Test {
member: string;
}
`,
`
interface Test {
[i: number]: string;
}
`,
{
code: `
type Test = {
member;
};
`,
options: [
{
propertyDeclaration: false,
},
],
},
{
code: noFormat`
type Test = {
[i: string];
};
`,
options: [
{
propertyDeclaration: false,
},
],
},
// Variable declarations
{
code: "const x: string = '';",
options: [
{
variableDeclaration: true,
},
],
},
{
code: "let x: string = '';",
options: [
{
variableDeclaration: true,
},
],
},
{
code: 'let x: string;',
options: [
{
variableDeclaration: true,
},
],
},
{
code: 'const a = 1;',
options: [
{
variableDeclaration: false,
},
],
},
{
code: 'let a;',
options: [
{
variableDeclaration: false,
},
],
},
{
code: 'let a = 1;',
options: [
{
variableDeclaration: false,
},
],
},
{
code: 'const [a, b] = [1, 2];',
options: [
{
objectDestructuring: false,
variableDeclaration: true,
},
],
},
{
code: "const { a, b } = { a: '', b: '' };",
options: [
{
objectDestructuring: false,
variableDeclaration: true,
},
],
},
// Contexts where TypeScript doesn't allow annotations
{
code: `
for (x of [1, 2, 3]) {
}
`,
options: [
{
variableDeclaration: true,
},
],
},
{
code: `
for (const x in {}) {
}
`,
options: [
{
variableDeclaration: true,
},
],
},
{
code: `
try {
} catch (e) {}
`,
options: [
{
variableDeclaration: true,
},
],
},
// variable declaration ignore function
{
code: 'const foo = function (): void {};',
options: [
{
variableDeclaration: true,
variableDeclarationIgnoreFunction: true,
},
],
},
{
code: 'const foo = (): void => {};',
options: [
{
variableDeclaration: true,
variableDeclarationIgnoreFunction: true,
},
],
},
{
code: 'const foo: () => void = (): void => {};',
options: [
{
variableDeclaration: true,
variableDeclarationIgnoreFunction: true,
},
],
},
{
code: 'const foo: () => void = function (): void {};',
options: [
{
variableDeclaration: true,
variableDeclarationIgnoreFunction: true,
},
],
},
{
code: `
class Foo {
a = (): void => {};
b = function (): void {};
}
`,
options: [
{
variableDeclaration: true,
variableDeclarationIgnoreFunction: true,
},
],
},
// https://github.com/typescript-eslint/typescript-eslint/issues/4033
{
code: `
class ClassName {
public str: string = 'str';
#num: number = 13;
func: () => void = (): void => {
console.log(this.str);
};
}
`,
options: [
{
memberVariableDeclaration: true,
},
],
},
],
invalid: [
// Array destructuring
{
code: 'const [a] = [1];',
errors: [
{
messageId: 'expectedTypedef',
},
],
options: [
{
arrayDestructuring: true,
},
],
},
{
code: 'const [a, b] = [1, 2];',
errors: [
{
messageId: 'expectedTypedef',
},
],
options: [
{
arrayDestructuring: true,
},
],
},
// Object destructuring
{
code: 'const { a } = { a: 1 };',
errors: [
{
messageId: 'expectedTypedef',
},
],
options: [
{
objectDestructuring: true,
},
],
},
{
code: 'const { a, b } = { a: 1, b: 2 };',
errors: [
{
messageId: 'expectedTypedef',
},
],
options: [
{
objectDestructuring: true,
},
],
},
// Arrow parameters
{
code: 'const receivesNumber = (a): void => {};',
errors: [
{
data: { name: 'a' },
messageId: 'expectedTypedefNamed',
},
],
options: [
{
arrowParameter: true,
},
],
},
{
code: 'const receivesStrings = (a, b): void => {};',
errors: [
{
data: { name: 'a' },
messageId: 'expectedTypedefNamed',
},
{
data: { name: 'b' },
messageId: 'expectedTypedefNamed',
},
],
options: [
{
arrowParameter: true,
},
],
},
// Member variable declarations
{
code: `
class Test {
state = 1;
}
`,
errors: [
{
data: { name: 'state' },
messageId: 'expectedTypedefNamed',
},
],
options: [
{
memberVariableDeclaration: true,
},
],
},
{
code: `
class Test {
['state'] = 1;
}
`,
errors: [
{
messageId: 'expectedTypedef',
},
],
options: [
{
memberVariableDeclaration: true,
},
],
},
// Function parameters
{
code: 'function receivesNumber(a): void {}',
errors: [
{
data: { name: 'a' },
messageId: 'expectedTypedefNamed',
},
],
options: [
{
parameter: true,
},
],
},
{
code: 'function receivesStrings(a, b): void {}',
errors: [
{
data: { name: 'a' },
messageId: 'expectedTypedefNamed',
},
{
data: { name: 'b' },
messageId: 'expectedTypedefNamed',
},
],
options: [
{
parameter: true,
},
],
},
{
code: 'function receivesNumber([a]): void {}',
errors: [
{
column: 25,
messageId: 'expectedTypedef',
},
],
options: [
{
parameter: true,
},
],
},
{
code: 'function receivesNumbers([a, b]): void {}',
errors: [
{
column: 26,
messageId: 'expectedTypedef',
},
],
options: [
{
parameter: true,
},
],
},
{
code: 'function receivesString({ a }): void {}',
errors: [
{
column: 25,
messageId: 'expectedTypedef',
},
],
options: [
{
parameter: true,
},
],
},
{
code: 'function receivesStrings({ a, b }): void {}',
errors: [
{
column: 26,
messageId: 'expectedTypedef',
},
],
options: [
{
parameter: true,
},
],
},
// Constructor parameters
{
code: `
class Test {
constructor(param) {}
}
`,
errors: [
{
column: 23,
messageId: 'expectedTypedefNamed',
},
],
options: [
{
parameter: true,
},
],
},
{
code: `
class Test {
constructor(param = 'something') {}
}
`,
errors: [
{
column: 23,
messageId: 'expectedTypedef',
},
],
options: [
{
parameter: true,
},
],
},
{
code: `
class Test {
constructor(private param = 'something') {}
}
`,
errors: [
{
column: 23,
messageId: 'expectedTypedef',
},
],
options: [
{
parameter: true,
},
],
},
// Method parameters
{
code: `
class Test {
public method(x): number {
return x;
}
}
`,
errors: [
{
column: 25,
messageId: 'expectedTypedefNamed',
},
],
options: [
{
parameter: true,
},
],
},
{
code: `
class Test {
public method(x = 123): number {
return x;
}
}
`,
errors: [
{
column: 25,
messageId: 'expectedTypedef',
},
],
options: [
{
parameter: true,
},
],
},
{
code: `
class Test {
public constructor(public x) {}
}
`,
errors: [
{
column: 30,
messageId: 'expectedTypedef',
},
],
options: [
{
parameter: true,
},
],
},
// Property declarations
{
code: `
type Test = {
member;
};
`,
errors: [
{
data: { name: 'member' },
messageId: 'expectedTypedefNamed',
},
],
options: [
{
propertyDeclaration: true,
},
],
},
{
code: noFormat`
type Test = {
[i: string];
};
`,
errors: [
{
messageId: 'expectedTypedef',
},
],
options: [
{
propertyDeclaration: true,
},
],
},
{
code: `
interface Test {
member;
}
`,
errors: [
{
data: { name: 'member' },
messageId: 'expectedTypedefNamed',
},
],
options: [
{
propertyDeclaration: true,
},
],
},
{
code: noFormat`
interface Test {
[i: string];
}
`,
errors: [
{
messageId: 'expectedTypedef',
},
],
options: [
{
propertyDeclaration: true,
},
],
},
// Variable declarations
{
code: 'const a = 1;',
errors: [
{
data: { name: 'a' },
messageId: 'expectedTypedefNamed',
},
],
options: [
{
variableDeclaration: true,
},
],
},
{
code: `
const a = 1,
b: number = 2,
c = 3;
`,
errors: [
{
data: { name: 'a' },
messageId: 'expectedTypedefNamed',
},
{
data: { name: 'c' },
messageId: 'expectedTypedefNamed',
},
],
options: [
{
variableDeclaration: true,
},
],
},
{
code: 'let a;',
errors: [
{
data: { name: 'a' },
messageId: 'expectedTypedefNamed',
},
],
options: [
{
variableDeclaration: true,
},
],
},
{
code: 'let a = 1;',
errors: [
{
data: { name: 'a' },
messageId: 'expectedTypedefNamed',
},
],
options: [
{
variableDeclaration: true,
},
],
},
{
code: `
let a = 1,
b: number,
c = 2;
`,
errors: [
{
data: { name: 'a' },
messageId: 'expectedTypedefNamed',
},
{
data: { name: 'c' },
messageId: 'expectedTypedefNamed',
},
],
options: [
{
variableDeclaration: true,
},
],
},
{
code: "const foo = 'foo';",
errors: [
{
messageId: 'expectedTypedefNamed',
data: { name: 'foo' },
},
],
options: [
{
variableDeclaration: true,
variableDeclarationIgnoreFunction: true,
},
],
},
{
code: 'const foo = function (): void {};',
errors: [
{
messageId: 'expectedTypedefNamed',
data: { name: 'foo' },
},
],
options: [
{
variableDeclaration: true,
variableDeclarationIgnoreFunction: false,
},
],
},
{
code: 'const foo = (): void => {};',
errors: [
{
messageId: 'expectedTypedefNamed',
data: { name: 'foo' },
},
],
options: [
{
variableDeclaration: true,
variableDeclarationIgnoreFunction: false,
},
],
},
{
code: `
class Foo {
a = (): void => {};
b = function (): void {};
}
`,
errors: [
{
messageId: 'expectedTypedefNamed',
data: { name: 'a' },
},
{
messageId: 'expectedTypedefNamed',
data: { name: 'b' },
},
],
options: [
{
memberVariableDeclaration: true,
variableDeclaration: true,
variableDeclarationIgnoreFunction: false,
},
],
},
],
}); | the_stack |
import { Template } from '@aws-cdk/assertions';
import * as iam from '@aws-cdk/aws-iam';
import * as cdk from '@aws-cdk/core';
import * as ecs from '../../lib';
describe('fargate task definition', () => {
describe('When creating a Fargate TaskDefinition', () => {
test('with only required properties set, it correctly sets default properties', () => {
// GIVEN
const stack = new cdk.Stack();
new ecs.FargateTaskDefinition(stack, 'FargateTaskDef');
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::ECS::TaskDefinition', {
Family: 'FargateTaskDef',
NetworkMode: ecs.NetworkMode.AWS_VPC,
RequiresCompatibilities: ['FARGATE'],
Cpu: '256',
Memory: '512',
});
});
test('support lazy cpu and memory values', () => {
// GIVEN
const stack = new cdk.Stack();
new ecs.FargateTaskDefinition(stack, 'FargateTaskDef', {
cpu: cdk.Lazy.number({ produce: () => 128 }),
memoryLimitMiB: cdk.Lazy.number({ produce: () => 1024 }),
});
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::ECS::TaskDefinition', {
Cpu: '128',
Memory: '1024',
});
});
test('with all properties set', () => {
// GIVEN
const stack = new cdk.Stack();
const taskDefinition = new ecs.FargateTaskDefinition(stack, 'FargateTaskDef', {
cpu: 128,
executionRole: new iam.Role(stack, 'ExecutionRole', {
path: '/',
assumedBy: new iam.CompositePrincipal(
new iam.ServicePrincipal('ecs.amazonaws.com'),
new iam.ServicePrincipal('ecs-tasks.amazonaws.com'),
),
}),
family: 'myApp',
memoryLimitMiB: 1024,
taskRole: new iam.Role(stack, 'TaskRole', {
assumedBy: new iam.ServicePrincipal('ecs-tasks.amazonaws.com'),
}),
ephemeralStorageGiB: 21,
runtimePlatform: {
cpuArchitecture: ecs.CpuArchitecture.X86_64,
operatingSystemFamily: ecs.OperatingSystemFamily.LINUX,
},
});
taskDefinition.addVolume({
host: {
sourcePath: '/tmp/cache',
},
name: 'scratch',
});
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::ECS::TaskDefinition', {
Cpu: '128',
ExecutionRoleArn: {
'Fn::GetAtt': [
'ExecutionRole605A040B',
'Arn',
],
},
EphemeralStorage: {
SizeInGiB: 21,
},
Family: 'myApp',
Memory: '1024',
NetworkMode: 'awsvpc',
RequiresCompatibilities: [
ecs.LaunchType.FARGATE,
],
RuntimePlatform: {
CpuArchitecture: 'X86_64',
OperatingSystemFamily: 'LINUX',
},
TaskRoleArn: {
'Fn::GetAtt': [
'TaskRole30FC0FBB',
'Arn',
],
},
Volumes: [
{
Host: {
SourcePath: '/tmp/cache',
},
Name: 'scratch',
},
],
});
});
test('throws when adding placement constraint', () => {
// GIVEN
const stack = new cdk.Stack();
const taskDefinition = new ecs.FargateTaskDefinition(stack, 'FargateTaskDef');
// THEN
expect(() => {
taskDefinition.addPlacementConstraint(ecs.PlacementConstraint.memberOf('attribute:ecs.instance-type =~ t2.*'));
}).toThrow(/Cannot set placement constraints on tasks that run on Fargate/);
});
test('throws when adding inference accelerators', () => {
// GIVEN
const stack = new cdk.Stack();
const taskDefinition = new ecs.FargateTaskDefinition(stack, 'FargateTaskDef');
const inferenceAccelerator = {
deviceName: 'device1',
deviceType: 'eia2.medium',
};
// THEN
expect(() => {
taskDefinition.addInferenceAccelerator(inferenceAccelerator);
}).toThrow(/Cannot use inference accelerators on tasks that run on Fargate/);
});
test('throws when ephemeral storage request is too high', () => {
// GIVEN
const stack = new cdk.Stack();
expect(() => {
new ecs.FargateTaskDefinition(stack, 'FargateTaskDef', {
ephemeralStorageGiB: 201,
});
}).toThrow(/Ephemeral storage size must be between 21GiB and 200GiB/);
// THEN
});
test('throws when ephemeral storage request is too low', () => {
// GIVEN
const stack = new cdk.Stack();
expect(() => {
new ecs.FargateTaskDefinition(stack, 'FargateTaskDef', {
ephemeralStorageGiB: 20,
});
}).toThrow(/Ephemeral storage size must be between 21GiB and 200GiB/);
// THEN
});
});
describe('When importing from an existing Fargate TaskDefinition', () => {
test('can succeed using TaskDefinition Arn', () => {
// GIVEN
const stack = new cdk.Stack();
const expectTaskDefinitionArn = 'TD_ARN';
// WHEN
const taskDefinition = ecs.FargateTaskDefinition.fromFargateTaskDefinitionArn(stack, 'FARGATE_TD_ID', expectTaskDefinitionArn);
// THEN
expect(taskDefinition.taskDefinitionArn).toEqual(expectTaskDefinitionArn);
});
test('can succeed using attributes', () => {
// GIVEN
const stack = new cdk.Stack();
const expectTaskDefinitionArn = 'TD_ARN';
const expectNetworkMode = ecs.NetworkMode.AWS_VPC;
const expectTaskRole = new iam.Role(stack, 'TaskRole', {
assumedBy: new iam.ServicePrincipal('ecs-tasks.amazonaws.com'),
});
// WHEN
const taskDefinition = ecs.FargateTaskDefinition.fromFargateTaskDefinitionAttributes(stack, 'TD_ID', {
taskDefinitionArn: expectTaskDefinitionArn,
networkMode: expectNetworkMode,
taskRole: expectTaskRole,
});
// THEN
expect(taskDefinition.taskDefinitionArn).toEqual(expectTaskDefinitionArn);
expect(taskDefinition.compatibility).toEqual(ecs.Compatibility.FARGATE);
expect(taskDefinition.isFargateCompatible).toEqual(true);
expect(taskDefinition.isEc2Compatible).toEqual(false);
expect(taskDefinition.networkMode).toEqual(expectNetworkMode);
expect(taskDefinition.taskRole).toEqual(expectTaskRole);
});
test('returns a Fargate TaskDefinition that will throw an error when trying to access its networkMode but its networkMode is undefined', () => {
// GIVEN
const stack = new cdk.Stack();
const expectTaskDefinitionArn = 'TD_ARN';
const expectTaskRole = new iam.Role(stack, 'TaskRole', {
assumedBy: new iam.ServicePrincipal('ecs-tasks.amazonaws.com'),
});
// WHEN
const taskDefinition = ecs.FargateTaskDefinition.fromFargateTaskDefinitionAttributes(stack, 'TD_ID', {
taskDefinitionArn: expectTaskDefinitionArn,
taskRole: expectTaskRole,
});
// THEN
expect(() => {
taskDefinition.networkMode;
}).toThrow('This operation requires the networkMode in ImportedTaskDefinition to be defined. ' +
'Add the \'networkMode\' in ImportedTaskDefinitionProps to instantiate ImportedTaskDefinition');
});
test('returns a Fargate TaskDefinition that will throw an error when trying to access its taskRole but its taskRole is undefined', () => {
// GIVEN
const stack = new cdk.Stack();
const expectTaskDefinitionArn = 'TD_ARN';
const expectNetworkMode = ecs.NetworkMode.AWS_VPC;
// WHEN
const taskDefinition = ecs.FargateTaskDefinition.fromFargateTaskDefinitionAttributes(stack, 'TD_ID', {
taskDefinitionArn: expectTaskDefinitionArn,
networkMode: expectNetworkMode,
});
// THEN
expect(() => {
taskDefinition.taskRole;
}).toThrow('This operation requires the taskRole in ImportedTaskDefinition to be defined. ' +
'Add the \'taskRole\' in ImportedTaskDefinitionProps to instantiate ImportedTaskDefinition');
});
test('Passing in token for ephemeral storage will not throw error', () => {
// GIVEN
const stack = new cdk.Stack();
// WHEN
const param = new cdk.CfnParameter(stack, 'prammm', {
type: 'Number',
default: 1,
});
const taskDefinition = new ecs.FargateTaskDefinition(stack, 'FargateTaskDef', {
ephemeralStorageGiB: param.valueAsNumber,
});
// THEN
expect(() => {
taskDefinition.ephemeralStorageGiB;
}).toBeTruthy;
});
test('runtime testing for windows container', () => {
// GIVEN
const stack = new cdk.Stack();
new ecs.FargateTaskDefinition(stack, 'FargateTaskDef', {
cpu: 1024,
memoryLimitMiB: 2048,
runtimePlatform: {
operatingSystemFamily: ecs.OperatingSystemFamily.WINDOWS_SERVER_2019_CORE,
cpuArchitecture: ecs.CpuArchitecture.X86_64,
},
});
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::ECS::TaskDefinition', {
Cpu: '1024',
Family: 'FargateTaskDef',
Memory: '2048',
NetworkMode: 'awsvpc',
RequiresCompatibilities: [
ecs.LaunchType.FARGATE,
],
RuntimePlatform: {
CpuArchitecture: 'X86_64',
OperatingSystemFamily: 'WINDOWS_SERVER_2019_CORE',
},
TaskRoleArn: {
'Fn::GetAtt': [
'FargateTaskDefTaskRole0B257552',
'Arn',
],
},
});
});
test('runtime testing for linux container', () => {
// GIVEN
const stack = new cdk.Stack();
new ecs.FargateTaskDefinition(stack, 'FargateTaskDef', {
cpu: 1024,
memoryLimitMiB: 2048,
runtimePlatform: {
operatingSystemFamily: ecs.OperatingSystemFamily.LINUX,
cpuArchitecture: ecs.CpuArchitecture.ARM64,
},
});
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::ECS::TaskDefinition', {
Cpu: '1024',
Family: 'FargateTaskDef',
Memory: '2048',
NetworkMode: 'awsvpc',
RequiresCompatibilities: [
ecs.LaunchType.FARGATE,
],
RuntimePlatform: {
CpuArchitecture: 'ARM64',
OperatingSystemFamily: 'LINUX',
},
TaskRoleArn: {
'Fn::GetAtt': [
'FargateTaskDefTaskRole0B257552',
'Arn',
],
},
});
});
test('creating a Fargate TaskDefinition with WINDOWS_SERVER_X operatingSystemFamily and incorrect cpu throws an error', () => {
// GIVEN
const stack = new cdk.Stack();
// Not in CPU Ranage.
expect(() => {
new ecs.FargateTaskDefinition(stack, 'FargateTaskDefCPU', {
cpu: 128,
memoryLimitMiB: 1024,
runtimePlatform: {
cpuArchitecture: ecs.CpuArchitecture.X86_64,
operatingSystemFamily: ecs.OperatingSystemFamily.WINDOWS_SERVER_2019_CORE,
},
});
}).toThrowError(`If operatingSystemFamily is ${ecs.OperatingSystemFamily.WINDOWS_SERVER_2019_CORE._operatingSystemFamily}, then cpu must be in 1024 (1 vCPU), 2048 (2 vCPU), or 4096 (4 vCPU).`);
// Memory is not in 1 GB increments.
expect(() => {
new ecs.FargateTaskDefinition(stack, 'FargateTaskDefMemory', {
cpu: 1024,
memoryLimitMiB: 1025,
runtimePlatform: {
cpuArchitecture: ecs.CpuArchitecture.X86_64,
operatingSystemFamily: ecs.OperatingSystemFamily.WINDOWS_SERVER_2019_CORE,
},
});
}).toThrowError('If provided cpu is 1024, then memoryMiB must have a min of 1024 and a max of 8192, in 1024 increments. Provided memoryMiB was 1025.');
// Check runtimePlatform was been defined ,but not undefined cpu and memoryLimitMiB.
expect(() => {
new ecs.FargateTaskDefinition(stack, 'FargateTaskDef', {
runtimePlatform: {
cpuArchitecture: ecs.CpuArchitecture.X86_64,
operatingSystemFamily: ecs.OperatingSystemFamily.WINDOWS_SERVER_2004_CORE,
},
});
}).toThrowError('If operatingSystemFamily is WINDOWS_SERVER_2004_CORE, then cpu must be in 1024 (1 vCPU), 2048 (2 vCPU), or 4096 (4 vCPU). Provided value was: 256');
});
});
}); | the_stack |
// The MIT License (MIT)
//
// vs-deploy (https://github.com/mkloubert/vs-deploy)
// Copyright (c) Marcel Joachim Kloubert <marcel.kloubert@gmx.net>
//
// 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.
import * as deploy_helpers from './helpers';
let MSSQL: any;
let MYSQL: any;
// try load Microsoft SQL module
try {
MSSQL = require('mssql');
}
catch (e) {
deploy_helpers.log(`Could not load MS-SQL module: ${deploy_helpers.toStringSafe(e)}`);
}
// try load MySQL
try {
MYSQL = require('mysql');
}
catch (e) {
deploy_helpers.log(`Could not load MySQL module: ${deploy_helpers.toStringSafe(e)}`);
}
/**
* MSSQL connection options.
*/
export interface MSSqlOptions {
/**
* The database to connect to.
*/
database?: string;
/**
* The driver to use.
*/
driver?: string;
/**
* Encrypt the connection or not.
*/
encrypt?: boolean;
/**
* The host.
*/
host?: string;
/**
* The TCP port.
*/
port?: number;
/**
* The password.
*/
password?: string;
/**
* The username.
*/
user?: string;
}
/**
* MySQL connection options.
*/
export interface MySqlOptions {
/**
* The database to connect to.
*/
database?: string;
/**
* The host.
*/
host?: string;
/**
* The TCP port.
*/
port?: number;
/**
* The password.
*/
password?: string;
/**
* Reject untrusted SSL connections or not.
*/
rejectUnauthorized?: boolean;
/**
* The username.
*/
user?: string;
}
/**
* A MSSQL connection.
*/
export interface MSSqlConnection extends SqlConnection {
/** @inheritdoc */
query: (sql: string, ...args: any[]) => Promise<MSSqlResult>;
}
/**
* A MySQL connection.
*/
export interface MySqlConnection extends SqlConnection {
/** @inheritdoc */
query: (sql: string, ...args: any[]) => Promise<MySqlResult>;
}
/**
* A MSSQL result.
*/
export interface MSSqlResult extends SqlResult {
}
/**
* A MySQL result.
*/
export interface MySqlResult extends SqlResult {
}
/**
* A SQL connection.
*/
export interface SqlConnection {
/**
* The underlying connection object.
*/
connection: any;
/**
* Closes the connection.
*
* @returns {Promise<any>} The promise.
*/
close: () => Promise<any>;
/**
* The (display) name of the connection.
*/
name: string;
/**
* Invokes a query.
*
* @param {string} sql The SQL query.
* @param {any[]} [args] One or more argument for the query.
*
* @returns {Promise<SqlResult>} The promise.
*/
query: (sql: string, ...args: any[]) => Promise<SqlResult>;
/**
* The type (if known).
*/
type?: SqlConnectionType;
}
/**
* List of known SQL connection types.
*/
export enum SqlConnectionType {
/**
* MySQL
*/
MySql = 0,
/**
* Microsoft SQL
*/
MSSql = 1,
}
/**
* A SQL result.
*/
export interface SqlResult {
}
/**
* Creates a new MSSQL connection.
*
* @param {MSSqlOptions} [opts] The options for the connection.
*
* @returns {Promise<MSSqlConnection>} The promise.
*/
export function createMSSqlConnection(opts?: MSSqlOptions): Promise<MSSqlConnection> {
if (!opts) {
opts = {};
}
return new Promise<MSSqlConnection>((resolve, reject) => {
let completed = (err?: any, conn?: MSSqlConnection) => {
if (err) {
reject(err);
}
else {
resolve(conn);
}
};
if (!MSSQL) {
completed(new Error(`Microsoft SQL is currently not available!`));
return;
}
try {
let driver = deploy_helpers.toStringSafe(opts.driver).toLowerCase().trim();
if (!driver) {
driver = 'tedious';
}
let host = deploy_helpers.toStringSafe(opts.host).toLowerCase().trim();
if (!host) {
host = '127.0.0.1';
}
let port = deploy_helpers.toStringSafe(opts.port).trim();
if ('' === port) {
port = '1433';
}
let user = deploy_helpers.toStringSafe(opts.user).trim();
if ('' === user) {
user = 'sa';
}
let pwd = deploy_helpers.toStringSafe(opts.password);
if ('' === pwd) {
pwd = undefined;
}
let db = deploy_helpers.toStringSafe(opts.database).trim();
if ('' === db) {
db = undefined;
}
let connOpts = {
database: db,
driver: driver,
server: host,
port: parseInt(port),
user: user,
password: pwd,
options: {
encrypt: deploy_helpers.toBooleanSafe(opts.encrypt),
},
};
let connection = new MSSQL.Connection(connOpts);
connection.connect().then(function(mssqlConn) {
let conn: MSSqlConnection = {
close: () => {
return new Promise<any>((resolve2, reject2) => {
try {
mssqlConn.close();
resolve2();
}
catch (e) {
reject2(e);
}
});
},
connection: mssqlConn,
name: `mssql://${host}:${port}/${deploy_helpers.toStringSafe(db)}`,
query: (sql, args) => {
return new Promise<MSSqlResult>((resolve2, reject2) => {
try {
let req = new MSSQL.Request(mssqlConn);
req.query(sql).then((recordset) => {
let result: MSSqlResult = {
};
resolve2(result);
}).catch((err) => {
reject2(err);
});
}
catch (e) {
reject2(e);
}
});
},
type: SqlConnectionType.MSSql,
};
completed(null, conn);
}).catch((err) => {
completed(err);
});
}
catch (e) {
completed(e);
}
});
}
/**
* Creates a new MySQL connection.
*
* @param {MySqlOptions} [opts] The options for the connection.
*
* @returns {Promise<MySqlConnection>} The promise.
*/
export function createMySqlConnection(opts?: MySqlOptions): Promise<MySqlConnection> {
if (!opts) {
opts = {};
}
return new Promise<MySqlConnection>((resolve, reject) => {
let completed = (err?: any, conn?: MySqlConnection) => {
if (err) {
reject(err);
}
else {
resolve(conn);
}
};
if (!MYSQL) {
completed(new Error(`MySQL is currently not available!`));
return;
}
try {
let host = deploy_helpers.toStringSafe(opts.host).toLowerCase().trim();
if ('' === host) {
host = '127.0.0.1';
}
let port = deploy_helpers.toStringSafe(opts.port).trim();
if ('' === port) {
port = '3306';
}
let user = deploy_helpers.toStringSafe(opts.user).trim();
if ('' === user) {
user = 'root';
}
let pwd = deploy_helpers.toStringSafe(opts.password);
if ('' === pwd) {
pwd = undefined;
}
let db = deploy_helpers.toStringSafe(opts.database).trim();
if ('' === db) {
db = undefined;
}
let connOpts = {
database: db,
host: host,
port: parseInt(port),
user: user,
password: pwd,
};
if (!deploy_helpers.isNullOrUndefined(opts.rejectUnauthorized)) {
connOpts['ssl'] = {
rejectUnauthorized: deploy_helpers.toBooleanSafe(opts.rejectUnauthorized),
};
}
let connection = MYSQL.createConnection(connOpts);
connection.connect(function(err) {
if (err) {
completed(err);
return;
}
let conn: MySqlConnection = {
close: () => {
return new Promise<any>((resolve2, reject2) => {
try {
connection.end((err) => {
if (err) {
reject2(err);
}
else {
resolve2();
}
});
}
catch (e) {
reject2(e);
}
});
},
connection: connection,
name: `mysql://${host}:${port}/${deploy_helpers.toStringSafe(db)}`,
query: (sql, args) => {
return new Promise<MySqlResult>((resolve2, reject2) => {
try {
connection.query({
sql: sql,
values: args,
}, (err, rows) => {
if (err) {
reject2(err);
}
else {
let result: MySqlResult = {
};
resolve2(result);
}
});
}
catch (e) {
reject2(e);
}
});
},
type: SqlConnectionType.MySql,
};
completed(null, conn);
});
}
catch (e) {
completed(e);
}
});
}
/**
* Creates a new SQL connection.
*
* @param {SqlConnectionType} type The type of the connection.
* @param {any[]} [args] One or more arguments for the connection.
*
* @returns {Promise<SqlConnection>} The promise.
*/
export function createSqlConnection(type: SqlConnectionType, args?: any[]): Promise<SqlConnection> {
let me = this;
if (!args) {
args = [];
}
return new Promise<SqlConnection>((resolve, reject) => {
let func: Function;
switch (type) {
case SqlConnectionType.MSSql:
// Microsoft SQL
func = createMSSqlConnection;
break;
case SqlConnectionType.MySql:
// MySQL
func = createMySqlConnection;
break;
}
if (func) {
try {
func.apply(me, args).then((conn) => {
resolve(conn);
}).catch((err) => {
reject(err);
});
}
catch (e) {
reject(e);
}
}
else {
reject(new Error(`Type '${type}' is not supported!`));
}
});
} | the_stack |
'use strict'
// eslint-disable-next-line one-var
import mqtt, { Client } from 'mqtt'
import { allSettled, sanitizeTopic } from './utils'
// import { storeDir } from '../config/app'
import { module } from './logger'
import { version as appVersion } from '../package.json'
import { TypedEventEmitter } from './EventEmitter'
// import LevelStore from 'mqtt-level-store'
// eslint-disable-next-line @typescript-eslint/no-var-requires
const url = require('native-url')
const logger = module('Mqtt')
export type MqttConfig = {
name: string
host: string
port: number
disabled: boolean
reconnectPeriod: number
prefix: string
qos: 0 | 1 | 2
retain: boolean
clean: boolean
store: boolean
allowSelfsigned: boolean
key: string
cert: string
ca: string
auth: boolean
username: string
password: string
_ca: string
_key: string
_cert: string
}
export interface MqttClientEventCallbacks {
writeRequest: (parts: string[], payload: any) => void
broadcastRequest: (parts: string[], payload: any) => void
multicastRequest: (payload: any) => void
apiCall: (topic: string, apiName: string, payload: any) => void
connect: () => void
brokerStatus: (online: boolean) => void
hassStatus: (online: boolean) => void
}
export type MqttClientEvents = Extract<keyof MqttClientEventCallbacks, string>
class MqttClient extends TypedEventEmitter<MqttClientEventCallbacks> {
private config: MqttConfig
private toSubscribe: Map<
string,
mqtt.IClientSubscribeOptions & { addPrefix: boolean }
>
private _clientID: string
private client: Client
private error?: string
private closed: boolean
private retrySubTimeout: NodeJS.Timeout | null
private _closeTimeout: NodeJS.Timeout | null
static CLIENTS_PREFIX = '_CLIENTS'
public static get EVENTS_PREFIX() {
return '_EVENTS'
}
private static NAME_PREFIX = 'ZWAVE_GATEWAY-'
private static ACTIONS: string[] = ['broadcast', 'api', 'multicast']
private static HASS_WILL = 'homeassistant/status'
private static STATUS_TOPIC = 'status'
private static VERSION_TOPIC = 'version'
public get clientID() {
return this._clientID
}
/**
* The constructor
*/
constructor(config: MqttConfig) {
super()
this._init(config)
}
get connected() {
return this.client && this.client.connected
}
get disabled() {
return this.config.disabled
}
/**
* Returns the topic used to send client and devices status updateStates
* if name is null the client is the gateway itself
*/
getClientTopic(suffix: string) {
return `${this.config.prefix}/${MqttClient.CLIENTS_PREFIX}/${this._clientID}/${suffix}`
}
/**
* Method used to close clients connection, use this before destroy
*/
close(): Promise<void> {
return new Promise((resolve) => {
if (this.closed) {
resolve()
return
}
this.closed = true
if (this.retrySubTimeout) {
clearTimeout(this.retrySubTimeout)
this.retrySubTimeout = null
}
let resolved = false
if (this.client) {
const onClose = (error: Error) => {
// prevent multiple resolve
if (resolved) {
return
}
resolved = true
if (this._closeTimeout) {
clearTimeout(this._closeTimeout)
this._closeTimeout = null
}
if (error) {
logger.error('Error while closing client', error)
}
this.removeAllListeners()
logger.info('Client closed')
resolve()
}
this.client.end(false, {}, onClose)
// in case a clean close doens't work, force close
this._closeTimeout = setTimeout(() => {
this.client.end(true, {}, onClose)
}, 5000)
} else {
this.removeAllListeners()
resolve()
}
})
}
/**
* Method used to get status
*/
getStatus() {
const status: Record<string, any> = {}
status.status = this.client && this.client.connected
status.error = this.error || 'Offline'
status.config = this.config
return status
}
/**
* Method used to update client connection status
*/
updateClientStatus(connected: boolean) {
if (this.client) {
this.client.publish(
this.getClientTopic(MqttClient.STATUS_TOPIC),
JSON.stringify({ value: connected, time: Date.now() }),
{ retain: this.config.retain, qos: this.config.qos }
)
}
}
/**
* Method used to publish app version to mqtt
*/
publishVersion() {
if (this.client) {
this.client.publish(
this.getClientTopic(MqttClient.VERSION_TOPIC),
JSON.stringify({ value: appVersion, time: Date.now() }),
{ retain: this.config.retain, qos: this.config.qos }
)
}
}
/**
* Method used to update client
*/
async update(config: MqttConfig) {
await this.close()
logger.info('Restarting Mqtt Client after update...')
this._init(config)
}
/**
* Method used to subscribe tags for write requests
*/
subscribe(
topic: string,
options: mqtt.IClientSubscribeOptions & { addPrefix: boolean } = {
qos: 1,
addPrefix: true,
}
): Promise<void> {
return new Promise((resolve, reject) => {
const subOptions: mqtt.IClientSubscribeOptions = {
qos: options.qos,
}
topic = options.addPrefix
? this.config.prefix + '/' + topic + '/set'
: topic
options.addPrefix = false // in case of retry, don't add again the prefix
if (this.client && this.client.connected) {
logger.log(
'debug',
`Subscribing to ${topic} with options %o`,
subOptions
)
this.client.subscribe(topic, subOptions, (err, granted) => {
if (err) {
logger.error(`Error subscribing to ${topic}`, err)
this.toSubscribe.set(topic, options)
reject(err)
} else {
for (const res of granted) {
if (res.qos === 128) {
logger.error(
`Error subscribing to ${topic}, client doesn't have permmission to subscribe to it`
)
} else {
logger.info(`Subscribed to ${topic}`)
}
this.toSubscribe.delete(topic)
}
resolve()
}
})
} else {
logger.debug(
`Client not connected yet, subscribing to ${topic} later...`
)
this.toSubscribe.set(topic, options)
reject(Error('Client not connected'))
}
})
}
/**
* Method used to publish an update
*/
publish(
topic: string,
data: any,
options?: mqtt.IClientPublishOptions,
prefix?: string
) {
if (this.client) {
const settingOptions = {
qos: this.config.qos,
retain: this.config.retain,
}
// by default use settingsOptions
options = Object.assign(settingOptions, options)
topic = (prefix || this.config.prefix) + '/' + topic
logger.log(
'debug',
'Publishing to %s: %o with options %o',
topic,
data,
options
)
this.client.publish(
topic,
JSON.stringify(data),
options,
function (err) {
if (err) {
logger.error(
`Error while publishing a value ${err.message}`
)
}
}
)
} // end if client
}
/**
* Method used to get the topic with prefix/suffix
*/
getTopic(topic: string, set = false) {
return this.config.prefix + '/' + topic + (set ? '/set' : '')
}
/**
* Initialize client
*/
private _init(config: MqttConfig) {
this.config = config
this.toSubscribe = new Map()
if (!config || config.disabled) {
logger.info('MQTT is disabled')
return
}
this._clientID = sanitizeTopic(
MqttClient.NAME_PREFIX + (process.env.MQTT_NAME || config.name)
)
const parsed = url.parse(config.host || '')
let protocol = 'mqtt'
if (parsed.protocol) protocol = parsed.protocol.replace(/:$/, '')
const options: mqtt.IClientOptions = {
clientId: this._clientID,
reconnectPeriod: config.reconnectPeriod,
clean: config.clean,
rejectUnauthorized: !config.allowSelfsigned,
will: {
topic: this.getClientTopic(MqttClient.STATUS_TOPIC),
payload: JSON.stringify({ value: false }),
qos: this.config.qos,
retain: this.config.retain,
},
}
if (['mqtts', 'wss', 'wxs', 'alis', 'tls'].indexOf(protocol) >= 0) {
if (!config.allowSelfsigned) options.ca = config._ca
if (config._key) {
options.key = config._key
}
if (config._cert) {
options.cert = config._cert
}
}
// Temporary fix, seems mqtt store prevents mqtt to work...
// if (config.store) {
// const manager = LevelStore(joinPath(storeDir, 'mqtt'))
// options.incomingStore = manager.incoming
// options.outgoingStore = manager.outgoing
// }
if (config.auth) {
options.username = config.username
options.password = config.password
}
try {
const serverUrl = `${protocol}://${
parsed.hostname || config.host
}:${config.port}`
logger.info(`Connecting to ${serverUrl}`)
const client = mqtt.connect(serverUrl, options)
this.client = client
client.on('connect', this._onConnect.bind(this))
client.on('message', this._onMessageReceived.bind(this))
client.on('reconnect', this._onReconnect.bind(this))
client.on('close', this._onClose.bind(this))
client.on('error', this._onError.bind(this))
client.on('offline', this._onOffline.bind(this))
} catch (e) {
logger.error(`Error while connecting MQTT ${e.message}`)
this.error = e.message
}
}
/**
* Function called when MQTT client connects
*/
private async _onConnect() {
logger.info('MQTT client connected')
this.emit('connect')
const subscribePromises: Promise<void>[] = []
subscribePromises.push(
this.subscribe(MqttClient.HASS_WILL, { addPrefix: false, qos: 1 })
)
// subscribe to actions
// eslint-disable-next-line no-redeclare
for (let i = 0; i < MqttClient.ACTIONS.length; i++) {
subscribePromises.push(
this.subscribe(
[
this.config.prefix,
MqttClient.CLIENTS_PREFIX,
this._clientID,
MqttClient.ACTIONS[i],
'#',
].join('/'),
{ addPrefix: false, qos: 1 }
)
)
}
await allSettled(subscribePromises)
await this._retrySubscribe()
this.emit('brokerStatus', true)
this.publishVersion()
// Update client status
this.updateClientStatus(true)
}
/**
* Function called when MQTT client reconnects
*/
private _onReconnect() {
logger.info('MQTT client reconnecting')
}
/**
* Function called when MQTT client reconnects
*/
private _onError(error: Error) {
logger.error('Mqtt client error', error)
this.error = error.message
}
/**
* Function called when MQTT client go offline
*/
private _onOffline() {
if (this.retrySubTimeout) {
clearTimeout(this.retrySubTimeout)
this.retrySubTimeout = null
}
logger.info('MQTT client offline')
this.emit('brokerStatus', false)
}
/**
* Function called when MQTT client is closed
*/
private _onClose() {
logger.info('MQTT client closed')
}
/**
* Function called when an MQTT message is received
*/
private _onMessageReceived(topic: string, payload: Buffer) {
if (this.closed) return
let parsed: string | number | Record<string, any> | undefined =
payload?.toString()
logger.log('info', `Message received on ${topic}: %o`, parsed)
if (topic === MqttClient.HASS_WILL) {
if (typeof parsed === 'string') {
this.emit('hassStatus', parsed.toLowerCase() === 'online')
} else {
logger.error('Invalid payload sent to Hass Will topic')
}
return
}
// remove prefix
topic = topic.substring(this.config.prefix.length + 1)
const parts = topic.split('/')
// It's not a write request
if (parts.pop() !== 'set') return
if (isNaN(parseInt(parsed))) {
try {
parsed = JSON.parse(parsed)
// eslint-disable-next-line no-empty
} catch (e) {} // it' ok fallback to string
} else {
parsed = Number(parsed)
}
// It's an action
if (parts[0] === MqttClient.CLIENTS_PREFIX) {
if (parts.length < 3) return
const action = MqttClient.ACTIONS.indexOf(parts[2])
switch (action) {
case 0: // broadcast
this.emit('broadcastRequest', parts.slice(3), parsed)
// publish back to give a feedback the action has been received
// same topic without /set suffix
this.publish(parts.join('/'), parsed)
break
case 1: // api
this.emit('apiCall', parts.join('/'), parts[3], parsed)
break
case 2: // multicast
this.emit('multicastRequest', parsed)
// publish back to give a feedback the action has been received
// same topic without /set suffix
this.publish(parts.join('/'), parsed)
break
default:
logger.warn(`Unknown action received ${action} ${topic}`)
}
} else {
// It's a write request on zwave network
this.emit('writeRequest', parts, parsed)
}
} // end onMessageReceived
private async _retrySubscribe() {
if (this.retrySubTimeout) {
clearTimeout(this.retrySubTimeout)
this.retrySubTimeout = null
}
if (this.toSubscribe.size === 0) {
return
}
logger.debug('Retry to subscribe to topics...')
const subscribePromises: Promise<void>[] = []
const topics = this.toSubscribe.keys()
for (const t of topics) {
subscribePromises.push(this.subscribe(t, this.toSubscribe.get(t)))
}
this.toSubscribe == new Map()
await allSettled(subscribePromises)
if (this.toSubscribe.size > 0) {
this.retrySubTimeout = setTimeout(
this._retrySubscribe.bind(this),
5000
)
}
}
}
export default MqttClient | the_stack |
import {useMemo} from 'react';
import * as jsonStableStringify from 'json-stable-stringify';
import {useSubscription} from 'use-subscription';
import {deprecate} from '../util';
import {
ResultFunc,
ResultFuncPure,
Strategy,
RegionOption,
Listener,
Props,
} from '../types';
const increase = (v: number = 0) => (v + 1);
const decrease = (v: number = 0) => (v - 1 > 0 ? v - 1 : 0);
interface ToPromiseParams<TParams, V> {
asyncFunction: (params: TParams) => Promise<V>;
params: any;
}
const toPromise = async <TParams, V>({asyncFunction, params}: ToPromiseParams<TParams, V>) => {
if (typeof asyncFunction === 'function') {
return asyncFunction(params);
}
// promise
return asyncFunction;
};
const formatLoading = (loading?: number) => {
// treat undefined as true
if (loading === undefined) {
return true;
}
return loading > 0;
};
const formatError = (error?: unknown): Error => {
return typeof error === 'string' ? new Error(error) : (error as Error);
};
const getSetResult = <V>(resultOrFunc: V | ResultFuncPure<V>, snapshot: V) => {
if (typeof resultOrFunc === 'function') {
return (resultOrFunc as ResultFuncPure<V>)(snapshot);
}
return resultOrFunc;
};
interface LoadBy<K, V, Extend> {
(
key: K | (() => K),
asyncFunction: () => Promise<V>,
): () => Promise<void>;
<TResult = unknown>(
key: K | (() => K),
asyncFunction: () => Promise<TResult>,
reducer: (state: V | Extend, result: TResult) => V,
): () => Promise<void>;
<TParams = void>(
key: K | ((params: TParams) => K),
asyncFunction: (params: TParams) => Promise<V>,
): (params: TParams) => Promise<void>;
<TParams = void, TResult = unknown>(
key: K | ((params: TParams) => K),
asyncFunction: (params: TParams) => Promise<TResult>,
reducer: (state: V | Extend, result: TResult, params: TParams) => V,
): (params: TParams) => Promise<void>;
}
export interface CreateMappedRegionReturnValue<K, V> {
private_getState_just_for_test: () => any;
private_setState_just_for_test: (value: any) => void;
set: (key: K, resultOrFunc: V | ResultFunc<V>) => void;
reset: (key: K) => void;
resetAll: () => void;
// emit: (key: K) => void;
// emitAll: () => void;
load: (key: K, promise: Promise<V>) => Promise<void>;
loadBy: LoadBy<K, V, undefined>;
getValue: (key: K) => V | undefined;
getLoading: (key: K) => boolean;
getError: (key: K) => Error | undefined;
useValue: {
(key: K): V | undefined;
<TResult>(key: K, selector: (value: V | undefined) => TResult): TResult;
};
useLoading: (key: K) => boolean;
useError: (key: K) => Error | undefined;
}
export interface CreateMappedRegionPureReturnValue<K, V>
extends Omit<CreateMappedRegionReturnValue<K, V>, 'set' | 'loadBy' | 'getValue' | 'useValue'> {
set: (key: K, resultOrFunc: V | ResultFuncPure<V>) => void;
loadBy: LoadBy<K, V, never>;
getValue: (key: K) => V;
useValue: {
(key: K): V;
<TResult>(key: K, selector: (value: V) => TResult): TResult;
};
}
// overload is unsafe in some way, ensure the return type is correct
function createMappedRegion <K, V>(initialValue: void | undefined, option?: RegionOption): CreateMappedRegionReturnValue<K, V>;
function createMappedRegion <K, V>(initialValue: V, option?: RegionOption): CreateMappedRegionPureReturnValue<K, V>;
function createMappedRegion <K, V>(initialValue: V | void | undefined, option?: RegionOption): CreateMappedRegionReturnValue<K, V> | CreateMappedRegionPureReturnValue<K, V> {
type Result = CreateMappedRegionPureReturnValue<K, V>;
const strategy: Strategy = option?.strategy ?? 'acceptLatest';
interface PrivateStoreState {
[key: string]: Props<V>;
}
interface PrivateStoreStateRef {
current: PrivateStoreState;
}
const private_stateRef: PrivateStoreStateRef = {
current: {},
};
const private_store_ensure = (key: string): void => {
if (!private_stateRef.current[key]) {
private_stateRef.current[key] = {};
}
};
const private_store_emit = (key: string): void => {
const props = private_stateRef.current[key];
if (!props) {
return;
}
const {listeners} = props;
if (!listeners) {
return;
}
listeners.forEach(listener => listener());
};
// only used for test
const private_store_getState = (): PrivateStoreState => {
return private_stateRef.current;
};
// only used for test
const private_store_setState = (value: PrivateStoreState): void => {
private_stateRef.current = value;
};
const private_store_getAttribute = <A extends keyof Props<V>>(key: string, attribute: A): Props<V>[A] => {
const props = private_stateRef.current[key];
if (!props) {
return undefined;
}
return props[attribute];
};
const private_store_load = <TResult>(key: string, promise: Promise<TResult>): void => {
private_store_ensure(key);
// since it is ensured
const props = private_stateRef.current[key];
props.promise = promise;
props.pendingMutex = increase(props.pendingMutex);
private_store_emit(key);
};
const private_store_loadEnd = (key: string): void => {
private_store_ensure(key);
// since it is ensured
const props = private_stateRef.current[key];
props.pendingMutex = decrease(props.pendingMutex);
private_store_emit(key);
};
const private_store_set = (key: string, value: V): void => {
private_store_ensure(key);
// since it is ensured
const props = private_stateRef.current[key];
const snapshot = props.value;
const formatValue = typeof value === 'function' ? value(snapshot) : value;
props.pendingMutex = decrease(props.pendingMutex);
props.value = formatValue;
props.error = undefined; // reset error
private_store_emit(key);
};
const private_store_setError = (key: string, error: unknown): void => {
private_store_ensure(key);
// since it is ensured
const props = private_stateRef.current[key];
props.pendingMutex = decrease(props.pendingMutex);
props.error = error;
if (error) {
console.error(error);
}
private_store_emit(key);
};
const private_store_reset = (key: string): void => {
private_stateRef.current[key] = {listeners: private_stateRef.current[key].listeners};
private_store_emit(key);
};
const private_store_resetAll = (): void => {
Object.keys(private_stateRef.current).forEach((key: string) => {
private_stateRef.current[key] = {listeners: private_stateRef.current[key].listeners};
private_store_emit(key);
});
};
// TODO add a regress test to prevent shadow variable usage of listeners
const private_store_subscribe = (key: string, listener: Listener): () => void => {
private_store_ensure(key);
// since it is ensured
const props = private_stateRef.current[key];
if (!props.listeners) {
props.listeners = [];
}
if (typeof listener === 'function') {
props.listeners.push(listener);
} else {
console.warn(`listener should be function, but received ${listener}`);
}
return () => {
private_store_ensure(key);
// since it is ensured
const props = private_stateRef.current[key];
if (!props.listeners) {
props.listeners = [];
}
props.listeners.splice(props.listeners.indexOf(listener), 1);
};
};
/* -------- */
const getKeyString = (key: K | K[]): string => {
if (typeof key === 'string') {
return key;
}
return jsonStableStringify(key);
};
const getValueOrInitialValue = (value: V | undefined): V => {
if (value !== undefined) {
return value;
}
return initialValue as V;
};
// ---- APIs ----
const set: Result['set'] = (key, resultOrFunc) => {
const keyString = getKeyString(key);
// Maybe we can use getValue here
const maybeSnapshot = private_store_getAttribute(keyString, 'value');
const snapshot = getValueOrInitialValue(maybeSnapshot);
const result = getSetResult(resultOrFunc, snapshot);
private_store_set(keyString, result);
return result;
};
const reset: Result['reset'] = (key: K) => {
if (key === undefined) {
deprecate('reset should be called with key, use resetAll to reset all keys.');
private_store_resetAll();
}
const keyString = getKeyString(key);
private_store_reset(keyString);
};
const resetAll: Result['resetAll'] = private_store_resetAll;
// const emit: Result['emit'] = (key: K) => {
// const keyString = getKeyString(key);
// private_store_emit(keyString);
// };
//
// const emitAll: Result['emitAll'] = private_store_emitAll;
const loadBy: Result['loadBy'] = <TParams = void, TResult = unknown>(
key: K | ((params: TParams) => K),
asyncFunction: (params: TParams) => Promise<TResult>,
reducer?: (state: V, result: TResult, params: TParams) => V
) => {
const loadByReturnFunction = async (params?: TParams) => {
const loadKey = typeof key === 'function' ? (key as any)(params) : key;
const keyString = getKeyString(loadKey);
const promise = toPromise({asyncFunction, params});
private_store_load(keyString, promise);
/**
* note
* 1. always get value after await, so it is the current one
* 2. ensure if initialValue is gaven, every branch should return initialValueOfKey as T[K]
*/
try {
const result = await promise;
const currentPromise = private_store_getAttribute(keyString, 'promise');
const snapshot = private_store_getAttribute(keyString, 'value');
const formattedResult = typeof reducer === 'function'
? reducer(getValueOrInitialValue(snapshot), result, params as TParams)
: result as unknown as V;
if (strategy === 'acceptLatest' && promise !== currentPromise) {
// decrease loading & return snapshot
private_store_loadEnd(keyString);
return getValueOrInitialValue(snapshot) as never;
}
private_store_set(keyString, formattedResult);
return getValueOrInitialValue(formattedResult) as never;
} catch (error) {
const currentPromise = private_store_getAttribute(keyString, 'promise');
const snapshot = private_store_getAttribute(keyString, 'value');
if (strategy === 'acceptLatest' && promise !== currentPromise) {
// decrease loading & return snapshot
private_store_loadEnd(keyString);
return getValueOrInitialValue(snapshot) as never;
}
private_store_setError(keyString, error);
return getValueOrInitialValue(snapshot) as never;
}
};
return loadByReturnFunction;
};
const load: Result['load'] = async (key, promise) => {
if (promise instanceof Promise || typeof promise === 'function') {
return loadBy(key, promise as unknown as any)();
}
console.warn('set result directly');
return set(key, promise);
};
const getValue: Result['getValue'] = key => {
const keyString = getKeyString(key);
const value = private_store_getAttribute(keyString, 'value');
return getValueOrInitialValue(value);
};
const getLoading: Result['getLoading'] = key => {
const keyString = getKeyString(key);
return formatLoading(private_store_getAttribute(keyString, 'pendingMutex'));
};
const getError: Result['getError'] = key => {
const keyString = getKeyString(key);
return formatError(private_store_getAttribute(keyString, 'error'));
};
const createHooks = <TReturnType>(getFn: (key: K) => TReturnType) => {
return (key: K): TReturnType => {
const subscription = useMemo(
() => ({
getCurrentValue: () => getFn(key),
subscribe: (listener: Listener) => private_store_subscribe(getKeyString(key), listener),
}),
// shallow-equal
// eslint-disable-next-line react-hooks/exhaustive-deps
[getFn, getKeyString(key)]
);
return useSubscription(subscription);
};
};
const useValue: Result['useValue'] = <TResult>(key: K, selector?: (value: V) => TResult) => {
// keep logic as createHook is
const getFn = getValue;
const subscription = useMemo(
() => ({
getCurrentValue: () => (selector ? selector(getFn(key)) : getFn(key)),
subscribe: (listener: Listener) => private_store_subscribe(getKeyString(key), listener),
}),
// shallow-equal
// eslint-disable-next-line react-hooks/exhaustive-deps
[getFn, selector, getKeyString(key)]
);
return useSubscription(subscription);
};
const useLoading: Result['useLoading'] = createHooks(getLoading);
const useError: Result['useError'] = createHooks(getError);
return {
private_getState_just_for_test: private_store_getState,
private_setState_just_for_test: private_store_setState,
set,
reset,
resetAll,
// emit,
// emitAll,
load,
loadBy,
getValue,
getLoading,
getError,
useValue,
useLoading,
useError,
};
}
export default createMappedRegion; | the_stack |
import {LinkAccessor} from './linklengths'
export interface LinkTypeAccessor<Link> extends LinkAccessor<Link> {
// return a unique identifier for the type of the link
getType(l: Link): number;
}
export class PowerEdge {
constructor(
public source: any,
public target: any,
public type: number) { }
}
export class Configuration<Link> {
// canonical list of modules.
// Initialized to a module for each leaf node, such that the ids and indexes of the module in the array match the indexes of the nodes in links
// Modules created through merges are appended to the end of this.
modules: Module[];
// top level modules and candidates for merges
roots: ModuleSet[];
// remaining edge count
R: number;
constructor(n: number, edges: Link[], private linkAccessor: LinkTypeAccessor<Link>, rootGroup?: any[]) {
this.modules = new Array(n);
this.roots = [];
if (rootGroup) {
this.initModulesFromGroup(rootGroup);
} else {
this.roots.push(new ModuleSet());
for (var i = 0; i < n; ++i)
this.roots[0].add(this.modules[i] = new Module(i));
}
this.R = edges.length;
edges.forEach(e => {
var s = this.modules[linkAccessor.getSourceIndex(e)],
t = this.modules[linkAccessor.getTargetIndex(e)],
type = linkAccessor.getType(e);
s.outgoing.add(type, t);
t.incoming.add(type, s);
});
}
private initModulesFromGroup(group): ModuleSet {
var moduleSet = new ModuleSet();
this.roots.push(moduleSet);
for (var i = 0; i < group.leaves.length; ++i) {
var node = group.leaves[i];
var module = new Module(node.id);
this.modules[node.id] = module;
moduleSet.add(module);
}
if (group.groups) {
for (var j = 0; j < group.groups.length; ++j) {
var child = group.groups[j];
// Propagate group properties (like padding, stiffness, ...) as module definition so that the generated power graph group will inherit it
var definition = {};
for (var prop in child)
if (prop !== "leaves" && prop !== "groups" && child.hasOwnProperty(prop))
definition[prop] = child[prop];
// Use negative module id to avoid clashes between predefined and generated modules
moduleSet.add(new Module(-1-j, new LinkSets(), new LinkSets(), this.initModulesFromGroup(child), definition));
}
}
return moduleSet;
}
// merge modules a and b keeping track of their power edges and removing the from roots
merge(a: Module, b: Module, k: number = 0): Module {
var inInt = a.incoming.intersection(b.incoming),
outInt = a.outgoing.intersection(b.outgoing);
var children = new ModuleSet();
children.add(a);
children.add(b);
var m = new Module(this.modules.length, outInt, inInt, children);
this.modules.push(m);
var update = (s: LinkSets, i: string, o: string) => {
s.forAll((ms, linktype) => {
ms.forAll(n => {
var nls = <LinkSets>n[i];
nls.add(linktype, m);
nls.remove(linktype, a);
nls.remove(linktype, b);
(<LinkSets>a[o]).remove(linktype, n);
(<LinkSets>b[o]).remove(linktype, n);
});
});
};
update(outInt, "incoming", "outgoing");
update(inInt, "outgoing", "incoming");
this.R -= inInt.count() + outInt.count();
this.roots[k].remove(a);
this.roots[k].remove(b);
this.roots[k].add(m);
return m;
}
private rootMerges(k: number = 0): {
id: number;
nEdges: number;
a: Module;
b: Module;
}[] {
var rs = this.roots[k].modules();
var n = rs.length;
var merges = new Array(n * (n - 1));
var ctr = 0;
for (var i = 0, i_ = n - 1; i < i_; ++i) {
for (var j = i+1; j < n; ++j) {
var a = rs[i], b = rs[j];
merges[ctr] = { id: ctr, nEdges: this.nEdges(a, b), a: a, b: b };
ctr++;
}
}
return merges;
}
greedyMerge(): boolean {
for (var i = 0; i < this.roots.length; ++i) {
// Handle single nested module case
if (this.roots[i].modules().length < 2) continue;
// find the merge that allows for the most edges to be removed. secondary ordering based on arbitrary id (for predictability)
var ms = this.rootMerges(i).sort((a, b) => a.nEdges == b.nEdges ? a.id - b.id : a.nEdges - b.nEdges);
var m = ms[0];
if (m.nEdges >= this.R) continue;
this.merge(m.a, m.b, i);
return true;
}
}
private nEdges(a: Module, b: Module): number {
var inInt = a.incoming.intersection(b.incoming),
outInt = a.outgoing.intersection(b.outgoing);
return this.R - inInt.count() - outInt.count();
}
getGroupHierarchy(retargetedEdges: PowerEdge[]): any[]{
var groups = [];
var root = {};
toGroups(this.roots[0], root, groups);
var es = this.allEdges();
es.forEach(e => {
var a = this.modules[e.source];
var b = this.modules[e.target];
retargetedEdges.push(new PowerEdge(
typeof a.gid === "undefined" ? e.source : groups[a.gid],
typeof b.gid === "undefined" ? e.target : groups[b.gid],
e.type
));
});
return groups;
}
allEdges(): PowerEdge[] {
var es = [];
Configuration.getEdges(this.roots[0], es);
return es;
}
static getEdges(modules: ModuleSet, es: PowerEdge[]) {
modules.forAll(m => {
m.getEdges(es);
Configuration.getEdges(m.children, es);
});
}
}
function toGroups(modules: ModuleSet, group, groups) {
modules.forAll(m => {
if (m.isLeaf()) {
if (!group.leaves) group.leaves = [];
group.leaves.push(m.id);
} else {
var g = group;
m.gid = groups.length;
if (!m.isIsland() || m.isPredefined()) {
g = { id: m.gid };
if (m.isPredefined())
// Apply original group properties
for (var prop in m.definition)
g[prop] = m.definition[prop];
if (!group.groups) group.groups = [];
group.groups.push(m.gid);
groups.push(g);
}
toGroups(m.children, g, groups);
}
});
}
export class Module {
gid: number;
constructor(
public id: number,
public outgoing: LinkSets = new LinkSets(),
public incoming: LinkSets = new LinkSets(),
public children: ModuleSet = new ModuleSet(),
public definition?: any) { }
getEdges(es: PowerEdge[]) {
this.outgoing.forAll((ms, edgetype) => {
ms.forAll(target => {
es.push(new PowerEdge(this.id, target.id, edgetype));
});
});
}
isLeaf() {
return this.children.count() === 0;
}
isIsland() {
return this.outgoing.count() === 0 && this.incoming.count() === 0;
}
isPredefined(): boolean {
return typeof this.definition !== "undefined";
}
}
function intersection(m: any, n: any): any {
var i = {};
for (var v in m) if (v in n) i[v] = m[v];
return i;
}
export class ModuleSet {
table: any = {};
count() {
return Object.keys(this.table).length;
}
intersection(other: ModuleSet): ModuleSet {
var result = new ModuleSet();
result.table = intersection(this.table, other.table);
return result;
}
intersectionCount(other: ModuleSet): number {
return this.intersection(other).count();
}
contains(id: number): boolean {
return id in this.table;
}
add(m: Module): void {
this.table[m.id] = m;
}
remove(m: Module): void {
delete this.table[m.id];
}
forAll(f: (m: Module) => void) {
for (var mid in this.table) {
f(this.table[mid]);
}
}
modules(): Module[] {
var vs = [];
this.forAll(m => {
if (!m.isPredefined())
vs.push(m);
});
return vs;
}
}
export class LinkSets {
sets: any = {};
n: number = 0;
count(): number {
return this.n;
}
contains(id: number) {
var result = false;
this.forAllModules(m => {
if (!result && m.id == id) {
result = true;
}
});
return result;
}
add(linktype: number, m: Module) {
var s: ModuleSet = linktype in this.sets ? this.sets[linktype] : this.sets[linktype] = new ModuleSet();
s.add(m);
++this.n;
}
remove(linktype: number, m: Module) {
var ms = <ModuleSet>this.sets[linktype];
ms.remove(m);
if (ms.count() === 0) {
delete this.sets[linktype];
}
--this.n;
}
forAll(f: (ms: ModuleSet, linktype: number) => void) {
for (var linktype in this.sets) {
f(<ModuleSet>this.sets[linktype], Number(linktype));
}
}
forAllModules(f: (m: Module) => void) {
this.forAll((ms, lt) => ms.forAll(f));
}
intersection(other: LinkSets): LinkSets {
var result: LinkSets = new LinkSets();
this.forAll((ms, lt) => {
if (lt in other.sets) {
var i = ms.intersection(other.sets[lt]),
n = i.count();
if (n > 0) {
result.sets[lt] = i;
result.n += n;
}
}
});
return result;
}
}
function intersectionCount(m: any, n: any): number {
return Object.keys(intersection(m, n)).length
}
export function getGroups<Link>(nodes: any[], links: Link[], la: LinkTypeAccessor<Link>, rootGroup?: any[]): { groups: any[]; powerEdges: PowerEdge[] } {
var n = nodes.length,
c = new Configuration(n, links, la, rootGroup);
while (c.greedyMerge());
var powerEdges: PowerEdge[] = [];
var g = c.getGroupHierarchy(powerEdges);
powerEdges.forEach(function (e) {
var f = (end) => {
var g = e[end];
if (typeof g == "number") e[end] = nodes[g];
};
f("source");
f("target");
});
return { groups: g, powerEdges: powerEdges };
} | the_stack |
import { SharePointQueryable, SharePointQueryableInstance, SharePointQueryableCollection } from "./sharepointqueryable";
import { ClientPeoplePickerQueryParameters, HashTagCollection, PeoplePickerEntity, UserProfile } from "./types";
import { readBlobAsArrayBuffer } from "../utils/files";
import { Util } from "../utils/util";
import { ODataValue } from "../odata/parsers";
export class UserProfileQuery extends SharePointQueryableInstance {
private clientPeoplePickerQuery: ClientPeoplePickerQuery;
private profileLoader: ProfileLoader;
/**
* Creates a new instance of the UserProfileQuery class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this user profile query
*/
constructor(baseUrl: string | SharePointQueryable, path = "_api/sp.userprofiles.peoplemanager") {
super(baseUrl, path);
this.clientPeoplePickerQuery = new ClientPeoplePickerQuery(baseUrl);
this.profileLoader = new ProfileLoader(baseUrl);
}
/**
* The url of the edit profile page for the current user
*/
public get editProfileLink(): Promise<string> {
return this.clone(UserProfileQuery, "EditProfileLink").getAs(ODataValue<string>());
}
/**
* A boolean value that indicates whether the current user's "People I'm Following" list is public
*/
public get isMyPeopleListPublic(): Promise<boolean> {
return this.clone(UserProfileQuery, "IsMyPeopleListPublic").getAs(ODataValue<boolean>());
}
/**
* A boolean value that indicates whether the current user is being followed by the specified user
*
* @param loginName The account name of the user
*/
public amIFollowedBy(loginName: string): Promise<boolean> {
const q = this.clone(UserProfileQuery, "amifollowedby(@v)");
q.query.add("@v", `'${encodeURIComponent(loginName)}'`);
return q.get();
}
/**
* A boolean value that indicates whether the current user is following the specified user
*
* @param loginName The account name of the user
*/
public amIFollowing(loginName: string): Promise<boolean> {
const q = this.clone(UserProfileQuery, "amifollowing(@v)");
q.query.add("@v", `'${encodeURIComponent(loginName)}'`);
return q.get();
}
/**
* Gets tags that the current user is following
*
* @param maxCount The maximum number of tags to retrieve (default is 20)
*/
public getFollowedTags(maxCount = 20): Promise<string[]> {
return this.clone(UserProfileQuery, `getfollowedtags(${maxCount})`).get();
}
/**
* Gets the people who are following the specified user
*
* @param loginName The account name of the user
*/
public getFollowersFor(loginName: string): Promise<any[]> {
const q = this.clone(UserProfileQuery, "getfollowersfor(@v)");
q.query.add("@v", `'${encodeURIComponent(loginName)}'`);
return q.get();
}
/**
* Gets the people who are following the current user
*
*/
public get myFollowers(): SharePointQueryableCollection {
return new SharePointQueryableCollection(this, "getmyfollowers");
}
/**
* Gets user properties for the current user
*
*/
public get myProperties(): SharePointQueryableInstance {
return new UserProfileQuery(this, "getmyproperties");
}
/**
* Gets the people who the specified user is following
*
* @param loginName The account name of the user.
*/
public getPeopleFollowedBy(loginName: string): Promise<any[]> {
const q = this.clone(UserProfileQuery, "getpeoplefollowedby(@v)");
q.query.add("@v", `'${encodeURIComponent(loginName)}'`);
return q.get();
}
/**
* Gets user properties for the specified user.
*
* @param loginName The account name of the user.
*/
public getPropertiesFor(loginName: string): Promise<any> {
const q = this.clone(UserProfileQuery, "getpropertiesfor(@v)");
q.query.add("@v", `'${encodeURIComponent(loginName)}'`);
return q.get();
}
/**
* Gets the 20 most popular hash tags over the past week, sorted so that the most popular tag appears first
*
*/
public get trendingTags(): Promise<HashTagCollection> {
const q = this.clone(UserProfileQuery, null);
q.concat(".gettrendingtags");
return q.get();
}
/**
* Gets the specified user profile property for the specified user
*
* @param loginName The account name of the user
* @param propertyName The case-sensitive name of the property to get
*/
public getUserProfilePropertyFor(loginName: string, propertyName: string): Promise<string> {
const q = this.clone(UserProfileQuery, `getuserprofilepropertyfor(accountname=@v, propertyname='${propertyName}')`);
q.query.add("@v", `'${encodeURIComponent(loginName)}'`);
return q.get();
}
/**
* Removes the specified user from the user's list of suggested people to follow
*
* @param loginName The account name of the user
*/
public hideSuggestion(loginName: string): Promise<void> {
const q = this.clone(UserProfileQuery, "hidesuggestion(@v)");
q.query.add("@v", `'${encodeURIComponent(loginName)}'`);
return q.postCore();
}
/**
* A boolean values that indicates whether the first user is following the second user
*
* @param follower The account name of the user who might be following the followee
* @param followee The account name of the user who might be followed by the follower
*/
public isFollowing(follower: string, followee: string): Promise<boolean> {
const q = this.clone(UserProfileQuery, null);
q.concat(`.isfollowing(possiblefolloweraccountname=@v, possiblefolloweeaccountname=@y)`);
q.query.add("@v", `'${encodeURIComponent(follower)}'`);
q.query.add("@y", `'${encodeURIComponent(followee)}'`);
return q.get();
}
/**
* Uploads and sets the user profile picture (Users can upload a picture to their own profile only). Not supported for batching.
*
* @param profilePicSource Blob data representing the user's picture in BMP, JPEG, or PNG format of up to 4.76MB
*/
public setMyProfilePic(profilePicSource: Blob): Promise<void> {
return new Promise<void>((resolve, reject) => {
readBlobAsArrayBuffer(profilePicSource).then((buffer) => {
const request = new UserProfileQuery(this, "setmyprofilepicture");
request.postCore({
body: String.fromCharCode.apply(null, new Uint16Array(buffer)),
}).then(_ => resolve());
}).catch(e => reject(e));
});
}
/**
* Sets single value User Profile property
*
* @param accountName The account name of the user
* @param propertyName Property name
* @param propertyValue Property value
*/
public setSingleValueProfileProperty(accountName: string, propertyName: string, propertyValue: string): Promise<void> {
const postBody: string = JSON.stringify({
accountName: accountName,
propertyName: propertyName,
propertyValue: propertyValue,
});
return this.clone(UserProfileQuery, "SetSingleValueProfileProperty")
.postCore({ body: postBody });
}
/**
* Sets multi valued User Profile property
*
* @param accountName The account name of the user
* @param propertyName Property name
* @param propertyValues Property values
*/
public setMultiValuedProfileProperty(accountName: string, propertyName: string, propertyValues: string[]): Promise<void> {
const postBody: string = JSON.stringify({
accountName: accountName,
propertyName: propertyName,
propertyValues: propertyValues,
});
return this.clone(UserProfileQuery, "SetMultiValuedProfileProperty")
.postCore({ body: postBody });
}
/**
* Provisions one or more users' personal sites. (My Site administrator on SharePoint Online only)
*
* @param emails The email addresses of the users to provision sites for
*/
public createPersonalSiteEnqueueBulk(...emails: string[]): Promise<void> {
return this.profileLoader.createPersonalSiteEnqueueBulk(emails);
}
/**
* Gets the user profile of the site owner
*
*/
public get ownerUserProfile(): Promise<UserProfile> {
return this.profileLoader.ownerUserProfile;
}
/**
* Gets the user profile for the current user
*/
public get userProfile(): Promise<any> {
return this.profileLoader.userProfile;
}
/**
* Enqueues creating a personal site for this user, which can be used to share documents, web pages, and other files
*
* @param interactiveRequest true if interactively (web) initiated request, or false (default) if non-interactively (client) initiated request
*/
public createPersonalSite(interactiveRequest = false): Promise<void> {
return this.profileLoader.createPersonalSite(interactiveRequest);
}
/**
* Sets the privacy settings for this profile
*
* @param share true to make all social data public; false to make all social data private
*/
public shareAllSocialData(share: boolean): Promise<void> {
return this.profileLoader.shareAllSocialData(share);
}
/**
* Resolves user or group using specified query parameters
*
* @param queryParams The query parameters used to perform resolve
*/
public clientPeoplePickerResolveUser(queryParams: ClientPeoplePickerQueryParameters): Promise<PeoplePickerEntity> {
return this.clientPeoplePickerQuery.clientPeoplePickerResolveUser(queryParams);
}
/**
* Searches for users or groups using specified query parameters
*
* @param queryParams The query parameters used to perform search
*/
public clientPeoplePickerSearchUser(queryParams: ClientPeoplePickerQueryParameters): Promise<PeoplePickerEntity[]> {
return this.clientPeoplePickerQuery.clientPeoplePickerSearchUser(queryParams);
}
}
class ProfileLoader extends SharePointQueryable {
/**
* Creates a new instance of the ProfileLoader class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this profile loader
*/
constructor(baseUrl: string | SharePointQueryable, path = "_api/sp.userprofiles.profileloader.getprofileloader") {
super(baseUrl, path);
}
/**
* Provisions one or more users' personal sites. (My Site administrator on SharePoint Online only) Doesn't support batching
*
* @param emails The email addresses of the users to provision sites for
*/
public createPersonalSiteEnqueueBulk(emails: string[]): Promise<void> {
return this.clone(ProfileLoader, "createpersonalsiteenqueuebulk", false).postCore({
body: JSON.stringify({ "emailIDs": emails }),
});
}
/**
* Gets the user profile of the site owner.
*
*/
public get ownerUserProfile(): Promise<UserProfile> {
let q = this.getParent(ProfileLoader, this.parentUrl, "_api/sp.userprofiles.profileloader.getowneruserprofile");
if (this.hasBatch) {
q = q.inBatch(this.batch);
}
return q.postAsCore<UserProfile>();
}
/**
* Gets the user profile of the current user.
*
*/
public get userProfile(): Promise<UserProfile> {
return this.clone(ProfileLoader, "getuserprofile").postAsCore<UserProfile>();
}
/**
* Enqueues creating a personal site for this user, which can be used to share documents, web pages, and other files.
*
* @param interactiveRequest true if interactively (web) initiated request, or false (default) if non-interactively (client) initiated request
*/
public createPersonalSite(interactiveRequest = false): Promise<void> {
return this.clone(ProfileLoader, `getuserprofile/createpersonalsiteenque(${interactiveRequest})`).postCore();
}
/**
* Sets the privacy settings for this profile
*
* @param share true to make all social data public; false to make all social data private.
*/
public shareAllSocialData(share: boolean): Promise<void> {
return this.clone(ProfileLoader, `getuserprofile/shareallsocialdata(${share})`).postCore();
}
}
class ClientPeoplePickerQuery extends SharePointQueryable {
/**
* Creates a new instance of the PeoplePickerQuery class
*
* @param baseUrl The url or SharePointQueryable which forms the parent of this people picker query
*/
constructor(baseUrl: string | SharePointQueryable, path = "_api/sp.ui.applicationpages.clientpeoplepickerwebserviceinterface") {
super(baseUrl, path);
}
/**
* Resolves user or group using specified query parameters
*
* @param queryParams The query parameters used to perform resolve
*/
public clientPeoplePickerResolveUser(queryParams: ClientPeoplePickerQueryParameters): Promise<PeoplePickerEntity> {
const q = this.clone(ClientPeoplePickerQuery, null);
q.concat(".clientpeoplepickerresolveuser");
return q.postAsCore<string>({
body: this.createClientPeoplePickerQueryParametersRequestBody(queryParams),
}).then((json) => JSON.parse(json));
}
/**
* Searches for users or groups using specified query parameters
*
* @param queryParams The query parameters used to perform search
*/
public clientPeoplePickerSearchUser(queryParams: ClientPeoplePickerQueryParameters): Promise<PeoplePickerEntity[]> {
const q = this.clone(ClientPeoplePickerQuery, null);
q.concat(".clientpeoplepickersearchuser");
return q.postAsCore<string>({
body: this.createClientPeoplePickerQueryParametersRequestBody(queryParams),
}).then((json) => JSON.parse(json));
}
/**
* Creates ClientPeoplePickerQueryParameters request body
*
* @param queryParams The query parameters to create request body
*/
private createClientPeoplePickerQueryParametersRequestBody(queryParams: ClientPeoplePickerQueryParameters): string {
return JSON.stringify({
"queryParams":
Util.extend({
"__metadata": { "type": "SP.UI.ApplicationPages.ClientPeoplePickerQueryParameters" },
}, queryParams),
});
}
} | the_stack |
import { chart_color_cyan_400 as knativeServingColor } from '@patternfly/react-tokens/dist/js/chart_color_cyan_400';
import { chart_color_red_300 as knativeEventingColor } from '@patternfly/react-tokens/dist/js/chart_color_red_300';
import { K8sKind } from '@console/internal/module/k8s';
import {
KNATIVE_EVENT_SOURCE_APIGROUP,
KNATIVE_EVENT_SOURCE_APIGROUP_DEP,
KNATIVE_SERVING_APIGROUP,
KNATIVE_EVENT_MESSAGE_APIGROUP,
KNATIVE_EVENTING_APIGROUP,
STRIMZI_KAFKA_APIGROUP,
CAMEL_APIGROUP,
} from './const';
const apiVersion = 'v1';
export const ConfigurationModel: K8sKind = {
apiGroup: KNATIVE_SERVING_APIGROUP,
apiVersion,
kind: 'Configuration',
plural: 'configurations',
label: 'Configuration',
// t('knative-plugin~Configuration')
labelKey: 'knative-plugin~Configuration',
labelPlural: 'Configurations',
// t('knative-plugin~Configurations')
labelPluralKey: 'knative-plugin~Configurations',
id: 'configuration',
abbr: 'CFG',
namespaced: true,
crd: true,
color: knativeServingColor.value,
};
export const KnativeServingModel: K8sKind = {
apiGroup: 'operator.knative.dev',
apiVersion: 'v1alpha1',
kind: 'KnativeServing',
label: 'KnativeServing',
// t('knative-plugin~KnativeServing')
labelKey: 'knative-plugin~KnativeServing',
labelPlural: 'KnativeServings',
// t('knative-plugin~KnativeServings')
labelPluralKey: 'knative-plugin~KnativeServings',
plural: 'knativeservings',
id: 'knativeserving',
abbr: 'KS',
namespaced: true,
crd: true,
color: knativeServingColor.value,
};
export const KnativeEventingModel: K8sKind = {
apiGroup: 'operator.knative.dev',
apiVersion: 'v1alpha1',
kind: 'KnativeEventing',
label: 'KnativeEventing',
// t('knative-plugin~KnativeEventing')
labelKey: 'knative-plugin~KnativeEventing',
labelPlural: 'KnativeEventings',
// t('knative-plugin~KnativeEventings')
labelPluralKey: 'knative-plugin~KnativeEventings',
plural: 'knativeeventings',
id: 'knativeeventing',
abbr: 'KE',
namespaced: true,
crd: true,
color: knativeEventingColor.value,
};
export const RevisionModel: K8sKind = {
apiGroup: KNATIVE_SERVING_APIGROUP,
apiVersion,
kind: 'Revision',
label: 'Revision',
// t('knative-plugin~Revision')
labelKey: 'knative-plugin~Revision',
// t('knative-plugin~Revisions')
labelPluralKey: 'knative-plugin~Revisions',
labelPlural: 'Revisions',
plural: 'revisions',
id: 'revision',
abbr: 'REV',
namespaced: true,
crd: true,
color: knativeServingColor.value,
};
export const RouteModel: K8sKind = {
apiGroup: KNATIVE_SERVING_APIGROUP,
apiVersion,
kind: 'Route',
label: 'Route',
// t('knative-plugin~Route')
labelKey: 'knative-plugin~Route',
labelPlural: 'Routes',
// t('knative-plugin~Routes')
labelPluralKey: 'knative-plugin~Routes',
plural: 'routes',
id: 'route',
abbr: 'RT',
namespaced: true,
crd: true,
color: knativeServingColor.value,
};
export const ServiceModel: K8sKind = {
apiGroup: KNATIVE_SERVING_APIGROUP,
apiVersion,
kind: 'Service',
label: 'Service',
// t('knative-plugin~Service')
labelKey: 'knative-plugin~Service',
// t('knative-plugin~Services')
labelPluralKey: 'knative-plugin~Services',
labelPlural: 'Services',
plural: 'services',
id: 'service',
abbr: 'KSVC',
namespaced: true,
crd: true,
color: knativeServingColor.value,
};
export const DomainMappingModel: K8sKind = {
apiGroup: KNATIVE_SERVING_APIGROUP,
apiVersion: 'v1alpha1',
kind: 'DomainMapping',
label: 'DomainMapping',
// t('knative-plugin~DomainMapping')
labelKey: 'knative-plugin~DomainMapping',
labelPlural: 'DomainMappings',
// t('knative-plugin~DomainMappings')
labelPluralKey: 'knative-plugin~DomainMappings',
plural: 'domainmappings',
id: 'DomainMapping',
abbr: 'DM',
namespaced: true,
crd: true,
color: knativeServingColor.value,
};
export const EventSourceCronJobModel: K8sKind = {
apiGroup: KNATIVE_EVENT_SOURCE_APIGROUP_DEP,
apiVersion: 'v1alpha1',
kind: 'CronJobSource',
label: 'CronJobSource',
// t('knative-plugin~CronJobSource')
labelKey: 'knative-plugin~CronJobSource',
labelPlural: 'CronJobSources',
// t('knative-plugin~CronJobSources')
labelPluralKey: 'knative-plugin~CronJobSources',
plural: 'cronjobsources',
id: 'cronjobsource',
abbr: 'CJS',
namespaced: true,
crd: true,
color: knativeEventingColor.value,
};
export const EventSourcePingModel: K8sKind = {
apiGroup: KNATIVE_EVENT_SOURCE_APIGROUP,
apiVersion: 'v1beta2',
kind: 'PingSource',
label: 'PingSource',
// t('knative-plugin~PingSource')
labelKey: 'knative-plugin~PingSource',
labelPlural: 'PingSources',
// t('knative-plugin~PingSources')
labelPluralKey: 'knative-plugin~PingSources',
plural: 'pingsources',
id: 'pingsource',
abbr: 'PS',
namespaced: true,
crd: true,
color: knativeEventingColor.value,
};
export const EventSourceContainerModel: K8sKind = {
apiGroup: KNATIVE_EVENT_SOURCE_APIGROUP,
apiVersion,
kind: 'ContainerSource',
label: 'ContainerSource',
// t('knative-plugin~ContainerSource')
labelKey: 'knative-plugin~ContainerSource',
labelPlural: 'ContainerSources',
// t('knative-plugin~ContainerSources')
labelPluralKey: 'knative-plugin~ContainerSources',
plural: 'containersources',
id: 'containersource',
abbr: 'CS',
namespaced: true,
crd: true,
color: knativeEventingColor.value,
};
export const EventSourceApiServerModel: K8sKind = {
apiGroup: KNATIVE_EVENT_SOURCE_APIGROUP,
apiVersion,
kind: 'ApiServerSource',
label: 'ApiServerSource',
// t('knative-plugin~ApiServerSource')
labelKey: 'knative-plugin~ApiServerSource',
labelPlural: 'ApiServerSources',
// t('knative-plugin~ApiServerSources')
labelPluralKey: 'knative-plugin~ApiServerSources',
plural: 'apiserversources',
id: 'apiserversource',
abbr: 'AS',
namespaced: true,
crd: true,
color: knativeEventingColor.value,
};
export const EventSourceCamelModel: K8sKind = {
apiGroup: KNATIVE_EVENT_SOURCE_APIGROUP,
apiVersion: 'v1alpha1',
kind: 'CamelSource',
label: 'CamelSource',
// t('knative-plugin~CamelSource')
labelKey: 'knative-plugin~CamelSource',
labelPlural: 'CamelSources',
// t('knative-plugin~CamelSources')
labelPluralKey: 'knative-plugin~CamelSources',
plural: 'camelsources',
id: 'camelsource',
abbr: 'CS',
namespaced: true,
crd: true,
color: knativeEventingColor.value,
};
export const EventSourceKafkaModel: K8sKind = {
apiGroup: KNATIVE_EVENT_SOURCE_APIGROUP,
apiVersion: 'v1beta1',
kind: 'KafkaSource',
label: 'KafkaSource',
// t('knative-plugin~KafkaSource')
labelKey: 'knative-plugin~KafkaSource',
labelPlural: 'KafkaSources',
// t('knative-plugin~KafkaSources')
labelPluralKey: 'knative-plugin~KafkaSources',
plural: 'kafkasources',
id: 'kafkasource',
abbr: 'KS',
namespaced: true,
crd: true,
color: knativeEventingColor.value,
};
export const EventSourceSinkBindingModel: K8sKind = {
apiGroup: KNATIVE_EVENT_SOURCE_APIGROUP,
apiVersion,
kind: 'SinkBinding',
label: 'SinkBinding',
// t('knative-plugin~SinkBinding')
labelKey: 'knative-plugin~SinkBinding',
labelPlural: 'SinkBindings',
// t('knative-plugin~SinkBindings')
labelPluralKey: 'knative-plugin~SinkBindings',
plural: 'sinkbindings',
id: 'sinkbindingsource',
abbr: 'SBS',
namespaced: true,
crd: true,
color: knativeEventingColor.value,
};
export const EventingSubscriptionModel: K8sKind = {
apiGroup: KNATIVE_EVENT_MESSAGE_APIGROUP,
apiVersion,
kind: 'Subscription',
label: 'Subscription',
// t('knative-plugin~Subscription')
labelKey: 'knative-plugin~Subscription',
labelPlural: 'Subscriptions',
// t('knative-plugin~Subscriptions')
labelPluralKey: 'knative-plugin~Subscriptions',
plural: 'subscriptions',
id: 'subscriptioneventing',
abbr: 'S',
namespaced: true,
crd: true,
color: knativeEventingColor.value,
};
export const EventingIMCModel: K8sKind = {
apiGroup: KNATIVE_EVENT_MESSAGE_APIGROUP,
apiVersion,
kind: 'InMemoryChannel',
label: 'InMemoryChannel',
// t('knative-plugin~InMemoryChannel')
labelKey: 'knative-plugin~InMemoryChannel',
// t('knative-plugin~InMemoryChannels')
labelPluralKey: 'knative-plugin~InMemoryChannels',
labelPlural: 'InMemoryChannels',
plural: 'inmemorychannels',
id: 'inmemorychannel',
abbr: 'IMC',
namespaced: true,
crd: true,
color: knativeEventingColor.value,
};
export const EventingChannelModel: K8sKind = {
apiGroup: KNATIVE_EVENT_MESSAGE_APIGROUP,
apiVersion,
kind: 'Channel',
label: 'Channel',
// t('knative-plugin~Channel')
labelKey: 'knative-plugin~Channel',
labelPlural: 'Channels',
// t('knative-plugin~Channels')
labelPluralKey: 'knative-plugin~Channels',
plural: 'channels',
id: 'channel',
abbr: 'C',
namespaced: true,
crd: true,
color: knativeEventingColor.value,
};
export const EventingKafkaChannelModel: K8sKind = {
apiGroup: KNATIVE_EVENT_MESSAGE_APIGROUP,
apiVersion: 'v1beta1',
kind: 'KafkaChannel',
label: 'KafkaChannel',
// t('knative-plugin~KafkaChannel')
labelKey: 'knative-plugin~KafkaChannel',
labelPlural: 'KafkaChannels',
// t('knative-plugin~KafkaChannels')
labelPluralKey: 'knative-plugin~KafkaChannels',
plural: 'kafkachannels',
id: 'kafkaChannel',
abbr: 'KC',
namespaced: true,
crd: true,
color: knativeEventingColor.value,
};
export const EventingBrokerModel: K8sKind = {
apiGroup: KNATIVE_EVENTING_APIGROUP,
apiVersion,
kind: 'Broker',
label: 'Broker',
// t('knative-plugin~Broker')
labelKey: 'knative-plugin~Broker',
labelPlural: 'Brokers',
// t('knative-plugin~Brokers')
labelPluralKey: 'knative-plugin~Brokers',
plural: 'brokers',
id: 'broker',
abbr: 'B',
namespaced: true,
crd: true,
color: knativeEventingColor.value,
};
export const EventingTriggerModel: K8sKind = {
apiGroup: KNATIVE_EVENTING_APIGROUP,
apiVersion,
kind: 'Trigger',
label: 'Trigger',
// t('knative-plugin~Trigger')
labelKey: 'knative-plugin~Trigger',
labelPlural: 'Triggers',
// t('knative-plugin~Triggers')
labelPluralKey: 'knative-plugin~Triggers',
plural: 'triggers',
id: 'trigger',
abbr: 'T',
namespaced: true,
crd: true,
color: knativeEventingColor.value,
};
export const CamelIntegrationModel: K8sKind = {
apiGroup: CAMEL_APIGROUP,
apiVersion,
kind: 'Integration',
label: 'Integration',
// t('knative-plugin~Integration')
labelKey: 'knative-plugin~Integration',
labelPlural: 'Integrations',
// t('knative-plugin~Integration')
labelPluralKey: 'knative-plugin~Integrations',
plural: 'integrations',
id: 'integration',
abbr: 'I',
namespaced: true,
crd: true,
color: knativeEventingColor.value,
};
export const KafkaModel: K8sKind = {
apiGroup: STRIMZI_KAFKA_APIGROUP,
apiVersion: 'v1beta1',
kind: 'Kafka',
label: 'Kafka',
// t('knative-plugin~Kafka')
labelKey: 'knative-plugin~Kafka',
labelPlural: 'Kafkas',
// t('knative-plugin~Kafkas')
labelPluralKey: 'knative-plugin~Kafkas',
plural: 'kafkas',
id: 'kafka',
abbr: 'K',
namespaced: true,
crd: true,
color: knativeEventingColor.value,
};
export const KafkaTopicModel: K8sKind = {
apiGroup: STRIMZI_KAFKA_APIGROUP,
apiVersion: 'v1beta1',
kind: 'KafkaTopic',
label: 'KafkaTopic',
// t('knative-plugin~KafkaTopic')
labelKey: 'knative-plugin~KafkaTopic',
labelPlural: 'KafkaTopics',
// t('knative-plugin~KafkaTopics')
labelPluralKey: 'knative-plugin~KafkaTopics',
plural: 'kafkatopics',
id: 'kafkatopic',
abbr: 'KT',
namespaced: true,
crd: true,
color: knativeEventingColor.value,
};
export const CamelKameletBindingModel: K8sKind = {
apiGroup: CAMEL_APIGROUP,
apiVersion: 'v1alpha1',
kind: 'KameletBinding',
label: 'KameletBinding',
// t('knative-plugin~KameletBinding')
labelKey: 'knative-plugin~KameletBinding',
labelPlural: 'KameletBindings',
// t('knative-plugin~KameletBindings')
labelPluralKey: 'knative-plugin~KameletBindings',
plural: 'kameletbindings',
id: 'kameletbinding',
abbr: 'KB',
namespaced: true,
crd: true,
color: knativeEventingColor.value,
};
export const CamelKameletModel: K8sKind = {
apiGroup: CAMEL_APIGROUP,
apiVersion: 'v1alpha1',
kind: 'Kamelet',
label: 'Kamelet',
// t('knative-plugin~Kamelet')
labelKey: 'knative-plugin~Kamelet',
labelPlural: 'Kamelets',
// t('knative-plugin~Kamelets')
labelPluralKey: 'knative-plugin~Kamelets',
plural: 'kamelets',
id: 'kamelet',
abbr: 'K',
namespaced: true,
crd: true,
color: knativeEventingColor.value,
};
export const CamelIntegrationPlatformModel: K8sKind = {
apiGroup: CAMEL_APIGROUP,
apiVersion,
kind: 'IntegrationPlatform',
label: 'IntegrationPlatform',
// t('knative-plugin~IntegrationPlatform')
labelKey: 'knative-plugin~IntegrationPlatform',
labelPlural: 'IntegrationPlatforms',
// t('knative-plugin~IntegrationPlatforms')
labelPluralKey: 'knative-plugin~IntegrationPlatforms',
plural: 'integrationplatforms',
id: 'integrationplatform',
abbr: 'IP',
namespaced: true,
crd: true,
color: knativeEventingColor.value,
}; | the_stack |
import { browser, element, by } from 'protractor';
import SignInPage from '../../page-objects/signin-page';
import NavBarPage from '../../page-objects/navbar-page';
import RegisterPage from '../../page-objects/register-page';
import PasswordPage from '../../page-objects/password-page';
import SettingsPage from '../../page-objects/settings-page';
import {
getToastByInnerText,
getUserDeactivatedButtonByLogin,
getModifiedDateSortButton,
waitUntilDisplayed,
waitUntilClickable,
waitUntilHidden,
} from '../../util/utils';
const expect = chai.expect;
describe('Account', () => {
let navBarPage: NavBarPage;
let signInPage: SignInPage;
const username = process.env.E2E_USERNAME || 'admin';
const password = process.env.E2E_PASSWORD || 'admin';
let passwordPage: PasswordPage;
let settingsPage: SettingsPage;
let registerPage: RegisterPage;
const registerPageTitle = 'register-title';
const passwordPageTitle = 'password-title';
const settingsPageTitle = 'settings-title';
const loginPageTitle = 'login-title';
before(async () => {
await browser.get('/');
navBarPage = new NavBarPage();
signInPage = await navBarPage.getSignInPage();
await signInPage.waitUntilDisplayed();
});
it('should fail to login with bad password', async () => {
// Login page should appear
expect(await signInPage.getTitle()).to.eq(loginPageTitle);
await signInPage.username.sendKeys(username);
await signInPage.password.sendKeys('foo');
await signInPage.loginButton.click();
// Login page should stay open when login fails
expect(await signInPage.getTitle()).to.eq(loginPageTitle);
});
it('should login with admin account', async () => {
await browser.get('/');
await signInPage.get();
expect(await signInPage.getTitle()).to.eq(loginPageTitle);
await signInPage.username.sendKeys(username);
await signInPage.password.sendKeys(password);
await signInPage.loginButton.click();
await signInPage.waitUntilHidden();
// Login page should close when login success
expect(await signInPage.isHidden()()).to.be.true;
await navBarPage.autoSignOut();
});
it('should be able to sign up', async () => {
await waitUntilDisplayed(navBarPage.accountMenu);
registerPage = await navBarPage.getRegisterPage();
await registerPage.waitUntilDisplayed();
expect(await registerPage.getTitle()).to.eq(registerPageTitle);
await registerPage.autoSignUpUsing('user_test', 'admin@localhost.jh', 'user_test');
const toast = getToastByInnerText('Registration saved! Please check your email for confirmation.');
await waitUntilDisplayed(toast);
// Success toast should appear
expect(await toast.isPresent()).to.be.true;
});
it('should load user management', async () => {
await signInPage.get();
expect(await signInPage.getTitle()).to.eq(loginPageTitle);
await signInPage.username.sendKeys(username);
await signInPage.password.sendKeys(password);
await signInPage.loginButton.click();
await signInPage.waitUntilHidden();
const title = element(by.id('user-management-page-heading'));
await waitUntilDisplayed(navBarPage.adminMenu);
await navBarPage.clickOnAdminMenuItem('user-management');
await waitUntilDisplayed(title);
expect(await title.isPresent()).to.be.true;
});
it('should activate the new registered user', async () => {
expect(await element(by.id('user-management-page-heading')).isPresent()).to.be.true;
const modifiedDateSortButton = getModifiedDateSortButton();
await waitUntilClickable(modifiedDateSortButton);
await modifiedDateSortButton.click();
const deactivatedButton = getUserDeactivatedButtonByLogin('user_test');
await waitUntilClickable(deactivatedButton);
await deactivatedButton.click();
await waitUntilHidden(deactivatedButton);
// Deactivated button should disappear
expect(await deactivatedButton.isPresent()).to.be.false;
await navBarPage.autoSignOut();
});
it('should not be able to sign up if login already taken', async () => {
await registerPage.get();
expect(await registerPage.getTitle()).to.eq(registerPageTitle);
await registerPage.autoSignUpUsing('user_test', 'admin@localhost.jh', 'user_test');
const toast = getToastByInnerText('Login name already used!');
await waitUntilDisplayed(toast);
// Error toast should appear
expect(await toast.isPresent()).to.be.true;
});
it('should not be able to sign up if email already taken', async () => {
expect(await registerPage.getTitle()).to.eq(registerPageTitle);
await registerPage.username.sendKeys('_jhi');
await registerPage.saveButton.click();
const toast = getToastByInnerText('Email is already in use!');
await waitUntilDisplayed(toast);
// Error toast should appear
expect(await toast.isPresent()).to.be.true;
});
it('should be able to log in with new registered account', async () => {
await signInPage.get();
expect(await signInPage.getTitle()).to.eq(loginPageTitle);
await signInPage.username.sendKeys('user_test');
await signInPage.password.sendKeys('user_test');
await signInPage.loginButton.click();
await signInPage.waitUntilHidden();
// Login page should close when login success
expect(await signInPage.isHidden()()).to.be.true;
await navBarPage.autoSignOut();
});
it('should login with admin account', async () => {
await signInPage.get();
expect(await signInPage.getTitle()).to.eq(loginPageTitle);
await signInPage.username.sendKeys(username);
await signInPage.password.sendKeys(password);
await signInPage.loginButton.click();
await signInPage.waitUntilHidden();
expect(await signInPage.isHidden()()).to.be.true;
});
it('should fail to update password when using incorrect current password', async () => {
passwordPage = await navBarPage.getPasswordPage();
await passwordPage.waitUntilDisplayed();
expect(await passwordPage.getTitle()).to.eq(passwordPageTitle);
await passwordPage.autoChangePassword('bad_password', 'new_password', 'new_password');
const toast = getToastByInnerText('An error has occurred! The password could not be changed.');
await waitUntilDisplayed(toast);
// Error toast should appear
expect(await toast.isPresent()).to.be.true;
});
it('should be able to update password', async () => {
await browser.refresh();
await passwordPage.waitUntilDisplayed();
expect(await passwordPage.getTitle()).to.eq(passwordPageTitle);
await passwordPage.autoChangePassword(username, 'new_password', 'new_password');
const toast = getToastByInnerText('Password changed!');
await waitUntilDisplayed(toast);
// Success toast should appear
expect(await toast.isPresent()).to.be.true;
await navBarPage.autoSignOut();
});
it('should be able to log in with new password', async () => {
await signInPage.get();
expect(await signInPage.getTitle()).to.eq(loginPageTitle);
await signInPage.username.sendKeys(username);
await signInPage.password.sendKeys('new_password');
await signInPage.loginButton.click();
await signInPage.waitUntilHidden();
expect(await signInPage.isHidden()()).to.be.true;
// change back to default
await passwordPage.get();
expect(await passwordPage.getTitle()).to.eq(passwordPageTitle);
await passwordPage.autoChangePassword('new_password', password, password);
const toast = getToastByInnerText('Password changed!');
await waitUntilDisplayed(toast);
await navBarPage.autoSignOut();
});
it('should login with user_test account', async () => {
await signInPage.get();
expect(await signInPage.getTitle()).to.eq(loginPageTitle);
await signInPage.username.sendKeys('user_test');
await signInPage.password.sendKeys('user_test');
await signInPage.loginButton.click();
await signInPage.waitUntilHidden();
expect(await signInPage.isHidden()()).to.be.true;
});
it('should be able to change user_test settings', async () => {
await waitUntilDisplayed(navBarPage.accountMenu);
settingsPage = await navBarPage.getSettingsPage();
await waitUntilDisplayed(settingsPage.title);
expect(await settingsPage.getTitle()).to.eq(settingsPageTitle);
await settingsPage.firstName.sendKeys('jhipster');
await settingsPage.lastName.sendKeys('retspihj');
await settingsPage.saveButton.click();
const toast = getToastByInnerText('Settings saved!');
await waitUntilDisplayed(toast);
// Success toast should appear
expect(await toast.isPresent()).to.be.true;
await navBarPage.autoSignOut();
});
it('should login with admin account', async () => {
await signInPage.get();
expect(await signInPage.getTitle()).to.eq(loginPageTitle);
await signInPage.username.sendKeys(username);
await signInPage.password.sendKeys(password);
await signInPage.loginButton.click();
await signInPage.waitUntilHidden();
expect(await signInPage.isHidden()()).to.be.true;
});
it('should not be able to change admin settings if email already exists', async () => {
await settingsPage.get();
expect(await settingsPage.getTitle()).to.eq(settingsPageTitle);
await settingsPage.setEmail('.jh');
await settingsPage.save();
const toast = getToastByInnerText('Email is already in use!');
await waitUntilDisplayed(toast);
// Error toast should appear
expect(await toast.isPresent()).to.be.true;
});
it('should delete previously created fake user', async () => {
await browser.get('/admin/user-management/user_test/delete');
const deleteModal = element(by.className('modal'));
await waitUntilDisplayed(deleteModal);
await element(by.buttonText('Delete')).click();
await waitUntilHidden(deleteModal);
// Delete modal should disappear
expect(await deleteModal.isPresent()).to.be.false;
});
after(async () => {
await navBarPage.autoSignOut();
});
}); | the_stack |
import type { Vnode, VnodeDOM } from "mithril"
import m from "mithril"
import OptionsModal, { editorFontOption, editorFontSizeOption } from "_/Options"
import Workspace from "_/Workspace"
import AuthService from "_/AuthService"
import { AuthState } from "_/AuthService"
import DocumentBrowser from "_/DocumentBrowser"
import * as Icons from "_/Icons"
import CookiesModal from "_/CookiesModal"
import LoginFormModal from "_/LoginFormModal"
import FileBucketModal from "_/FileBucketModal"
import ColorPaletteModal from "_/ColorPaletteModal"
import { NavLink } from "_/NavLink"
import ResultPane from "_/ResultPane"
import * as Env from "_/Env"
import Toaster from "_/Toaster"
import ExternalLink from "_/ExternalLink"
import ModalManager from "_/ModalManager"
import Toolbar from "_/Toolbar"
import PageEnd from "_/PageEnd"
import { currentSheet, isManualSaveAvailable, SaveState } from "_/Persistence"
import Rollbar from "rollbar"
import * as pings from "_/pings"
const REPO_URL = "https://github.com/sharat87/prestige"
window.addEventListener("load", main)
function main() {
if (Env.rollbarToken != null) {
console.info("Enabling Rollbar with environment", Env.name)
Rollbar.init({
accessToken: Env.rollbarToken,
captureUncaught: true,
captureUnhandledRejections: true,
payload: {
environment: Env.name,
},
})
}
const root = document.createElement("main")
root.setAttribute("id", "app")
document.body.insertAdjacentElement("afterbegin", root)
document.getElementById("loadingBox")?.remove()
applyCookieStorageMigration()
m.route(root, "/doc/browser/master", {
"/doc/:path...": {
render: (vnode: Vnode) => m(Layout, m(WorkspaceView, vnode.attrs)),
},
// TODO: "/:404...": errorPageComponent,
})
AuthService.check()
interface GitHubApiResponse {
stargazers_count: number
}
m.request<GitHubApiResponse>(
`${Env.EXT_URL_PREFIX}https://api.github.com/repos/sharat87/prestige`,
).then((response) => {
RepoStats.stars = response.stargazers_count
})
pings.load()
}
const RepoStats = {
stars: 0,
}
const Layout: m.Component = {
view(vnode: m.VnodeDOM): m.Children {
return [
vnode.children,
ModalManager.render(),
Toaster.render(),
]
},
}
function WorkspaceView(): m.Component {
const workspace = new Workspace()
let redrawCount = 0
const enum VisiblePopup {
AboutPane,
ColorPalette,
Cookies,
FileBucketPopup,
LoginForm,
None,
Options,
}
let popup: VisiblePopup = VisiblePopup.None
return {
view,
oncreate,
onremove,
oninit: loadSheet,
onupdate: loadSheet,
}
function loadSheet(vnode: VnodeDOM<{ path: string }>) {
if (workspace.currentSheetQualifiedPath() !== vnode.attrs.path) {
workspace.currentSheetQualifiedPath(vnode.attrs.path)
popup = VisiblePopup.None
}
}
function oncreate() {
document.addEventListener("keydown", onKeyDown)
}
function onremove() {
document.removeEventListener("keydown", onKeyDown)
}
function onKeyDown(event: KeyboardEvent) {
if (event.key === "Escape") {
ModalManager.close()
if (popup !== VisiblePopup.None) {
popup = VisiblePopup.None
m.redraw()
}
workspace.codeMirror?.focus()
} else if ((event.ctrlKey || event.metaKey) && event.key === "s") {
event.preventDefault()
if (isManualSaveAvailable()) {
workspace.saveSheetManual()
} else {
workspace.saveSheetAuto()
}
m.redraw()
}
}
function view() {
const authState = AuthService.getAuthState()
return m("section.top-layout", [
m("header", [
m(".flex.items-end", [
m("h1.f3.mh2.mv0", "Prestige"),
m(".f6.i.ml3", [
"Just an HTTP client by ",
m("a", { href: "https://sharats.me", target: "_blank" }, "Shri"),
".",
]),
]),
m(".flex.items-stretch", [
RepoStats.stars > 0 && m(".pv1.ph2.db.flex.items-center.silver", [
m(
NavLink,
{ href: REPO_URL },
[m(Icons.github), "Star: ", RepoStats.stars, m(Icons.externalLink)],
),
]),
workspace.saveState === SaveState.unsaved
&& m(".i.pv1.ph2.db.flex.items-center.silver", "Unsaved"),
workspace.saveState === SaveState.saving
&& m(".i.pv1.ph2.db.flex.items-center.silver", m.trust("Saving…")),
Env.isDev() && m(
"code.flex.items-center.ph1",
{ style: { lineHeight: 1.15, color: "var(--red-3)", background: "var(--red-9)" } },
["R", ++redrawCount],
),
Env.isDev() && m(
NavLink,
{ onclick: onColorPaletteToggle, isActive: ModalManager.isShowing(VisiblePopup.ColorPalette) },
"Palette",
),
m(
NavLink,
{
class: "t-cookies-toggle-btn",
onclick: onCookiesToggle,
isActive: ModalManager.isShowing(VisiblePopup.Cookies),
},
[
m(Icons.cookie),
`Cookies (${ workspace.cookieJar?.size ?? 0 })`,
],
),
m(
NavLink,
{ onclick: onFileBucketToggle, isActive: ModalManager.isShowing(VisiblePopup.FileBucketPopup) },
[
m(Icons.folderClosed),
`FileBucket (${workspace.fileBucket.size})`,
],
),
m(
NavLink,
{ onclick: onOptionsToggle, isActive: ModalManager.isShowing(VisiblePopup.Options) },
[
m(Icons.wrench),
"Options",
],
),
[
authState === AuthState.PENDING
? m.trust("· · ·")
: m(
NavLink,
{
class: "t-login-signup-btn",
onclick: onLoginFormToggle,
isActive: ModalManager.isShowing(VisiblePopup.LoginForm),
},
[
m(Icons.user),
authState === AuthState.LOGGED_IN ? "Profile" : "LogIn/SignUp",
],
),
],
m(
NavLink,
{ onclick: onAboutPaneToggle, isActive: ModalManager.isShowing(VisiblePopup.AboutPane) },
[
m(Icons.info),
"About",
],
),
m(NavLink, { href: "/docs/" }, [m(Icons.question), "Docs", m(Icons.externalLink)]),
m(
NavLink,
{ href: REPO_URL + "/issues/new" },
["Report a problem", m(Icons.externalLink)],
),
]),
]),
m(Sidebar, { workspace }),
// The order of the below is a bit unintuitive, but is needed.
// Firstly, the parent element of these two, is a grid container. So layout can be different from order.
// Secondly, we need editor's layout to change, depending on result-pane's existence. So, we need these two
// ... to be next to each other in this order, so that a `+` selector works for layout change.
m(ResultPane, { workspace }),
m(EditorPane, { workspace }),
m("style", "body { --monospace-font: '" + editorFontOption() + "'; --monospace-font-size: " +
editorFontSizeOption() + "px; }"),
])
}
function onAboutPaneToggle() {
ModalManager.toggleDrawer(
() => m(ModalManager.DrawerLayout, { title: "About" }, m(AboutModal)),
VisiblePopup.AboutPane,
)
}
function onCookiesToggle() {
ModalManager.toggleDrawer(
() => m(CookiesModal, { cookieJar: workspace.cookieJar, workspace }),
VisiblePopup.Cookies,
)
}
function onFileBucketToggle() {
ModalManager.toggleDrawer(
() => m(FileBucketModal, { fileBucket: workspace.fileBucket }),
VisiblePopup.FileBucketPopup,
)
}
function onLoginFormToggle() {
ModalManager.toggleDrawer(() => m(LoginFormModal), VisiblePopup.LoginForm)
}
function onOptionsToggle() {
ModalManager.toggleDrawer(() => m(OptionsModal), VisiblePopup.Options)
}
function onColorPaletteToggle() {
ModalManager.toggleDrawer(() => m(ColorPaletteModal), VisiblePopup.ColorPalette)
}
}
class Sidebar implements m.ClassComponent {
isOpen: boolean
constructor() {
this.isOpen = false
}
view() {
return m("aside.sidebar.flex", [
m(".tab-bar", [
m(NavLink, { isActive: this.isOpen, onclick: this.toggleOpen.bind(this) }, m(Icons.files)),
]),
this.isOpen && m(".content", [
m(DocumentBrowser),
m(PageEnd),
]),
])
}
toggleOpen() {
this.isOpen = !this.isOpen
}
}
function EditorPane(): m.Component<{ class?: string, workspace: Workspace }> {
return { view, oncreate }
function oncreate(vnode: VnodeDOM<{ class?: string, workspace: Workspace }>): void {
if (!(vnode.dom.firstElementChild instanceof HTMLElement)) {
throw new Error(
"CodeMirror for Editor cannot be initialized unless `vnode.dom.firstElementChild` is an HTMLElement.",
)
}
const bodyEl = vnode.dom.querySelector(".body")
if (bodyEl != null) {
vnode.attrs.workspace.initCodeMirror(bodyEl as HTMLElement)
} else {
throw new Error("Unable to find body element in editor pane for initializing CodeMirror.")
}
}
function view(vnode: VnodeDOM<{ class?: string, workspace: Workspace }>): m.Vnode {
const { workspace } = vnode.attrs
workspace.doFlashes()
workspace.codeMirror?.refresh()
let saveButtonSpace: m.Children = null
if (!isManualSaveAvailable()) {
saveButtonSpace = m("em.pa1", "Autosaved")
} else {
saveButtonSpace = m(".stack-view", [
m(
NavLink,
{
onclick: () => {
workspace.saveSheetManual()
},
},
"๐พ Save document",
),
workspace.saveState === SaveState.unchanged && m("div", "No changes"),
workspace.saveState === SaveState.saving && m("div", m.trust("โ๏ธ Saving…")),
workspace.saveState === SaveState.saved && m("div", "โ Saved!"),
])
}
return m(".editor-pane", [
m(Toolbar, {
left: m(".flex", [
saveButtonSpace,
m("span.pa1", "๐ " + workspace.currentSheetQualifiedPath()),
]),
right: m(".flex", [
Env.isDev() && m(
NavLink,
{
onclick: () => {
alert("Work in progress")
},
},
"Create a Gist",
),
]),
}),
m(".body", {
onclick(event: Event) {
if ((event.target as HTMLElement).matches("span.cm-link")) {
window.open((event.target as HTMLElement).innerText, "_blank", "noopener")
}
},
}),
currentSheet() === "loading" && m(".mask.pa5", [
m(".loading", m.trust("Loading…")),
]),
])
}
}
const AboutModal: m.Component = {
view() {
return m(
"div.f3.ph4",
[
m("h3", "Hello there! ๐"),
m(
"p",
"My name is Shrikant. I built Prestige because I needed an app like this when working" +
" with APIs and playing with external APIs.",
),
m(
"p",
[
"Check out my blog at ",
m("a", { href: "https://sharats.me", target: "_blank" }, "sharats.me"),
". You can also find me on ",
m(ExternalLink, { href: "https://github.com/sharat87" }, "GitHub"),
" or ",
m(ExternalLink, { href: "https://twitter.com/sharat87" }, "Twitter"),
" or ",
m(ExternalLink, { href: "https://www.linkedin.com/in/sharat87" }, "LinkedIn"),
", althought I'm not quite active on those platforms.",
],
),
m(
"p",
[
"If you like Prestige, please consider ",
m(
ExternalLink,
{ href: "https://github.com/sharat87/prestige" },
"starring the project on GitHub",
),
". It'll help improve the project's visibility and works as indication that this " +
"project is indeed a useful tool. Thank you! ๐",
],
),
m(
"p",
[
"If you found a bug or have a feature request, please ",
m(
ExternalLink,
{ href: "https://github.com/sharat87/prestige/issues" },
"open an issue",
),
" on the GitHub project page.",
],
),
],
)
},
}
function applyCookieStorageMigration() {
for (const [key, value] of Object.entries(localStorage)) {
const match = key.match(/^instance:(.+?):cookieJar$/)
if (match != null) {
localStorage.setItem("cookies:browser/" + match[1], value)
localStorage.removeItem(key)
}
}
} | the_stack |
import {LuBuildCore} from './core'
import {Settings} from './settings'
import {MultiLanguageRecognizer} from './multi-language-recognizer'
import {Recognizer} from './recognizer'
import {CrossTrainedRecognizer} from './cross-trained-recognizer'
const path = require('path')
const fs = require('fs-extra')
const delay = require('delay')
const fileHelper = require('./../../utils/filehelper')
const fileExtEnum = require('./../utils/helpers').FileExtTypeEnum
const retCode = require('./../utils/enums/CLI-errors')
const exception = require('./../utils/exception')
const LuisBuilderVerbose = require('./../luis/luisCollate')
const LuisBuilder = require('./../luis/luisBuilder')
const Luis = require('./../luis/luis')
const LUOptions = require('./../lu/luOptions')
const Content = require('./../lu/lu')
const recognizerType = require('./../utils/enums/recognizertypes')
export class Builder {
private readonly handler: (input: string) => any
constructor(handler: any) {
this.handler = handler
}
async loadContents(
files: string[],
culture: string,
suffix: string,
region: string,
schema?: string,
importResolver?: object) {
let multiRecognizers = new Map<string, MultiLanguageRecognizer>()
let settings: any
let recognizers = new Map<string, Recognizer>()
let luContents: Array<any> = []
let crosstrainedRecognizers = new Map<string, CrossTrainedRecognizer>()
for (const file of files) {
let fileCulture: string
let fileName: string
let cultureFromPath = fileHelper.getCultureFromPath(file)
if (cultureFromPath) {
fileCulture = cultureFromPath
let fileNameWithCulture = path.basename(file, path.extname(file))
fileName = fileNameWithCulture.substring(0, fileNameWithCulture.length - fileCulture.length - 1)
} else {
fileCulture = culture
fileName = path.basename(file, path.extname(file))
}
const fileFolder = path.dirname(file)
const crossTrainedFileName = fileName + '.lu.qna.dialog'
const crossTrainedRecognizerPath = path.join(fileFolder, crossTrainedFileName)
if (!crosstrainedRecognizers.has(fileName)) {
let crosstrainedRecognizerContent = []
let crosstrainedRecognizerSchema = schema
if (fs.existsSync(crossTrainedRecognizerPath)) {
let crosstrainedRecognizerObject = JSON.parse(await fileHelper.getContentFromFile(crossTrainedRecognizerPath))
crosstrainedRecognizerContent = crosstrainedRecognizerObject.recognizers
crosstrainedRecognizerSchema = crosstrainedRecognizerSchema || crosstrainedRecognizerObject.$schema
this.handler(`${crossTrainedRecognizerPath} loaded\n`)
}
crosstrainedRecognizers.set(fileName, new CrossTrainedRecognizer(crossTrainedRecognizerPath, crosstrainedRecognizerContent, crosstrainedRecognizerSchema as string))
}
let fileContent = ''
let result
let luisObj
let luFiles = await fileHelper.getLuObjects(undefined, file, true, fileExtEnum.LUFile)
this.handler(`${file} loaded\n`)
// filter empty lu files
luFiles = luFiles.filter((file: any) => file.content !== '')
if (luFiles.length <= 0) continue
try {
result = await LuisBuilderVerbose.build(luFiles, true, fileCulture, importResolver)
luisObj = new Luis(result)
fileContent = luisObj.parseToLuContent()
} catch (err) {
if (err.source) {
err.text = `Invalid LU file ${err.source}: ${err.text}`
} else {
err.text = `Invalid LU file ${file}: ${err.text}`
}
throw (new exception(retCode.errorCode.INVALID_INPUT_FILE, err.text))
}
const multiRecognizerPath = path.join(fileFolder, `${fileName}.lu.dialog`)
if (!multiRecognizers.has(fileName)) {
let multiRecognizerContent = {}
let multiRecognizerSchema = schema
if (fs.existsSync(multiRecognizerPath)) {
let multiRecognizerObject = JSON.parse(await fileHelper.getContentFromFile(multiRecognizerPath))
multiRecognizerContent = multiRecognizerObject.recognizers
multiRecognizerSchema = multiRecognizerSchema || multiRecognizerObject.$schema
this.handler(`${multiRecognizerPath} loaded\n`)
}
multiRecognizers.set(fileName, new MultiLanguageRecognizer(multiRecognizerPath, multiRecognizerContent, multiRecognizerSchema as string))
}
if (settings === undefined) {
const settingsPath = path.join(fileFolder, `luis.settings.${suffix}.${region}.json`)
let settingsContent = {}
if (fs.existsSync(settingsPath)) {
settingsContent = JSON.parse(await fileHelper.getContentFromFile(settingsPath)).luis
this.handler(`${settingsPath} loaded\n`)
}
settings = new Settings(settingsPath, settingsContent)
}
const content = new Content(fileContent, new LUOptions(fileName, true, fileCulture, file))
luContents.push(content)
const dialogFile = path.join(fileFolder, `${content.name}.dialog`)
let existingDialogObj: any
if (fs.existsSync(dialogFile)) {
existingDialogObj = JSON.parse(await fileHelper.getContentFromFile(dialogFile))
this.handler(`${dialogFile} loaded\n`)
}
if (existingDialogObj && schema) {
existingDialogObj.$schema = schema
}
let recognizer = Recognizer.load(content.path, content.name, dialogFile, settings, existingDialogObj, schema)
recognizers.set(content.name, recognizer)
}
// validate if there are duplicated files with same name and locale
let setOfContents = new Set()
const hasDuplicates = luContents.some(function (currentObj) {
return setOfContents.size === setOfContents.add(currentObj.name).size
})
if (hasDuplicates) {
throw(new exception(retCode.errorCode.INVALID_INPUT_FILE, 'Files with same name and locale are found.'))
}
return {luContents, recognizers, multiRecognizers, settings, crosstrainedRecognizers}
}
async build(
luContents: any[],
recognizers: Map<string, Recognizer>,
authoringKey: string,
endpoint: string,
botName: string,
suffix: string,
fallbackLocale: string,
deleteOldVersion: boolean,
isStaging: boolean,
multiRecognizers?: Map<string, MultiLanguageRecognizer>,
settings?: Settings,
crosstrainedRecognizers?: Map<string, CrossTrainedRecognizer>,
dialogType?: string,
luisAPITPS?: number,
timeBucketOfRequests?: number,
retryCount?: number,
retryDuration?: number) {
// luis api TPS which means 5 concurrent transactions to luis api in 1 second
// can set to other value if switched to a higher TPS(transaction per second) key
let luisApiTps = luisAPITPS || 5
// set luis call delay duration to 1100 millisecond because 1000 can hit corner case of rate limit
let timeBucket = timeBucketOfRequests || 1100
// set retry count for rate limit luis API failure
let countForRetry = retryCount || 1
// set retry duration for rate limit luis API failure
let durationForRetry = retryDuration || 1000
//default returned recognizer values
let recognizerValues: Recognizer[] = []
let multiRecognizerValues: MultiLanguageRecognizer[] = []
let settingsValue: any
let crosstrainedRecognizerValues: CrossTrainedRecognizer[] = []
// filter if all lu contents are emtty
let isAllLuEmpty = fileHelper.isAllFilesSectionEmpty(luContents)
if (!isAllLuEmpty) {
const luBuildCore = new LuBuildCore(authoringKey, endpoint, countForRetry, durationForRetry)
const apps = await luBuildCore.getApplicationList()
// here we do a while loop to make full use of luis tps capacity
while (luContents.length > 0) {
// get a number(set by luisApiTps) of contents for each loop
const subLuContents = luContents.splice(0, luisApiTps)
// concurrently handle applications
await Promise.all(subLuContents.map(async content => {
// init current application object from lu content
let currentApp = await this.initApplicationFromLuContent(content, botName, suffix)
// get recognizer
let recognizer = recognizers.get(content.name) as Recognizer
// find if there is a matched name with current app under current authoring key
if (!recognizer.getAppId()) {
for (let app of apps) {
if (app.name === currentApp.name) {
recognizer.setAppId(app.id)
break
}
}
}
let needTrainAndPublish = false
// compare models to update the model if a match found
// otherwise create a new application
if (recognizer.getAppId() && recognizer.getAppId() !== '') {
// To see if need update the model
needTrainAndPublish = await this.updateApplication(currentApp, luBuildCore, recognizer, timeBucket, deleteOldVersion)
} else {
// create a new application
needTrainAndPublish = await this.createApplication(currentApp, luBuildCore, recognizer, timeBucket)
}
if (needTrainAndPublish) {
// train and publish application
await this.trainAndPublishApplication(luBuildCore, recognizer, timeBucket, isStaging)
}
// update multiLanguageRecognizer asset
if (multiRecognizers && multiRecognizers.has(content.id)) {
let multiRecognizer = multiRecognizers.get(content.id) as MultiLanguageRecognizer
multiRecognizer.recognizers[currentApp.culture] = path.basename(recognizer.getDialogPath(), '.dialog')
if (currentApp.culture.toLowerCase() === fallbackLocale.toLowerCase()) {
multiRecognizer.recognizers[''] = path.basename(recognizer.getDialogPath(), '.dialog')
}
}
if (crosstrainedRecognizers && crosstrainedRecognizers.has(content.id)) {
let crosstrainedRecognizer = crosstrainedRecognizers.get(content.id) as CrossTrainedRecognizer
if (!crosstrainedRecognizer.recognizers.includes(content.id + '.lu')) {
crosstrainedRecognizer.recognizers.push(content.id + '.lu')
}
}
// update settings asset
if (settings) {
settings.luis[content.name.split('.').join('_').replace(/-/g, '_')] = recognizer.getAppId()
}
}))
}
// write dialog assets
if (recognizers) {
recognizerValues = Array.from(recognizers.values())
}
if (multiRecognizers) {
multiRecognizerValues = Array.from(multiRecognizers.values())
}
if (settings) {
settingsValue = settings as Settings
}
}
if (dialogType === recognizerType.CROSSTRAINED && crosstrainedRecognizers) {
crosstrainedRecognizerValues = Array.from(crosstrainedRecognizers.values())
}
const dialogContents = this.generateDeclarativeAssets(recognizerValues, multiRecognizerValues, settingsValue, crosstrainedRecognizerValues)
return dialogContents
}
async writeDialogAssets(contents: any[], force: boolean, out: string, luconfig: string) {
let writeDone = false
let writeContents = contents.filter(c => c.id.endsWith('.dialog'))
let settingsContents = contents.filter(c => c.id.endsWith('.json'))
if (settingsContents && settingsContents.length > 0) {
let outPath
if (luconfig) {
outPath = path.join(path.resolve(path.dirname(luconfig)), settingsContents[0].id)
} else if (out) {
outPath = path.join(path.resolve(out), settingsContents[0].id)
} else {
outPath = path.resolve(settingsContents[0].id)
}
writeContents.push(this.mergeSettingsContent(outPath, settingsContents))
}
for (const content of writeContents) {
let outFilePath
if (out) {
outFilePath = path.join(path.resolve(out), path.basename(content.path))
} else {
outFilePath = content.path
}
let fileExists = fs.existsSync(outFilePath)
if (fileExists && outFilePath.endsWith('.lu.qna.dialog')) {
let existingCTRecognizerObject = JSON.parse(await fileHelper.getContentFromFile(outFilePath))
let currentCTRecognizerObject = JSON.parse(content.content)
let ctRecognizerToBeMerged = currentCTRecognizerObject.recognizers.filter((r: string) => !existingCTRecognizerObject.recognizers.includes(r))
existingCTRecognizerObject.recognizers = existingCTRecognizerObject.recognizers.concat(ctRecognizerToBeMerged)
content.content = JSON.stringify(existingCTRecognizerObject, null, 4)
}
if (force || !fs.existsSync(outFilePath)) {
if (!fs.existsSync(path.dirname(outFilePath))) {
fs.mkdirSync(path.dirname(outFilePath))
}
this.handler(`Writing to ${outFilePath}\n`)
await fs.writeFile(outFilePath, content.content, 'utf-8')
writeDone = true
}
}
return writeDone
}
async getActiveVersionIds(appNames: string[], authoringKey: string, region: string, retryCount?: number, retryDuration?: number) {
const luBuildCore = new LuBuildCore(authoringKey, `https://${region}.api.cognitive.microsoft.com`, retryCount || 1, retryDuration || 1000)
const apps = await luBuildCore.getApplicationList()
let appNameVersionMap = new Map<string, string>()
for (const appName of appNames) {
// find if there is a matched name with current app under current authoring key
appNameVersionMap.set(appName, '')
for (let app of apps) {
if (app.name === appName) {
const appInfo = await luBuildCore.getApplicationInfo(app.id)
appNameVersionMap.set(appName, appInfo.activeVersion)
break
}
}
}
return appNameVersionMap
}
async initApplicationFromLuContent(content: any, botName: string, suffix: string) {
let currentApp = await LuisBuilder.fromLUAsync([content]) // content.parseToLuis(true, content.language)
currentApp.culture = currentApp.culture && currentApp.culture !== '' && currentApp.culture !== 'en-us' ? currentApp.culture : content.language as string
currentApp.desc = currentApp.desc && currentApp.desc !== '' ? currentApp.desc : `Model for ${botName} app, targetting ${suffix}`
if (currentApp.name === undefined || currentApp.name === '') {
currentApp.name = `${botName}(${suffix})-${content.name}`
}
// remove empty intents from current app to avoid fewLabels error when training
this.filterEmptyIntents(currentApp)
return currentApp
}
async updateApplication(currentApp: any, luBuildCore: LuBuildCore, recognizer: Recognizer, timeBucket: number, deleteOldVersion: boolean) {
await delay(timeBucket)
const appInfo = await luBuildCore.getApplicationInfo(recognizer.getAppId())
recognizer.versionId = appInfo.activeVersion || appInfo.endpoints.PRODUCTION.versionId
await delay(timeBucket)
const existingApp = await luBuildCore.exportApplication(recognizer.getAppId(), recognizer.versionId)
// compare models
const needUpdate = luBuildCore.compareApplications(currentApp, existingApp)
if (needUpdate) {
const newVersionId = luBuildCore.updateVersion(currentApp, existingApp)
recognizer.versionId = newVersionId
const options: any = {
versionId: newVersionId
}
this.handler(`${recognizer.getLuPath()} creating version=${newVersionId}\n`)
await delay(timeBucket)
await luBuildCore.importNewVersion(recognizer.getAppId(), currentApp, options)
if (deleteOldVersion) {
await delay(timeBucket)
const versionObjs = await luBuildCore.listApplicationVersions(recognizer.getAppId())
for (const versionObj of versionObjs) {
if (versionObj.version !== newVersionId) {
this.handler(`${recognizer.getLuPath()} deleting old version=${versionObj.version}`)
await delay(timeBucket)
await luBuildCore.deleteVersion(recognizer.getAppId(), versionObj.version)
}
}
}
return true
} else {
this.handler(`${recognizer.getLuPath()} no changes\n`)
return false
}
}
async createApplication(currentApp: any, luBuildCore: LuBuildCore, recognizer: Recognizer, timeBucket: number) {
currentApp.versionId = currentApp.versionId && currentApp.versionId !== '' ? currentApp.versionId : '0.1'
recognizer.versionId = currentApp.versionId
this.handler(`Creating LUIS.ai application: ${currentApp.name} version:${currentApp.versionId}\n`)
await delay(timeBucket)
const response = await luBuildCore.importApplication(currentApp)
recognizer.setAppId(typeof response === 'string' ? response : response[Object.keys(response)[0]])
return true
}
async trainAndPublishApplication(luBuildCore: LuBuildCore, recognizer: Recognizer, timeBucket: number, isStaging: boolean) {
// send train application request
this.handler(`${recognizer.getLuPath()} training version=${recognizer.versionId}\n`)
await delay(timeBucket)
await luBuildCore.trainApplication(recognizer.getAppId(), recognizer.versionId)
this.handler(`${recognizer.getLuPath()} waiting for training for version=${recognizer.versionId}...\n`)
let done = true
do {
await delay(timeBucket)
// get training status to see if training completed
let trainingStatus = await luBuildCore.getTrainingStatus(recognizer.getAppId(), recognizer.versionId)
done = true
for (let status of trainingStatus) {
if (status.details) {
if (status.details.status === 'InProgress' || status.details.status === 'Queued') {
done = false
break
}
}
}
} while (!done)
this.handler('done\n')
// publish applications
this.handler(`${recognizer.getLuPath()} publishing version=${recognizer.versionId}\n`)
await delay(timeBucket)
await luBuildCore.publishApplication(recognizer.getAppId(), recognizer.versionId, isStaging)
this.handler(`${recognizer.getLuPath()} publishing finished for ${isStaging ? 'Staging' : 'Production'} slot\n`)
}
generateDeclarativeAssets(recognizers: Array<Recognizer>, multiRecognizers: Array<MultiLanguageRecognizer>, settings: Settings, crosstrainedRecognizers: Array<CrossTrainedRecognizer>)
: Array<any> {
let contents = new Array<any>()
for (const recognizer of recognizers) {
let content = new Content(recognizer.save(), new LUOptions(path.basename(recognizer.getDialogPath()), true, '', recognizer.getDialogPath()))
contents.push(content)
}
for (const multiRecognizer of multiRecognizers) {
const multiLangContent = new Content(multiRecognizer.save(), new LUOptions(path.basename(multiRecognizer.getDialogPath()), true, '', multiRecognizer.getDialogPath()))
contents.push(multiLangContent)
}
if (settings) {
const settingsContent = new Content(settings.save(), new LUOptions(path.basename(settings.getSettingsPath()), true, '', settings.getSettingsPath()))
contents.push(settingsContent)
}
for (const crosstrainedRecognizer of crosstrainedRecognizers) {
const crosstrainedContent = new Content(crosstrainedRecognizer.save(), new LUOptions(path.basename(crosstrainedRecognizer.getDialogPath()), true, '', crosstrainedRecognizer.getDialogPath()))
contents.push(crosstrainedContent)
}
return contents
}
mergeSettingsContent(settingsPath: string, contents: any[]) {
let settings = new Settings(settingsPath, {})
for (const content of contents) {
const luisAppsMap = JSON.parse(content.content).luis
for (const appName of Object.keys(luisAppsMap)) {
settings.luis[appName] = luisAppsMap[appName]
}
}
return new Content(settings.save(), new LUOptions(path.basename(settings.getSettingsPath()), true, '', settings.getSettingsPath()))
}
filterEmptyIntents(app: any) {
const intents = app.intents
const utterances = app.utterances
const patterns = app.patterns
const emptyIntents = intents.filter((intent: any) => !utterances.some((utterance: any) => utterance.intent === intent.name)
&& !patterns.some((pattern: any) => pattern.intent === intent.name))
if (emptyIntents && emptyIntents.length > 0) {
const filteredIntents = intents.filter((intent: any) => !emptyIntents.some((emptyIntent: any) => emptyIntent.name === intent.name))
this.handler(`[WARN]: empty intent(s) ${emptyIntents.map((intent: any) => '# ' + intent.name).join(', ')} are filtered when handling luis application`)
app.intents = filteredIntents
}
}
} | the_stack |
import {
HttpClientModule,
HTTP_INTERCEPTORS,
} from '@angular/common/http';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { InjectionToken, NgModule } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import {
NG_MOCKS_GUARDS,
NG_MOCKS_INTERCEPTORS,
} from '../common/core.tokens';
import ngMocksUniverse from '../common/ng-mocks-universe';
import { MockBuilder } from '../mock-builder/mock-builder';
import { ngMocks } from '../mock-helper/mock-helper';
import helperMockService from './helper.mock-service';
import { MockService } from './mock-service';
class DeepParentClass {
public deepParentMethodName = 'deepParentMethod';
public deepParentMethod() {
return this.deepParentMethodName;
}
}
class ParentClass extends DeepParentClass {
public overrideMeName = 'overrideMe';
public parentMethodName = 'parentMethod';
public overrideMe() {
return this.overrideMeName;
}
public parentMethod() {
return this.parentMethodName;
}
}
class ChildClass extends ParentClass {
public childMethodName = 'childMethod';
public overrideMeName = 'childOverrideMe';
public childMethod() {
return this.childMethodName;
}
public overrideMe() {
return this.overrideMeName;
}
}
class GetterSetterMethodHuetod {
public nameValue = 'nameValue';
public get name(): string {
return `${this.nameValue}${this.nameValue}`;
}
public set name(value: string) {
this.nameValue = value;
}
public nameMethod(value?: string): string {
if (value) {
this.name = value;
}
return this.name;
}
}
describe('MockService', () => {
it('should convert boolean, number, string, null and undefined to undefined', () => {
expect(MockService(true)).toBeUndefined();
expect(MockService(false)).toBeUndefined();
expect(MockService(0)).toBeUndefined();
expect(MockService(1)).toBeUndefined();
expect(MockService(-1)).toBeUndefined();
expect(MockService(NaN)).toBeUndefined();
expect(MockService('')).toBeUndefined();
expect(MockService(null)).toBeUndefined();
expect(MockService(undefined)).toBeUndefined();
});
it('should convert an array of anything to an empty array', () => {
expect(MockService([1, 0, 1])).toEqual([]);
expect(MockService([new DeepParentClass()])).toEqual([]);
});
it('should convert arrow functions to () => undefined', () => {
const mockService = MockService(() => 0);
expect(mockService).toEqual(jasmine.any(Function));
expect(mockService()).toBeUndefined();
expect(mockService.and.identity).toBe('func:arrow-function');
});
it('should convert normal functions to () => undefined', () => {
// tslint:disable-next-line:no-function-expression
const mockService = MockService(function test() {
return 0;
});
expect(mockService).toEqual(jasmine.any(Function));
expect(mockService()).toBeUndefined();
expect(mockService.and.identity).toBe('func:test');
});
it('should convert normal class to an empty object', () => {
const mockService = MockService(
class Test {
public constructor(public readonly name: string) {}
},
);
expect(mockService).toEqual(jasmine.any(Object));
});
it('should mock own methods of a class without a parent', () => {
const mockService = MockService(DeepParentClass);
expect(mockService).toEqual(jasmine.any(Object));
// all properties should be undefined, maybe defined as getters and setters.
expect(mockService.deepParentMethodName).toBeUndefined();
// all methods should be defined as functions which return undefined.
expect(mockService.deepParentMethod).toEqual(
jasmine.any(Function),
);
expect(mockService.deepParentMethod()).toBeUndefined();
expect(
ngMocks.stub<any>(mockService, 'deepParentMethod').and.identity,
).toBe('DeepParentClass.deepParentMethod');
});
it('should mock own and parent methods of a class', () => {
const mockService = MockService(ChildClass);
expect(mockService).toEqual(jasmine.any(ChildClass));
// all properties should be undefined, maybe defined as getters and setters.
expect(mockService.deepParentMethodName).toBeUndefined();
expect(mockService.parentMethodName).toBeUndefined();
expect(mockService.overrideMeName).toBeUndefined();
expect(mockService.childMethodName).toBeUndefined();
// all methods should be defined as functions which return undefined.
expect(mockService.deepParentMethod).toEqual(
jasmine.any(Function),
);
expect(mockService.deepParentMethod()).toBeUndefined();
expect(
ngMocks.stub<any>(mockService, 'deepParentMethod').and.identity,
).toBe('ChildClass.deepParentMethod');
expect(mockService.parentMethod).toEqual(jasmine.any(Function));
expect(mockService.parentMethod()).toBeUndefined();
expect(
ngMocks.stub<any>(mockService, 'parentMethod').and.identity,
).toBe('ChildClass.parentMethod');
expect(mockService.overrideMe).toEqual(jasmine.any(Function));
expect(mockService.overrideMe()).toBeUndefined();
expect(
ngMocks.stub<any>(mockService, 'overrideMe').and.identity,
).toBe('ChildClass.overrideMe');
expect(mockService.childMethod).toEqual(jasmine.any(Function));
expect(mockService.childMethod()).toBeUndefined();
expect(
ngMocks.stub<any>(mockService, 'childMethod').and.identity,
).toBe('ChildClass.childMethod');
});
it('should mock an instance of a class as an object', () => {
const mockService = MockService(new ChildClass());
expect(mockService).toEqual(jasmine.any(ChildClass));
// all properties should be undefined, maybe defined as getters and setters.
expect(mockService.deepParentMethodName).toBeUndefined();
expect(mockService.parentMethodName).toBeUndefined();
expect(mockService.overrideMeName).toBeUndefined();
expect(mockService.childMethodName).toBeUndefined();
// all methods should be defined as functions which return undefined.
expect(mockService.deepParentMethod).toEqual(
jasmine.any(Function),
);
expect(mockService.deepParentMethod()).toBeUndefined();
expect(mockService.deepParentMethod.and.identity).toBe(
'ChildClass.deepParentMethod',
);
expect(mockService.parentMethod).toEqual(jasmine.any(Function));
expect(mockService.parentMethod()).toBeUndefined();
expect(mockService.parentMethod.and.identity).toBe(
'ChildClass.parentMethod',
);
expect(mockService.overrideMe).toEqual(jasmine.any(Function));
expect(mockService.overrideMe()).toBeUndefined();
expect(mockService.overrideMe.and.identity).toBe(
'ChildClass.overrideMe',
);
expect(mockService.childMethod).toEqual(jasmine.any(Function));
expect(mockService.childMethod()).toBeUndefined();
expect(mockService.childMethod.and.identity).toBe(
'ChildClass.childMethod',
);
});
it('should mock own and nested properties of an object', () => {
const mockService = MockService({
booleanFalse: false,
booleanTrue: true,
child1: {
child11: {
func1: () => 0,
nullValue: null,
undefinedValue: undefined,
},
number0: 0,
number1: 1,
},
child2: {
stringEmpty: '',
},
func2: () => 1,
func3: () => false,
});
expect(mockService).toEqual({
child1: {
child11: {
func1: jasmine.any(Function),
},
},
child2: {},
func2: jasmine.any(Function),
func3: jasmine.any(Function),
});
expect(mockService.child1.child11.func1()).toBeUndefined();
expect(mockService.child1.child11.func1.and.identity).toBe(
'func:instance.child1.child11.func1',
);
expect(mockService.func2()).toBeUndefined();
expect(mockService.func2.and.identity).toBe(
'func:instance.func2',
);
expect(mockService.func3()).toBeUndefined();
expect(mockService.func3.and.identity).toBe(
'func:instance.func3',
);
});
it('mocks getters, setters and methods in a way that jasmine can mock them w/o an issue', () => {
const mock: GetterSetterMethodHuetod = MockService(
GetterSetterMethodHuetod,
);
expect(mock).toBeDefined();
// Creating a mock on the getter.
spyOnProperty(mock, 'name', 'get').and.returnValue('mock');
// for jest
// spyOnProperty(mock, 'name', 'get').mockReturnValue('mock');
expect(mock.name).toEqual('mock');
// Creating a mock on the setter.
spyOnProperty(mock, 'name', 'set');
mock.name = 'mock';
expect(ngMocks.stub(mock, 'name', 'set')).toHaveBeenCalledWith(
'mock',
);
// Creating a mock on the method.
spyOn(mock, 'nameMethod').and.returnValue('mock');
// for jest
// spyOn(mock, 'nameMethod').mockReturnValue('mock');
expect(mock.nameMethod('mock')).toEqual('mock');
expect(ngMocks.stub(mock, 'nameMethod')).toHaveBeenCalledWith(
'mock',
);
});
it('mocks injection tokens as undefined', () => {
const token1 = MockService(new InjectionToken('hello'));
expect(token1).toBeUndefined();
});
it('mocks a class to an instance with proper types', () => {
class Test {
public readonly nameRead = 'read';
private name = 'test';
public get nameGet(): string {
return this.name;
}
public set nameSet(name: string) {
this.name = name;
}
public echo(): string {
return this.name;
}
}
const test = ngMocks.stub(MockService(Test), {
echo: jasmine.createSpy().and.returnValue('fake1'),
nameGet: 'fake3',
nameSet: 'fake5',
});
ngMocks.stub(test, 'nameRead', 'get');
spyOnProperty(test, 'nameRead', 'get').and.returnValue('fake4');
expect(test).toEqual(jasmine.any(Test));
expect(test.echo()).toBe('fake1');
expect(test.nameGet).toBe('fake3');
expect(test.nameRead).toBe('fake4');
expect(test.nameSet).toBe('fake5');
});
it('respects original class in replaceWithMocks', () => {
class A {}
class B {}
class Test {
private readonly member = A;
public getMember() {
return this.member;
}
}
ngMocksUniverse.cacheDeclarations.set(A, B);
const instance = new Test();
const updated = helperMockService.replaceWithMocks(instance);
expect(updated).toEqual(jasmine.any(Test));
expect(updated.getMember()).toBe(B);
});
it('keeps setter when we add getter', () => {
const value = {};
helperMockService.mock(value, 'prop', 'set');
helperMockService.mock(value, 'prop', 'get');
const def = Object.getOwnPropertyDescriptor(value, 'prop') || {};
expect(def.get).toBeDefined();
expect(def.set).toBeDefined();
});
it('returns undefined on undefined in replaceWithMocks', () => {
expect(helperMockService.replaceWithMocks(null)).toEqual(null);
});
});
describe('replaceWithMocks', () => {
it('removes excluded things from an array', async () => {
@NgModule({
providers: [
{
provide: 'test',
useValue: [
DeepParentClass,
ParentClass,
GetterSetterMethodHuetod,
],
},
],
})
class TargetModule {}
await MockBuilder()
.mock(TargetModule)
.keep('test')
.exclude(ParentClass);
const actual = TestBed.get('test');
expect(actual).toEqual([
DeepParentClass,
GetterSetterMethodHuetod,
]);
});
it('removes excluded things from an object', async () => {
@NgModule({
providers: [
{
provide: 'test',
useValue: {
DeepParentClass,
GetterSetterMethodHuetod,
ParentClass,
},
},
],
})
class TargetModule {}
await MockBuilder()
.mock(TargetModule)
.keep('test')
.exclude(ParentClass);
const actual = TestBed.get('test');
expect(actual).toEqual({
DeepParentClass,
GetterSetterMethodHuetod,
});
});
it('keeps all guards without excluding NG_MOCKS_GUARDS', async () => {
@NgModule({
providers: [
{
provide: 'test',
useValue: {
canActivate: [
DeepParentClass,
GetterSetterMethodHuetod,
ParentClass,
],
},
},
],
})
class TargetModule {}
await MockBuilder().mock(TargetModule).keep('test');
const actual = TestBed.get('test');
expect(actual).toEqual({
canActivate: [
DeepParentClass,
GetterSetterMethodHuetod,
ParentClass,
],
});
});
it('ignores all guards with excluded NG_MOCKS_GUARDS', async () => {
@NgModule({
providers: [
{
provide: 'test',
useValue: {
canActivate: [
DeepParentClass,
GetterSetterMethodHuetod,
ParentClass,
],
},
},
],
})
class TargetModule {}
await MockBuilder()
.mock(TargetModule)
.keep('test')
.exclude(NG_MOCKS_GUARDS);
const actual = TestBed.get('test');
expect(actual).toEqual({
canActivate: [],
});
});
});
describe('resolveProvider', () => {
it('ignores helperUseFactory and useValue interceptors with excluded NG_MOCKS_INTERCEPTORS', async () => {
@NgModule({
imports: [HttpClientModule],
providers: [
{
multi: true,
provide: HTTP_INTERCEPTORS,
useValue: false,
},
{
multi: true,
provide: HTTP_INTERCEPTORS,
useFactory: () => true,
},
],
})
class TargetModule {}
await MockBuilder()
.mock(TargetModule)
.replace(HttpClientModule, HttpClientTestingModule)
.keep(HTTP_INTERCEPTORS)
.exclude(NG_MOCKS_INTERCEPTORS);
const actual = TestBed.get(HTTP_INTERCEPTORS);
expect(actual).not.toEqual(
jasmine.arrayContaining([false, true]),
);
});
}); | the_stack |
import {
DecryptionMaterial,
EncryptedDataKey,
EncryptionMaterial,
immutableClass,
Keyring,
KeyringTrace,
KeyringTraceFlag,
needs,
readOnlyProperty,
SupportedAlgorithmSuites,
Newable,
Catchable,
} from '@aws-crypto/material-management'
import {
constructArnInOtherRegion,
isMultiRegionAwsKmsArn,
parseAwsKmsKeyArn,
} from './arn_parsing'
import { decrypt, KMS_PROVIDER_ID } from './helpers'
import { AwsEsdkKMSInterface, RequiredDecryptResponse } from './kms_types'
export interface AwsKmsMrkAwareSymmetricDiscoveryKeyringInput<
Client extends AwsEsdkKMSInterface
> {
client: Client
discoveryFilter?: Readonly<{
accountIDs: readonly string[]
partition: string
}>
grantTokens?: string[]
}
export interface IAwsKmsMrkAwareSymmetricDiscoveryKeyring<
S extends SupportedAlgorithmSuites,
Client extends AwsEsdkKMSInterface
> extends Keyring<S> {
client: Client
clientRegion: string
discoveryFilter?: Readonly<{
accountIDs: readonly string[]
partition: string
}>
grantTokens?: string[]
_onEncrypt(material: EncryptionMaterial<S>): Promise<EncryptionMaterial<S>>
_onDecrypt(
material: DecryptionMaterial<S>,
encryptedDataKeys: EncryptedDataKey[]
): Promise<DecryptionMaterial<S>>
}
export interface AwsKmsMrkAwareSymmetricDiscoveryKeyringConstructible<
S extends SupportedAlgorithmSuites,
Client extends AwsEsdkKMSInterface
> {
new (
input: AwsKmsMrkAwareSymmetricDiscoveryKeyringInput<Client>
): IAwsKmsMrkAwareSymmetricDiscoveryKeyring<S, Client>
}
export function AwsKmsMrkAwareSymmetricDiscoveryKeyringClass<
S extends SupportedAlgorithmSuites,
Client extends AwsEsdkKMSInterface
>(
BaseKeyring: Newable<Keyring<S>>
): AwsKmsMrkAwareSymmetricDiscoveryKeyringConstructible<S, Client> {
class AwsKmsMrkAwareSymmetricDiscoveryKeyring
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.5
//# MUST implement that AWS Encryption SDK Keyring interface (../keyring-
//# interface.md#interface)
extends BaseKeyring
implements IAwsKmsMrkAwareSymmetricDiscoveryKeyring<S, Client>
{
public declare client: Client
public declare clientRegion: string
public declare grantTokens?: string[]
public declare discoveryFilter?: Readonly<{
accountIDs: readonly string[]
partition: string
}>
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.6
//# On initialization the caller MUST provide:
constructor({
client,
grantTokens,
discoveryFilter,
}: AwsKmsMrkAwareSymmetricDiscoveryKeyringInput<Client>) {
super()
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.6
//# The keyring MUST know what Region the AWS KMS client is in.
//
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.6
//# It
//# SHOULD obtain this information directly from the client as opposed to
//# having an additional parameter.
//
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.6
//# However if it can not, then it MUST
//# NOT create the client itself.
//
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.6
//# It SHOULD have a Region parameter and
//# SHOULD try to identify mismatched configurations.
//
// @ts-ignore the V3 client has set the config to protected
const clientRegion = client.config.region
needs(clientRegion, 'Client must be configured to a region.')
/* Precondition: The AwsKmsMrkAwareSymmetricDiscoveryKeyring Discovery filter *must* be able to match something.
* I am not going to wait to tell you
* that no CMK can match an empty account list.
* e.g. [], [''], '' are not valid.
*/
needs(
!discoveryFilter ||
(discoveryFilter.accountIDs &&
discoveryFilter.accountIDs.length &&
!!discoveryFilter.partition &&
discoveryFilter.accountIDs.every(
(a) => typeof a === 'string' && !!a
)),
'A discovery filter must be able to match something.'
)
readOnlyProperty(this, 'client', client)
readOnlyProperty(this, 'clientRegion', clientRegion)
readOnlyProperty(this, 'grantTokens', grantTokens)
readOnlyProperty(
this,
'discoveryFilter',
discoveryFilter
? Object.freeze({
...discoveryFilter,
accountIDs: Object.freeze(discoveryFilter.accountIDs),
})
: discoveryFilter
)
}
async _onEncrypt(): Promise<EncryptionMaterial<S>> {
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.7
//# This function MUST fail.
throw new Error(
'AwsKmsMrkAwareSymmetricDiscoveryKeyring cannot be used to encrypt'
)
}
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//# OnDecrypt MUST take decryption materials (structures.md#decryption-
//# materials) and a list of encrypted data keys
//# (structures.md#encrypted-data-key) as input.
async _onDecrypt(
material: DecryptionMaterial<S>,
encryptedDataKeys: EncryptedDataKey[]
): Promise<DecryptionMaterial<S>> {
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//# If the decryption materials (structures.md#decryption-materials)
//# already contained a valid plaintext data key OnDecrypt MUST
//# immediately return the unmodified decryption materials
//# (structures.md#decryption-materials).
if (material.hasValidKey()) return material
const { client, grantTokens, clientRegion } = this
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//# The set of encrypted data keys MUST first be filtered to match this
//# keyring's configuration.
const decryptableEDKs = encryptedDataKeys.filter(filterEDKs(this))
const cmkErrors: Catchable[] = []
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//# For each encrypted data key in the filtered set, one at a time, the
//# OnDecrypt MUST attempt to decrypt the data key.
for (const edk of decryptableEDKs) {
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//# Otherwise it MUST
//# be the provider info.
let keyId = edk.providerInfo
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//# * "KeyId": If the provider info's resource type is "key" and its
//# resource is a multi-Region key then a new ARN MUST be created
//# where the region part MUST equal the AWS KMS client region and
//# every other part MUST equal the provider info.
const keyArn = parseAwsKmsKeyArn(edk.providerInfo)
needs(keyArn, 'Unexpected EDK ProviderInfo for AWS KMS EDK')
if (isMultiRegionAwsKmsArn(keyArn)) {
keyId = constructArnInOtherRegion(keyArn, clientRegion)
}
let dataKey: RequiredDecryptResponse | false = false
try {
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//# When calling AWS KMS Decrypt
//# (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_Decrypt.html), the keyring MUST call with a request constructed
//# as follows:
dataKey = await decrypt(
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//# To attempt to decrypt a particular encrypted data key
//# (structures.md#encrypted-data-key), OnDecrypt MUST call AWS KMS
//# Decrypt (https://docs.aws.amazon.com/kms/latest/APIReference/
//# API_Decrypt.html) with the configured AWS KMS client.
client,
{
providerId: edk.providerId,
providerInfo: keyId,
encryptedDataKey: edk.encryptedDataKey,
},
material.encryptionContext,
grantTokens
)
/* This should be impossible given that decrypt only returns false if the client supplier does
* or if the providerId is not "aws-kms", which we have already filtered out
*/
if (!dataKey) continue
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//# * The "KeyId" field in the response MUST equal the requested "KeyId"
needs(
dataKey.KeyId === keyId,
'KMS Decryption key does not match the requested key id.'
)
const flags =
KeyringTraceFlag.WRAPPING_KEY_DECRYPTED_DATA_KEY |
KeyringTraceFlag.WRAPPING_KEY_VERIFIED_ENC_CTX
const trace: KeyringTrace = {
keyNamespace: KMS_PROVIDER_ID,
keyName: dataKey.KeyId,
flags,
}
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//# * The length of the response's "Plaintext" MUST equal the key
//# derivation input length (algorithm-suites.md#key-derivation-input-
//# length) specified by the algorithm suite (algorithm-suites.md)
//# included in the input decryption materials
//# (structures.md#decryption-materials).
//
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//# Since the response does satisfies these requirements then OnDecrypt
//# MUST do the following with the response:
//
// setUnencryptedDataKey will throw if the plaintext does not match the algorithm suite requirements.
material.setUnencryptedDataKey(dataKey.Plaintext, trace)
return material
} catch (e) {
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//# If the response does not satisfies these requirements then an error
//# is collected and the next encrypted data key in the filtered set MUST
//# be attempted.
cmkErrors.push({ errPlus: e })
}
}
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//# If OnDecrypt fails to successfully decrypt any encrypted data key
//# (structures.md#encrypted-data-key), then it MUST yield an error that
//# includes all collected errors.
needs(
material.hasValidKey(),
[
`Unable to decrypt data key${
!decryptableEDKs.length ? ': No EDKs supplied' : ''
}.`,
...cmkErrors.map((e, i) => `Error #${i + 1} \n${e.errPlus.stack}`),
].join('\n')
)
return material
}
}
immutableClass(AwsKmsMrkAwareSymmetricDiscoveryKeyring)
return AwsKmsMrkAwareSymmetricDiscoveryKeyring
}
function filterEDKs<
S extends SupportedAlgorithmSuites,
Client extends AwsEsdkKMSInterface
>({
discoveryFilter,
clientRegion,
}: IAwsKmsMrkAwareSymmetricDiscoveryKeyring<S, Client>) {
return function filter({ providerId, providerInfo }: EncryptedDataKey) {
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//# * Its provider ID MUST exactly match the value "aws-kms".
if (providerId !== KMS_PROVIDER_ID) return false
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//# * The provider info MUST be a valid AWS KMS ARN (aws-kms-key-
//# arn.md#a-valid-aws-kms-arn) with a resource type of "key" or
//# OnDecrypt MUST fail.
const edkArn = parseAwsKmsKeyArn(providerInfo)
needs(
edkArn && edkArn.ResourceType === 'key',
'Unexpected EDK ProviderInfo for AWS KMS EDK'
)
const {
AccountId: account,
Partition: partition,
Region: edkRegion,
} = edkArn
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//# * If the provider info is not identified as a multi-Region key (aws-
//# kms-key-arn.md#identifying-an-aws-kms-multi-region-key), then the
//# provider info's Region MUST match the AWS KMS client region.
if (!isMultiRegionAwsKmsArn(edkArn) && clientRegion !== edkRegion) {
return false
}
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//# * If a discovery filter is configured, its partition and the
//# provider info partition MUST match.
//
//= compliance/framework/aws-kms/aws-kms-mrk-aware-symmetric-region-discovery-keyring.txt#2.8
//# * If a discovery filter is configured, its set of accounts MUST
//# contain the provider info account.
return (
!discoveryFilter ||
(discoveryFilter.partition === partition &&
discoveryFilter.accountIDs.includes(account))
)
}
} | the_stack |
import * as fs from 'fs';
import * as path from 'path';
import { SynthUtils } from '@aws-cdk/assert-internal';
import '@aws-cdk/assert-internal/jest';
import * as s3_assets from '@aws-cdk/aws-s3-assets';
import * as sns from '@aws-cdk/aws-sns';
import { describeDeprecated } from '@aws-cdk/cdk-build-tools';
import { App, CfnParameter, CfnResource, ContextProvider, LegacyStackSynthesizer, Names, Stack } from '@aws-cdk/core';
import { NestedStack } from '../lib/nested-stack';
// keep this import separate from other imports to reduce chance for merge conflicts with v2-main
// eslint-disable-next-line no-duplicate-imports, import/order
import { Construct } from '@aws-cdk/core';
/* eslint-disable @aws-cdk/no-core-construct */
/* eslint-disable max-len */
describeDeprecated('NestedStack', () => {
test('fails if defined as a root', () => {
// THEN
expect(() => new NestedStack(undefined as any, 'boom')).toThrow(/Nested stacks cannot be defined as a root construct/);
});
test('fails if defined without a parent stack', () => {
// GIVEN
const app = new App();
const group = new Construct(app, 'group');
// THEN
expect(() => new NestedStack(app, 'boom')).toThrow(/must be defined within scope of another non-nested stack/);
expect(() => new NestedStack(group, 'bam')).toThrow(/must be defined within scope of another non-nested stack/);
});
test('can be defined as a direct child or an indirect child of a Stack', () => {
// GIVEN
const parent = new Stack();
// THEN
expect(() => new NestedStack(parent, 'direct')).not.toThrow();
expect(() => new NestedStack(new Construct(parent, 'group'), 'indirect')).not.toThrow();
});
test('nested stack is not synthesized as a stack artifact into the assembly', () => {
// GIVEN
const app = new App();
const parentStack = new Stack(app, 'parent-stack');
new NestedStack(parentStack, 'nested-stack');
// WHEN
const assembly = app.synth();
// THEN
expect(assembly.artifacts.length).toEqual(2);
});
test('the template of the nested stack is synthesized into the cloud assembly', () => {
// GIVEN
const app = new App();
const parent = new Stack(app, 'parent-stack');
const nested = new NestedStack(parent, 'nested-stack');
new CfnResource(nested, 'ResourceInNestedStack', { type: 'AWS::Resource::Nested' });
// WHEN
const assembly = app.synth();
// THEN
const template = JSON.parse(fs.readFileSync(path.join(assembly.directory, `${Names.uniqueId(nested)}.nested.template.json`), 'utf-8'));
expect(template).toEqual({
Resources: {
ResourceInNestedStack: {
Type: 'AWS::Resource::Nested',
},
},
});
});
test('file asset metadata is associated with the parent stack', () => {
// GIVEN
const app = new App();
const parent = new Stack(app, 'parent-stack');
const nested = new NestedStack(parent, 'nested-stack');
new CfnResource(nested, 'ResourceInNestedStack', { type: 'AWS::Resource::Nested' });
// WHEN
const assembly = app.synth();
// THEN
expect(assembly.getStackByName(parent.stackName).assets).toEqual([{
path: 'parentstacknestedstack844892C0.nested.template.json',
id: 'c639c0a5e7320758aa22589669ecebc98f185b711300b074f53998c8f9a45096',
packaging: 'file',
sourceHash: 'c639c0a5e7320758aa22589669ecebc98f185b711300b074f53998c8f9a45096',
s3BucketParameter: 'AssetParametersc639c0a5e7320758aa22589669ecebc98f185b711300b074f53998c8f9a45096S3BucketDA8C3345',
s3KeyParameter: 'AssetParametersc639c0a5e7320758aa22589669ecebc98f185b711300b074f53998c8f9a45096S3VersionKey09D03EE6',
artifactHashParameter: 'AssetParametersc639c0a5e7320758aa22589669ecebc98f185b711300b074f53998c8f9a45096ArtifactHash8DE450C7',
}]);
});
test('aws::cloudformation::stack is synthesized in the parent scope', () => {
// GIVEN
const app = new App();
const parent = new Stack(app, 'parent-stack');
// WHEN
const nested = new NestedStack(parent, 'nested-stack');
new CfnResource(nested, 'ResourceInNestedStack', { type: 'AWS::Resource::Nested' });
// THEN
const assembly = app.synth();
// assembly has one stack (the parent)
expect(assembly.stacks.length).toEqual(1);
// but this stack has an asset that points to the synthesized template
expect(assembly.stacks[0].assets[0].path).toEqual('parentstacknestedstack844892C0.nested.template.json');
// the template includes our resource
const filePath = path.join(assembly.directory, assembly.stacks[0].assets[0].path);
expect(JSON.parse(fs.readFileSync(filePath).toString('utf-8'))).toEqual({
Resources: { ResourceInNestedStack: { Type: 'AWS::Resource::Nested' } },
});
// the parent template includes the parameters and the nested stack resource which points to the s3 url
expect(parent).toMatchTemplate({
Resources: {
nestedstackNestedStacknestedstackNestedStackResource71CDD241: {
Type: 'AWS::CloudFormation::Stack',
DeletionPolicy: 'Delete',
UpdateReplacePolicy: 'Delete',
Properties: {
TemplateURL: {
'Fn::Join': [
'',
[
'https://s3.',
{
Ref: 'AWS::Region',
},
'.',
{
Ref: 'AWS::URLSuffix',
},
'/',
{
Ref: 'AssetParametersc639c0a5e7320758aa22589669ecebc98f185b711300b074f53998c8f9a45096S3BucketDA8C3345',
},
'/',
{
'Fn::Select': [
0,
{
'Fn::Split': [
'||',
{
Ref: 'AssetParametersc639c0a5e7320758aa22589669ecebc98f185b711300b074f53998c8f9a45096S3VersionKey09D03EE6',
},
],
},
],
},
{
'Fn::Select': [
1,
{
'Fn::Split': [
'||',
{
Ref: 'AssetParametersc639c0a5e7320758aa22589669ecebc98f185b711300b074f53998c8f9a45096S3VersionKey09D03EE6',
},
],
},
],
},
],
],
},
},
},
},
Parameters: {
AssetParametersc639c0a5e7320758aa22589669ecebc98f185b711300b074f53998c8f9a45096S3BucketDA8C3345: {
Type: 'String',
Description: 'S3 bucket for asset "c639c0a5e7320758aa22589669ecebc98f185b711300b074f53998c8f9a45096"',
},
AssetParametersc639c0a5e7320758aa22589669ecebc98f185b711300b074f53998c8f9a45096S3VersionKey09D03EE6: {
Type: 'String',
Description: 'S3 key for asset version "c639c0a5e7320758aa22589669ecebc98f185b711300b074f53998c8f9a45096"',
},
AssetParametersc639c0a5e7320758aa22589669ecebc98f185b711300b074f53998c8f9a45096ArtifactHash8DE450C7: {
Type: 'String',
Description: 'Artifact hash for asset "c639c0a5e7320758aa22589669ecebc98f185b711300b074f53998c8f9a45096"',
},
},
});
});
test('Stack.of()', () => {
class MyNestedStack extends NestedStack {
public readonly stackOfChild: Stack;
constructor(scope: Construct, id: string) {
super(scope, id);
const param = new CfnParameter(this, 'param', { type: 'String' });
this.stackOfChild = Stack.of(param);
}
}
const parent = new Stack();
const nested = new MyNestedStack(parent, 'nested');
expect(nested.stackOfChild).toEqual(nested);
expect(Stack.of(nested)).toEqual(nested);
});
test('references within the nested stack are not reported as cross stack references', () => {
class MyNestedStack extends NestedStack {
constructor(scope: Construct, id: string) {
super(scope, id);
const param = new CfnParameter(this, 'param', { type: 'String' });
new CfnResource(this, 'resource', {
type: 'My::Resource',
properties: {
SomeProp: param.valueAsString,
},
});
}
}
const app = new App();
const parent = new Stack(app, 'parent');
new MyNestedStack(parent, 'nested');
// references are added during "prepare"
const assembly = app.synth();
expect(assembly.stacks.length).toEqual(1);
expect(assembly.stacks[0].dependencies).toEqual([]);
});
test('references to a resource from the parent stack in a nested stack is translated into a cfn parameter', () => {
// WHEN
class MyNestedStack extends NestedStack {
constructor(scope: Construct, id: string, resourceFromParent: CfnResource) {
super(scope, id);
new CfnResource(this, 'resource', {
type: 'AWS::Child::Resource',
properties: {
ReferenceToResourceInParentStack: resourceFromParent.ref,
},
});
new CfnResource(this, 'resource2', {
type: 'My::Resource::2',
properties: {
Prop1: resourceFromParent.getAtt('Attr'),
Prop2: resourceFromParent.ref,
},
});
}
}
const app = new App();
const parentStack = new Stack(app, 'parent');
const resource = new CfnResource(parentStack, 'parent-resource', { type: 'AWS::Parent::Resource' });
const nested = new MyNestedStack(parentStack, 'nested', resource);
// THEN
app.synth();
// nested template should use a parameter to reference the resource from the parent stack
expect(nested).toMatchTemplate({
Resources:
{
resource:
{
Type: 'AWS::Child::Resource',
Properties:
{ ReferenceToResourceInParentStack: { Ref: 'referencetoparentparentresourceD56EA8F7Ref' } },
},
resource2:
{
Type: 'My::Resource::2',
Properties:
{
Prop1: { Ref: 'referencetoparentparentresourceD56EA8F7Attr' },
Prop2: { Ref: 'referencetoparentparentresourceD56EA8F7Ref' },
},
},
},
Parameters:
{
referencetoparentparentresourceD56EA8F7Ref: { Type: 'String' },
referencetoparentparentresourceD56EA8F7Attr: { Type: 'String' },
},
});
// parent template should pass in the value through the parameter
expect(parentStack).toHaveResource('AWS::CloudFormation::Stack', {
Parameters: {
referencetoparentparentresourceD56EA8F7Ref: {
Ref: 'parentresource',
},
referencetoparentparentresourceD56EA8F7Attr: {
'Fn::GetAtt': [
'parentresource',
'Attr',
],
},
},
});
});
test('references to a resource in the nested stack in the parent is translated into a cfn output', () => {
class MyNestedStack extends NestedStack {
public readonly resourceFromChild: CfnResource;
constructor(scope: Construct, id: string) {
super(scope, id);
this.resourceFromChild = new CfnResource(this, 'resource', {
type: 'AWS::Child::Resource',
});
}
}
const app = new App();
const parentStack = new Stack(app, 'parent');
const nested = new MyNestedStack(parentStack, 'nested');
new CfnResource(parentStack, 'another-parent-resource', {
type: 'AWS::Parent::Resource',
properties: {
RefToResourceInNestedStack: nested.resourceFromChild.ref,
},
});
// references are added during "prepare"
app.synth();
// nested template should use a parameter to reference the resource from the parent stack
expect(nested).toMatchTemplate({
Resources: {
resource: { Type: 'AWS::Child::Resource' },
},
Outputs: {
parentnestedresource4D680677Ref: { Value: { Ref: 'resource' } },
},
});
// parent template should pass in the value through the parameter
expect(parentStack).toHaveResource('AWS::Parent::Resource', {
RefToResourceInNestedStack: {
'Fn::GetAtt': [
'nestedNestedStacknestedNestedStackResource3DD143BF',
'Outputs.parentnestedresource4D680677Ref',
],
},
});
});
test('nested stack references a resource from another non-nested stack (not the parent)', () => {
// GIVEN
const app = new App();
const stack1 = new Stack(app, 'Stack1');
const stack2 = new Stack(app, 'Stack2');
const nestedUnderStack1 = new NestedStack(stack1, 'NestedUnderStack1');
const resourceInStack2 = new CfnResource(stack2, 'ResourceInStack2', { type: 'MyResource' });
// WHEN
new CfnResource(nestedUnderStack1, 'ResourceInNestedStack1', {
type: 'Nested::Resource',
properties: {
RefToSibling: resourceInStack2.getAtt('MyAttribute'),
},
});
// THEN
const assembly = app.synth();
// producing stack should have an export
expect(stack2).toMatchTemplate({
Resources: {
ResourceInStack2: { Type: 'MyResource' },
},
Outputs: {
ExportsOutputFnGetAttResourceInStack2MyAttributeC15F1009: {
Value: { 'Fn::GetAtt': ['ResourceInStack2', 'MyAttribute'] },
Export: { Name: 'Stack2:ExportsOutputFnGetAttResourceInStack2MyAttributeC15F1009' },
},
},
});
// nested stack uses Fn::ImportValue like normal
expect(nestedUnderStack1).toMatchTemplate({
Resources: {
ResourceInNestedStack1: {
Type: 'Nested::Resource',
Properties: {
RefToSibling: {
'Fn::ImportValue': 'Stack2:ExportsOutputFnGetAttResourceInStack2MyAttributeC15F1009',
},
},
},
},
});
// verify a depedency was established between the parents
const stack1Artifact = assembly.getStackByName(stack1.stackName);
const stack2Artifact = assembly.getStackByName(stack2.stackName);
expect(stack1Artifact.dependencies.length).toEqual(1);
expect(stack2Artifact.dependencies.length).toEqual(0);
expect(stack1Artifact.dependencies[0]).toEqual(stack2Artifact);
});
test('nested stack within a nested stack references a resource in a sibling top-level stack', () => {
// GIVEN
const app = new App();
const consumerTopLevel = new Stack(app, 'ConsumerTopLevel');
const consumerNested1 = new NestedStack(consumerTopLevel, 'ConsumerNested1');
const consumerNested2 = new NestedStack(consumerNested1, 'ConsumerNested2');
const producerTopLevel = new Stack(app, 'ProducerTopLevel');
const producer = new CfnResource(producerTopLevel, 'Producer', { type: 'Producer' });
// WHEN
new CfnResource(consumerNested2, 'Consumer', {
type: 'Consumer',
properties: {
Ref: producer.ref,
},
});
// THEN
const manifest = app.synth();
const consumerDeps = manifest.getStackArtifact(consumerTopLevel.artifactId).dependencies.map(d => d.id);
expect(consumerDeps).toEqual(['ProducerTopLevel']);
});
test('another non-nested stack takes a reference on a resource within the nested stack (the parent exports)', () => {
// GIVEN
const app = new App();
const stack1 = new Stack(app, 'Stack1');
const stack2 = new Stack(app, 'Stack2');
const nestedUnderStack1 = new NestedStack(stack1, 'NestedUnderStack1');
const resourceInNestedStack = new CfnResource(nestedUnderStack1, 'ResourceInNestedStack', { type: 'MyResource' });
// WHEN
new CfnResource(stack2, 'ResourceInStack2', {
type: 'JustResource',
properties: {
RefToSibling: resourceInNestedStack.getAtt('MyAttribute'),
},
});
// THEN
const assembly = app.synth();
// nested stack should output this value as if it was referenced by the parent (without the export)
expect(nestedUnderStack1).toMatchTemplate({
Resources: {
ResourceInNestedStack: {
Type: 'MyResource',
},
},
Outputs: {
Stack1NestedUnderStack1ResourceInNestedStack6EE9DCD2MyAttribute: {
Value: {
'Fn::GetAtt': [
'ResourceInNestedStack',
'MyAttribute',
],
},
},
},
});
// parent stack (stack1) should export this value
expect(assembly.getStackByName(stack1.stackName).template.Outputs).toEqual({
ExportsOutputFnGetAttNestedUnderStack1NestedStackNestedUnderStack1NestedStackResourceF616305BOutputsStack1NestedUnderStack1ResourceInNestedStack6EE9DCD2MyAttribute564EECF3: {
Value: { 'Fn::GetAtt': ['NestedUnderStack1NestedStackNestedUnderStack1NestedStackResourceF616305B', 'Outputs.Stack1NestedUnderStack1ResourceInNestedStack6EE9DCD2MyAttribute'] },
Export: { Name: 'Stack1:ExportsOutputFnGetAttNestedUnderStack1NestedStackNestedUnderStack1NestedStackResourceF616305BOutputsStack1NestedUnderStack1ResourceInNestedStack6EE9DCD2MyAttribute564EECF3' },
},
});
// consuming stack should use ImportValue to import the value from the parent stack
expect(stack2).toMatchTemplate({
Resources: {
ResourceInStack2: {
Type: 'JustResource',
Properties: {
RefToSibling: {
'Fn::ImportValue': 'Stack1:ExportsOutputFnGetAttNestedUnderStack1NestedStackNestedUnderStack1NestedStackResourceF616305BOutputsStack1NestedUnderStack1ResourceInNestedStack6EE9DCD2MyAttribute564EECF3',
},
},
},
},
});
expect(assembly.stacks.length).toEqual(2);
const stack1Artifact = assembly.getStackByName(stack1.stackName);
const stack2Artifact = assembly.getStackByName(stack2.stackName);
expect(stack1Artifact.dependencies.length).toEqual(0);
expect(stack2Artifact.dependencies.length).toEqual(1);
expect(stack2Artifact.dependencies[0]).toEqual(stack1Artifact);
});
test('references between sibling nested stacks should output from one and getAtt from the other', () => {
// GIVEN
const app = new App();
const parent = new Stack(app, 'Parent');
const nested1 = new NestedStack(parent, 'Nested1');
const nested2 = new NestedStack(parent, 'Nested2');
const resource1 = new CfnResource(nested1, 'Resource1', { type: 'Resource1' });
// WHEN
new CfnResource(nested2, 'Resource2', {
type: 'Resource2',
properties: {
RefToResource1: resource1.ref,
},
});
// THEN
app.synth();
// producing nested stack
expect(nested1).toMatchTemplate({
Resources: {
Resource1: {
Type: 'Resource1',
},
},
Outputs: {
ParentNested1Resource15F3F0657Ref: {
Value: {
Ref: 'Resource1',
},
},
},
});
// consuming nested stack
expect(nested2).toMatchTemplate({
Resources: {
Resource2: {
Type: 'Resource2',
Properties: {
RefToResource1: {
Ref: 'referencetoParentNested1NestedStackNested1NestedStackResource9C05342COutputsParentNested1Resource15F3F0657Ref',
},
},
},
},
Parameters: {
referencetoParentNested1NestedStackNested1NestedStackResource9C05342COutputsParentNested1Resource15F3F0657Ref: {
Type: 'String',
},
},
});
// parent
expect(parent).toHaveResource('AWS::CloudFormation::Stack', {
Parameters: {
referencetoParentNested1NestedStackNested1NestedStackResource9C05342COutputsParentNested1Resource15F3F0657Ref: {
'Fn::GetAtt': [
'Nested1NestedStackNested1NestedStackResourceCD0AD36B',
'Outputs.ParentNested1Resource15F3F0657Ref',
],
},
},
});
});
test('stackId returns AWS::StackId when referenced from the context of the nested stack', () => {
// GIVEN
const parent = new Stack();
const nested = new NestedStack(parent, 'NestedStack');
// WHEN
new CfnResource(nested, 'NestedResource', {
type: 'Nested::Resource',
properties: { MyStackId: nested.stackId },
});
// THEN
expect(nested).toHaveResource('Nested::Resource', {
MyStackId: { Ref: 'AWS::StackId' },
});
});
test('stackId returns the REF of the CloudFormation::Stack resource when referenced from the parent stack', () => {
// GIVEN
const parent = new Stack();
const nested = new NestedStack(parent, 'NestedStack');
// WHEN
new CfnResource(parent, 'ParentResource', {
type: 'Parent::Resource',
properties: { NestedStackId: nested.stackId },
});
// THEN
expect(parent).toHaveResource('Parent::Resource', {
NestedStackId: { Ref: 'NestedStackNestedStackNestedStackNestedStackResourceB70834FD' },
});
});
test('stackName returns AWS::StackName when referenced from the context of the nested stack', () => {
// GIVEN
const parent = new Stack();
const nested = new NestedStack(parent, 'NestedStack');
// WHEN
new CfnResource(nested, 'NestedResource', {
type: 'Nested::Resource',
properties: { MyStackName: nested.stackName },
});
// THEN
expect(nested).toHaveResource('Nested::Resource', {
MyStackName: { Ref: 'AWS::StackName' },
});
});
test('stackName returns the REF of the CloudFormation::Stack resource when referenced from the parent stack', () => {
// GIVEN
const parent = new Stack();
const nested = new NestedStack(parent, 'NestedStack');
// WHEN
new CfnResource(parent, 'ParentResource', {
type: 'Parent::Resource',
properties: { NestedStackName: nested.stackName },
});
// THEN
expect(parent).toHaveResource('Parent::Resource', {
NestedStackName: {
'Fn::Select': [
1,
{
'Fn::Split': [
'/',
{
Ref: 'NestedStackNestedStackNestedStackNestedStackResourceB70834FD',
},
],
},
],
},
});
});
test('"account", "region" and "environment" are all derived from the parent', () => {
// GIVEN
const app = new App();
const parent = new Stack(app, 'ParentStack', { env: { account: '1234account', region: 'us-east-44' } });
// WHEN
const nested = new NestedStack(parent, 'NestedStack');
// THEN
expect(nested.environment).toEqual(parent.environment);
expect(nested.account).toEqual(parent.account);
expect(nested.region).toEqual(parent.region);
});
test('double-nested stack', () => {
// GIVEN
const app = new App();
const parent = new Stack(app, 'stack');
// WHEN
const nested1 = new NestedStack(parent, 'Nested1');
const nested2 = new NestedStack(nested1, 'Nested2');
new CfnResource(nested1, 'Resource1', { type: 'Resource::1' });
new CfnResource(nested2, 'Resource2', { type: 'Resource::2' });
// THEN
const assembly = app.synth();
// nested2 is a "leaf", so it's just the resource
expect(nested2).toMatchTemplate({
Resources: {
Resource2: { Type: 'Resource::2' },
},
});
const middleStackHash = '7c426f7299a739900279ac1ece040397c1913cdf786f5228677b289f4d5e4c48';
const bucketSuffix = 'C706B101';
const versionSuffix = '4B193AA5';
const hashSuffix = 'E28F0693';
// nested1 wires the nested2 template through parameters, so we expect those
expect(nested1).toHaveResource('Resource::1');
const nested2Template = SynthUtils.toCloudFormation(nested1);
expect(nested2Template.Parameters).toEqual({
referencetostackAssetParameters8169c6f8aaeaf5e2e8620f5f895ffe2099202ccb4b6889df48fe0967a894235cS3BucketE8768F5CRef: { Type: 'String' },
referencetostackAssetParameters8169c6f8aaeaf5e2e8620f5f895ffe2099202ccb4b6889df48fe0967a894235cS3VersionKey49DD83A2Ref: { Type: 'String' },
});
// parent stack should have two sets of parameters. one for the first nested stack and the second
// for the second nested stack, passed in as parameters to the first
const template = SynthUtils.toCloudFormation(parent);
expect(template.Parameters).toEqual({
AssetParameters8169c6f8aaeaf5e2e8620f5f895ffe2099202ccb4b6889df48fe0967a894235cS3BucketDE3B88D6: { Type: 'String', Description: 'S3 bucket for asset "8169c6f8aaeaf5e2e8620f5f895ffe2099202ccb4b6889df48fe0967a894235c"' },
AssetParameters8169c6f8aaeaf5e2e8620f5f895ffe2099202ccb4b6889df48fe0967a894235cS3VersionKey3A62EFEA: { Type: 'String', Description: 'S3 key for asset version "8169c6f8aaeaf5e2e8620f5f895ffe2099202ccb4b6889df48fe0967a894235c"' },
AssetParameters8169c6f8aaeaf5e2e8620f5f895ffe2099202ccb4b6889df48fe0967a894235cArtifactHash7DC546E0: { Type: 'String', Description: 'Artifact hash for asset "8169c6f8aaeaf5e2e8620f5f895ffe2099202ccb4b6889df48fe0967a894235c"' },
[`AssetParameters${middleStackHash}S3Bucket${bucketSuffix}`]: { Type: 'String', Description: `S3 bucket for asset "${middleStackHash}"` },
[`AssetParameters${middleStackHash}S3VersionKey${versionSuffix}`]: { Type: 'String', Description: `S3 key for asset version "${middleStackHash}"` },
[`AssetParameters${middleStackHash}ArtifactHash${hashSuffix}`]: { Type: 'String', Description: `Artifact hash for asset "${middleStackHash}"` },
});
// proxy asset params to nested stack
expect(parent).toHaveResource('AWS::CloudFormation::Stack', {
Parameters: {
referencetostackAssetParameters8169c6f8aaeaf5e2e8620f5f895ffe2099202ccb4b6889df48fe0967a894235cS3BucketE8768F5CRef: { Ref: 'AssetParameters8169c6f8aaeaf5e2e8620f5f895ffe2099202ccb4b6889df48fe0967a894235cS3BucketDE3B88D6' },
referencetostackAssetParameters8169c6f8aaeaf5e2e8620f5f895ffe2099202ccb4b6889df48fe0967a894235cS3VersionKey49DD83A2Ref: { Ref: 'AssetParameters8169c6f8aaeaf5e2e8620f5f895ffe2099202ccb4b6889df48fe0967a894235cS3VersionKey3A62EFEA' },
},
});
// parent stack should have 2 assets
expect(assembly.getStackByName(parent.stackName).assets.length).toEqual(2);
});
test('reference resource in a double nested stack (#15155)', () => {
// GIVEN
const app = new App();
const producerStack = new Stack(app, 'Producer');
const nested2 = new NestedStack(new NestedStack(producerStack, 'Nested1'), 'Nested2');
const producerResource = new CfnResource(nested2, 'Resource', { type: 'MyResource' });
const consumerStack = new Stack(app, 'Consumer');
// WHEN
new CfnResource(consumerStack, 'ConsumingResource', {
type: 'YourResource',
properties: { RefToResource: producerResource.ref },
});
// THEN
const casm = app.synth(); // before #15155 was fixed this threw an error
const producerTemplate = casm.getStackArtifact(producerStack.artifactId).template;
const consumerTemplate = casm.getStackArtifact(consumerStack.artifactId).template;
// check that the consuming resource references the expected export name
const outputName = 'ExportsOutputFnGetAttNested1NestedStackNested1NestedStackResourceCD0AD36BOutputsProducerNested1Nested2NestedStackNested2NestedStackResource1E6FA3C3OutputsProducerNested1Nested238A89CC5Ref2E9E52EA';
const exportName = producerTemplate.Outputs[outputName].Export.Name;
const importName = consumerTemplate.Resources.ConsumingResource.Properties.RefToResource['Fn::ImportValue'];
expect(exportName).toEqual(importName);
});
test('assets within nested stacks are proxied from the parent', () => {
// GIVEN
const app = new App();
const parent = new Stack(app, 'ParentStack');
const nested = new NestedStack(parent, 'NestedStack');
// WHEN
const asset = new s3_assets.Asset(nested, 'asset', {
path: path.join(__dirname, 'asset-fixture.txt'),
});
new CfnResource(nested, 'NestedResource', {
type: 'Nested::Resource',
properties: {
AssetBucket: asset.s3BucketName,
AssetKey: asset.s3ObjectKey,
},
});
// THEN
const assembly = app.synth();
const template = SynthUtils.toCloudFormation(parent);
// two sets of asset parameters: one for the nested stack itself and one as a proxy for the asset within the stack
expect(template.Parameters).toEqual({
AssetParametersdb01ee2eb7adc7915e364dc410d861e569543f9be3761d535a68d5c2cc181281S3BucketC188F637: { Type: 'String', Description: 'S3 bucket for asset "db01ee2eb7adc7915e364dc410d861e569543f9be3761d535a68d5c2cc181281"' },
AssetParametersdb01ee2eb7adc7915e364dc410d861e569543f9be3761d535a68d5c2cc181281S3VersionKeyC7F4DBF2: { Type: 'String', Description: 'S3 key for asset version "db01ee2eb7adc7915e364dc410d861e569543f9be3761d535a68d5c2cc181281"' },
AssetParametersdb01ee2eb7adc7915e364dc410d861e569543f9be3761d535a68d5c2cc181281ArtifactHash373B14D2: { Type: 'String', Description: 'Artifact hash for asset "db01ee2eb7adc7915e364dc410d861e569543f9be3761d535a68d5c2cc181281"' },
AssetParameters46b107d6db798ca46046b8669d057a4debcbdbaaddb6170400748c2f9e4f9d71S3Bucket3C4265E9: { Type: 'String', Description: 'S3 bucket for asset "46b107d6db798ca46046b8669d057a4debcbdbaaddb6170400748c2f9e4f9d71"' },
AssetParameters46b107d6db798ca46046b8669d057a4debcbdbaaddb6170400748c2f9e4f9d71S3VersionKey8E981535: { Type: 'String', Description: 'S3 key for asset version "46b107d6db798ca46046b8669d057a4debcbdbaaddb6170400748c2f9e4f9d71"' },
AssetParameters46b107d6db798ca46046b8669d057a4debcbdbaaddb6170400748c2f9e4f9d71ArtifactHash45A28583: { Type: 'String', Description: 'Artifact hash for asset "46b107d6db798ca46046b8669d057a4debcbdbaaddb6170400748c2f9e4f9d71"' },
});
// asset proxy parameters are passed to the nested stack
expect(parent).toHaveResource('AWS::CloudFormation::Stack', {
Parameters: {
referencetoParentStackAssetParametersdb01ee2eb7adc7915e364dc410d861e569543f9be3761d535a68d5c2cc181281S3Bucket82C55B96Ref: { Ref: 'AssetParametersdb01ee2eb7adc7915e364dc410d861e569543f9be3761d535a68d5c2cc181281S3BucketC188F637' },
referencetoParentStackAssetParametersdb01ee2eb7adc7915e364dc410d861e569543f9be3761d535a68d5c2cc181281S3VersionKeyA43C3CC6Ref: { Ref: 'AssetParametersdb01ee2eb7adc7915e364dc410d861e569543f9be3761d535a68d5c2cc181281S3VersionKeyC7F4DBF2' },
},
});
// parent stack should have 2 assets
expect(assembly.getStackByName(parent.stackName).assets.length).toEqual(2);
});
test('docker image assets are wired through the top-level stack', () => {
// GIVEN
const app = new App();
const parent = new Stack(app, 'my-stack');
const nested = new NestedStack(parent, 'nested-stack');
// WHEN
const location = nested.synthesizer.addDockerImageAsset({
directoryName: 'my-image',
dockerBuildArgs: { key: 'value', boom: 'bam' },
dockerBuildTarget: 'buildTarget',
sourceHash: 'hash-of-source',
});
// use the asset, so the parameters will be wired.
new sns.Topic(nested, 'MyTopic', {
displayName: `image location is ${location.imageUri}`,
});
// THEN
const asm = app.synth();
expect(asm.getStackArtifact(parent.artifactId).assets).toEqual([
{
repositoryName: 'aws-cdk/assets',
imageTag: 'hash-of-source',
id: 'hash-of-source',
packaging: 'container-image',
path: 'my-image',
sourceHash: 'hash-of-source',
buildArgs: { key: 'value', boom: 'bam' },
target: 'buildTarget',
},
{
path: 'mystacknestedstackFAE12FB5.nested.template.json',
id: 'fcdaee79eb79f37eca3a9b1cc0cc9ba150e4eea8c5d6d0c343cb6cd9dc68e2e5',
packaging: 'file',
sourceHash: 'fcdaee79eb79f37eca3a9b1cc0cc9ba150e4eea8c5d6d0c343cb6cd9dc68e2e5',
s3BucketParameter: 'AssetParametersfcdaee79eb79f37eca3a9b1cc0cc9ba150e4eea8c5d6d0c343cb6cd9dc68e2e5S3Bucket67A749F8',
s3KeyParameter: 'AssetParametersfcdaee79eb79f37eca3a9b1cc0cc9ba150e4eea8c5d6d0c343cb6cd9dc68e2e5S3VersionKeyE1E6A8D4',
artifactHashParameter: 'AssetParametersfcdaee79eb79f37eca3a9b1cc0cc9ba150e4eea8c5d6d0c343cb6cd9dc68e2e5ArtifactHash0AEDBE8A',
},
]);
});
test('metadata defined in nested stacks is reported at the parent stack level in the cloud assembly', () => {
// GIVEN
const app = new App({ stackTraces: false });
const parent = new Stack(app, 'parent');
const child = new Stack(parent, 'child');
const nested = new NestedStack(child, 'nested');
const resource = new CfnResource(nested, 'resource', { type: 'foo' });
// WHEN
resource.node.addMetadata('foo', 'bar');
// THEN: the first non-nested stack records the assembly metadata
const asm = app.synth();
expect(asm.stacks.length).toEqual(2); // only one stack is defined as an artifact
expect(asm.getStackByName(parent.stackName).findMetadataByType('foo')).toEqual([]);
expect(asm.getStackByName(child.stackName).findMetadataByType('foo')).toEqual([
{
path: '/parent/child/nested/resource',
type: 'foo',
data: 'bar',
},
]);
});
test('referencing attributes with period across stacks', () => {
// GIVEN
const parent = new Stack();
const nested = new NestedStack(parent, 'nested');
const consumed = new CfnResource(nested, 'resource-in-nested', { type: 'CONSUMED' });
// WHEN
new CfnResource(parent, 'resource-in-parent', {
type: 'CONSUMER',
properties: {
ConsumedAttribute: consumed.getAtt('Consumed.Attribute'),
},
});
// THEN
expect(nested).toMatchTemplate({
Resources: {
resourceinnested: {
Type: 'CONSUMED',
},
},
Outputs: {
nestedresourceinnested59B1F01CConsumedAttribute: {
Value: {
'Fn::GetAtt': [
'resourceinnested',
'Consumed.Attribute',
],
},
},
},
});
expect(parent).toHaveResource('CONSUMER', {
ConsumedAttribute: {
'Fn::GetAtt': [
'nestedNestedStacknestedNestedStackResource3DD143BF',
'Outputs.nestedresourceinnested59B1F01CConsumedAttribute',
],
},
});
});
test('missing context in nested stack is reported if the context is not available', () => {
// GIVEN
const app = new App();
const stack = new Stack(app, 'ParentStack', { env: { account: '1234account', region: 'us-east-44' } });
const nestedStack = new NestedStack(stack, 'nested');
const provider = 'availability-zones';
const expectedKey = ContextProvider.getKey(nestedStack, {
provider,
}).key;
// WHEN
ContextProvider.getValue(nestedStack, {
provider,
dummyValue: ['dummy1a', 'dummy1b', 'dummy1c'],
});
// THEN: missing context is reported in the cloud assembly
const asm = app.synth();
const missing = asm.manifest.missing;
expect(missing && missing.find(m => {
return (m.key === expectedKey);
})).toBeTruthy();
});
test('3-level stacks: legacy synthesizer parameters are added to the middle-level stack', () => {
// GIVEN
const app = new App();
const top = new Stack(app, 'stack', {
synthesizer: new LegacyStackSynthesizer(),
});
const middle = new NestedStack(top, 'nested1');
const bottom = new NestedStack(middle, 'nested2');
// WHEN
new CfnResource(bottom, 'Something', {
type: 'BottomLevel',
});
// THEN
const asm = app.synth();
const middleTemplate = JSON.parse(fs.readFileSync(path.join(asm.directory, middle.templateFile), { encoding: 'utf-8' }));
const hash = 'bc3c51e4d3545ee0a0069401e5a32c37b66d044b983f12de416ba1576ecaf0a4';
expect(middleTemplate.Parameters ?? {}).toEqual({
[`referencetostackAssetParameters${hash}S3BucketD7C30435Ref`]: {
Type: 'String',
},
[`referencetostackAssetParameters${hash}S3VersionKeyB667DBE1Ref`]: {
Type: 'String',
},
});
});
test('references to a resource from a deeply nested stack', () => {
// GIVEN
const app = new App();
const top = new Stack(app, 'stack');
const topLevel = new CfnResource(top, 'toplevel', { type: 'TopLevel' });
const nested1 = new NestedStack(top, 'nested1');
const nested2 = new NestedStack(nested1, 'nested2');
// WHEN
new CfnResource(nested2, 'refToTopLevel', {
type: 'BottomLevel',
properties: { RefToTopLevel: topLevel.ref },
});
// THEN
expect(top).toHaveResource('AWS::CloudFormation::Stack', {
Parameters: {
referencetostackAssetParameters842982bd421cce9742ba27151ef12ed699d44d22801f41e8029f63f2358a3f2fS3Bucket5DA5D2E7Ref: {
Ref: 'AssetParameters842982bd421cce9742ba27151ef12ed699d44d22801f41e8029f63f2358a3f2fS3BucketDD4D96B5',
},
referencetostackAssetParameters842982bd421cce9742ba27151ef12ed699d44d22801f41e8029f63f2358a3f2fS3VersionKey8FBE5C12Ref: {
Ref: 'AssetParameters842982bd421cce9742ba27151ef12ed699d44d22801f41e8029f63f2358a3f2fS3VersionKey83E381F3',
},
referencetostacktoplevelBB16BF13Ref: {
Ref: 'toplevel',
},
},
});
expect(nested1).toHaveResource('AWS::CloudFormation::Stack', {
Parameters: {
referencetostacktoplevelBB16BF13Ref: {
Ref: 'referencetostacktoplevelBB16BF13Ref',
},
},
});
expect(nested2).toMatchTemplate({
Resources: {
refToTopLevel: {
Type: 'BottomLevel',
Properties: {
RefToTopLevel: {
Ref: 'referencetostacktoplevelBB16BF13Ref',
},
},
},
},
Parameters: {
referencetostacktoplevelBB16BF13Ref: {
Type: 'String',
},
},
});
});
test('bottom nested stack consumes value from a top-level stack through a parameter in a middle nested stack', () => {
// GIVEN
const app = new App();
const top = new Stack(app, 'Grandparent');
const middle = new NestedStack(top, 'Parent');
const bottom = new NestedStack(middle, 'Child');
const resourceInGrandparent = new CfnResource(top, 'ResourceInGrandparent', { type: 'ResourceInGrandparent' });
// WHEN
new CfnResource(bottom, 'ResourceInChild', {
type: 'ResourceInChild',
properties: {
RefToGrandparent: resourceInGrandparent.ref,
},
});
// THEN
// this is the name allocated for the parameter that's propagated through
// the hierarchy.
const paramName = 'referencetoGrandparentResourceInGrandparent010E997ARef';
// child (bottom) references through a parameter.
expect(bottom).toMatchTemplate({
Resources: {
ResourceInChild: {
Type: 'ResourceInChild',
Properties: {
RefToGrandparent: { Ref: paramName },
},
},
},
Parameters: {
[paramName]: { Type: 'String' },
},
});
// the parent (middle) sets the value of this parameter to be a reference to another parameter
expect(middle).toHaveResource('AWS::CloudFormation::Stack', {
Parameters: {
[paramName]: { Ref: paramName },
},
});
// grandparent (top) assigns the actual value to the parameter
expect(top).toHaveResource('AWS::CloudFormation::Stack', {
Parameters: {
[paramName]: { Ref: 'ResourceInGrandparent' },
// these are for the asset of the bottom nested stack
referencetoGrandparentAssetParameters3208f43b793a1dbe28ca02cf31fb975489071beb42c492b22dc3d32decc3b4b7S3Bucket06EEE58DRef: {
Ref: 'AssetParameters3208f43b793a1dbe28ca02cf31fb975489071beb42c492b22dc3d32decc3b4b7S3Bucket01877C2E',
},
referencetoGrandparentAssetParameters3208f43b793a1dbe28ca02cf31fb975489071beb42c492b22dc3d32decc3b4b7S3VersionKeyD3B04909Ref: {
Ref: 'AssetParameters3208f43b793a1dbe28ca02cf31fb975489071beb42c492b22dc3d32decc3b4b7S3VersionKey5765F084',
},
},
});
});
}); | the_stack |
import {SqlResult, SqlResultImpl} from './SqlResult';
import {ConnectionManager} from '../network/ConnectionManager';
import {ConnectionRegistry} from '../network/ConnectionRegistry';
import {SqlExpectedResultType, SqlStatement, SqlStatementOptions} from './SqlStatement';
import {HazelcastSqlException, IllegalArgumentError} from '../core';
import {SqlErrorCode} from './SqlErrorCode';
import {SqlQueryId} from './SqlQueryId';
import {SerializationService} from '../serialization/SerializationService';
import {SqlExecuteCodec} from '../codec/SqlExecuteCodec';
import * as Long from 'long';
import {InvocationService} from '../invocation/InvocationService';
import {ClientMessage} from '../protocol/ClientMessage';
import {Connection} from '../network/Connection';
import {SqlRowMetadataImpl} from './SqlRowMetadata';
import {SqlCloseCodec} from '../codec/SqlCloseCodec';
import {SqlFetchCodec} from '../codec/SqlFetchCodec';
import {
tryGetArray,
tryGetBoolean,
tryGetEnum,
tryGetNumber,
tryGetString
} from '../util/Util';
import {SqlPage} from './SqlPage';
import {Data} from '../serialization';
import {SqlError} from './SqlError';
/**
* SQL Service of the client. You can use this service to execute SQL queries.
*
* ## Enabling SQL Service
*
* To use this service, the Jet engine must be enabled on the members and the `hazelcast-sql` module must be in the classpath
* of the members. If you are using the CLI, Docker image, or distributions to start Hazelcast members, then you don't need to
* do anything, as the above preconditions are already satisfied for such members.
*
* However, if you are using Hazelcast members in the embedded mode, or receiving errors saying that
* `The Jet engine is disabled` or `Cannot execute SQL query because "hazelcast-sql" module is not in the classpath.` while
* executing queries, enable the Jet engine following one of the instructions pointed out in the error message, or add the
* `hazelcast-sql` module to your member's classpath.
*
* ## Overview
*
* Hazelcast is currently able to execute distributed SQL queries using the following connectors:
* * {@link IMap}
* * Kafka
* * Files
*
* SQL statements are not atomic. _INSERT_/_SINK_ can fail and commit part of the data.
*
* ## Usage
*
* Before you can access any object using SQL, a _mapping_ has to be created. See the documentation for the `CREATE MAPPING`
* command.
*
* When a query is executed, an {@link SqlResult} is returned. The returned result is an async iterable of {@link SqlRowType}.
* It can also be iterated using {@link SqlResult.next} method. The result should be closed at the end to release server
* resources. Fetching the last page closes the result. The code snippet below demonstrates a typical usage pattern:
*
* ```
* const client = await Client.newHazelcastClient();
* const result = await client.getSql().execute('SELECT * FROM persons');
* for await (const row of result) {
* console.log(row.personId);
* console.log(row.name);
* }
* await result.close();
* await client.shutdown();
* ```
*/
export interface SqlService {
/**
* Executes SQL and returns an {@link SqlResult}.
* Converts passed SQL string and parameter values into an {@link SqlStatement} object and invokes {@link executeStatement}.
*
* @param sql SQL string. SQL string placeholder character is question mark(`?`)
* @param params Parameter list. The parameter count must be equal to number of placeholders in the SQL string
* @param options Options that are affecting how the query is executed
* @throws {@link IllegalArgumentError} if arguments are not valid
* @throws {@link HazelcastSqlException} in case of an execution error
*/
execute(sql: string, params?: any[], options?: SqlStatementOptions): Promise<SqlResult>;
/**
* Executes SQL and returns an {@link SqlResult}.
* @param sql SQL statement object
* @throws {@link IllegalArgumentError} if arguments are not valid
* @throws {@link HazelcastSqlException} in case of an execution error
*/
executeStatement(sql: SqlStatement): Promise<SqlResult>;
}
/** @internal */
export class SqlServiceImpl implements SqlService {
/** Value for the timeout that is not set. */
static readonly TIMEOUT_NOT_SET = Long.fromInt(-1);
/** Default timeout. */
static readonly DEFAULT_TIMEOUT = SqlServiceImpl.TIMEOUT_NOT_SET;
/** Default cursor buffer size. */
static readonly DEFAULT_CURSOR_BUFFER_SIZE = 4096;
static readonly DEFAULT_FOR_RETURN_RAW_RESULT = false; // don't return raw result by default
static readonly DEFAULT_EXPECTED_RESULT_TYPE = SqlExpectedResultType.ANY;
static readonly DEFAULT_SCHEMA: null = null;
constructor(
private readonly connectionRegistry: ConnectionRegistry,
private readonly serializationService: SerializationService,
private readonly invocationService: InvocationService,
private readonly connectionManager: ConnectionManager
) {
}
/**
* Handles SQL execute response.
* @param clientMessage The response message
* @param res SQL result for this response
*/
private static handleExecuteResponse(clientMessage: ClientMessage, res: SqlResultImpl): void {
const response = SqlExecuteCodec.decodeResponse(clientMessage);
const sqlError = response.error;
if (sqlError !== null) {
throw new HazelcastSqlException(sqlError.originatingMemberId, sqlError.code, sqlError.message, sqlError.suggestion);
} else {
res.onExecuteResponse(
response.rowMetadata !== null ? new SqlRowMetadataImpl(response.rowMetadata) : null,
response.rowPage,
response.updateCount
);
}
}
/**
* Validates SqlStatement
*
* @param sqlStatement
* @throws RangeError if validation is not successful
*/
private static validateSqlStatement(sqlStatement: SqlStatement | null): void {
if (sqlStatement === null) {
throw new RangeError('SQL statement cannot be null');
}
tryGetString(sqlStatement.sql);
if (sqlStatement.sql.length === 0) { // empty sql string is disallowed
throw new RangeError('Empty SQL string is disallowed.')
}
if (sqlStatement.hasOwnProperty('params')) { // if params is provided, validate it
tryGetArray(sqlStatement.params);
}
if (sqlStatement.hasOwnProperty('options')) { // if options is provided, validate it
SqlServiceImpl.validateSqlStatementOptions(sqlStatement.options);
}
}
/**
* Validates SqlStatementOptions
*
* @param sqlStatementOptions
* @throws RangeError if validation is not successful
*/
private static validateSqlStatementOptions(sqlStatementOptions: SqlStatementOptions): void {
if (sqlStatementOptions.hasOwnProperty('schema')) {
tryGetString(sqlStatementOptions.schema);
}
if (sqlStatementOptions.hasOwnProperty('timeoutMillis')) {
const timeoutMillis = tryGetNumber(sqlStatementOptions.timeoutMillis);
if (timeoutMillis < 0 && timeoutMillis !== -1) {
throw new RangeError('Timeout millis can be non-negative or -1');
}
}
if (sqlStatementOptions.hasOwnProperty('cursorBufferSize') && tryGetNumber(sqlStatementOptions.cursorBufferSize) <= 0) {
throw new RangeError('Cursor buffer size cannot be negative');
}
if (sqlStatementOptions.hasOwnProperty('expectedResultType')) {
tryGetEnum(SqlExpectedResultType, sqlStatementOptions.expectedResultType);
}
if (sqlStatementOptions.hasOwnProperty('returnRawResult')) {
tryGetBoolean(sqlStatementOptions.returnRawResult);
}
}
/**
* Converts an error to HazelcastSqlException and returns it. Used by execute, close and fetch
* @param err
* @param connection
* @returns {@link HazelcastSqlException}
*/
rethrow(err: Error, connection: Connection): HazelcastSqlException {
if (err instanceof HazelcastSqlException) {
return err;
}
if (!connection.isAlive()) {
return new HazelcastSqlException(
this.connectionManager.getClientUuid(),
SqlErrorCode.CONNECTION_PROBLEM,
'Cluster topology changed while a query was executed:' +
`Member cannot be reached: ${connection.getRemoteAddress()}`,
undefined,
err
)
} else {
return this.toHazelcastSqlException(err);
}
}
toHazelcastSqlException(err: Error, message: string = err.message): HazelcastSqlException {
let originatingMemberId;
if (err instanceof SqlError) {
originatingMemberId = err.originatingMemberId;
} else {
originatingMemberId = this.connectionManager.getClientUuid();
}
return new HazelcastSqlException(
originatingMemberId, SqlErrorCode.GENERIC, message, undefined, err
);
}
executeStatement(sqlStatement: SqlStatement): Promise<SqlResult> {
try {
SqlServiceImpl.validateSqlStatement(sqlStatement);
} catch (error) {
throw new IllegalArgumentError(`Invalid argument given to execute(): ${error.message}`, error)
}
let connection: Connection | null;
try {
connection = this.connectionRegistry.getConnectionForSql();
} catch (e) {
throw this.toHazelcastSqlException(e);
}
if (connection === null) {
// The client is not connected to the cluster.
throw new HazelcastSqlException(
this.connectionManager.getClientUuid(),
SqlErrorCode.CONNECTION_PROBLEM,
'Client is not currently connected to the cluster.'
);
}
const queryId = SqlQueryId.fromMemberId(connection.getRemoteUuid());
const expectedResultType: SqlExpectedResultType = sqlStatement.options?.hasOwnProperty('expectedResultType') ?
SqlExpectedResultType[sqlStatement.options.expectedResultType] : SqlServiceImpl.DEFAULT_EXPECTED_RESULT_TYPE;
let timeoutMillis: Long;
if (sqlStatement.options?.hasOwnProperty('timeoutMillis')) {
timeoutMillis = Long.fromNumber(sqlStatement.options.timeoutMillis);
} else {
timeoutMillis = SqlServiceImpl.DEFAULT_TIMEOUT;
}
try {
let serializedParams;
if (Array.isArray(sqlStatement.params)) { // params can be undefined
serializedParams = new Array(sqlStatement.params.length);
for (let i = 0; i < sqlStatement.params.length; i++) {
serializedParams[i] = this.serializationService.toData(sqlStatement.params[i]);
}
} else {
serializedParams = [];
}
const cursorBufferSize = sqlStatement.options?.hasOwnProperty('cursorBufferSize') ?
sqlStatement.options.cursorBufferSize : SqlServiceImpl.DEFAULT_CURSOR_BUFFER_SIZE;
const returnRawResult = sqlStatement.options?.hasOwnProperty('returnRawResult') ?
sqlStatement.options.returnRawResult : SqlServiceImpl.DEFAULT_FOR_RETURN_RAW_RESULT;
const schema = sqlStatement.options?.hasOwnProperty('schema') ?
sqlStatement.options.schema : SqlServiceImpl.DEFAULT_SCHEMA;
const requestMessage = SqlExecuteCodec.encodeRequest(
sqlStatement.sql,
serializedParams,
timeoutMillis,
cursorBufferSize,
schema,
expectedResultType,
queryId,
false // Used to skip updating statistics from MC client, should be false in other clients
);
const res = SqlResultImpl.newResult(
this,
this.deserializeRowValue.bind(this),
connection,
queryId,
cursorBufferSize,
returnRawResult,
this.connectionManager.getClientUuid()
);
return this.invocationService.invokeOnConnection(connection, requestMessage).then(clientMessage => {
SqlServiceImpl.handleExecuteResponse(clientMessage, res);
return res;
}).catch(err => {
const error = this.rethrow(err, connection);
res.onExecuteError(error);
throw error;
});
} catch (error) {
throw this.rethrow(error, connection);
}
}
execute(sql: string, params?: any[], options?: SqlStatementOptions): Promise<SqlResult> {
const sqlStatement: SqlStatement = {
sql: sql
};
// If params is not provided it won't be validated. Default value for optional parameters is undefined.
// So, if they are undefined we don't set it, and in validator method we check for property existence.
if (params !== undefined) {
sqlStatement.params = params;
}
if (options !== undefined) {
sqlStatement.options = options;
}
return this.executeStatement(sqlStatement);
}
/**
* Sends a close request on a connection for an SQL result using its query id.
* @param connection The connection the request will be sent to
* @param queryId The query id that defines the SQL result
*/
close(connection: Connection, queryId: SqlQueryId): Promise<ClientMessage> {
const requestMessage = SqlCloseCodec.encodeRequest(queryId);
return this.invocationService.invokeOnConnection(connection, requestMessage);
}
/**
* Sends a fetch request on a connection for an SQL result using its query id.
* @param connection The connection the request will be sent to
* @param queryId The query id that defines the SQL result
* @param cursorBufferSize The cursor buffer size associated with SQL fetch request, i.e its page size
*/
fetch(connection: Connection, queryId: SqlQueryId, cursorBufferSize: number): Promise<SqlPage> {
const requestMessage = SqlFetchCodec.encodeRequest(queryId, cursorBufferSize);
return this.invocationService.invokeOnConnection(connection, requestMessage).then(clientMessage => {
const response = SqlFetchCodec.decodeResponse(clientMessage);
if (response.error !== null) {
throw new HazelcastSqlException(
response.error.originatingMemberId,
response.error.code,
response.error.message
);
}
return response.rowPage;
});
}
/**
* Used for lazy deserialization of row values.
* @param data The data to be deserialized.
* @param isRaw `true` if the row is raw, i.e an {@link SqlRowImpl}; `false` otherwise, i.e a regular JSON object. Used to log
* more information about lazy deserialization if row is a regular JSON object.
*/
private deserializeRowValue(data: Data, isRaw: boolean) : any {
try {
return this.serializationService.toObject(data);
} catch (e) {
let message = 'Failed to deserialize query result value.';
if (!isRaw) {
message += ' In order to partially deserialize SQL rows you can set `returnRawResult` option to `true`. Check '
+ 'out the "Lazy SQL Row Deserialization" section in the client\'s reference manual.';
}
message += ` Error: ${e.message}`;
throw this.toHazelcastSqlException(e, message);
}
}
} | the_stack |
import {Array1D, Array2D, Array4D, conv_util, Graph, Initializer, NDArrayInitializer, Tensor, util, VarianceScalingInitializer, ZerosInitializer} from 'deeplearn';
/**
* Classes that specify operation parameters, how they affect output shape,
* and methods for building the operations themselves. Any new ops to be added
* to the model builder UI should be added here.
*/
export type LayerName = 'Fully connected' | 'ReLU' | 'Convolution' |
'Max pool' | 'Reshape' | 'Flatten';
/**
* Creates a layer builder object.
*
* @param layerName The name of the layer to build.
* @param layerBuilderJson An optional LayerBuilder JSON object. This doesn't
* have the prototype methods on them as it comes from serialization. This
* method creates the object with the necessary prototype methods.
*/
export function getLayerBuilder(
layerName: LayerName, layerBuilderJson?: LayerBuilder): LayerBuilder {
let layerBuilder: LayerBuilder;
switch (layerName) {
case 'Fully connected':
layerBuilder = new FullyConnectedLayerBuilder();
break;
case 'ReLU':
layerBuilder = new ReLULayerBuilder();
break;
case 'Convolution':
layerBuilder = new Convolution2DLayerBuilder();
break;
case 'Max pool':
layerBuilder = new MaxPoolLayerBuilder();
break;
case 'Reshape':
layerBuilder = new ReshapeLayerBuilder();
break;
case 'Flatten':
layerBuilder = new FlattenLayerBuilder();
break;
default:
throw new Error('Layer builder for ' + layerName + ' not found.');
}
// For layer builders passed as serialized objects, we create the objects and
// set the fields.
if (layerBuilderJson != null) {
for (const prop in layerBuilderJson) {
if (layerBuilderJson.hasOwnProperty(prop)) {
// tslint:disable-next-line:no-any
(layerBuilder as any)[prop] = (layerBuilderJson as any)[prop];
}
}
}
return layerBuilder;
}
export interface LayerParam {
label: string;
initialValue(inputShape: number[]): number|string;
type: 'number'|'text';
min?: number;
max?: number;
setValue(value: number|string): void;
getValue(): number|string;
}
export type LayerWeightsDict = {
[name: string]: number[]
};
export interface LayerBuilder {
layerName: LayerName;
getLayerParams(): LayerParam[];
getOutputShape(inputShape: number[]): number[];
addLayer(
g: Graph, network: Tensor, inputShape: number[], index: number,
weights?: LayerWeightsDict|null): Tensor;
addLayerMultiple(
g: Graph, networks: Tensor[], inputShape: number[], name: string,
weights?: LayerWeightsDict|null): Tensor[];
// Return null if no errors, otherwise return an array of errors.
validate(inputShape: number[]): string[]|null;
}
export class FullyConnectedLayerBuilder implements LayerBuilder {
layerName: LayerName = 'Fully connected';
hiddenUnits: number;
getLayerParams(): LayerParam[] {
return [{
label: 'Hidden units',
initialValue: (inputShape: number[]) => 10,
type: 'number',
min: 1,
max: 1000,
setValue: (value: number) => this.hiddenUnits = value,
getValue: () => this.hiddenUnits
}];
}
getOutputShape(inputShape: number[]): number[] {
return [this.hiddenUnits];
}
addLayer(
g: Graph, network: Tensor, inputShape: number[], index: number,
weights: LayerWeightsDict|null): Tensor {
const inputSize = util.sizeFromShape(inputShape);
const wShape: [number, number] = [this.hiddenUnits, inputSize];
let weightsInitializer: Initializer;
let biasInitializer: Initializer;
if (weights != null) {
weightsInitializer =
new NDArrayInitializer(Array2D.new(wShape, weights['W']));
biasInitializer = new NDArrayInitializer(Array1D.new(weights['b']));
} else {
weightsInitializer = new VarianceScalingInitializer();
biasInitializer = new ZerosInitializer();
}
const useBias = true;
return g.layers.dense(
'fc1', network, this.hiddenUnits, null, useBias, weightsInitializer,
biasInitializer);
}
addLayerMultiple(
g: Graph, networks: Tensor[], inputShape: number[], name: string,
weights: LayerWeightsDict|null): Tensor[] {
const inputSize = util.sizeFromShape(inputShape);
const wShape: [number, number] = [inputSize, this.hiddenUnits];
let w: Array2D;
let b: Array1D;
if (weights != null) {
throw new Error;
} else {
w = Array2D.randTruncatedNormal(wShape, 0, 0.1);
b = Array1D.zeros([this.hiddenUnits]);
}
const wTensor = g.variable(name + '-weights', w);
const bTensor = g.variable(name + '-bias', b);
const returnedTensors = []
for (let i = 0; i < networks.length; i++) {
returnedTensors.push(
g.add(g.matmul(networks[i], wTensor), bTensor)
);
}
return returnedTensors;
}
validate(inputShape: number[]) {
if (inputShape.length !== 1) {
return ['Input shape must be a Array1D.'];
}
return null;
}
}
export class ReLULayerBuilder implements LayerBuilder {
layerName: LayerName = 'ReLU';
getLayerParams(): LayerParam[] {
return [];
}
getOutputShape(inputShape: number[]): number[] {
return inputShape;
}
addLayer(
g: Graph, network: Tensor, inputShape: number[], index: number,
weights: LayerWeightsDict|null): Tensor {
return g.relu(network);
}
addLayerMultiple(
g: Graph, networks: Tensor[], inputShape: number[], name: string,
weights: LayerWeightsDict|null): Tensor[] {
const returnedTensors = []
for (let i = 0; i < networks.length; i++) {
returnedTensors.push(g.relu(networks[i]));
}
return returnedTensors;
}
validate(inputShape: number[]): string[]|null {
return null;
}
}
export class Convolution2DLayerBuilder implements LayerBuilder {
layerName: LayerName = 'Convolution';
fieldSize: number;
stride: number;
zeroPad: number;
outputDepth: number;
getLayerParams(): LayerParam[] {
return [
{
label: 'Field size',
initialValue: (inputShape: number[]) => 3,
type: 'number',
min: 1,
max: 100,
setValue: (value: number) => this.fieldSize = value,
getValue: () => this.fieldSize
},
{
label: 'Stride',
initialValue: (inputShape: number[]) => 1,
type: 'number',
min: 1,
max: 100,
setValue: (value: number) => this.stride = value,
getValue: () => this.stride
},
{
label: 'Zero pad',
initialValue: (inputShape: number[]) => 0,
type: 'number',
min: 0,
max: 100,
setValue: (value: number) => this.zeroPad = value,
getValue: () => this.zeroPad
},
{
label: 'Output depth',
initialValue: (inputShape: number[]) =>
this.outputDepth != null ? this.outputDepth : 1,
type: 'number',
min: 1,
max: 1000,
setValue: (value: number) => this.outputDepth = value,
getValue: () => this.outputDepth
}
];
}
getOutputShape(inputShape: number[]): number[] {
return conv_util.computeOutputShape3D(
inputShape as [number, number, number], this.fieldSize,
this.outputDepth, this.stride, this.zeroPad);
}
addLayer(
g: Graph, network: Tensor, inputShape: number[], index: number,
weights: LayerWeightsDict|null): Tensor {
const wShape: [number, number, number, number] =
[this.fieldSize, this.fieldSize, inputShape[2], this.outputDepth];
let w: Array4D;
let b: Array1D;
if (weights != null) {
w = Array4D.new(wShape, weights['W']);
b = Array1D.new(weights['b']);
} else {
w = Array4D.randTruncatedNormal(wShape, 0, 0.1);
b = Array1D.zeros([this.outputDepth]);
}
const wTensor = g.variable('conv2d-' + index + '-w', w);
const bTensor = g.variable('conv2d-' + index + '-b', b);
return g.conv2d(
network, wTensor, bTensor, this.fieldSize, this.outputDepth,
this.stride, this.zeroPad);
}
addLayerMultiple(
g: Graph, networks: Tensor[], inputShape: number[], name: string,
weights: LayerWeightsDict|null): Tensor[] {
const wShape: [number, number, number, number] =
[this.fieldSize, this.fieldSize, inputShape[2], this.outputDepth];
let w: Array4D;
let b: Array1D;
if (weights != null) {
w = Array4D.new(wShape, weights['W']);
b = Array1D.new(weights['b']);
} else {
w = Array4D.randTruncatedNormal(wShape, 0, 0.1);
b = Array1D.zeros([this.outputDepth]);
}
const wTensor = g.variable(name + 'conv2d-w', w);
const bTensor = g.variable(name + 'conv2d-b', b);
const returnedTensors = []
for (let i = 0; i < networks.length; i++) {
returnedTensors.push(
g.conv2d(
networks[i], wTensor, bTensor, this.fieldSize,
this.outputDepth, this.stride, this.zeroPad)
);
}
return returnedTensors;
}
validate(inputShape: number[]) {
if (inputShape.length !== 3) {
return ['Input shape must be a Array3D.'];
}
return null;
}
}
export class MaxPoolLayerBuilder implements LayerBuilder {
layerName: LayerName = 'Max pool';
fieldSize: number;
stride: number;
zeroPad: number;
getLayerParams(): LayerParam[] {
return [
{
label: 'Field size',
initialValue: (inputShape: number[]) => 3,
type: 'number',
min: 1,
max: 100,
setValue: (value: number) => this.fieldSize = value,
getValue: () => this.fieldSize
},
{
label: 'Stride',
initialValue: (inputShape: number[]) => 1,
type: 'number',
min: 1,
max: 100,
setValue: (value: number) => this.stride = value,
getValue: () => this.stride
},
{
label: 'Zero pad',
initialValue: (inputShape: number[]) => 0,
type: 'number',
min: 0,
max: 100,
setValue: (value: number) => this.zeroPad = value,
getValue: () => this.zeroPad
}
];
}
getOutputShape(inputShape: number[]): number[] {
return conv_util.computeOutputShape3D(
inputShape as [number, number, number], this.fieldSize, inputShape[2],
this.stride, this.zeroPad);
}
addLayer(
g: Graph, network: Tensor, inputShape: number[], index: number,
weights: LayerWeightsDict|null): Tensor {
return g.maxPool(network, this.fieldSize, this.stride, this.zeroPad);
}
addLayerMultiple(
g: Graph, networks: Tensor[], inputShape: number[], name: string,
weights: LayerWeightsDict|null): Tensor[] {
const returnedTensors = []
for (let i = 0; i < networks.length; i++) {
returnedTensors.push(g.maxPool(networks[i], this.fieldSize,
this.stride, this.zeroPad));
}
return returnedTensors;
}
validate(inputShape: number[]) {
if (inputShape.length !== 3) {
return ['Input shape must be a Array3D.'];
}
return null;
}
}
export class ReshapeLayerBuilder implements LayerBuilder {
layerName: LayerName = 'Reshape';
outputShape: number[];
getLayerParams() {
return [{
label: 'Shape (comma separated)',
initialValue: (inputShape: number[]) => inputShape.join(', '),
type: 'text' as 'text',
setValue: (value: string) => this.outputShape =
value.split(',').map((value) => +value),
getValue: () => this.outputShape.join(', ')
}];
}
getOutputShape(inputShape: number[]): number[] {
return this.outputShape;
}
addLayer(
g: Graph, network: Tensor, inputShape: number[], index: number,
weights: LayerWeightsDict|null): Tensor {
return g.reshape(network, this.outputShape);
}
addLayerMultiple(
g: Graph, networks: Tensor[], inputShape: number[], name: string,
weights: LayerWeightsDict|null): Tensor[] {
const returnedTensors = []
for (let i = 0; i < networks.length; i++) {
returnedTensors.push(g.reshape(networks[i], this.outputShape));
}
return returnedTensors;
}
validate(inputShape: number[]) {
const inputSize = util.sizeFromShape(inputShape);
const outputSize = util.sizeFromShape(this.outputShape);
if (inputSize !== outputSize) {
return [
`Input size (${inputSize}) must match output size (${outputSize}).`
];
}
return null;
}
}
export class FlattenLayerBuilder implements LayerBuilder {
layerName: LayerName = 'Flatten';
getLayerParams(): LayerParam[] {
return [];
}
getOutputShape(inputShape: number[]): number[] {
return [util.sizeFromShape(inputShape)];
}
addLayer(
g: Graph, network: Tensor, inputShape: number[], index: number,
weights: LayerWeightsDict|null): Tensor {
return g.reshape(network, this.getOutputShape(inputShape));
}
addLayerMultiple(
g: Graph, networks: Tensor[], inputShape: number[], name: string,
weights: LayerWeightsDict|null): Tensor[] {
const returnedTensors = []
for (let i = 0; i < networks.length; i++) {
returnedTensors.push(g.reshape(networks[i],
this.getOutputShape(inputShape)));
}
return returnedTensors;
}
validate(inputShape: number[]): string[]|null {
return null;
}
} | the_stack |
import type { AstNode } from '../node/index.js'
import { SequenceUtil, SequenceUtilDiscriminator } from '../node/index.js'
import type { ParserContext } from '../service/index.js'
import { ErrorReporter } from '../service/index.js'
import type { ErrorSeverity, ReadonlySource, Source } from '../source/index.js'
import { Range } from '../source/index.js'
import type { InfallibleParser, Parser, Result, Returnable } from './Parser.js'
import { Failure } from './Parser.js'
type ExtractNodeType<P extends Parser<Returnable>> = P extends Parser<infer V> ? V : never
/**
* @template PA Parser array.
*/
type ExtractNodeTypes<PA extends Parser<Returnable>[]> = ExtractNodeType<PA[number]>
export interface AttemptResult<N extends Returnable = AstNode> {
result: Result<N>,
updateSrcAndCtx: () => void,
endCursor: number,
errorAmount: number,
}
interface InfallibleAttemptResult<N extends Returnable = AstNode> extends AttemptResult<N> {
result: N,
}
/**
* Attempts to parse using the given `parser`.
* @returns
* - `result`: The result returned by the `parser`.
* - `updateSrcAndCtx`: A function that will update the passed-in `src` and `ctx` to the state where `parser` has been executed.
* - `endCursor`: The offset where the `parser` stopped parsing.
* - `errorAmount`: The amount of errors created by the `parser`.
*/
export function attempt<N extends Returnable = AstNode>(parser: InfallibleParser<N>, src: Source, ctx: ParserContext): InfallibleAttemptResult<N>
export function attempt<N extends Returnable = AstNode>(parser: Parser<N>, src: Source, ctx: ParserContext): AttemptResult<N>
export function attempt<N extends Returnable = AstNode>(parser: Parser<N>, src: Source, ctx: ParserContext): AttemptResult<N> {
const tmpSrc = src.clone()
const tmpCtx = {
...ctx,
err: new ErrorReporter(),
}
const result = parser(tmpSrc, tmpCtx)
return {
result,
endCursor: tmpSrc.cursor,
errorAmount: tmpCtx.err.errors.length,
updateSrcAndCtx: () => {
src.innerCursor = tmpSrc.innerCursor
ctx.err.absorb(tmpCtx.err)
},
}
}
type SP<CN extends AstNode> = SIP<CN> | Parser<CN | SequenceUtil<CN> | undefined> | { get: (result: SequenceUtil<CN>) => Parser<CN | SequenceUtil<CN> | undefined> | undefined }
type SIP<CN extends AstNode> = InfallibleParser<CN | SequenceUtil<CN> | undefined> | { get: (result: SequenceUtil<CN>) => InfallibleParser<CN | SequenceUtil<CN> | undefined> | undefined }
/**
* @template GN Gap node.
* @template PA Parser array.
*
* @param parseGap A parser that parses gaps between nodes in the sequence.
*
* @returns A parser that takes a sequence built with the passed-in parsers.
*
* `Failure` when any of the `parsers` returns a `Failure`.
*/
export function sequence<GN extends AstNode = never, PA extends SIP<AstNode>[] = SIP<AstNode>[]>(parsers: PA, parseGap?: InfallibleParser<GN[]>): InfallibleParser<SequenceUtil<GN | { [K in number]: PA[K] extends SP<infer V> ? V : never }[number]>>
export function sequence<GN extends AstNode = never, PA extends SP<AstNode>[] = SP<AstNode>[]>(parsers: PA, parseGap?: InfallibleParser<GN[]>): Parser<SequenceUtil<GN | { [K in number]: PA[K] extends SP<infer V> ? V : never }[number]>>
export function sequence(parsers: SP<AstNode>[], parseGap?: InfallibleParser<AstNode[]>): Parser<SequenceUtil<AstNode>> {
return (src: Source, ctx: ParserContext): Result<SequenceUtil<AstNode>> => {
const ans: SequenceUtil<AstNode> = {
[SequenceUtilDiscriminator]: true,
children: [],
range: Range.create(src),
}
for (const [i, p] of parsers.entries()) {
const parser = typeof p === 'function' ? p : p.get(ans)
if (parser === undefined) {
continue
}
if (i > 0 && parseGap) {
ans.children.push(...parseGap(src, ctx))
}
const result = parser(src, ctx)
if (result === Failure) {
return Failure
} else if (result === undefined) {
continue
} else if (SequenceUtil.is(result)) {
ans.children.push(...result.children)
} else {
ans.children.push(result)
}
}
ans.range.end = src.cursor
return ans
}
}
/**
* @template CN Child node.
*
* @param parser Must be fallible, as an infallible parser being repeated will result in an infinite loop.
* @param parseGap A parser that parses gaps between nodes in the sequence.
*
* @returns A parser that takes a sequence with the passed-in parser being repeated zero or more times.
*/
export function repeat<CN extends AstNode>(parser: InfallibleParser<CN | SequenceUtil<CN>>, parseGap?: InfallibleParser<CN[]>): { _inputParserIsInfallible: never } & void
export function repeat<CN extends AstNode>(parser: Parser<CN | SequenceUtil<CN>>, parseGap?: InfallibleParser<CN[]>): InfallibleParser<SequenceUtil<CN>>
export function repeat<CN extends AstNode>(parser: Parser<CN | SequenceUtil<CN>>, parseGap?: InfallibleParser<CN[]>): InfallibleParser<SequenceUtil<CN>> | void {
return (src: Source, ctx: ParserContext): SequenceUtil<CN> => {
const ans: SequenceUtil<CN> = {
[SequenceUtilDiscriminator]: true,
children: [],
range: Range.create(src),
}
while (src.canRead()) {
if (parseGap) {
ans.children.push(...parseGap(src, ctx))
}
const { result, updateSrcAndCtx } = attempt(parser, src, ctx)
if (result === Failure) {
break
}
updateSrcAndCtx()
if (SequenceUtil.is(result)) {
ans.children.push(...result.children)
} else {
ans.children.push(result)
}
}
ans.range.end = src.cursor
return ans
}
}
export interface AnyOutObject {
/**
* The index of the parser in the provided `parsers` array that was ultimately taken. `-1` if all parsers failed.
*/
index: number,
}
/**
* @param out An optional object that will be modified with additional information if provided.
*
* @returns A parser that returns the result of the passed-in parser which produces the least amount of error.
* If there are more than one `parsers` produced the same amount of errors, it then takes the parser that went the furthest in `Source`.
* If there is still a tie, it takes the one closer to the beginning of the `parsers` array.
*
* `Failure` when all of the `parsers` failed.
*/
export function any<PA extends [...Parser<Returnable>[], InfallibleParser<Returnable>]>(parsers: PA, out?: AnyOutObject): InfallibleParser<ExtractNodeTypes<PA>>
export function any<PA extends Parser<Returnable>[]>(parsers: PA, out?: AnyOutObject): Parser<ExtractNodeTypes<PA>>
export function any(parsers: Parser<Returnable>[], out?: AnyOutObject): Parser<Returnable> {
return (src: Source, ctx: ParserContext): Result<Returnable> => {
const results: { attempt: AttemptResult<Returnable>, index: number }[] = parsers
.map((parser, i) => ({ attempt: attempt(parser, src, ctx), index: i }))
.filter(({ attempt }) => attempt.result !== Failure)
.sort((a, b) => (b.attempt.endCursor - a.attempt.endCursor) || (a.attempt.errorAmount - b.attempt.errorAmount))
if (results.length === 0) {
if (out) {
out.index = -1
}
return Failure
}
results[0].attempt.updateSrcAndCtx()
if (out) {
out.index = results[0].index
}
return results[0].attempt.result
}
}
/**
* @returns A parser that fails when the passed-in parser didn't move the cursor at all.
*/
export function failOnEmpty<T extends Returnable>(parser: Parser<T>): Parser<T> {
return (src, ctx) => {
const start = src.cursor
const { endCursor, updateSrcAndCtx, result } = attempt(parser, src, ctx)
if (endCursor - start > 0) {
updateSrcAndCtx()
return result
}
return Failure
}
}
/**
* @returns A parser that fails when the passed-in parser produced any errors.
*/
export function failOnError<T extends Returnable>(parser: Parser<T>): Parser<T> {
return (src, ctx) => {
const start = src.cursor
const { errorAmount, updateSrcAndCtx, result } = attempt(parser, src, ctx)
if (!errorAmount) {
updateSrcAndCtx()
return result
}
return Failure
}
}
/**
* @returns A parser that takes an optional syntax component.
*/
export function optional<N extends Returnable>(parser: InfallibleParser<N>): { _inputParserIsInfallible: never } & void
export function optional<N extends Returnable>(parser: Parser<N>): InfallibleParser<N | undefined>
export function optional<N extends Returnable>(parser: Parser<N>): InfallibleParser<N | undefined> | void {
return ((src: Source, ctx: ParserContext): N | undefined => {
const { result, updateSrcAndCtx } = attempt(parser, src, ctx)
if (result === Failure) {
return undefined
} else {
updateSrcAndCtx()
return result
}
}) as never
}
/**
* @param parser Must be fallible.
*
* @returns A parser that returns the return value of the `parser`, or the return value of `defaultValue` it it's a `Failure`.
*/
export function recover<N extends Returnable>(parser: InfallibleParser<N>, defaultValue: (src: Source, ctx: ParserContext) => N): { _inputParserIsInfallible: never } & void
export function recover<N extends Returnable>(parser: Parser<N>, defaultValue: (src: Source, ctx: ParserContext) => N): InfallibleParser<N>
export function recover<N extends Returnable>(parser: Parser<N>, defaultValue: (src: Source, ctx: ParserContext) => N): InfallibleParser<N> | void {
return (src: Source, ctx: ParserContext): N => {
const result = parser(src, ctx)
if (result === Failure) {
const ans = defaultValue(src, ctx)
return ans
}
return result
}
}
type GettableParser = Parser<Returnable> | { get: () => Parser<Returnable> }
type ExtractFromGettableParser<T extends GettableParser> = T extends { get: () => infer V }
? V
: T extends Parser<Returnable> ? T : never
type Case = { predicate?: (this: void, src: ReadonlySource) => boolean, prefix?: string, parser: GettableParser }
/**
* @template CA Case array.
*/
export function select<CA extends readonly Case[]>(cases: CA): ExtractFromGettableParser<CA[number]['parser']> extends InfallibleParser<Returnable>
? InfallibleParser<ExtractNodeType<ExtractFromGettableParser<CA[number]['parser']>>>
: Parser<ExtractNodeType<ExtractFromGettableParser<CA[number]['parser']>>>
export function select(cases: readonly Case[]): Parser<Returnable> {
return (src: Source, ctx: ParserContext): Result<Returnable> => {
for (const { predicate, prefix, parser } of cases) {
if (predicate?.(src) ?? (prefix !== undefined ? src.tryPeek(prefix) : undefined) ?? true) {
const callableParser = typeof parser === 'object' ? parser.get() : parser
return callableParser(src, ctx)
}
}
throw new Error('The select parser util was called with non-exhaustive cases')
}
}
/**
* @returns A parser that returns the return value of `fn`.
*
* `Failure` when the `parser` returns a `Failure`.
*/
export function map<NA extends Returnable, NB extends Returnable = NA>(parser: InfallibleParser<NA>, fn: (res: NA, src: Source, ctx: ParserContext) => NB): InfallibleParser<NB>
export function map<NA extends Returnable, NB extends Returnable = NA>(parser: Parser<NA>, fn: (res: NA, src: Source, ctx: ParserContext) => NB): Parser<NB>
export function map<NA extends Returnable, NB extends Returnable = NA>(parser: Parser<NA>, fn: (res: NA, src: Source, ctx: ParserContext) => NB): Parser<NB> {
return (src: Source, ctx: ParserContext): Result<NB> => {
const result = parser(src, ctx)
if (result === Failure) {
return Failure
}
const ans = fn(result, src, ctx)
return ans
}
}
export function setType<N extends Omit<AstNode, 'type'>, T extends string>(type: T, parser: InfallibleParser<N>): InfallibleParser<Omit<N, 'type'> & { type: T }>
export function setType<N extends Omit<AstNode, 'type'>, T extends string>(type: T, parser: Parser<N>): Parser<Omit<N, 'type'> & { type: T }>
export function setType<N extends Omit<AstNode, 'type'>, T extends string>(type: T, parser: Parser<N>): Parser<Omit<N, 'type'> & { type: T }> {
return map(
parser,
res => {
const { type: _type, ...restResult } = res as N & { type: never }
const ans = {
type,
...restResult,
}
delete (ans as Partial<SequenceUtil>)[SequenceUtilDiscriminator]
return ans
}
)
}
/**
* Checks if the result of `parser` is valid, and reports an error if it's not.
*
* `Failure` when the `parser` returns a `Failure`.
*/
export function validate<N extends AstNode>(parser: InfallibleParser<N>, validator: (res: N, src: Source, ctx: ParserContext) => boolean, message: string, severity?: ErrorSeverity): InfallibleParser<N>
export function validate<N extends AstNode>(parser: Parser<N>, validator: (res: N, src: Source, ctx: ParserContext) => boolean, message: string, severity?: ErrorSeverity): Parser<N>
export function validate<N extends AstNode>(parser: Parser<N>, validator: (res: N, src: Source, ctx: ParserContext) => boolean, message: string, severity?: ErrorSeverity): Parser<N> {
return map(
parser,
(res, src, ctx) => {
const isLegal = validator(res, src, ctx)
if (!isLegal) {
ctx.err.report(message, res.range, severity)
}
return res
}
)
}
/**
* @returns A parser that is based on the passed-in `parser`, but will never read to any of the terminator strings.
*/
export function stopBefore<N extends Returnable>(parser: InfallibleParser<N>, ...teminators: (string | readonly string[])[]): InfallibleParser<N>
export function stopBefore<N extends Returnable>(parser: Parser<N>, ...teminators: (string | readonly string[])[]): Parser<N>
export function stopBefore<N extends Returnable>(parser: Parser<N>, ...teminators: (string | readonly string[])[]): Parser<N> {
const flatTerminators = teminators.flat()
return (src, ctx): Result<N> => {
const tmpSrc = src.clone()
// Cut tmpSrc.string before the nearest terminator.
tmpSrc.string = tmpSrc.string.slice(0, flatTerminators.reduce((p, c) => {
const index = tmpSrc.string.indexOf(c, tmpSrc.innerCursor)
return Math.min(p, index === -1 ? Infinity : index)
}, Infinity))
const ans = parser(tmpSrc, ctx)
src.cursor = tmpSrc.cursor
return ans
}
}
/**
* @returns A parser that is based on the passed-in `parser`, but will only read the acceptable characters.
*/
export function acceptOnly<N extends Returnable>(parser: InfallibleParser<N>, ...characters: (string | readonly string[])[]): InfallibleParser<N>
export function acceptOnly<N extends Returnable>(parser: Parser<N>, ...characters: (string | readonly string[])[]): Parser<N>
export function acceptOnly<N extends Returnable>(parser: Parser<N>, ...characters: (string | readonly string[])[]): Parser<N> {
const set = new Set(characters.flat())
return (src, ctx): Result<N> => {
const tmpSrc = src.clone()
// Cut tmpSrc.string before the nearest unacceptable character.
for (let i = tmpSrc.innerCursor; i < tmpSrc.string.length; i++) {
if (!set.has(tmpSrc.string.charAt(i))) {
tmpSrc.string = tmpSrc.string.slice(0, i)
break
}
}
const ans = parser(tmpSrc, ctx)
src.cursor = tmpSrc.cursor
return ans
}
}
export function acceptIf<P extends Parser<AstNode>>(parser: P, predicate: (this: void, char: string) => boolean): P extends InfallibleParser<infer N>
? InfallibleParser<N>
: P extends Parser<infer N> ? Parser<N> : never {
return ((src: Source, ctx: ParserContext) => {
const tmpSrc = src.clone()
// Cut tmpSrc.string before the nearest unacceptable character.
for (let i = tmpSrc.innerCursor; i < tmpSrc.string.length; i++) {
if (!predicate(tmpSrc.string.charAt(i))) {
tmpSrc.string = tmpSrc.string.slice(0, i)
break
}
}
const ans = parser(tmpSrc, ctx)
src.innerCursor = tmpSrc.innerCursor
return ans
}) as ReturnType<typeof acceptIf<P>>
} | the_stack |
* @module Compatibility
*/
import { ProcessDetector } from "@itwin/core-bentley";
import {
GraphicsDriverBugs, WebGLContext, WebGLFeature, WebGLRenderCompatibilityInfo, WebGLRenderCompatibilityStatus,
} from "./RenderCompatibility";
/** @internal */
export type WebGLExtensionName =
"WEBGL_draw_buffers" | "OES_element_index_uint" | "OES_texture_float" | "OES_texture_float_linear" |
"OES_texture_half_float" | "OES_texture_half_float_linear" | "EXT_texture_filter_anisotropic" | "WEBGL_depth_texture" |
"EXT_color_buffer_float" | "EXT_shader_texture_lod" | "ANGLE_instanced_arrays" | "OES_vertex_array_object" | "WEBGL_lose_context" |
"EXT_frag_depth" | "EXT_disjoint_timer_query" | "EXT_disjoint_timer_query_webgl2" | "OES_standard_derivatives" | "EXT_float_blend";
const knownExtensions: WebGLExtensionName[] = [
"WEBGL_draw_buffers",
"OES_element_index_uint",
"OES_texture_float",
"OES_texture_float_linear",
"OES_texture_half_float",
"OES_texture_half_float_linear",
"EXT_texture_filter_anisotropic",
"WEBGL_depth_texture",
"EXT_color_buffer_float",
"EXT_shader_texture_lod",
"EXT_frag_depth",
"ANGLE_instanced_arrays",
"OES_vertex_array_object",
"WEBGL_lose_context",
"EXT_disjoint_timer_query",
"EXT_disjoint_timer_query_webgl2",
"OES_standard_derivatives",
"EXT_float_blend",
];
/** Describes the type of a render target. Used by Capabilities to represent maximum precision render target available on host system.
* @internal
*/
export enum RenderType {
TextureUnsignedByte,
TextureHalfFloat,
TextureFloat,
}
/**
* Describes the type of a depth buffer. Used by Capabilities to represent maximum depth buffer precision available on host system.
* Note: the commented-out values are unimplemented but left in place for reference, in case desired for future implementation.
* @internal
*/
export enum DepthType {
RenderBufferUnsignedShort16, // core to WebGL1
// TextureUnsignedShort16, // core to WebGL2; available to WebGL1 via WEBGL_depth_texture
// TextureUnsignedInt24, // core to WebGL2
TextureUnsignedInt24Stencil8, // core to WebGL2; available to WebGL1 via WEBGL_depth_texture
TextureUnsignedInt32, // core to WebGL2; available to WebGL1 via WEBGL_depth_texture
// TextureFloat32, // core to WebGL2
// TextureFloat32Stencil8, // core to WeBGL2
}
const maxTexSizeAllowed = 4096; // many devices and browsers have issues with source textures larger than this
// Regexes to match Intel UHD/HD 620/630 integrated GPUS that suffer from GraphicsDriverBugs.fragDepthDoesNotDisableEarlyZ.
const buggyIntelMatchers = [
// Original unmasked renderer string when workaround we implemented.
/ANGLE \(Intel\(R\) (U)?HD Graphics 6(2|3)0 Direct3D11/,
// New unmasked renderer string circa October 2021.
/ANGLE \(Intel, Intel\(R\) (U)?HD Graphics 6(2|3)0 Direct3D11/,
];
// Regexes to match Mali GPUs known to suffer from GraphicsDriverBugs.msaaWillHang.
const buggyMaliMatchers = [
/Mali-G71/,
/Mali-G76/,
];
// Regexes to match as many Intel integrated GPUs as possible.
// https://en.wikipedia.org/wiki/List_of_Intel_graphics_processing_units
const integratedIntelGpuMatchers = [
/(U)?HD Graphics/,
/Iris/,
];
function isIntegratedGraphics(args: {unmaskedVendor?: string, unmaskedRenderer?: string}): boolean {
if (args.unmaskedRenderer && args.unmaskedRenderer.includes("Intel") && integratedIntelGpuMatchers.some((x) => x.test(args.unmaskedRenderer!)))
return true;
// NB: For now, we do not attempt to detect AMD integrated graphics.
// It appears that AMD integrated graphics are not usually paired with a graphics card so detecting integrated usage there is less important than Intel.
return false;
}
/** Describes the rendering capabilities of the host system.
* @internal
*/
export class Capabilities {
private _maxRenderType: RenderType = RenderType.TextureUnsignedByte;
private _maxDepthType: DepthType = DepthType.RenderBufferUnsignedShort16;
private _maxTextureSize: number = 0;
private _maxColorAttachments: number = 0;
private _maxDrawBuffers: number = 0;
private _maxFragTextureUnits: number = 0;
private _maxVertTextureUnits: number = 0;
private _maxVertAttribs: number = 0;
private _maxVertUniformVectors: number = 0;
private _maxVaryingVectors: number = 0;
private _maxFragUniformVectors: number = 0;
private _canRenderDepthWithoutColor: boolean = false;
private _maxAnisotropy?: number;
private _maxAntialiasSamples: number = 1;
private _supportsCreateImageBitmap: boolean = false;
private _maxTexSizeAllow: number = maxTexSizeAllowed;
private _extensionMap: { [key: string]: any } = {}; // Use this map to store actual extension objects retrieved from GL.
private _presentFeatures: WebGLFeature[] = []; // List of features the system can support (not necessarily dependent on extensions)
private _isWebGL2: boolean = false;
private _isMobile: boolean = false;
private _driverBugs: GraphicsDriverBugs = {};
public get maxRenderType(): RenderType { return this._maxRenderType; }
public get maxDepthType(): DepthType { return this._maxDepthType; }
public get maxTextureSize(): number { return this._maxTextureSize; }
public get maxTexSizeAllow(): number { return this._maxTexSizeAllow; }
public get supportsCreateImageBitmap(): boolean { return this._supportsCreateImageBitmap; }
public get maxColorAttachments(): number { return this._maxColorAttachments; }
public get maxDrawBuffers(): number { return this._maxDrawBuffers; }
public get maxFragTextureUnits(): number { return this._maxFragTextureUnits; }
public get maxVertTextureUnits(): number { return this._maxVertTextureUnits; }
public get maxVertAttribs(): number { return this._maxVertAttribs; }
public get maxVertUniformVectors(): number { return this._maxVertUniformVectors; }
public get maxVaryingVectors(): number { return this._maxVaryingVectors; }
public get maxFragUniformVectors(): number { return this._maxFragUniformVectors; }
public get maxAntialiasSamples(): number { return this._maxAntialiasSamples; }
public get isWebGL2(): boolean { return this._isWebGL2; }
public get driverBugs(): GraphicsDriverBugs { return this._driverBugs; }
/** These getters check for existence of extension objects to determine availability of features. In WebGL2, could just return true for some. */
public get supportsNonPowerOf2Textures(): boolean { return false; }
public get supportsDrawBuffers(): boolean { return this._isWebGL2 || this.queryExtensionObject<WEBGL_draw_buffers>("WEBGL_draw_buffers") !== undefined; }
public get supportsInstancing(): boolean { return this._isWebGL2 || this.queryExtensionObject<ANGLE_instanced_arrays>("ANGLE_instanced_arrays") !== undefined; }
public get supports32BitElementIndex(): boolean { return this._isWebGL2 || this.queryExtensionObject<OES_element_index_uint>("OES_element_index_uint") !== undefined; }
public get supportsTextureFloat(): boolean { return this._isWebGL2 || this.queryExtensionObject<OES_texture_float>("OES_texture_float") !== undefined; }
public get supportsTextureFloatLinear(): boolean { return this._isWebGL2 || this.queryExtensionObject<OES_texture_float_linear>("OES_texture_float_linear") !== undefined; }
public get supportsTextureHalfFloat(): boolean { return this._isWebGL2 || this.queryExtensionObject<OES_texture_half_float>("OES_texture_half_float") !== undefined; }
public get supportsTextureHalfFloatLinear(): boolean { return this._isWebGL2 || this.queryExtensionObject<OES_texture_half_float_linear>("OES_texture_half_float_linear") !== undefined; }
public get supportsTextureFilterAnisotropic(): boolean { return this.queryExtensionObject<EXT_texture_filter_anisotropic>("EXT_texture_filter_anisotropic") !== undefined; }
public get supportsShaderTextureLOD(): boolean { return this._isWebGL2 || this.queryExtensionObject<EXT_shader_texture_lod>("EXT_shader_texture_lod") !== undefined; }
public get supportsVertexArrayObjects(): boolean { return this._isWebGL2 || this.queryExtensionObject<OES_vertex_array_object>("OES_vertex_array_object") !== undefined; }
public get supportsFragDepth(): boolean { return this._isWebGL2 || this.queryExtensionObject<EXT_frag_depth>("EXT_frag_depth") !== undefined; }
public get supportsDisjointTimerQuery(): boolean { return (this._isWebGL2 && this.queryExtensionObject<any>("EXT_disjoint_timer_query_webgl2") !== undefined) || this.queryExtensionObject<any>("EXT_disjoint_timer_query") !== undefined; }
public get supportsStandardDerivatives(): boolean { return this._isWebGL2 || this.queryExtensionObject<OES_standard_derivatives>("OES_standard_derivatives") !== undefined; }
public get supportsMRTTransparency(): boolean { return this.maxColorAttachments >= 2; }
public get supportsMRTPickShaders(): boolean { return this.maxColorAttachments >= 3; }
public get canRenderDepthWithoutColor(): boolean { return this._canRenderDepthWithoutColor; }
public get supportsShadowMaps(): boolean {
return this.supportsTextureFloat || this.supportsTextureHalfFloat;
}
public get supportsAntiAliasing(): boolean { return this._isWebGL2 && this.maxAntialiasSamples > 1; }
public get isMobile(): boolean { return this._isMobile; }
private findExtension(name: WebGLExtensionName): any {
const ext = this._extensionMap[name];
return null !== ext ? ext : undefined;
}
/** Queries an extension object if available. This is necessary for other parts of the system to access some constants within extensions. */
public queryExtensionObject<T>(ext: WebGLExtensionName): T | undefined {
return this.findExtension(ext) as T;
}
public static readonly optionalFeatures: WebGLFeature[] = [
WebGLFeature.MrtTransparency,
WebGLFeature.MrtPick,
WebGLFeature.DepthTexture,
WebGLFeature.FloatRendering,
WebGLFeature.Instancing,
WebGLFeature.ShadowMaps,
WebGLFeature.FragDepth,
WebGLFeature.StandardDerivatives,
WebGLFeature.AntiAliasing,
];
public static readonly requiredFeatures: WebGLFeature[] = [
WebGLFeature.UintElementIndex,
WebGLFeature.MinimalTextureUnits,
];
private get _hasRequiredTextureUnits(): boolean { return this.maxFragTextureUnits >= 4 && this.maxVertTextureUnits >= 5; }
/** Return an array containing any features not supported by the system as compared to the input array. */
private _findMissingFeatures(featuresToSeek: WebGLFeature[]): WebGLFeature[] {
const missingFeatures: WebGLFeature[] = [];
for (const featureName of featuresToSeek) {
if (-1 === this._presentFeatures.indexOf(featureName))
missingFeatures.push(featureName);
}
return missingFeatures;
}
/** Populate and return an array containing features that this system supports. */
private _gatherFeatures(): WebGLFeature[] {
const features: WebGLFeature[] = [];
// simply check for presence of various extensions if that gives enough information
if (this._isWebGL2 || this._extensionMap["OES_element_index_uint" as WebGLExtensionName] !== undefined)
features.push(WebGLFeature.UintElementIndex);
if (this._isWebGL2 || this._extensionMap["ANGLE_instanced_arrays" as WebGLExtensionName] !== undefined)
features.push(WebGLFeature.Instancing);
if (this.supportsMRTTransparency)
features.push(WebGLFeature.MrtTransparency);
if (this.supportsMRTPickShaders)
features.push(WebGLFeature.MrtPick);
if (this.supportsShadowMaps)
features.push(WebGLFeature.ShadowMaps);
if (this._hasRequiredTextureUnits)
features.push(WebGLFeature.MinimalTextureUnits);
if (this.supportsFragDepth)
features.push(WebGLFeature.FragDepth);
if (this.supportsStandardDerivatives)
features.push(WebGLFeature.StandardDerivatives);
if (this.supportsAntiAliasing)
features.push(WebGLFeature.AntiAliasing);
if (DepthType.TextureUnsignedInt24Stencil8 === this._maxDepthType)
features.push(WebGLFeature.DepthTexture);
// check if at least half-float rendering is available based on maximum discovered renderable target
if (RenderType.TextureUnsignedByte !== this._maxRenderType)
features.push(WebGLFeature.FloatRendering);
return features;
}
/** Retrieve compatibility status based on presence of various features. */
private _getCompatibilityStatus(missingRequiredFeatures: WebGLFeature[], missingOptionalFeatures: WebGLFeature[]): WebGLRenderCompatibilityStatus {
let status: WebGLRenderCompatibilityStatus = WebGLRenderCompatibilityStatus.AllOkay;
if (missingOptionalFeatures.length > 0)
status = WebGLRenderCompatibilityStatus.MissingOptionalFeatures;
if (missingRequiredFeatures.length > 0)
status = WebGLRenderCompatibilityStatus.MissingRequiredFeatures;
return status;
}
/** Initializes the capabilities based on a GL context. Must be called first. */
public init(gl: WebGLContext, disabledExtensions?: WebGLExtensionName[]): WebGLRenderCompatibilityInfo {
const gl2 = !(gl instanceof WebGLRenderingContext) ? gl : undefined;
this._isWebGL2 = undefined !== gl2;
this._isMobile = ProcessDetector.isMobileBrowser;
const debugInfo = gl.getExtension("WEBGL_debug_renderer_info");
const unmaskedRenderer = debugInfo !== null ? gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) : undefined;
const unmaskedVendor = debugInfo !== null ? gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL) : undefined;
this._driverBugs = {};
if (unmaskedRenderer && buggyIntelMatchers.some((x) => x.test(unmaskedRenderer)))
this._driverBugs.fragDepthDoesNotDisableEarlyZ = true;
if (unmaskedRenderer && buggyMaliMatchers.some((x) => x.test(unmaskedRenderer)))
this._driverBugs.msaaWillHang = true;
this._maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
this._supportsCreateImageBitmap = typeof createImageBitmap === "function" && ProcessDetector.isChromium && !ProcessDetector.isIOSBrowser;
this._maxTexSizeAllow = Math.min(this._maxTextureSize, maxTexSizeAllowed);
this._maxFragTextureUnits = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
this._maxVertTextureUnits = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
this._maxVertAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
this._maxVertUniformVectors = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
this._maxVaryingVectors = gl.getParameter(gl.MAX_VARYING_VECTORS);
this._maxFragUniformVectors = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
this._maxAntialiasSamples = this._driverBugs.msaaWillHang ? 1 : (this._isWebGL2 && undefined !== gl2 ? gl.getParameter(gl2.MAX_SAMPLES) : 1);
const extensions = gl.getSupportedExtensions(); // This just retrieves a list of available extensions (not necessarily enabled).
if (extensions) {
for (const extStr of extensions) {
const ext = extStr as WebGLExtensionName;
if (-1 === knownExtensions.indexOf(ext))
continue;
else if (undefined !== disabledExtensions && -1 !== disabledExtensions.indexOf(ext))
continue;
const extObj: any = gl.getExtension(ext); // This call enables the extension and returns a WebGLObject containing extension instance.
if (null !== extObj)
this._extensionMap[ext] = extObj;
}
}
if (this._isWebGL2 && undefined !== gl2) {
this._maxColorAttachments = gl.getParameter(gl2.MAX_COLOR_ATTACHMENTS);
this._maxDrawBuffers = gl.getParameter(gl2.MAX_DRAW_BUFFERS);
} else {
const dbExt: WEBGL_draw_buffers | undefined = this.queryExtensionObject<WEBGL_draw_buffers>("WEBGL_draw_buffers");
this._maxColorAttachments = dbExt !== undefined ? gl.getParameter(dbExt.MAX_COLOR_ATTACHMENTS_WEBGL) : 1;
this._maxDrawBuffers = dbExt !== undefined ? gl.getParameter(dbExt.MAX_DRAW_BUFFERS_WEBGL) : 1;
}
// Determine the maximum color-renderable attachment type.
const allowFloatRender =
(undefined === disabledExtensions || -1 === disabledExtensions.indexOf("OES_texture_float"))
// iOS>=15 allows full-float rendering. However, it does not actually work on non-M1 devices.
// Because of this, for now we disallow full float rendering on iOS devices.
// ###TODO: Re-assess this after future iOS updates.
&& !ProcessDetector.isIOSBrowser
// Samsung Galaxy Note 8 exhibits same issue as described above for iOS >= 15.
// It uses specifically Mali-G71 MP20 but reports its renderer as follows.
&& unmaskedRenderer !== "Mali-G71";
if (allowFloatRender && undefined !== this.queryExtensionObject("EXT_float_blend") && this.isTextureRenderable(gl, gl.FLOAT)) {
this._maxRenderType = RenderType.TextureFloat;
} else if (this.isWebGL2) {
this._maxRenderType = (this.isTextureRenderable(gl, (gl as WebGL2RenderingContext).HALF_FLOAT)) ? RenderType.TextureHalfFloat : RenderType.TextureUnsignedByte;
} else {
const hfExt: OES_texture_half_float | undefined = this.queryExtensionObject<OES_texture_half_float>("OES_texture_half_float");
this._maxRenderType = (hfExt !== undefined && this.isTextureRenderable(gl, hfExt.HALF_FLOAT_OES)) ? RenderType.TextureHalfFloat : RenderType.TextureUnsignedByte;
}
// Determine the maximum depth attachment type.
// this._maxDepthType = this.queryExtensionObject("WEBGL_depth_texture") !== undefined ? DepthType.TextureUnsignedInt32 : DepthType.RenderBufferUnsignedShort16;
this._maxDepthType = this._isWebGL2 || this.queryExtensionObject("WEBGL_depth_texture") !== undefined ? DepthType.TextureUnsignedInt24Stencil8 : DepthType.RenderBufferUnsignedShort16;
this._canRenderDepthWithoutColor = this._maxDepthType === DepthType.TextureUnsignedInt24Stencil8 ? this.isDepthRenderableWithoutColor(gl) : false;
this._presentFeatures = this._gatherFeatures();
const missingRequiredFeatures = this._findMissingFeatures(Capabilities.requiredFeatures);
const missingOptionalFeatures = this._findMissingFeatures(Capabilities.optionalFeatures);
return {
status: this._getCompatibilityStatus(missingRequiredFeatures, missingOptionalFeatures),
missingRequiredFeatures,
missingOptionalFeatures,
unmaskedRenderer,
unmaskedVendor,
usingIntegratedGraphics: isIntegratedGraphics({unmaskedVendor, unmaskedRenderer}),
driverBugs: { ...this._driverBugs },
userAgent: navigator.userAgent,
createdContext: gl,
};
}
public static create(gl: WebGLContext, disabledExtensions?: WebGLExtensionName[]): Capabilities | undefined {
const caps = new Capabilities();
const compatibility = caps.init(gl, disabledExtensions);
if (WebGLRenderCompatibilityStatus.CannotCreateContext === compatibility.status || WebGLRenderCompatibilityStatus.MissingRequiredFeatures === compatibility.status)
return undefined;
return caps;
}
/** Determines if a particular texture type is color-renderable on the host system. */
private isTextureRenderable(gl: WebGLContext, texType: number): boolean {
const tex: WebGLTexture | null = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
if (this.isWebGL2) {
if (gl.FLOAT === texType)
gl.texImage2D(gl.TEXTURE_2D, 0, (gl as WebGL2RenderingContext).RGBA32F, 1, 1, 0, gl.RGBA, texType, null);
else
gl.texImage2D(gl.TEXTURE_2D, 0, (gl as WebGL2RenderingContext).RGBA16F, 1, 1, 0, gl.RGBA, texType, null);
} else
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, texType, null);
const fb: WebGLFramebuffer | null = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
const fbStatus: number = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.deleteFramebuffer(fb);
gl.deleteTexture(tex);
gl.getError(); // clear any errors
return fbStatus === gl.FRAMEBUFFER_COMPLETE;
}
/** Determines if depth textures can be rendered without also having a color attachment bound on the host system. */
private isDepthRenderableWithoutColor(gl: WebGLContext): boolean {
const dtExt = this.queryExtensionObject<WEBGL_depth_texture>("WEBGL_depth_texture");
if (dtExt === undefined)
return false;
const tex: WebGLTexture | null = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, 1, 1, 0, gl.DEPTH_STENCIL, dtExt.UNSIGNED_INT_24_8_WEBGL, null);
const fb: WebGLFramebuffer | null = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, tex, 0);
const fbStatus: number = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.deleteFramebuffer(fb);
gl.deleteTexture(tex);
gl.getError(); // clear any errors
return fbStatus === gl.FRAMEBUFFER_COMPLETE;
}
public setMaxAnisotropy(desiredMax: number | undefined, gl: WebGLContext): void {
const ext = this.queryExtensionObject<EXT_texture_filter_anisotropic>("EXT_texture_filter_anisotropic");
if (undefined === ext)
return;
if (undefined === this._maxAnisotropy)
this._maxAnisotropy = gl.getParameter(ext.MAX_TEXTURE_MAX_ANISOTROPY_EXT) as number;
const max = (undefined !== desiredMax) ? Math.min(desiredMax, this._maxAnisotropy) : this._maxAnisotropy;
gl.texParameterf(gl.TEXTURE_2D, ext.TEXTURE_MAX_ANISOTROPY_EXT, max);
}
} | the_stack |
import type { ComponentInterface, EventEmitter } from '@stencil/core';
import { Build, Component, Element, Event, Host, Method, Prop, State, Watch, h } from '@stencil/core';
import { getIonMode } from '../../global/ionic-global';
import type {
AutocompleteTypes,
Color,
InputChangeEventDetail,
StyleEventDetail,
TextFieldTypes,
} from '../../interface';
import type { Attributes } from '../../utils/helpers';
import { inheritAriaAttributes, debounceEvent, findItemLabel, inheritAttributes } from '../../utils/helpers';
import { createColorClasses } from '../../utils/theme';
/**
* @virtualProp {"ios" | "md"} mode - The mode determines which platform styles to use.
*/
@Component({
tag: 'ion-input',
styleUrls: {
ios: 'input.ios.scss',
md: 'input.md.scss',
},
scoped: true,
})
export class Input implements ComponentInterface {
private nativeInput?: HTMLInputElement;
private inputId = `ion-input-${inputIds++}`;
private didBlurAfterEdit = false;
private inheritedAttributes: Attributes = {};
private isComposing = false;
/**
* This is required for a WebKit bug which requires us to
* blur and focus an input to properly focus the input in
* an item with delegatesFocus. It will no longer be needed
* with iOS 14.
*
* @internal
*/
@Prop() fireFocusEvents = true;
@State() hasFocus = false;
@Element() el!: HTMLElement;
/**
* The color to use from your application's color palette.
* Default options are: `"primary"`, `"secondary"`, `"tertiary"`, `"success"`, `"warning"`, `"danger"`, `"light"`, `"medium"`, and `"dark"`.
* For more information on colors, see [theming](/docs/theming/basics).
*/
@Prop({ reflect: true }) color?: Color;
/**
* If the value of the type attribute is `"file"`, then this attribute will indicate the types of files that the server accepts, otherwise it will be ignored. The value must be a comma-separated list of unique content type specifiers.
*/
@Prop() accept?: string;
/**
* Indicates whether and how the text value should be automatically capitalized as it is entered/edited by the user.
* Available options: `"off"`, `"none"`, `"on"`, `"sentences"`, `"words"`, `"characters"`.
*/
@Prop() autocapitalize = 'off';
/**
* Indicates whether the value of the control can be automatically completed by the browser.
*/
@Prop() autocomplete: AutocompleteTypes = 'off';
/**
* Whether auto correction should be enabled when the user is entering/editing the text value.
*/
@Prop() autocorrect: 'on' | 'off' = 'off';
/**
* This Boolean attribute lets you specify that a form control should have input focus when the page loads.
*/
@Prop() autofocus = false;
/**
* If `true`, a clear icon will appear in the input when there is a value. Clicking it clears the input.
*/
@Prop() clearInput = false;
/**
* If `true`, the value will be cleared after focus upon edit. Defaults to `true` when `type` is `"password"`, `false` for all other types.
*/
@Prop() clearOnEdit?: boolean;
/**
* Set the amount of time, in milliseconds, to wait to trigger the `ionChange` event after each keystroke. This also impacts form bindings such as `ngModel` or `v-model`.
*/
@Prop() debounce = 0;
@Watch('debounce')
protected debounceChanged() {
this.ionChange = debounceEvent(this.ionChange, this.debounce);
}
/**
* If `true`, the user cannot interact with the input.
*/
@Prop() disabled = false;
@Watch('disabled')
protected disabledChanged() {
this.emitStyle();
}
/**
* A hint to the browser for which enter key to display.
* Possible values: `"enter"`, `"done"`, `"go"`, `"next"`,
* `"previous"`, `"search"`, and `"send"`.
*/
@Prop() enterkeyhint?: 'enter' | 'done' | 'go' | 'next' | 'previous' | 'search' | 'send';
/**
* A hint to the browser for which keyboard to display.
* Possible values: `"none"`, `"text"`, `"tel"`, `"url"`,
* `"email"`, `"numeric"`, `"decimal"`, and `"search"`.
*/
@Prop() inputmode?: 'none' | 'text' | 'tel' | 'url' | 'email' | 'numeric' | 'decimal' | 'search';
/**
* The maximum value, which must not be less than its minimum (min attribute) value.
*/
@Prop() max?: string | number;
/**
* If the value of the type attribute is `text`, `email`, `search`, `password`, `tel`, or `url`, this attribute specifies the maximum number of characters that the user can enter.
*/
@Prop() maxlength?: number;
/**
* The minimum value, which must not be greater than its maximum (max attribute) value.
*/
@Prop() min?: string | number;
/**
* If the value of the type attribute is `text`, `email`, `search`, `password`, `tel`, or `url`, this attribute specifies the minimum number of characters that the user can enter.
*/
@Prop() minlength?: number;
/**
* If `true`, the user can enter more than one value. This attribute applies when the type attribute is set to `"email"` or `"file"`, otherwise it is ignored.
*/
@Prop() multiple?: boolean;
/**
* The name of the control, which is submitted with the form data.
*/
@Prop() name: string = this.inputId;
/**
* A regular expression that the value is checked against. The pattern must match the entire value, not just some subset. Use the title attribute to describe the pattern to help the user. This attribute applies when the value of the type attribute is `"text"`, `"search"`, `"tel"`, `"url"`, `"email"`, `"date"`, or `"password"`, otherwise it is ignored. When the type attribute is `"date"`, `pattern` will only be used in browsers that do not support the `"date"` input type natively. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date for more information.
*/
@Prop() pattern?: string;
/**
* Instructional text that shows before the input has a value.
* This property applies only when the `type` property is set to `"email"`,
* `"number"`, `"password"`, `"search"`, `"tel"`, `"text"`, or `"url"`, otherwise it is ignored.
*/
@Prop() placeholder?: string;
/**
* If `true`, the user cannot modify the value.
*/
@Prop() readonly = false;
/**
* If `true`, the user must fill in a value before submitting a form.
*/
@Prop() required = false;
/**
* If `true`, the element will have its spelling and grammar checked.
*/
@Prop() spellcheck = false;
/**
* Works with the min and max attributes to limit the increments at which a value can be set.
* Possible values are: `"any"` or a positive floating point number.
*/
@Prop() step?: string;
/**
* The initial size of the control. This value is in pixels unless the value of the type attribute is `"text"` or `"password"`, in which case it is an integer number of characters. This attribute applies only when the `type` attribute is set to `"text"`, `"search"`, `"tel"`, `"url"`, `"email"`, or `"password"`, otherwise it is ignored.
*/
@Prop() size?: number;
/**
* The type of control to display. The default type is text.
*/
@Prop() type: TextFieldTypes = 'text';
/**
* The value of the input.
*/
@Prop({ mutable: true }) value?: string | number | null = '';
/**
* Emitted when a keyboard input occurred.
*/
@Event() ionInput!: EventEmitter<InputEvent>;
/**
* Emitted when the value has changed.
*/
@Event() ionChange!: EventEmitter<InputChangeEventDetail>;
/**
* Emitted when the input loses focus.
*/
@Event() ionBlur!: EventEmitter<FocusEvent>;
/**
* Emitted when the input has focus.
*/
@Event() ionFocus!: EventEmitter<FocusEvent>;
/**
* Emitted when the styles change.
* @internal
*/
@Event() ionStyle!: EventEmitter<StyleEventDetail>;
/**
* Update the item classes when the placeholder changes
*/
@Watch('placeholder')
protected placeholderChanged() {
this.emitStyle();
}
/**
* Update the native input element when the value changes
*/
@Watch('value')
protected valueChanged() {
const nativeInput = this.nativeInput;
const value = this.getValue();
if (nativeInput && nativeInput.value !== value && !this.isComposing) {
/**
* Assigning the native input's value on attribute
* value change, allows `ionInput` implementations
* to override the control's value.
*
* Used for patterns such as input trimming (removing whitespace),
* or input masking.
*/
nativeInput.value = value;
}
this.emitStyle();
this.ionChange.emit({ value: this.value == null ? this.value : this.value.toString() });
}
componentWillLoad() {
this.inheritedAttributes = {
...inheritAriaAttributes(this.el),
...inheritAttributes(this.el, ['tabindex', 'title']),
};
}
connectedCallback() {
this.emitStyle();
this.debounceChanged();
if (Build.isBrowser) {
document.dispatchEvent(
new CustomEvent('ionInputDidLoad', {
detail: this.el,
})
);
}
}
componentDidLoad() {
const nativeInput = this.nativeInput;
if (nativeInput) {
// TODO: FW-729 Update to JSX bindings when Stencil resolves bug with:
// https://github.com/ionic-team/stencil/issues/3235
nativeInput.addEventListener('compositionstart', this.onCompositionStart);
nativeInput.addEventListener('compositionend', this.onCompositionEnd);
}
}
disconnectedCallback() {
if (Build.isBrowser) {
document.dispatchEvent(
new CustomEvent('ionInputDidUnload', {
detail: this.el,
})
);
}
const nativeInput = this.nativeInput;
if (nativeInput) {
nativeInput.removeEventListener('compositionstart', this.onCompositionStart);
nativeInput.removeEventListener('compositionEnd', this.onCompositionEnd);
}
}
/**
* Sets focus on the native `input` in `ion-input`. Use this method instead of the global
* `input.focus()`.
*/
@Method()
async setFocus() {
if (this.nativeInput) {
this.nativeInput.focus();
}
}
/**
* Sets blur on the native `input` in `ion-input`. Use this method instead of the global
* `input.blur()`.
* @internal
*/
@Method()
async setBlur() {
if (this.nativeInput) {
this.nativeInput.blur();
}
}
/**
* Returns the native `<input>` element used under the hood.
*/
@Method()
getInputElement(): Promise<HTMLInputElement> {
return Promise.resolve(this.nativeInput!);
}
private shouldClearOnEdit() {
const { type, clearOnEdit } = this;
return clearOnEdit === undefined ? type === 'password' : clearOnEdit;
}
private getValue(): string {
return typeof this.value === 'number' ? this.value.toString() : (this.value || '').toString();
}
private emitStyle() {
this.ionStyle.emit({
interactive: true,
input: true,
'has-placeholder': this.placeholder !== undefined,
'has-value': this.hasValue(),
'has-focus': this.hasFocus,
'interactive-disabled': this.disabled,
});
}
private onInput = (ev: Event) => {
const input = ev.target as HTMLInputElement | null;
if (input) {
this.value = input.value || '';
}
this.ionInput.emit(ev as InputEvent);
};
private onBlur = (ev: FocusEvent) => {
this.hasFocus = false;
this.focusChanged();
this.emitStyle();
if (this.fireFocusEvents) {
this.ionBlur.emit(ev);
}
};
private onFocus = (ev: FocusEvent) => {
this.hasFocus = true;
this.focusChanged();
this.emitStyle();
if (this.fireFocusEvents) {
this.ionFocus.emit(ev);
}
};
private onKeydown = (ev: KeyboardEvent) => {
if (this.shouldClearOnEdit()) {
// Did the input value change after it was blurred and edited?
// Do not clear if user is hitting Enter to submit form
if (this.didBlurAfterEdit && this.hasValue() && ev.key !== 'Enter') {
// Clear the input
this.clearTextInput();
}
// Reset the flag
this.didBlurAfterEdit = false;
}
};
private onCompositionStart = () => {
this.isComposing = true;
};
private onCompositionEnd = () => {
this.isComposing = false;
};
private clearTextOnEnter = (ev: KeyboardEvent) => {
if (ev.key === 'Enter') {
this.clearTextInput(ev);
}
};
private clearTextInput = (ev?: Event) => {
if (this.clearInput && !this.readonly && !this.disabled && ev) {
ev.preventDefault();
ev.stopPropagation();
// Attempt to focus input again after pressing clear button
this.setFocus();
}
this.value = '';
/**
* This is needed for clearOnEdit
* Otherwise the value will not be cleared
* if user is inside the input
*/
if (this.nativeInput) {
this.nativeInput.value = '';
}
};
private focusChanged() {
// If clearOnEdit is enabled and the input blurred but has a value, set a flag
if (!this.hasFocus && this.shouldClearOnEdit() && this.hasValue()) {
this.didBlurAfterEdit = true;
}
}
private hasValue(): boolean {
return this.getValue().length > 0;
}
render() {
const mode = getIonMode(this);
const value = this.getValue();
const labelId = this.inputId + '-lbl';
const label = findItemLabel(this.el);
if (label) {
label.id = labelId;
}
return (
<Host
aria-disabled={this.disabled ? 'true' : null}
class={createColorClasses(this.color, {
[mode]: true,
'has-value': this.hasValue(),
'has-focus': this.hasFocus,
})}
>
<input
class="native-input"
ref={(input) => (this.nativeInput = input)}
aria-labelledby={label ? labelId : null}
disabled={this.disabled}
accept={this.accept}
autoCapitalize={this.autocapitalize}
autoComplete={this.autocomplete}
autoCorrect={this.autocorrect}
autoFocus={this.autofocus}
enterKeyHint={this.enterkeyhint}
inputMode={this.inputmode}
min={this.min}
max={this.max}
minLength={this.minlength}
maxLength={this.maxlength}
multiple={this.multiple}
name={this.name}
pattern={this.pattern}
placeholder={this.placeholder || ''}
readOnly={this.readonly}
required={this.required}
spellcheck={this.spellcheck}
step={this.step}
size={this.size}
type={this.type}
value={value}
onInput={this.onInput}
onBlur={this.onBlur}
onFocus={this.onFocus}
onKeyDown={this.onKeydown}
{...this.inheritedAttributes}
/>
{this.clearInput && !this.readonly && !this.disabled && (
<button
aria-label="reset"
type="button"
class="input-clear-icon"
onTouchStart={this.clearTextInput}
onMouseDown={this.clearTextInput}
onKeyDown={this.clearTextOnEnter}
/>
)}
</Host>
);
}
}
let inputIds = 0; | the_stack |
module dragonBones {
/**
* @class dragonBones.Animation
* @classdesc
* Animationๅฎไพ้ถๅฑไบArmature,็จไบๆงๅถArmature็ๅจ็ปๆญๆพใ
* @see dragonBones.Bone
* @see dragonBones.Armature
* @see dragonBones.AnimationState
* @see dragonBones.AnimationData
*
* @example
<pre>
//่ทๅๅจ็ปๆฐๆฎ
var skeletonData = RES.getRes("skeleton");
//่ทๅ็บน็้ๆฐๆฎ
var textureData = RES.getRes("textureConfig");
//่ทๅ็บน็้ๅพ็
var texture = RES.getRes("texture");
//ๅๅปบไธไธชๅทฅๅ๏ผ็จๆฅๅๅปบArmature
var factory:dragonBones.EgretFactory = new dragonBones.EgretFactory();
//ๆๅจ็ปๆฐๆฎๆทปๅ ๅฐๅทฅๅ้
factory.addSkeletonData(dragonBones.DataParser.parseDragonBonesData(skeletonData));
//ๆ็บน็้ๆฐๆฎๅๅพ็ๆทปๅ ๅฐๅทฅๅ้
factory.addTextureAtlas(new dragonBones.EgretTextureAtlas(texture, textureData));
//่ทๅArmature็ๅๅญ๏ผdragonBones4.0็ๆฐๆฎๅฏไปฅๅ
ๅซๅคไธช้ชจๆถ๏ผ่ฟ้ๅ็ฌฌไธไธชArmature
var armatureName:string = skeletonData.armature[0].name;
//ไปๅทฅๅ้ๅๅปบๅบArmature
var armature:dragonBones.Armature = factory.buildArmature(armatureName);
//่ทๅ่ฃ
่ฝฝArmature็ๅฎนๅจ
var armatureDisplay = armature.display;
armatureDisplay.x = 200;
armatureDisplay.y = 500;
//ๆๅฎๆทปๅ ๅฐ่ๅฐไธ
this.addChild(armatureDisplay);
//ๅๅพ่ฟไธชArmatureๅจ็ปๅ่กจไธญ็็ฌฌไธไธชๅจ็ป็ๅๅญ
var curAnimationName:string = armature.animation.animationList[0];
var animation:dragonBones.Animation = armature.animation;
//gotoAndPlay็็จๆณ๏ผๅจ็ปๆญๆพ๏ผๆญๆพไธ้
animation.gotoAndPlay(curAnimationName,0,-1,1);
//gotoAndStop็็จๆณ๏ผ
//curAnimationName = armature.animation.animationList[1];
//ๅจ็ปๅๅจ็ฌฌไบไธชๅจ็ป็็ฌฌ0.2็ง็ไฝ็ฝฎ
//animation.gotoAndStop(curAnimationName,0.2);
//ๅจ็ปๅๅจ็ฌฌไบไธชๅจ็ป็ไธๅ็ไฝ็ฝฎ๏ผๅฆๆ็ฌฌไธไธชๅๆฐๅคงไบ0๏ผไผๅฟฝ็ฅ็ฌฌไบไธชๅๆฐ
//animation.gotoAndStop(curAnimationName,0, 0.5);
//็ปง็ปญๆญๆพ
//animation.play();
//ๆๅๆญๆพ
//animation.stop();
//ๅจ็ป่ๅ
//animation.gotoAndPlay(curAnimationName,0,-1,0,0,"group1");
//var animationState:dragonBones.AnimationState = armature.animation.getState(curAnimationName);
//animationState.addBoneMask("neck",true);
//ๆญๆพ็ฌฌไบไธชๅจ็ป๏ผ ๆพๅฐgroup "Squat"้
//curAnimationName = armature.animation.animationList[1];
//armature.animation.gotoAndPlay(curAnimationName,0,-1,0,0,"group2",dragonBones.Animation.SAME_GROUP);
//animationState = armature.animation.getState(curAnimationName);
//animationState.addBoneMask("hip",true);//โhipโๆฏ้ชจๆถ็ๆ น้ชจ้ชผ็ๅๅญ
//animationState.removeBoneMask("neck",true);
//ๆArmatureๆทปๅ ๅฐๅฟ่ทณๆถ้้
dragonBones.WorldClock.clock.add(armature);
//ๅฟ่ทณๆถ้ๅผๅฏ
egret.Ticker.getInstance().register(function (advancedTime) {
dragonBones.WorldClock.clock.advanceTime(advancedTime / 1000);
}, this);
</pre>
*/
export class Animation{
public static NONE:string = "none";
public static SAME_LAYER:string = "sameLayer";
public static SAME_GROUP:string = "sameGroup";
public static SAME_LAYER_AND_GROUP:string = "sameLayerAndGroup";
public static ALL:string = "all";
/**
* ๆ ่ฎฐๆฏๅฆๅผๅฏ่ชๅจ่กฅ้ดใ
* ่ฎพ็ฝฎไธบ trueๆถ๏ผAnimationไผๆ นๆฎๅจ็ปๆฐๆฎ็ๅ
ๅฎน๏ผๅจๅ
ณ้ฎๅธงไน้ด่ชๅจ่กฅ้ดใ่ฎพ็ฝฎไธบfalseๆถ๏ผๆๆๅจ็ปๅไธ่กฅ้ด
* ้ป่ฎคๅผ๏ผtrueใ
* @member {boolean} dragonBones.Animation#tweenEnabled
*/
public tweenEnabled:boolean;
private _armature:Armature;
private _animationStateList:Array<AnimationState>;
private _animationDataList:Array<AnimationData>;
private _animationList:Array<string>;
private _isPlaying:boolean;
private _timeScale:number;
/** @private */
public _lastAnimationState:AnimationState;
/** @private */
public _isFading:boolean;
/** @private */
public _animationStateCount:number = 0;
/**
* ๅๅปบไธไธชๆฐ็Animationๅฎไพๅนถ่ต็ปไผ ๅ
ฅ็Armatureๅฎไพ
* @param armature {Armature} ้ชจๆถๅฎไพ
*/
public constructor(armature:Armature){
this._armature = armature;
this._animationList = [];
this._animationStateList = [];
this._timeScale = 1;
this._isPlaying = false;
this.tweenEnabled = true;
}
/**
* ๅๆถAnimationๅฎไพ็จๅฐ็ๆๆ่ตๆบ
*/
public dispose():void{
if(!this._armature){
return;
}
this._resetAnimationStateList();
this._animationList.length = 0;
this._armature = null;
this._animationDataList = null;
this._animationList = null;
this._animationStateList = null;
}
public _resetAnimationStateList():void
{
var i:number = this._animationStateList.length;
var animationState:AnimationState;
while(i --)
{
animationState = this._animationStateList[i];
animationState._resetTimelineStateList();
AnimationState._returnObject(animationState);
}
this._animationStateList.length = 0;
}
/**
* ๅผๅงๆญๆพๆๅฎๅ็งฐ็ๅจ็ปใ
* ่ฆๆญๆพ็ๅจ็ปๅฐ็ป่ฟๆๅฎๆถ้ด็ๆทกๅ
ฅ่ฟ็จ๏ผ็ถๅๅผๅงๆญๆพ๏ผๅๆถไนๅๆญๆพ็ๅจ็ปไผ็ป่ฟ็ธๅๆถ้ด็ๆทกๅบ่ฟ็จใ
* @param animationName {string} ๆๅฎๆญๆพๅจ็ป็ๅ็งฐ.
* @param fadeInTime {number} ๅจ็ปๆทกๅ
ฅๆถ้ด (>= 0), ้ป่ฎคๅผ๏ผ-1 ๆๅณ็ไฝฟ็จๅจ็ปๆฐๆฎไธญ็ๆทกๅ
ฅๆถ้ด.
* @param duration {number} ๅจ็ปๆญๆพๆถ้ดใ้ป่ฎคๅผ๏ผ-1 ๆๅณ็ไฝฟ็จๅจ็ปๆฐๆฎไธญ็ๆญๆพๆถ้ด.
* @param playTimes {number} ๅจ็ปๆญๆพๆฌกๆฐ(0:ๅพช็ฏๆญๆพ, >=1:ๆญๆพๆฌกๆฐ, NaN:ไฝฟ็จๅจ็ปๆฐๆฎไธญ็ๆญๆพๆถ้ด), ้ป่ฎคๅผ๏ผNaN
* @param layer {number} ๅจ็ปๆๅค็ๅฑ
* @param group {string} ๅจ็ปๆๅค็็ป
* @param fadeOutMode {string} ๅจ็ปๆทกๅบๆจกๅผ (none, sameLayer, sameGroup, sameLayerAndGroup, all).้ป่ฎคๅผ๏ผsameLayerAndGroup
* @param pauseFadeOut {boolean} ๅจ็ปๆทกๅบๆถๆๅๆญๆพ
* @param pauseFadeIn {boolean} ๅจ็ปๆทกๅ
ฅๆถๆๅๆญๆพ
* @returns {AnimationState} ๅจ็ปๆญๆพ็ถๆๅฎไพ
* @see dragonBones.AnimationState.
*/
public gotoAndPlay(
animationName:string,
fadeInTime:number = -1,
duration:number = -1,
playTimes:number = NaN,
layer:number = 0,
group:string = null,
fadeOutMode:string = Animation.SAME_LAYER_AND_GROUP,
pauseFadeOut:boolean = true,
pauseFadeIn:boolean = true
):AnimationState{
if (!this._animationDataList){
return null;
}
var i:number = this._animationDataList.length;
var animationData:AnimationData;
while(i --){
if(this._animationDataList[i].name == animationName){
animationData = this._animationDataList[i];
break;
}
}
if (!animationData){
return null;
}
var needUpdate:boolean = this._isPlaying == false;
this._isPlaying = true;
this._isFading = true;
//
fadeInTime = fadeInTime < 0?(animationData.fadeTime < 0?0.3:animationData.fadeTime):fadeInTime;
var durationScale:number;
if(duration < 0){
durationScale = animationData.scale < 0?1:animationData.scale;
}
else{
durationScale = duration * 1000 / animationData.duration;
}
playTimes = isNaN(playTimes)?animationData.playTimes:playTimes;
//ๆ นๆฎfadeOutMode,้ๆฉๆญฃ็กฎ็animationStateๆง่กfadeOut
var animationState:AnimationState;
switch(fadeOutMode){
case Animation.NONE:
break;
case Animation.SAME_LAYER:
i = this._animationStateList.length;
while(i --){
animationState = this._animationStateList[i];
if(animationState.layer == layer){
animationState.fadeOut(fadeInTime, pauseFadeOut);
}
}
break;
case Animation.SAME_GROUP:
i = this._animationStateList.length;
while(i --){
animationState = this._animationStateList[i];
if(animationState.group == group){
animationState.fadeOut(fadeInTime, pauseFadeOut);
}
}
break;
case Animation.ALL:
i = this._animationStateList.length;
while(i --){
animationState = this._animationStateList[i];
animationState.fadeOut(fadeInTime, pauseFadeOut);
}
break;
case Animation.SAME_LAYER_AND_GROUP:
default:
i = this._animationStateList.length;
while(i --){
animationState = this._animationStateList[i];
if(animationState.layer == layer && animationState.group == group ){
animationState.fadeOut(fadeInTime, pauseFadeOut);
}
}
break;
}
this._lastAnimationState = AnimationState._borrowObject();
this._lastAnimationState._layer = layer;
this._lastAnimationState._group = group;
this._lastAnimationState.autoTween = this.tweenEnabled;
this._lastAnimationState._fadeIn(this._armature, animationData, fadeInTime, 1 / durationScale, playTimes, pauseFadeIn);
this.addState(this._lastAnimationState);
//ๆงๅถๅญ้ชจๆถๆญๆพๅๅๅจ็ป
var slotList:Array<Slot> = this._armature.getSlots(false);
i = slotList.length;
while(i --){
var slot:Slot = slotList[i];
if(slot.childArmature){
slot.childArmature.animation.gotoAndPlay(animationName, fadeInTime);
}
}
if(needUpdate)
{
this._armature.advanceTime(0);
}
return this._lastAnimationState;
}
/**
* ๆญๆพๆๅฎๅ็งฐ็ๅจ็ปๅนถๅๆญขไบๆไธชๆถ้ด็น
* @param animationName {string} ๆๅฎๆญๆพ็ๅจ็ปๅ็งฐ.
* @param time {number} ๅจ็ปๅๆญข็็ปๅฏนๆถ้ด
* @param normalizedTime {number} ๅจ็ปๅๆญข็็ธๅฏนๅจ็ปๆปๆถ้ด็็ณปๆฐ๏ผ่ฟไธชๅๆฐๅtimeๅๆฐๆฏไบๆฅ็๏ผไพๅฆ 0.2๏ผๅจ็ปๅๆญขๆปๆถ้ด็20%ไฝ็ฝฎ๏ผ ้ป่ฎคๅผ๏ผ-1 ๆๅณ็ไฝฟ็จ็ปๅฏนๆถ้ดใ
* @param fadeInTime {number} ๅจ็ปๆทกๅ
ฅๆถ้ด (>= 0), ้ป่ฎคๅผ๏ผ0
* @param duration {number} ๅจ็ปๆญๆพๆถ้ดใ้ป่ฎคๅผ๏ผ-1 ๆๅณ็ไฝฟ็จๅจ็ปๆฐๆฎไธญ็ๆญๆพๆถ้ด.
* @param layer {string} ๅจ็ปๆๅค็ๅฑ
* @param group {string} ๅจ็ปๆๅค็็ป
* @param fadeOutMode {string} ๅจ็ปๆทกๅบๆจกๅผ (none, sameLayer, sameGroup, sameLayerAndGroup, all).้ป่ฎคๅผ๏ผsameLayerAndGroup
* @returns {AnimationState} ๅจ็ปๆญๆพ็ถๆๅฎไพ
* @see dragonBones.AnimationState.
*/
public gotoAndStop(
animationName:string,
time:number,
normalizedTime:number = -1,
fadeInTime:number = 0,
duration:number = -1,
layer:number = 0,
group:string = null,
fadeOutMode:string = Animation.ALL
):AnimationState{
var animationState:AnimationState = this.getState(animationName, layer);
if(!animationState){
animationState = this.gotoAndPlay(animationName, fadeInTime, duration, NaN, layer, group, fadeOutMode);
}
if(normalizedTime >= 0){
animationState.setCurrentTime(animationState.totalTime * normalizedTime);
}
else{
animationState.setCurrentTime(time);
}
animationState.stop();
return animationState;
}
/**
* ไปๅฝๅไฝ็ฝฎ็ปง็ปญๆญๆพๅจ็ป
*/
public play():void{
if (!this._animationDataList || this._animationDataList.length == 0){
return;
}
if(!this._lastAnimationState){
this.gotoAndPlay(this._animationDataList[0].name);
}
else if (!this._isPlaying){
this._isPlaying = true;
}
else{
this.gotoAndPlay(this._lastAnimationState.name);
}
}
/**
* ๆๅๅจ็ปๆญๆพ
*/
public stop():void{
this._isPlaying = false;
}
/**
* ่ทๅพๆๅฎๅ็งฐ็ AnimationState ๅฎไพ.
* @returns {AnimationState} AnimationState ๅฎไพ.
* @see dragonBones..AnimationState.
*/
public getState(name:string, layer:number = 0):AnimationState{
var i:number = this._animationStateList.length;
while(i --){
var animationState:AnimationState = this._animationStateList[i];
if(animationState.name == name && animationState.layer == layer){
return animationState;
}
}
return null;
}
/**
* ๆฃๆฅๆฏๅฆๅ
ๅซๆๅฎๅ็งฐ็ๅจ็ป.
* @returns {boolean}.
*/
public hasAnimation(animationName:string):boolean{
var i:number = this._animationDataList.length;
while(i --){
if(this._animationDataList[i].name == animationName){
return true;
}
}
return false;
}
/** @private */
public _advanceTime(passedTime:number):void{
if(!this._isPlaying){
return;
}
var isFading:boolean = false;
passedTime *= this._timeScale;
var i:number = this._animationStateList.length;
while(i --){
var animationState:AnimationState = this._animationStateList[i];
if(animationState._advanceTime(passedTime)){
this.removeState(animationState);
}
else if(animationState.fadeState != 1){
isFading = true;
}
}
this._isFading = isFading;
}
/** @private */
//ๅฝๅจ็ปๆญๆพ่ฟ็จไธญBonelistๆนๅๆถ่งฆๅ
public _updateAnimationStates():void{
var i:number = this._animationStateList.length;
while(i --){
this._animationStateList[i]._updateTimelineStates();
}
}
private addState(animationState:AnimationState):void{
if(this._animationStateList.indexOf(animationState) < 0){
this._animationStateList.unshift(animationState);
this._animationStateCount = this._animationStateList.length;
}
}
private removeState(animationState:AnimationState):void{
var index:number = this._animationStateList.indexOf(animationState);
if(index >= 0){
this._animationStateList.splice(index, 1);
AnimationState._returnObject(animationState);
if(this._lastAnimationState == animationState){
if(this._animationStateList.length > 0){
this._lastAnimationState = this._animationStateList[0];
}
else{
this._lastAnimationState = null;
}
}
this._animationStateCount = this._animationStateList.length;
}
}
/**
* ไธๆจ่็API.ๆจ่ไฝฟ็จ animationList.
*/
public get movementList():Array<string>{
return this._animationList;
}
/**
* ไธๆจ่็API.ๆจ่ไฝฟ็จ lastAnimationName.
*/
public get movementID():string{
return this.lastAnimationName;
}
/**
* ๆ่ฟๆญๆพ็ AnimationState ๅฎไพใ
* @member {AnimationState} dragonBones.Animation#lastAnimationState
* @see dragonBones.AnimationState
*/
public get lastAnimationState():AnimationState{
return this._lastAnimationState;
}
/**
* ๆ่ฟๆญๆพ็ๅจ็ปๅ็งฐ.
* @member {string} dragonBones.Animation#lastAnimationName
*/
public get lastAnimationName():string{
return this._lastAnimationState?this._lastAnimationState.name:null;
}
/**
* ๆๆๅจ็ปๅ็งฐๅ่กจ.
* @member {string[]} dragonBones.Animation#animationList
*/
public get animationList():Array<string>{
return this._animationList;
}
/**
* ๆฏๅฆๆญฃๅจๆญๆพ
* @member {boolean} dragonBones.Animation#isPlaying
*/
public get isPlaying():boolean{
return this._isPlaying && !this.isComplete;
}
/**
* ๆ่ฟๆญๆพ็ๅจ็ปๆฏๅฆๆญๆพๅฎๆ.
* @member {boolean} dragonBones.Animation#isComplete
*/
public get isComplete():boolean{
if(this._lastAnimationState){
if(!this._lastAnimationState.isComplete){
return false;
}
var i:number = this._animationStateList.length;
while(i --){
if(!this._animationStateList[i].isComplete){
return false;
}
}
return true;
}
return true;
}
/**
* ๆถ้ด็ผฉๆพๅๆฐ
* @member {number} dragonBones.Animation#timeScale
*/
public get timeScale():number{
return this._timeScale;
}
public set timeScale(value:number){
if(isNaN(value) || value < 0){
value = 1;
}
this._timeScale = value;
}
/**
* ๅ
ๅซ็ๆๆๅจ็ปๆฐๆฎๅ่กจ
* @member {AnimationData[]} dragonBones.Animation#animationDataList
* @see dragonBones.AnimationData.
*/
public get animationDataList():Array<AnimationData>{
return this._animationDataList;
}
public set animationDataList(value:Array<AnimationData>){
this._animationDataList = value;
this._animationList.length = 0;
for(var i:number = 0,len:number = this._animationDataList.length; i < len; i++)
{
var animationData:AnimationData = this._animationDataList[i];
this._animationList[this._animationList.length] = animationData.name;
}
}
}
} | the_stack |
import * as pako from 'pako';
import crc32 from '../helpers/crc32';
import encodeIDAT from './encode-idat';
import Metadata from '../helpers/metadata';
import PNG_SIGNATURE from '../helpers/signature';
import { GAMMA_DIVISION } from '../helpers/gamma';
import { COLOR_TYPES } from '../helpers/color-types';
import rescaleSample from '../helpers/rescale-sample';
import { encode as encodeUTF8 } from '../helpers/utf8';
import { concatUInt8Array } from '../helpers/typed-array';
import { CHROMATICITIES_DIVISION } from '../helpers/chromaticities';
const NULL_SEPARATOR = 0;
const COMPRESSION_METHOD = 0;
export default function encode(metadata: Metadata) {
// Signature
let typedArray = new Uint8Array(PNG_SIGNATURE);
// Helpers
function packUInt32BE(value: number) {
return new Uint8Array([
(value >> 24) & 0xff,
(value >> 16) & 0xff,
(value >> 8) & 0xff,
value & 0xff,
]);
}
function packUInt16BE(value: number) {
return new Uint8Array([(value >> 8) & 0xff, value & 0xff]);
}
function packUInt8(value: number) {
return new Uint8Array([value & 0xff]);
}
function packString(name: string) {
const data = new Uint8Array(name.length);
for (let i = 0; i < name.length; i++) {
data[i] = name.charCodeAt(i);
}
return data;
}
// Chunks
const chunkPackers: {
[chunkName: string]: () => Uint8Array;
} = {
IHDR: packIHDR,
tIME: packTIME,
sRGB: packSRGB,
pHYs: packPHYS,
sPLT: packSPLT,
iCCP: packICCP,
sBIT: packSBIT,
gAMA: packGAMA,
cHRM: packCHRM,
PLTE: packPLTE,
tRNS: packTRNS,
hIST: packHIST,
bKGD: packBKGD,
IDAT: packIDAT,
IEND: packIEND,
};
function packIHDR() {
let data = new Uint8Array();
data = concatUInt8Array(data, packUInt32BE(metadata.width));
data = concatUInt8Array(data, packUInt32BE(metadata.height));
data = concatUInt8Array(data, packUInt8(metadata.depth));
data = concatUInt8Array(data, packUInt8(metadata.colorType));
data = concatUInt8Array(data, packUInt8(metadata.compression));
data = concatUInt8Array(data, packUInt8(metadata.filter));
data = concatUInt8Array(data, packUInt8(metadata.interlace));
return data;
}
function packPLTE() {
const data = [];
if (metadata.palette) {
for (let i = 0; i < metadata.palette.length; i++) {
const palette = metadata.palette[i];
data.push(palette[0], palette[1], palette[2]);
}
}
return new Uint8Array(data);
}
function packIDAT() {
return encodeIDAT(
metadata.data,
metadata.width,
metadata.height,
metadata.colorType,
metadata.depth,
metadata.interlace,
metadata.palette,
);
}
function packIEND() {
return new Uint8Array();
}
function packTRNS() {
const data = [];
if (metadata.colorType === COLOR_TYPES.GRAYSCALE) {
if (metadata.transparent) {
const color = rescaleSample(metadata.transparent[0], 8, metadata.depth);
data.push((color >> 8) & 0xff, color & 0xff);
}
} else if (metadata.colorType === COLOR_TYPES.TRUE_COLOR) {
if (metadata.transparent) {
for (let i = 0; i < 3; i++) {
const color = rescaleSample(
metadata.transparent[i],
8,
metadata.depth,
);
data.push((color >> 8) & 0xff, color & 0xff);
}
}
} else if (metadata.colorType === COLOR_TYPES.PALETTE) {
if (!metadata.palette) {
throw new Error('Palette is required');
}
const { palette } = metadata;
let transparent = false;
for (let i = 0; i < palette.length; i++) {
data.push(palette[i][3]);
if (palette[i][3] !== 0xff) {
transparent = true;
}
}
if (!transparent) {
return new Uint8Array();
}
}
return new Uint8Array(data);
}
function packCHRM() {
if (!metadata.chromaticities) {
return new Uint8Array();
}
const { chromaticities } = metadata;
let data = new Uint8Array();
([
'white',
'red',
'green',
'blue',
] as (keyof typeof chromaticities)[]).forEach(function (color) {
(['x', 'y'] as (keyof typeof chromaticities[typeof color])[]).forEach(
function (axis) {
data = concatUInt8Array(
data,
packUInt32BE(
chromaticities[color]![axis] * CHROMATICITIES_DIVISION,
),
);
},
);
});
return data;
}
function packGAMA() {
if (metadata.gamma !== undefined) {
return packUInt32BE(metadata.gamma * GAMMA_DIVISION);
}
return new Uint8Array();
}
function packICCP() {
if (!metadata.icc) {
return new Uint8Array();
}
let data = packString(metadata.icc.name);
data = concatUInt8Array(data, packUInt8(NULL_SEPARATOR));
data = concatUInt8Array(data, packUInt8(COMPRESSION_METHOD));
data = concatUInt8Array(
data,
pako.deflate(new Uint8Array(metadata.icc.profile)),
);
return data;
}
function packSBIT() {
if (!metadata.significantBits) {
return new Uint8Array();
}
if (metadata.colorType === COLOR_TYPES.GRAYSCALE) {
return packUInt8(metadata.significantBits[0]);
}
if (
metadata.colorType === COLOR_TYPES.TRUE_COLOR ||
metadata.colorType === COLOR_TYPES.PALETTE
) {
const data = new Uint8Array(3);
for (let i = 0; i < 3; i++) {
data[i] = metadata.significantBits[i];
}
return data;
}
if (metadata.colorType === COLOR_TYPES.GRAYSCALE_WITH_ALPHA) {
return concatUInt8Array(
packUInt8(metadata.significantBits[0]),
packUInt8(metadata.significantBits[3]),
);
}
if (metadata.colorType === COLOR_TYPES.TRUE_COLOR_WITH_ALPHA) {
const data = new Uint8Array(4);
for (let i = 0; i < 4; i++) {
data[i] = metadata.significantBits[i];
}
return data;
}
return new Uint8Array();
}
function packSRGB() {
if (metadata.sRGB !== undefined) {
return packUInt8(metadata.sRGB);
}
return new Uint8Array();
}
function packBKGD() {
if (!metadata.background) {
return new Uint8Array();
}
if ((metadata.colorType & 3) === COLOR_TYPES.GRAYSCALE) {
const color = rescaleSample(metadata.background[0], 8, metadata.depth);
return packUInt16BE(color);
}
if ((metadata.colorType & 3) === COLOR_TYPES.TRUE_COLOR) {
const data = new Uint8Array(6);
for (let i = 0; i < 3; i++) {
const color = rescaleSample(metadata.background[i], 8, metadata.depth);
data[i * 2] = (color >> 8) & 0xff;
data[i * 2 + 1] = color & 0xff;
}
return data;
} else if (metadata.colorType === COLOR_TYPES.PALETTE) {
if (!metadata.palette) {
throw new Error('Missing chunk: PLTE');
}
let index = -1;
for (
let paletteIndex = 0;
paletteIndex < metadata.palette.length;
paletteIndex++
) {
for (let i = 0; i < 4; i++) {
if (metadata.palette[paletteIndex][i] === metadata.background[i]) {
index = paletteIndex;
break;
}
}
}
if (index === -1) {
throw new Error('Background not in palette');
}
return packUInt8(index);
}
return new Uint8Array();
}
function packHIST() {
const data = [];
if (metadata.histogram) {
metadata.histogram.forEach(function (value) {
data.push((value >> 8) & 0xff, value & 0xff);
});
}
return new Uint8Array();
}
function packPHYS() {
let data = new Uint8Array();
if (metadata.physicalDimensions) {
data = concatUInt8Array(
data,
packUInt32BE(metadata.physicalDimensions.pixelPerUnitX),
);
data = concatUInt8Array(
data,
packUInt32BE(metadata.physicalDimensions.pixelPerUnitY),
);
data = concatUInt8Array(
data,
packUInt8(metadata.physicalDimensions.unit),
);
}
return data;
}
function packSPLT() {
if (!metadata.suggestedPalette) {
return new Uint8Array();
}
let data = concatUInt8Array(
packString(metadata.suggestedPalette.name),
packUInt8(NULL_SEPARATOR),
);
data = concatUInt8Array(data, packUInt8(metadata.suggestedPalette.depth));
for (let i = 0; i < metadata.suggestedPalette.palette.length; i++) {
const palette = metadata.suggestedPalette.palette[i];
if (metadata.suggestedPalette.depth === 8) {
const paletteData = new Uint8Array([
palette[0],
palette[1],
palette[2],
palette[3],
(palette[4] >> 8) & 0xff,
palette[4] & 0xff,
]);
data = concatUInt8Array(data, paletteData);
} else if (metadata.suggestedPalette.depth === 16) {
const paletteData = new Uint8Array(10);
for (let i = 0; i < 5; i++) {
paletteData[i * 2] = (palette[i] >> 8) & 0xff;
paletteData[i * 2 + 1] = palette[i] & 0xff;
}
data = concatUInt8Array(data, paletteData);
} else {
// throw new Error('Unsupported sPLT depth: ' + depth);
}
}
return data;
}
function packTIME() {
if (!metadata.lastModificationTime) {
return new Uint8Array();
}
const data = new Uint8Array(7);
const date = new Date(metadata.lastModificationTime);
const year = date.getUTCFullYear();
data[0] = (year >> 8) & 0xff;
data[1] = year & 0xff;
data[2] = date.getUTCMonth() + 1;
data[3] = date.getUTCDate();
data[4] = date.getUTCHours();
data[5] = date.getUTCMinutes();
data[6] = date.getUTCSeconds();
return data;
}
function addChunk(chunkName: string, data: Uint8Array) {
const nameData = packString(chunkName);
const lengthData = packUInt32BE(data.length);
const typeAndData = concatUInt8Array(nameData, data);
const calculatedCrc32 = crc32(typeAndData);
const endData = packUInt32BE(calculatedCrc32);
const chunkData = concatUInt8Array(
concatUInt8Array(lengthData, typeAndData),
endData,
);
typedArray = concatUInt8Array(typedArray, chunkData);
}
// tEXt
if (metadata.text) {
Object.keys(metadata.text).forEach(function (keyword) {
let data = concatUInt8Array(
packString(keyword),
packUInt8(NULL_SEPARATOR),
);
data = concatUInt8Array(data, packString(metadata.text![keyword]));
addChunk('tEXt', data);
});
}
// zTXt
if (metadata.compressedText) {
Object.keys(metadata.compressedText).forEach(function (keyword) {
let data = concatUInt8Array(
packString(keyword),
packUInt8(NULL_SEPARATOR),
);
data = concatUInt8Array(data, packUInt8(COMPRESSION_METHOD));
data = concatUInt8Array(
data,
pako.deflate(packString(metadata.compressedText![keyword])),
);
addChunk('zTXt', data);
});
}
// iTXt
if (metadata.internationalText) {
Object.keys(metadata.internationalText).forEach(function (keyword) {
const {
languageTag,
translatedKeyword,
text,
} = metadata.internationalText![keyword];
const textData = encodeUTF8(text);
const compressedTextData = pako.deflate(textData);
const compressionFlag =
compressedTextData.length < textData.length ? 1 : 0;
let data = concatUInt8Array(
packString(keyword),
packUInt8(NULL_SEPARATOR),
);
data = concatUInt8Array(data, packUInt8(compressionFlag));
data = concatUInt8Array(data, packUInt8(COMPRESSION_METHOD));
data = concatUInt8Array(data, packString(languageTag));
data = concatUInt8Array(data, packUInt8(NULL_SEPARATOR));
data = concatUInt8Array(data, encodeUTF8(translatedKeyword));
data = concatUInt8Array(data, packUInt8(NULL_SEPARATOR));
data = concatUInt8Array(
data,
compressionFlag ? compressedTextData : textData,
);
addChunk('iTXt', data);
});
}
// Other Chunks
Object.keys(chunkPackers).forEach(function (chunkName) {
const data = chunkPackers[chunkName]();
if (data.length > 0 || chunkName === 'IEND') {
addChunk(chunkName, data);
}
});
return typedArray;
} | the_stack |
import {defs} from "./defs";
import {create, setPosition} from "./svg-create";
import {cursorInteraction} from "svg-editor-tools/lib/cursor-interaction";
import {shapes} from "./shapes";
import {
boxesOverlap,
cabDistance,
insideBox,
intersectPolylineBox,
project,
scaleBox,
Segment,
uncenterBox
} from "./intersect";
import {autoLayout} from "./dagre";
import {Undo} from "./undo";
import {
ADD_LABEL_VERTEX,
ADD_VERTEX,
DEL_VERTEX,
DESELECT,
findShortcut,
MOVE_DOWN,
MOVE_DOWN_FAST,
MOVE_LEFT,
MOVE_LEFT_FAST,
MOVE_RIGHT,
MOVE_RIGHT_FAST,
MOVE_UP,
MOVE_UP_FAST,
REDO,
SELECT_ALL,
UNDO,
ZOOM_100,
ZOOM_FIT,
ZOOM_IN,
ZOOM_OUT
} from "../shortcuts";
interface Point {
x: number;
y: number;
}
interface BBox extends Point {
width: number;
height: number;
}
interface Group extends BBox {
id: string;
name: string;
nodes: (Node | Group)[];
ref?: SVGGElement;
style: NodeStyle;
}
interface Node extends BBox {
id: string;
title: string;
sub: string;
description: string;
ref?: SVGGElement;
selected?: boolean;
intersect: (p: Point) => Point
style: NodeStyle
}
export interface NodeStyle {
// Width of element, in pixels.
width?: number
// Height of element, in pixels.
height?: number
// Background color of element as HTML RGB hex string (e.g. "#ffffff")
background?: string
// Stroke color of element as HTML RGB hex string (e.g. "#000000")
stroke?: string
// Foreground (text) color of element as HTML RGB hex string (e.g. "#ffffff")
color?: string
// Standard font size used to render text, in pixels.
fontSize?: number
// Shape used to render element.
shape?: string
// URL of PNG/JPG/GIF file or Base64 data URI representation.
icon?: string
// Type of border used to render element.
border?: string
// Opacity used to render element; 0-100.
opacity?: number
// Whether element metadata should be shown.
metadata?: boolean
// Whether element description should be shown.
description?: boolean
}
// RelationshipStyle defines a relationship style.
export interface EdgeStyle {
// Thickness of line, in pixels.
thickness?: number
// Color of line as HTML RGB hex string (e.g. "#ffffff").
color?: string
// Standard font size used to render relationship annotation, in pixels.
fontSize?: number
// Width of relationship annotation, in pixels.
width?: number
// Whether line is rendered dashed or not.
dashed?: boolean
// Routing algorithm used to render lines.
routing?: string
// Position of annotation along the line; 0 (start) to 100 (end).
position?: number
// Opacity used to render line; 0-100.
opacity?: number
}
const defaultEdgeStyle: EdgeStyle = {
thickness: 3,
color: '#999',
opacity: 1,
fontSize: 22,
dashed: true,
}
const defaultNodeStyle: NodeStyle = {
width: 300,
height: 300,
background: 'rgba(255, 255, 255, .9)',
color: '#666',
opacity: .9,
stroke: '#999',
fontSize: 22,
shape: 'Rect'
}
interface Edge {
id: string;
label: string;
from: Node;
to: Node;
vertices?: EdgeVertex[];
ref?: SVGGElement;
style: EdgeStyle;
initVertex: (p: Point) => EdgeVertex
}
interface EdgeVertex extends Point {
id: string
selected?: boolean
edge: Edge
ref?: SVGElement
label?: boolean
auto?: boolean
}
interface Layout {
[k: string]: Point | (Point & { label: boolean })[]
}
export class GraphData {
id: string;
name: string;
nodesMap: Map<string, Node>;
edges: Edge[];
edgeVertices: Map<string, EdgeVertex>
groupsMap: Map<string, Group>;
metadata: any;
private _undo: Undo<Layout>;
constructor(id?: string, name?: string) {
this.id = id;
this.name = name;
this.edges = [];
this.edgeVertices = new Map;
this.nodesMap = new Map;
this.groupsMap = new Map;
this._undo = new Undo<Layout>(
this.id,
() => this.exportLayout(true),
(lo) => this.importLayout(lo, true)
)
// @ts-ignore
window.graph = this
}
// after the graph model is build using addNode, addEdge etc, initialize
init(layout?: Layout) {
layout && this.importLayout(layout)
this._undo = new Undo<Layout>(
this.id,
() => this.exportLayout(true),
(lo) => this.importLayout(lo, true)
)
if (this._undo.length()) {
this.importLayout(this._undo.currentState())
}
}
addNode(id: string, label: string, sub: string, description: string, style: NodeStyle) {
if (this.nodesMap.has(id)) throw Error('duplicate node: ' + id)
const n: Node = {
id, title: label, sub, description, style: {...defaultNodeStyle, ...style},
x: 0, y: 0, width: style.width, height: style.height, intersect: null
}
// console.log(label, id, style, {...defaultNodeStyle, ...style})
this.nodesMap.set(n.id, n)
}
nodes() {
return Array.from(this.nodesMap.values())
}
addEdge(id: string, fromNode: string, toNode: string, label: string, vertices: Point[], style: EdgeStyle) {
vertices && vertices.forEach((p, i) => {
const v = p as EdgeVertex
v.id = `v-${id}-${i}`
this.edgeVertices.set(v.id, v)
})
const randomID = () => Math.round(Math.random() * 1e10).toString(36)
const initVertex = (p: Point) => {
const v = p as EdgeVertex
if (!v.id) {
v.id = `v-${randomID()}`
this.edgeVertices.set(v.id, v)
}
v.edge = edge
return p as EdgeVertex
}
const edge = {
id,
from: this.nodesMap.get(fromNode),
to: this.nodesMap.get(toNode),
label,
vertices: null as EdgeVertex[],
style: {...defaultEdgeStyle, ...style},
initVertex
}
this.edges.push(edge)
if (vertices) {
edge.vertices = vertices.map(p => edge.initVertex(p))
}
}
addGroup(id: string, name: string, nodesOrGroups: string[], style: NodeStyle) {
if (this.groupsMap.has(id)) {
console.error(`Group exists: ${id} ${name}`)
return
}
const group: Group = {
id, name, x: null, y: null, width: null, height: null,
nodes: nodesOrGroups.map(k => {
const n = this.nodesMap.get(k) || this.groupsMap.get(k)
if (!n) console.error(`Node or group ${k} not found for group ${id} "${name}"`)
return n
}).filter(Boolean),
style
}
this.groupsMap.set(id, group)
}
// private rebuildNode(node: Node) {
// const p = node.ref.parentElement;
// p.removeChild(node.ref)
// node.ref = buildNode(node, this)
// p.appendChild(node.ref)
// this.redrawEdges(node)
// this.redrawGroups(node)
// }
setNodeSelected(node: Node, selected: boolean) {
node.selected = selected
selected ?
node.ref.classList.add('selected') :
node.ref.classList.remove('selected')
this.updateEdgesSel()
}
private updateEdgesSel() {
this.edges.forEach(e => {
if (e.to.selected || e.from.selected) {
e.ref.classList.add('selected')
} else {
e.ref.classList.remove('selected')
}
})
}
moveNode(n: Node, x: number, y: number) {
[x, y] = roundPoint(x, y)
if (n.x == x && n.y == y) return
this._undo.beforeChange()
n.x = x;
n.y = y;
setPosition(n.ref, x, y)
this.redrawEdges(n);
this.redrawGroups(n)
this._undo.change()
}
moveEdgeVertex(v: EdgeVertex, x: number, y: number) {
[x, y] = roundPoint(x, y)
if (v.x == x && v.y == y) return
this._undo.beforeChange()
v.x = x;
v.y = y;
this.redrawEdge(v.edge)
this._undo.change()
}
moveSelected(dx: number, dy: number) {
this.nodes().forEach(n => n.selected && this.moveNode(n, n.x + dx, n.y + dy))
this.edgeVertices.forEach(v => v.selected && this.moveEdgeVertex(v, v.x + dx, v.y + dy))
}
insertEdgeVertex(edge: Edge, p: Point, pos: number, isLabel: boolean) {
this._undo.beforeChange()
const v = edge.initVertex(p)
v.selected = true
if (isLabel) { // when shift down, make it label position
edge.vertices.forEach(v => v.label = false)
v.label = true
}
edge.vertices.splice(pos - 1, 0, v)
this.redrawEdge(edge)
this._undo.change()
}
deleteEdgeVertex(v: EdgeVertex) {
this._undo.beforeChange()
if (v.auto) {
v.auto = true
} else {
v.edge.vertices.splice(v.edge.vertices.indexOf(v), 1)
this.edgeVertices.delete(v.id)
}
this.redrawEdge(v.edge)
this._undo.change()
}
changed() {
return this._undo.changed()
}
undo() {
this._undo.undo()
}
redo() {
this._undo.redo()
}
// moves the entire graph to be aligned top-left of the drawing area
// used to bring back to visible the nodes that end up at negative coordinates
alignTopLeft() {
const nodes: Point[] = this.nodes()
const vertices = Array.from(this.edgeVertices.values())
const all: Point[] = nodes.concat(vertices)
let minX: number = Math.min(...all.map(n => n.x)) - 250
let minY: number = Math.min(...all.map(n => n.y)) - 250
this.nodesMap.forEach(n => this.moveNode(n, n.x - minX, n.y - minY))
vertices.forEach(v => this.moveEdgeVertex(v, v.x - minX, v.y - minY))
}
//redraw connected edges
private redrawEdges(n: Node) {
this.edges.forEach(e => (n == e.from || n == e.to) && this.redrawEdge(e))
this.updateEdgesSel()
}
redrawEdge(e: Edge) {
const p = e.ref.parentElement;
p.removeChild(e.ref)
e.ref = buildEdge(this, e)
p.append(e.ref)
}
private redrawGroups(node: Node) {
this.groupsMap.forEach(group => {
//if (group.nodes.indexOf(node) == -1) return
const p = group.ref.parentElement
p.removeChild(group.ref)
buildGroup(group)
p.append(group.ref)
})
}
exportSVG() {
//save svg html
let svg: SVGSVGElement = document.querySelector('svg#graph')
const elastic = svg.querySelector('rect.elastic')
const p = elastic.parentElement
p.removeChild(elastic)
const zoom = getZoom()
setZoom(1)
// inject metadata
const script = document.createElement('script')
script.setAttribute('type', 'application/json')
this.metadata.layout = this.exportLayout()
script.append('<![CDATA[' + escapeCdata(JSON.stringify(this.metadata, null, 2)) + ']]>')
svg.insertBefore(script, svg.firstChild)
// read the SVG
let src = svg.outerHTML
// restore all
svg.removeChild(script)
p.append(elastic)
setZoom(zoom)
return src.replace(/^<svg/, '<svg xmlns="http://www.w3.org/2000/svg"')
}
/**
* @param full when true, the edges without vertices are saved too, used for undo buffer
* for saving, full is false
*/
exportLayout(full = false) {
const ret: Layout = {}
this.nodes().forEach(n => ret[n.id] = {x: n.x, y: n.y})
this.edges.forEach(e => {
const lst = e.vertices.filter(v => !v.auto).map(v => ({x: v.x, y: v.y, label: v.label}));
(lst.length || full) && (ret[`e-${e.id}`] = lst)
})
return ret
}
setSaved() {
this._undo.setSaved()
}
importLayout(layout: { [key: string]: any }, rerender = false) {
Object.entries(layout).forEach(([k, v]) => {
// nodes
const n = this.nodesMap.get(k)
if (n) {
n.x = v.x
n.y = v.y
} else
// edge vertices
if (k.startsWith('e-')) {
const edge = this.edges.find(e => e.id == k.slice(2))
if (!edge) return;
edge.vertices && edge.vertices.forEach(v => this.edgeVertices.delete(v.id))
edge.vertices = v.map((p: Point) => edge.initVertex(p))
return;
}
})
if (rerender) {
this.nodes().forEach(n => setPosition(n.ref, n.x, n.y))
this.edges.forEach(e => this.redrawEdge(e))
this.updateEdgesSel()
this.redrawGroups(null)
}
}
autoLayout() {
const auto = autoLayout(this)
auto.nodes.forEach(an => {
const n = this.nodesMap.get(an.id)
this.moveNode(n, an.x, an.y)
})
this.edgeVertices.clear()
auto.edges.forEach(ae => {
const edge = this.edges.find(e => e.id == ae.id)
const labelVertex = ae.vertices.find(v => ae.label.x == v.x && ae.label.y == v.y) as EdgeVertex
labelVertex && (labelVertex.label = true)
edge.vertices = ae.vertices.slice(1, -1).map(p => edge.initVertex(p))
this.redrawEdge(edge)
})
updatePanning()
}
alignSelectionV() {
const lst: Point[] = this.nodes().filter(n => n.selected)
lst.push(...Array.from(this.edgeVertices.values()).filter(v => v.selected))
let minY = Math.min(...lst.map(p => p.y))
this.nodesMap.forEach(n => n.selected && this.moveNode(n, n.x, minY))
this.edgeVertices.forEach(v => v.selected && this.moveEdgeVertex(v, v.x, minY))
}
alignSelectionH() {
const lst: Point[] = this.nodes().filter(n => n.selected)
lst.push(...Array.from(this.edgeVertices.values()).filter(v => v.selected))
let minX = Math.min(...lst.map(p => p.x))
this.nodesMap.forEach(n => n.selected && this.moveNode(n, minX, n.y))
this.edgeVertices.forEach(v => v.selected && this.moveEdgeVertex(v, minX, v.y))
}
}
function escapeCdata(code: string) {
return code.replace(/]]>/g, ']]]>]><![CDATA[')
}
function roundPoint(x: number, y: number) {
return [Math.round(x / 10) * 10, Math.round(y / 10) * 10]
}
let svg: SVGSVGElement = document.querySelector('svg#graph')
if (!svg) {
svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute('id', 'graph')
svg.addEventListener('click', e => clickListener(e))
addCursorInteraction(svg)
}
svg.setAttribute('width', '100%')
svg.setAttribute('height', '100%')
let clickListener: (e: MouseEvent) => void
let dragging = false;
let selectListener: (n: Node) => void
export const buildGraph = (data: GraphData, onNodeSelect: (n: Node) => void) => {
// empty svg
svg.innerHTML = defs
document.body.append(svg) // make sure svg element is connected, we will measure texts sizes
// @ts-ignore
svg.__data = data
selectListener = onNodeSelect
//use event delegation
clickListener = e => {
if (dragging) {
return;
}
// the expand button was clicked
// let el = (e.target as any).closest('.node > .expand');
}
_buildGraph(data)
const elasticEl = create.rect(300, 300, 50, 50, 0, 'elastic')
svg.append(elasticEl)
return {
svg,
setZoom,
}
}
export const buildGraphView = (data: GraphData) => {
svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute('id', 'graph')
_buildGraph(data)
return svg
}
const _buildGraph = (data: GraphData) => {
//toplevel groups
const zoomG = create.element('g', {}, 'zoom') as SVGGElement
const nodesG = create.element('g', {}, 'nodes') as SVGGElement
const edgesG = create.element('g', {}, 'edges') as SVGGElement
const groupsG = create.element('g', {}, 'groups') as SVGGElement
zoomG.append(groupsG, edgesG, nodesG)
data.nodesMap.forEach((n) => {
buildNode(n, data)
nodesG.append(n.ref)
})
data.edges.forEach(e => {
buildEdge(data, e)
edgesG.append(e.ref)
})
data.groupsMap.forEach((group) => {
buildGroup(group)
groupsG.append(group.ref)
})
svg.append(zoomG)
}
function buildEdge(data: GraphData, edge: Edge) {
const n1 = edge.from, n2 = edge.to;
const g = create.element('g', {}, 'edge') as SVGGElement
g.setAttribute('id', edge.id)
g.setAttribute('data-from', edge.from.id)
g.setAttribute('data-to', edge.to.id)
const position = (edge.style.position || 50) / 100
// if vertices exists, follow them
let vertices: Point[] = edge.vertices ? edge.vertices.concat() : [];
// remove auto vertices, they will be regenerated
const tmp = (vertices as EdgeVertex[]);
tmp.forEach(v => v.auto && data.edgeVertices.delete(v.id))
vertices = tmp.filter(v => !v.auto)
if (vertices.length == 0) {
// for edges with same "from" and "to", we must spread the labels so they don't overlap
// lookup the other "same" edges
const sameEdges = data.edges.filter(e => e.from == edge.from && e.to == edge.to)
let spreadPos = 0
if (sameEdges.length > 1) {
const idx = sameEdges.indexOf(edge) // my index in the list of same edges
spreadPos = idx - (sameEdges.length - 1) / 2
let spreadX = 0, spreadY = 0;
if (Math.abs(n1.x - n2.x) > Math.abs(n1.y - n2.y)) {
spreadY = spreadPos * 70
} else {
spreadX = spreadPos * 200
}
const v = edge.initVertex({
x: (n1.x + n2.x) / 2 + spreadX,
y: (n1.y + n2.y) / 2 + spreadY
})
v.label = true
v.auto = true
vertices.push(v)
// only if no vertices and no splitting, obey routing style Orthogonal
} else if (edge.style.routing == 'Orthogonal') {
Math.abs(n2.x - n1.x) > Math.abs(n2.y - n1.y) ?
vertices.push({x: n1.x, y: n2.y, auto: true} as Point) :
vertices.push({x: n2.x, y: n1.y, auto: true} as Point)
// vertices.push({x: (n1.x + n2.x)/2, y: n1.y, auto: true} as Point)
// vertices.push({x: (n1.x + n2.x)/2, y: n2.y, auto: true} as Point)
// vertices.push({x: n1.x, y: (n1.y + n2.y) /2, auto: true} as Point)
// vertices.push({x: n2.x, y: (n1.y + n2.y) /2, auto: true} as Point)
}
}
vertices.unshift(n1)
vertices.push(n2)
vertices[0] = n1.intersect(vertices[1])
vertices[vertices.length - 1] = n2.intersect(vertices[vertices.length - 2])
// where along the edge is the label?
// position of label
let pLabel: Point = vertices.find(v => (v as EdgeVertex).label)
if (!pLabel) {
const distance = (p1: Point, p2: Point) =>
Math.sqrt((p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y))
let sum = 0 // total length of the edge, sum of segments
for (let i = 1; i < vertices.length; i++) {
sum += distance(vertices[i - 1], vertices[i])
}
pLabel = {x: n1.x, y: n1.y} // fallback for corner cases
let acc = 0
for (let i = 1; i < vertices.length; i++) {
const d = distance(vertices[i - 1], vertices[i])
if (acc + d > sum * position) {
const pos = (sum * position - acc) / d
pLabel = {
x: vertices[i - 1].x + (vertices[i].x - vertices[i - 1].x) * pos,
y: vertices[i - 1].y + (vertices[i].y - vertices[i - 1].y) * pos
}
break
}
acc += d
}
}
const {bg, txt, bbox} = buildEdgeLabel(pLabel, edge)
g.append(bg, txt)
const segments: Segment[] = []
for (let i = 1; i < vertices.length; i++) {
segments.push({p: vertices[i - 1], q: vertices[i]})
}
// splice edge over label box
intersectPolylineBox(segments, bbox)
const path = segments.map(s => `M${s.p.x},${s.p.y} L${s.q.x},${s.q.y}`).join(' ')
const p = create.path(path, {'marker-end': 'url(#arrow)'}, 'edge')
p.setAttribute('fill', 'none')
p.setAttribute('stroke', edge.style.color)
p.setAttribute('stroke-width', String(edge.style.thickness))
p.setAttribute('stroke-linecap', 'round')
edge.style.dashed && p.setAttribute('stroke-dasharray', '8')
g.append(p)
// drag handlers
edge.vertices = vertices.slice(1, -1).map(p => edge.initVertex(p))
edge.vertices.forEach((p, i) => {
const v = p as EdgeVertex
v.ref = create.element('circle', {id: v.id, cx: p.x, cy: p.y, r: 7, fill: 'none'}, 'v-dot')
v.selected && v.ref.classList.add('selected')
v.auto && v.ref.classList.add('auto')
g.append(v.ref)
})
edge.ref = g
return g
}
function buildEdgeLabel(pLabel: Point, edge: Edge) {
// label
const fontSize = edge.style.fontSize
let {txt, dy, maxW} = create.textArea(edge.label, 200, fontSize, false, pLabel.x, pLabel.y, 'middle')
//move text up to center relative to the edge
dy -= fontSize / 2
txt.setAttribute('y', String(pLabel.y - dy / 2))
maxW += fontSize
applyStyle(txt, styles.edgeText)
txt.setAttribute('stroke', 'none')
txt.setAttribute('font-size', String(edge.style.fontSize))
txt.setAttribute('fill', edge.style.color)
const bbox = {x: pLabel.x - maxW / 2, y: pLabel.y - dy / 2, width: maxW, height: dy}
const bg = create.rect(bbox.width, bbox.height, bbox.x, bbox.y)
applyStyle(bg, styles.edgeRect)
txt.setAttribute('data-field', 'label')
bbox.x += bbox.width / 2
bbox.y += bbox.height / 2
return {bg, txt, bbox}
}
function buildNode(n: Node, data: GraphData) {
// @ts-ignore
window.gdata = data
const w = n.style.width;//Math.max(60, textWidth(n.id), ...n.fields.map(f => textWidth(f.name))) + 70
const h = n.style.height;
n.width = w;
n.height = h;
const g = create.element('g', {}, 'node') as SVGGElement
g.setAttribute('id', n.id)
n.selected && g.classList.add('selected')
setPosition(g, n.x, n.y)
const shapeFn = shapes[n.style.shape.toLowerCase()] || shapes.box
const shape: SVGElement = shapeFn(g, n);
shape.classList.add('nodeBorder')
applyStyle(shape, styles.nodeBorder)
shape.setAttribute('fill', n.style.background)
shape.setAttribute('stroke', n.style.stroke)
shape.setAttribute('stroke-width', (n.width / 70).toFixed(1))
shape.setAttribute('opacity', String(n.style.opacity))
setBorderStyle(shape, n.style.border)
const tg = create.element('g') as SVGGElement
let cy = Number(g.getAttribute('label-offset-y')) || 0
{
const fontSize = n.style.fontSize
const {txt, dy} = create.textArea(n.title, w - 40, fontSize, true, 0, cy, 'middle')
applyStyle(txt, styles.nodeText)
txt.setAttribute('fill', n.style.color)
txt.setAttribute('data-field', 'name')
tg.append(txt)
cy += dy
}
{
const txt = create.text(`[${n.sub}]`, 0, cy, 'middle')
applyStyle(txt, styles.nodeText)
txt.setAttribute('fill', n.style.color)
txt.setAttribute('font-size', String(0.75 * n.style.fontSize))
tg.append(txt)
cy += 10
}
{
cy += 10
const fontSize = n.style.fontSize
const {txt, dy} = create.textArea(n.description, w - 40, fontSize, false, 0, cy, 'middle')
applyStyle(txt, styles.nodeText)
txt.setAttribute('fill', n.style.color)
txt.setAttribute('data-field', 'description')
tg.append(txt)
cy += dy
}
setPosition(tg, 0, -cy / 2)
g.append(tg)
// @ts-ignore
g.__data = n;
n.ref = g;
return g
}
function buildGroup(group: Group) {
if (group.nodes.length == 0) {
return
}
const g = create.element('g', {}, 'group') as SVGGElement
let p0: Point = {x: 1e100, y: 1e100}, p1: Point = {x: 0, y: 0}
group.nodes.forEach(n => {
const b = {x: n.x - n.width / 2, y: n.y - n.height / 2, width: n.width, height: n.height}
p0.x = Math.min(p0.x, b.x)
p0.y = Math.min(p0.y, b.y)
p1.x = Math.max(p1.x, b.x + b.width)
p1.y = Math.max(p1.y, b.y + b.height)
})
const pad = 25
const w = Math.max(p1.x - p0.x, 200)
const h = p1.y - p0.y + pad * 1.5
const bb = {
x: p0.x - pad,
y: p0.y - pad,
width: w + pad * 2,
height: h + pad * 2,
}
const r = create.rect(bb.width, bb.height, bb.x, bb.y)
group.x = bb.x + bb.width / 2
group.y = bb.y + bb.height / 2
group.width = bb.width
group.height = bb.height
applyStyle(r, styles.groupRect)
group.style.stroke && r.setAttribute('stroke', group.style.stroke)
group.style.background && r.setAttribute('fill', group.style.background)
const txt = create.text(group.name, p0.x, bb.y + bb.height - styles.groupText["font-size"])
applyStyle(txt, styles.groupText)
group.style.color && txt.setAttribute('fill', group.style.color)
g.append(r, txt)
group.ref = g
}
function findClosestSegment(graph: GraphData, p: Point) {
// find the closest point on a segment
let fnd = {dst: Number.POSITIVE_INFINITY, pos: -1, edge: null as Edge, prj: null as Point}
graph.edges.forEach(edge => {
const vertices = edge.vertices || []
const pts = [edge.from, ...vertices, edge.to]
for (let i = 1; i < pts.length; i++) {
const prj = project(p, pts[i - 1], pts[i])
const dst = cabDistance(p, prj)
if (dst > 50) continue
if (dst < fnd.dst) {
fnd = {dst, pos: i, prj, edge}
}
}
})
return fnd.edge ? fnd : null
}
function mouseToDrawing(e: MouseEvent): Point {
// transform event coords to drawing coords
const b = svg.getBoundingClientRect()
const z = getZoom()
return {x: (e.clientX - b.x) / z, y: (e.clientY - b.y) / z}
}
function addCursorInteraction(svg: SVGSVGElement) {
function getData(el: SVGElement) {
// @ts-ignore
return el.__data
}
const gd = () => (getData(svg) as GraphData)
interface Handle extends Point {
id: string
selected?: boolean
ref?: SVGElement
}
window.addEventListener("beforeunload", e => {
if (!gd().changed()) return
e.preventDefault()
e.returnValue = ''
})
function setDotSelected(d: Handle, selected: boolean) {
d.selected = selected
const dotEl = svg.querySelector('#' + d.id)
d.selected ? dotEl.classList.add('selected') : dotEl.classList.remove('selected')
}
// show moving dot along edge when ALT is pressed
svg.addEventListener('mousemove', e => {
if (!e.altKey) return
const fnd = findClosestSegment(gd(), mouseToDrawing(e))
if (fnd) {
const {prj} = fnd
const parent = svg.querySelector('g.edges')
let dot = parent.querySelector('#prj')
if (!dot) {
dot = create.element('circle', {id: 'prj', cx: prj.x, cy: prj.y, r: 7})
parent.append(dot)
}
dot.setAttribute('cx', String(prj.x))
dot.setAttribute('cy', String(prj.y))
} else {
removePrjDot()
}
})
window.addEventListener('keyup', e => {
const key = findShortcut(e, true)
if (key == ADD_VERTEX || key == ADD_LABEL_VERTEX) return
removePrjDot()
})
function removePrjDot() {
const el = svg.querySelector('g.edges #prj')
el && el.parentElement.removeChild(el)
}
svg.addEventListener('click', e => {
const key = findShortcut(e, true)
if (key != ADD_LABEL_VERTEX && key != ADD_VERTEX) return
const fnd = findClosestSegment(gd(), mouseToDrawing(e))
if (fnd) {
const {edge, pos, prj} = fnd
// depending on keyboard modifier, make it label position
gd().insertEdgeVertex(edge, prj, pos, key == ADD_LABEL_VERTEX)
removePrjDot()
}
})
svg.addEventListener('wheel', e => {
const key = findShortcut(e, false, true)
if (key == ZOOM_OUT || key == ZOOM_IN) {
const delta = Math.round(e.deltaY / 10) / 100
setZoom(getZoom() - delta)
e.preventDefault()
}
})
window.addEventListener('keydown', e => {
switch (findShortcut(e)) {
case DEL_VERTEX:
Array.from(gd().edgeVertices.values()).filter(v => v.selected).forEach(v => {
gd().deleteEdgeVertex(v)
})
break
case UNDO:
gd().undo()
break
case REDO:
gd().redo()
break
case ZOOM_IN:
setZoom(getZoom() + .05)
e.preventDefault()
break
case ZOOM_OUT:
setZoom(getZoom() - .05)
e.preventDefault()
break
case ZOOM_100:
setZoom(1)
e.preventDefault()
break
case ZOOM_FIT:
gd().alignTopLeft()
setZoom(getZoomAuto())
e.preventDefault()
break
case SELECT_ALL:
gd().nodes().forEach(n => gd().setNodeSelected(n, true))
gd().edgeVertices.forEach(v => setDotSelected(v, true))
e.preventDefault()
break
case DESELECT:
gd().nodes().forEach(n => gd().setNodeSelected(n, false))
gd().edgeVertices.forEach(v => setDotSelected(v, false))
e.preventDefault()
break
case MOVE_LEFT:
gd().moveSelected(-1, 0)
break
case MOVE_LEFT_FAST:
gd().moveSelected(-10, 0)
break
case MOVE_RIGHT:
gd().moveSelected(1, 0)
break
case MOVE_RIGHT_FAST:
gd().moveSelected(10, 0)
break
case MOVE_UP:
gd().moveSelected(0, -1)
break
case MOVE_UP_FAST:
gd().moveSelected(0, -10)
break
case MOVE_DOWN:
gd().moveSelected(0, 1)
break
case MOVE_DOWN_FAST:
gd().moveSelected(0, 10)
break
}
})
cursorInteraction({
svg: svg,
nodeFromEvent(e: MouseEvent): Handle {
e.preventDefault()
// node clicked
let el = (e.target as SVGElement).closest('g.nodes g.node') as SVGElement
if (el) return getData(el)
// vertex dot clicked
el = (e.target as SVGElement).closest('g.edges g.edge .v-dot') as SVGElement
if (el) {
return gd().edgeVertices.get(el.id)
}
return null
},
setSelection(handles: Handle[]) {
// nodes
gd().nodes().forEach(n => gd().setNodeSelected(n, handles.some(h => h.id == n.id)))
// dots
gd().edgeVertices.forEach(d => setDotSelected(d, handles.some(h => h.id == d.id)))
selectListener(gd().nodes().find(n => n.selected))
},
setDragging(d: boolean) {
dragging = d
},
isSelected(handle: Handle): boolean {
return handle.selected
},
getSelection(): Handle[] {
const ret: Handle[] = gd().nodes().filter(n => n.selected)
gd().edgeVertices.forEach(d => d.selected && ret.push(d))
return ret
},
getZoom: getZoom,
moveNode(h: Handle, x: number, y: number) {
if (gd().nodesMap.has(h.id))
gd().moveNode(h as Node, x, y)
else {
(h as EdgeVertex).auto = false
gd().moveEdgeVertex(h as EdgeVertex, x, y)
}
},
boxSelection(box: DOMRect, add) {
const b = scaleBox(box, 1 / getZoom())
// nodes
gd().nodesMap.forEach(n => gd().setNodeSelected(n, (add && n.selected) || boxesOverlap(uncenterBox(n), b)))
// dots
gd().edgeVertices.forEach(d => setDotSelected(d, (add && d.selected) || insideBox(d, b, false)))
selectListener(gd().nodes().find(n => n.selected))
},
updatePanning: updatePanning,
})
}
export function getZoom() {
const el = svg.querySelector('g.zoom') as SVGGElement
if (el.transform.baseVal.numberOfItems == 0) return 1
return el.transform.baseVal.getItem(0).matrix.a
}
const svgPadding = 20
export function setZoom(zoom: number) {
const el = svg.querySelector('g.zoom') as SVGGElement
el.setAttribute('transform', `scale(${zoom})`)
// also set panning size
updatePanning()
}
function updatePanning() {
const el = svg.querySelector('g.zoom') as SVGGElement
const bb = el.getBBox()
const zoom = getZoom()
const w = Math.max(svg.parentElement.clientWidth / zoom, bb.x + bb.width + svgPadding)
const h = Math.max(svg.parentElement.clientHeight / zoom, bb.y + bb.height + svgPadding)
svg.setAttribute('width', String(w * zoom))
svg.setAttribute('height', String(h * zoom))
}
export const getZoomAuto = () => {
const el = svg.querySelector('g.zoom') as SVGGElement
const bb = el.getBBox()
const zoom = Math.min(
(svg.parentElement.clientWidth - 20) / (bb.width + bb.x + svgPadding),
(svg.parentElement.clientHeight - 20) / (bb.height + bb.y + svgPadding),
)
return Math.max(Math.min(zoom, 1), .2)
}
const setBorderStyle = (el: SVGElement, style: string) => {
if (style == 'Dashed') el.setAttribute('stroke-dasharray', '4')
else if (style == 'Dotted') el.setAttribute('stroke-dasharray', '2')
}
const styles = {
//node styles
nodeBorder: {
fill: "rgba(255, 255, 255, 0.86)",
stroke: "#aaa",
filter: 'url(#shadow)',
},
nodeText: {
'font-family': 'Arial, sans-serif',
stroke: "none"
},
//edge styles
edgeText: {
'font-family': 'Arial, sans-serif',
stroke: "none"
},
edgeRect: {
fill: "none",
stroke: "none",
},
//group styles
groupRect: {
//fill: "none",
fill: "rgba(0, 0, 0, 0.02)",
stroke: "#666",
'stroke-width': 3,
"stroke-dasharray": 4,
},
groupText: {
fill: "#666",
"font-size": 22,
cursor: "default"
}
}
const applyStyle = (el: SVGElement, style: { [key: string]: string | number }) => {
Object.keys(style).forEach(name => {
if (name == 'font-size') {
if (typeof (style[name]) != 'number') {
console.error(`All font-sizes in styles have to be numbers representing px! Found:`, style)
}
el.setAttribute(name, style[name] + 'px')
} else {
el.setAttribute(name, String(style[name]))
}
})
} | the_stack |
import {
CreateTransferParams,
DEFAULT_TRANSFER_TIMEOUT,
EngineParams,
FullChannelState,
FullTransferState,
HashlockTransferState,
RegisteredTransfer,
ResolveTransferParams,
Result,
TransferNames,
ChainError,
UpdateType,
jsonifyError,
DEFAULT_CHANNEL_TIMEOUT,
SetupParams,
IVectorChainReader,
} from "@connext/vector-types";
import {
createTestChannelState,
createTestChannelStateWithSigners,
createTestFullHashlockTransferState,
getRandomAddress,
getRandomBytes32,
getRandomIdentifier,
mkAddress,
ChannelSigner,
NatsMessagingService,
mkPublicIdentifier,
} from "@connext/vector-utils";
import { expect } from "chai";
import Sinon from "sinon";
import { VectorChainReader, WithdrawCommitment } from "@connext/vector-contracts";
import { getAddress } from "@ethersproject/address";
import { BigNumber } from "@ethersproject/bignumber";
import { AddressZero } from "@ethersproject/constants";
import {
convertConditionalTransferParams,
convertResolveConditionParams,
convertSetupParams,
convertWithdrawParams,
} from "../paramConverter";
import { ParameterConversionError } from "../errors";
import { env } from "./env";
describe("ParamConverter", () => {
const chainId = parseInt(Object.keys(env.chainProviders)[0]);
const providerUrl = env.chainProviders[chainId];
const chainAddresses = { ...env.chainAddresses };
const withdrawRegisteredInfo: RegisteredTransfer = {
definition: mkAddress("0xdef"),
resolverEncoding: "resolve",
stateEncoding: "state",
name: TransferNames.Withdraw,
encodedCancel: "encodedCancel",
};
const transferRegisteredInfo: RegisteredTransfer = {
definition: mkAddress("0xdef"),
resolverEncoding: "resolve",
stateEncoding: "state",
name: TransferNames.HashlockTransfer,
encodedCancel: "encodedCancel",
};
let chainReader: Sinon.SinonStubbedInstance<VectorChainReader>;
let signerA: Sinon.SinonStubbedInstance<ChannelSigner>;
let signerB: Sinon.SinonStubbedInstance<ChannelSigner>;
let messaging: Sinon.SinonStubbedInstance<NatsMessagingService>;
const setDefaultStubs = (registryInfo: RegisteredTransfer = transferRegisteredInfo) => {
chainReader = Sinon.createStubInstance(VectorChainReader);
signerA = Sinon.createStubInstance(ChannelSigner);
signerB = Sinon.createStubInstance(ChannelSigner);
messaging = Sinon.createStubInstance(NatsMessagingService);
signerA.signMessage.resolves("success");
signerB.signMessage.resolves("success");
signerA.publicIdentifier = mkPublicIdentifier("vectorAAA");
signerB.publicIdentifier = mkPublicIdentifier("vectorBBB");
signerA.address = mkAddress("0xaaa");
signerB.address = mkAddress("0xeee");
chainReader.getBlockNumber.resolves(Result.ok<number>(110));
chainReader.getRegisteredTransferByName.resolves(Result.ok<RegisteredTransfer>(registryInfo));
chainReader.getRegisteredTransferByDefinition.resolves(Result.ok<RegisteredTransfer>(registryInfo));
};
afterEach(() => Sinon.restore());
describe("convertSetupParams", () => {
const { channel: channelState } = createTestChannelState(UpdateType.deposit, {
channelAddress: mkAddress("0xa"),
networkContext: {
...chainAddresses[chainId],
chainId,
providerUrl,
},
});
const generateParams = (): EngineParams.Setup => {
return {
counterpartyIdentifier: channelState.aliceIdentifier,
chainId: chainId,
timeout: DEFAULT_CHANNEL_TIMEOUT.toString(),
meta: undefined,
};
};
const runTest = (params: EngineParams.Setup, result: SetupParams) => {
// Check results of a test run, making sure the result conforms to desirable SetupParams
// based on input EngineParams.Setup.
expect(result).to.containSubset({
counterpartyIdentifier: params.counterpartyIdentifier,
timeout: params.timeout,
networkContext: {
channelFactoryAddress: chainAddresses[params.chainId].channelFactoryAddress,
transferRegistryAddress: chainAddresses[params.chainId].transferRegistryAddress,
chainId: params.chainId,
},
meta: params.meta,
});
};
it("should work with provided params.timeout", async () => {
const params = { ...generateParams(), timeout: "100000" };
const result = await convertSetupParams(params, chainAddresses);
runTest(params, result.getValue());
});
it("should work with default params.timeout", async () => {
// Set timeout to undefined in actual passed params.
const params = { ...generateParams(), timeout: undefined };
const result = await convertSetupParams(params, chainAddresses);
// Now that we've run the method, overwrite timeout to use the default value, and pass
// these expected params into our check method.
const expectedParams = { ...params, timeout: DEFAULT_CHANNEL_TIMEOUT.toString() };
runTest(expectedParams, result.getValue());
});
});
describe("convertConditionalTransferParams", () => {
const transferFee = "5";
const generateParams = (bIsRecipient = false): EngineParams.ConditionalTransfer => {
setDefaultStubs();
const hashlockState: Omit<HashlockTransferState, "balance"> = {
lockHash: getRandomBytes32(),
expiry: "45000",
};
const params = {
channelAddress: mkAddress("0xa"),
amount: "8",
assetId: mkAddress("0x0"),
recipient: bIsRecipient ? signerB.publicIdentifier : getRandomIdentifier(),
recipientChainId: chainId,
recipientAssetId: mkAddress("0x1"),
type: TransferNames.HashlockTransfer,
details: hashlockState,
timeout: DEFAULT_TRANSFER_TIMEOUT.toString(),
meta: {
message: "test",
routingId: getRandomBytes32(),
},
};
setMessagingStub(params, !bIsRecipient);
return params;
};
const setMessagingStub = (submittedParams, isUserA = false) => {
messaging.sendTransferQuoteMessage.resolves(
Result.ok({
routerIdentifier: signerA.publicIdentifier,
chainId,
amount: submittedParams.amount,
assetId: submittedParams.assetId,
recipient: submittedParams.recipient ?? (isUserA ? signerA.publicIdentifier : signerB.publicIdentifier),
recipientChainId: submittedParams.recipientChainId ?? chainId,
recipientAssetId: submittedParams.recipientAssetId ?? submittedParams.assetId,
fee: transferFee,
expiry: (Date.now() + 30_000).toString(),
signature: "success",
}),
);
};
it("should fail if params.type is a name and chainReader.getRegisteredTransferByName fails", async () => {
const params = generateParams();
const chainErr = new ChainError("Failure");
chainReader.getRegisteredTransferByName.resolves(Result.fail(chainErr));
// Set incorrect type
params.type = "FailingTest";
const { channel: channelState } = createTestChannelState(UpdateType.deposit, {
channelAddress: params.channelAddress,
networkContext: {
...chainAddresses[chainId],
chainId,
providerUrl,
},
});
const ret = await convertConditionalTransferParams(
params,
signerA,
channelState,
chainReader as IVectorChainReader,
messaging,
);
expect(ret.isError).to.be.true;
const err = ret.getError();
expect(err?.message).to.be.eq(ParameterConversionError.reasons.FailedToGetRegisteredTransfer);
expect(err?.context.channelAddress).to.be.eq(channelState.channelAddress);
expect(err?.context.publicIdentifier).to.be.eq(signerA.publicIdentifier);
expect(err?.context.params).to.be.deep.eq(params);
expect(err?.context.registryError).to.be.deep.eq(jsonifyError(chainErr));
});
it("should fail if bob is sending and cannot get quote from alice", async () => {
const params = generateParams();
const err = new Error("fail");
messaging.sendTransferQuoteMessage.resolves(Result.fail(err) as any);
const { channel: channelState } = createTestChannelState(UpdateType.deposit, {
channelAddress: params.channelAddress,
networkContext: {
...chainAddresses[chainId],
chainId,
providerUrl,
},
});
const ret = await convertConditionalTransferParams(
params,
signerA,
channelState,
chainReader as IVectorChainReader,
messaging,
);
expect(ret.isError).to.be.true;
expect(ret.getError()?.message).to.be.eq(ParameterConversionError.reasons.CouldNotGetQuote);
expect(ret.getError()?.context.quoteError.message).to.be.eq("fail");
});
it("should use the params.quote if it is provided", async () => {
const params = generateParams();
const { channel: channelState } = createTestChannelState(UpdateType.deposit, {
channelAddress: params.channelAddress,
networkContext: {
...chainAddresses[chainId],
chainId,
providerUrl,
},
});
params.quote = {
signature: undefined,
chainId,
routerIdentifier: channelState.aliceIdentifier,
amount: params.amount,
assetId: params.assetId,
recipient: params.recipient!,
recipientChainId: params.recipientChainId!,
recipientAssetId: params.recipientAssetId!,
fee: "0",
expiry: (Date.now() + 30_000).toString(),
};
const ret = await convertConditionalTransferParams(
params,
signerA,
channelState,
chainReader as IVectorChainReader,
messaging,
);
expect(ret.isError).to.be.false;
expect(ret.getValue().meta.quote).to.be.deep.eq(params.quote);
expect(messaging.sendTransferQuoteMessage.callCount).to.be.eq(0);
});
it("should return an unsigned quote if requester is channel.aliceIdentifier", async () => {
const params = generateParams();
const { channel: channelState } = createTestChannelState(UpdateType.deposit, {
channelAddress: params.channelAddress,
networkContext: {
...chainAddresses[chainId],
chainId,
providerUrl,
},
});
signerA.publicIdentifier = channelState.aliceIdentifier;
const ret = await convertConditionalTransferParams(
params,
signerA,
channelState,
chainReader as IVectorChainReader,
messaging,
);
expect(ret.isError).to.be.false;
expect(ret.getValue().meta.quote).to.containSubset({
signature: undefined,
chainId: channelState.networkContext.chainId,
routerIdentifier: signerA.publicIdentifier,
amount: params.amount,
assetId: params.assetId,
recipient: params.recipient!,
recipientChainId: params.recipientChainId!,
recipientAssetId: params.recipientAssetId!,
fee: "0",
});
expect(messaging.sendTransferQuoteMessage.callCount).to.be.eq(0);
});
it("should fail if quote.fee is larger than transfer amount", async () => {
const params = generateParams();
const { channel: channelState } = createTestChannelState(UpdateType.deposit, {
channelAddress: params.channelAddress,
networkContext: {
...chainAddresses[chainId],
chainId,
providerUrl,
},
});
params.quote = {
signature: undefined,
chainId,
routerIdentifier: channelState.aliceIdentifier,
amount: params.amount,
assetId: params.assetId,
recipient: params.recipient!,
recipientChainId: params.recipientChainId!,
recipientAssetId: params.recipientAssetId!,
fee: "10000000",
expiry: (Date.now() + 30_000).toString(),
};
const ret = await convertConditionalTransferParams(
params,
signerA,
channelState,
chainReader as IVectorChainReader,
messaging,
);
expect(ret.isError).to.be.true;
expect(ret.getError()?.message).to.be.eq(ParameterConversionError.reasons.FeeGreaterThanAmount);
});
it("should fail if params.type is an address and chainReader.getRegisteredTransferByDefinition fails", async () => {
const params = generateParams();
const chainErr = new ChainError("Failure");
chainReader.getRegisteredTransferByDefinition.resolves(Result.fail(chainErr));
// Set incorrect type
params.type = getRandomAddress();
const { channel: channelState } = createTestChannelState(UpdateType.deposit, {
channelAddress: params.channelAddress,
networkContext: {
...chainAddresses[chainId],
chainId,
providerUrl,
},
});
const ret = await convertConditionalTransferParams(
params,
signerA,
channelState,
chainReader as IVectorChainReader,
messaging,
);
expect(ret.isError).to.be.true;
const err = ret.getError();
expect(err?.message).to.be.eq(ParameterConversionError.reasons.FailedToGetRegisteredTransfer);
expect(err?.context.channelAddress).to.be.eq(channelState.channelAddress);
expect(err?.context.publicIdentifier).to.be.eq(signerA.publicIdentifier);
expect(err?.context.params).to.be.deep.eq(params);
expect(err?.context.registryError).to.be.deep.eq(jsonifyError(chainErr));
});
it("should fail if initiator is receiver for same chain/network", async () => {
const params = generateParams(true);
const channelState: FullChannelState = createTestChannelStateWithSigners([signerA, signerB], "deposit", {
channelAddress: params.channelAddress,
networkContext: {
...chainAddresses[chainId],
chainId,
providerUrl,
},
});
const ret = await convertConditionalTransferParams(
params,
signerB,
channelState,
chainReader as IVectorChainReader,
messaging,
);
expect(ret.isError).to.be.true;
const err = ret.getError();
expect(err?.message).to.be.eq(ParameterConversionError.reasons.CannotSendToSelf);
expect(err?.context.channelAddress).to.be.eq(channelState.channelAddress);
expect(err?.context.publicIdentifier).to.be.eq(signerB.publicIdentifier);
expect(err?.context.params).to.be.deep.eq(params);
});
const runTest = (params: any, result: CreateTransferParams, isUserA: boolean) => {
expect(result).to.containSubset({
channelAddress: params.channelAddress,
balance: {
amount: [params.amount, "0"],
to: isUserA ? [signerA.address, signerB.address] : [signerB.address, signerA.address],
},
assetId: getAddress(params.assetId),
transferDefinition: transferRegisteredInfo.definition,
transferInitialState: {
lockHash: params.details.lockHash,
expiry: params.details.expiry,
},
timeout: params.timeout,
meta: {
requireOnline: true,
routingId: params.meta!.routingId,
path: [
{
recipientAssetId: params.recipientAssetId,
recipientChainId: params.recipientChainId,
recipient: params.recipient,
},
],
quote: {
fee: isUserA ? "0" : transferFee,
routerIdentifier: signerA.publicIdentifier,
amount: params.amount,
assetId: params.assetId,
chainId,
recipientAssetId: params.recipientAssetId,
recipientChainId: params.recipientChainId,
recipient: params.recipient,
signature: isUserA ? undefined : "success",
},
...params.meta!,
},
});
};
const testSetup = async (params: any, isUserA: boolean) => {
const channelState: FullChannelState = createTestChannelStateWithSigners([signerA, signerB], UpdateType.deposit, {
channelAddress: params.channelAddress,
networkContext: {
...chainAddresses[chainId],
chainId,
providerUrl,
},
});
setMessagingStub(params, isUserA);
const result = isUserA
? await convertConditionalTransferParams(
params,
signerA,
channelState,
chainReader as IVectorChainReader,
messaging,
)
: await convertConditionalTransferParams(
params,
signerB,
channelState,
chainReader as IVectorChainReader,
messaging,
);
return result;
};
const users = ["A", "B"];
for (const user of users) {
let isUserA = false;
if (user === "A") {
isUserA = true;
}
describe(`should work for ${user}`, () => {
it("should work with provided params.recipientChainId", async () => {
const params = { ...generateParams(), recipientChainId: 2 };
const result = await testSetup(params, isUserA);
runTest(params, result.getValue(), isUserA);
});
it("should work with default params.recipientChainId", async () => {
const params = { ...generateParams(), recipientChainId: undefined };
const result = await testSetup(params, isUserA);
const expectedParams = { ...params, recipientChainId: chainId };
runTest(expectedParams, result.getValue(), isUserA);
});
it("should work with provided params.timeout", async () => {
const params = { ...generateParams(), timeout: "100000" };
const result = await testSetup(params, isUserA);
runTest(params, result.getValue(), isUserA);
});
it("should work with default params.timeout", async () => {
const params = { ...generateParams(), timeout: undefined };
const result = await testSetup(params, isUserA);
const expectedParams = { ...params, timeout: DEFAULT_TRANSFER_TIMEOUT.toString() };
runTest(expectedParams, result.getValue(), isUserA);
});
it("should work with provided params.recipientAssetId", async () => {
const params = { ...generateParams(), recipientAssetId: AddressZero };
const result = await testSetup(params, isUserA);
runTest(params, result.getValue(), isUserA);
});
it("should work with provided params.assetId", async () => {
const params = { ...generateParams(), assetId: AddressZero };
const result = await testSetup(params, isUserA);
runTest(params, result.getValue(), isUserA);
});
it("should work with in-channel recipient", async () => {
const params = { ...generateParams() };
const result = await testSetup(params, isUserA);
runTest(params, result.getValue(), isUserA);
});
it("should work with out-of-channel recipient", async () => {
const params = generateParams(false);
const result = await testSetup(params, isUserA);
runTest(params, result.getValue(), isUserA);
});
it("should work for A with out-of-channel recipient and given routingId", async () => {
let params = generateParams(false);
params = {
...params,
recipient: getRandomIdentifier(),
meta: { ...params.meta, routingId: getRandomBytes32() },
};
const result = await testSetup(params, isUserA);
runTest(params, result.getValue(), isUserA);
});
it("should work when params.type is a name", async () => {
const params = { ...generateParams(), type: TransferNames.Withdraw };
const result = await testSetup(params, isUserA);
runTest(params, result.getValue(), isUserA);
});
it("should work when params.type is an address (transferDefinition)", async () => {
const params = { ...generateParams(), type: getRandomBytes32() };
const result = await testSetup(params, isUserA);
runTest(params, result.getValue(), isUserA);
});
});
}
});
describe("convertResolveConditionParams", () => {
const generateParams = (): EngineParams.ResolveTransfer => {
setDefaultStubs();
return {
channelAddress: mkAddress("0xa"),
transferId: getRandomBytes32(),
transferResolver: {
preImage: getRandomBytes32(),
},
meta: {
message: "test",
},
};
};
it("should work", async () => {
const params = generateParams();
const transferState: FullTransferState = createTestFullHashlockTransferState({
channelAddress: params.channelAddress,
});
const ret: ResolveTransferParams = convertResolveConditionParams(params, transferState).getValue();
expect(ret).to.deep.eq({
channelAddress: params.channelAddress,
transferId: transferState.transferId,
transferResolver: {
preImage: params.transferResolver.preImage,
},
meta: {
...transferState.meta,
...params.meta,
},
});
});
});
describe("convertWithdrawParams", () => {
const quoteFee = "3";
const generateParams = () => {
setDefaultStubs(withdrawRegisteredInfo);
const params = {
channelAddress: mkAddress("0xa"),
amount: "8",
assetId: mkAddress("0x0"),
recipient: mkAddress("0xb"),
callTo: AddressZero,
callData: "0x",
};
return params;
};
const generateChainData = (params, channel, isUserA) => {
const commitment = new WithdrawCommitment(
channel.channelAddress,
channel.alice,
channel.bob,
params.recipient,
params.assetId,
params.amount,
channel.nonce.toString(),
);
return commitment.hashToSign();
};
const testSetup = async (params: any, isUserA: boolean) => {
const channelState = createTestChannelStateWithSigners([signerA, signerB], UpdateType.deposit, {
channelAddress: params.channelAddress,
networkContext: {
...chainAddresses[chainId],
chainId,
providerUrl,
},
});
const result = isUserA
? await convertWithdrawParams(
params,
signerA,
channelState,
chainAddresses,
chainReader as IVectorChainReader,
messaging,
)
: await convertWithdrawParams(
params,
signerB,
channelState,
chainAddresses,
chainReader as IVectorChainReader,
messaging,
);
return { channelState, result };
};
const runTest = async (
params: any,
channelState: FullChannelState,
result: CreateTransferParams,
isUserA: boolean,
) => {
const withdrawHash = generateChainData(params, channelState, isUserA);
const signature = isUserA ? await signerA.signMessage(withdrawHash) : await signerB.signMessage(withdrawHash);
expect(result).to.containSubset({
channelAddress: channelState.channelAddress,
balance: {
amount: [params.amount, "0"],
to: isUserA
? [getAddress(params.recipient), channelState.bob]
: [getAddress(params.recipient), channelState.alice],
},
assetId: getAddress(params.assetId),
transferDefinition: withdrawRegisteredInfo.definition,
transferInitialState: {
initiatorSignature: signature,
initiator: isUserA ? signerA.address : signerB.address,
responder: isUserA ? signerB.address : signerA.address,
data: withdrawHash,
nonce: channelState.nonce.toString(),
fee: "0",
callTo: params.callTo ?? AddressZero,
callData: params.callData ?? "0x",
},
timeout: params.timeout ?? DEFAULT_TRANSFER_TIMEOUT.toString(),
});
expect(result.meta).to.containSubset({
initiatorSubmits: false,
withdrawNonce: channelState.nonce.toString(),
quote: {
channelAddress: params.channelAddress,
amount: params.amount,
assetId: params.assetId,
fee: "0",
},
});
if (!isUserA) {
// expect(result.meta.quote.signature).to.be.ok;
}
};
it("should fail if signer fails to sign message", async () => {
const params = generateParams();
signerA.signMessage.rejects(new Error("fail"));
const { result } = await testSetup(params, true);
expect(result.isError).to.be.true;
expect(result.getError()).to.contain(new Error(`${signerA.publicIdentifier} failed to sign: fail`));
});
it("should fail if it cannot get registry information", async () => {
const params = generateParams();
const chainErr = new ChainError("Failure");
chainReader.getRegisteredTransferByName.resolves(Result.fail(chainErr));
const { channelState, result } = await testSetup(params, true);
expect(result.isError).to.be.true;
const err = result.getError();
expect(err?.message).to.be.eq(ParameterConversionError.reasons.FailedToGetRegisteredTransfer);
expect(err?.context.channelAddress).to.be.eq(channelState.channelAddress);
expect(err?.context.publicIdentifier).to.be.eq(signerA.publicIdentifier);
expect(err?.context.params).to.be.deep.eq(params);
expect(err?.context.registryError).to.be.deep.eq(jsonifyError(chainErr));
});
const users = ["A", "B"];
for (const user of users) {
const isUserA = user === "A";
describe(`should work for ${user}`, () => {
it("should work with provided params.callTo", async () => {
const params = { ...generateParams(), callTo: AddressZero };
const { channelState, result } = await testSetup(params, isUserA);
await runTest(params, channelState, result.getValue(), isUserA);
});
it("should work without provided params.callTo", async () => {
const params = { ...generateParams(), callTo: undefined };
const { channelState, result } = await testSetup(params, isUserA);
const expectedParams = { ...generateParams(), callTo: AddressZero };
await runTest(expectedParams, channelState, result.getValue(), isUserA);
});
it("should work with provided params.callData", async () => {
const params = { ...generateParams(), callData: "0x" };
const { channelState, result } = await testSetup(params, isUserA);
await runTest(params, channelState, result.getValue(), isUserA);
});
it("should work without provided params.callData", async () => {
const params = { ...generateParams(), callData: undefined };
const { channelState, result } = await testSetup(params, isUserA);
const expectedParams = { ...generateParams(), callData: "0x" };
await runTest(expectedParams, channelState, result.getValue(), isUserA);
});
it("should work with provided params.timeout", async () => {
const params = { ...generateParams(), timeout: "100000" };
const { channelState, result } = await testSetup(params, isUserA);
runTest(params, channelState, result.getValue(), isUserA);
});
it("should work with default params.timeout", async () => {
const params = { ...generateParams(), timeout: undefined };
const { channelState, result } = await testSetup(params, isUserA);
const expectedParams = { ...params, timeout: DEFAULT_TRANSFER_TIMEOUT.toString() };
runTest(expectedParams, channelState, result.getValue(), isUserA);
});
});
}
});
}); | the_stack |
import {Component, EventEmitter, Output, ViewChild} from '@angular/core';
import { Observable } from 'rxjs';
import { Store } from '@ngrx/store';
import * as sqlQueryActions from '../../shared/actions/query.actions';
import * as sqlCancelActions from '../../shared/actions/cancel.actions';
import * as appActions from '../../shared/actions/app.actions'
import * as dataverseActions from '../../shared/actions/dataverse.actions'
import * as CodeMirror from 'codemirror';
import 'codemirror/addon/edit/closebrackets';
import 'codemirror/mode/sql/sql';
import 'codemirror/addon/hint/show-hint';
import 'codemirror/addon/hint/sql-hint';
/*
* Query component
* has editor (codemirror)
*/
@Component({
moduleId: module.id,
selector: 'awc-query',
templateUrl: 'input.component.html',
styleUrls: ['input.component.scss']
})
export class InputQueryComponent {
@Output() inputToOutputEmitter: EventEmitter<Object> = new EventEmitter<Object>();
@Output() isErrorEmitter: EventEmitter<Boolean> = new EventEmitter<Boolean>();
@Output() hideOutputEmitter: EventEmitter<Boolean> = new EventEmitter<Boolean>();
currentQuery = 0;
queryString: string = "";
metricsString: {};
queryErrorMessageString: string = "";
collapse = false;
input_expanded_icon = 'expand_less';
queryRequest: any;
queryPrepare: any;
queryMetrics$: Observable <any> ;
queryMetrics: {};
querySuccess$: Observable <any> ;
querySuccess: Boolean = false;
querySuccessWarnings: Boolean = false;
queryWarnings: any;
queryWarnings$: Observable<any> ;
queryWarningsMessages: string[] = [];
queryWarningsCount = 0;
queryWarningsShow: Boolean = false;
queryError$: Observable <any> ;
queryError: Boolean = false;
queryErrorMessage$: Observable <any> ;
queryErrorMessages: {};
queryPrepared$: Observable <any> ;
queryPrepared: {};
queryPlanFormats$: Observable <any> ;
queryPlanFormats: {};
cancelQuery$: Observable<any>;
isCanceled: boolean = false;
preparedQueryCount: number;
previousDisabled = true;
nextDisabled = true;
querySuccesResults: any;
querySpinnerVisible: boolean = false;
dataverses$: Observable<any>;
dataverses: any;
defaultDataverse = 'Default';
selected = 'Default';
history = [];
currentHistory = 0;
viewCurrentHistory = 0; // for the view
sideMenuVisible$: Observable<any>;
sideMenuVisible: any;
none = 'None';
planFormat = 'JSON';
historyStringSelected = '';
historyIdxSelected = 0;
formatOptions = 'JSON';
outputOptions = 'JSON';
explainMode = false;
inputToOutput = {};
objectsReturned = 0;
/* Codemirror configuration */
//sql++ keywords
sqlppKeywords = "alter and as asc between by count create delete desc distinct drop from group having in insert into " +
"is join like not on or order select set union update values where limit use let dataverse dataset exists with index type" +
"inner outer offset value type if exists declare function explain";
//sql++ builtin types
sqlppTypes = "boolean tinyint smallint integer int bigint string float double binary point line rectangle circle polygon" +
"uuid object array multiset date time datetime duration year_month_duration day_time_duration interval"
constructor(private store: Store < any > ) {
this.currentQuery = 0;
this.querySuccess$ = this.store.select(s => s.sqlQuery.successHash);
this.querySuccess$.subscribe((data: any) => {
this.isCanceled = false;
this.querySuccesResults = data;
this.querySpinnerVisible = false;
if (data != undefined && data[this.currentQuery] === true) {
this.querySuccess = true;
} else {
this.querySuccess = false;
}
})
/* Watching for SQL Input Errors in current Query */
this.queryError$ = this.store.select(s => s.sqlQuery.errorHash);
this.queryError$.subscribe((data: any) => {
this.querySpinnerVisible = false;
if (data != undefined && data[this.currentQuery] === true) {
this.queryError = true;
this.showErrors();
} else {
this.queryError = false;
}
})
/* Watching for Queries that are in prepared state,
* those are SQL strings that still has not been executed
*/
this.queryPrepared$ = this.store.select(s => s.sqlQuery.sqlQueryPrepared);
this.queryPrepared$.subscribe((data: any) => {
if (data) {
this.queryPrepared = data;
this.preparedQueryCount = Object.keys(this.queryPrepared).length;
if (this.queryPrepared && this.queryPrepared[this.currentQuery]) {
this.queryString = this.queryPrepared[this.currentQuery];
}
} else {
this.queryPrepared = {};
}
})
/* Watching for Metrics */
this.queryMetrics$ = this.store.select(s => s.sqlQuery.sqlQueryMetrics);
this.queryMetrics$.subscribe((data: any) => {
if (data != undefined) {
this.queryMetrics = Object.assign(data);
if (this.queryMetrics && this.queryMetrics[this.currentQuery]) {
this.objectsReturned = this.queryMetrics[this.currentQuery].resultCount;
this.isErrorEmitter.emit(false);
this.hideOutputEmitter.emit(false);
this.metricsString = "SUCCESS: ";
if ('warningCount' in this.queryMetrics[this.currentQuery]) {
this.metricsString += " (WITH " + this.queryMetrics[this.currentQuery].warningCount + " WARNINGS)";
}
this.metricsString += " Execution time: " + this.queryMetrics[this.currentQuery].executionTime;
this.metricsString += " Elapsed time: " + this.queryMetrics[this.currentQuery].elapsedTime;
this.metricsString += " Size: " + (this.queryMetrics[this.currentQuery].resultSize/1024).toFixed(2) + ' Kb';
}
} else {
this.queryMetrics = {};
this.objectsReturned = 0;
}
})
/* Watching for SQL Input Errors: Error Message stored in Query Cache */
this.queryErrorMessage$ = this.store.select(s => s.sqlQuery.sqlQueryErrorHash);
this.queryErrorMessage$.subscribe((data: any) => {
if (data) {
this.queryErrorMessages = data;
this.showErrors();
} else {
this.queryErrorMessages = {};
}
})
/* Watching for SQL Input Warnings in current Query*/
this.queryWarnings$ = this.store.select(s => s.sqlQuery.sqlQueryWarnings);
this.queryWarnings$.subscribe((data: any) => {
if (data) {
this.queryWarnings = data;
this.showWarnings();
} else {
this.queryWarnings = {};
}
})
/*
* Watching for SQL Cancel Query
*/
this.cancelQuery$ = this.store.select(s => s.cancelQuery.success);
this.cancelQuery$.subscribe((data: any) => {
if (data) {
this.querySpinnerVisible = false;
this.isCanceled = true;
}
})
/* Watching for SQL Input Errors: Error Message stored in Query Cache */
this.queryPlanFormats$ = this.store.select(s => s.sqlQuery.sqlQueryPlanFormatHash);
this.queryPlanFormats$.subscribe((data: any) => {
if (data) {
this.queryPlanFormats = data;
} else {
this.queryPlanFormats = {};
}
})
this.preparedQueryCount = 0;
// Initialize Query Editor, prepare the default query
this.saveQuery(String(this.currentQuery), this.queryString, this.formatOptions, "JSON");
// lets inform other views what's the current SQL editor
this.store.dispatch(new appActions.setEditorIndex(String(this.currentQuery)));
}
ngOnInit() {
this.dataverses$ = this.store.select(s => s.dataverse.dataverses.results);
// Watching for Dataverses
this.dataverses$ = this.store.select(s => s.dataverse.dataverses.results);
this.dataverses$.subscribe((data: any[]) => {
this.dataverses = data;
this.defaultDataverse = ''
});
this.store.dispatch(new dataverseActions.SelectDataverses('-'), );
}
showMetrics() {
this.querySuccess = false;
if (this.queryMetrics && this.queryMetrics[this.currentQuery] && this.querySuccesResults[this.currentQuery]) {
this.objectsReturned = this.queryMetrics[this.currentQuery].resultCount;
this.metricsString = "SUCCESS: ";
if ('warningCount' in this.queryMetrics[this.currentQuery]) {
this.metricsString += " [WITH " + this.queryMetrics[this.currentQuery].warningCount + " WARNING(S)]";
}
this.metricsString += " Execution time: " + this.queryMetrics[this.currentQuery].executionTime;
this.metricsString += " Elapsed time: " + this.queryMetrics[this.currentQuery].elapsedTime;
this.metricsString += " Size: " + (this.queryMetrics[this.currentQuery].resultSize/1024).toFixed(2) + ' Kb';
this.querySuccess = true;
}
}
showWarnings() {
this.queryWarningsShow = false;
if (this.queryWarnings && this.queryWarnings[this.currentQuery]) {
let warningObject = this.queryWarnings[this.currentQuery];
this.queryWarningsMessages = [];
this.queryWarningsCount = warningObject.length;
if (warningObject.length != 0) {
for (let warning of warningObject.reverse()) {
let warningString = "WARNING: Code: " + JSON.stringify(warning.code, null, 8);
warningString += " " + JSON.stringify(warning.msg, null, 8);
this.queryWarningsMessages.push(warningString);
}
this.queryWarningsShow = true;
}
}
}
showErrors() {
this.queryError = false;
if (this.queryErrorMessages && this.queryErrorMessages[this.currentQuery]) {
let errorObject = this.queryErrorMessages[this.currentQuery];
if (errorObject.length != 0) {
this.queryErrorMessageString = "ERROR: Code: " + JSON.stringify(errorObject[0].code, null, 8);
this.queryErrorMessageString += " " + JSON.stringify(errorObject[0].msg, null, 8);
this.queryError = true;
this.isErrorEmitter.emit(true);
}
}
}
getQueryResults(queryString: string, planFormat: string, outputFormat: string) {
let QueryOrder = this.currentQuery;
this.queryRequest = {
requestId: String(QueryOrder),
queryString: queryString,
planFormat: planFormat,
format: outputFormat
};
this.store.dispatch(new sqlQueryActions.ExecuteQuery(this.queryRequest));
this.querySpinnerVisible = true;
}
onClickExplain() {
//for future use...currently we do not support explaining for INSERT, UPDATE, or DELETE
/*
let insert_regex = /insert/i;
let update_regex = /update/i;
let delete_regex = /delete/i;
*/
let select_regex = /select/i;
let explainString = "";
if (select_regex.test(this.queryString))
explainString = this.queryString.replace(select_regex, "explain $& ");
else
explainString = "explain " + this.queryString;
this.runQuery(explainString, true);
this.explainMode = true;
this.sendInputToOutput();
}
onClickRun() {
this.explainMode = false;
this.sendInputToOutput();
this.runQuery(this.queryString, this.explainMode);
}
runQuery(stringToRun: string, isExplain: boolean) {
this.autodetectDataverse();
if (this.queryString != this.queryPrepared[Object.keys(this.queryPrepared).length - 1]) {
//not the same query as before, currentQuery needs to be incremented and another needs to be dispatched
//increment currentQuery
if (this.queryPrepared[Object.keys(this.queryPrepared).length - 1] != '')
this.currentQuery = Object.keys(this.queryPrepared).length;
this.saveQuery(String(this.currentQuery), this.queryString, this.formatOptions, this.outputOptions);
this.history.unshift({query: this.queryString, index: this.currentQuery});
//this.currentHistory = this.history.length - 1;
//this.viewCurrentHistory = this.history.length;
//display
let currentQueryIndex = String(this.currentQuery);
this.store.dispatch(new appActions.setEditorIndex(currentQueryIndex));
this.editor.focus();
} else {
//the same query as before, currentQuery is not incremented
//save the current Query
this.saveQuery(String(this.currentQuery), this.queryString, this.formatOptions, this.outputOptions);
}
let planFormat = this.formatOptions;
let outputFormat = this.outputOptions;
this.historyIdxSelected = this.currentQuery;
this.getQueryResults(stringToRun, planFormat, outputFormat); // .replace(/\n/g, " "));
}
onClickStop() {
let cancel_request = {
requestId: String(this.currentQuery)
}
this.store.dispatch(new sqlCancelActions.CancelQuery(cancel_request));
}
onClickNew() {
// Saving first
this.saveQuery(String(this.currentQuery), this.queryString, this.formatOptions, this.outputOptions);
//let output section know to hide
this.hideOutputEmitter.emit(true);
this.historyIdxSelected = -1;
// Prepare a new Query String, cleanup screen messages
this.currentQuery = Object.keys(this.queryPrepared).length;
this.queryString = "";
this.editor.getDoc().setValue(this.queryString);
this.queryErrorMessageString = "";
this.metricsString = "";
this.querySuccess = false;
this.queryError = false;
this.queryWarningsShow = false;
this.saveQuery(String(this.currentQuery), "", this.formatOptions, this.outputOptions);
// lets inform other views what's the current SQL editor
let currentQueryIndex = String(this.currentQuery);
this.store.dispatch(new appActions.setEditorIndex(currentQueryIndex));
this.selected = "Default";
this.editor.focus();
}
onClickClear() {
let queryClear = {
editorId: String(this.currentQuery),
queryString: "",
planFormat: "JSON"
};
this.store.dispatch(new sqlQueryActions.CleanQuery(queryClear));
this.queryErrorMessageString = "";
this.queryString = "";
this.metricsString = "";
this.queryWarningsCount = 0;
this.queryWarningsMessages = [];
this.dataverseSelected();
this.editor.getDoc().setValue(this.queryString);
this.editor.execCommand('goDocEnd')
this.editor.focus();
//hide output on clear
this.hideOutputEmitter.emit(true);
}
onClickPrevious() {
if (this.currentQuery > 0) {
this.nextSQLEditor(this.currentQuery - 1);
}
}
onClickNext() {
if (this.currentQuery < this.preparedQueryCount - 1) {
this.nextSQLEditor(this.currentQuery + 1);
}
else {
if (this.queryString != '') {
this.onClickNew();
}
}
}
checkNext() {
if (this.currentQuery == this.preparedQueryCount) {
return true;
} else {
return false;
}
}
checkPrevious() {
if (this.currentQuery == 0) {
return true;
} else {
return false;
}
}
nextSQLEditor(next) {
// Saving First
this.saveQuery(String(this.currentQuery), this.queryString, this.formatOptions, this.outputOptions);
//this.currentQuery = this.currentQuery + next;
this.currentQuery = next;
this.queryErrorMessageString = "";
this.metricsString = "";
// Retrieve Metrics or Error Message if Query was executed
this.showMetrics();
// Retrieve Metrics or Error Message if Query was executed
this.showErrors();
// Retrieve the prepared SQL string
this.queryString = this.queryPrepared[this.currentQuery];
this.editor.getDoc().setValue(this.queryString);
// Select the query from the QUERY History
this.historyIdxSelected = this.currentQuery;
this.autodetectDataverse();
// Retrieve the prepared SQL plan Format
this.formatOptions = this.queryPlanFormats[this.currentQuery];
// lets inform other views what's the current SQL editor
let currentQueryIndex = String(this.currentQuery);
// Inform the app we are now active in next editor
this.store.dispatch(new appActions.setEditorIndex(currentQueryIndex));
}
onClickInputCardCollapse() {
this.collapse = !this.collapse;
if (this.collapse) {
this.input_expanded_icon = 'expand_more';
} else {
this.input_expanded_icon = 'expand_less';
}
}
/**
* On component view init
*/
@ViewChild('editor') editor: CodeMirror.Editor;
ngAfterViewInit() {
this.codemirrorInit();
}
/**
* Initialize codemirror
*/
codemirrorInit() {
this.editor = CodeMirror.fromTextArea(this.editor.nativeElement, {
mode: {
name: "sql",
keywords: this.set(this.sqlppKeywords),
builtin: this.set(this.sqlppTypes),
atoms: this.set("true false null missing"),
dateSQL: this.set("date time datetime duration year_month_duration day_time_duration interval"),
support: this.set("ODBCdotTable doubleQuote binaryNumber hexNumber commentSlashSlash")
},
lineWrapping: true,
showCursorWhenSelecting: true,
autofocus: true,
lineNumbers: true,
autoCloseBrackets: {
pairs: "()[]{}''\"\"``",
closeBefore: ")]}'\":;>",
triples: "",
explode: "[]{}()",
override: true
},
extraKeys: {"Ctrl-Space": "autocomplete"},
hint: CodeMirror.hint.sql,
});
this.editor.setSize(null, 'auto');
this.editor.getDoc().setValue(this.queryString);
this.editor.on('changes', () => {
this.queryString = this.editor.getValue();
});
}
dataverseSelected() {
if (this.selected == undefined) {
this.queryString = 'None';
} else if (this.selected === 'None' || this.selected === 'Default') {
this.queryString = '';
this.selected = 'Default';
} else {
this.queryString = 'USE ' + this.selected + '; \n';
}
this.editor.getDoc().setValue(this.queryString);
this.editor.execCommand('goDocEnd')
this.editor.focus();
}
historySelected(idx: number) {
if (this.historyStringSelected == undefined) {
this.historyStringSelected = '';
} else if (this.historyStringSelected === 'Clear') {
this.history = [];
this.historyStringSelected = '';
}
this.nextSQLEditor(idx);
}
planFormatSelected() {}
onClickNextHistory() {
if (this.currentHistory < this.history.length - 1) {
this.currentHistory++;
this.viewCurrentHistory++;
this.queryString = this.history[this.currentHistory];
this.editor.getDoc().setValue(this.queryString);
this.editor.focus();
}
}
onClickPrevHistory() {
if (this.currentHistory > 0) {
this.currentHistory--;
this.viewCurrentHistory--;
this.queryString = this.history[this.currentHistory];
this.editor.getDoc().setValue(this.queryString);
this.editor.focus();
}
}
saveQuery(editorId, queryString, planFormat, outputFormat) {
this.queryPrepare = {
editorId: String(editorId),
queryString: queryString,
planFormat: planFormat,
format: outputFormat
};
this.store.dispatch(new sqlQueryActions.PrepareQuery(this.queryPrepare));
}
sendInputToOutput() {
this.inputToOutput['isExplain'] = this.explainMode;
this.inputToOutput['outputFormat'] = this.outputOptions;
this.inputToOutputEmitter.emit(this.inputToOutput);
}
autodetectDataverse() {
let dataverseRegex = /use (.*?);/i
let matches = this.queryString.match(dataverseRegex);
let detectedDataverse = "";
if (matches) {
if (matches.length == 2) {
detectedDataverse = matches[1];
}
}
if (detectedDataverse != "") {
let dataverseNames = this.dataverses.map(function (e) {
return e.DataverseName
});
if (dataverseNames.includes(detectedDataverse)) {
this.selected = detectedDataverse;
} else {
this.selected = "Default";
}
} else {
this.selected = "Default";
}
}
set(str: string) {
let obj = {};
let words = str.split(" ");
for (let i = 0; i < words.length; i++) {
obj[words[i]] = true;
}
return obj;
}
} | the_stack |
import { disconnect } from 'process';
import * as vscode from 'vscode';
import { LanguageClient } from 'vscode-languageclient/node';
import { NbLanguageClient } from './extension';
import { NodeChangedParams, NodeInfoNotification, NodeInfoRequest } from './protocol';
const doLog : boolean = false;
export class TreeViewService extends vscode.Disposable {
private handler : vscode.Disposable | undefined;
private client : NbLanguageClient;
private trees : Map<string, vscode.TreeView<Visualizer>> = new Map();
private images : Map<number, vscode.Uri> = new Map();
private providers : Map<number, VisualizerProvider> = new Map();
log : vscode.OutputChannel;
constructor (log : vscode.OutputChannel, c : NbLanguageClient, disposeFunc : () => void) {
super(() => { this.disposeAllViews(); disposeFunc(); });
this.log = log;
this.client = c;
}
getClient() : NbLanguageClient {
return this.client;
}
private disposeAllViews() : void {
for (let tree of this.trees.values()) {
tree.dispose();
}
for (let provider of this.providers.values()) {
provider.dispose();
}
this.trees.clear();
this.providers.clear();
this.handler?.dispose();
}
public async createView(id : string, title? : string, options? :
Partial<vscode.TreeViewOptions<any> & {
providerInitializer : (provider : CustomizableTreeDataProvider<Visualizer>) => void }
>) : Promise<vscode.TreeView<Visualizer>> {
let tv : vscode.TreeView<Visualizer> | undefined = this.trees.get(id);
if (tv) {
return tv;
}
const res = await createViewProvider(this.client, id);
this.providers.set(res.getRoot().data.id, res);
options?.providerInitializer?.(res)
let opts : vscode.TreeViewOptions<Visualizer> = {
treeDataProvider : res,
canSelectMany: true,
showCollapseAll: true,
}
if (options?.canSelectMany !== undefined) {
opts.canSelectMany = options.canSelectMany;
}
if (options?.showCollapseAll !== undefined) {
opts.showCollapseAll = options.showCollapseAll;
}
let view = vscode.window.createTreeView(id, opts);
this.trees.set(id, view);
// this will replace the handler over and over, but never mind
this.handler = this.client.onNotification(NodeInfoNotification.type, params => this.nodeChanged(params));
return view;
}
private nodeChanged(params : NodeChangedParams) : void {
let p : VisualizerProvider | undefined = this.providers.get(params.rootId);
if (p) {
p.refresh(params);
}
}
imageUri(nodeData : NodeInfoRequest.Data) : vscode.Uri | undefined {
if (nodeData.iconUri) {
const uri : vscode.Uri = vscode.Uri.parse(nodeData.iconUri)
this.images.set(nodeData.iconIndex, uri);
return uri;
} else {
return this.images.get(nodeData.iconIndex);
}
}
}
export interface TreeItemDecorator<T> extends vscode.Disposable {
decorateTreeItem(element: T, item : vscode.TreeItem): vscode.TreeItem | Thenable<vscode.TreeItem>;
}
export interface CustomizableTreeDataProvider<T> extends vscode.TreeDataProvider<T> {
fireItemChange(item? : T) : void;
addItemDecorator(deco : TreeItemDecorator<T>) : vscode.Disposable;
}
class VisualizerProvider extends vscode.Disposable implements CustomizableTreeDataProvider<Visualizer> {
private root: Visualizer;
private treeData : Map<number, Visualizer> = new Map();
private decorators : TreeItemDecorator<Visualizer>[] = [];
constructor(
private client: LanguageClient,
private ts : TreeViewService,
private log : vscode.OutputChannel,
id : string,
rootData : NodeInfoRequest.Data
) {
super(() => this.disconnect());
this.root = new Visualizer(rootData, ts.imageUri(rootData));
this.treeData.set(rootData.id, this.root);
}
private _onDidChangeTreeData: vscode.EventEmitter<Visualizer | undefined | null | void> = new vscode.EventEmitter<Visualizer | undefined | null | void>();
readonly onDidChangeTreeData: vscode.Event<Visualizer | undefined | null | void> = this._onDidChangeTreeData.event;
private disconnect() : void {
// nothing at the moment.
for (let deco of this.decorators) {
deco.dispose();
}
}
fireItemChange(item : Visualizer | undefined) : void {
if (doLog) {
this.log.appendLine(`Firing change on ${item?.idstring()}`);
}
if (!item || item == this.root) {
this._onDidChangeTreeData.fire();
} else {
this._onDidChangeTreeData.fire(item);
}
}
addItemDecorator(decoInstance : TreeItemDecorator<Visualizer>) : vscode.Disposable {
this.decorators.push(decoInstance);
const self = this;
return new vscode.Disposable(() => {
const idx = this.decorators.indexOf(decoInstance);
if (idx > 0) {
this.decorators.splice(idx, 1);
decoInstance.dispose();
}
});
}
refresh(params : NodeChangedParams): void {
if (this.root.data.id === params.rootId) {
let v : Visualizer | undefined;
if (this. root.data.id == params.nodeId || !params.nodeId) {
v = this.root;
} else {
v = this.treeData.get(params.nodeId);
}
if (v) {
if (this.delayedFire.has(v)) {
if (doLog) {
this.log.appendLine(`Delaying change on ${v.idstring()}`);
}
v.pendingChange = true;
} else {
this.fireItemChange(v);
}
}
}
}
getRoot() : Visualizer {
return this.root.copy();
}
getTreeItem(element: Visualizer): vscode.TreeItem | Thenable<vscode.TreeItem> {
const n : number = Number(element.id);
const self = this;
if (doLog) {
this.log.appendLine(`Doing getTreeItem on ${element.idstring()}`);
}
return this.wrap(async (arr) => {
let fetched = await this.queryVisualizer(element, arr, () => this.fetchItem(n));
element.update(fetched);
return self.getTreeItem2(fetched);
});
}
/**
* Wraps code that queries individual Visualizers so that blocked changes are fired after
* the code terminated.
*
* Usage:
* wrap(() => { ... code ... ; queryVisualizer(vis, () => { ... })});
* @param fn the code to execute
* @returns value of the code function
*/
async wrap<X>(fn : (pending : Visualizer[]) => Thenable<X>) : Promise<X> {
let arr : Visualizer[] = [];
try {
return await fn(arr);
} finally {
this.releaseVisualizersAndFire(arr);
}
}
/**
* Just creates a string list from visualizer IDs. Diagnostics only.
*/
private visualizerList(arr : Visualizer[]) : string {
let s = "";
for (let v of arr) {
s += v.idstring() + " ";
}
return s;
}
/**
* Do not use directly, use wrap(). Fires delayed events for visualizers that have no pending queries.
*/
private releaseVisualizersAndFire(list : Visualizer[] | undefined) {
if (!list) {
list = Array.from(this.delayedFire);
}
if (doLog) {
this.log.appendLine(`Done with ${this.visualizerList(list)}`);
}
// v can be in list several times, each push increased its counter, so we need to decrease it.
for (let v of list) {
if (this.treeData?.get(Number(v.id || -1)) === v) {
if (--v.pendingQueries) {
if (doLog) {
this.log.appendLine(`${v.idstring()} has pending ${v.pendingQueries} queries`);
}
continue;
}
if (v.pendingChange) {
if (doLog) {
this.log.appendLine(`Fire delayed change on ${v.idstring()}`);
}
this.fireItemChange(v);
v.pendingChange = false;
}
}
this.delayedFire.delete(v);
}
if (doLog) {
this.log.appendLine("Pending queue: " + this.visualizerList(Array.from(this.delayedFire)));
this.log.appendLine("---------------");
}
}
/**
* Should wrap calls to NBLS for individual visualizers (info, children). Puts visualizer on the delayed fire list.
* Must be itself wrapped in wrap() -- wrap(... queryVisualizer()).
* @param element visualizer to be queried, possibly undefined (new item is expected)
* @param fn code to execute
* @returns code's result
*/
async queryVisualizer<X>(element : Visualizer | undefined, pending : Visualizer[], fn : () => Promise<X>) : Promise<X> {
if (!element) {
return fn();
}
this.delayedFire.add(element);
pending.push(element);
element.pendingQueries++;
if (doLog) {
this.log.appendLine(`Delaying visualizer ${element.idstring()}, queries = ${element.pendingQueries}`)
}
return fn();
}
async getTreeItem2(element: Visualizer): Promise<vscode.TreeItem> {
const n = Number(element.id);
if (this.decorators.length == 0) {
return element;
}
let list : TreeItemDecorator<Visualizer>[] = [...this.decorators];
async function f(item : vscode.TreeItem) : Promise<vscode.TreeItem> {
const deco = list.shift();
if (!deco) {
return item;
}
const decorated = deco.decorateTreeItem(element, item);
if (decorated instanceof vscode.TreeItem) {
return f(decorated);
} else {
return (decorated as Thenable<vscode.TreeItem>).then(f);
}
}
return f(element.copy());
}
delayedFire : Set<Visualizer> = new Set<Visualizer>();
async fetchItem(n : number) : Promise<Visualizer> {
let d = await this.client.sendRequest(NodeInfoRequest.info, { nodeId : n });
let v = new Visualizer(d, this.ts.imageUri(d));
if (d.command) {
// PENDING: provide an API to register command (+ parameters) -> command translators.
if (d.command === 'vscode.open') {
v.command = { command : d.command, title: '', arguments: [v.resourceUri]};
} else {
v.command = { command : d.command, title: '', arguments: [v]};
}
}
return v;
}
getChildren(e?: Visualizer): Thenable<Visualizer[]> {
const self = this;
if (doLog) {
this.log.appendLine(`Doing getChildren on ${e?.idstring()}`);
}
async function collectResults(list : Visualizer[], arr: any, element: Visualizer): Promise<Visualizer[]> {
let res : Visualizer[] = [];
let now : Visualizer[] | undefined;
for (let i = 0; i < arr.length; i++) {
const old : Visualizer | undefined = self.treeData.get(arr[i]);
res.push(
await self.queryVisualizer(old, list, () => self.fetchItem(arr[i]))
);
}
now = element.updateChildren(res, self);
for (let i = 0; i < arr.length; i++) {
const v = now[i];
const n : number = Number(v.id || -1);
self.treeData.set(n, v);
v.parent = element;
}
return now || [];
}
return self.wrap((list) => self.queryVisualizer(e, list, () => {
if (e) {
return this.client.sendRequest(NodeInfoRequest.children, { nodeId : e.data.id}).then(async (arr) => {
return collectResults(list, arr, e);
});
} else {
return this.client.sendRequest(NodeInfoRequest.children, { nodeId: this.root.data.id}).then(async (arr) => {
return collectResults(list, arr, this.root);
});
}
}
));
}
removeVisualizers(vis : number[]) {
let ch : number[] = [];
vis.forEach(a => {
let v : Visualizer | undefined = this.treeData.get(a);
if (v && v.children) {
ch.push(...v.children.keys());
this.treeData.delete(a);
}
});
// cascade
if (ch.length > 0) {
this.removeVisualizers(ch);
}
}
}
let visualizerSerial = 1;
export class Visualizer extends vscode.TreeItem {
visId : number;
pendingQueries : number = 0;
pendingChange : boolean = false;
constructor(
public data : NodeInfoRequest.Data,
public image : vscode.Uri | undefined
) {
super(data.label, data.collapsibleState);
this.visId = visualizerSerial++;
this.id = "" + data.id;
this.label = data.label;
this.description = data.description;
this.tooltip = data.tooltip;
this.collapsibleState = data.collapsibleState;
this.iconPath = image;
if (data.resourceUri) {
this.resourceUri = vscode.Uri.parse(data.resourceUri);
}
this.contextValue = data.contextValue;
}
copy() : Visualizer {
let v : Visualizer = new Visualizer(this.data, this.image);
v.id = this.id;
v.label = this.label;
v.description = this.description;
v.tooltip = this.tooltip;
v.iconPath = this.iconPath;
v.resourceUri = this.resourceUri;
v.contextValue = this.contextValue;
return v;
}
parent: Visualizer | null = null;
children: Map<number, Visualizer> | null = null;
idstring() : string {
return `[${this.id} : ${this.visId} - "${this.label}"]`;
}
update(other : Visualizer) : Visualizer {
this.label = other.label;
this.description = other.description;
this.tooltip = other.tooltip;
this.collapsibleState = other.collapsibleState;
this.iconPath = other.iconPath;
this.resourceUri = other.resourceUri;
this.contextValue = other.contextValue;
this.data = other.data;
this.image = other.image;
this.collapsibleState = other.collapsibleState;
this.command = other.command;
return this;
}
updateChildren(newChildren : Visualizer[], provider : VisualizerProvider) : Visualizer[] {
let toRemove : number[] = [];
let ch : Map<number, Visualizer> = new Map();
for (let i = 0; i < newChildren.length; i++) {
let c = newChildren[i];
const n : number = Number(c.id || -1);
const v : Visualizer | undefined = this.children?.get(n);
if (v) {
v.update(c);
newChildren[i] = c = v;
}
ch.set(n, c);
}
if (this.children) {
for (let k of this.children.keys()) {
if (!ch.get(k)) {
toRemove.push(k);
}
}
}
this.children = ch;
if (toRemove.length) {
provider.removeVisualizers(toRemove);
}
return newChildren;
}
}
export async function createViewProvider(c : NbLanguageClient, id : string) : Promise<VisualizerProvider> {
const ts = c.findTreeViewService();
const client = ts.getClient();
const res = client.sendRequest(NodeInfoRequest.explorermanager, { explorerId: id }).then(node => {
if (!node) {
throw "Unsupported view: " + id;
}
return new VisualizerProvider(client, ts, ts.log, id, node);
});
if (!res) {
throw "Unsupported view: " + id;
}
return res;
}
/**
* Creates a view of the specified type or returns an existing one. The View has to be registered in package.json in
* some workspace position. Waits until the view service initializes.
*
* @param id view ID, consistent with package.json registration
* @param viewTitle title for the new view, optional.
* @returns promise of the tree view instance.
*/
export async function createTreeView<T>(c: NbLanguageClient, viewId: string, viewTitle? : string, options? : Partial<vscode.TreeViewOptions<any>>) : Promise<vscode.TreeView<Visualizer>> {
let ts = c.findTreeViewService();
return ts.createView(viewId, viewTitle, options);
}
/**
* Registers the treeview service with the language server.
*/
export function createTreeViewService(log : vscode.OutputChannel, c : NbLanguageClient): TreeViewService {
const d = vscode.commands.registerCommand("foundProjects.deleteEntry", async function (this: any, args: any) {
let v = args as Visualizer;
let ok = await c.sendRequest(NodeInfoRequest.destroy, { nodeId : v.data.id });
if (!ok) {
vscode.window.showErrorMessage('Cannot delete node ' + v.label);
}
});
const ts : TreeViewService = new TreeViewService(log, c, () => {
d.dispose()
});
return ts;
} | the_stack |
import {IColorSet} from '@moxer/vscode-theme-generator';
import {ThemeSetting} from './types';
export const getColorSet = (theme: ThemeSetting): IColorSet => {
return {
semanticHighlighting: true,
base: {
// Determines the overall background color
background: theme.scheme.background,
// Determines boolean, identifier, keyword, storage, and cssClass
color1: theme.scheme.base.red,
// Determines string, stringEscape, and cssId
color2: theme.scheme.base.green,
// Determines function, class, classMember, type, and cssTag
color3: theme.scheme.base.yellow,
// Determines functionCall and number
color4: theme.scheme.base.blue,
// Determines the overall text foreground color
foreground: theme.scheme.foreground
},
/**
* Overrides specific syntax scopes provided
* by the theme generator
*/
syntax: {
boolean: theme.scheme.base.pink,
class: theme.scheme.base.yellow,
classMember: theme.scheme.base.red,
comment: theme.scheme.comments,
cssClass: theme.scheme.base.yellow,
cssId: theme.scheme.base.orange,
cssProperties: theme.scheme.base.paleblue,
cssTag: theme.scheme.base.yellow,
function: theme.scheme.base.blue,
functionCall: theme.scheme.base.blue,
identifier: theme.scheme.base.red,
keyword: theme.scheme.base.cyan,
storage: theme.scheme.base.purple,
string: theme.scheme.base.green,
stringEscape: theme.scheme.foreground,
type: theme.scheme.base.yellow,
punctuation: theme.scheme.base.cyan,
otherKeyword: theme.scheme.base.orange,
variable: theme.scheme.foreground,
number: theme.scheme.base.orange
},
/**
* Override all syntax tokens
*/
customTokens: [
{
name: 'Markup Deleted',
scope: [
'markup.deleted'
],
settings: {
foreground: theme.scheme.base.red
}
},
{
name: 'Markup Inserted',
scope: [
'markup.inserted'
],
settings: {
foreground: theme.scheme.base.green
}
},
{
name: 'Markup Underline',
scope: [
'markup.underline'
],
settings: {
fontStyle: 'underline'
}
},
{
name: 'Keyword Control',
scope: [
'keyword.control'
],
settings: {
foreground: theme.scheme.base.cyan,
fontStyle: 'italic'
}
},
{
name: 'Parameter',
scope: [
'variable.parameter'
],
settings: {
fontStyle: 'italic'
}
},
{
name: 'Python - Self Parameter',
scope: [
'variable.parameter.function.language.special.self.python'
],
settings: {
foreground: theme.scheme.base.red,
fontStyle: 'italic'
}
},
{
name: 'Python - Format Placeholder',
scope: [
'constant.character.format.placeholder.other.python'
],
settings: {
foreground: theme.scheme.base.orange
}
},
{
name: 'Markdown - Blockquote',
scope: [
'markup.quote'
],
settings: {
fontStyle: 'italic',
foreground: theme.scheme.base.cyan
}
},
{
name: 'Markdown - Fenced Language',
scope: [
'markup.fenced_code.block'
],
settings: {
foreground: `${theme.scheme.foreground}90`
}
},
{
name: 'Markdown - Blockquote Punctuation',
scope: [
'punctuation.definition.quote'
],
settings: {
foreground: theme.scheme.base.pink
}
},
{
name: 'JSON Key - Level 0',
scope: [
'meta.structure.dictionary.json support.type.property-name.json'
],
settings: {
foreground: theme.scheme.base.purple
}
},
{
name: 'JSON Key - Level 1',
scope: [
'meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json support.type.property-name.json'
],
settings: {
foreground: theme.scheme.base.yellow
}
},
{
name: 'JSON Key - Level 2',
scope: [
'meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json support.type.property-name.json'
],
settings: {
foreground: theme.scheme.base.orange
}
},
{
name: 'JSON Key - Level 3',
scope: [
'meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json support.type.property-name.json'
],
settings: {
foreground: theme.scheme.base.red
}
},
{
name: 'JSON Key - Level 4',
scope: [
'meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json support.type.property-name.json'
],
settings: {
foreground: theme.scheme.base.brown
}
},
{
name: 'JSON Key - Level 5',
scope: [
'meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json support.type.property-name.json'
],
settings: {
foreground: theme.scheme.base.blue
}
},
{
name: 'JSON Key - Level 6',
scope: [
'meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json support.type.property-name.json'
],
settings: {
foreground: theme.scheme.base.pink
}
},
{
name: 'JSON Key - Level 7',
scope: [
'meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json support.type.property-name.json'
],
settings: {
foreground: theme.scheme.base.purple
}
},
{
name: 'JSON Key - Level 8',
scope: [
'meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json meta.structure.dictionary.value.json meta.structure.dictionary.json support.type.property-name.json'
],
settings: {
foreground: theme.scheme.base.green
}
}
],
/**
* Overrides workbench UI Elements
*/
workbench: {
/**
* General elements style
*/
focusBorder: `${theme.scheme.focusBorder}00`,
'editorRuler.foreground': theme.scheme.guides,
'widget.shadow': theme.scheme.shadow,
'scrollbar.shadow': theme.scheme.shadow,
'editorLink.activeForeground': theme.scheme.foreground,
'selection.background': `${theme.scheme.lineHighlight}80`,
'progressBar.background': theme.scheme.defaultAccent,
'debugToolBar.background': theme.scheme.background,
'pickerGroup.foreground': theme.scheme.defaultAccent,
'editorMarkerNavigation.background': `${theme.scheme.foreground}05`,
'tree.indentGuidesStroke': theme.scheme.guides,
'terminalCursor.foreground': theme.scheme.base.yellow,
'terminalCursor.background': theme.scheme.base.black,
'editorWhitespace.foreground': `${theme.scheme.foreground}40`,
/**
* InputOption
*/
'inputOption.activeBackground': `${theme.scheme.foreground}30`,
'inputOption.activeBorder': `${theme.scheme.foreground}30`,
/**
* Buttons style
*/
'button.background': theme.scheme.selection,
// 'button.hoverBackground': theme.scheme.shade2,
/**
* Links style
*/
'textLink.foreground': theme.scheme.defaultAccent,
'textLink.activeForeground': theme.scheme.foreground,
/**
* Sidebar style
*/
'sideBar.background': theme.scheme.backgroundAlt,
'sideBar.foreground': theme.scheme.sidebarForeground,
'sideBar.border': `${theme.scheme.contrastBorder}60`,
/**
* Sidebar elements style
*/
'sideBarTitle.foreground': theme.scheme.foreground,
'sideBarSectionHeader.background': theme.scheme.backgroundAlt,
'sideBarSectionHeader.border': `${theme.scheme.contrastBorder}60`,
// "sideBarSectionHeader.foreground": theme.scheme.foreground,
/**
* Window panels style (terminal, global search)
*/
'panel.border': `${theme.scheme.contrastBorder}60`,
'panel.background': theme.scheme.backgroundAlt,
'panel.dropBackground': theme.scheme.foreground,
/**
* Window panels elements style
*/
'panelTitle.inactiveForeground': theme.scheme.foreground,
'panelTitle.activeForeground': theme.scheme.tabActiveForeground,
'panelTitle.activeBorder': theme.scheme.defaultAccent,
/**
* Code Editor style
*/
'editor.background': theme.scheme.background,
'editor.foreground': theme.scheme.foreground,
'editor.lineHighlightBackground': `${theme.scheme.lineHighlight}50`,
'editor.selectionHighlightBackground': `${theme.scheme.caret}20`,
'editor.lineHighlightBorder': `${theme.scheme.lineHighlight}00`,
'editor.findMatchBackground': theme.scheme.findMatchBackground,
'editor.findMatchHighlightBackground': theme.scheme.findMatchHighlightBackground,
'editor.findMatchBorder': theme.scheme.defaultAccent,
'editor.findMatchHighlightBorder': theme.scheme.findMatchHighlightBorder,
// Editor Indent guides
'editorIndentGuide.background': `${theme.scheme.guides}70`,
'editorIndentGuide.activeBackground': theme.scheme.guides,
// Editor line number
'editorLineNumber.foreground': theme.scheme.lineNumbers,
'editorLineNumber.activeForeground': theme.scheme.sidebarForeground,
// Editor tab groups
'editorGroupHeader.tabsBackground': theme.scheme.background,
'editorGroup.border': theme.scheme.shadow,
// Editor gutter
'editorGutter.modifiedBackground': `${theme.scheme.base.blue}60`,
'editorGutter.addedBackground': `${theme.scheme.base.green}60`,
'editorGutter.deletedBackground': `${theme.scheme.base.red}60`,
/**
* Activity bar style
*/
'activityBar.background': theme.scheme.backgroundAlt,
'activityBar.border': `${theme.scheme.contrastBorder}60`,
'activityBar.foreground': theme.scheme.foreground,
'activityBar.activeBorder': theme.scheme.defaultAccent,
/**
* Activity bar badges style
*/
'activityBarBadge.background': theme.scheme.defaultAccent,
'activityBarBadge.foreground': theme.scheme.base.black,
/**
* Global badges style
*/
'badge.background': `${theme.scheme.lineHighlight}30`,
'badge.foreground': theme.scheme.comments,
/**
* Extensions badge style
*/
// 'extensionBadge.remoteBackground': theme.scheme.shade3,
'extensionBadge.remoteForeground': theme.scheme.foreground,
/**
* Scrollbar style
*/
'scrollbarSlider.background': theme.scheme.scrollbars,
'scrollbarSlider.hoverBackground': theme.scheme.scrollbarsHover,
'scrollbarSlider.activeBackground': theme.scheme.defaultAccent,
/**
* Tabs style
*/
'tab.activeBorder': theme.scheme.defaultAccent,
'tab.activeModifiedBorder': theme.scheme.sidebarForeground,
'tab.unfocusedActiveBorder': theme.scheme.comments,
'tab.activeForeground': theme.scheme.tabActiveForeground,
'tab.inactiveForeground': theme.scheme.sidebarForeground,
'tab.inactiveBackground': theme.scheme.background,
'tab.activeBackground': theme.scheme.background,
'tab.unfocusedActiveForeground': theme.scheme.foreground,
'tab.border': theme.scheme.background,
// 'tab.inactiveModifiedBorder': theme.scheme.shade5,
/**
* Editor overlay widgets style (find/replace..)
*/
'editorWidget.background': theme.scheme.backgroundAlt,
'editorWidget.resizeBorder': theme.scheme.defaultAccent,
'editorWidget.border': theme.scheme.defaultAccent,
/**
* Statusbar style
*/
'statusBar.noFolderBackground': theme.scheme.background,
'statusBar.border': `${theme.scheme.contrastBorder}60`,
'statusBar.background': theme.scheme.backgroundAlt,
'statusBar.foreground': theme.scheme.statusbarForeground,
'statusBar.debuggingBackground': theme.scheme.base.purple,
'statusBar.debuggingForeground': theme.scheme.base.white,
/**
* Statusbar items style
*/
'statusBarItem.hoverBackground': `${theme.scheme.comments}20`,
'statusBarItem.remoteForeground': theme.scheme.base.black,
'statusBarItem.remoteBackground': theme.scheme.defaultAccent,
/**
* Matching brackets style
*/
'editorBracketMatch.border': `${theme.scheme.caret}50`,
'editorBracketMatch.background': theme.scheme.background,
/**
* Editor Overview Ruler style
*/
'editorOverviewRuler.findMatchForeground': theme.scheme.defaultAccent,
'editorOverviewRuler.border': theme.scheme.background,
'editorOverviewRuler.errorForeground': `${theme.scheme.base.red}40`,
'editorOverviewRuler.infoForeground': `${theme.scheme.base.blue}40`,
'editorOverviewRuler.warningForeground': `${theme.scheme.base.yellow}40`,
/**
* Squigglies style
*/
'editorInfo.foreground': `${theme.scheme.base.blue}70`,
'editorWarning.foreground': `${theme.scheme.base.yellow}70`,
'editorError.foreground': `${theme.scheme.base.red}70`,
/**
* Popop dialogs style
*/
'editorHoverWidget.background': theme.scheme.background,
'editorHoverWidget.border': theme.scheme.inputBorder,
/**
* Title bar style
*/
'titleBar.activeBackground': theme.scheme.backgroundAlt,
'titleBar.activeForeground': theme.scheme.foreground,
'titleBar.inactiveBackground': theme.scheme.backgroundAlt,
'titleBar.inactiveForeground': theme.scheme.sidebarForeground,
'titleBar.border': `${theme.scheme.contrastBorder}60`,
/**
* Textfield and inputs style
*/
'input.background': theme.scheme.inputBackground,
'input.foreground': theme.scheme.foreground,
'input.placeholderForeground': `${theme.scheme.foreground}60`,
'input.border': theme.scheme.inputBorder,
/**
* Inputs validation style
*/
'inputValidation.errorBorder': `${theme.scheme.base.red}`,
'inputValidation.infoBorder': `${theme.scheme.base.blue}`,
'inputValidation.warningBorder': `${theme.scheme.base.yellow}`,
/**
* Dropdown menu style
*/
'dropdown.background': theme.scheme.background,
'dropdown.border': theme.scheme.inputBorder,
/**
* Quick Panel
*/
'quickInput.background': theme.scheme.background,
'quickInput.foreground': theme.scheme.sidebarForeground,
/**
* Lists style
*/
'list.hoverForeground': theme.scheme.listHoverForeground,
'list.hoverBackground': theme.scheme.backgroundAlt,
'list.activeSelectionBackground': theme.scheme.backgroundAlt,
'list.activeSelectionForeground': theme.scheme.defaultAccent,
'list.inactiveSelectionForeground': theme.scheme.defaultAccent,
'list.inactiveSelectionBackground': theme.scheme.inactiveSelectionBackground,
'list.focusBackground': `${theme.scheme.foreground}20`,
'quickInput.list.focusBackground': `${theme.scheme.foreground}20`,
'list.focusForeground': theme.scheme.foreground,
'list.highlightForeground': theme.scheme.defaultAccent,
// 'list.dropBackground': theme.scheme.shade2,
/**
* Editor suggest widget style
*/
'editorSuggestWidget.background': theme.scheme.background,
'editorSuggestWidget.foreground': theme.scheme.foreground,
'editorSuggestWidget.highlightForeground': theme.scheme.defaultAccent,
'editorSuggestWidget.selectedBackground': `${theme.scheme.lineHighlight}50`,
'editorSuggestWidget.border': theme.scheme.inputBorder,
/**
* Editor diff editor style
*/
'diffEditor.insertedTextBackground': `${theme.scheme.base.cyan}20`,
'diffEditor.removedTextBackground': `${theme.scheme.base.pink}20`,
/**
* Notifications
*/
'notifications.background': theme.scheme.background,
'notifications.foreground': theme.scheme.foreground,
'notificationLink.foreground': theme.scheme.defaultAccent,
/**
* Extensions button style
*/
'extensionButton.prominentBackground': `${theme.scheme.base.green}90`,
'extensionButton.prominentHoverBackground': theme.scheme.base.green,
'extensionButton.prominentForeground': theme.scheme.base.black,
/**
* Peekview window style
*/
'peekView.border': theme.scheme.shadow,
'peekViewEditor.background': `${theme.scheme.foreground}05`,
'peekViewTitle.background': `${theme.scheme.foreground}05`,
'peekViewResult.background': `${theme.scheme.foreground}05`,
'peekViewEditorGutter.background': `${theme.scheme.foreground}05`,
'peekViewTitleDescription.foreground': `${theme.scheme.foreground}60`,
'peekViewResult.matchHighlightBackground': theme.scheme.selection,
'peekViewEditor.matchHighlightBackground': theme.scheme.selection,
'peekViewResult.selectionBackground': `${theme.scheme.sidebarForeground}70`,
/**
* GIT decorations style
*/
'gitDecoration.deletedResourceForeground': `${theme.scheme.base.red}90`,
'gitDecoration.conflictingResourceForeground': `${theme.scheme.base.yellow}90`,
'gitDecoration.modifiedResourceForeground': `${theme.scheme.base.blue}90`,
'gitDecoration.untrackedResourceForeground': `${theme.scheme.base.green}90`,
'gitDecoration.ignoredResourceForeground': `${theme.scheme.sidebarForeground}90`,
/**
* Breadcrumb style
*/
'breadcrumb.background': theme.scheme.background,
'breadcrumb.foreground': theme.scheme.sidebarForeground,
'breadcrumb.focusForeground': theme.scheme.foreground,
'breadcrumb.activeSelectionForeground': theme.scheme.defaultAccent,
'breadcrumbPicker.background': theme.scheme.backgroundAlt,
/**
* Custom menus style
*/
'menu.background': theme.scheme.background,
'menu.foreground': theme.scheme.foreground,
'menu.selectionBackground': `${theme.scheme.lineHighlight}50`,
'menu.selectionForeground': theme.scheme.defaultAccent,
'menu.selectionBorder': theme.scheme.inactiveSelectionBackground,
'menu.separatorBackground': theme.scheme.foreground,
/**
* Menu Bar style
*/
'menubar.selectionBackground': theme.scheme.inactiveSelectionBackground,
'menubar.selectionForeground': theme.scheme.defaultAccent,
'menubar.selectionBorder': theme.scheme.inactiveSelectionBackground,
/**
* Settings elements style
*/
'settings.dropdownForeground': theme.scheme.foreground,
'settings.dropdownBackground': theme.scheme.backgroundAlt,
'settings.numberInputForeground': theme.scheme.foreground,
'settings.numberInputBackground': theme.scheme.backgroundAlt,
'settings.textInputForeground': theme.scheme.foreground,
'settings.textInputBackground': theme.scheme.backgroundAlt,
'settings.headerForeground': theme.scheme.defaultAccent,
'settings.modifiedItemIndicator': theme.scheme.defaultAccent,
'settings.checkboxBackground': theme.scheme.backgroundAlt,
'settings.checkboxForeground': theme.scheme.foreground,
/**
* List Filter Widget style
*/
'listFilterWidget.background': theme.scheme.inactiveSelectionBackground,
'listFilterWidget.outline': theme.scheme.inactiveSelectionBackground,
'listFilterWidget.noMatchesOutline': theme.scheme.inactiveSelectionBackground,
/**
* Debug Console
*/
'debugConsole.errorForeground': theme.scheme.base.red,
'debugConsole.infoForeground': theme.scheme.base.cyan,
'debugConsole.warningForeground': theme.scheme.base.yellow
},
/**
* Define the integrated shell
* color palette
*/
terminal: {
black: theme.scheme.base.black,
blue: theme.scheme.base.blue,
brightBlack: theme.scheme.comments,
brightBlue: theme.scheme.base.blue,
brightCyan: theme.scheme.base.cyan,
brightGreen: theme.scheme.base.green,
brightMagenta: theme.scheme.base.purple,
brightRed: theme.scheme.base.red,
brightWhite: theme.scheme.base.white,
brightYellow: theme.scheme.base.yellow,
cyan: theme.scheme.base.cyan,
green: theme.scheme.base.green,
magenta: theme.scheme.base.purple,
red: theme.scheme.base.red,
white: theme.scheme.base.white,
yellow: theme.scheme.base.yellow
},
/**
* Define workbench colors
*/
ui: {
// Highlights matches from the find widget
// currentFindMatchHighlight: theme.scheme.shade5,
// Set the editor cursor color
cursor: theme.scheme.caret,
// Ighlights matches from the find widget
findMatchHighlight: theme.scheme.foreground,
// Highlights the selected area for "find in selection"
findRangeHighlight: `${theme.scheme.base.yellow}30`,
// Set color for invisible characters/whitespaces
invisibles: theme.scheme.guides,
// Highlights text which matches the selected text
selection: theme.scheme.selection,
// Highlights text inside selected area
selectionHighlight: `${theme.scheme.base.yellow}50`,
// When the cursor is on a symbol, highlights places that symbol is read
wordHighlight: `${theme.scheme.base.pink}30`,
// When the cursor is on a symbol, highlights places that symbol is written
wordHighlightStrong: `${theme.scheme.base.green}30`
}
};
}; | the_stack |
import type { ComponentInterface, EventEmitter } from '@stencil/core';
import { Component, Element, Event, Host, Method, Prop, State, Watch, h } from '@stencil/core';
import { getIonMode } from '../../global/ionic-global';
import type {
AnimationBuilder,
ComponentProps,
ComponentRef,
FrameworkDelegate,
OverlayEventDetail,
PopoverAttributes,
PopoverInterface,
PopoverSize,
PositionAlign,
PositionReference,
PositionSide,
TriggerAction,
} from '../../interface';
import { CoreDelegate, attachComponent, detachComponent } from '../../utils/framework-delegate';
import { addEventListener, raf } from '../../utils/helpers';
import { BACKDROP, dismiss, eventMethod, focusFirstDescendant, prepareOverlay, present } from '../../utils/overlays';
import { isPlatform } from '../../utils/platform';
import { getClassMap } from '../../utils/theme';
import { deepReady } from '../../utils/transition';
import { iosEnterAnimation } from './animations/ios.enter';
import { iosLeaveAnimation } from './animations/ios.leave';
import { mdEnterAnimation } from './animations/md.enter';
import { mdLeaveAnimation } from './animations/md.leave';
import { configureDismissInteraction, configureKeyboardInteraction, configureTriggerInteraction } from './utils';
/**
* @virtualProp {"ios" | "md"} mode - The mode determines which platform styles to use.
*
* @slot - Content is placed inside of the `.popover-content` element.
*
* @part backdrop - The `ion-backdrop` element.
* @part arrow - The arrow that points to the reference element. Only applies on `ios` mode.
* @part content - The wrapper element for the default slot.
*/
@Component({
tag: 'ion-popover',
styleUrls: {
ios: 'popover.ios.scss',
md: 'popover.md.scss',
},
shadow: true,
})
export class Popover implements ComponentInterface, PopoverInterface {
private usersElement?: HTMLElement;
private triggerEl?: HTMLElement | null;
private parentPopover: HTMLIonPopoverElement | null = null;
private popoverIndex = popoverIds++;
private popoverId?: string;
private coreDelegate: FrameworkDelegate = CoreDelegate();
private currentTransition?: Promise<any>;
private destroyTriggerInteraction?: () => void;
private destroyKeyboardInteraction?: () => void;
private destroyDismissInteraction?: () => void;
private inline = false;
private workingDelegate?: FrameworkDelegate;
private focusDescendantOnPresent = false;
lastFocus?: HTMLElement;
@State() presented = false;
@Element() el!: HTMLIonPopoverElement;
/** @internal */
@Prop() hasController = false;
/** @internal */
@Prop() delegate?: FrameworkDelegate;
/** @internal */
@Prop() overlayIndex!: number;
/**
* Animation to use when the popover is presented.
*/
@Prop() enterAnimation?: AnimationBuilder;
/**
* Animation to use when the popover is dismissed.
*/
@Prop() leaveAnimation?: AnimationBuilder;
/**
* The component to display inside of the popover.
* You only need to use this if you are not using
* a JavaScript framework. Otherwise, you can just
* slot your component inside of `ion-popover`.
*/
@Prop() component?: ComponentRef;
/**
* The data to pass to the popover component.
* You only need to use this if you are not using
* a JavaScript framework. Otherwise, you can just
* set the props directly on your component.
*/
@Prop() componentProps?: ComponentProps;
/**
* If `true`, the keyboard will be automatically dismissed when the overlay is presented.
*/
@Prop() keyboardClose = true;
/**
* Additional classes to apply for custom CSS. If multiple classes are
* provided they should be separated by spaces.
* @internal
*/
@Prop() cssClass?: string | string[];
/**
* If `true`, the popover will be dismissed when the backdrop is clicked.
*/
@Prop() backdropDismiss = true;
/**
* The event to pass to the popover animation.
*/
@Prop() event: any;
/**
* If `true`, a backdrop will be displayed behind the popover.
*/
@Prop() showBackdrop = true;
/**
* If `true`, the popover will be translucent.
* Only applies when the mode is `"ios"` and the device supports
* [`backdrop-filter`](https://developer.mozilla.org/en-US/docs/Web/CSS/backdrop-filter#Browser_compatibility).
*/
@Prop() translucent = false;
/**
* If `true`, the popover will animate.
*/
@Prop() animated = true;
/**
* Additional attributes to pass to the popover.
*/
@Prop() htmlAttributes?: PopoverAttributes;
/**
* Describes what kind of interaction with the trigger that
* should cause the popover to open. Does not apply when the `trigger`
* property is `undefined`.
* If `'click'`, the popover will be presented when the trigger is left clicked.
* If `'hover'`, the popover will be presented when a pointer hovers over the trigger.
* If `'context-menu'`, the popover will be presented when the trigger is right
* clicked on desktop and long pressed on mobile. This will also prevent your
* device's normal context menu from appearing.
*/
@Prop() triggerAction: TriggerAction = 'click';
/**
* An ID corresponding to the trigger element that
* causes the popover to open. Use the `trigger-action`
* property to customize the interaction that results in
* the popover opening.
*/
@Prop() trigger: string | undefined;
/**
* Describes how to calculate the popover width.
* If `'cover'`, the popover width will match the width of the trigger.
* If `'auto'`, the popover width will be determined by the content in
* the popover.
*/
@Prop() size: PopoverSize = 'auto';
/**
* If `true`, the popover will be automatically
* dismissed when the content has been clicked.
*/
@Prop() dismissOnSelect = false;
/**
* Describes what to position the popover relative to.
* If `'trigger'`, the popover will be positioned relative
* to the trigger button. If passing in an event, this is
* determined via event.target.
* If `'event'`, the popover will be positioned relative
* to the x/y coordinates of the trigger action. If passing
* in an event, this is determined via event.clientX and event.clientY.
*/
@Prop() reference: PositionReference = 'trigger';
/**
* Describes which side of the `reference` point to position
* the popover on. The `'start'` and `'end'` values are RTL-aware,
* and the `'left'` and `'right'` values are not.
*/
@Prop() side: PositionSide = 'bottom';
/**
* Describes how to align the popover content with the `reference` point.
* Defaults to `'center'` for `ios` mode, and `'start'` for `md` mode.
*/
@Prop({ mutable: true }) alignment?: PositionAlign;
/**
* If `true`, the popover will display an arrow that points at the
* `reference` when running in `ios` mode. Does not apply in `md` mode.
*/
@Prop() arrow = true;
/**
* If `true`, the popover will open. If `false`, the popover will close.
* Use this if you need finer grained control over presentation, otherwise
* just use the popoverController or the `trigger` property.
* Note: `isOpen` will not automatically be set back to `false` when
* the popover dismisses. You will need to do that in your code.
*/
@Prop() isOpen = false;
/**
* @internal
*
* If `true` the popover will not register its own keyboard event handlers.
* This allows the contents of the popover to handle their own keyboard interactions.
*
* If `false`, the popover will register its own keyboard event handlers for
* navigating `ion-list` items within a popover (up/down/home/end/etc.).
* This will also cancel browser keyboard event bindings to prevent scroll
* behavior in a popover using a list of items.
*/
@Prop() keyboardEvents = false;
@Watch('trigger')
@Watch('triggerAction')
onTriggerChange() {
this.configureTriggerInteraction();
}
@Watch('isOpen')
onIsOpenChange(newValue: boolean, oldValue: boolean) {
if (newValue === true && oldValue === false) {
this.present();
} else if (newValue === false && oldValue === true) {
this.dismiss();
}
}
/**
* Emitted after the popover has presented.
*/
@Event({ eventName: 'ionPopoverDidPresent' }) didPresent!: EventEmitter<void>;
/**
* Emitted before the popover has presented.
*/
@Event({ eventName: 'ionPopoverWillPresent' }) willPresent!: EventEmitter<void>;
/**
* Emitted before the popover has dismissed.
*/
@Event({ eventName: 'ionPopoverWillDismiss' }) willDismiss!: EventEmitter<OverlayEventDetail>;
/**
* Emitted after the popover has dismissed.
*/
@Event({ eventName: 'ionPopoverDidDismiss' }) didDismiss!: EventEmitter<OverlayEventDetail>;
/**
* Emitted after the popover has presented.
* Shorthand for ionPopoverWillDismiss.
*/
@Event({ eventName: 'didPresent' }) didPresentShorthand!: EventEmitter<void>;
/**
* Emitted before the popover has presented.
* Shorthand for ionPopoverWillPresent.
*/
@Event({ eventName: 'willPresent' }) willPresentShorthand!: EventEmitter<void>;
/**
* Emitted before the popover has dismissed.
* Shorthand for ionPopoverWillDismiss.
*/
@Event({ eventName: 'willDismiss' }) willDismissShorthand!: EventEmitter<OverlayEventDetail>;
/**
* Emitted after the popover has dismissed.
* Shorthand for ionPopoverDidDismiss.
*/
@Event({ eventName: 'didDismiss' }) didDismissShorthand!: EventEmitter<OverlayEventDetail>;
connectedCallback() {
prepareOverlay(this.el);
}
componentWillLoad() {
/**
* If user has custom ID set then we should
* not assign the default incrementing ID.
*/
this.popoverId = this.el.hasAttribute('id') ? this.el.getAttribute('id')! : `ion-popover-${this.popoverIndex}`;
this.parentPopover = this.el.closest(`ion-popover:not(#${this.popoverId})`) as HTMLIonPopoverElement | null;
if (this.alignment === undefined) {
this.alignment = getIonMode(this) === 'ios' ? 'center' : 'start';
}
}
componentDidLoad() {
const { parentPopover, isOpen } = this;
/**
* If popover was rendered with isOpen="true"
* then we should open popover immediately.
*/
if (isOpen === true) {
raf(() => this.present());
}
if (parentPopover) {
addEventListener(parentPopover, 'ionPopoverWillDismiss', () => {
this.dismiss(undefined, undefined, false);
});
}
this.configureTriggerInteraction();
}
/**
* When opening a popover from a trigger, we should not be
* modifying the `event` prop from inside the component.
* Additionally, when pressing the "Right" arrow key, we need
* to shift focus to the first descendant in the newly presented
* popover.
*
* @internal
*/
@Method()
async presentFromTrigger(event?: any, focusDescendant = false) {
this.focusDescendantOnPresent = focusDescendant;
await this.present(event);
this.focusDescendantOnPresent = false;
}
/**
* Determines whether or not an overlay
* is being used inline or via a controller/JS
* and returns the correct delegate.
* By default, subsequent calls to getDelegate
* will use a cached version of the delegate.
* This is useful for calling dismiss after
* present so that the correct delegate is given.
*/
private getDelegate(force = false) {
if (this.workingDelegate && !force) {
return {
delegate: this.workingDelegate,
inline: this.inline,
};
}
/**
* If using overlay inline
* we potentially need to use the coreDelegate
* so that this works in vanilla JS apps.
* If a developer has presented this component
* via a controller, then we can assume
* the component is already in the
* correct place.
*/
const parentEl = this.el.parentNode as HTMLElement | null;
const inline = (this.inline = parentEl !== null && !this.hasController);
const delegate = (this.workingDelegate = inline ? this.delegate || this.coreDelegate : this.delegate);
return { inline, delegate };
}
/**
* Present the popover overlay after it has been created.
* Developers can pass a mouse, touch, or pointer event
* to position the popover relative to where that event
* was dispatched.
*/
@Method()
async present(event?: MouseEvent | TouchEvent | PointerEvent | CustomEvent): Promise<void> {
if (this.presented) {
return;
}
/**
* When using an inline popover
* and dismissing a popover it is possible to
* quickly present the popover while it is
* dismissing. We need to await any current
* transition to allow the dismiss to finish
* before presenting again.
*/
if (this.currentTransition !== undefined) {
await this.currentTransition;
}
const data = {
...this.componentProps,
popover: this.el,
};
const { inline, delegate } = this.getDelegate(true);
this.usersElement = await attachComponent(delegate, this.el, this.component, ['popover-viewport'], data, inline);
await deepReady(this.usersElement);
if (!this.keyboardEvents) {
this.configureKeyboardInteraction();
}
this.configureDismissInteraction();
this.currentTransition = present(this, 'popoverEnter', iosEnterAnimation, mdEnterAnimation, {
event: event || this.event,
size: this.size,
trigger: this.triggerEl,
reference: this.reference,
side: this.side,
align: this.alignment,
});
await this.currentTransition;
this.currentTransition = undefined;
/**
* If popover is nested and was
* presented using the "Right" arrow key,
* we need to move focus to the first
* descendant inside of the popover.
*/
if (this.focusDescendantOnPresent) {
focusFirstDescendant(this.el, this.el);
}
}
/**
* Dismiss the popover overlay after it has been presented.
*
* @param data Any data to emit in the dismiss events.
* @param role The role of the element that is dismissing the popover. For example, 'cancel' or 'backdrop'.
* @param dismissParentPopover If `true`, dismissing this popover will also dismiss
* a parent popover if this popover is nested. Defaults to `true`.
*/
@Method()
async dismiss(data?: any, role?: string, dismissParentPopover = true): Promise<boolean> {
/**
* When using an inline popover
* and presenting a popover it is possible to
* quickly dismiss the popover while it is
* presenting. We need to await any current
* transition to allow the present to finish
* before dismissing again.
*/
if (this.currentTransition !== undefined) {
await this.currentTransition;
}
const { destroyKeyboardInteraction, destroyDismissInteraction } = this;
if (dismissParentPopover && this.parentPopover) {
this.parentPopover.dismiss(data, role, dismissParentPopover);
}
this.currentTransition = dismiss(this, data, role, 'popoverLeave', iosLeaveAnimation, mdLeaveAnimation, this.event);
const shouldDismiss = await this.currentTransition;
if (shouldDismiss) {
if (destroyKeyboardInteraction) {
destroyKeyboardInteraction();
this.destroyKeyboardInteraction = undefined;
}
if (destroyDismissInteraction) {
destroyDismissInteraction();
this.destroyDismissInteraction = undefined;
}
/**
* If using popover inline
* we potentially need to use the coreDelegate
* so that this works in vanilla JS apps
*/
const { delegate } = this.getDelegate();
await detachComponent(delegate, this.usersElement);
}
this.currentTransition = undefined;
return shouldDismiss;
}
/**
* @internal
*/
@Method()
async getParentPopover(): Promise<HTMLIonPopoverElement | null> {
return this.parentPopover;
}
/**
* Returns a promise that resolves when the popover did dismiss.
*/
@Method()
onDidDismiss<T = any>(): Promise<OverlayEventDetail<T>> {
return eventMethod(this.el, 'ionPopoverDidDismiss');
}
/**
* Returns a promise that resolves when the popover will dismiss.
*/
@Method()
onWillDismiss<T = any>(): Promise<OverlayEventDetail<T>> {
return eventMethod(this.el, 'ionPopoverWillDismiss');
}
private onBackdropTap = () => {
this.dismiss(undefined, BACKDROP);
};
private onLifecycle = (modalEvent: CustomEvent) => {
const el = this.usersElement;
const name = LIFECYCLE_MAP[modalEvent.type];
if (el && name) {
const event = new CustomEvent(name, {
bubbles: false,
cancelable: false,
detail: modalEvent.detail,
});
el.dispatchEvent(event);
}
};
private configureTriggerInteraction = () => {
const { trigger, triggerAction, el, destroyTriggerInteraction } = this;
if (destroyTriggerInteraction) {
destroyTriggerInteraction();
}
const triggerEl = (this.triggerEl = trigger !== undefined ? document.getElementById(trigger) : null);
if (!triggerEl) {
return;
}
this.destroyTriggerInteraction = configureTriggerInteraction(triggerEl, triggerAction, el);
};
private configureKeyboardInteraction = () => {
const { destroyKeyboardInteraction, el } = this;
if (destroyKeyboardInteraction) {
destroyKeyboardInteraction();
}
this.destroyKeyboardInteraction = configureKeyboardInteraction(el);
};
private configureDismissInteraction = () => {
const { destroyDismissInteraction, parentPopover, triggerAction, triggerEl, el } = this;
if (!parentPopover || !triggerEl) {
return;
}
if (destroyDismissInteraction) {
destroyDismissInteraction();
}
this.destroyDismissInteraction = configureDismissInteraction(triggerEl, triggerAction, el, parentPopover);
};
render() {
const mode = getIonMode(this);
const { onLifecycle, popoverId, parentPopover, dismissOnSelect, side, arrow, htmlAttributes } = this;
const desktop = isPlatform('desktop');
const enableArrow = arrow && !parentPopover;
return (
<Host
aria-modal="true"
no-router
tabindex="-1"
{...(htmlAttributes as any)}
style={{
zIndex: `${20000 + this.overlayIndex}`,
}}
id={popoverId}
class={{
...getClassMap(this.cssClass),
[mode]: true,
'popover-translucent': this.translucent,
'overlay-hidden': true,
'popover-desktop': desktop,
[`popover-side-${side}`]: true,
'popover-nested': !!parentPopover,
}}
onIonPopoverDidPresent={onLifecycle}
onIonPopoverWillPresent={onLifecycle}
onIonPopoverWillDismiss={onLifecycle}
onIonPopoverDidDismiss={onLifecycle}
onIonBackdropTap={this.onBackdropTap}
>
{!parentPopover && <ion-backdrop tappable={this.backdropDismiss} visible={this.showBackdrop} part="backdrop" />}
<div class="popover-wrapper ion-overlay-wrapper" onClick={dismissOnSelect ? () => this.dismiss() : undefined}>
{enableArrow && <div class="popover-arrow" part="arrow"></div>}
<div class="popover-content" part="content">
<slot></slot>
</div>
</div>
</Host>
);
}
}
const LIFECYCLE_MAP: any = {
ionPopoverDidPresent: 'ionViewDidEnter',
ionPopoverWillPresent: 'ionViewWillEnter',
ionPopoverWillDismiss: 'ionViewWillLeave',
ionPopoverDidDismiss: 'ionViewDidLeave',
};
let popoverIds = 0; | the_stack |
import { IKeyboardKey } from '@secret-agent/interfaces/IKeyboardLayoutUS';
export interface IKeyDefinition {
keyCode?: number;
shiftKeyCode?: number;
key?: string;
shiftKey?: string;
code?: string;
text?: string;
shiftText?: string;
location?: number;
}
export const keyDefinitions: Readonly<Record<IKeyboardKey, IKeyDefinition>> = {
'0': { keyCode: 48, key: '0', code: 'Digit0' },
'1': { keyCode: 49, key: '1', code: 'Digit1' },
'2': { keyCode: 50, key: '2', code: 'Digit2' },
'3': { keyCode: 51, key: '3', code: 'Digit3' },
'4': { keyCode: 52, key: '4', code: 'Digit4' },
'5': { keyCode: 53, key: '5', code: 'Digit5' },
'6': { keyCode: 54, key: '6', code: 'Digit6' },
'7': { keyCode: 55, key: '7', code: 'Digit7' },
'8': { keyCode: 56, key: '8', code: 'Digit8' },
'9': { keyCode: 57, key: '9', code: 'Digit9' },
Power: { key: 'Power', code: 'Power' },
Eject: { key: 'Eject', code: 'Eject' },
Abort: { keyCode: 3, code: 'Abort', key: 'Cancel' },
Help: { keyCode: 6, code: 'Help', key: 'Help' },
Backspace: { keyCode: 8, code: 'Backspace', key: 'Backspace' },
Tab: { keyCode: 9, code: 'Tab', key: 'Tab' },
Numpad5: {
keyCode: 12,
shiftKeyCode: 101,
key: 'Clear',
code: 'Numpad5',
shiftKey: '5',
location: 3,
},
NumpadEnter: {
keyCode: 13,
code: 'NumpadEnter',
key: 'Enter',
text: '\r',
location: 3,
},
Enter: { keyCode: 13, code: 'Enter', key: 'Enter', text: '\r' },
'\r': { keyCode: 13, code: 'Enter', key: 'Enter', text: '\r' },
'\n': { keyCode: 13, code: 'Enter', key: 'Enter', text: '\r' },
ShiftLeft: { keyCode: 16, code: 'ShiftLeft', key: 'Shift', location: 1 },
ShiftRight: { keyCode: 16, code: 'ShiftRight', key: 'Shift', location: 2 },
ControlLeft: {
keyCode: 17,
code: 'ControlLeft',
key: 'Control',
location: 1,
},
ControlRight: {
keyCode: 17,
code: 'ControlRight',
key: 'Control',
location: 2,
},
AltLeft: { keyCode: 18, code: 'AltLeft', key: 'Alt', location: 1 },
AltRight: { keyCode: 18, code: 'AltRight', key: 'Alt', location: 2 },
Pause: { keyCode: 19, code: 'Pause', key: 'Pause' },
CapsLock: { keyCode: 20, code: 'CapsLock', key: 'CapsLock' },
Escape: { keyCode: 27, code: 'Escape', key: 'Escape' },
Convert: { keyCode: 28, code: 'Convert', key: 'Convert' },
NonConvert: { keyCode: 29, code: 'NonConvert', key: 'NonConvert' },
Space: { keyCode: 32, code: 'Space', key: ' ' },
Numpad9: {
keyCode: 33,
shiftKeyCode: 105,
key: 'PageUp',
code: 'Numpad9',
shiftKey: '9',
location: 3,
},
PageUp: { keyCode: 33, code: 'PageUp', key: 'PageUp' },
Numpad3: {
keyCode: 34,
shiftKeyCode: 99,
key: 'PageDown',
code: 'Numpad3',
shiftKey: '3',
location: 3,
},
PageDown: { keyCode: 34, code: 'PageDown', key: 'PageDown' },
End: { keyCode: 35, code: 'End', key: 'End' },
Numpad1: {
keyCode: 35,
shiftKeyCode: 97,
key: 'End',
code: 'Numpad1',
shiftKey: '1',
location: 3,
},
Home: { keyCode: 36, code: 'Home', key: 'Home' },
Numpad7: {
keyCode: 36,
shiftKeyCode: 103,
key: 'Home',
code: 'Numpad7',
shiftKey: '7',
location: 3,
},
ArrowLeft: { keyCode: 37, code: 'ArrowLeft', key: 'ArrowLeft' },
Numpad4: {
keyCode: 37,
shiftKeyCode: 100,
key: 'ArrowLeft',
code: 'Numpad4',
shiftKey: '4',
location: 3,
},
Numpad8: {
keyCode: 38,
shiftKeyCode: 104,
key: 'ArrowUp',
code: 'Numpad8',
shiftKey: '8',
location: 3,
},
ArrowUp: { keyCode: 38, code: 'ArrowUp', key: 'ArrowUp' },
ArrowRight: { keyCode: 39, code: 'ArrowRight', key: 'ArrowRight' },
Numpad6: {
keyCode: 39,
shiftKeyCode: 102,
key: 'ArrowRight',
code: 'Numpad6',
shiftKey: '6',
location: 3,
},
Numpad2: {
keyCode: 40,
shiftKeyCode: 98,
key: 'ArrowDown',
code: 'Numpad2',
shiftKey: '2',
location: 3,
},
ArrowDown: { keyCode: 40, code: 'ArrowDown', key: 'ArrowDown' },
Select: { keyCode: 41, code: 'Select', key: 'Select' },
Open: { keyCode: 43, code: 'Open', key: 'Execute' },
PrintScreen: { keyCode: 44, code: 'PrintScreen', key: 'PrintScreen' },
Insert: { keyCode: 45, code: 'Insert', key: 'Insert' },
Numpad0: {
keyCode: 45,
shiftKeyCode: 96,
key: 'Insert',
code: 'Numpad0',
shiftKey: '0',
location: 3,
},
Delete: { keyCode: 46, code: 'Delete', key: 'Delete' },
NumpadDecimal: {
keyCode: 46,
shiftKeyCode: 110,
code: 'NumpadDecimal',
key: '\u0000',
shiftKey: '.',
location: 3,
},
Digit0: { keyCode: 48, code: 'Digit0', shiftKey: ')', key: '0' },
Digit1: { keyCode: 49, code: 'Digit1', shiftKey: '!', key: '1' },
Digit2: { keyCode: 50, code: 'Digit2', shiftKey: '@', key: '2' },
Digit3: { keyCode: 51, code: 'Digit3', shiftKey: '#', key: '3' },
Digit4: { keyCode: 52, code: 'Digit4', shiftKey: '$', key: '4' },
Digit5: { keyCode: 53, code: 'Digit5', shiftKey: '%', key: '5' },
Digit6: { keyCode: 54, code: 'Digit6', shiftKey: '^', key: '6' },
Digit7: { keyCode: 55, code: 'Digit7', shiftKey: '&', key: '7' },
Digit8: { keyCode: 56, code: 'Digit8', shiftKey: '*', key: '8' },
Digit9: { keyCode: 57, code: 'Digit9', shiftKey: '(', key: '9' },
KeyA: { keyCode: 65, code: 'KeyA', shiftKey: 'A', key: 'a' },
KeyB: { keyCode: 66, code: 'KeyB', shiftKey: 'B', key: 'b' },
KeyC: { keyCode: 67, code: 'KeyC', shiftKey: 'C', key: 'c' },
KeyD: { keyCode: 68, code: 'KeyD', shiftKey: 'D', key: 'd' },
KeyE: { keyCode: 69, code: 'KeyE', shiftKey: 'E', key: 'e' },
KeyF: { keyCode: 70, code: 'KeyF', shiftKey: 'F', key: 'f' },
KeyG: { keyCode: 71, code: 'KeyG', shiftKey: 'G', key: 'g' },
KeyH: { keyCode: 72, code: 'KeyH', shiftKey: 'H', key: 'h' },
KeyI: { keyCode: 73, code: 'KeyI', shiftKey: 'I', key: 'i' },
KeyJ: { keyCode: 74, code: 'KeyJ', shiftKey: 'J', key: 'j' },
KeyK: { keyCode: 75, code: 'KeyK', shiftKey: 'K', key: 'k' },
KeyL: { keyCode: 76, code: 'KeyL', shiftKey: 'L', key: 'l' },
KeyM: { keyCode: 77, code: 'KeyM', shiftKey: 'M', key: 'm' },
KeyN: { keyCode: 78, code: 'KeyN', shiftKey: 'N', key: 'n' },
KeyO: { keyCode: 79, code: 'KeyO', shiftKey: 'O', key: 'o' },
KeyP: { keyCode: 80, code: 'KeyP', shiftKey: 'P', key: 'p' },
KeyQ: { keyCode: 81, code: 'KeyQ', shiftKey: 'Q', key: 'q' },
KeyR: { keyCode: 82, code: 'KeyR', shiftKey: 'R', key: 'r' },
KeyS: { keyCode: 83, code: 'KeyS', shiftKey: 'S', key: 's' },
KeyT: { keyCode: 84, code: 'KeyT', shiftKey: 'T', key: 't' },
KeyU: { keyCode: 85, code: 'KeyU', shiftKey: 'U', key: 'u' },
KeyV: { keyCode: 86, code: 'KeyV', shiftKey: 'V', key: 'v' },
KeyW: { keyCode: 87, code: 'KeyW', shiftKey: 'W', key: 'w' },
KeyX: { keyCode: 88, code: 'KeyX', shiftKey: 'X', key: 'x' },
KeyY: { keyCode: 89, code: 'KeyY', shiftKey: 'Y', key: 'y' },
KeyZ: { keyCode: 90, code: 'KeyZ', shiftKey: 'Z', key: 'z' },
MetaLeft: { keyCode: 91, code: 'MetaLeft', key: 'Meta', location: 1 },
MetaRight: { keyCode: 92, code: 'MetaRight', key: 'Meta', location: 2 },
ContextMenu: { keyCode: 93, code: 'ContextMenu', key: 'ContextMenu' },
NumpadMultiply: {
keyCode: 106,
code: 'NumpadMultiply',
key: '*',
location: 3,
},
NumpadAdd: { keyCode: 107, code: 'NumpadAdd', key: '+', location: 3 },
NumpadSubtract: {
keyCode: 109,
code: 'NumpadSubtract',
key: '-',
location: 3,
},
NumpadDivide: { keyCode: 111, code: 'NumpadDivide', key: '/', location: 3 },
F1: { keyCode: 112, code: 'F1', key: 'F1' },
F2: { keyCode: 113, code: 'F2', key: 'F2' },
F3: { keyCode: 114, code: 'F3', key: 'F3' },
F4: { keyCode: 115, code: 'F4', key: 'F4' },
F5: { keyCode: 116, code: 'F5', key: 'F5' },
F6: { keyCode: 117, code: 'F6', key: 'F6' },
F7: { keyCode: 118, code: 'F7', key: 'F7' },
F8: { keyCode: 119, code: 'F8', key: 'F8' },
F9: { keyCode: 120, code: 'F9', key: 'F9' },
F10: { keyCode: 121, code: 'F10', key: 'F10' },
F11: { keyCode: 122, code: 'F11', key: 'F11' },
F12: { keyCode: 123, code: 'F12', key: 'F12' },
F13: { keyCode: 124, code: 'F13', key: 'F13' },
F14: { keyCode: 125, code: 'F14', key: 'F14' },
F15: { keyCode: 126, code: 'F15', key: 'F15' },
F16: { keyCode: 127, code: 'F16', key: 'F16' },
F17: { keyCode: 128, code: 'F17', key: 'F17' },
F18: { keyCode: 129, code: 'F18', key: 'F18' },
F19: { keyCode: 130, code: 'F19', key: 'F19' },
F20: { keyCode: 131, code: 'F20', key: 'F20' },
F21: { keyCode: 132, code: 'F21', key: 'F21' },
F22: { keyCode: 133, code: 'F22', key: 'F22' },
F23: { keyCode: 134, code: 'F23', key: 'F23' },
F24: { keyCode: 135, code: 'F24', key: 'F24' },
NumLock: { keyCode: 144, code: 'NumLock', key: 'NumLock' },
ScrollLock: { keyCode: 145, code: 'ScrollLock', key: 'ScrollLock' },
AudioVolumeMute: {
keyCode: 173,
code: 'AudioVolumeMute',
key: 'AudioVolumeMute',
},
AudioVolumeDown: {
keyCode: 174,
code: 'AudioVolumeDown',
key: 'AudioVolumeDown',
},
AudioVolumeUp: { keyCode: 175, code: 'AudioVolumeUp', key: 'AudioVolumeUp' },
MediaTrackNext: {
keyCode: 176,
code: 'MediaTrackNext',
key: 'MediaTrackNext',
},
MediaTrackPrevious: {
keyCode: 177,
code: 'MediaTrackPrevious',
key: 'MediaTrackPrevious',
},
MediaStop: { keyCode: 178, code: 'MediaStop', key: 'MediaStop' },
MediaPlayPause: {
keyCode: 179,
code: 'MediaPlayPause',
key: 'MediaPlayPause',
},
Semicolon: { keyCode: 186, code: 'Semicolon', shiftKey: ':', key: ';' },
Equal: { keyCode: 187, code: 'Equal', shiftKey: '+', key: '=' },
NumpadEqual: { keyCode: 187, code: 'NumpadEqual', key: '=', location: 3 },
Comma: { keyCode: 188, code: 'Comma', shiftKey: '<', key: ',' },
Minus: { keyCode: 189, code: 'Minus', shiftKey: '_', key: '-' },
Period: { keyCode: 190, code: 'Period', shiftKey: '>', key: '.' },
Slash: { keyCode: 191, code: 'Slash', shiftKey: '?', key: '/' },
Backquote: { keyCode: 192, code: 'Backquote', shiftKey: '~', key: '`' },
BracketLeft: { keyCode: 219, code: 'BracketLeft', shiftKey: '{', key: '[' },
Backslash: { keyCode: 220, code: 'Backslash', shiftKey: '|', key: '\\' },
BracketRight: { keyCode: 221, code: 'BracketRight', shiftKey: '}', key: ']' },
Quote: { keyCode: 222, code: 'Quote', shiftKey: '"', key: "'" },
AltGraph: { keyCode: 225, code: 'AltGraph', key: 'AltGraph' },
Props: { keyCode: 247, code: 'Props', key: 'CrSel' },
Cancel: { keyCode: 3, key: 'Cancel', code: 'Abort' },
Clear: { keyCode: 12, key: 'Clear', code: 'Numpad5', location: 3 },
Shift: { keyCode: 16, key: 'Shift', code: 'ShiftLeft', location: 1 },
Control: { keyCode: 17, key: 'Control', code: 'ControlLeft', location: 1 },
Alt: { keyCode: 18, key: 'Alt', code: 'AltLeft', location: 1 },
Accept: { keyCode: 30, key: 'Accept' },
ModeChange: { keyCode: 31, key: 'ModeChange' },
' ': { keyCode: 32, key: ' ', code: 'Space' },
Print: { keyCode: 42, key: 'Print' },
Execute: { keyCode: 43, key: 'Execute', code: 'Open' },
'\u0000': { keyCode: 46, key: '\u0000', code: 'NumpadDecimal', location: 3 },
a: { keyCode: 65, key: 'a', code: 'KeyA' },
b: { keyCode: 66, key: 'b', code: 'KeyB' },
c: { keyCode: 67, key: 'c', code: 'KeyC' },
d: { keyCode: 68, key: 'd', code: 'KeyD' },
e: { keyCode: 69, key: 'e', code: 'KeyE' },
f: { keyCode: 70, key: 'f', code: 'KeyF' },
g: { keyCode: 71, key: 'g', code: 'KeyG' },
h: { keyCode: 72, key: 'h', code: 'KeyH' },
i: { keyCode: 73, key: 'i', code: 'KeyI' },
j: { keyCode: 74, key: 'j', code: 'KeyJ' },
k: { keyCode: 75, key: 'k', code: 'KeyK' },
l: { keyCode: 76, key: 'l', code: 'KeyL' },
m: { keyCode: 77, key: 'm', code: 'KeyM' },
n: { keyCode: 78, key: 'n', code: 'KeyN' },
o: { keyCode: 79, key: 'o', code: 'KeyO' },
p: { keyCode: 80, key: 'p', code: 'KeyP' },
q: { keyCode: 81, key: 'q', code: 'KeyQ' },
r: { keyCode: 82, key: 'r', code: 'KeyR' },
s: { keyCode: 83, key: 's', code: 'KeyS' },
t: { keyCode: 84, key: 't', code: 'KeyT' },
u: { keyCode: 85, key: 'u', code: 'KeyU' },
v: { keyCode: 86, key: 'v', code: 'KeyV' },
w: { keyCode: 87, key: 'w', code: 'KeyW' },
x: { keyCode: 88, key: 'x', code: 'KeyX' },
y: { keyCode: 89, key: 'y', code: 'KeyY' },
z: { keyCode: 90, key: 'z', code: 'KeyZ' },
Meta: { keyCode: 91, key: 'Meta', code: 'MetaLeft', location: 1 },
'*': { keyCode: 106, key: '*', code: 'NumpadMultiply', location: 3 },
'+': { keyCode: 107, key: '+', code: 'NumpadAdd', location: 3 },
'-': { keyCode: 109, key: '-', code: 'NumpadSubtract', location: 3 },
'/': { keyCode: 111, key: '/', code: 'NumpadDivide', location: 3 },
';': { keyCode: 186, key: ';', code: 'Semicolon' },
'=': { keyCode: 187, key: '=', code: 'Equal' },
',': { keyCode: 188, key: ',', code: 'Comma' },
'.': { keyCode: 190, key: '.', code: 'Period' },
'`': { keyCode: 192, key: '`', code: 'Backquote' },
'[': { keyCode: 219, key: '[', code: 'BracketLeft' },
'\\': { keyCode: 220, key: '\\', code: 'Backslash' },
']': { keyCode: 221, key: ']', code: 'BracketRight' },
"'": { keyCode: 222, key: "'", code: 'Quote' },
Attn: { keyCode: 246, key: 'Attn' },
CrSel: { keyCode: 247, key: 'CrSel', code: 'Props' },
ExSel: { keyCode: 248, key: 'ExSel' },
EraseEof: { keyCode: 249, key: 'EraseEof' },
Play: { keyCode: 250, key: 'Play' },
ZoomOut: { keyCode: 251, key: 'ZoomOut' },
')': { keyCode: 48, key: ')', code: 'Digit0' },
'!': { keyCode: 49, key: '!', code: 'Digit1' },
'@': { keyCode: 50, key: '@', code: 'Digit2' },
'#': { keyCode: 51, key: '#', code: 'Digit3' },
$: { keyCode: 52, key: '$', code: 'Digit4' },
'%': { keyCode: 53, key: '%', code: 'Digit5' },
'^': { keyCode: 54, key: '^', code: 'Digit6' },
'&': { keyCode: 55, key: '&', code: 'Digit7' },
'(': { keyCode: 57, key: '(', code: 'Digit9' },
A: { keyCode: 65, key: 'A', code: 'KeyA' },
B: { keyCode: 66, key: 'B', code: 'KeyB' },
C: { keyCode: 67, key: 'C', code: 'KeyC' },
D: { keyCode: 68, key: 'D', code: 'KeyD' },
E: { keyCode: 69, key: 'E', code: 'KeyE' },
F: { keyCode: 70, key: 'F', code: 'KeyF' },
G: { keyCode: 71, key: 'G', code: 'KeyG' },
H: { keyCode: 72, key: 'H', code: 'KeyH' },
I: { keyCode: 73, key: 'I', code: 'KeyI' },
J: { keyCode: 74, key: 'J', code: 'KeyJ' },
K: { keyCode: 75, key: 'K', code: 'KeyK' },
L: { keyCode: 76, key: 'L', code: 'KeyL' },
M: { keyCode: 77, key: 'M', code: 'KeyM' },
N: { keyCode: 78, key: 'N', code: 'KeyN' },
O: { keyCode: 79, key: 'O', code: 'KeyO' },
P: { keyCode: 80, key: 'P', code: 'KeyP' },
Q: { keyCode: 81, key: 'Q', code: 'KeyQ' },
R: { keyCode: 82, key: 'R', code: 'KeyR' },
S: { keyCode: 83, key: 'S', code: 'KeyS' },
T: { keyCode: 84, key: 'T', code: 'KeyT' },
U: { keyCode: 85, key: 'U', code: 'KeyU' },
V: { keyCode: 86, key: 'V', code: 'KeyV' },
W: { keyCode: 87, key: 'W', code: 'KeyW' },
X: { keyCode: 88, key: 'X', code: 'KeyX' },
Y: { keyCode: 89, key: 'Y', code: 'KeyY' },
Z: { keyCode: 90, key: 'Z', code: 'KeyZ' },
':': { keyCode: 186, key: ':', code: 'Semicolon' },
'<': { keyCode: 188, key: '<', code: 'Comma' },
_: { keyCode: 189, key: '_', code: 'Minus' },
'>': { keyCode: 190, key: '>', code: 'Period' },
'?': { keyCode: 191, key: '?', code: 'Slash' },
'~': { keyCode: 192, key: '~', code: 'Backquote' },
'{': { keyCode: 219, key: '{', code: 'BracketLeft' },
'|': { keyCode: 220, key: '|', code: 'Backslash' },
'}': { keyCode: 221, key: '}', code: 'BracketRight' },
'"': { keyCode: 222, key: '"', code: 'Quote' },
SoftLeft: { key: 'SoftLeft', code: 'SoftLeft', location: 4 },
SoftRight: { key: 'SoftRight', code: 'SoftRight', location: 4 },
Camera: { keyCode: 44, key: 'Camera', code: 'Camera', location: 4 },
Call: { key: 'Call', code: 'Call', location: 4 },
EndCall: { keyCode: 95, key: 'EndCall', code: 'EndCall', location: 4 },
VolumeDown: {
keyCode: 182,
key: 'VolumeDown',
code: 'VolumeDown',
location: 4,
},
VolumeUp: { keyCode: 183, key: 'VolumeUp', code: 'VolumeUp', location: 4 },
}; | the_stack |
import { MutableObject } from '../model/MutableObject';
import { HashedObject } from '../model/HashedObject';
import { Hash } from 'data/model/Hashing';
import { MutationOp } from 'data/model/MutationOp';
import { HashedSet } from 'data/model/HashedSet';
import { HashReference } from 'data/model/HashReference';
import { Types } from './Types';
import { Logger, LogLevel } from 'util/logging';
type ElmtHash = Hash;
// a simple mutable set with a single writer
abstract class MutableSetOp<T extends HashedObject> extends MutationOp {
constructor(target?: MutableSet<T>) {
super(target);
if (target !== undefined) {
let author = target.getAuthor();
if (author !== undefined) {
this.setAuthor(author);
}
}
}
init(): void {
}
async validate(references: Map<Hash, HashedObject>) {
if (!await super.validate(references)) {
return false;
}
if (! (this.getTargetObject() instanceof MutableSet)) {
return false;
//throw new Error('MutableSetOp.target must be a MutableSet, got a ' + this.getTarget().getClassName() + ' instead.');
}
if (this.getTargetObject().getAuthor() !== undefined &&ย !(this.getTargetObject().getAuthor()?.equals(this.getAuthor()))) {
return false;
//throw new Error('MutableSetOp has author ' + this.getAuthor()?.hash() + ' but points to a target authored by ' + this.getTarget().getAuthor()?.hash() + '.');
}
return true;
}
}
class MutableSetAddOp<T extends HashedObject> extends MutableSetOp<T> {
static className = 'hhs/v0/MutableSetAddOp';
element?: T;
constructor(target?: MutableSet<T>, element?: T) {
super(target);
if (element !== undefined) {
this.element = element;
this.setRandomId();
}
}
getClassName() {
return MutableSetAddOp.className;
}
init() {
super.init();
}
async validate(references: Map<Hash, HashedObject>) {
if (!await super.validate(references)) {
return false;
}
const constraints = (this.getTargetObject() as MutableSet<T>).typeConstraints;
if (!Types.satisfies(this.element, constraints)) {
return false;
//throw new Error('MutableSetAddOp contains a value with an unexpected type.')
}
return true;
}
}
MutableSetAddOp.registerClass(MutableSetAddOp.className, MutableSetAddOp);
class MutableSetDeleteOp<T extends HashedObject> extends MutableSetOp<T> {
static className = 'hhs/v0/MutableSetDeleteOp';
elementHash? : Hash;
deletedOps? : HashedSet<HashReference<MutableSetAddOp<T>>>;
constructor(target?: MutableSet<T>, elementHash?: Hash, addOps?: IterableIterator<HashReference<MutableSetAddOp<T>>>) {
super(target);
this.elementHash = elementHash;
if (addOps !== undefined) {
this.deletedOps = new HashedSet();
for (const addOp of addOps) {
if (addOp.className !== MutableSetAddOp.className) {
throw new Error('Trying to create a delete op referencing an op that is not an addition op.');
}
this.deletedOps.add(addOp);
}
}
}
// need a valid() function, that is called only when an object is NEW and we don't yet
// trust its integrity. init() will be called every time it is loaded (after all the
// fields have been filled in, either by the constructor or by the deliteralization
// mechanism, and after valid, if it is untrusted)
// valid needs all the references also, already validated, to do its checks.
// (all this follows from the need to validate deletedOps)
init() {
super.init();
}
async validate(references: Map<Hash, HashedObject>) {
if (!await super.validate(references)) {
return false;
}
if (this.elementHash === undefined) {
MutableSet.logger.warning('The field elementHash of type MutableSetDeletOp is mandatory.')
return false;
}
if (typeof this.elementHash !== 'string') {
MutableSet.logger.warning('The field elementHash of type MutebleSetDeleteOp should be a string.')
return false;
}
if (this.deletedOps === undefined) {
MutableSet.logger.warning('The field deletedOps of type MutableSetDeleteOp is mandatory');
return false;
}
if (!(this.deletedOps instanceof HashedSet)) {
MutableSet.logger.warning('The field deletedOps of type MutableSetDeleteOp should be a HashedSet.');
return false;
}
for (const ref of (this.deletedOps as HashedSet<HashReference<MutableSetAddOp<T>>>).values()) {
const op = references.get(ref.hash);
if (op === undefined) {
MutableSet.logger.warning('Addition op referenced in MutableSet deletion op is missing from references provided for validation.');
}
if (!(op instanceof MutableSetAddOp)) {
MutableSet.logger.warning('Addition op referenced in MutableSet deletion op has the wrong type in the references provided for validation.');
return false;
}
if (!op.targetObject?.equals(this.targetObject)) {
MutableSet.logger.warning('Addition op referenced in MutableSet deletion op points to a different set.');
return false;
}
const addOp = op as MutableSetAddOp<T>;
if (addOp.element?.hash() !== this.elementHash) {
MutableSet.logger.warning('Addition op referenced in MutableSet deletion op contains an element whose hash does not match the one being deleted.');
return false;
}
}
return true;
}
getClassName() {
return MutableSetDeleteOp.className;
}
}
MutableSetDeleteOp.registerClass(MutableSetDeleteOp.className, MutableSetDeleteOp);
class MutableSet<T extends HashedObject> extends MutableObject {
static className = 'hss/v0/MutableSet';
static opClasses = [MutableSetAddOp.className, MutableSetDeleteOp.className];
static logger = new Logger(MutableSet.className, LogLevel.INFO);
_logger: Logger;
typeConstraints?: Array<string>;
_elements: Map<ElmtHash, T>;
_currentAddOpRefs: Map<ElmtHash, HashedSet<HashReference<T>>>;
//_unsavedAppliedOps: Set<Hash>;
_addElementCallback? : (element: T) => void;
_deleteElementCallback? : (element: T) => void;
constructor() {
super(MutableSet.opClasses);
this._logger = MutableSet.logger;
this.setRandomId();
this._elements = new Map();
this._currentAddOpRefs = new Map();
//this._unsavedAppliedOps = new Set();
}
init(): void {
}
async validate(references: Map<Hash, HashedObject>) {
references;
return Types.isTypeConstraint(this.typeConstraints);
}
async add(element: T) {
let op = new MutableSetAddOp(this, element);
await this.applyNewOp(op);
}
async delete(element: T) {
return await this.deleteByHash(element.hash());
}
async deleteByHash(hash: Hash): Promise<boolean> {
let addOpRefs = this._currentAddOpRefs.get(hash);
if (addOpRefs !== undefined && addOpRefs.size() > 0) {
let op = new MutableSetDeleteOp(this, hash, addOpRefs.values());
await this.applyNewOp(op);
return true;
} else {
return false;
}
}
has(element: T) {
return this.hasByHash(element.hash());
}
hasByHash(hash: Hash) {
return this._elements.get(hash) !== undefined;
}
get(hash: Hash) : T |ย undefined {
return this._elements.get(hash);
}
size() {
return this._elements.size;
}
values() {
return this._elements.values();
}
mutate(op: MutationOp): Promise<boolean> {
let mutated = false;
if (op instanceof MutableSetAddOp ) {
const addOp = op as MutableSetAddOp<T>;
let hash = op.element.hash();
if (hash === undefined) {
throw new Error('Trying to add an element to set, but the element is undefined.');
}
let current = this._currentAddOpRefs.get(hash);
if (current === undefined)ย {
current = new HashedSet();
this._currentAddOpRefs.set(hash, current);
}
mutated = current.size() === 0;
current.add(addOp.createReference());
this._elements.set(hash, addOp.element as T)
if (mutated) {
if (this._addElementCallback !== undefined) {
try {
this._addElementCallback(addOp.element as T);
} catch (e) {
this._logger.warning(() => ('Error calling MutableSet element addition callback on op ' + addOp.hash()));
}
}
}
} else if (op instanceof MutableSetDeleteOp) {
const deleteOp = op as MutableSetDeleteOp<T>;
let hash = deleteOp.elementHash;
if (hash === undefined) {
throw new Error('Trying to remove an element from set, but elementHash is undefined.');
}
let current = this._currentAddOpRefs.get(hash);
if (current !== undefined) {
if (deleteOp.deletedOps !== undefined) {
for (const opRef of deleteOp.deletedOps.values())ย {
current.remove(opRef);
}
}
if (current.size() === 0) {
mutated = true;
const deleted = this._elements.get(hash) as T;
this._elements.delete(hash);
this._currentAddOpRefs.delete(hash);
if (this._deleteElementCallback !== undefined) {
try {
this._deleteElementCallback(deleted);
} catch (e) {
this._logger.warning(() => ('Error calling MutableSet element deletion callback on op ' + deleteOp.hash()));
}
}
}
}
} else {
throw new Error("Method not implemented.");
}
return Promise.resolve(mutated);
}
onAddition(callback: (elem: T) => void) {
this._addElementCallback = callback;
}
onDeletion(callback: (elem: T) => void) {
this._deleteElementCallback = callback;
}
getClassName(): string {
return MutableSet.className;
}
}
MutableSet.registerClass(MutableSet.className, MutableSet);
export { MutableSet }; | the_stack |
import * as React from "react";
import * as Hammer from "hammerjs";
import { Graphics, Prototypes, Point, Geometry } from "../../../../core";
import * as globals from "../../../globals";
import * as R from "../../../resources";
import { toSVGNumber } from "../../../utils";
import { PopupView } from "../../../controllers";
import { ButtonRaised } from "../../../components";
import { InputNumber } from "../../panels/widgets/controls";
import { HandlesDragContext, HandleViewProps } from "./common";
import { strings } from "../../../../strings";
export interface InputCurveHandleViewProps extends HandleViewProps {
handle: Prototypes.Handles.InputCurve;
}
export interface InputCurveHandleViewState {
enabled: boolean;
drawing: boolean;
points: Point[];
}
export class InputCurveHandleView extends React.Component<
InputCurveHandleViewProps,
InputCurveHandleViewState
> {
public refs: {
interaction: SVGRectElement;
};
public state: InputCurveHandleViewState = {
enabled: false,
drawing: false,
points: [],
};
public hammer: HammerManager;
public getPoint(x: number, y: number): Point {
const bbox = this.refs.interaction.getBoundingClientRect();
x -= bbox.left;
y -= bbox.top + bbox.height;
x /= this.props.zoom.scale;
y /= -this.props.zoom.scale;
// Scale x, y
const w = Math.abs(this.props.handle.x2 - this.props.handle.x1);
const h = Math.abs(this.props.handle.y2 - this.props.handle.y1);
return {
x: (x - w / 2) / (w / 2),
y: (y - h / 2) / (w / 2),
};
}
public getBezierCurvesFromMousePoints(points: Point[]) {
if (points.length < 2) {
return [];
}
const segs: Graphics.LineSegmentParametrization[] = [];
for (let i = 0; i < points.length - 1; i++) {
segs.push(
new Graphics.LineSegmentParametrization(points[i], points[i + 1])
);
}
const lp = new Graphics.MultiCurveParametrization(segs);
const lpLength = lp.getLength();
const segments = Math.ceil(lpLength / 0.2);
const sampleAtS = (s: number) => {
const p = lp.getPointAtS(s);
let tx = 0,
ty = 0;
for (let k = -5; k <= 5; k++) {
let ks = s + ((k / 40) * lpLength) / segments;
ks = Math.max(0, Math.min(lpLength, ks));
const t = lp.getTangentAtS(ks);
tx += t.x;
ty += t.y;
}
const t = Geometry.vectorNormalize({ x: tx, y: ty });
return [p, t];
};
let [p0, t0] = sampleAtS(0);
let s0 = 0;
const curves: Point[][] = [];
for (let i = 1; i <= segments; i++) {
const s = (i / segments) * lpLength;
const [pi, ti] = sampleAtS(s);
const ds = (s - s0) / 3;
curves.push([
p0,
Geometry.vectorAdd(p0, Geometry.vectorScale(t0, ds)),
Geometry.vectorAdd(pi, Geometry.vectorScale(ti, -ds)),
pi,
]);
s0 = s;
p0 = pi;
t0 = ti;
}
return curves;
}
public componentDidMount() {
this.hammer = new Hammer(this.refs.interaction);
this.hammer.on("panstart", (e) => {
const x = e.center.x - e.deltaX;
const y = e.center.y - e.deltaY;
this.setState({
drawing: true,
points: [this.getPoint(x, y)],
});
});
this.hammer.on("pan", (e) => {
this.state.points.push(this.getPoint(e.center.x, e.center.y));
this.setState({
points: this.state.points,
});
});
this.hammer.on("panend", () => {
const curve = this.getBezierCurvesFromMousePoints(this.state.points);
const context = new HandlesDragContext();
this.props.onDragStart(this.props.handle, context);
context.emit("end", { value: curve });
this.setState({
drawing: false,
enabled: false,
});
});
}
public componentWillUnmount() {
this.hammer.destroy();
}
public renderDrawing() {
const handle = this.props.handle;
const fX = (x: number) =>
x * this.props.zoom.scale + this.props.zoom.centerX;
const fY = (y: number) =>
-y * this.props.zoom.scale + this.props.zoom.centerY;
const transformPoint = (p: Point) => {
const scaler = Math.abs(handle.x2 - handle.x1) / 2;
const x = p.x * scaler + (handle.x1 + handle.x2) / 2;
const y = p.y * scaler + (handle.y1 + handle.y2) / 2;
return {
x: fX(x),
y: fY(y),
};
};
return (
<path
d={
"M" +
this.state.points
.map((p) => {
const pt = transformPoint(p);
return `${toSVGNumber(pt.x)},${toSVGNumber(pt.y)}`;
})
.join("L")
}
className="handle-hint element-line"
/>
);
}
public renderButton(x: number, y: number) {
const margin = 2;
const cx = x - 16 - margin;
const cy = y + 16 + margin;
return (
<g
className="handle-button"
onClick={() => {
this.setState({ enabled: true });
}}
>
<rect x={cx - 16} y={cy - 16} width={32} height={32} />
<image
xlinkHref={R.getSVGIcon("Edit")}
x={cx - 12}
y={cy - 12}
width={24}
height={24}
/>
</g>
);
}
// eslint-disable-next-line
public renderSpiralButton(x: number, y: number) {
const margin = 2;
const cx = x - 16 - margin;
const cy = y + 16 + margin;
let anchorElement: SVGRectElement;
return (
<g
className="handle-button"
// eslint-disable-next-line
onClick={() => {
globals.popupController.popupAt(
// eslint-disable-next-line
(context) => {
let windings = 4;
let startAngle = 180;
return (
<PopupView context={context}>
<div style={{ padding: "10px" }}>
<div className="charticulator__widget-row">
<span className="charticulator__widget-row-label">
{strings.handles.windings}:
</span>
<InputNumber
defaultValue={windings}
onEnter={(value) => {
windings = value;
return true;
}}
/>
</div>
<div className="charticulator__widget-row">
<span className="charticulator__widget-row-label">
{strings.handles.startAngle}:
</span>
<InputNumber
defaultValue={startAngle}
onEnter={(value) => {
startAngle = value;
return true;
}}
/>
</div>
<div style={{ textAlign: "right", marginTop: "10px" }}>
<ButtonRaised
text={strings.handles.drawSpiral}
onClick={() => {
context.close();
// Make sprial and emit.
const dragContext = new HandlesDragContext();
const curve: Point[][] = [];
this.props.onDragStart(
this.props.handle,
dragContext
);
const thetaStart = Geometry.degreesToRadians(
startAngle
);
const thetaEnd = thetaStart + windings * Math.PI * 2;
const N = 64;
const a = 1 / thetaEnd; // r = a theta
const swapXY = (p: Point) => {
return { x: p.y, y: p.x };
};
for (let i = 0; i < N; i++) {
const theta1 =
thetaStart + (i / N) * (thetaEnd - thetaStart);
const theta2 =
thetaStart +
((i + 1) / N) * (thetaEnd - thetaStart);
const scaler = 3 / (theta2 - theta1);
const r1 = a * theta1;
const r2 = a * theta2;
const p1 = {
x: r1 * Math.cos(theta1),
y: r1 * Math.sin(theta1),
};
const p2 = {
x: r2 * Math.cos(theta2),
y: r2 * Math.sin(theta2),
};
const cp1 = {
x:
p1.x +
(a *
(Math.cos(theta1) -
theta1 * Math.sin(theta1))) /
scaler,
y:
p1.y +
(a *
(Math.sin(theta1) +
theta1 * Math.cos(theta1))) /
scaler,
};
const cp2 = {
x:
p2.x -
(a *
(Math.cos(theta2) -
theta2 * Math.sin(theta2))) /
scaler,
y:
p2.y -
(a *
(Math.sin(theta2) +
theta2 * Math.cos(theta2))) /
scaler,
};
curve.push([p1, cp1, cp2, p2].map(swapXY));
}
dragContext.emit("end", { value: curve });
}}
/>
</div>
</div>
</PopupView>
);
},
{ anchor: anchorElement }
);
}}
>
<rect
x={cx - 16}
y={cy - 16}
width={32}
height={32}
ref={(e) => (anchorElement = e)}
/>
<image
xlinkHref={R.getSVGIcon("scaffold/spiral")}
x={cx - 12}
y={cy - 12}
width={24}
height={24}
/>
</g>
);
}
public render() {
const handle = this.props.handle;
const fX = (x: number) =>
x * this.props.zoom.scale + this.props.zoom.centerX;
const fY = (y: number) =>
-y * this.props.zoom.scale + this.props.zoom.centerY;
return (
<g className="handle">
<rect
ref="interaction"
style={{
pointerEvents: this.state.enabled ? "fill" : "none",
cursor: "crosshair",
}}
className="handle-ghost element-region"
x={Math.min(fX(handle.x1), fX(handle.x2))}
y={Math.min(fY(handle.y1), fY(handle.y2))}
width={Math.abs(fX(handle.x1) - fX(handle.x2))}
height={Math.abs(fY(handle.y1) - fY(handle.y2))}
/>
{this.state.drawing ? this.renderDrawing() : null}
{!this.state.enabled ? (
<g>
{this.renderSpiralButton(
Math.max(fX(handle.x1), fX(handle.x2)) - 38,
Math.min(fY(handle.y1), fY(handle.y2))
)}
{this.renderButton(
Math.max(fX(handle.x1), fX(handle.x2)),
Math.min(fY(handle.y1), fY(handle.y2))
)}
</g>
) : null}
</g>
);
}
} | the_stack |
import Point from '../util/point';
import clipLine from './clip_line';
import PathInterpolator from './path_interpolator';
import * as intersectionTests from '../util/intersection_tests';
import Grid from './grid_index';
import {mat4, vec4} from 'gl-matrix';
import ONE_EM from '../symbol/one_em';
import assert from 'assert';
import * as projection from '../symbol/projection';
import type Transform from '../geo/transform';
import type {SingleCollisionBox} from '../data/bucket/symbol_bucket';
import type {
GlyphOffsetArray,
SymbolLineVertexArray
} from '../data/array_types';
// When a symbol crosses the edge that causes it to be included in
// collision detection, it will cause changes in the symbols around
// it. This constant specifies how many pixels to pad the edge of
// the viewport for collision detection so that the bulk of the changes
// occur offscreen. Making this constant greater increases label
// stability, but it's expensive.
const viewportPadding = 100;
/**
* A collision index used to prevent symbols from overlapping. It keep tracks of
* where previous symbols have been placed and is used to check if a new
* symbol overlaps with any previously added symbols.
*
* There are two steps to insertion: first placeCollisionBox/Circles checks if
* there's room for a symbol, then insertCollisionBox/Circles actually puts the
* symbol in the index. The two step process allows paired symbols to be inserted
* together even if they overlap.
*
* @private
*/
class CollisionIndex {
grid: Grid;
ignoredGrid: Grid;
transform: Transform;
pitchfactor: number;
screenRightBoundary: number;
screenBottomBoundary: number;
gridRightBoundary: number;
gridBottomBoundary: number;
constructor(
transform: Transform,
grid: Grid = new Grid(transform.width + 2 * viewportPadding, transform.height + 2 * viewportPadding, 25),
ignoredGrid: Grid = new Grid(transform.width + 2 * viewportPadding, transform.height + 2 * viewportPadding, 25)
) {
this.transform = transform;
this.grid = grid;
this.ignoredGrid = ignoredGrid;
this.pitchfactor = Math.cos(transform._pitch) * transform.cameraToCenterDistance;
this.screenRightBoundary = transform.width + viewportPadding;
this.screenBottomBoundary = transform.height + viewportPadding;
this.gridRightBoundary = transform.width + 2 * viewportPadding;
this.gridBottomBoundary = transform.height + 2 * viewportPadding;
}
placeCollisionBox(
collisionBox: SingleCollisionBox,
allowOverlap: boolean,
textPixelRatio: number,
posMatrix: mat4,
collisionGroupPredicate?: any
): {
box: Array<number>;
offscreen: boolean;
} {
const projectedPoint = this.projectAndGetPerspectiveRatio(posMatrix, collisionBox.anchorPointX, collisionBox.anchorPointY);
const tileToViewport = textPixelRatio * projectedPoint.perspectiveRatio;
const tlX = collisionBox.x1 * tileToViewport + projectedPoint.point.x;
const tlY = collisionBox.y1 * tileToViewport + projectedPoint.point.y;
const brX = collisionBox.x2 * tileToViewport + projectedPoint.point.x;
const brY = collisionBox.y2 * tileToViewport + projectedPoint.point.y;
if (!this.isInsideGrid(tlX, tlY, brX, brY) ||
(!allowOverlap && this.grid.hitTest(tlX, tlY, brX, brY, collisionGroupPredicate))) {
return {
box: [],
offscreen: false
};
}
return {
box: [tlX, tlY, brX, brY],
offscreen: this.isOffscreen(tlX, tlY, brX, brY)
};
}
placeCollisionCircles(
allowOverlap: boolean,
symbol: any,
lineVertexArray: SymbolLineVertexArray,
glyphOffsetArray: GlyphOffsetArray,
fontSize: number,
posMatrix: mat4,
labelPlaneMatrix: mat4,
labelToScreenMatrix: mat4,
showCollisionCircles: boolean,
pitchWithMap: boolean,
collisionGroupPredicate: any,
circlePixelDiameter: number,
textPixelPadding: number
): {
circles: Array<number>;
offscreen: boolean;
collisionDetected: boolean;
} {
const placedCollisionCircles = [];
const tileUnitAnchorPoint = new Point(symbol.anchorX, symbol.anchorY);
const screenAnchorPoint = projection.project(tileUnitAnchorPoint, posMatrix);
const perspectiveRatio = projection.getPerspectiveRatio(this.transform.cameraToCenterDistance, screenAnchorPoint.signedDistanceFromCamera);
const labelPlaneFontSize = pitchWithMap ? fontSize / perspectiveRatio : fontSize * perspectiveRatio;
const labelPlaneFontScale = labelPlaneFontSize / ONE_EM;
const labelPlaneAnchorPoint = projection.project(tileUnitAnchorPoint, labelPlaneMatrix).point;
const projectionCache = {};
const lineOffsetX = symbol.lineOffsetX * labelPlaneFontScale;
const lineOffsetY = symbol.lineOffsetY * labelPlaneFontScale;
const firstAndLastGlyph = projection.placeFirstAndLastGlyph(
labelPlaneFontScale,
glyphOffsetArray,
lineOffsetX,
lineOffsetY,
/*flip*/ false,
labelPlaneAnchorPoint,
tileUnitAnchorPoint,
symbol,
lineVertexArray,
labelPlaneMatrix,
projectionCache);
let collisionDetected = false;
let inGrid = false;
let entirelyOffscreen = true;
if (firstAndLastGlyph) {
const radius = circlePixelDiameter * 0.5 * perspectiveRatio + textPixelPadding;
const screenPlaneMin = new Point(-viewportPadding, -viewportPadding);
const screenPlaneMax = new Point(this.screenRightBoundary, this.screenBottomBoundary);
const interpolator = new PathInterpolator();
// Construct a projected path from projected line vertices. Anchor points are ignored and removed
const first = firstAndLastGlyph.first;
const last = firstAndLastGlyph.last;
let projectedPath = [];
for (let i = first.path.length - 1; i >= 1; i--) {
projectedPath.push(first.path[i]);
}
for (let i = 1; i < last.path.length; i++) {
projectedPath.push(last.path[i]);
}
assert(projectedPath.length >= 2);
// Tolerate a slightly longer distance than one diameter between two adjacent circles
const circleDist = radius * 2.5;
// The path might need to be converted into screen space if a pitched map is used as the label space
if (labelToScreenMatrix) {
const screenSpacePath = projectedPath.map(p => projection.project(p, labelToScreenMatrix));
// Do not try to place collision circles if even of the points is behind the camera.
// This is a plausible scenario with big camera pitch angles
if (screenSpacePath.some(point => point.signedDistanceFromCamera <= 0)) {
projectedPath = [];
} else {
projectedPath = screenSpacePath.map(p => p.point);
}
}
let segments = [];
if (projectedPath.length > 0) {
// Quickly check if the path is fully inside or outside of the padded collision region.
// For overlapping paths we'll only create collision circles for the visible segments
const minPoint = projectedPath[0].clone();
const maxPoint = projectedPath[0].clone();
for (let i = 1; i < projectedPath.length; i++) {
minPoint.x = Math.min(minPoint.x, projectedPath[i].x);
minPoint.y = Math.min(minPoint.y, projectedPath[i].y);
maxPoint.x = Math.max(maxPoint.x, projectedPath[i].x);
maxPoint.y = Math.max(maxPoint.y, projectedPath[i].y);
}
if (minPoint.x >= screenPlaneMin.x && maxPoint.x <= screenPlaneMax.x &&
minPoint.y >= screenPlaneMin.y && maxPoint.y <= screenPlaneMax.y) {
// Quad fully visible
segments = [projectedPath];
} else if (maxPoint.x < screenPlaneMin.x || minPoint.x > screenPlaneMax.x ||
maxPoint.y < screenPlaneMin.y || minPoint.y > screenPlaneMax.y) {
// Not visible
segments = [];
} else {
segments = clipLine([projectedPath], screenPlaneMin.x, screenPlaneMin.y, screenPlaneMax.x, screenPlaneMax.y);
}
}
for (const seg of segments) {
// interpolate positions for collision circles. Add a small padding to both ends of the segment
assert(seg.length > 0);
interpolator.reset(seg, radius * 0.25);
let numCircles = 0;
if (interpolator.length <= 0.5 * radius) {
numCircles = 1;
} else {
numCircles = Math.ceil(interpolator.paddedLength / circleDist) + 1;
}
for (let i = 0; i < numCircles; i++) {
const t = i / Math.max(numCircles - 1, 1);
const circlePosition = interpolator.lerp(t);
// add viewport padding to the position and perform initial collision check
const centerX = circlePosition.x + viewportPadding;
const centerY = circlePosition.y + viewportPadding;
placedCollisionCircles.push(centerX, centerY, radius, 0);
const x1 = centerX - radius;
const y1 = centerY - radius;
const x2 = centerX + radius;
const y2 = centerY + radius;
entirelyOffscreen = entirelyOffscreen && this.isOffscreen(x1, y1, x2, y2);
inGrid = inGrid || this.isInsideGrid(x1, y1, x2, y2);
if (!allowOverlap) {
if (this.grid.hitTestCircle(centerX, centerY, radius, collisionGroupPredicate)) {
// Don't early exit if we're showing the debug circles because we still want to calculate
// which circles are in use
collisionDetected = true;
if (!showCollisionCircles) {
return {
circles: [],
offscreen: false,
collisionDetected
};
}
}
}
}
}
}
return {
circles: ((!showCollisionCircles && collisionDetected) || !inGrid) ? [] : placedCollisionCircles,
offscreen: entirelyOffscreen,
collisionDetected
};
}
/**
* Because the geometries in the CollisionIndex are an approximation of the shape of
* symbols on the map, we use the CollisionIndex to look up the symbol part of
* `queryRenderedFeatures`.
*
* @private
*/
queryRenderedSymbols(viewportQueryGeometry: Array<Point>) {
if (viewportQueryGeometry.length === 0 || (this.grid.keysLength() === 0 && this.ignoredGrid.keysLength() === 0)) {
return {};
}
const query = [];
let minX = Infinity;
let minY = Infinity;
let maxX = -Infinity;
let maxY = -Infinity;
for (const point of viewportQueryGeometry) {
const gridPoint = new Point(point.x + viewportPadding, point.y + viewportPadding);
minX = Math.min(minX, gridPoint.x);
minY = Math.min(minY, gridPoint.y);
maxX = Math.max(maxX, gridPoint.x);
maxY = Math.max(maxY, gridPoint.y);
query.push(gridPoint);
}
const features = this.grid.query(minX, minY, maxX, maxY)
.concat(this.ignoredGrid.query(minX, minY, maxX, maxY));
const seenFeatures = {};
const result = {};
for (const feature of features) {
const featureKey = feature.key;
// Skip already seen features.
if (seenFeatures[featureKey.bucketInstanceId] === undefined) {
seenFeatures[featureKey.bucketInstanceId] = {};
}
if (seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex]) {
continue;
}
// Check if query intersects with the feature box
// "Collision Circles" for line labels are treated as boxes here
// Since there's no actual collision taking place, the circle vs. square
// distinction doesn't matter as much, and box geometry is easier
// to work with.
const bbox = [
new Point(feature.x1, feature.y1),
new Point(feature.x2, feature.y1),
new Point(feature.x2, feature.y2),
new Point(feature.x1, feature.y2)
];
if (!intersectionTests.polygonIntersectsPolygon(query, bbox)) {
continue;
}
seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex] = true;
if (result[featureKey.bucketInstanceId] === undefined) {
result[featureKey.bucketInstanceId] = [];
}
result[featureKey.bucketInstanceId].push(featureKey.featureIndex);
}
return result;
}
insertCollisionBox(collisionBox: Array<number>, ignorePlacement: boolean, bucketInstanceId: number, featureIndex: number, collisionGroupID: number) {
const grid = ignorePlacement ? this.ignoredGrid : this.grid;
const key = {bucketInstanceId, featureIndex, collisionGroupID};
grid.insert(key, collisionBox[0], collisionBox[1], collisionBox[2], collisionBox[3]);
}
insertCollisionCircles(collisionCircles: Array<number>, ignorePlacement: boolean, bucketInstanceId: number, featureIndex: number, collisionGroupID: number) {
const grid = ignorePlacement ? this.ignoredGrid : this.grid;
const key = {bucketInstanceId, featureIndex, collisionGroupID};
for (let k = 0; k < collisionCircles.length; k += 4) {
grid.insertCircle(key, collisionCircles[k], collisionCircles[k + 1], collisionCircles[k + 2]);
}
}
projectAndGetPerspectiveRatio(posMatrix: mat4, x: number, y: number) {
const p = vec4.fromValues(x, y, 0, 1);
projection.xyTransformMat4(p, p, posMatrix);
const a = new Point(
(((p[0] / p[3] + 1) / 2) * this.transform.width) + viewportPadding,
(((-p[1] / p[3] + 1) / 2) * this.transform.height) + viewportPadding
);
return {
point: a,
// See perspective ratio comment in symbol_sdf.vertex
// We're doing collision detection in viewport space so we need
// to scale down boxes in the distance
perspectiveRatio: 0.5 + 0.5 * (this.transform.cameraToCenterDistance / p[3])
};
}
isOffscreen(x1: number, y1: number, x2: number, y2: number) {
return x2 < viewportPadding || x1 >= this.screenRightBoundary || y2 < viewportPadding || y1 > this.screenBottomBoundary;
}
isInsideGrid(x1: number, y1: number, x2: number, y2: number) {
return x2 >= 0 && x1 < this.gridRightBoundary && y2 >= 0 && y1 < this.gridBottomBoundary;
}
/*
* Returns a matrix for transforming collision shapes to viewport coordinate space.
* Use this function to render e.g. collision circles on the screen.
* example transformation: clipPos = glCoordMatrix * viewportMatrix * circle_pos
*/
getViewportMatrix() {
const m = mat4.identity([] as any);
mat4.translate(m, m, [-viewportPadding, -viewportPadding, 0.0]);
return m;
}
}
export default CollisionIndex; | the_stack |
function alliances(show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('alliances', { show_column_headings, version })
}
/**
* Public information about an alliance
*
* @param {number} alliance_id - An EVE alliance ID
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function alliances_alliance(alliance_id: number, show_column_headings: boolean = true, version: string = "v3"): SheetsArray {
if (!alliance_id) throw new Error(`alliance_id is required`);
return invoke('alliances_alliance', { alliance_id, show_column_headings, version })
}
/**
* Return contacts of an alliance
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function alliances_alliance_contacts(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('alliances_alliance_contacts', { name, show_column_headings, version })
}
/**
* Return custom labels for an alliance's contacts
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function alliances_alliance_contacts_labels(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('alliances_alliance_contacts_labels', { name, show_column_headings, version })
}
/**
* List all current member corporations of an alliance
*
* @param {number} alliance_id - An EVE alliance ID
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function alliances_alliance_corporations(alliance_id: number, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!alliance_id) throw new Error(`alliance_id is required`);
return invoke('alliances_alliance_corporations', { alliance_id, show_column_headings, version })
}
/**
* Get the icon urls for a alliance
*
* @param {number} alliance_id - An EVE alliance ID
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function alliances_alliance_icons(alliance_id: number, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!alliance_id) throw new Error(`alliance_id is required`);
return invoke('alliances_alliance_icons', { alliance_id, show_column_headings, version })
}
/**
* Bulk lookup of character IDs to corporation, alliance and faction
*
* @param {number[]} characters - The character IDs to fetch affiliations for. All characters must exist, or none will be returned
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_affiliation(characters: number[], show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
if (!characters) throw new Error(`characters is required`);
return invoke('characters_affiliation', { characters, show_column_headings, version })
}
/**
* Public information about a character
*
* @param {number} character_id - An EVE character ID
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character(character_id: number, show_column_headings: boolean = true, version: string = "v5"): SheetsArray {
if (!character_id) throw new Error(`character_id is required`);
return invoke('characters_character', { character_id, show_column_headings, version })
}
/**
* Return a list of agents research information for a character. The formula for finding the current research points with an agent is: currentPoints = remainderPoints + pointsPerDay * days(currentTime - researchStartDate)
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_agents_research(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('characters_character_agents_research', { name, show_column_headings, version })
}
/**
* Return a list of the characters assets
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_assets(name?: string, show_column_headings: boolean = true, version: string = "v5"): SheetsArray {
return invoke('characters_character_assets', { name, show_column_headings, version })
}
/**
* Return locations for a set of item ids, which you can get from character assets endpoint. Coordinates for items in hangars or stations are set to (0,0,0)
*
* @param {number[]} item_ids - A list of item ids
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_assets_locations(item_ids: number[], name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
if (!item_ids) throw new Error(`item_ids is required`);
return invoke('characters_character_assets_locations', { item_ids, name, show_column_headings, version })
}
/**
* Return names for a set of item ids, which you can get from character assets endpoint. Typically used for items that can customize names, like containers or ships.
*
* @param {number[]} item_ids - A list of item ids
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_assets_names(item_ids: number[], name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!item_ids) throw new Error(`item_ids is required`);
return invoke('characters_character_assets_names', { item_ids, name, show_column_headings, version })
}
/**
* Return attributes of a character
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_attributes(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('characters_character_attributes', { name, show_column_headings, version })
}
/**
* Return a list of blueprints the character owns
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_blueprints(name?: string, show_column_headings: boolean = true, version: string = "v3"): SheetsArray {
return invoke('characters_character_blueprints', { name, show_column_headings, version })
}
/**
* A list of your character's personal bookmarks
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_bookmarks(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('characters_character_bookmarks', { name, show_column_headings, version })
}
/**
* A list of your character's personal bookmark folders
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_bookmarks_folders(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('characters_character_bookmarks_folders', { name, show_column_headings, version })
}
/**
* Get 50 event summaries from the calendar. If no from_event ID is given, the resource will return the next 50 chronological event summaries from now. If a from_event ID is specified, it will return the next 50 chronological event summaries from after that event
*
* @param {number} from_event - The event ID to retrieve events from
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_calendar(from_event?: number, name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('characters_character_calendar', { from_event, name, show_column_headings, version })
}
/**
* Get all the information for a specific event
*
* @param {number} event_id - The id of the event requested
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_calendar_event(event_id: number, name?: string, show_column_headings: boolean = true, version: string = "v3"): SheetsArray {
if (!event_id) throw new Error(`event_id is required`);
return invoke('characters_character_calendar_event', { event_id, name, show_column_headings, version })
}
/**
* Get all invited attendees for a given event
*
* @param {number} event_id - The id of the event requested
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_calendar_event_attendees(event_id: number, name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!event_id) throw new Error(`event_id is required`);
return invoke('characters_character_calendar_event_attendees', { event_id, name, show_column_headings, version })
}
/**
* A list of the character's clones
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_clones(name?: string, show_column_headings: boolean = true, version: string = "v3"): SheetsArray {
return invoke('characters_character_clones', { name, show_column_headings, version })
}
/**
* Return contacts of a character
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_contacts(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('characters_character_contacts', { name, show_column_headings, version })
}
/**
* Return custom labels for a character's contacts
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_contacts_labels(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('characters_character_contacts_labels', { name, show_column_headings, version })
}
/**
* Returns contracts available to a character, only if the character is issuer, acceptor or assignee. Only returns contracts no older than 30 days, or if the status is "in_progress".
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_contracts(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('characters_character_contracts', { name, show_column_headings, version })
}
/**
* Lists bids on a particular auction contract
*
* @param {number} contract_id - ID of a contract
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_contracts_contract_bids(contract_id: number, name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!contract_id) throw new Error(`contract_id is required`);
return invoke('characters_character_contracts_contract_bids', { contract_id, name, show_column_headings, version })
}
/**
* Lists items of a particular contract
*
* @param {number} contract_id - ID of a contract
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_contracts_contract_items(contract_id: number, name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!contract_id) throw new Error(`contract_id is required`);
return invoke('characters_character_contracts_contract_items', { contract_id, name, show_column_headings, version })
}
/**
* Get a list of all the corporations a character has been a member of
*
* @param {number} character_id - An EVE character ID
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_corporationhistory(character_id: number, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
if (!character_id) throw new Error(`character_id is required`);
return invoke('characters_character_corporationhistory', { character_id, show_column_headings, version })
}
/**
* Return a character's jump activation and fatigue information
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_fatigue(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('characters_character_fatigue', { name, show_column_headings, version })
}
/**
* Return fittings of a character
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_fittings(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('characters_character_fittings', { name, show_column_headings, version })
}
/**
* Return the fleet ID the character is in, if any.
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_fleet(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('characters_character_fleet', { name, show_column_headings, version })
}
/**
* Statistical overview of a character involved in faction warfare
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_fw_stats(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('characters_character_fw_stats', { name, show_column_headings, version })
}
/**
* Return implants on the active clone of a character
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_implants(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('characters_character_implants', { name, show_column_headings, version })
}
/**
* List industry jobs placed by a character
*
* @param {boolean} include_completed - Whether to retrieve completed character industry jobs. Only includes jobs from the past 90 days
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_industry_jobs(include_completed?: boolean, name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('characters_character_industry_jobs', { include_completed, name, show_column_headings, version })
}
/**
* Return a list of a character's kills and losses going back 90 days
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_killmails_recent(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('characters_character_killmails_recent', { name, show_column_headings, version })
}
/**
* Information about the characters current location. Returns the current solar system id, and also the current station or structure ID if applicable
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_location(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('characters_character_location', { name, show_column_headings, version })
}
/**
* Return a list of loyalty points for all corporations the character has worked for
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_loyalty_points(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('characters_character_loyalty_points', { name, show_column_headings, version })
}
/**
* Return the 50 most recent mail headers belonging to the character that match the query criteria. Queries can be filtered by label, and last_mail_id can be used to paginate backwards
*
* @param {number[]} labels - Fetch only mails that match one or more of the given labels
* @param {number} last_mail_id - List only mail with an ID lower than the given ID, if present
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_mail(labels?: number[], last_mail_id?: number, name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('characters_character_mail', { labels, last_mail_id, name, show_column_headings, version })
}
/**
* Return a list of the users mail labels, unread counts for each label and a total unread count.
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_mail_labels(name?: string, show_column_headings: boolean = true, version: string = "v3"): SheetsArray {
return invoke('characters_character_mail_labels', { name, show_column_headings, version })
}
/**
* Return all mailing lists that the character is subscribed to
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_mail_lists(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('characters_character_mail_lists', { name, show_column_headings, version })
}
/**
* Return the contents of an EVE mail
*
* @param {number} mail_id - An EVE mail ID
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_mail_mail(mail_id: number, name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!mail_id) throw new Error(`mail_id is required`);
return invoke('characters_character_mail_mail', { mail_id, name, show_column_headings, version })
}
/**
* Return a list of medals the character has
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_medals(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('characters_character_medals', { name, show_column_headings, version })
}
/**
* Paginated record of all mining done by a character for the past 30 days
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_mining(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('characters_character_mining', { name, show_column_headings, version })
}
/**
* Return character notifications
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_notifications(name?: string, show_column_headings: boolean = true, version: string = "v5"): SheetsArray {
return invoke('characters_character_notifications', { name, show_column_headings, version })
}
/**
* Return notifications about having been added to someone's contact list
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_notifications_contacts(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('characters_character_notifications_contacts', { name, show_column_headings, version })
}
/**
* Checks if the character is currently online
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_online(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('characters_character_online', { name, show_column_headings, version })
}
/**
* Return a list of tasks finished by a character
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_opportunities(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('characters_character_opportunities', { name, show_column_headings, version })
}
/**
* List open market orders placed by a character
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_orders(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('characters_character_orders', { name, show_column_headings, version })
}
/**
* List cancelled and expired market orders placed by a character up to 90 days in the past.
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_orders_history(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('characters_character_orders_history', { name, show_column_headings, version })
}
/**
* Returns a list of all planetary colonies owned by a character.
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_planets(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('characters_character_planets', { name, show_column_headings, version })
}
/**
* Returns full details on the layout of a single planetary colony, including links, pins and routes. Note: Planetary information is only recalculated when the colony is viewed through the client. Information will not update until this criteria is met.
*
* @param {number} planet_id - Planet id of the target planet
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_planets_planet(planet_id: number, name?: string, show_column_headings: boolean = true, version: string = "v3"): SheetsArray {
if (!planet_id) throw new Error(`planet_id is required`);
return invoke('characters_character_planets_planet', { planet_id, name, show_column_headings, version })
}
/**
* Get portrait urls for a character
*
* @param {number} character_id - An EVE character ID
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_portrait(character_id: number, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
if (!character_id) throw new Error(`character_id is required`);
return invoke('characters_character_portrait', { character_id, show_column_headings, version })
}
/**
* Returns a character's corporation roles
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_roles(name?: string, show_column_headings: boolean = true, version: string = "v3"): SheetsArray {
return invoke('characters_character_roles', { name, show_column_headings, version })
}
/**
* Search for entities that match a given sub-string.
*
* @param {string} search - The string to search on
* @param {string[]} categories - Type of entities to search for
* @param {string} language - Language to use in the response, takes precedence over Accept-Language
* @param {boolean} strict - Whether the search should be a strict match
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_search(search: string, categories: string[], language?: string, strict?: boolean, name?: string, show_column_headings: boolean = true, version: string = "v3"): SheetsArray {
if (!search) throw new Error(`search is required`);
if (!categories) throw new Error(`categories is required`);
return invoke('characters_character_search', { search, categories, language, strict, name, show_column_headings, version })
}
/**
* Get the current ship type, name and id
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_ship(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('characters_character_ship', { name, show_column_headings, version })
}
/**
* List the configured skill queue for the given character
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_skillqueue(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('characters_character_skillqueue', { name, show_column_headings, version })
}
/**
* List all trained skills for the given character
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_skills(name?: string, show_column_headings: boolean = true, version: string = "v4"): SheetsArray {
return invoke('characters_character_skills', { name, show_column_headings, version })
}
/**
* Return character standings from agents, NPC corporations, and factions
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_standings(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('characters_character_standings', { name, show_column_headings, version })
}
/**
* Returns a character's titles
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_titles(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('characters_character_titles', { name, show_column_headings, version })
}
/**
* Returns a character's wallet balance
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_wallet(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('characters_character_wallet', { name, show_column_headings, version })
}
/**
* Retrieve the given character's wallet journal going 30 days back
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_wallet_journal(name?: string, show_column_headings: boolean = true, version: string = "v6"): SheetsArray {
return invoke('characters_character_wallet_journal', { name, show_column_headings, version })
}
/**
* Get wallet transactions of a character
*
* @param {number} from_id - Only show transactions happened before the one referenced by this id
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function characters_character_wallet_transactions(from_id?: number, name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('characters_character_wallet_transactions', { from_id, name, show_column_headings, version })
}
/**
* Lists bids on a public auction contract
*
* @param {number} contract_id - ID of a contract
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function contracts_public_bids_contract(contract_id: number, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!contract_id) throw new Error(`contract_id is required`);
return invoke('contracts_public_bids_contract', { contract_id, show_column_headings, version })
}
/**
* Lists items of a public contract
*
* @param {number} contract_id - ID of a contract
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function contracts_public_items_contract(contract_id: number, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!contract_id) throw new Error(`contract_id is required`);
return invoke('contracts_public_items_contract', { contract_id, show_column_headings, version })
}
/**
* Returns a paginated list of all public contracts in the given region
*
* @param {number} region_id - An EVE region id
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function contracts_public_region(region_id: number, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!region_id) throw new Error(`region_id is required`);
return invoke('contracts_public_region', { region_id, show_column_headings, version })
}
/**
* Extraction timers for all moon chunks being extracted by refineries belonging to a corporation.
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporation_corporation_mining_extractions(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('corporation_corporation_mining_extractions', { name, show_column_headings, version })
}
/**
* Paginated list of all entities capable of observing and recording mining for a corporation
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporation_corporation_mining_observers(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('corporation_corporation_mining_observers', { name, show_column_headings, version })
}
/**
* Paginated record of all mining seen by an observer
*
* @param {number} observer_id - A mining observer id
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporation_corporation_mining_observers_observer(observer_id: number, name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!observer_id) throw new Error(`observer_id is required`);
return invoke('corporation_corporation_mining_observers_observer', { observer_id, name, show_column_headings, version })
}
/**
* Public information about a corporation
*
* @param {number} corporation_id - An EVE corporation ID
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation(corporation_id: number, show_column_headings: boolean = true, version: string = "v5"): SheetsArray {
if (!corporation_id) throw new Error(`corporation_id is required`);
return invoke('corporations_corporation', { corporation_id, show_column_headings, version })
}
/**
* Get a list of all the alliances a corporation has been a member of
*
* @param {number} corporation_id - An EVE corporation ID
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_alliancehistory(corporation_id: number, show_column_headings: boolean = true, version: string = "v3"): SheetsArray {
if (!corporation_id) throw new Error(`corporation_id is required`);
return invoke('corporations_corporation_alliancehistory', { corporation_id, show_column_headings, version })
}
/**
* Return a list of the corporation assets
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_assets(name?: string, show_column_headings: boolean = true, version: string = "v5"): SheetsArray {
return invoke('corporations_corporation_assets', { name, show_column_headings, version })
}
/**
* Return locations for a set of item ids, which you can get from corporation assets endpoint. Coordinates for items in hangars or stations are set to (0,0,0)
*
* @param {number[]} item_ids - A list of item ids
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_assets_locations(item_ids: number[], name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
if (!item_ids) throw new Error(`item_ids is required`);
return invoke('corporations_corporation_assets_locations', { item_ids, name, show_column_headings, version })
}
/**
* Return names for a set of item ids, which you can get from corporation assets endpoint. Only valid for items that can customize names, like containers or ships
*
* @param {number[]} item_ids - A list of item ids
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_assets_names(item_ids: number[], name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!item_ids) throw new Error(`item_ids is required`);
return invoke('corporations_corporation_assets_names', { item_ids, name, show_column_headings, version })
}
/**
* Returns a list of blueprints the corporation owns
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_blueprints(name?: string, show_column_headings: boolean = true, version: string = "v3"): SheetsArray {
return invoke('corporations_corporation_blueprints', { name, show_column_headings, version })
}
/**
* A list of your corporation's bookmarks
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_bookmarks(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('corporations_corporation_bookmarks', { name, show_column_headings, version })
}
/**
* A list of your corporation's bookmark folders
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_bookmarks_folders(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('corporations_corporation_bookmarks_folders', { name, show_column_headings, version })
}
/**
* Return contacts of a corporation
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_contacts(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('corporations_corporation_contacts', { name, show_column_headings, version })
}
/**
* Return custom labels for a corporation's contacts
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_contacts_labels(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('corporations_corporation_contacts_labels', { name, show_column_headings, version })
}
/**
* Returns logs recorded in the past seven days from all audit log secure containers (ALSC) owned by a given corporation
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_containers_logs(name?: string, show_column_headings: boolean = true, version: string = "v3"): SheetsArray {
return invoke('corporations_corporation_containers_logs', { name, show_column_headings, version })
}
/**
* Returns contracts available to a corporation, only if the corporation is issuer, acceptor or assignee. Only returns contracts no older than 30 days, or if the status is "in_progress".
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_contracts(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('corporations_corporation_contracts', { name, show_column_headings, version })
}
/**
* Lists bids on a particular auction contract
*
* @param {number} contract_id - ID of a contract
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_contracts_contract_bids(contract_id: number, name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!contract_id) throw new Error(`contract_id is required`);
return invoke('corporations_corporation_contracts_contract_bids', { contract_id, name, show_column_headings, version })
}
/**
* Lists items of a particular contract
*
* @param {number} contract_id - ID of a contract
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_contracts_contract_items(contract_id: number, name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!contract_id) throw new Error(`contract_id is required`);
return invoke('corporations_corporation_contracts_contract_items', { contract_id, name, show_column_headings, version })
}
/**
* List customs offices owned by a corporation
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_customs_offices(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('corporations_corporation_customs_offices', { name, show_column_headings, version })
}
/**
* Return corporation hangar and wallet division names, only show if a division is not using the default name
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_divisions(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('corporations_corporation_divisions', { name, show_column_headings, version })
}
/**
* Return a corporation's facilities
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_facilities(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('corporations_corporation_facilities', { name, show_column_headings, version })
}
/**
* Statistics about a corporation involved in faction warfare
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_fw_stats(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('corporations_corporation_fw_stats', { name, show_column_headings, version })
}
/**
* Get the icon urls for a corporation
*
* @param {number} corporation_id - An EVE corporation ID
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_icons(corporation_id: number, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
if (!corporation_id) throw new Error(`corporation_id is required`);
return invoke('corporations_corporation_icons', { corporation_id, show_column_headings, version })
}
/**
* List industry jobs run by a corporation
*
* @param {boolean} include_completed - Whether to retrieve completed corporation industry jobs. Only includes jobs from the past 90 days
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_industry_jobs(include_completed?: boolean, name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('corporations_corporation_industry_jobs', { include_completed, name, show_column_headings, version })
}
/**
* Get a list of a corporation's kills and losses going back 90 days
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_killmails_recent(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('corporations_corporation_killmails_recent', { name, show_column_headings, version })
}
/**
* Returns a corporation's medals
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_medals(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('corporations_corporation_medals', { name, show_column_headings, version })
}
/**
* Returns medals issued by a corporation
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_medals_issued(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('corporations_corporation_medals_issued', { name, show_column_headings, version })
}
/**
* Return the current member list of a corporation, the token's character need to be a member of the corporation.
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_members(name?: string, show_column_headings: boolean = true, version: string = "v4"): SheetsArray {
return invoke('corporations_corporation_members', { name, show_column_headings, version })
}
/**
* Return a corporation's member limit, not including CEO himself
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_members_limit(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('corporations_corporation_members_limit', { name, show_column_headings, version })
}
/**
* Returns a corporation's members' titles
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_members_titles(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('corporations_corporation_members_titles', { name, show_column_headings, version })
}
/**
* Returns additional information about a corporation's members which helps tracking their activities
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_membertracking(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('corporations_corporation_membertracking', { name, show_column_headings, version })
}
/**
* List open market orders placed on behalf of a corporation
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_orders(name?: string, show_column_headings: boolean = true, version: string = "v3"): SheetsArray {
return invoke('corporations_corporation_orders', { name, show_column_headings, version })
}
/**
* List cancelled and expired market orders placed on behalf of a corporation up to 90 days in the past.
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_orders_history(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('corporations_corporation_orders_history', { name, show_column_headings, version })
}
/**
* Return the roles of all members if the character has the personnel manager role or any grantable role.
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_roles(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('corporations_corporation_roles', { name, show_column_headings, version })
}
/**
* Return how roles have changed for a coporation's members, up to a month
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_roles_history(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('corporations_corporation_roles_history', { name, show_column_headings, version })
}
/**
* Return the current shareholders of a corporation.
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_shareholders(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('corporations_corporation_shareholders', { name, show_column_headings, version })
}
/**
* Return corporation standings from agents, NPC corporations, and factions
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_standings(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('corporations_corporation_standings', { name, show_column_headings, version })
}
/**
* Returns list of corporation starbases (POSes)
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_starbases(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('corporations_corporation_starbases', { name, show_column_headings, version })
}
/**
* Returns various settings and fuels of a starbase (POS)
*
* @param {number} system_id - The solar system this starbase (POS) is located in,
* @param {number} starbase_id - An EVE starbase (POS) ID
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_starbases_starbase(system_id: number, starbase_id: number, name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
if (!system_id) throw new Error(`system_id is required`);
if (!starbase_id) throw new Error(`starbase_id is required`);
return invoke('corporations_corporation_starbases_starbase', { system_id, starbase_id, name, show_column_headings, version })
}
/**
* Get a list of corporation structures. This route's version includes the changes to structures detailed in this blog: https://www.eveonline.com/article/upwell-2.0-structures-changes-coming-on-february-13th
*
* @param {string} language - Language to use in the response, takes precedence over Accept-Language
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_structures(language?: string, name?: string, show_column_headings: boolean = true, version: string = "v4"): SheetsArray {
return invoke('corporations_corporation_structures', { language, name, show_column_headings, version })
}
/**
* Returns a corporation's titles
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_titles(name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('corporations_corporation_titles', { name, show_column_headings, version })
}
/**
* Get a corporation's wallets
*
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_wallets(name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('corporations_corporation_wallets', { name, show_column_headings, version })
}
/**
* Retrieve the given corporation's wallet journal for the given division going 30 days back
*
* @param {number} division - Wallet key of the division to fetch journals from
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_wallets_division_journal(division: number, name?: string, show_column_headings: boolean = true, version: string = "v4"): SheetsArray {
if (!division) throw new Error(`division is required`);
return invoke('corporations_corporation_wallets_division_journal', { division, name, show_column_headings, version })
}
/**
* Get wallet transactions of a corporation
*
* @param {number} division - Wallet key of the division to fetch journals from
* @param {number} from_id - Only show journal entries happened before the transaction referenced by this id
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_corporation_wallets_division_transactions(division: number, from_id?: number, name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!division) throw new Error(`division is required`);
return invoke('corporations_corporation_wallets_division_transactions', { division, from_id, name, show_column_headings, version })
}
/**
* Get a list of npc corporations
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function corporations_npccorps(show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('corporations_npccorps', { show_column_headings, version })
}
/**
* Get a list of dogma attribute ids
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function dogma_attributes(show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('dogma_attributes', { show_column_headings, version })
}
/**
* Get information on a dogma attribute
*
* @param {number} attribute_id - A dogma attribute ID
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function dogma_attributes_attribute(attribute_id: number, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!attribute_id) throw new Error(`attribute_id is required`);
return invoke('dogma_attributes_attribute', { attribute_id, show_column_headings, version })
}
/**
* Returns info about a dynamic item resulting from mutation with a mutaplasmid.
*
* @param {number} type_id - type_id integer
* @param {number} item_id - item_id integer
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function dogma_dynamic_items_type_item(type_id: number, item_id: number, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!type_id) throw new Error(`type_id is required`);
if (!item_id) throw new Error(`item_id is required`);
return invoke('dogma_dynamic_items_type_item', { type_id, item_id, show_column_headings, version })
}
/**
* Get a list of dogma effect ids
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function dogma_effects(show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('dogma_effects', { show_column_headings, version })
}
/**
* Get information on a dogma effect
*
* @param {number} effect_id - A dogma effect ID
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function dogma_effects_effect(effect_id: number, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
if (!effect_id) throw new Error(`effect_id is required`);
return invoke('dogma_effects_effect', { effect_id, show_column_headings, version })
}
/**
* Search for entities that match a given sub-string.
*
* @param {string} search - The string to search on
* @param {string[]} categories - Type of entities to search for
* @param {string} language - Language to use in the response, takes precedence over Accept-Language
* @param {boolean} strict - Whether the search should be a strict match
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function eve_search(search: string, categories: string[], language?: string, strict?: boolean, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
if (!search) throw new Error(`search is required`);
if (!categories) throw new Error(`categories is required`);
return invoke('eve_search', { search, categories, language, strict, show_column_headings, version })
}
/**
* EVE Server status
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function eve_status(show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('eve_status', { show_column_headings, version })
}
/**
* Return details about a fleet
*
* @param {number} fleet_id - ID for a fleet
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function fleets_fleet(fleet_id: number, name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!fleet_id) throw new Error(`fleet_id is required`);
return invoke('fleets_fleet', { fleet_id, name, show_column_headings, version })
}
/**
* Return information about fleet members
*
* @param {number} fleet_id - ID for a fleet
* @param {string} language - Language to use in the response, takes precedence over Accept-Language
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function fleets_fleet_members(fleet_id: number, language?: string, name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!fleet_id) throw new Error(`fleet_id is required`);
return invoke('fleets_fleet_members', { fleet_id, language, name, show_column_headings, version })
}
/**
* Return information about wings in a fleet
*
* @param {number} fleet_id - ID for a fleet
* @param {string} language - Language to use in the response, takes precedence over Accept-Language
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function fleets_fleet_wings(fleet_id: number, language?: string, name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!fleet_id) throw new Error(`fleet_id is required`);
return invoke('fleets_fleet_wings', { fleet_id, language, name, show_column_headings, version })
}
/**
* Top 4 leaderboard of factions for kills and victory points separated by total, last week and yesterday
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function fw_leaderboards(show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('fw_leaderboards', { show_column_headings, version })
}
/**
* Top 100 leaderboard of pilots for kills and victory points separated by total, last week and yesterday
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function fw_leaderboards_characters(show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('fw_leaderboards_characters', { show_column_headings, version })
}
/**
* Top 10 leaderboard of corporations for kills and victory points separated by total, last week and yesterday
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function fw_leaderboards_corporations(show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('fw_leaderboards_corporations', { show_column_headings, version })
}
/**
* Statistical overviews of factions involved in faction warfare
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function fw_stats(show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('fw_stats', { show_column_headings, version })
}
/**
* An overview of the current ownership of faction warfare solar systems
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function fw_systems(show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('fw_systems', { show_column_headings, version })
}
/**
* Data about which NPC factions are at war
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function fw_wars(show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('fw_wars', { show_column_headings, version })
}
/**
* Return a list of current incursions
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function incursions(show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('incursions', { show_column_headings, version })
}
/**
* Return a list of industry facilities
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function industry_facilities(show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('industry_facilities', { show_column_headings, version })
}
/**
* Return cost indices for solar systems
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function industry_systems(show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('industry_systems', { show_column_headings, version })
}
/**
* Return available insurance levels for all ship types
*
* @param {string} language - Language to use in the response, takes precedence over Accept-Language
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function insurance_prices(language?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('insurance_prices', { language, show_column_headings, version })
}
/**
* Return a single killmail from its ID and hash
*
* @param {number} killmail_id - The killmail ID to be queried
* @param {string} killmail_hash - The killmail hash for verification
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function killmails_killmail_killmail_hash(killmail_id: number, killmail_hash: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!killmail_id) throw new Error(`killmail_id is required`);
if (!killmail_hash) throw new Error(`killmail_hash is required`);
return invoke('killmails_killmail_killmail_hash', { killmail_id, killmail_hash, show_column_headings, version })
}
/**
* Return a list of offers from a specific corporation's loyalty store
*
* @param {number} corporation_id - An EVE corporation ID
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function loyalty_stores_corporation_offers(corporation_id: number, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!corporation_id) throw new Error(`corporation_id is required`);
return invoke('loyalty_stores_corporation_offers', { corporation_id, show_column_headings, version })
}
/**
* Get a list of item groups
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function markets_groups(show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('markets_groups', { show_column_headings, version })
}
/**
* Get information on an item group
*
* @param {number} market_group_id - An Eve item group ID
* @param {string} language - Language to use in the response, takes precedence over Accept-Language
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function markets_groups_market_group(market_group_id: number, language?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!market_group_id) throw new Error(`market_group_id is required`);
return invoke('markets_groups_market_group', { market_group_id, language, show_column_headings, version })
}
/**
* Return a list of prices
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function markets_prices(show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('markets_prices', { show_column_headings, version })
}
/**
* Return a list of historical market statistics for the specified type in a region
*
* @param {number} type_id - Return statistics for this type
* @param {number} region_id - Return statistics in this region
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function markets_region_history(type_id: number, region_id: number, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!type_id) throw new Error(`type_id is required`);
if (!region_id) throw new Error(`region_id is required`);
return invoke('markets_region_history', { type_id, region_id, show_column_headings, version })
}
/**
* Return a list of orders in a region
*
* @param {number} region_id - Return orders in this region
* @param {string} order_type - Filter buy/sell orders, return all orders by default. If you query without type_id, we always return both buy and sell orders
* @param {number} type_id - Return orders only for this type
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function markets_region_orders(region_id: number, order_type: string, type_id?: number, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!region_id) throw new Error(`region_id is required`);
if (!order_type) throw new Error(`order_type is required`);
return invoke('markets_region_orders', { region_id, order_type, type_id, show_column_headings, version })
}
/**
* Return a list of type IDs that have active orders in the region, for efficient market indexing.
*
* @param {number} region_id - Return statistics in this region
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function markets_region_types(region_id: number, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!region_id) throw new Error(`region_id is required`);
return invoke('markets_region_types', { region_id, show_column_headings, version })
}
/**
* Return all orders in a structure
*
* @param {number} structure_id - Return orders in this structure
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function markets_structures_structure(structure_id: number, name?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!structure_id) throw new Error(`structure_id is required`);
return invoke('markets_structures_structure', { structure_id, name, show_column_headings, version })
}
/**
* Return a list of opportunities groups
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function opportunities_groups(show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('opportunities_groups', { show_column_headings, version })
}
/**
* Return information of an opportunities group
*
* @param {number} group_id - ID of an opportunities group
* @param {string} language - Language to use in the response, takes precedence over Accept-Language
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function opportunities_groups_group(group_id: number, language?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!group_id) throw new Error(`group_id is required`);
return invoke('opportunities_groups_group', { group_id, language, show_column_headings, version })
}
/**
* Return a list of opportunities tasks
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function opportunities_tasks(show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('opportunities_tasks', { show_column_headings, version })
}
/**
* Return information of an opportunities task
*
* @param {number} task_id - ID of an opportunities task
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function opportunities_tasks_task(task_id: number, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!task_id) throw new Error(`task_id is required`);
return invoke('opportunities_tasks_task', { task_id, show_column_headings, version })
}
/**
* Get the systems between origin and destination
*
* @param {number} origin - origin solar system ID
* @param {number} destination - destination solar system ID
* @param {number[]} avoid - avoid solar system ID(s)
* @param {number[]} connections - connected solar system pairs
* @param {string} flag - route security preference
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function route_origin_destination(origin: number, destination: number, avoid?: number[], connections?: number[], flag?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!origin) throw new Error(`origin is required`);
if (!destination) throw new Error(`destination is required`);
return invoke('route_origin_destination', { origin, destination, avoid, connections, flag, show_column_headings, version })
}
/**
* Shows sovereignty data for campaigns.
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function sovereignty_campaigns(show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('sovereignty_campaigns', { show_column_headings, version })
}
/**
* Shows sovereignty information for solar systems
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function sovereignty_map(show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('sovereignty_map', { show_column_headings, version })
}
/**
* Shows sovereignty data for structures.
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function sovereignty_structures(show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('sovereignty_structures', { show_column_headings, version })
}
/**
* Get all character ancestries
*
* @param {string} language - Language to use in the response, takes precedence over Accept-Language
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_ancestries(language?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('universe_ancestries', { language, show_column_headings, version })
}
/**
* Get information on an asteroid belt
*
* @param {number} asteroid_belt_id - asteroid_belt_id integer
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_asteroid_belts_asteroid_belt(asteroid_belt_id: number, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!asteroid_belt_id) throw new Error(`asteroid_belt_id is required`);
return invoke('universe_asteroid_belts_asteroid_belt', { asteroid_belt_id, show_column_headings, version })
}
/**
* Get a list of bloodlines
*
* @param {string} language - Language to use in the response, takes precedence over Accept-Language
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_bloodlines(language?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('universe_bloodlines', { language, show_column_headings, version })
}
/**
* Get a list of item categories
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_categories(show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('universe_categories', { show_column_headings, version })
}
/**
* Get information of an item category
*
* @param {number} category_id - An Eve item category ID
* @param {string} language - Language to use in the response, takes precedence over Accept-Language
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_categories_category(category_id: number, language?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!category_id) throw new Error(`category_id is required`);
return invoke('universe_categories_category', { category_id, language, show_column_headings, version })
}
/**
* Get a list of constellations
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_constellations(show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('universe_constellations', { show_column_headings, version })
}
/**
* Get information on a constellation
*
* @param {number} constellation_id - constellation_id integer
* @param {string} language - Language to use in the response, takes precedence over Accept-Language
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_constellations_constellation(constellation_id: number, language?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!constellation_id) throw new Error(`constellation_id is required`);
return invoke('universe_constellations_constellation', { constellation_id, language, show_column_headings, version })
}
/**
* Get a list of factions
*
* @param {string} language - Language to use in the response, takes precedence over Accept-Language
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_factions(language?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('universe_factions', { language, show_column_headings, version })
}
/**
* Get a list of graphics
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_graphics(show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('universe_graphics', { show_column_headings, version })
}
/**
* Get information on a graphic
*
* @param {number} graphic_id - graphic_id integer
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_graphics_graphic(graphic_id: number, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!graphic_id) throw new Error(`graphic_id is required`);
return invoke('universe_graphics_graphic', { graphic_id, show_column_headings, version })
}
/**
* Get a list of item groups
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_groups(show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('universe_groups', { show_column_headings, version })
}
/**
* Get information on an item group
*
* @param {number} group_id - An Eve item group ID
* @param {string} language - Language to use in the response, takes precedence over Accept-Language
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_groups_group(group_id: number, language?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!group_id) throw new Error(`group_id is required`);
return invoke('universe_groups_group', { group_id, language, show_column_headings, version })
}
/**
* Resolve a set of names to IDs in the following categories: agents, alliances, characters, constellations, corporations factions, inventory_types, regions, stations, and systems. Only exact matches will be returned. All names searched for are cached for 12 hours
*
* @param {string[]} names - The names to resolve
* @param {string} language - Language to use in the response, takes precedence over Accept-Language
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_ids(names: string[], language?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!names) throw new Error(`names is required`);
return invoke('universe_ids', { names, language, show_column_headings, version })
}
/**
* Get information on a moon
*
* @param {number} moon_id - moon_id integer
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_moons_moon(moon_id: number, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!moon_id) throw new Error(`moon_id is required`);
return invoke('universe_moons_moon', { moon_id, show_column_headings, version })
}
/**
* Resolve a set of IDs to names and categories. Supported ID's for resolving are: Characters, Corporations, Alliances, Stations, Solar Systems, Constellations, Regions, Types, Factions
*
* @param {number[]} ids - The ids to resolve
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_names(ids: number[], show_column_headings: boolean = true, version: string = "v3"): SheetsArray {
if (!ids) throw new Error(`ids is required`);
return invoke('universe_names', { ids, show_column_headings, version })
}
/**
* Get information on a planet
*
* @param {number} planet_id - planet_id integer
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_planets_planet(planet_id: number, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!planet_id) throw new Error(`planet_id is required`);
return invoke('universe_planets_planet', { planet_id, show_column_headings, version })
}
/**
* Get a list of character races
*
* @param {string} language - Language to use in the response, takes precedence over Accept-Language
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_races(language?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('universe_races', { language, show_column_headings, version })
}
/**
* Get a list of regions
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_regions(show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('universe_regions', { show_column_headings, version })
}
/**
* Get information on a region
*
* @param {number} region_id - region_id integer
* @param {string} language - Language to use in the response, takes precedence over Accept-Language
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_regions_region(region_id: number, language?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!region_id) throw new Error(`region_id is required`);
return invoke('universe_regions_region', { region_id, language, show_column_headings, version })
}
/**
* Get information on a planetary factory schematic
*
* @param {number} schematic_id - A PI schematic ID
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_schematics_schematic(schematic_id: number, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!schematic_id) throw new Error(`schematic_id is required`);
return invoke('universe_schematics_schematic', { schematic_id, show_column_headings, version })
}
/**
* Get information on a stargate
*
* @param {number} stargate_id - stargate_id integer
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_stargates_stargate(stargate_id: number, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!stargate_id) throw new Error(`stargate_id is required`);
return invoke('universe_stargates_stargate', { stargate_id, show_column_headings, version })
}
/**
* Get information on a star
*
* @param {number} star_id - star_id integer
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_stars_star(star_id: number, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!star_id) throw new Error(`star_id is required`);
return invoke('universe_stars_star', { star_id, show_column_headings, version })
}
/**
* Get information on a station
*
* @param {number} station_id - station_id integer
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_stations_station(station_id: number, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
if (!station_id) throw new Error(`station_id is required`);
return invoke('universe_stations_station', { station_id, show_column_headings, version })
}
/**
* List all public structures
*
* @param {string} filter - Only list public structures that have this service online
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_structures(filter?: string, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('universe_structures', { filter, show_column_headings, version })
}
/**
* Returns information on requested structure if you are on the ACL. Otherwise, returns "Forbidden" for all inputs.
*
* @param {number} structure_id - An Eve structure ID
* @param {string} name - Name of the character used for auth. Defaults to the first authenticated character.
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_structures_structure(structure_id: number, name?: string, show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
if (!structure_id) throw new Error(`structure_id is required`);
return invoke('universe_structures_structure', { structure_id, name, show_column_headings, version })
}
/**
* Get the number of jumps in solar systems within the last hour ending at the timestamp of the Last-Modified header, excluding wormhole space. Only systems with jumps will be listed
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_system_jumps(show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('universe_system_jumps', { show_column_headings, version })
}
/**
* Get the number of ship, pod and NPC kills per solar system within the last hour ending at the timestamp of the Last-Modified header, excluding wormhole space. Only systems with kills will be listed
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_system_kills(show_column_headings: boolean = true, version: string = "v2"): SheetsArray {
return invoke('universe_system_kills', { show_column_headings, version })
}
/**
* Get a list of solar systems
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_systems(show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('universe_systems', { show_column_headings, version })
}
/**
* Get information on a solar system.
*
* @param {number} system_id - system_id integer
* @param {string} language - Language to use in the response, takes precedence over Accept-Language
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_systems_system(system_id: number, language?: string, show_column_headings: boolean = true, version: string = "v4"): SheetsArray {
if (!system_id) throw new Error(`system_id is required`);
return invoke('universe_systems_system', { system_id, language, show_column_headings, version })
}
/**
* Get a list of type ids
*
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_types(show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('universe_types', { show_column_headings, version })
}
/**
* Get information on a type
*
* @param {number} type_id - An Eve item type ID
* @param {string} language - Language to use in the response, takes precedence over Accept-Language
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function universe_types_type(type_id: number, language?: string, show_column_headings: boolean = true, version: string = "v3"): SheetsArray {
if (!type_id) throw new Error(`type_id is required`);
return invoke('universe_types_type', { type_id, language, show_column_headings, version })
}
/**
* Return a list of wars
*
* @param {number} max_war_id - Only return wars with ID smaller than this
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function wars(max_war_id?: number, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
return invoke('wars', { max_war_id, show_column_headings, version })
}
/**
* Return details about a war
*
* @param {number} war_id - ID for a war
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function wars_war(war_id: number, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!war_id) throw new Error(`war_id is required`);
return invoke('wars_war', { war_id, show_column_headings, version })
}
/**
* Return a list of kills related to a war
*
* @param {number} war_id - A valid war ID
* @param {boolean} show_column_headings - If column headings should be shown.
* @param {string} version - Which ESI version to use for the request.
* @customfunction
*/
function wars_war_killmails(war_id: number, show_column_headings: boolean = true, version: string = "v1"): SheetsArray {
if (!war_id) throw new Error(`war_id is required`);
return invoke('wars_war_killmails', { war_id, show_column_headings, version })
} | the_stack |
import randomBytes from "randombytes";
import { sanitizePath } from "skynet-mysky-utils";
import { secretbox } from "tweetnacl";
import { HASH_LENGTH, sha512 } from "../crypto";
import { hexToUint8Array, stringToUint8ArrayUtf8, toHexString, uint8ArrayToStringUtf8 } from "../utils/string";
import { JsonData } from "../utils/types";
import {
throwValidationError,
validateBoolean,
validateHexString,
validateNumber,
validateObject,
validateString,
validateUint8Array,
validateUint8ArrayLen,
} from "../utils/validation";
/**
* The current response version for encrypted JSON files. Part of the metadata
* prepended to encrypted data.
*/
export const ENCRYPTED_JSON_RESPONSE_VERSION = 1;
/**
* The length of the encryption key.
*/
export const ENCRYPTION_KEY_LENGTH = 32;
/**
* The length of the hidden field metadata stored along with encrypted files.
* Note that this is hidden from the user, but not actually encrypted. It is
* stored after the nonce.
*/
export const ENCRYPTION_HIDDEN_FIELD_METADATA_LENGTH = 16;
/**
* The length of the random nonce, prepended to the encrypted bytes. It comes
* before the unencrypted hidden field metadata.
*/
export const ENCRYPTION_NONCE_LENGTH = 24;
/**
* The length of the overhead introduced by encryption.
*/
const ENCRYPTION_OVERHEAD_LENGTH = 16;
/**
* The length of the hex-encoded share-able directory path seed.
*/
export const ENCRYPTION_PATH_SEED_DIRECTORY_LENGTH = 128;
/**
* The length of the hex-encoded share-able file path seed.
*/
export const ENCRYPTION_PATH_SEED_FILE_LENGTH = 64;
// Descriptive salt that should not be changed.
const SALT_ENCRYPTED_CHILD = "encrypted filesystem child";
// Descriptive salt that should not be changed.
const SALT_ENCRYPTED_TWEAK = "encrypted filesystem tweak";
// Descriptive salt that should not be changed.
const SALT_ENCRYPTION = "encryption";
export type EncryptedJSONResponse = {
data: JsonData | null;
};
type DerivationPathObject = {
pathSeed: Uint8Array;
directory: boolean;
name: string;
};
type EncryptedFileMetadata = {
// 8-bit uint.
version: number;
};
/**
* Decrypts the given bytes as an encrypted JSON file.
*
* @param data - The given raw bytes.
* @param key - The encryption key.
* @returns - The JSON data and metadata.
* @throws - Will throw if the bytes could not be decrypted.
*/
export function decryptJSONFile(data: Uint8Array, key: Uint8Array): JsonData {
validateUint8Array("data", data, "parameter");
validateUint8ArrayLen("key", key, "parameter", ENCRYPTION_KEY_LENGTH);
// Validate that the size of the data corresponds to a padded block.
if (!checkPaddedBlock(data.length)) {
throw new Error(
`Expected parameter 'data' to be padded encrypted data, length was '${
data.length
}', nearest padded block is '${padFileSize(data.length)}'`
);
}
// Extract the nonce.
const nonce = data.slice(0, ENCRYPTION_NONCE_LENGTH);
data = data.slice(ENCRYPTION_NONCE_LENGTH);
// Extract the unencrypted hidden field metadata.
const metadataBytes = data.slice(0, ENCRYPTION_HIDDEN_FIELD_METADATA_LENGTH);
data = data.slice(ENCRYPTION_HIDDEN_FIELD_METADATA_LENGTH);
const metadata = decodeEncryptedFileMetadata(metadataBytes);
if (metadata.version !== ENCRYPTED_JSON_RESPONSE_VERSION) {
throw new Error(
`Received unrecognized JSON response version '${metadata.version}' in metadata, expected '${ENCRYPTED_JSON_RESPONSE_VERSION}'`
);
}
// Decrypt the non-nonce part of the data.
let decryptedBytes = secretbox.open(data, nonce, key);
if (!decryptedBytes) {
throw new Error("Could not decrypt given encrypted JSON file");
}
// Trim the 0-byte padding off the end of the decrypted bytes. This should never remove real data as
// properly-formatted JSON must end with '}'.
let paddingIndex = decryptedBytes.length;
while (paddingIndex > 0 && decryptedBytes[paddingIndex - 1] === 0) {
paddingIndex--;
}
decryptedBytes = decryptedBytes.slice(0, paddingIndex);
// Parse the final decrypted message as json.
return JSON.parse(uint8ArrayToStringUtf8(decryptedBytes));
}
/**
* Encrypts the given JSON data and metadata.
*
* @param json - The given JSON data.
* @param metadata - The given metadata.
* @param key - The encryption key.
* @returns - The encrypted data.
*/
export function encryptJSONFile(json: JsonData, metadata: EncryptedFileMetadata, key: Uint8Array): Uint8Array {
validateObject("json", json, "parameter");
validateNumber("metadata.version", metadata.version, "parameter");
validateUint8ArrayLen("key", key, "parameter", ENCRYPTION_KEY_LENGTH);
// Stringify the json and convert to bytes.
let data = stringToUint8ArrayUtf8(JSON.stringify(json));
// Add padding so that the final size will be a padded block. The overhead will be added by encryption and we add the nonce at the end.
const totalOverhead = ENCRYPTION_OVERHEAD_LENGTH + ENCRYPTION_NONCE_LENGTH + ENCRYPTION_HIDDEN_FIELD_METADATA_LENGTH;
const finalSize = padFileSize(data.length + totalOverhead) - totalOverhead;
data = new Uint8Array([...data, ...new Uint8Array(finalSize - data.length)]);
// Generate a random nonce.
const nonce = new Uint8Array(randomBytes(ENCRYPTION_NONCE_LENGTH));
// Encrypt the data.
const encryptedBytes = secretbox(data, nonce, key);
// Prepend the metadata.
const metadataBytes = encodeEncryptedFileMetadata(metadata);
const finalBytes = new Uint8Array([...metadataBytes, ...encryptedBytes]);
// Prepend the nonce to the final data.
return new Uint8Array([...nonce, ...finalBytes]);
}
/**
* Derives key entropy for the given path seed.
*
* @param pathSeed - The given path seed.
* @returns - The key entropy.
*/
export function deriveEncryptedFileKeyEntropy(pathSeed: string): Uint8Array {
// Validate the path seed and get bytes.
const pathSeedBytes = validateAndGetFilePathSeedBytes(pathSeed);
const bytes = new Uint8Array([...sha512(SALT_ENCRYPTION), ...sha512(pathSeedBytes)]);
const hashBytes = sha512(bytes);
// Truncate the hash to the size of an encryption key.
return hashBytes.slice(0, ENCRYPTION_KEY_LENGTH);
}
/**
* Derives the encrypted file tweak for the given path seed.
*
* @param pathSeed - the given path seed.
* @returns - The encrypted file tweak.
*/
export function deriveEncryptedFileTweak(pathSeed: string): string {
// Validate the path seed and get bytes.
const pathSeedBytes = validateAndGetFilePathSeedBytes(pathSeed);
let hashBytes = sha512(new Uint8Array([...sha512(SALT_ENCRYPTED_TWEAK), ...sha512(pathSeedBytes)]));
// Truncate the hash or it will be rejected in skyd.
hashBytes = hashBytes.slice(0, HASH_LENGTH);
return toHexString(hashBytes);
}
/* istanbul ignore next */
/**
* Derives the path seed for the relative path, given the starting path seed and
* whether it is a directory. The path can be an absolute path if the root seed
* is given.
*
* @param pathSeed - The given starting path seed.
* @param subPath - The path.
* @param isDirectory - Whether the path is a directory.
* @returns - The path seed for the given path.
* @throws - Will throw if the input sub path is not a valid path.
* @deprecated - This function has been deprecated in favor of deriveEncryptedPathSeed.
*/
export function deriveEncryptedFileSeed(pathSeed: string, subPath: string, isDirectory: boolean): string {
return deriveEncryptedPathSeed(pathSeed, subPath, isDirectory);
}
/**
* Derives the path seed for the relative path, given the starting path seed and
* whether it is a directory. The path can be an absolute path if the root seed
* is given.
*
* @param pathSeed - The given starting path seed.
* @param subPath - The path.
* @param isDirectory - Whether the path is a directory.
* @returns - The path seed for the given path.
* @throws - Will throw if the input sub path is not a valid path.
*/
export function deriveEncryptedPathSeed(pathSeed: string, subPath: string, isDirectory: boolean): string {
validateHexString("pathSeed", pathSeed, "parameter");
validateString("subPath", subPath, "parameter");
validateBoolean("isDirectory", isDirectory, "parameter");
// The path seed must be for a directory and not a file.
if (pathSeed.length !== ENCRYPTION_PATH_SEED_DIRECTORY_LENGTH) {
throwValidationError(
"pathSeed",
pathSeed,
"parameter",
`a directory path seed of length '${ENCRYPTION_PATH_SEED_DIRECTORY_LENGTH}'`
);
}
let pathSeedBytes = hexToUint8Array(pathSeed);
const sanitizedPath = sanitizePath(subPath);
if (sanitizedPath === null) {
throw new Error(`Input subPath '${subPath}' not a valid path`);
}
const names = sanitizedPath.split("/");
names.forEach((name: string, index: number) => {
const directory = index === names.length - 1 ? isDirectory : true;
const derivationPathObj: DerivationPathObject = {
pathSeed: pathSeedBytes,
directory,
name,
};
const derivationPath = hashDerivationPathObject(derivationPathObj);
const bytes = new Uint8Array([...sha512(SALT_ENCRYPTED_CHILD), ...derivationPath]);
pathSeedBytes = sha512(bytes);
});
// Truncate the path seed bytes for files only.
if (!isDirectory) {
// Divide `ENCRYPTION_PATH_SEED_FILE_LENGTH` by 2 since that is the final hex-encoded length.
pathSeedBytes = pathSeedBytes.slice(0, ENCRYPTION_PATH_SEED_FILE_LENGTH / 2);
}
// Hex-encode the final output.
return toHexString(pathSeedBytes);
}
/**
* Hashes the derivation path object.
*
* @param obj - The given object containing the derivation path.
* @returns - The hash.
*/
function hashDerivationPathObject(obj: DerivationPathObject): Uint8Array {
const bytes = new Uint8Array([...obj.pathSeed, obj.directory ? 1 : 0, ...stringToUint8ArrayUtf8(obj.name)]);
return sha512(bytes);
}
/**
* To prevent analysis that can occur by looking at the sizes of files, all
* encrypted files will be padded to the nearest "pad block" (after encryption).
* A pad block is minimally 4 kib in size, is always a power of 2, and is always
* at least 5% of the size of the file.
*
* For example, a 1 kib encrypted file would be padded to 4 kib, a 5 kib file
* would be padded to 8 kib, and a 105 kib file would be padded to 112 kib.
* Below is a short table of valid file sizes:
*
* ```
* 4 KiB 8 KiB 12 KiB 16 KiB 20 KiB
* 24 KiB 28 KiB 32 KiB 36 KiB 40 KiB
* 44 KiB 48 KiB 52 KiB 56 KiB 60 KiB
* 64 KiB 68 KiB 72 KiB 76 KiB 80 KiB
*
* 88 KiB 96 KiB 104 KiB 112 KiB 120 KiB
* 128 KiB 136 KiB 144 KiB 152 KiB 160 KiB
*
* 176 KiB 192 Kib 208 KiB 224 KiB 240 KiB
* 256 KiB 272 KiB 288 KiB 304 KiB 320 KiB
*
* 352 KiB ... etc
* ```
*
* Note that the first 20 valid sizes are all a multiple of 4 KiB, the next 10
* are a multiple of 8 KiB, and each 10 after that the multiple doubles. We use
* this method of padding files to prevent an adversary from guessing the
* contents or structure of the file based on its size.
*
* @param initialSize - The size of the file.
* @returns - The final size, padded to a pad block.
* @throws - Will throw if the size would overflow the JS number type.
*/
export function padFileSize(initialSize: number): number {
const kib = 1 << 10;
// Only iterate to 53 (the maximum safe power of 2).
for (let n = 0; n < 53; n++) {
if (initialSize <= (1 << n) * 80 * kib) {
const paddingBlock = (1 << n) * 4 * kib;
let finalSize = initialSize;
if (finalSize % paddingBlock !== 0) {
finalSize = initialSize - (initialSize % paddingBlock) + paddingBlock;
}
return finalSize;
}
}
// Prevent overflow. Max JS number size is 2^53-1.
throw new Error("Could not pad file size, overflow detected.");
}
/**
* Checks if the given size corresponds to the correct padded block.
*
* @param size - The given file size.
* @returns - Whether the size corresponds to a padded block.
* @throws - Will throw if the size would overflow the JS number type.
*/
export function checkPaddedBlock(size: number): boolean {
const kib = 1 << 10;
// Only iterate to 53 (the maximum safe power of 2).
for (let n = 0; n < 53; n++) {
if (size <= (1 << n) * 80 * kib) {
const paddingBlock = (1 << n) * 4 * kib;
return size % paddingBlock === 0;
}
}
// Prevent overflow. Max JS number size is 2^53-1.
throw new Error("Could not check padded file size, overflow detected.");
}
/**
* Decodes the encoded encrypted file metadata.
*
* @param bytes - The encoded metadata.
* @returns - The decoded metadata.
* @throws - Will throw if the given bytes are of the wrong length.
*/
function decodeEncryptedFileMetadata(bytes: Uint8Array): EncryptedFileMetadata {
// Ensure input is correct length.
validateUint8ArrayLen("bytes", bytes, "encrypted file metadata bytes", ENCRYPTION_HIDDEN_FIELD_METADATA_LENGTH);
const version = bytes[0];
return {
version,
};
}
/**
* Encodes the given encrypted file metadata.
*
* @param metadata - The given metadata.
* @returns - The encoded metadata bytes.
* @throws - Will throw if the version does not fit in a byte.
*/
export function encodeEncryptedFileMetadata(metadata: EncryptedFileMetadata): Uint8Array {
const bytes = new Uint8Array(ENCRYPTION_HIDDEN_FIELD_METADATA_LENGTH);
// Encode the version
if (metadata.version >= 1 << 8 || metadata.version < 0) {
throw new Error(`Metadata version '${metadata.version}' could not be stored in a uint8`);
}
// Don't need to use a DataView or worry about endianness for a uint8.
bytes[0] = metadata.version;
return bytes;
}
/**
* Validates the path seed and converts it to bytes.
*
* @param pathSeed - The given path seed.
* @returns - The path seed bytes.
*/
function validateAndGetFilePathSeedBytes(pathSeed: string): Uint8Array {
validateHexString("pathSeed", pathSeed, "parameter");
if (pathSeed.length !== ENCRYPTION_PATH_SEED_FILE_LENGTH) {
throwValidationError(
"pathSeed",
pathSeed,
"parameter",
`a valid file path seed of length '${ENCRYPTION_PATH_SEED_FILE_LENGTH}'`
);
}
// Convert hex string to bytes.
//
// NOTE: This should have been `hexToUint8Array` but it has been left for
// backwards compatibility with existing encrypted file tweaks. Because hex
// strings are valid UTF8 strings, `stringToUint8ArrayUtf8` converts them to
// byte arrays that are suitable for deriving tweaks from. These bytes are
// never used to derive further path seed bytes.
return stringToUint8ArrayUtf8(pathSeed);
} | the_stack |
import "./global.ts";
import { fileURLToPath, pathToFileURL } from "./url.ts";
import {
ERR_INVALID_MODULE_SPECIFIER,
ERR_INVALID_PACKAGE_CONFIG,
ERR_INVALID_PACKAGE_TARGET,
ERR_MODULE_NOT_FOUND,
ERR_PACKAGE_IMPORT_NOT_DEFINED,
ERR_PACKAGE_PATH_NOT_EXPORTED,
NodeError,
} from "./_errors.ts";
const { hasOwn } = Object;
export const encodedSepRegEx = /%2F|%2C/i;
function throwInvalidSubpath(
subpath: string,
packageJSONUrl: string,
internal: boolean,
base: string,
) {
const reason = `request is not a valid subpath for the "${
internal ? "imports" : "exports"
}" resolution of ${fileURLToPath(packageJSONUrl)}`;
throw new ERR_INVALID_MODULE_SPECIFIER(
subpath,
reason,
base && fileURLToPath(base),
);
}
// deno-lint-ignore no-explicit-any
function throwInvalidPackageTarget(
subpath: string,
target: any,
packageJSONUrl: string,
internal: boolean,
base: string,
) {
if (typeof target === "object" && target !== null) {
target = JSON.stringify(target, null, "");
} else {
target = `${target}`;
}
throw new ERR_INVALID_PACKAGE_TARGET(
fileURLToPath(new URL(".", packageJSONUrl)),
subpath,
target,
internal,
base && fileURLToPath(base),
);
}
function throwImportNotDefined(
specifier: string,
packageJSONUrl: URL | undefined,
base: string | URL,
): TypeError & { code: string } {
throw new ERR_PACKAGE_IMPORT_NOT_DEFINED(specifier, packageJSONUrl, base);
}
function throwExportsNotFound(
subpath: string,
packageJSONUrl: string,
base?: string,
): Error & { code: string } {
throw new ERR_PACKAGE_PATH_NOT_EXPORTED(
subpath,
packageJSONUrl,
base,
);
}
function patternKeyCompare(a: string, b: string): number {
const aPatternIndex = a.indexOf("*");
const bPatternIndex = b.indexOf("*");
const baseLenA = aPatternIndex === -1 ? a.length : aPatternIndex + 1;
const baseLenB = bPatternIndex === -1 ? b.length : bPatternIndex + 1;
if (baseLenA > baseLenB) return -1;
if (baseLenB > baseLenA) return 1;
if (aPatternIndex === -1) return 1;
if (bPatternIndex === -1) return -1;
if (a.length > b.length) return -1;
if (b.length > a.length) return 1;
return 0;
}
function fileExists(url: string | URL): boolean {
try {
const info = Deno.statSync(url);
return info.isFile;
} catch {
return false;
}
}
function tryStatSync(path: string): { isDirectory: boolean } {
try {
const info = Deno.statSync(path);
return { isDirectory: info.isDirectory };
} catch {
return { isDirectory: false };
}
}
/**
* Legacy CommonJS main resolution:
* 1. let M = pkg_url + (json main field)
* 2. TRY(M, M.js, M.json, M.node)
* 3. TRY(M/index.js, M/index.json, M/index.node)
* 4. TRY(pkg_url/index.js, pkg_url/index.json, pkg_url/index.node)
* 5. NOT_FOUND
*/
function legacyMainResolve(
packageJSONUrl: URL,
packageConfig: PackageConfig,
base: string | URL,
): URL {
let guess;
if (packageConfig.main !== undefined) {
// Note: fs check redundances will be handled by Descriptor cache here.
if (
fileExists(guess = new URL(`./${packageConfig.main}`, packageJSONUrl))
) {
return guess;
} else if (
fileExists(guess = new URL(`./${packageConfig.main}.js`, packageJSONUrl))
) {
} else if (
fileExists(
guess = new URL(`./${packageConfig.main}.json`, packageJSONUrl),
)
) {
} else if (
fileExists(
guess = new URL(`./${packageConfig.main}.node`, packageJSONUrl),
)
) {
} else if (
fileExists(
guess = new URL(`./${packageConfig.main}/index.js`, packageJSONUrl),
)
) {
} else if (
fileExists(
guess = new URL(`./${packageConfig.main}/index.json`, packageJSONUrl),
)
) {
} else if (
fileExists(
guess = new URL(`./${packageConfig.main}/index.node`, packageJSONUrl),
)
) {
} else guess = undefined;
if (guess) {
// TODO(bartlomieju):
// emitLegacyIndexDeprecation(guess, packageJSONUrl, base,
// packageConfig.main);
return guess;
}
// Fallthrough.
}
if (fileExists(guess = new URL("./index.js", packageJSONUrl))) {}
// So fs.
else if (fileExists(guess = new URL("./index.json", packageJSONUrl))) {}
else if (fileExists(guess = new URL("./index.node", packageJSONUrl))) {}
else guess = undefined;
if (guess) {
// TODO(bartlomieju):
// emitLegacyIndexDeprecation(guess, packageJSONUrl, base, packageConfig.main);
return guess;
}
// Not found.
throw new ERR_MODULE_NOT_FOUND(
fileURLToPath(new URL(".", packageJSONUrl)),
fileURLToPath(base),
);
}
function parsePackageName(
specifier: string,
base: string | URL,
): { packageName: string; packageSubpath: string; isScoped: boolean } {
let separatorIndex = specifier.indexOf("/");
let validPackageName = true;
let isScoped = false;
if (specifier[0] === "@") {
isScoped = true;
if (separatorIndex === -1 || specifier.length === 0) {
validPackageName = false;
} else {
separatorIndex = specifier.indexOf("/", separatorIndex + 1);
}
}
const packageName = separatorIndex === -1
? specifier
: specifier.slice(0, separatorIndex);
// Package name cannot have leading . and cannot have percent-encoding or
// separators.
for (let i = 0; i < packageName.length; i++) {
if (packageName[i] === "%" || packageName[i] === "\\") {
validPackageName = false;
break;
}
}
if (!validPackageName) {
throw new ERR_INVALID_MODULE_SPECIFIER(
specifier,
"is not a valid package name",
fileURLToPath(base),
);
}
const packageSubpath = "." +
(separatorIndex === -1 ? "" : specifier.slice(separatorIndex));
return { packageName, packageSubpath, isScoped };
}
function packageResolve(
specifier: string,
base: string,
conditions: Set<string>,
): URL | undefined {
const { packageName, packageSubpath, isScoped } = parsePackageName(
specifier,
base,
);
// ResolveSelf
const packageConfig = getPackageScopeConfig(base);
if (packageConfig.exists) {
const packageJSONUrl = pathToFileURL(packageConfig.pjsonPath);
if (
packageConfig.name === packageName &&
packageConfig.exports !== undefined && packageConfig.exports !== null
) {
return packageExportsResolve(
packageJSONUrl.toString(),
packageSubpath,
packageConfig,
base,
conditions,
);
}
}
let packageJSONUrl = new URL(
"./node_modules/" + packageName + "/package.json",
base,
);
let packageJSONPath = fileURLToPath(packageJSONUrl);
let lastPath;
do {
const stat = tryStatSync(
packageJSONPath.slice(0, packageJSONPath.length - 13),
);
if (!stat.isDirectory) {
lastPath = packageJSONPath;
packageJSONUrl = new URL(
(isScoped ? "../../../../node_modules/" : "../../../node_modules/") +
packageName + "/package.json",
packageJSONUrl,
);
packageJSONPath = fileURLToPath(packageJSONUrl);
continue;
}
// Package match.
const packageConfig = getPackageConfig(packageJSONPath, specifier, base);
if (packageConfig.exports !== undefined && packageConfig.exports !== null) {
return packageExportsResolve(
packageJSONUrl.toString(),
packageSubpath,
packageConfig,
base,
conditions,
);
}
if (packageSubpath === ".") {
return legacyMainResolve(packageJSONUrl, packageConfig, base);
}
return new URL(packageSubpath, packageJSONUrl);
// Cross-platform root check.
} while (packageJSONPath.length !== lastPath.length);
throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath(base));
}
const invalidSegmentRegEx = /(^|\\|\/)(\.\.?|node_modules)(\\|\/|$)/;
const patternRegEx = /\*/g;
function resolvePackageTargetString(
target: string,
subpath: string,
match: string,
packageJSONUrl: string,
base: string,
pattern: boolean,
internal: boolean,
conditions: Set<string>,
): URL | undefined {
if (subpath !== "" && !pattern && target[target.length - 1] !== "/") {
throwInvalidPackageTarget(match, target, packageJSONUrl, internal, base);
}
if (!target.startsWith("./")) {
if (
internal && !target.startsWith("../") &&
!target.startsWith("/")
) {
let isURL = false;
try {
new URL(target);
isURL = true;
} catch {}
if (!isURL) {
const exportTarget = pattern
? target.replace(patternRegEx, () => subpath)
: target + subpath;
return packageResolve(exportTarget, packageJSONUrl, conditions);
}
}
throwInvalidPackageTarget(match, target, packageJSONUrl, internal, base);
}
if (invalidSegmentRegEx.test(target.slice(2))) {
throwInvalidPackageTarget(match, target, packageJSONUrl, internal, base);
}
const resolved = new URL(target, packageJSONUrl);
const resolvedPath = resolved.pathname;
const packagePath = new URL(".", packageJSONUrl).pathname;
if (!resolvedPath.startsWith(packagePath)) {
throwInvalidPackageTarget(match, target, packageJSONUrl, internal, base);
}
if (subpath === "") return resolved;
if (invalidSegmentRegEx.test(subpath)) {
const request = pattern
? match.replace("*", () => subpath)
: match + subpath;
throwInvalidSubpath(request, packageJSONUrl, internal, base);
}
if (pattern) {
return new URL(resolved.href.replace(patternRegEx, () => subpath));
}
return new URL(subpath, resolved);
}
function isArrayIndex(key: string): boolean {
const keyNum = +key;
if (`${keyNum}` !== key) return false;
return keyNum >= 0 && keyNum < 0xFFFF_FFFF;
}
// deno-lint-ignore no-explicit-any
function resolvePackageTarget(
packageJSONUrl: string,
target: any,
subpath: string,
packageSubpath: string,
base: string,
pattern: boolean,
internal: boolean,
conditions: Set<string>,
): URL | undefined {
if (typeof target === "string") {
return resolvePackageTargetString(
target,
subpath,
packageSubpath,
packageJSONUrl,
base,
pattern,
internal,
conditions,
);
} else if (Array.isArray(target)) {
if (target.length === 0) {
return undefined;
}
let lastException;
for (let i = 0; i < target.length; i++) {
const targetItem = target[i];
let resolved;
try {
resolved = resolvePackageTarget(
packageJSONUrl,
targetItem,
subpath,
packageSubpath,
base,
pattern,
internal,
conditions,
);
} catch (e: unknown) {
lastException = e;
if (e instanceof NodeError && e.code === "ERR_INVALID_PACKAGE_TARGET") {
continue;
}
throw e;
}
if (resolved === undefined) {
continue;
}
if (resolved === null) {
lastException = null;
continue;
}
return resolved;
}
if (lastException === undefined || lastException === null) {
return undefined;
}
throw lastException;
} else if (typeof target === "object" && target !== null) {
const keys = Object.getOwnPropertyNames(target);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (isArrayIndex(key)) {
throw new ERR_INVALID_PACKAGE_CONFIG(
fileURLToPath(packageJSONUrl),
base,
'"exports" cannot contain numeric property keys.',
);
}
}
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (key === "default" || conditions.has(key)) {
const conditionalTarget = target[key];
const resolved = resolvePackageTarget(
packageJSONUrl,
conditionalTarget,
subpath,
packageSubpath,
base,
pattern,
internal,
conditions,
);
if (resolved === undefined) {
continue;
}
return resolved;
}
}
return undefined;
} else if (target === null) {
return undefined;
}
throwInvalidPackageTarget(
packageSubpath,
target,
packageJSONUrl,
internal,
base,
);
}
export function packageExportsResolve(
packageJSONUrl: string,
packageSubpath: string,
packageConfig: PackageConfig,
base: string,
conditions: Set<string>,
// @ts-ignore
): URL {
let exports = packageConfig.exports;
if (isConditionalExportsMainSugar(exports, packageJSONUrl, base)) {
exports = { ".": exports };
}
if (
hasOwn(exports, packageSubpath) &&
!packageSubpath.includes("*") &&
!packageSubpath.endsWith("/")
) {
const target = exports[packageSubpath];
const resolved = resolvePackageTarget(
packageJSONUrl,
target,
"",
packageSubpath,
base,
false,
false,
conditions,
);
if (resolved === null || resolved === undefined) {
throwExportsNotFound(packageSubpath, packageJSONUrl, base);
}
return resolved!;
}
let bestMatch = "";
let bestMatchSubpath = "";
const keys = Object.getOwnPropertyNames(exports);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const patternIndex = key.indexOf("*");
if (
patternIndex !== -1 &&
packageSubpath.startsWith(key.slice(0, patternIndex))
) {
// When this reaches EOL, this can throw at the top of the whole function:
//
// if (StringPrototypeEndsWith(packageSubpath, '/'))
// throwInvalidSubpath(packageSubpath)
//
// To match "imports" and the spec.
if (packageSubpath.endsWith("/")) {
// TODO:
// emitTrailingSlashPatternDeprecation(
// packageSubpath,
// packageJSONUrl,
// base,
// );
}
const patternTrailer = key.slice(patternIndex + 1);
if (
packageSubpath.length >= key.length &&
packageSubpath.endsWith(patternTrailer) &&
patternKeyCompare(bestMatch, key) === 1 &&
key.lastIndexOf("*") === patternIndex
) {
bestMatch = key;
bestMatchSubpath = packageSubpath.slice(
patternIndex,
packageSubpath.length - patternTrailer.length,
);
}
}
}
if (bestMatch) {
const target = exports[bestMatch];
const resolved = resolvePackageTarget(
packageJSONUrl,
target,
bestMatchSubpath,
bestMatch,
base,
true,
false,
conditions,
);
if (resolved === null || resolved === undefined) {
throwExportsNotFound(packageSubpath, packageJSONUrl, base);
}
return resolved!;
}
throwExportsNotFound(packageSubpath, packageJSONUrl, base);
}
export interface PackageConfig {
pjsonPath: string;
exists: boolean;
name?: string;
main?: string;
// deno-lint-ignore no-explicit-any
exports?: any;
// deno-lint-ignore no-explicit-any
imports?: any;
// deno-lint-ignore no-explicit-any
type?: string;
}
const packageJSONCache = new Map(); /* string -> PackageConfig */
function getPackageConfig(
path: string,
specifier: string | URL,
base?: string | URL,
): PackageConfig {
const existing = packageJSONCache.get(path);
if (existing !== undefined) {
return existing;
}
let source: string | undefined;
try {
source = new TextDecoder().decode(
Deno.readFileSync(path),
);
} catch {
// pass
}
if (source === undefined) {
const packageConfig = {
pjsonPath: path,
exists: false,
main: undefined,
name: undefined,
type: "none",
exports: undefined,
imports: undefined,
};
packageJSONCache.set(path, packageConfig);
return packageConfig;
}
let packageJSON;
try {
packageJSON = JSON.parse(source);
} catch (error) {
throw new ERR_INVALID_PACKAGE_CONFIG(
path,
(base ? `"${specifier}" from ` : "") + fileURLToPath(base || specifier),
// @ts-ignore
error.message,
);
}
let { imports, main, name, type } = packageJSON;
const { exports } = packageJSON;
if (typeof imports !== "object" || imports === null) imports = undefined;
if (typeof main !== "string") main = undefined;
if (typeof name !== "string") name = undefined;
// Ignore unknown types for forwards compatibility
if (type !== "module" && type !== "commonjs") type = "none";
const packageConfig = {
pjsonPath: path,
exists: true,
main,
name,
type,
exports,
imports,
};
packageJSONCache.set(path, packageConfig);
return packageConfig;
}
function getPackageScopeConfig(resolved: URL | string): PackageConfig {
let packageJSONUrl = new URL("./package.json", resolved);
while (true) {
const packageJSONPath = packageJSONUrl.pathname;
if (packageJSONPath.endsWith("node_modules/package.json")) {
break;
}
const packageConfig = getPackageConfig(
fileURLToPath(packageJSONUrl),
resolved,
);
if (packageConfig.exists) return packageConfig;
const lastPackageJSONUrl = packageJSONUrl;
packageJSONUrl = new URL("../package.json", packageJSONUrl);
// Terminates at root where ../package.json equals ../../package.json
// (can't just check "/package.json" for Windows support).
if (packageJSONUrl.pathname === lastPackageJSONUrl.pathname) break;
}
const packageJSONPath = fileURLToPath(packageJSONUrl);
const packageConfig = {
pjsonPath: packageJSONPath,
exists: false,
main: undefined,
name: undefined,
type: "none",
exports: undefined,
imports: undefined,
};
packageJSONCache.set(packageJSONPath, packageConfig);
return packageConfig;
}
export function packageImportsResolve(
name: string,
base: string,
conditions: Set<string>,
// @ts-ignore
): URL {
if (
name === "#" || name.startsWith("#/") ||
name.startsWith("/")
) {
const reason = "is not a valid internal imports specifier name";
throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, fileURLToPath(base));
}
let packageJSONUrl;
const packageConfig = getPackageScopeConfig(base);
if (packageConfig.exists) {
packageJSONUrl = pathToFileURL(packageConfig.pjsonPath);
const imports = packageConfig.imports;
if (imports) {
if (
hasOwn(imports, name) &&
!name.includes("*")
) {
const resolved = resolvePackageTarget(
packageJSONUrl.toString(),
imports[name],
"",
name,
base,
false,
true,
conditions,
);
if (resolved !== null && resolved !== undefined) {
return resolved;
}
} else {
let bestMatch = "";
let bestMatchSubpath = "";
const keys = Object.getOwnPropertyNames(imports);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const patternIndex = key.indexOf("*");
if (
patternIndex !== -1 &&
name.startsWith(
key.slice(0, patternIndex),
)
) {
const patternTrailer = key.slice(patternIndex + 1);
if (
name.length >= key.length &&
name.endsWith(patternTrailer) &&
patternKeyCompare(bestMatch, key) === 1 &&
key.lastIndexOf("*") === patternIndex
) {
bestMatch = key;
bestMatchSubpath = name.slice(
patternIndex,
name.length - patternTrailer.length,
);
}
}
}
if (bestMatch) {
const target = imports[bestMatch];
const resolved = resolvePackageTarget(
packageJSONUrl.toString(),
target,
bestMatchSubpath,
bestMatch,
base,
true,
true,
conditions,
);
if (resolved !== null && resolved !== undefined) {
return resolved;
}
}
}
}
}
throwImportNotDefined(name, packageJSONUrl, base);
}
// deno-lint-ignore no-explicit-any
function isConditionalExportsMainSugar(
exports: any,
packageJSONUrl: string,
base: string,
): boolean {
if (typeof exports === "string" || Array.isArray(exports)) return true;
if (typeof exports !== "object" || exports === null) return false;
const keys = Object.getOwnPropertyNames(exports);
let isConditionalSugar = false;
let i = 0;
for (let j = 0; j < keys.length; j++) {
const key = keys[j];
const curIsConditionalSugar = key === "" || key[0] !== ".";
if (i++ === 0) {
isConditionalSugar = curIsConditionalSugar;
} else if (isConditionalSugar !== curIsConditionalSugar) {
const message =
"\"exports\" cannot contain some keys starting with '.' and some not." +
" The exports object must either be an object of package subpath keys" +
" or an object of main entry condition name keys only.";
throw new ERR_INVALID_PACKAGE_CONFIG(
fileURLToPath(packageJSONUrl),
base,
message,
);
}
}
return isConditionalSugar;
} | the_stack |
import * as React from 'react';
import { css } from '@patternfly/react-styles';
import styles from '@patternfly/react-styles/css/components/DragDrop/drag-drop';
import { DroppableContext } from './DroppableContext';
import { DragDropContext } from './DragDrop';
export interface DraggableProps extends React.HTMLProps<HTMLDivElement> {
/** Content rendered inside DragDrop */
children?: React.ReactNode;
/** Don't wrap the component in a div. Requires passing a single child. */
hasNoWrapper?: boolean;
/** Class to add to outer div */
className?: string;
}
// Browsers really like being different from each other.
function getDefaultBackground() {
const div = document.createElement('div');
document.head.appendChild(div);
const bg = window.getComputedStyle(div).backgroundColor;
document.head.removeChild(div);
return bg;
}
function getInheritedBackgroundColor(el: HTMLElement): string {
const defaultStyle = getDefaultBackground();
const backgroundColor = window.getComputedStyle(el).backgroundColor;
if (backgroundColor !== defaultStyle) {
return backgroundColor;
} else if (!el.parentElement) {
return defaultStyle;
}
return getInheritedBackgroundColor(el.parentElement);
}
function removeBlankDiv(node: HTMLElement) {
if (node.getAttribute('blankDiv') === 'true') {
// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (let i = 0; i < node.children.length; i++) {
const child = node.children[i];
if (child.getAttribute('blankDiv') === 'true') {
node.removeChild(child);
node.setAttribute('blankDiv', 'false');
break;
}
}
}
}
interface DroppableItem {
node: HTMLElement;
rect: DOMRect;
isDraggingHost: boolean;
draggableNodes: HTMLElement[];
draggableNodesRects: DOMRect[];
}
// Reset per-element state
function resetDroppableItem(droppableItem: DroppableItem) {
removeBlankDiv(droppableItem.node);
droppableItem.node.classList.remove(styles.modifiers.dragging);
droppableItem.node.classList.remove(styles.modifiers.dragOutside);
droppableItem.draggableNodes.forEach((n, i) => {
n.style.transform = '';
n.style.transition = '';
droppableItem.draggableNodesRects[i] = n.getBoundingClientRect();
});
}
function overlaps(ev: MouseEvent, rect: DOMRect) {
return (
ev.clientX > rect.x && ev.clientX < rect.x + rect.width && ev.clientY > rect.y && ev.clientY < rect.y + rect.height
);
}
export const Draggable: React.FunctionComponent<DraggableProps> = ({
className,
children,
style: styleProp = {},
hasNoWrapper = false,
...props
}: DraggableProps) => {
/* eslint-disable prefer-const */
let [style, setStyle] = React.useState(styleProp);
/* eslint-enable prefer-const */
const [isDragging, setIsDragging] = React.useState(false);
const [isValidDrag, setIsValidDrag] = React.useState(true);
const { zone, droppableId } = React.useContext(DroppableContext);
const { onDrag, onDragMove, onDrop } = React.useContext(DragDropContext);
// Some state is better just to leave as vars passed around between various callbacks
// You can only drag around one item at a time anyways...
let startX = 0;
let startY = 0;
let index: number = null; // Index of this draggable
let hoveringDroppable: HTMLElement;
let hoveringIndex: number = null;
let mouseMoveListener: EventListener;
let mouseUpListener: EventListener;
// Makes it so dragging the _bottom_ of the item over the halfway of another moves it
let startYOffset = 0;
// After item returning to where it started animation completes
const onTransitionEnd = (_ev: React.TransitionEvent<HTMLElement>) => {
if (isDragging) {
setIsDragging(false);
setStyle(styleProp);
}
};
function getSourceAndDest() {
const hoveringDroppableId = hoveringDroppable ? hoveringDroppable.getAttribute('data-pf-droppableid') : null;
const source = {
droppableId,
index
};
const dest =
hoveringDroppableId !== null && hoveringIndex !== null
? {
droppableId: hoveringDroppableId,
index: hoveringIndex
}
: undefined;
return { source, dest, hoveringDroppableId };
}
const onMouseUpWhileDragging = (droppableItems: DroppableItem[]) => {
droppableItems.forEach(resetDroppableItem);
document.removeEventListener('mousemove', mouseMoveListener);
document.removeEventListener('mouseup', mouseUpListener);
document.removeEventListener('contextmenu', mouseUpListener);
const { source, dest, hoveringDroppableId } = getSourceAndDest();
const consumerReordered = onDrop(source, dest);
if (consumerReordered && droppableId === hoveringDroppableId) {
setIsDragging(false);
setStyle(styleProp);
} else if (!consumerReordered) {
// Animate item returning to where it started
setStyle({
...style,
transition: 'transform 0.5s cubic-bezier(0.2, 1, 0.1, 1) 0s',
transform: '',
background: styleProp.background,
boxShadow: styleProp.boxShadow
});
}
};
// This is where the magic happens
const onMouseMoveWhileDragging = (ev: MouseEvent, droppableItems: DroppableItem[], blankDivRect: DOMRect) => {
// Compute each time what droppable node we are hovering over
hoveringDroppable = null;
droppableItems.forEach(droppableItem => {
const { node, rect, isDraggingHost, draggableNodes, draggableNodesRects } = droppableItem;
if (overlaps(ev, rect)) {
// Add valid dropzone style
node.classList.remove(styles.modifiers.dragOutside);
hoveringDroppable = node;
// Check if we need to add a blank div row
if (node.getAttribute('blankDiv') !== 'true' && !isDraggingHost) {
const blankDiv = document.createElement('div');
blankDiv.setAttribute('blankDiv', 'true'); // Makes removing easier
let blankDivPos = -1;
for (let i = 0; i < draggableNodes.length; i++) {
const childRect = draggableNodesRects[i];
const isLast = i === draggableNodes.length - 1;
const startOverlaps = childRect.y >= startY - startYOffset;
if ((startOverlaps || isLast) && blankDivPos === -1) {
if (isLast && !startOverlaps) {
draggableNodes[i].after(blankDiv);
} else {
draggableNodes[i].before(blankDiv);
}
blankDiv.style.height = `${blankDivRect.height}px`;
blankDiv.style.width = `${blankDivRect.width}px`;
node.setAttribute('blankDiv', 'true'); // Makes removing easier
blankDivPos = i;
}
if (blankDivPos !== -1) {
childRect.y += blankDivRect.height;
}
}
// Insert so drag + drop behavior matches single-list case
draggableNodes.splice(blankDivPos, 0, blankDiv);
draggableNodesRects.splice(blankDivPos, 0, blankDivRect);
// Extend hitbox of droppable zone
rect.height += blankDivRect.height;
}
} else {
resetDroppableItem(droppableItem);
node.classList.add(styles.modifiers.dragging);
node.classList.add(styles.modifiers.dragOutside);
}
});
// Move hovering draggable and style it based on cursor position
setStyle({
...style,
transform: `translate(${ev.pageX - startX}px, ${ev.pageY - startY}px)`
});
setIsValidDrag(Boolean(hoveringDroppable));
// Iterate through sibling draggable nodes to reposition them and store correct hoveringIndex for onDrop
hoveringIndex = null;
if (hoveringDroppable) {
const { draggableNodes, draggableNodesRects } = droppableItems.find(item => item.node === hoveringDroppable);
let lastTranslate = 0;
draggableNodes.forEach((n, i) => {
n.style.transition = 'transform 0.5s cubic-bezier(0.2, 1, 0.1, 1) 0s';
const rect = draggableNodesRects[i];
const halfway = rect.y + rect.height / 2;
let translateY = 0;
// Use offset for more interactive translations
if (startY < halfway && ev.pageY + (blankDivRect.height - startYOffset) > halfway) {
translateY -= blankDivRect.height;
} else if (startY >= halfway && ev.pageY - startYOffset <= halfway) {
translateY += blankDivRect.height;
}
// Clever way to find item currently hovering over
if ((translateY <= lastTranslate && translateY < 0) || (translateY > lastTranslate && translateY > 0)) {
hoveringIndex = i;
}
n.style.transform = `translate(0, ${translateY}px`;
lastTranslate = translateY;
});
}
const { source, dest } = getSourceAndDest();
onDragMove(source, dest);
};
const onDragStart = (ev: React.DragEvent<HTMLElement>) => {
// Default HTML drag and drop doesn't allow us to change what the thing
// being dragged looks like. Because of this we'll use prevent the default
// and use `mouseMove` and `mouseUp` instead
ev.preventDefault();
if (isDragging) {
// still in animation
return;
}
// Cache droppable and draggable nodes and their bounding rects
const dragging = ev.target as HTMLElement;
const rect = dragging.getBoundingClientRect();
const droppableNodes = Array.from(document.querySelectorAll(`[data-pf-droppable="${zone}"]`)) as HTMLElement[];
const droppableItems = droppableNodes.reduce((acc, cur) => {
cur.classList.add(styles.modifiers.dragging);
const draggableNodes = Array.from(cur.querySelectorAll(`[data-pf-draggable-zone="${zone}"]`)) as HTMLElement[];
const isDraggingHost = cur.contains(dragging);
if (isDraggingHost) {
index = draggableNodes.indexOf(dragging);
}
const droppableItem = {
node: cur,
rect: cur.getBoundingClientRect(),
isDraggingHost,
// We don't want styles to apply to the left behind div in onMouseMoveWhileDragging
draggableNodes: draggableNodes.map(node => (node === dragging ? node.cloneNode(false) : node)),
draggableNodesRects: draggableNodes.map(node => node.getBoundingClientRect())
};
acc.push(droppableItem);
return acc;
}, []);
if (!onDrag({ droppableId, index })) {
// Consumer disallowed drag
return;
}
// Set initial style so future style mods take effect
style = {
...style,
top: rect.y,
left: rect.x,
width: rect.width,
height: rect.height,
'--pf-c-draggable--m-dragging--BackgroundColor': getInheritedBackgroundColor(dragging),
position: 'fixed',
zIndex: 5000
} as any;
setStyle(style);
// Store event details
startX = ev.pageX;
startY = ev.pageY;
startYOffset = startY - rect.y;
setIsDragging(true);
mouseMoveListener = ev => onMouseMoveWhileDragging(ev as MouseEvent, droppableItems, rect);
mouseUpListener = () => onMouseUpWhileDragging(droppableItems);
document.addEventListener('mousemove', mouseMoveListener);
document.addEventListener('mouseup', mouseUpListener);
// Comment out this line to debug while dragging by right clicking
// document.addEventListener('contextmenu', mouseUpListener);
};
const childProps = {
'data-pf-draggable-zone': isDragging ? null : zone,
draggable: true,
className: css(
styles.draggable,
isDragging && styles.modifiers.dragging,
!isValidDrag && styles.modifiers.dragOutside,
className
),
onDragStart,
onTransitionEnd,
style,
...props
};
return (
<React.Fragment>
{/* Leave behind blank spot per-design */}
{isDragging && (
<div draggable {...props} style={{ ...styleProp, visibility: 'hidden' }}>
{children}
</div>
)}
{hasNoWrapper ? (
React.cloneElement(children as React.ReactElement, childProps)
) : (
<div {...childProps}>{children}</div>
)}
</React.Fragment>
);
};
Draggable.displayName = 'Draggable'; | the_stack |
import { Injectable } from '@angular/core';
import { FileEntry, DirectoryEntry, Entry, Metadata, IFile } from '@ionic-native/file/ngx';
import { CoreApp } from '@services/app';
import { CoreMimetypeUtils } from '@services/utils/mimetype';
import { CoreTextUtils } from '@services/utils/text';
import { CoreUtils } from '@services/utils/utils';
import { CoreConstants } from '@/core/constants';
import { CoreError } from '@classes/errors/error';
import { CoreLogger } from '@singletons/logger';
import { makeSingleton, File, Zip, Platform, WebView } from '@singletons';
import { CoreFileEntry } from '@services/file-helper';
import { CoreText } from '@singletons/text';
/**
* Progress event used when writing a file data into a file.
*/
export type CoreFileProgressEvent = {
/**
* Whether the values are reliabรฑe.
*/
lengthComputable?: boolean;
/**
* Number of treated bytes.
*/
loaded?: number;
/**
* Total of bytes.
*/
total?: number;
};
/**
* Progress function.
*/
export type CoreFileProgressFunction = (event: CoreFileProgressEvent) => void;
/**
* Constants to define the format to read a file.
*/
export const enum CoreFileFormat {
FORMATTEXT = 0,
FORMATDATAURL = 1,
FORMATBINARYSTRING = 2,
FORMATARRAYBUFFER = 3,
FORMATJSON = 4,
}
/**
* Factory to interact with the file system.
*/
@Injectable({ providedIn: 'root' })
export class CoreFileProvider {
// Formats to read a file.
/**
* @deprecated since 3.9.5, use CoreFileFormat directly.
*/
static readonly FORMATTEXT = CoreFileFormat.FORMATTEXT;
/**
* @deprecated since 3.9.5, use CoreFileFormat directly.
*/
static readonly FORMATDATAURL = CoreFileFormat.FORMATDATAURL;
/**
* @deprecated since 3.9.5, use CoreFileFormat directly.
*/
static readonly FORMATBINARYSTRING = CoreFileFormat.FORMATBINARYSTRING;
/**
* @deprecated since 3.9.5, use CoreFileFormat directly.
*/
static readonly FORMATARRAYBUFFER = CoreFileFormat.FORMATARRAYBUFFER;
/**
* @deprecated since 3.9.5, use CoreFileFormat directly.
*/
static readonly FORMATJSON = CoreFileFormat.FORMATJSON;
// Folders.
static readonly SITESFOLDER = 'sites';
static readonly TMPFOLDER = 'tmp';
static readonly CHUNK_SIZE = 1048576; // 1 MB. Same chunk size as Ionic Native.
protected logger: CoreLogger;
protected initialized = false;
protected basePath = '';
protected isHTMLAPI = false;
constructor() {
this.logger = CoreLogger.getInstance('CoreFileProvider');
}
/**
* Sets basePath to use with HTML API. Reserved for core use.
*
* @param path Base path to use.
*/
setHTMLBasePath(path: string): void {
this.isHTMLAPI = true;
this.basePath = path;
}
/**
* Checks if we're using HTML API.
*
* @return True if uses HTML API, false otherwise.
*/
usesHTMLAPI(): boolean {
return this.isHTMLAPI;
}
/**
* Initialize basePath based on the OS if it's not initialized already.
*
* @return Promise to be resolved when the initialization is finished.
*/
async init(): Promise<void> {
if (this.initialized) {
return;
}
await Platform.ready();
if (CoreApp.isAndroid()) {
this.basePath = File.externalApplicationStorageDirectory || this.basePath;
} else if (CoreApp.isIOS()) {
this.basePath = File.documentsDirectory || this.basePath;
} else if (!this.isAvailable() || this.basePath === '') {
this.logger.error('Error getting device OS.');
return Promise.reject(new CoreError('Error getting device OS to initialize file system.'));
}
this.initialized = true;
this.logger.debug('FS initialized: ' + this.basePath);
}
/**
* Check if the plugin is available.
*
* @return Whether the plugin is available.
*/
isAvailable(): boolean {
return window.resolveLocalFileSystemURL !== undefined;
}
/**
* Get a file.
*
* @param path Relative path to the file.
* @return Promise resolved when the file is retrieved.
*/
getFile(path: string): Promise<FileEntry> {
return this.init().then(() => {
this.logger.debug('Get file: ' + path);
return File.resolveLocalFilesystemUrl(this.addBasePathIfNeeded(path));
}).then((entry) => <FileEntry> entry);
}
/**
* Get a directory.
*
* @param path Relative path to the directory.
* @return Promise resolved when the directory is retrieved.
*/
getDir(path: string): Promise<DirectoryEntry> {
return this.init().then(() => {
this.logger.debug('Get directory: ' + path);
return File.resolveDirectoryUrl(this.addBasePathIfNeeded(path));
});
}
/**
* Get site folder path.
*
* @param siteId Site ID.
* @return Site folder path.
*/
getSiteFolder(siteId: string): string {
return CoreFileProvider.SITESFOLDER + '/' + siteId;
}
/**
* Create a directory or a file.
*
* @param isDirectory True if a directory should be created, false if it should create a file.
* @param path Relative path to the dir/file.
* @param failIfExists True if it should fail if the dir/file exists, false otherwise.
* @param base Base path to create the dir/file in. If not set, use basePath.
* @return Promise to be resolved when the dir/file is created.
*/
protected async create(
isDirectory: boolean,
path: string,
failIfExists?: boolean,
base?: string,
): Promise<FileEntry | DirectoryEntry> {
await this.init();
// Remove basePath if it's in the path.
path = this.removeStartingSlash(path.replace(this.basePath, ''));
base = base || this.basePath;
if (path.indexOf('/') == -1) {
if (isDirectory) {
this.logger.debug('Create dir ' + path + ' in ' + base);
return File.createDir(base, path, !failIfExists);
} else {
this.logger.debug('Create file ' + path + ' in ' + base);
return File.createFile(base, path, !failIfExists);
}
} else {
// The file plugin doesn't allow creating more than 1 level at a time (e.g. tmp/folder).
// We need to create them 1 by 1.
const firstDir = path.substring(0, path.indexOf('/'));
const restOfPath = path.substring(path.indexOf('/') + 1);
this.logger.debug('Create dir ' + firstDir + ' in ' + base);
const newDirEntry = await File.createDir(base, firstDir, true);
return this.create(isDirectory, restOfPath, failIfExists, newDirEntry.toURL());
}
}
/**
* Create a directory.
*
* @param path Relative path to the directory.
* @param failIfExists True if it should fail if the directory exists, false otherwise.
* @return Promise to be resolved when the directory is created.
*/
async createDir(path: string, failIfExists?: boolean): Promise<DirectoryEntry> {
const entry = <DirectoryEntry> await this.create(true, path, failIfExists);
return entry;
}
/**
* Create a file.
*
* @param path Relative path to the file.
* @param failIfExists True if it should fail if the file exists, false otherwise..
* @return Promise to be resolved when the file is created.
*/
async createFile(path: string, failIfExists?: boolean): Promise<FileEntry> {
const entry = <FileEntry> await this.create(false, path, failIfExists);
return entry;
}
/**
* Removes a directory and all its contents.
*
* @param path Relative path to the directory.
* @return Promise to be resolved when the directory is deleted.
*/
async removeDir(path: string): Promise<void> {
await this.init();
// Remove basePath if it's in the path.
path = this.removeStartingSlash(path.replace(this.basePath, ''));
this.logger.debug('Remove directory: ' + path);
await File.removeRecursively(this.basePath, path);
}
/**
* Removes a file and all its contents.
*
* @param path Relative path to the file.
* @return Promise to be resolved when the file is deleted.
*/
async removeFile(path: string): Promise<void> {
await this.init();
// Remove basePath if it's in the path.
path = this.removeStartingSlash(path.replace(this.basePath, ''));
this.logger.debug('Remove file: ' + path);
try {
await File.removeFile(this.basePath, path);
} catch (error) {
// The delete can fail if the path has encoded characters. Try again if that's the case.
const decodedPath = decodeURI(path);
if (decodedPath != path) {
await File.removeFile(this.basePath, decodedPath);
} else {
throw error;
}
}
}
/**
* Removes a file given its FileEntry.
*
* @param fileEntry File Entry.
* @return Promise resolved when the file is deleted.
*/
removeFileByFileEntry(entry: Entry): Promise<void> {
return new Promise((resolve, reject) => entry.remove(resolve, reject));
}
/**
* Retrieve the contents of a directory (not subdirectories).
*
* @param path Relative path to the directory.
* @return Promise to be resolved when the contents are retrieved.
*/
async getDirectoryContents(path: string): Promise<(FileEntry | DirectoryEntry)[]> {
await this.init();
// Remove basePath if it's in the path.
path = this.removeStartingSlash(path.replace(this.basePath, ''));
this.logger.debug('Get contents of dir: ' + path);
const result = await File.listDir(this.basePath, path);
return <(FileEntry | DirectoryEntry)[]> result;
}
/**
* Type guard to check if the param is a DirectoryEntry.
*
* @param entry Param to check.
* @return Whether the param is a DirectoryEntry.
*/
protected isDirectoryEntry(entry: FileEntry | DirectoryEntry): entry is DirectoryEntry {
return entry.isDirectory === true;
}
/**
* Calculate the size of a directory or a file.
*
* @param entry Directory or file.
* @return Promise to be resolved when the size is calculated.
*/
protected getSize(entry: DirectoryEntry | FileEntry): Promise<number> {
return new Promise<number>((resolve, reject) => {
if (this.isDirectoryEntry(entry)) {
const directoryReader = entry.createReader();
directoryReader.readEntries(async (entries: (DirectoryEntry | FileEntry)[]) => {
const promises: Promise<number>[] = [];
for (let i = 0; i < entries.length; i++) {
promises.push(this.getSize(entries[i]));
}
try {
const sizes = await Promise.all(promises);
let directorySize = 0;
for (let i = 0; i < sizes.length; i++) {
const fileSize = Number(sizes[i]);
if (isNaN(fileSize)) {
reject();
return;
}
directorySize += fileSize;
}
resolve(directorySize);
} catch (error) {
reject(error);
}
}, reject);
} else {
entry.file((file) => {
resolve(file.size);
}, reject);
}
});
}
/**
* Calculate the size of a directory.
*
* @param path Relative path to the directory.
* @return Promise to be resolved when the size is calculated.
*/
getDirectorySize(path: string): Promise<number> {
// Remove basePath if it's in the path.
path = this.removeStartingSlash(path.replace(this.basePath, ''));
this.logger.debug('Get size of dir: ' + path);
return this.getDir(path).then((dirEntry) => this.getSize(dirEntry));
}
/**
* Calculate the size of a file.
*
* @param path Relative path to the file.
* @return Promise to be resolved when the size is calculated.
*/
getFileSize(path: string): Promise<number> {
// Remove basePath if it's in the path.
path = this.removeStartingSlash(path.replace(this.basePath, ''));
this.logger.debug('Get size of file: ' + path);
return this.getFile(path).then((fileEntry) => this.getSize(fileEntry));
}
/**
* Get file object from a FileEntry.
*
* @param path Relative path to the file.
* @return Promise to be resolved when the file is retrieved.
*/
getFileObjectFromFileEntry(entry: FileEntry): Promise<IFile> {
return new Promise((resolve, reject): void => {
this.logger.debug('Get file object of: ' + entry.fullPath);
entry.file(resolve, reject);
});
}
/**
* Calculate the free space in the disk.
* Please notice that this function isn't reliable and it's not documented in the Cordova File plugin.
*
* @return Promise resolved with the estimated free space in bytes.
*/
calculateFreeSpace(): Promise<number> {
return File.getFreeDiskSpace().then((size) => {
if (CoreApp.isIOS()) {
// In iOS the size is in bytes.
return Number(size);
}
// The size is in KB, convert it to bytes.
return Number(size) * 1024;
});
}
/**
* Normalize a filename that usually comes URL encoded.
*
* @param filename The file name.
* @return The file name normalized.
*/
normalizeFileName(filename: string): string {
filename = CoreTextUtils.decodeURIComponent(filename);
return filename;
}
/**
* Read a file from local file system.
*
* @param path Relative path to the file.
* @param format Format to read the file.
* @param folder Absolute path to the folder where the file is. Use it to read files outside of the app's data folder.
* @return Promise to be resolved when the file is read.
*/
readFile(
path: string,
format?: CoreFileFormat.FORMATTEXT | CoreFileFormat.FORMATDATAURL | CoreFileFormat.FORMATBINARYSTRING,
folder?: string,
): Promise<string>;
readFile(path: string, format: CoreFileFormat.FORMATARRAYBUFFER, folder?: string): Promise<ArrayBuffer>;
readFile<T = unknown>(path: string, format: CoreFileFormat.FORMATJSON, folder?: string): Promise<T>;
readFile(
path: string,
format: CoreFileFormat = CoreFileFormat.FORMATTEXT,
folder?: string,
): Promise<string | ArrayBuffer | unknown> {
if (!folder) {
folder = this.basePath;
// Remove basePath if it's in the path.
path = this.removeStartingSlash(path.replace(this.basePath, ''));
}
this.logger.debug(`Read file ${path} with format ${format} in folder ${folder}`);
switch (format) {
case CoreFileFormat.FORMATDATAURL:
return File.readAsDataURL(folder, path);
case CoreFileFormat.FORMATBINARYSTRING:
return File.readAsBinaryString(folder, path);
case CoreFileFormat.FORMATARRAYBUFFER:
return File.readAsArrayBuffer(folder, path);
case CoreFileFormat.FORMATJSON:
return File.readAsText(folder, path).then((text) => {
const parsed = CoreTextUtils.parseJSON(text, null);
if (parsed == null && text != null) {
throw new CoreError('Error parsing JSON file: ' + path);
}
return parsed;
});
default:
return File.readAsText(folder, path);
}
}
/**
* Read file contents from a file data object.
*
* @param fileData File's data.
* @param format Format to read the file.
* @return Promise to be resolved when the file is read.
*/
readFileData(fileData: IFile, format: CoreFileFormat = CoreFileFormat.FORMATTEXT): Promise<string | ArrayBuffer | unknown> {
format = format || CoreFileFormat.FORMATTEXT;
this.logger.debug('Read file from file data with format ' + format);
return new Promise((resolve, reject): void => {
const reader = new FileReader();
reader.onloadend = (event): void => {
if (event.target?.result !== undefined && event.target.result !== null) {
if (format == CoreFileFormat.FORMATJSON) {
// Convert to object.
const parsed = CoreTextUtils.parseJSON(<string> event.target.result, null);
if (parsed == null) {
reject('Error parsing JSON file.');
}
resolve(parsed);
} else {
resolve(event.target.result);
}
} else if (event.target?.error !== undefined && event.target.error !== null) {
reject(event.target.error);
} else {
reject({ code: null, message: 'READER_ONLOADEND_ERR' });
}
};
// Check if the load starts. If it doesn't start in 3 seconds, reject.
// Sometimes in Android the read doesn't start for some reason, so the promise never finishes.
let hasStarted = false;
reader.onloadstart = () => {
hasStarted = true;
};
setTimeout(() => {
if (!hasStarted) {
reject('Upload cannot start.');
}
}, 3000);
switch (format) {
case CoreFileFormat.FORMATDATAURL:
reader.readAsDataURL(fileData);
break;
case CoreFileFormat.FORMATBINARYSTRING:
reader.readAsBinaryString(fileData);
break;
case CoreFileFormat.FORMATARRAYBUFFER:
reader.readAsArrayBuffer(fileData);
break;
default:
reader.readAsText(fileData);
}
});
}
/**
* Writes some data in a file.
*
* @param path Relative path to the file.
* @param data Data to write.
* @param append Whether to append the data to the end of the file.
* @return Promise to be resolved when the file is written.
*/
async writeFile(path: string, data: string | Blob, append?: boolean): Promise<FileEntry> {
await this.init();
// Remove basePath if it's in the path.
path = this.removeStartingSlash(path.replace(this.basePath, ''));
this.logger.debug('Write file: ' + path);
// Create file (and parent folders) to prevent errors.
const fileEntry = await this.createFile(path);
if (this.isHTMLAPI && (typeof data == 'string' || data.toString() == '[object ArrayBuffer]')) {
// We need to write Blobs.
const extension = CoreMimetypeUtils.getFileExtension(path);
const type = extension ? CoreMimetypeUtils.getMimeType(extension) : '';
data = new Blob([data], { type: type || 'text/plain' });
}
await File.writeFile(this.basePath, path, data, { replace: !append, append: !!append });
return fileEntry;
}
/**
* Write some file data into a filesystem file.
* It's done in chunks to prevent crashing the app for big files.
* Please notice Ionic Native writeFile function already splits by chunks, but it doesn't have an onProgress function.
*
* @param file The data to write.
* @param path Path where to store the data.
* @param onProgress Function to call on progress.
* @param offset Offset where to start reading from.
* @param append Whether to append the data to the end of the file.
* @return Promise resolved when done.
*/
async writeFileDataInFile(
file: Blob,
path: string,
onProgress?: CoreFileProgressFunction,
offset: number = 0,
append?: boolean,
): Promise<FileEntry> {
offset = offset || 0;
try {
// Get the chunk to write.
const chunk = file.slice(offset, Math.min(offset + CoreFileProvider.CHUNK_SIZE, file.size));
const fileEntry = await this.writeFile(path, chunk, append);
offset += CoreFileProvider.CHUNK_SIZE;
onProgress && onProgress({
lengthComputable: true,
loaded: offset,
total: file.size,
});
if (offset >= file.size) {
// Done, stop.
return fileEntry;
}
// Read the next chunk.
return this.writeFileDataInFile(file, path, onProgress, offset, true);
} catch (error) {
if (error && error.target && error.target.error) {
// Error returned by the writer, throw the "real" error.
throw error.target.error;
}
throw error;
}
}
/**
* Gets a file that might be outside the app's folder.
*
* @param fullPath Absolute path to the file.
* @return Promise to be resolved when the file is retrieved.
*/
getExternalFile(fullPath: string): Promise<FileEntry> {
return File.resolveLocalFilesystemUrl(fullPath).then((entry) => <FileEntry> entry);
}
/**
* Calculate the size of a file.
*
* @param path Absolute path to the file.
* @return Promise to be resolved when the size is calculated.
*/
async getExternalFileSize(path: string): Promise<number> {
const fileEntry = await this.getExternalFile(path);
return this.getSize(fileEntry);
}
/**
* Removes a file that might be outside the app's folder.
*
* @param fullPath Absolute path to the file.
* @return Promise to be resolved when the file is removed.
*/
async removeExternalFile(fullPath: string): Promise<void> {
const directory = fullPath.substring(0, fullPath.lastIndexOf('/'));
const filename = fullPath.substring(fullPath.lastIndexOf('/') + 1);
await File.removeFile(directory, filename);
}
/**
* Get the base path where the application files are stored.
*
* @return Promise to be resolved when the base path is retrieved.
*/
getBasePath(): Promise<string> {
return this.init().then(() => {
if (this.basePath.slice(-1) == '/') {
return this.basePath;
} else {
return this.basePath + '/';
}
});
}
/**
* Get the base path where the application files are stored in the format to be used for downloads.
* iOS: Internal URL (cdvfile://).
* Others: basePath (file://)
*
* @return Promise to be resolved when the base path is retrieved.
*/
async getBasePathToDownload(): Promise<string> {
await this.init();
if (CoreApp.isIOS()) {
// In iOS we want the internal URL (cdvfile://localhost/persistent/...).
const dirEntry = await File.resolveDirectoryUrl(this.basePath);
return dirEntry.toInternalURL();
} else {
// In the other platforms we use the basePath as it is (file://...).
return this.basePath;
}
}
/**
* Get the base path where the application files are stored. Returns the value instantly, without waiting for it to be ready.
*
* @return Base path. If the service hasn't been initialized it will return an invalid value.
*/
getBasePathInstant(): string {
if (!this.basePath) {
return this.basePath;
} else if (this.basePath.slice(-1) == '/') {
return this.basePath;
} else {
return this.basePath + '/';
}
}
/**
* Move a dir.
*
* @param originalPath Path to the dir to move.
* @param newPath New path of the dir.
* @param destDirExists Set it to true if you know the directory where to put the dir exists. If false, the function will
* try to create it (slower).
* @return Promise resolved when the entry is moved.
*/
async moveDir(originalPath: string, newPath: string, destDirExists?: boolean): Promise<DirectoryEntry> {
const entry = await this.copyOrMoveFileOrDir(originalPath, newPath, true, false, destDirExists);
return <DirectoryEntry> entry;
}
/**
* Move a file.
*
* @param originalPath Path to the file to move.
* @param newPath New path of the file.
* @param destDirExists Set it to true if you know the directory where to put the file exists. If false, the function will
* try to create it (slower).
* @return Promise resolved when the entry is moved.
*/
async moveFile(originalPath: string, newPath: string, destDirExists?: boolean): Promise<FileEntry> {
const entry = await this.copyOrMoveFileOrDir(originalPath, newPath, false, false, destDirExists);
return <FileEntry> entry;
}
/**
* Copy a directory.
*
* @param from Path to the directory to move.
* @param to New path of the directory.
* @param destDirExists Set it to true if you know the directory where to put the dir exists. If false, the function will
* try to create it (slower).
* @return Promise resolved when the entry is copied.
*/
async copyDir(from: string, to: string, destDirExists?: boolean): Promise<DirectoryEntry> {
const entry = await this.copyOrMoveFileOrDir(from, to, true, true, destDirExists);
return <DirectoryEntry> entry;
}
/**
* Copy a file.
*
* @param from Path to the file to move.
* @param to New path of the file.
* @param destDirExists Set it to true if you know the directory where to put the file exists. If false, the function will
* try to create it (slower).
* @return Promise resolved when the entry is copied.
*/
async copyFile(from: string, to: string, destDirExists?: boolean): Promise<FileEntry> {
const entry = await this.copyOrMoveFileOrDir(from, to, false, true, destDirExists);
return <FileEntry> entry;
}
/**
* Copy or move a file or a directory.
*
* @param from Path to the file/dir to move.
* @param to New path of the file/dir.
* @param isDir Whether it's a dir or a file.
* @param copy Whether to copy. If false, it will move the file.
* @param destDirExists Set it to true if you know the directory where to put the file/dir exists. If false, the function will
* try to create it (slower).
* @return Promise resolved when the entry is copied.
*/
protected async copyOrMoveFileOrDir(
from: string,
to: string,
isDir?: boolean,
copy?: boolean,
destDirExists?: boolean,
): Promise<FileEntry | DirectoryEntry> {
const fileIsInAppFolder = this.isPathInAppFolder(from);
if (!fileIsInAppFolder) {
return this.copyOrMoveExternalFile(from, to, copy);
}
const moveCopyFn: MoveCopyFunction = copy ?
(isDir ? File.copyDir.bind(File.instance) : File.copyFile.bind(File.instance)) :
(isDir ? File.moveDir.bind(File.instance) : File.moveFile.bind(File.instance));
await this.init();
// Paths cannot start with "/". Remove basePath if present.
from = this.removeStartingSlash(from.replace(this.basePath, ''));
to = this.removeStartingSlash(to.replace(this.basePath, ''));
const toFileAndDir = this.getFileAndDirectoryFromPath(to);
if (toFileAndDir.directory && !destDirExists) {
// Create the target directory if it doesn't exist.
await this.createDir(toFileAndDir.directory);
}
try {
const entry = await moveCopyFn(this.basePath, from, this.basePath, to);
return entry;
} catch (error) {
// The copy can fail if the path has encoded characters. Try again if that's the case.
const decodedFrom = decodeURI(from);
const decodedTo = decodeURI(to);
if (from != decodedFrom || to != decodedTo) {
return moveCopyFn(this.basePath, decodedFrom, this.basePath, decodedTo);
} else {
return Promise.reject(error);
}
}
}
/**
* Extract the file name and directory from a given path.
*
* @param path Path to be extracted.
* @return Plain object containing the file name and directory.
* @description
* file.pdf -> directory: '', name: 'file.pdf'
* /file.pdf -> directory: '', name: 'file.pdf'
* path/file.pdf -> directory: 'path', name: 'file.pdf'
* path/ -> directory: 'path', name: ''
* path -> directory: '', name: 'path'
*/
getFileAndDirectoryFromPath(path: string): {directory: string; name: string} {
const file = {
directory: '',
name: '',
};
file.directory = path.substring(0, path.lastIndexOf('/'));
file.name = path.substring(path.lastIndexOf('/') + 1);
return file;
}
/**
* Get the internal URL of a file.
* Please notice that with WKWebView these URLs no longer work in mobile. Use fileEntry.toURL() along with convertFileSrc.
*
* @param fileEntry File Entry.
* @return Internal URL.
*/
getInternalURL(fileEntry: FileEntry): string {
if (!fileEntry.toInternalURL) {
// File doesn't implement toInternalURL, use toURL.
return fileEntry.toURL();
}
return fileEntry.toInternalURL();
}
/**
* Adds the basePath to a path if it doesn't have it already.
*
* @param path Path to treat.
* @return Path with basePath added.
*/
addBasePathIfNeeded(path: string): string {
if (path.indexOf(this.basePath) > -1) {
return path;
} else {
return CoreText.concatenatePaths(this.basePath, path);
}
}
/**
* Remove the base path from a path. If basePath isn't found, return false.
*
* @param path Path to treat.
* @return Path without basePath if basePath was found, undefined otherwise.
*/
removeBasePath(path: string): string {
if (path.indexOf(this.basePath) > -1) {
return path.replace(this.basePath, '');
}
return path;
}
/**
* Unzips a file.
*
* @param path Path to the ZIP file.
* @param destFolder Path to the destination folder. If not defined, a new folder will be created with the
* same location and name as the ZIP file (without extension).
* @param onProgress Function to call on progress.
* @param recreateDir Delete the dest directory before unzipping. Defaults to true.
* @return Promise resolved when the file is unzipped.
*/
async unzipFile(
path: string,
destFolder?: string,
onProgress?: (progress: ProgressEvent) => void,
recreateDir: boolean = true,
): Promise<void> {
// Get the source file.
const fileEntry = await this.getFile(path);
if (destFolder && recreateDir) {
// Make sure the dest dir doesn't exist already.
await CoreUtils.ignoreErrors(this.removeDir(destFolder));
// Now create the dir, otherwise if any of the ancestor dirs doesn't exist the unzip would fail.
await this.createDir(destFolder);
}
// If destFolder is not set, use same location as ZIP file. We need to use absolute paths (including basePath).
destFolder = this.addBasePathIfNeeded(destFolder || CoreMimetypeUtils.removeExtension(path));
const result = await Zip.unzip(fileEntry.toURL(), destFolder, onProgress);
if (result == -1) {
throw new CoreError('Unzip failed.');
}
}
/**
* Search a string or regexp in a file contents and replace it. The result is saved in the same file.
*
* @param path Path to the file.
* @param search Value to search.
* @param newValue New value.
* @return Promise resolved in success.
*/
async replaceInFile(path: string, search: string | RegExp, newValue: string): Promise<void> {
let content = <string> await this.readFile(path);
if (content === undefined || content === null || !content.replace) {
throw new CoreError(`Error reading file ${path}`);
}
if (content.match(search)) {
content = content.replace(search, newValue);
await this.writeFile(path, content);
}
}
/**
* Get a file/dir metadata given the file's entry.
*
* @param fileEntry FileEntry retrieved from getFile or similar.
* @return Promise resolved with metadata.
*/
getMetadata(fileEntry: Entry): Promise<Metadata> {
if (!fileEntry || !fileEntry.getMetadata) {
return Promise.reject(new CoreError('Cannot get metadata from file entry.'));
}
return new Promise((resolve, reject): void => {
fileEntry.getMetadata(resolve, reject);
});
}
/**
* Get a file/dir metadata given the path.
*
* @param path Path to the file/dir.
* @param isDir True if directory, false if file.
* @return Promise resolved with metadata.
*/
getMetadataFromPath(path: string, isDir?: boolean): Promise<Metadata> {
let promise;
if (isDir) {
promise = this.getDir(path);
} else {
promise = this.getFile(path);
}
return promise.then((entry) => this.getMetadata(entry));
}
/**
* Remove the starting slash of a path if it's there. E.g. '/sites/filepool' -> 'sites/filepool'.
*
* @param path Path.
* @return Path without a slash in the first position.
*/
removeStartingSlash(path: string): string {
if (path[0] == '/') {
return path.substring(1);
}
return path;
}
/**
* Convenience function to copy or move an external file.
*
* @param from Absolute path to the file to copy/move.
* @param to Relative new path of the file (inside the app folder).
* @param copy True to copy, false to move.
* @return Promise resolved when the entry is copied/moved.
*/
protected async copyOrMoveExternalFile(from: string, to: string, copy?: boolean): Promise<FileEntry> {
// Get the file to copy/move.
const fileEntry = await this.getExternalFile(from);
// Create the destination dir if it doesn't exist.
const dirAndFile = this.getFileAndDirectoryFromPath(to);
const dirEntry = await this.createDir(dirAndFile.directory);
// Now copy/move the file.
return new Promise((resolve, reject): void => {
if (copy) {
fileEntry.copyTo(dirEntry, dirAndFile.name, (entry: FileEntry) => resolve(entry), reject);
} else {
fileEntry.moveTo(dirEntry, dirAndFile.name, (entry: FileEntry) => resolve(entry), reject);
}
});
}
/**
* Copy a file from outside of the app folder to somewhere inside the app folder.
*
* @param from Absolute path to the file to copy.
* @param to Relative new path of the file (inside the app folder).
* @return Promise resolved when the entry is copied.
*/
copyExternalFile(from: string, to: string): Promise<FileEntry> {
return this.copyOrMoveExternalFile(from, to, true);
}
/**
* Move a file from outside of the app folder to somewhere inside the app folder.
*
* @param from Absolute path to the file to move.
* @param to Relative new path of the file (inside the app folder).
* @return Promise resolved when the entry is moved.
*/
moveExternalFile(from: string, to: string): Promise<FileEntry> {
return this.copyOrMoveExternalFile(from, to, false);
}
/**
* Get a unique file name inside a folder, adding numbers to the file name if needed.
*
* @param dirPath Path to the destination folder.
* @param fileName File name that wants to be used.
* @param defaultExt Default extension to use if no extension found in the file.
* @return Promise resolved with the unique file name.
*/
async getUniqueNameInFolder(dirPath: string, fileName: string, defaultExt?: string): Promise<string> {
// Get existing files in the folder.
try {
const entries = await this.getDirectoryContents(dirPath);
const files = {};
let fileNameWithoutExtension = CoreMimetypeUtils.removeExtension(fileName);
let extension = CoreMimetypeUtils.getFileExtension(fileName) || defaultExt;
// Clean the file name.
fileNameWithoutExtension = CoreTextUtils.removeSpecialCharactersForFiles(
CoreTextUtils.decodeURIComponent(fileNameWithoutExtension),
);
// Index the files by name.
entries.forEach((entry) => {
files[entry.name.toLowerCase()] = entry;
});
// Format extension.
if (extension) {
extension = '.' + extension;
} else {
extension = '';
}
return this.calculateUniqueName(files, fileNameWithoutExtension + extension);
} catch (error) {
// Folder doesn't exist, name is unique. Clean it and return it.
return CoreTextUtils.removeSpecialCharactersForFiles(CoreTextUtils.decodeURIComponent(fileName));
}
}
/**
* Given a file name and a set of already used names, calculate a unique name.
*
* @param usedNames Object with names already used as keys.
* @param name Name to check.
* @return Unique name.
*/
calculateUniqueName(usedNames: Record<string, unknown>, name: string): string {
if (usedNames[name.toLowerCase()] === undefined) {
// No file with the same name.
return name;
}
// Repeated name. Add a number until we find a free name.
const nameWithoutExtension = CoreMimetypeUtils.removeExtension(name);
let extension = CoreMimetypeUtils.getFileExtension(name);
let num = 1;
extension = extension ? '.' + extension : '';
do {
name = nameWithoutExtension + '(' + num + ')' + extension;
num++;
} while (usedNames[name.toLowerCase()] !== undefined);
return name;
}
/**
* Remove app temporary folder.
*
* @return Promise resolved when done.
*/
async clearTmpFolder(): Promise<void> {
// Ignore errors because the folder might not exist.
await CoreUtils.ignoreErrors(this.removeDir(CoreFileProvider.TMPFOLDER));
}
/**
* Given a folder path and a list of used files, remove all the files of the folder that aren't on the list of used files.
*
* @param dirPath Folder path.
* @param files List of used files.
* @return Promise resolved when done, rejected if failure.
*/
async removeUnusedFiles(dirPath: string, files: CoreFileEntry[]): Promise<void> {
// Get the directory contents.
try {
const contents = await this.getDirectoryContents(dirPath);
if (!contents.length) {
return;
}
const filesMap: {[fullPath: string]: FileEntry} = {};
const promises: Promise<void>[] = [];
// Index the received files by fullPath and ignore the invalid ones.
files.forEach((file) => {
if ('fullPath' in file) {
filesMap[file.fullPath] = file;
}
});
// Check which of the content files aren't used anymore and delete them.
contents.forEach((file) => {
if (!filesMap[file.fullPath]) {
// File isn't used, delete it.
promises.push(this.removeFileByFileEntry(file));
}
});
await Promise.all(promises);
} catch (error) {
// Ignore errors, maybe it doesn't exist.
}
}
/**
* Check if a file is inside the app's folder.
*
* @param path The absolute path of the file to check.
* @return Whether the file is in the app's folder.
*/
isFileInAppFolder(path: string): boolean {
return path.indexOf(this.basePath) != -1;
}
/**
* Get the path to the www folder at runtime based on the WebView URL.
*
* @return Path.
*/
getWWWPath(): string {
// Use current URL, removing the path.
if (!window.location.pathname || window.location.pathname == '/') {
return window.location.href;
}
const position = window.location.href.indexOf(window.location.pathname);
if (position != -1) {
return window.location.href.substring(0, position);
}
return window.location.href;
}
/**
* Get the full path to the www folder.
*
* @return Path.
*/
getWWWAbsolutePath(): string {
if (window.cordova && cordova.file && cordova.file.applicationDirectory) {
return CoreText.concatenatePaths(cordova.file.applicationDirectory, 'www');
}
// Cannot use Cordova to get it, use the WebView URL.
return this.getWWWPath();
}
/**
* Helper function to call Ionic WebView convertFileSrc only in the needed platforms.
* This is needed to make files work with the Ionic WebView plugin.
*
* @param src Source to convert.
* @return Converted src.
*/
convertFileSrc(src: string): string {
return CoreApp.isMobile() ? WebView.convertFileSrc(src) : src;
}
/**
* Undo the conversion of convertFileSrc.
*
* @param src Source to unconvert.
* @return Unconverted src.
*/
unconvertFileSrc(src: string): string {
if (!CoreApp.isMobile()) {
return src;
}
if (CoreApp.isIOS()) {
return src.replace(CoreConstants.CONFIG.ioswebviewscheme + '://localhost/_app_file_', 'file://');
}
return src.replace('http://localhost/_app_file_', 'file://');
}
/**
* Check if a certain path is in the app's folder (basePath).
*
* @param path Path to check.
* @return Whether it's in the app folder.
*/
protected isPathInAppFolder(path: string): boolean {
return !path || !path.match(/^[a-z0-9]+:\/\//i) || path.indexOf(this.basePath) != -1;
}
/**
* Get the file's name.
*
* @param file The file.
* @return The file name.
*/
getFileName(file: CoreFileEntry): string | undefined {
return CoreUtils.isFileEntry(file) ? file.name : file.filename;
}
}
export const CoreFile = makeSingleton(CoreFileProvider);
type MoveCopyFunction = (path: string, dirName: string, newPath: string, newDirName: string) => Promise<FileEntry | DirectoryEntry>; | the_stack |
* @packageDocumentation
* @module geometry
*/
import { EPSILON, Mat3, Vec3, Mat4 } from '../math';
import { AABB } from './aabb';
import { Capsule } from './capsule';
import * as distance from './distance';
import enums from './enums';
import { Frustum } from './frustum';
import { Line } from './line';
import { OBB } from './obb';
import { Plane } from './plane';
import { Ray } from './ray';
import { Sphere } from './sphere';
import { Triangle } from './triangle';
import { PrimitiveMode } from '../gfx';
import { Mesh } from '../../3d/assets/mesh';
import { IBArray, RenderingSubMesh } from '../assets/rendering-sub-mesh';
import { IRaySubMeshOptions, ERaycastMode, IRaySubMeshResult, IRayMeshOptions, IRayModelOptions } from './spec';
import { IVec3Like } from '../math/type-define';
import { scene } from '../renderer';
/**
* @en
* ray-plane intersect detect.
* @zh
* ๅฐ็บฟไธๅนณ้ข็็ธไบคๆงๆฃๆตใ
* @param {Ray} ray ๅฐ็บฟ
* @param {Plane} plane ๅนณ้ข
* @return {number} 0 ๆ ้0
*/
const rayPlane = (function () {
const pt = new Vec3(0, 0, 0);
return function (ray: Ray, plane: Plane): number {
const denom = Vec3.dot(ray.d, plane.n);
if (Math.abs(denom) < Number.EPSILON) { return 0; }
Vec3.multiplyScalar(pt, plane.n, plane.d);
const t = Vec3.dot(Vec3.subtract(pt, pt, ray.o), plane.n) / denom;
if (t < 0) { return 0; }
return t;
};
}());
// based on http://fileadmin.cs.lth.se/cs/Personal/Tomas_Akenine-Moller/raytri/
/**
* @en
* ray-triangle intersect detect.
* @zh
* ๅฐ็บฟไธไธ่งๅฝข็็ธไบคๆงๆฃๆตใ
* @param {Ray} ray ๅฐ็บฟ
* @param {Triangle} triangle ไธ่งๅฝข
* @param {boolean} doubleSided ไธ่งๅฝขๆฏๅฆไธบๅ้ข
* @return {number} 0 ๆ ้0
*/
const rayTriangle = (function () {
const ab = new Vec3(0, 0, 0);
const ac = new Vec3(0, 0, 0);
const pvec = new Vec3(0, 0, 0);
const tvec = new Vec3(0, 0, 0);
const qvec = new Vec3(0, 0, 0);
return function (ray: Ray, triangle: Triangle, doubleSided?: boolean) {
Vec3.subtract(ab, triangle.b, triangle.a);
Vec3.subtract(ac, triangle.c, triangle.a);
Vec3.cross(pvec, ray.d, ac);
const det = Vec3.dot(ab, pvec);
if (det < Number.EPSILON && (!doubleSided || det > -Number.EPSILON)) { return 0; }
const inv_det = 1 / det;
Vec3.subtract(tvec, ray.o, triangle.a);
const u = Vec3.dot(tvec, pvec) * inv_det;
if (u < 0 || u > 1) { return 0; }
Vec3.cross(qvec, tvec, ab);
const v = Vec3.dot(ray.d, qvec) * inv_det;
if (v < 0 || u + v > 1) { return 0; }
const t = Vec3.dot(ac, qvec) * inv_det;
return t < 0 ? 0 : t;
};
}());
/**
* @en
* ray-sphere intersect detect.
* @zh
* ๅฐ็บฟๅ็็็ธไบคๆงๆฃๆตใ
* @param {Ray} ray ๅฐ็บฟ
* @param {Sphere} sphere ็
* @return {number} 0 ๆ ้0
*/
const raySphere = (function () {
const e = new Vec3(0, 0, 0);
return function (ray: Ray, sphere: Sphere): number {
const r = sphere.radius;
const c = sphere.center;
const o = ray.o;
const d = ray.d;
const rSq = r * r;
Vec3.subtract(e, c, o);
const eSq = e.lengthSqr();
const aLength = Vec3.dot(e, d); // assume ray direction already normalized
const fSq = rSq - (eSq - aLength * aLength);
if (fSq < 0) { return 0; }
const f = Math.sqrt(fSq);
const t = eSq < rSq ? aLength + f : aLength - f;
if (t < 0) { return 0; }
return t;
};
}());
/**
* @en
* ray-aabb intersect detect.
* @zh
* ๅฐ็บฟๅ่ฝดๅฏน้ฝๅ
ๅด็็็ธไบคๆงๆฃๆตใ
* @param {Ray} ray ๅฐ็บฟ
* @param {AABB} aabb ่ฝดๅฏน้ฝๅ
ๅด็
* @return {number} 0 ๆ ้0
*/
const rayAABB = (function () {
const min = new Vec3();
const max = new Vec3();
return function (ray: Ray, aabb: AABB): number {
Vec3.subtract(min, aabb.center, aabb.halfExtents);
Vec3.add(max, aabb.center, aabb.halfExtents);
return rayAABB2(ray, min, max);
};
}());
function rayAABB2 (ray: Ray, min: IVec3Like, max: IVec3Like) {
const o = ray.o; const d = ray.d;
const ix = 1 / d.x; const iy = 1 / d.y; const iz = 1 / d.z;
const t1 = (min.x - o.x) * ix;
const t2 = (max.x - o.x) * ix;
const t3 = (min.y - o.y) * iy;
const t4 = (max.y - o.y) * iy;
const t5 = (min.z - o.z) * iz;
const t6 = (max.z - o.z) * iz;
const tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)), Math.min(t5, t6));
const tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)), Math.max(t5, t6));
if (tmax < 0 || tmin > tmax) { return 0; }
return tmin > 0 ? tmin : tmax; // ray origin inside aabb
}
/**
* @en
* ray-obb intersect detect.
* @zh
* ๅฐ็บฟๅๆนๅๅ
ๅด็็็ธไบคๆงๆฃๆตใ
* @param {Ray} ray ๅฐ็บฟ
* @param {OBB} obb ๆนๅๅ
ๅด็
* @return {number} 0 ๆ ้0
*/
const rayOBB = (function () {
let center = new Vec3();
let o = new Vec3();
let d = new Vec3();
const X = new Vec3();
const Y = new Vec3();
const Z = new Vec3();
const p = new Vec3();
const size = new Array<number>(3);
const f = new Array<number>(3);
const e = new Array<number>(3);
const t = new Array<number>(6);
return function (ray: Ray, obb: OBB): number {
size[0] = obb.halfExtents.x;
size[1] = obb.halfExtents.y;
size[2] = obb.halfExtents.z;
center = obb.center;
o = ray.o;
d = ray.d;
Vec3.set(X, obb.orientation.m00, obb.orientation.m01, obb.orientation.m02);
Vec3.set(Y, obb.orientation.m03, obb.orientation.m04, obb.orientation.m05);
Vec3.set(Z, obb.orientation.m06, obb.orientation.m07, obb.orientation.m08);
Vec3.subtract(p, center, o);
// The cos values of the ray on the X, Y, Z
f[0] = Vec3.dot(X, d);
f[1] = Vec3.dot(Y, d);
f[2] = Vec3.dot(Z, d);
// The projection length of P on X, Y, Z
e[0] = Vec3.dot(X, p);
e[1] = Vec3.dot(Y, p);
e[2] = Vec3.dot(Z, p);
for (let i = 0; i < 3; ++i) {
if (f[i] === 0) {
if (-e[i] - size[i] > 0 || -e[i] + size[i] < 0) {
return 0;
}
// Avoid div by 0!
f[i] = 0.0000001;
}
// min
t[i * 2 + 0] = (e[i] + size[i]) / f[i];
// max
t[i * 2 + 1] = (e[i] - size[i]) / f[i];
}
const tmin = Math.max(
Math.max(
Math.min(t[0], t[1]),
Math.min(t[2], t[3]),
),
Math.min(t[4], t[5]),
);
const tmax = Math.min(
Math.min(
Math.max(t[0], t[1]),
Math.max(t[2], t[3]),
),
Math.max(t[4], t[5]),
);
if (tmax < 0 || tmin > tmax) {
return 0;
}
return tmin > 0 ? tmin : tmax; // ray origin inside aabb
};
}());
/**
* @en
* ray-capsule intersect detect.
* @zh
* ๅฐ็บฟๅ่ถๅไฝ็็ธไบคๆงๆฃๆตใ
* @param {Ray} ray ๅฐ็บฟ
* @param {Capsule} capsule ่ถๅไฝ
* @return {number} 0 ๆ ้0
*/
const rayCapsule = (function () {
const v3_0 = new Vec3();
const v3_1 = new Vec3();
const v3_2 = new Vec3();
const v3_3 = new Vec3();
const v3_4 = new Vec3();
const v3_5 = new Vec3();
const v3_6 = new Vec3();
const sphere_0 = new Sphere();
return function (ray: Ray, capsule: Capsule) {
const radiusSqr = capsule.radius * capsule.radius;
const vRayNorm = Vec3.normalize(v3_0, ray.d);
const A = capsule.ellipseCenter0;
const B = capsule.ellipseCenter1;
const BA = Vec3.subtract(v3_1, B, A);
if (BA.equals(Vec3.ZERO)) {
sphere_0.radius = capsule.radius;
sphere_0.center.set(capsule.ellipseCenter0);
return intersect.raySphere(ray, sphere_0);
}
const O = ray.o;
const OA = Vec3.subtract(v3_2, O, A);
const VxBA = Vec3.cross(v3_3, vRayNorm, BA);
const a = VxBA.lengthSqr();
if (a === 0) {
sphere_0.radius = capsule.radius;
const BO = Vec3.subtract(v3_4, B, O);
if (OA.lengthSqr() < BO.lengthSqr()) {
sphere_0.center.set(capsule.ellipseCenter0);
} else {
sphere_0.center.set(capsule.ellipseCenter1);
}
return intersect.raySphere(ray, sphere_0);
}
const OAxBA = Vec3.cross(v3_4, OA, BA);
const ab2 = BA.lengthSqr();
const b = 2 * Vec3.dot(VxBA, OAxBA);
const c = OAxBA.lengthSqr() - (radiusSqr * ab2);
const d = b * b - 4 * a * c;
if (d < 0) { return 0; }
const t = (-b - Math.sqrt(d)) / (2 * a);
if (t < 0) {
sphere_0.radius = capsule.radius;
const BO = Vec3.subtract(v3_5, B, O);
if (OA.lengthSqr() < BO.lengthSqr()) {
sphere_0.center.set(capsule.ellipseCenter0);
} else {
sphere_0.center.set(capsule.ellipseCenter1);
}
return intersect.raySphere(ray, sphere_0);
} else {
// Limit intersection between the bounds of the cylinder's end caps.
const iPos = Vec3.scaleAndAdd(v3_5, ray.o, vRayNorm, t);
const iPosLen = Vec3.subtract(v3_6, iPos, A);
const tLimit = Vec3.dot(iPosLen, BA) / ab2;
if (tLimit >= 0 && tLimit <= 1) {
return t;
} else if (tLimit < 0) {
sphere_0.radius = capsule.radius;
sphere_0.center.set(capsule.ellipseCenter0);
return intersect.raySphere(ray, sphere_0);
} else if (tLimit > 1) {
sphere_0.radius = capsule.radius;
sphere_0.center.set(capsule.ellipseCenter1);
return intersect.raySphere(ray, sphere_0);
} else {
return 0;
}
}
};
}());
/**
* @en
* ray-subMesh intersect detect, in model space.
* @zh
* ๅจๆจกๅ็ฉบ้ดไธญ๏ผๅฐ็บฟๅๅญไธ่ง็ฝๆ ผ็็ธไบคๆงๆฃๆตใ
* @param {Ray} ray
* @param {RenderingSubMesh} subMesh
* @param {IRaySubMeshOptions} options
* @return {number} 0 or !0
*/
const raySubMesh = (function () {
const tri = Triangle.create();
const deOpt: IRaySubMeshOptions = { distance: Infinity, doubleSided: false, mode: ERaycastMode.ANY };
let minDis = 0;
const fillResult = (m: ERaycastMode, d: number, i0: number, i1: number, i2: number, r?: IRaySubMeshResult[]) => {
if (m === ERaycastMode.CLOSEST) {
if (minDis > d || minDis === 0) {
minDis = d;
if (r) {
if (r.length === 0) {
r.push({ distance: d, vertexIndex0: i0 / 3, vertexIndex1: i1 / 3, vertexIndex2: i2 / 3 });
} else {
r[0].distance = d; r[0].vertexIndex0 = i0 / 3; r[0].vertexIndex1 = i1 / 3; r[0].vertexIndex2 = i2 / 3;
}
}
}
} else {
minDis = d;
if (r) r.push({ distance: d, vertexIndex0: i0 / 3, vertexIndex1: i1 / 3, vertexIndex2: i2 / 3 });
}
};
const narrowphase = (vb: Float32Array, ib: IBArray, pm: PrimitiveMode, ray: Ray, opt: IRaySubMeshOptions) => {
if (pm === PrimitiveMode.TRIANGLE_LIST) {
const cnt = ib.length;
for (let j = 0; j < cnt; j += 3) {
const i0 = ib[j] * 3;
const i1 = ib[j + 1] * 3;
const i2 = ib[j + 2] * 3;
Vec3.set(tri.a, vb[i0], vb[i0 + 1], vb[i0 + 2]);
Vec3.set(tri.b, vb[i1], vb[i1 + 1], vb[i1 + 2]);
Vec3.set(tri.c, vb[i2], vb[i2 + 1], vb[i2 + 2]);
const dist = intersect.rayTriangle(ray, tri, opt.doubleSided);
if (dist === 0 || dist > opt.distance) continue;
fillResult(opt.mode, dist, i0, i1, i2, opt.result);
if (opt.mode === ERaycastMode.ANY) return dist;
}
} else if (pm === PrimitiveMode.TRIANGLE_STRIP) {
const cnt = ib.length - 2;
let rev = 0;
for (let j = 0; j < cnt; j += 1) {
const i0 = ib[j - rev] * 3;
const i1 = ib[j + rev + 1] * 3;
const i2 = ib[j + 2] * 3;
Vec3.set(tri.a, vb[i0], vb[i0 + 1], vb[i0 + 2]);
Vec3.set(tri.b, vb[i1], vb[i1 + 1], vb[i1 + 2]);
Vec3.set(tri.c, vb[i2], vb[i2 + 1], vb[i2 + 2]);
rev = ~rev;
const dist = intersect.rayTriangle(ray, tri, opt.doubleSided);
if (dist === 0 || dist > opt.distance) continue;
fillResult(opt.mode, dist, i0, i1, i2, opt.result);
if (opt.mode === ERaycastMode.ANY) return dist;
}
} else if (pm === PrimitiveMode.TRIANGLE_FAN) {
const cnt = ib.length - 1;
const i0 = ib[0] * 3;
Vec3.set(tri.a, vb[i0], vb[i0 + 1], vb[i0 + 2]);
for (let j = 1; j < cnt; j += 1) {
const i1 = ib[j] * 3;
const i2 = ib[j + 1] * 3;
Vec3.set(tri.b, vb[i1], vb[i1 + 1], vb[i1 + 2]);
Vec3.set(tri.c, vb[i2], vb[i2 + 1], vb[i2 + 2]);
const dist = intersect.rayTriangle(ray, tri, opt.doubleSided);
if (dist === 0 || dist > opt.distance) continue;
fillResult(opt.mode, dist, i0, i1, i2, opt.result);
if (opt.mode === ERaycastMode.ANY) return dist;
}
}
return minDis;
};
return function (ray: Ray, submesh: RenderingSubMesh, options?: IRaySubMeshOptions) {
minDis = 0;
if (submesh.geometricInfo.positions.length === 0) return minDis;
const opt = options === undefined ? deOpt : options;
const min = submesh.geometricInfo.boundingBox.min;
const max = submesh.geometricInfo.boundingBox.max;
if (rayAABB2(ray, min, max)) {
const pm = submesh.primitiveMode;
const { positions: vb, indices: ib } = submesh.geometricInfo;
narrowphase(vb, ib!, pm, ray, opt);
}
return minDis;
};
}());
/**
* @en
* ray-mesh intersect detect, in model space.
* @zh
* ๅจๆจกๅ็ฉบ้ดไธญ๏ผๅฐ็บฟๅไธ่ง็ฝๆ ผ่ตๆบ็็ธไบคๆงๆฃๆตใ
* @param {Ray} ray
* @param {Mesh} mesh
* @param {IRayMeshOptions} options
* @return {number} 0 or !0
*/
const rayMesh = (function () {
let minDis = 0;
const deOpt: IRayMeshOptions = { distance: Infinity, doubleSided: false, mode: ERaycastMode.ANY };
return function (ray: Ray, mesh: Mesh, options?: IRayMeshOptions) {
minDis = 0;
const opt = options === undefined ? deOpt : options;
const length = mesh.renderingSubMeshes.length;
const min = mesh.struct.minPosition;
const max = mesh.struct.maxPosition;
if (min && max && !rayAABB2(ray, min, max)) return minDis;
for (let i = 0; i < length; i++) {
const sm = mesh.renderingSubMeshes[i];
const dis = raySubMesh(ray, sm, opt);
if (dis) {
if (opt.mode === ERaycastMode.CLOSEST) {
if (minDis === 0 || minDis > dis) {
minDis = dis;
if (opt.subIndices) opt.subIndices[0] = i;
}
} else {
minDis = dis;
if (opt.subIndices) opt.subIndices.push(i);
if (opt.mode === ERaycastMode.ANY) {
return dis;
}
}
}
}
if (minDis && opt.mode === ERaycastMode.CLOSEST) {
if (opt.result) {
opt.result[0].distance = minDis;
opt.result.length = 1;
}
if (opt.subIndices) opt.subIndices.length = 1;
}
return minDis;
};
}());
/**
* @en
* ray-model intersect detect, in world space.
* @zh
* ๅจไธ็็ฉบ้ดไธญ๏ผๅฐ็บฟๅๆธฒๆๆจกๅ็็ธไบคๆงๆฃๆตใ
* @param ray
* @param model
* @param options
* @return 0 or !0
*/
const rayModel = (function () {
let minDis = 0;
const deOpt: IRayModelOptions = { distance: Infinity, doubleSided: false, mode: ERaycastMode.ANY };
const modelRay = new Ray();
const m4 = new Mat4();
return function (r: Ray, model: scene.Model, options?: IRayModelOptions) {
minDis = 0;
const opt = options === undefined ? deOpt : options;
const wb = model.worldBounds;
if (wb && !rayAABB(r, wb)) return minDis;
Ray.copy(modelRay, r);
if (model.node) {
Mat4.invert(m4, model.node.getWorldMatrix(m4));
Vec3.transformMat4(modelRay.o, r.o, m4);
Vec3.transformMat4Normal(modelRay.d, r.d, m4);
}
const subModels = model.subModels;
for (let i = 0; i < subModels.length; i++) {
const subMesh = subModels[i].subMesh;
const dis = raySubMesh(modelRay, subMesh, opt);
if (dis) {
if (opt.mode === ERaycastMode.CLOSEST) {
if (minDis === 0 || minDis > dis) {
minDis = dis;
if (opt.subIndices) opt.subIndices[0] = i;
}
} else {
minDis = dis;
if (opt.subIndices) opt.subIndices.push(i);
if (opt.mode === ERaycastMode.ANY) {
return dis;
}
}
}
}
if (minDis && opt.mode === ERaycastMode.CLOSEST) {
if (opt.result) {
opt.result[0].distance = minDis;
opt.result.length = 1;
}
if (opt.subIndices) opt.subIndices.length = 1;
}
return minDis;
};
}());
/**
* @en
* line-plane intersect detect.
* @zh
* ็บฟๆฎตไธๅนณ้ข็็ธไบคๆงๆฃๆตใ
* @param {line} line ็บฟๆฎต
* @param {Plane} plane ๅนณ้ข
* @return {number} 0 ๆ ้0
*/
const linePlane = (function () {
const ab = new Vec3(0, 0, 0);
return function (line: Line, plane: Plane): number {
Vec3.subtract(ab, line.e, line.s);
const t = (plane.d - Vec3.dot(line.s, plane.n)) / Vec3.dot(ab, plane.n);
if (t < 0 || t > 1) { return 0; }
return t;
};
}());
/**
* @en
* line-triangle intersect detect.
* @zh
* ็บฟๆฎตไธไธ่งๅฝข็็ธไบคๆงๆฃๆตใ
* @param {line} line ็บฟๆฎต
* @param {Triangle} triangle ไธ่งๅฝข
* @param {Vec3} outPt ๅฏ้๏ผ็ธไบค็น
* @return {number} 0 ๆ ้0
*/
const lineTriangle = (function () {
const ab = new Vec3(0, 0, 0);
const ac = new Vec3(0, 0, 0);
const qp = new Vec3(0, 0, 0);
const ap = new Vec3(0, 0, 0);
const n = new Vec3(0, 0, 0);
const e = new Vec3(0, 0, 0);
return function (line: Line, triangle: Triangle, outPt?: Vec3): number {
Vec3.subtract(ab, triangle.b, triangle.a);
Vec3.subtract(ac, triangle.c, triangle.a);
Vec3.subtract(qp, line.s, line.e);
Vec3.cross(n, ab, ac);
const det = Vec3.dot(qp, n);
if (det <= 0.0) {
return 0;
}
Vec3.subtract(ap, line.s, triangle.a);
const t = Vec3.dot(ap, n);
if (t < 0 || t > det) {
return 0;
}
Vec3.cross(e, qp, ap);
let v = Vec3.dot(ac, e);
if (v < 0 || v > det) {
return 0;
}
let w = -Vec3.dot(ab, e);
if (w < 0.0 || v + w > det) {
return 0;
}
if (outPt) {
const invDet = 1.0 / det;
v *= invDet;
w *= invDet;
const u = 1.0 - v - w;
// outPt = u*a + v*d + w*c;
Vec3.set(outPt,
triangle.a.x * u + triangle.b.x * v + triangle.c.x * w,
triangle.a.y * u + triangle.b.y * v + triangle.c.y * w,
triangle.a.z * u + triangle.b.z * v + triangle.c.z * w);
}
return 1;
};
}());
const r_t = new Ray();
/**
* @en
* line-aabb intersect detect.
* @zh
* ็บฟๆฎตไธ่ฝดๅฏน้ฝๅ
ๅด็็็ธไบคๆงๆฃๆต
* @param line ็บฟๆฎต
* @param aabb ่ฝดๅฏน้ฝๅ
ๅด็
* @return {number} 0 ๆ ้0
*/
function lineAABB (line: Line, aabb: AABB): number {
r_t.o.set(line.s);
Vec3.subtract(r_t.d, line.e, line.s);
r_t.d.normalize();
const min = rayAABB(r_t, aabb);
const len = line.length();
if (min <= len) {
return min;
} else {
return 0;
}
}
/**
* @en
* line-obb intersect detect.
* @zh
* ็บฟๆฎตไธๆนๅๅ
ๅด็็็ธไบคๆงๆฃๆต
* @param line ็บฟๆฎต
* @param obb ๆนๅๅ
ๅด็
* @return {number} 0 ๆ ้0
*/
function lineOBB (line: Line, obb: OBB): number {
r_t.o.set(line.s);
Vec3.subtract(r_t.d, line.e, line.s);
r_t.d.normalize();
const min = rayOBB(r_t, obb);
const len = line.length();
if (min <= len) {
return min;
} else {
return 0;
}
}
/**
* @en
* line-sphere intersect detect.
* @zh
* ็บฟๆฎตไธ็็็ธไบคๆงๆฃๆต
* @param line ็บฟๆฎต
* @param sphere ็
* @return {number} 0 ๆ ้0
*/
function lineSphere (line: Line, sphere: Sphere): number {
r_t.o.set(line.s);
Vec3.subtract(r_t.d, line.e, line.s);
r_t.d.normalize();
const min = raySphere(r_t, sphere);
const len = line.length();
if (min <= len) {
return min;
} else {
return 0;
}
}
/**
* @en
* aabb-aabb intersect detect.
* @zh
* ่ฝดๅฏน้ฝๅ
ๅด็ๅ่ฝดๅฏน้ฝๅ
ๅด็็็ธไบคๆงๆฃๆตใ
* @param {AABB} aabb1 ่ฝดๅฏน้ฝๅ
ๅด็1
* @param {AABB} aabb2 ่ฝดๅฏน้ฝๅ
ๅด็2
* @return {number} 0 ๆ ้0
*/
const aabbWithAABB = (function () {
const aMin = new Vec3();
const aMax = new Vec3();
const bMin = new Vec3();
const bMax = new Vec3();
return function (aabb1: AABB, aabb2: AABB) {
Vec3.subtract(aMin, aabb1.center, aabb1.halfExtents);
Vec3.add(aMax, aabb1.center, aabb1.halfExtents);
Vec3.subtract(bMin, aabb2.center, aabb2.halfExtents);
Vec3.add(bMax, aabb2.center, aabb2.halfExtents);
return (aMin.x <= bMax.x && aMax.x >= bMin.x)
&& (aMin.y <= bMax.y && aMax.y >= bMin.y)
&& (aMin.z <= bMax.z && aMax.z >= bMin.z);
};
}());
function getAABBVertices (min: Vec3, max: Vec3, out: Vec3[]) {
Vec3.set(out[0], min.x, max.y, max.z);
Vec3.set(out[1], min.x, max.y, min.z);
Vec3.set(out[2], min.x, min.y, max.z);
Vec3.set(out[3], min.x, min.y, min.z);
Vec3.set(out[4], max.x, max.y, max.z);
Vec3.set(out[5], max.x, max.y, min.z);
Vec3.set(out[6], max.x, min.y, max.z);
Vec3.set(out[7], max.x, min.y, min.z);
}
function getOBBVertices (c: Vec3, e: Vec3, a1: Vec3, a2: Vec3, a3: Vec3, out: Vec3[]) {
Vec3.set(out[0],
c.x + a1.x * e.x + a2.x * e.y + a3.x * e.z,
c.y + a1.y * e.x + a2.y * e.y + a3.y * e.z,
c.z + a1.z * e.x + a2.z * e.y + a3.z * e.z);
Vec3.set(out[1],
c.x - a1.x * e.x + a2.x * e.y + a3.x * e.z,
c.y - a1.y * e.x + a2.y * e.y + a3.y * e.z,
c.z - a1.z * e.x + a2.z * e.y + a3.z * e.z);
Vec3.set(out[2],
c.x + a1.x * e.x - a2.x * e.y + a3.x * e.z,
c.y + a1.y * e.x - a2.y * e.y + a3.y * e.z,
c.z + a1.z * e.x - a2.z * e.y + a3.z * e.z);
Vec3.set(out[3],
c.x + a1.x * e.x + a2.x * e.y - a3.x * e.z,
c.y + a1.y * e.x + a2.y * e.y - a3.y * e.z,
c.z + a1.z * e.x + a2.z * e.y - a3.z * e.z);
Vec3.set(out[4],
c.x - a1.x * e.x - a2.x * e.y - a3.x * e.z,
c.y - a1.y * e.x - a2.y * e.y - a3.y * e.z,
c.z - a1.z * e.x - a2.z * e.y - a3.z * e.z);
Vec3.set(out[5],
c.x + a1.x * e.x - a2.x * e.y - a3.x * e.z,
c.y + a1.y * e.x - a2.y * e.y - a3.y * e.z,
c.z + a1.z * e.x - a2.z * e.y - a3.z * e.z);
Vec3.set(out[6],
c.x - a1.x * e.x + a2.x * e.y - a3.x * e.z,
c.y - a1.y * e.x + a2.y * e.y - a3.y * e.z,
c.z - a1.z * e.x + a2.z * e.y - a3.z * e.z);
Vec3.set(out[7],
c.x - a1.x * e.x - a2.x * e.y + a3.x * e.z,
c.y - a1.y * e.x - a2.y * e.y + a3.y * e.z,
c.z - a1.z * e.x - a2.z * e.y + a3.z * e.z);
}
function getInterval (vertices: any[] | Vec3[], axis: Vec3) {
let min = Vec3.dot(axis, vertices[0]); let max = min;
for (let i = 1; i < 8; ++i) {
const projection = Vec3.dot(axis, vertices[i]);
min = (projection < min) ? projection : min;
max = (projection > max) ? projection : max;
}
return [min, max];
}
/**
* @en
* aabb-obb intersect detect.
* @zh
* ่ฝดๅฏน้ฝๅ
ๅด็ๅๆนๅๅ
ๅด็็็ธไบคๆงๆฃๆตใ
* @param {AABB} aabb ่ฝดๅฏน้ฝๅ
ๅด็
* @param {OBB} obb ๆนๅๅ
ๅด็
* @return {number} 0 ๆ ้0
*/
const aabbWithOBB = (function () {
const test = new Array(15);
for (let i = 0; i < 15; i++) {
test[i] = new Vec3(0, 0, 0);
}
const vertices = new Array(8);
const vertices2 = new Array(8);
for (let i = 0; i < 8; i++) {
vertices[i] = new Vec3(0, 0, 0);
vertices2[i] = new Vec3(0, 0, 0);
}
const min = new Vec3();
const max = new Vec3();
return function (aabb: AABB, obb: OBB): number {
Vec3.set(test[0], 1, 0, 0);
Vec3.set(test[1], 0, 1, 0);
Vec3.set(test[2], 0, 0, 1);
Vec3.set(test[3], obb.orientation.m00, obb.orientation.m01, obb.orientation.m02);
Vec3.set(test[4], obb.orientation.m03, obb.orientation.m04, obb.orientation.m05);
Vec3.set(test[5], obb.orientation.m06, obb.orientation.m07, obb.orientation.m08);
for (let i = 0; i < 3; ++i) { // Fill out rest of axis
Vec3.cross(test[6 + i * 3 + 0], test[i], test[3]);
Vec3.cross(test[6 + i * 3 + 1], test[i], test[4]);
Vec3.cross(test[6 + i * 3 + 1], test[i], test[5]);
}
Vec3.subtract(min, aabb.center, aabb.halfExtents);
Vec3.add(max, aabb.center, aabb.halfExtents);
getAABBVertices(min, max, vertices);
getOBBVertices(obb.center, obb.halfExtents, test[3], test[4], test[5], vertices2);
for (let j = 0; j < 15; ++j) {
const a = getInterval(vertices, test[j]);
const b = getInterval(vertices2, test[j]);
if (b[0] > a[1] || a[0] > b[1]) {
return 0; // Seperating axis found
}
}
return 1;
};
}());
/**
* @en
* aabb-plane intersect detect.
* @zh
* ่ฝดๅฏน้ฝๅ
ๅด็ๅๅนณ้ข็็ธไบคๆงๆฃๆตใ
* @param {AABB} aabb ่ฝดๅฏน้ฝๅ
ๅด็
* @param {Plane} plane ๅนณ้ข
* @return {number} inside(back) = -1, outside(front) = 0, intersect = 1
*/
const aabbPlane = function (aabb: AABB, plane: Plane): number {
const r = aabb.halfExtents.x * Math.abs(plane.n.x)
+ aabb.halfExtents.y * Math.abs(plane.n.y)
+ aabb.halfExtents.z * Math.abs(plane.n.z);
const dot = Vec3.dot(plane.n, aabb.center);
if (dot + r < plane.d) { return -1; } else if (dot - r > plane.d) { return 0; }
return 1;
};
/**
* @en
* aabb-frustum intersect detect, faster but has false positive corner cases.
* @zh
* ่ฝดๅฏน้ฝๅ
ๅด็ๅ้ฅๅฐ็ธไบคๆงๆฃๆต๏ผ้ๅบฆๅฟซ๏ผไฝๆ้่ฏฏๆ
ๅตใ
* @param {AABB} aabb ่ฝดๅฏน้ฝๅ
ๅด็
* @param {Frustum} frustum ้ฅๅฐ
* @return {number} 0 ๆ ้0
*/
const aabbFrustum = function (aabb: AABB, frustum: Frustum): number {
for (let i = 0; i < frustum.planes.length; i++) {
// frustum plane normal points to the inside
if (aabbPlane(aabb, frustum.planes[i]) === -1) {
return 0;
}
} // completely outside
return 1;
};
// https://cesium.com/blog/2017/02/02/tighter-frustum-culling-and-why-you-may-want-to-disregard-it/
/**
* @en
* aabb-frustum intersect, handles most of the false positives correctly.
* @zh
* ่ฝดๅฏน้ฝๅ
ๅด็ๅ้ฅๅฐ็ธไบคๆงๆฃๆต๏ผๆญฃ็กฎๅค็ๅคงๅคๆฐ้่ฏฏๆ
ๅตใ
* @param {AABB} aabb ่ฝดๅฏน้ฝๅ
ๅด็
* @param {Frustum} frustum ้ฅๅฐ
* @return {number}
*/
const aabbFrustumAccurate = (function () {
const tmp = new Array(8);
let out1 = 0; let out2 = 0;
for (let i = 0; i < tmp.length; i++) {
tmp[i] = new Vec3(0, 0, 0);
}
return function (aabb: AABB, frustum: Frustum): number {
let result = 0; let intersects = false;
// 1. aabb inside/outside frustum test
for (let i = 0; i < frustum.planes.length; i++) {
result = aabbPlane(aabb, frustum.planes[i]);
// frustum plane normal points to the inside
if (result === -1) return 0; // completely outside
else if (result === 1) { intersects = true; }
}
if (!intersects) { return 1; } // completely inside
// in case of false positives
// 2. frustum inside/outside aabb test
for (let i = 0; i < frustum.vertices.length; i++) {
Vec3.subtract(tmp[i], frustum.vertices[i], aabb.center);
}
out1 = 0, out2 = 0;
for (let i = 0; i < frustum.vertices.length; i++) {
if (tmp[i].x > aabb.halfExtents.x) { out1++; } else if (tmp[i].x < -aabb.halfExtents.x) { out2++; }
}
if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) { return 0; }
out1 = 0; out2 = 0;
for (let i = 0; i < frustum.vertices.length; i++) {
if (tmp[i].y > aabb.halfExtents.y) { out1++; } else if (tmp[i].y < -aabb.halfExtents.y) { out2++; }
}
if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) { return 0; }
out1 = 0; out2 = 0;
for (let i = 0; i < frustum.vertices.length; i++) {
if (tmp[i].z > aabb.halfExtents.z) { out1++; } else if (tmp[i].z < -aabb.halfExtents.z) { out2++; }
}
if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) { return 0; }
return 1;
};
}());
/**
* @en
* obb contains the point.
* @zh
* ๆนๅๅ
ๅด็ๅ็น็็ธไบคๆงๆฃๆตใ
* @param {OBB} obb ๆนๅๅ
ๅด็
* @param {Vec3} point ็น
* @return {boolean} true or false
*/
const obbPoint = (function () {
const tmp = new Vec3(0, 0, 0); const m3 = new Mat3();
const lessThan = function (a: Vec3, b: Vec3): boolean { return Math.abs(a.x) < b.x && Math.abs(a.y) < b.y && Math.abs(a.z) < b.z; };
return function (obb: OBB, point: Vec3): boolean {
Vec3.subtract(tmp, point, obb.center);
Vec3.transformMat3(tmp, tmp, Mat3.transpose(m3, obb.orientation));
return lessThan(tmp, obb.halfExtents);
};
}());
/**
* @en
* obb-plane intersect detect.
* @zh
* ๆนๅๅ
ๅด็ๅๅนณ้ข็็ธไบคๆงๆฃๆตใ
* @param {OBB} obb ๆนๅๅ
ๅด็
* @param {Plane} plane ๅนณ้ข
* @return {number} inside(back) = -1, outside(front) = 0, intersect = 1
*/
const obbPlane = (function () {
const absDot = function (n: Vec3, x: number, y: number, z: number) {
return Math.abs(n.x * x + n.y * y + n.z * z);
};
return function (obb: OBB, plane: Plane): number {
// Real-Time Collision Detection, Christer Ericson, p. 163.
const r = obb.halfExtents.x * absDot(plane.n, obb.orientation.m00, obb.orientation.m01, obb.orientation.m02)
+ obb.halfExtents.y * absDot(plane.n, obb.orientation.m03, obb.orientation.m04, obb.orientation.m05)
+ obb.halfExtents.z * absDot(plane.n, obb.orientation.m06, obb.orientation.m07, obb.orientation.m08);
const dot = Vec3.dot(plane.n, obb.center);
if (dot + r < plane.d) { return -1; } else if (dot - r > plane.d) { return 0; }
return 1;
};
}());
/**
* @en
* obb-frustum intersect, faster but has false positive corner cases.
* @zh
* ๆนๅๅ
ๅด็ๅ้ฅๅฐ็ธไบคๆงๆฃๆต๏ผ้ๅบฆๅฟซ๏ผไฝๆ้่ฏฏๆ
ๅตใ
* @param {OBB} obb ๆนๅๅ
ๅด็
* @param {Frustum} frustum ้ฅๅฐ
* @return {number} 0 ๆ ้0
*/
const obbFrustum = function (obb: OBB, frustum: Frustum): number {
for (let i = 0; i < frustum.planes.length; i++) {
// frustum plane normal points to the inside
if (obbPlane(obb, frustum.planes[i]) === -1) {
return 0;
}
} // completely outside
return 1;
};
// https://cesium.com/blog/2017/02/02/tighter-frustum-culling-and-why-you-may-want-to-disregard-it/
/**
* @en
* obb-frustum intersect, handles most of the false positives correctly.
* @zh
* ๆนๅๅ
ๅด็ๅ้ฅๅฐ็ธไบคๆงๆฃๆต๏ผๆญฃ็กฎๅค็ๅคงๅคๆฐ้่ฏฏๆ
ๅตใ
* @param {OBB} obb ๆนๅๅ
ๅด็
* @param {Frustum} frustum ้ฅๅฐ
* @return {number} 0 ๆ ้0
*/
const obbFrustumAccurate = (function () {
const tmp = new Array(8);
let dist = 0; let out1 = 0; let out2 = 0;
for (let i = 0; i < tmp.length; i++) {
tmp[i] = new Vec3(0, 0, 0);
}
const dot = function (n: Vec3, x: number, y: number, z: number): number {
return n.x * x + n.y * y + n.z * z;
};
return function (obb: OBB, frustum: Frustum): number {
let result = 0; let intersects = false;
// 1. obb inside/outside frustum test
for (let i = 0; i < frustum.planes.length; i++) {
result = obbPlane(obb, frustum.planes[i]);
// frustum plane normal points to the inside
if (result === -1) return 0; // completely outside
else if (result === 1) { intersects = true; }
}
if (!intersects) { return 1; } // completely inside
// in case of false positives
// 2. frustum inside/outside obb test
for (let i = 0; i < frustum.vertices.length; i++) {
Vec3.subtract(tmp[i], frustum.vertices[i], obb.center);
}
out1 = 0, out2 = 0;
for (let i = 0; i < frustum.vertices.length; i++) {
dist = dot(tmp[i], obb.orientation.m00, obb.orientation.m01, obb.orientation.m02);
if (dist > obb.halfExtents.x) { out1++; } else if (dist < -obb.halfExtents.x) { out2++; }
}
if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) { return 0; }
out1 = 0; out2 = 0;
for (let i = 0; i < frustum.vertices.length; i++) {
dist = dot(tmp[i], obb.orientation.m03, obb.orientation.m04, obb.orientation.m05);
if (dist > obb.halfExtents.y) { out1++; } else if (dist < -obb.halfExtents.y) { out2++; }
}
if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) { return 0; }
out1 = 0; out2 = 0;
for (let i = 0; i < frustum.vertices.length; i++) {
dist = dot(tmp[i], obb.orientation.m06, obb.orientation.m07, obb.orientation.m08);
if (dist > obb.halfExtents.z) { out1++; } else if (dist < -obb.halfExtents.z) { out2++; }
}
if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) { return 0; }
return 1;
};
}());
/**
* @en
* obb-obb intersect detect.
* @zh
* ๆนๅๅ
ๅด็ๅๆนๅๅ
ๅด็็็ธไบคๆงๆฃๆตใ
* @param {OBB} obb1 ๆนๅๅ
ๅด็1
* @param {OBB} obb2 ๆนๅๅ
ๅด็2
* @return {number} 0 ๆ ้0
*/
const obbWithOBB = (function () {
const test = new Array(15);
for (let i = 0; i < 15; i++) {
test[i] = new Vec3(0, 0, 0);
}
const vertices = new Array(8);
const vertices2 = new Array(8);
for (let i = 0; i < 8; i++) {
vertices[i] = new Vec3(0, 0, 0);
vertices2[i] = new Vec3(0, 0, 0);
}
return function (obb1: OBB, obb2: OBB): number {
Vec3.set(test[0], obb1.orientation.m00, obb1.orientation.m01, obb1.orientation.m02);
Vec3.set(test[1], obb1.orientation.m03, obb1.orientation.m04, obb1.orientation.m05);
Vec3.set(test[2], obb1.orientation.m06, obb1.orientation.m07, obb1.orientation.m08);
Vec3.set(test[3], obb2.orientation.m00, obb2.orientation.m01, obb2.orientation.m02);
Vec3.set(test[4], obb2.orientation.m03, obb2.orientation.m04, obb2.orientation.m05);
Vec3.set(test[5], obb2.orientation.m06, obb2.orientation.m07, obb2.orientation.m08);
for (let i = 0; i < 3; ++i) { // Fill out rest of axis
Vec3.cross(test[6 + i * 3 + 0], test[i], test[3]);
Vec3.cross(test[6 + i * 3 + 1], test[i], test[4]);
Vec3.cross(test[6 + i * 3 + 2], test[i], test[5]);
}
getOBBVertices(obb1.center, obb1.halfExtents, test[0], test[1], test[2], vertices);
getOBBVertices(obb2.center, obb2.halfExtents, test[3], test[4], test[5], vertices2);
for (let i = 0; i < 15; ++i) {
const a = getInterval(vertices, test[i]);
const b = getInterval(vertices2, test[i]);
if (b[0] > a[1] || a[0] > b[1]) {
return 0; // Seperating axis found
}
}
return 1;
};
}());
// https://github.com/diku-dk/bvh-tvcg18/blob/1fd3348c17bc8cf3da0b4ae60fdb8f2aa90a6ff0/FOUNDATION/GEOMETRY/GEOMETRY/include/overlap/geometry_overlap_obb_capsule.h
/**
* @en
* obb-capsule intersect detect.
* @zh
* ๆนๅๅ
ๅด็ๅ่ถๅไฝ็็ธไบคๆงๆฃๆตใ
* @param obb ๆนๅๅ
ๅด็
* @param capsule ่ถๅไฝ
*/
const obbCapsule = (function () {
const sphere_0 = new Sphere();
const v3_0 = new Vec3();
const v3_1 = new Vec3();
const v3_2 = new Vec3();
const v3_verts8 = new Array<Vec3>(8);
for (let i = 0; i < 8; i++) { v3_verts8[i] = new Vec3(); }
const v3_axis8 = new Array<Vec3>(8);
for (let i = 0; i < 8; i++) { v3_axis8[i] = new Vec3(); }
return function (obb: OBB, capsule: Capsule) {
const h = Vec3.squaredDistance(capsule.ellipseCenter0, capsule.ellipseCenter1);
if (h === 0) {
sphere_0.radius = capsule.radius;
sphere_0.center.set(capsule.ellipseCenter0);
return intersect.sphereOBB(sphere_0, obb);
} else {
v3_0.x = obb.orientation.m00;
v3_0.y = obb.orientation.m01;
v3_0.z = obb.orientation.m02;
v3_1.x = obb.orientation.m03;
v3_1.y = obb.orientation.m04;
v3_1.z = obb.orientation.m05;
v3_2.x = obb.orientation.m06;
v3_2.y = obb.orientation.m07;
v3_2.z = obb.orientation.m08;
getOBBVertices(obb.center, obb.halfExtents, v3_0, v3_1, v3_2, v3_verts8);
const axes = v3_axis8;
const a0 = Vec3.copy(axes[0], v3_0);
const a1 = Vec3.copy(axes[1], v3_1);
const a2 = Vec3.copy(axes[2], v3_2);
const C = Vec3.subtract(axes[3], capsule.center, obb.center);
C.normalize();
const B = Vec3.subtract(axes[4], capsule.ellipseCenter0, capsule.ellipseCenter1);
B.normalize();
Vec3.cross(axes[5], a0, B);
Vec3.cross(axes[6], a1, B);
Vec3.cross(axes[7], a2, B);
for (let i = 0; i < 8; ++i) {
const a = getInterval(v3_verts8, axes[i]);
const d0 = Vec3.dot(axes[i], capsule.ellipseCenter0);
const d1 = Vec3.dot(axes[i], capsule.ellipseCenter1);
const max_d = Math.max(d0, d1);
const min_d = Math.min(d0, d1);
const d_min = min_d - capsule.radius;
const d_max = max_d + capsule.radius;
if (d_min > a[1] || a[0] > d_max) {
return 0; // Seperating axis found
}
}
return 1;
}
};
}());
/**
* @en
* sphere-plane intersect, not necessarily faster than obb-plane,due to the length calculation of the
* plane normal to factor out the unnomalized plane distance.
* @zh
* ็ไธๅนณ้ข็็ธไบคๆงๆฃๆตใ
* @param {Sphere} sphere ็
* @param {Plane} plane ๅนณ้ข
* @return {number} inside(back) = -1, outside(front) = 0, intersect = 1
*/
const spherePlane = function (sphere: Sphere, plane: Plane): number {
const dot = Vec3.dot(plane.n, sphere.center);
const r = sphere.radius * plane.n.length();
if (dot + r < plane.d) { return -1; } else if (dot - r > plane.d) { return 0; }
return 1;
};
/**
* @en
* sphere-frustum intersect, faster but has false positive corner cases.
* @zh
* ็ๅ้ฅๅฐ็็ธไบคๆงๆฃๆต๏ผ้ๅบฆๅฟซ๏ผไฝๆ้่ฏฏๆ
ๅตใ
* @param {Sphere} sphere ็
* @param {Frustum} frustum ้ฅๅฐ
* @return {number} 0 ๆ ้0
*/
const sphereFrustum = function (sphere: Sphere, frustum: Frustum): number {
for (let i = 0; i < frustum.planes.length; i++) {
// frustum plane normal points to the inside
if (spherePlane(sphere, frustum.planes[i]) === -1) {
return 0;
}
} // completely outside
return 1;
};
// https://stackoverflow.com/questions/20912692/view-frustum-culling-corner-cases
/**
* @en
* sphere-frustum intersect, handles the false positives correctly.
* @zh
* ็ๅ้ฅๅฐ็็ธไบคๆงๆฃๆต๏ผๆญฃ็กฎๅค็ๅคงๅคๆฐ้่ฏฏๆ
ๅตใ
* @param {Sphere} sphere ็
* @param {Frustum} frustum ้ฅๅฐ
* @return {number} 0 ๆ ้0
*/
const sphereFrustumAccurate = (function () {
const pt = new Vec3(0, 0, 0); const map = [1, -1, 1, -1, 1, -1];
return function (sphere: Sphere, frustum: Frustum): number {
for (let i = 0; i < 6; i++) {
const plane = frustum.planes[i];
const r = sphere.radius; const c = sphere.center;
const n = plane.n; const d = plane.d;
const dot = Vec3.dot(n, c);
// frustum plane normal points to the inside
if (dot + r < d) return 0; // completely outside
else if (dot - r > d) { continue; }
// in case of false positives
// has false negatives, still working on it
Vec3.add(pt, c, Vec3.multiplyScalar(pt, n, r));
for (let j = 0; j < 6; j++) {
if (j === i || j === i + map[i]) { continue; }
const test = frustum.planes[j];
if (Vec3.dot(test.n, pt) < test.d) { return 0; }
}
}
return 1;
};
}());
/**
* @en
* sphere-sphere intersect detect.
* @zh
* ็ๅ็็็ธไบคๆงๆฃๆตใ
* @param {Sphere} sphere0 ็0
* @param {Sphere} sphere1 ็1
* @return {boolean} true or false
*/
const sphereWithSphere = function (sphere0: Sphere, sphere1: Sphere): boolean {
const r = sphere0.radius + sphere1.radius;
return Vec3.squaredDistance(sphere0.center, sphere1.center) < r * r;
};
/**
* @en
* sphere-aabb intersect detect.
* @zh
* ็ๅ่ฝดๅฏน้ฝๅ
ๅด็็็ธไบคๆงๆฃๆตใ
* @param {Sphere} sphere ็
* @param {AABB} aabb ่ฝดๅฏน้ฝๅ
ๅด็
* @return {boolean} true or false
*/
const sphereAABB = (function () {
const pt = new Vec3();
return function (sphere: Sphere, aabb: AABB): boolean {
distance.pt_point_aabb(pt, sphere.center, aabb);
return Vec3.squaredDistance(sphere.center, pt) < sphere.radius * sphere.radius;
};
}());
/**
* @en
* sphere-obb intersect detect.
* @zh
* ็ๅๆนๅๅ
ๅด็็็ธไบคๆงๆฃๆตใ
* @param {Sphere} sphere ็
* @param {OBB} obb ๆนๅๅ
ๅด็
* @return {boolean} true or false
*/
const sphereOBB = (function () {
const pt = new Vec3();
return function (sphere: Sphere, obb: OBB): boolean {
distance.pt_point_obb(pt, sphere.center, obb);
return Vec3.squaredDistance(sphere.center, pt) < sphere.radius * sphere.radius;
};
}());
/**
* @en
* sphere-capsule intersect detect.
* @zh
* ็ๅ่ถๅไฝ็็ธไบคๆงๆฃๆตใ
*/
const sphereCapsule = (function () {
const v3_0 = new Vec3();
const v3_1 = new Vec3();
return function (sphere: Sphere, capsule: Capsule) {
const r = sphere.radius + capsule.radius;
const squaredR = r * r;
const h = Vec3.squaredDistance(capsule.ellipseCenter0, capsule.ellipseCenter1);
if (h === 0) {
return Vec3.squaredDistance(sphere.center, capsule.center) < squaredR;
} else {
Vec3.subtract(v3_0, sphere.center, capsule.ellipseCenter0);
Vec3.subtract(v3_1, capsule.ellipseCenter1, capsule.ellipseCenter0);
const t = Vec3.dot(v3_0, v3_1) / h;
if (t < 0) {
return Vec3.squaredDistance(sphere.center, capsule.ellipseCenter0) < squaredR;
} else if (t > 1) {
return Vec3.squaredDistance(sphere.center, capsule.ellipseCenter1) < squaredR;
} else {
Vec3.scaleAndAdd(v3_0, capsule.ellipseCenter0, v3_1, t);
return Vec3.squaredDistance(sphere.center, v3_0) < squaredR;
}
}
};
}());
// http://www.geomalgorithms.com/a07-_distance.html
/**
* @en
* capsule-capsule intersect detect.
* @zh
* ่ถๅไฝๅ่ถๅไฝ็็ธไบคๆงๆฃๆตใ
*/
const capsuleWithCapsule = (function () {
const v3_0 = new Vec3();
const v3_1 = new Vec3();
const v3_2 = new Vec3();
const v3_3 = new Vec3();
const v3_4 = new Vec3();
const v3_5 = new Vec3();
return function capsuleWithCapsule (capsuleA: Capsule, capsuleB: Capsule) {
const u = Vec3.subtract(v3_0, capsuleA.ellipseCenter1, capsuleA.ellipseCenter0);
const v = Vec3.subtract(v3_1, capsuleB.ellipseCenter1, capsuleB.ellipseCenter0);
const w = Vec3.subtract(v3_2, capsuleA.ellipseCenter0, capsuleB.ellipseCenter0);
const a = Vec3.dot(u, u); // always >= 0
const b = Vec3.dot(u, v);
const c = Vec3.dot(v, v); // always >= 0
const d = Vec3.dot(u, w);
const e = Vec3.dot(v, w);
const D = a * c - b * b; // always >= 0
let sN: number;
let sD = D; // sc = sN / sD, default sD = D >= 0
let tN: number;
let tD = D; // tc = tN / tD, default tD = D >= 0
// compute the line parameters of the two closest points
if (D < EPSILON) { // the lines are almost parallel
sN = 0.0; // force using point P0 on segment S1
sD = 1.0; // to prevent possible division by 0.0 later
tN = e;
tD = c;
} else { // get the closest points on the infinite lines
sN = (b * e - c * d);
tN = (a * e - b * d);
if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
sN = 0.0;
tN = e;
tD = c;
} else if (sN > sD) { // sc > 1 => the s=1 edge is visible
sN = sD;
tN = e + b;
tD = c;
}
}
if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
tN = 0.0;
// recompute sc for this edge
if (-d < 0.0) {
sN = 0.0;
} else if (-d > a) {
sN = sD;
} else {
sN = -d;
sD = a;
}
} else if (tN > tD) { // tc > 1 => the t=1 edge is visible
tN = tD;
// recompute sc for this edge
if ((-d + b) < 0.0) {
sN = 0;
} else if ((-d + b) > a) {
sN = sD;
} else {
sN = (-d + b);
sD = a;
}
}
// finally do the division to get sc and tc
const sc = (Math.abs(sN) < EPSILON ? 0.0 : sN / sD);
const tc = (Math.abs(tN) < EPSILON ? 0.0 : tN / tD);
// get the difference of the two closest points
const dP = v3_3;
dP.set(w);
dP.add(Vec3.multiplyScalar(v3_4, u, sc));
dP.subtract(Vec3.multiplyScalar(v3_5, v, tc));
const radius = capsuleA.radius + capsuleB.radius;
return dP.lengthSqr() < radius * radius;
};
}());
/**
* @en
* Algorithm of intersect detect for basic geometry.
* @zh
* ๅบ็กๅ ไฝ็็ธไบคๆงๆฃๆต็ฎๆณใ
*/
const intersect = {
raySphere,
rayAABB,
rayOBB,
rayPlane,
rayTriangle,
rayCapsule,
raySubMesh,
rayMesh,
rayModel,
lineSphere,
lineAABB,
lineOBB,
linePlane,
lineTriangle,
sphereWithSphere,
sphereAABB,
sphereOBB,
spherePlane,
sphereFrustum,
sphereFrustumAccurate,
sphereCapsule,
aabbWithAABB,
aabbWithOBB,
aabbPlane,
aabbFrustum,
aabbFrustumAccurate,
obbWithOBB,
obbPlane,
obbFrustum,
obbFrustumAccurate,
obbPoint,
obbCapsule,
capsuleWithCapsule,
/**
* @zh
* g1 ๅ g2 ็็ธไบคๆงๆฃๆต๏ผๅฏๅกซๅ
ฅๅบ็กๅ ไฝไธญ็ๅฝข็ถใ
* @param g1 ๅ ไฝ1
* @param g2 ๅ ไฝ2
* @param outPt ๅฏ้๏ผ็ธไบค็นใ๏ผๆณจ๏ผไป
้จๅๅฝข็ถ็ๆฃๆตๅธฆๆ่ฟไธช่ฟๅๅผ๏ผ
*/
resolve (g1: any, g2: any, outPt = null) {
const type1 = g1._type; const type2 = g2._type;
const resolver = this[type1 | type2] as (...args: any) => number;
return type1 < type2 ? resolver(g1, g2, outPt) : resolver(g2, g1, outPt);
},
};
intersect[enums.SHAPE_RAY | enums.SHAPE_SPHERE] = raySphere;
intersect[enums.SHAPE_RAY | enums.SHAPE_AABB] = rayAABB;
intersect[enums.SHAPE_RAY | enums.SHAPE_OBB] = rayOBB;
intersect[enums.SHAPE_RAY | enums.SHAPE_PLANE] = rayPlane;
intersect[enums.SHAPE_RAY | enums.SHAPE_TRIANGLE] = rayTriangle;
intersect[enums.SHAPE_RAY | enums.SHAPE_CAPSULE] = rayCapsule;
intersect[enums.SHAPE_LINE | enums.SHAPE_SPHERE] = lineSphere;
intersect[enums.SHAPE_LINE | enums.SHAPE_AABB] = lineAABB;
intersect[enums.SHAPE_LINE | enums.SHAPE_OBB] = lineOBB;
intersect[enums.SHAPE_LINE | enums.SHAPE_PLANE] = linePlane;
intersect[enums.SHAPE_LINE | enums.SHAPE_TRIANGLE] = lineTriangle;
intersect[enums.SHAPE_SPHERE] = sphereWithSphere;
intersect[enums.SHAPE_SPHERE | enums.SHAPE_AABB] = sphereAABB;
intersect[enums.SHAPE_SPHERE | enums.SHAPE_OBB] = sphereOBB;
intersect[enums.SHAPE_SPHERE | enums.SHAPE_PLANE] = spherePlane;
intersect[enums.SHAPE_SPHERE | enums.SHAPE_FRUSTUM] = sphereFrustum;
intersect[enums.SHAPE_SPHERE | enums.SHAPE_FRUSTUM_ACCURATE] = sphereFrustumAccurate;
intersect[enums.SHAPE_SPHERE | enums.SHAPE_CAPSULE] = sphereCapsule;
intersect[enums.SHAPE_AABB] = aabbWithAABB;
intersect[enums.SHAPE_AABB | enums.SHAPE_OBB] = aabbWithOBB;
intersect[enums.SHAPE_AABB | enums.SHAPE_PLANE] = aabbPlane;
intersect[enums.SHAPE_AABB | enums.SHAPE_FRUSTUM] = aabbFrustum;
intersect[enums.SHAPE_AABB | enums.SHAPE_FRUSTUM_ACCURATE] = aabbFrustumAccurate;
intersect[enums.SHAPE_OBB] = obbWithOBB;
intersect[enums.SHAPE_OBB | enums.SHAPE_PLANE] = obbPlane;
intersect[enums.SHAPE_OBB | enums.SHAPE_FRUSTUM] = obbFrustum;
intersect[enums.SHAPE_OBB | enums.SHAPE_FRUSTUM_ACCURATE] = obbFrustumAccurate;
intersect[enums.SHAPE_OBB | enums.SHAPE_CAPSULE] = obbCapsule;
intersect[enums.SHAPE_CAPSULE] = capsuleWithCapsule;
export default intersect; | the_stack |
import { ExclamationCircleTwoTone } from '@ant-design/icons';
import { Alert, Button, Result, Tabs, Tooltip } from 'antd';
import { DripTableBuiltInColumnSchema, DripTableColumnSchema, DripTableDriver, DripTableGenericRenderElement } from 'drip-table';
import cloneDeep from 'lodash/cloneDeep';
import React from 'react';
import MonacoEditor from 'react-monaco-editor';
import { filterAttributes, filterAttributesByRegExp } from '@/utils';
import { DripTableColumn, globalActions, GlobalSchema, GlobalStore } from '@/store';
import CustomForm from '@/components/CustomForm';
import { useGlobalData } from '@/hooks';
import components from '@/table-components';
import { basicColumnAttrComponents } from '@/table-components/configs';
import { DripTableComponentAttrConfig, DripTableGeneratorPanel, DTGComponentPropertySchema } from '@/typing';
import { GlobalAttrFormConfigs } from '../configs';
import { getColumnItemByPath, updateColumnItemByPath } from '../utils';
import { CollapseIcon, TabsIcon } from './icons';
import styles from './index.module.less';
interface Props {
customComponentPanel: DripTableGeneratorPanel<DripTableComponentAttrConfig> | undefined;
customGlobalConfigPanel: DripTableGeneratorPanel<DTGComponentPropertySchema> | undefined;
driver: DripTableDriver;
}
const { TabPane } = Tabs;
const AttributeLayout = (props: Props & { store: GlobalStore }) => {
const { dataFields, mockDataSource: isDemo } = useGlobalData();
const [state, setState] = props.store;
const store = { state, setState };
const [activeKey, setActiveKey] = React.useState('0');
const [formDisplayMode, setFormDisplayMode] = React.useState('tabs' as 'collapse' | 'tabs');
const [codeErrorMessage, setCodeErrorMessage] = React.useState('');
const [code, setCode] = React.useState(JSON.stringify(state.previewDataSource, null, 4));
const getActiveKey = () => {
if (activeKey === '0') {
return state.currentColumn ? '1' : '2';
}
return activeKey;
};
const getComponents = () => {
let componentsToUse = components;
if (props.customComponentPanel) {
const customComponents = props.customComponentPanel.configs;
componentsToUse = props.customComponentPanel.mode === 'add' ? [...components, ...customComponents] : [...customComponents];
}
return [...componentsToUse];
};
/**
* ๅฐๅ
จๅฑ้
็ฝฎ่ฝฌๆขๆFormData
* @param {GlobalSchema} globalConfigs ๅ
จๅฑ้
็ฝฎ
* @returns {Record<string, unknown>} ่กจๅๆฐๆฎ
*/
const decodeGlobalConfigs = (globalConfigs?: GlobalSchema) => {
const formData: Record<string, unknown> = { ...filterAttributes(globalConfigs, 'header') };
if (typeof globalConfigs?.header === 'object') {
formData.header = true;
const headerElements = globalConfigs?.header?.elements || [];
for (const headerItem of headerElements) {
if (headerItem.type === 'spacer') {
headerItem['style.width'] = headerItem.style?.width;
}
if (headerItem.type === 'search') {
headerItem['wrapperStyle.width'] = headerItem.wrapperStyle?.width;
}
}
formData['header.items'] = headerElements;
}
if (typeof globalConfigs?.footer === 'object') {
formData.footer = true;
const footerElements = globalConfigs?.footer?.elements || [];
for (const footerItem of footerElements) {
if (footerItem.type === 'text') {
footerItem['style.width'] = footerItem.style?.width;
}
if (footerItem.type === 'search') {
footerItem['wrapperStyle.width'] = footerItem.wrapperStyle?.width;
}
}
formData['footer.items'] = footerElements;
}
if (typeof globalConfigs?.pagination === 'object') {
formData.pagination = true;
Object.keys(globalConfigs?.pagination || {}).forEach((key) => {
formData[`pagination.${key}`] = globalConfigs?.pagination?.[key];
});
}
return formData;
};
const encodeGlobalConfigs = (formData: { [key: string]: unknown }): GlobalSchema => {
const formatElement = (element) => {
if (element.type === 'display-column-selector') {
return {
type: 'display-column-selector',
selectorButtonType: element.selectorButtonType,
selectorButtonText: element.selectorButtonText,
};
}
if (element.type === 'spacer') {
const width = element['style.width'];
element['style.width'] = void 0;
return {
type: 'spacer',
style: { width },
};
}
if (element.type === 'text') {
return {
type: 'text',
span: element.span,
align: element.align,
text: element.text,
};
}
if (element.type === 'search') {
const width = element['wrapperStyle.width'];
element['wrapperStyle.width'] = void 0;
return {
type: 'search',
wrapperStyle: { width },
align: element.align,
placeholder: element.placeholder,
allowClear: element.allowClear,
searchButtonText: element.searchButtonText,
searchKeys: element.searchKeys,
searchKeyDefaultValue: element.searchKeyDefaultValue,
};
}
if (element.type === 'insert-button') {
return {
type: 'insert-button',
align: element.align,
insertButtonText: element.insertButtonText,
showIcon: element.showIcon,
};
}
return { ...element };
};
return {
...filterAttributesByRegExp(formData, /^(footer|header|pagination)\./u),
$version: formData.$version as number,
bordered: formData.bordered as boolean,
size: formData.size as 'small' | 'middle' | 'large' | undefined,
ellipsis: formData.ellipsis as boolean,
sticky: formData.sticky as boolean,
rowSelection: formData.rowSelection as boolean,
virtual: formData.virtual as boolean,
scroll: {
x: formData.scrollX as number,
y: formData.scrollY as number,
},
header: formData.header
? {
style: { margin: '0', padding: '12px 0' },
elements: (formData['header.items'] as DripTableGenericRenderElement[] || []).map(item => ({ ...formatElement(item) })),
}
: false,
footer: formData.footer
? {
style: { margin: '0', padding: '12px 0' },
elements: (formData['footer.items'] as DripTableGenericRenderElement[] || []).map(item => ({ ...formatElement(item) })),
}
: void 0,
pagination: formData.pagination
? {
size: formData['pagination.size'] as 'small' | 'default',
pageSize: formData['pagination.pageSize'] as number,
position: formData['pagination.position'] as 'bottomLeft' | 'bottomCenter' | 'bottomRight',
showQuickJumper: formData['pagination.showQuickJumper'] as boolean,
showSizeChanger: formData['pagination.showSizeChanger'] as boolean,
}
: false,
};
};
const encodeColumnConfigs = (formData: { [key: string]: unknown }): DripTableColumn => {
const uiProps: Record<string, unknown> = {};
const dataProps = {};
Object.keys(formData).forEach((key) => {
if (key.startsWith('options.')) {
uiProps[key.replace('options.', '')] = formData[key];
} else if (key.startsWith('ui:props.')) {
uiProps[key.replace('ui:props.', '')] = formData[key];
} else {
dataProps[key] = formData[key];
}
});
if (state.currentColumn?.component === 'group') {
const length = (uiProps.layout as number[])?.reduce((p, v) => p + v, 0) || 0;
uiProps.items = Array.from({ length }, _ => null);
if (state.currentColumn.options.items) {
(state.currentColumn.options.items as Record<string, unknown>[])
.slice(0, length)
.forEach((item, i) => { (uiProps.items as Record<string, unknown>[])[i] = item; });
}
}
// const columnConfig = getComponents().find(item => item['ui:type'] === state.currentColumn?.component);
return {
...filterAttributes(dataProps, [
'options',
'component',
'ui:props',
'ui:type',
'type',
'name',
'dataIndex',
'title',
'width',
'group',
]),
key: state.currentColumn?.key ?? '',
index: state.currentColumn?.index ?? 0,
sort: state.currentColumn?.sort ?? 0,
dataIndex: formData.dataIndex as string | string[],
title: formData.title as string,
width: formData.width as string,
component: state.currentColumn?.component ?? '',
options: uiProps,
};
};
const encodeColumnConfigsByPath = (formData: { [key: string]: unknown }): DripTableColumnSchema | DripTableBuiltInColumnSchema | null => {
const uiProps: Record<string, unknown> = {};
const dataProps = {};
Object.keys(formData).forEach((key) => {
if (key.startsWith('options.')) {
uiProps[key.replace('options.', '')] = formData[key];
} else if (key.startsWith('ui:props.')) {
uiProps[key.replace('ui:props.', '')] = formData[key];
} else {
dataProps[key] = formData[key];
}
});
if (state.currentColumn) {
const currentColumnItem = getColumnItemByPath(state.currentColumn, state.currentColumnPath || []);
if (currentColumnItem?.component === 'group') {
const length = (uiProps.layout as number[])?.reduce((p, v) => p + v, 0) || 0;
uiProps.items = Array.from({ length }, _ => null);
if (currentColumnItem.options.items) {
currentColumnItem.options.items.slice(0, length).forEach((item, i) => {
(uiProps.items as Record<string, unknown>[])[i] = item;
});
}
}
return {
...filterAttributes(dataProps, [
'options',
'component',
'ui:props',
'ui:type',
'type',
'name',
'dataIndex',
'title',
'width',
'group',
]),
key: currentColumnItem.key,
title: '',
dataIndex: formData.dataIndex as string | string[],
component: currentColumnItem.component ?? '',
options: uiProps,
};
}
return null;
};
const submitTableData = (codeValue?: string) => {
setCodeErrorMessage('');
setCode(codeValue || '');
try {
state.previewDataSource = JSON.parse(codeValue || '');
setState({ ...state });
globalActions.updatePreviewDataSource(store);
} catch (error) {
setCodeErrorMessage((error as Error).message);
}
};
const getGlobalFormConfigs = () => {
if (props.customGlobalConfigPanel) {
return props.customGlobalConfigPanel?.mode === 'add'
? [
...GlobalAttrFormConfigs,
...props.customGlobalConfigPanel?.configs || [],
]
: [...props.customGlobalConfigPanel?.configs || []];
}
return GlobalAttrFormConfigs;
};
const renderGlobalForm = () => (
<CustomForm<GlobalSchema>
primaryKey="$version"
configs={getGlobalFormConfigs()}
data={cloneDeep(state.globalConfigs)}
decodeData={decodeGlobalConfigs}
encodeData={encodeGlobalConfigs}
groupType={formDisplayMode}
theme={props.driver}
onChange={(data) => {
store.state.globalConfigs = cloneDeep({ ...data });
globalActions.updateGlobalConfig(store);
}}
/>
);
const getColumnConfigs = (componentType: string) => {
const columnConfig = getComponents().find(schema => schema['ui:type'] === componentType);
columnConfig?.attrSchema.forEach((schema) => {
const uiProps = schema['ui:props'];
if (!uiProps) {
return;
}
if (uiProps.optionsParam === '$$FIELD_KEY_OPTIONS$$') {
uiProps.options = isDemo
? Object.keys(state.previewDataSource[0] || {}).map(key => ({ label: key, value: key }))
: dataFields?.map(key => ({ label: key, value: key })) || [];
}
if (uiProps.items) {
(uiProps.items as DTGComponentPropertySchema[])?.forEach((item, index) => {
const itemUiProps = item['ui:props'];
if (!itemUiProps) {
return;
}
if (itemUiProps.optionsParam === '$$FIELD_KEY_OPTIONS$$') {
itemUiProps.options = isDemo
? Object.keys(state.previewDataSource[0] || {}).map(key => ({ label: key, value: key }))
: dataFields?.map(key => ({ label: key, value: key })) || [];
}
});
}
});
return columnConfig;
};
const errorBoundary = (message?: string) => (
<Result
icon={<ExclamationCircleTwoTone />}
title={<div style={{ color: '#999' }}>{ message }</div>}
/>
);
const renderColumnForm = () => {
if (!state.currentColumn) {
return errorBoundary('่ฏท็นๅป้ๆฉ่ฆ็ผ่พ็ๅ');
}
const columnConfig = getColumnConfigs(state.currentColumn?.component || '');
return (
<CustomForm<DripTableColumn>
primaryKey="key"
configs={columnConfig ? columnConfig.attrSchema || [] : []}
data={state.currentColumn}
encodeData={encodeColumnConfigs}
extendKeys={['ui:props', 'options']}
groupType={formDisplayMode}
theme={props.driver}
onChange={(data) => {
state.currentColumn = Object.assign(state.currentColumn, data);
const idx = state.columns.findIndex(item => item.key === state.currentColumn?.key);
if (idx > -1 && state.currentColumn) {
state.columns[idx] = state.currentColumn;
}
globalActions.editColumns(store);
globalActions.checkColumn(store);
}}
/>
);
};
const renderColumnFormItem = () => {
if (!state.currentColumn || (state.currentColumnPath?.length || 0) <= 0) {
return errorBoundary('่ฏท็นๅป้ๆฉ่ฆ็ผ่พ็ๅญๅ
็ด ');
}
const currentColumnItem = getColumnItemByPath(state.currentColumn, state.currentColumnPath || []);
const columnConfig = getColumnConfigs(currentColumnItem?.component || '');
const tableCellBaseProps = new Set(basicColumnAttrComponents.map(prop => prop.name));
if (columnConfig) {
columnConfig.attrSchema = columnConfig.attrSchema.filter(item => !tableCellBaseProps.has(item.name));
}
if (!currentColumnItem || !currentColumnItem.component) {
return errorBoundary('ๅญๅ
็ด ๆๆช้
็ฝฎ็ปไปถ');
}
return (
<CustomForm<DripTableColumnSchema | DripTableBuiltInColumnSchema | null>
primaryKey="key"
configs={columnConfig ? columnConfig.attrSchema || [] : []}
data={currentColumnItem}
encodeData={encodeColumnConfigsByPath}
extendKeys={['ui:props', 'options']}
groupType={formDisplayMode}
theme={props.driver}
onChange={(data) => {
if (data && state.currentColumn) {
const schema = { ...filterAttributes(data, ['index', 'sort', 'title']) };
updateColumnItemByPath(state.currentColumn, state.currentColumnPath || [], schema);
globalActions.editColumns(store);
}
}}
/>
);
};
return (
<div className={styles['attributes-wrapper']}>
<div className={styles['attributes-container']}>
<Tabs
activeKey={getActiveKey()}
type="card"
onChange={(key) => { setActiveKey(key); }}
tabBarExtraContent={activeKey !== '3'
? (
<Tooltip title={formDisplayMode === 'tabs' ? 'ๆๅ ้ขๆฟ' : 'ๆ ็ญพ้ขๆฟ'}>
<Button
style={{ borderRadius: 2 }}
size="small"
onClick={() => { setFormDisplayMode(formDisplayMode === 'collapse' ? 'tabs' : 'collapse'); }}
icon={formDisplayMode === 'tabs' ? <CollapseIcon style={{ marginTop: 4 }} /> : <TabsIcon style={{ marginTop: 4 }} />}
/>
</Tooltip>
)
: null}
>
<TabPane tab="ๅฑๆง้
็ฝฎ" key="1" className={styles['attribute-panel']}>
<div className={styles['attributes-form-panel']}>
{ renderColumnForm() }
</div>
</TabPane>
{ (state.currentColumnPath?.length || 0) > 0 && (
<TabPane tab="ๅญ็ปไปถๅฑๆง" key="4" className={styles['attribute-panel']}>
<div className={styles['attributes-form-panel']}>
{ renderColumnFormItem() }
</div>
</TabPane>
) }
<TabPane tab="ๅ
จๅฑ่ฎพ็ฝฎ" key="2" className={styles['attribute-panel']}>
<div className={styles['attributes-form-panel']}>
{ renderGlobalForm() }
</div>
</TabPane>
{ isDemo && (
<TabPane tab="่กจๆ ผๆฐๆฎ" key="3" className={styles['attribute-panel']}>
<div className={styles['attributes-code-panel']}>
{ codeErrorMessage && <Alert style={{ margin: '8px 0' }} message={codeErrorMessage} type="error" showIcon /> }
<MonacoEditor
width="100%"
height={428}
language="json"
theme="vs-dark"
value={code || ''}
onChange={(value) => { submitTableData(value); }}
/>
</div>
</TabPane>
) }
</Tabs>
</div>
</div>
);
};
export default AttributeLayout; | the_stack |
export class IgxFilteringOperand {
protected static _instance: IgxFilteringOperand = null;
public operations: IFilteringOperation[];
constructor() {
this.operations = [{
name: 'null',
isUnary: true,
iconName: 'is-null',
logic: (target: any) => target === null
}, {
name: 'notNull',
isUnary: true,
iconName: 'is-not-null',
logic: (target: any) => target !== null
}, {
name: 'in',
isUnary: false,
iconName: 'is-in',
hidden: true,
logic: (target: any, searchVal: Set<any>) => this.findValueInSet(target, searchVal)
}];
}
public static instance(): IgxFilteringOperand {
return this._instance || (this._instance = new this());
}
/**
* Returns an array of names of the conditions which are visible in the UI
*/
public conditionList(): string[] {
return this.operations.filter(f => !f.hidden).map((element) => element.name);
}
/**
* Returns an instance of the condition with the specified name.
*
* @param name The name of the condition.
*/
public condition(name: string): IFilteringOperation {
return this.operations.find((element) => element.name === name);
}
/**
* Adds a new condition to the filtering operations.
*
* @param operation The filtering operation.
*/
public append(operation: IFilteringOperation) {
this.operations.push(operation);
}
/**
* @hidden
*/
protected findValueInSet(target: any, searchVal: Set<any>) {
return searchVal.has(target);
}
}
/**
* Provides filtering operations for booleans
*
* @export
*/
export class IgxBooleanFilteringOperand extends IgxFilteringOperand {
protected constructor() {
super();
this.operations = [{
name: 'all',
isUnary: true,
iconName: 'select-all',
logic: (target: boolean) => true
}, {
name: 'true',
isUnary: true,
iconName: 'is-true',
logic: (target: boolean) => !!(target && target !== null && target !== undefined)
}, {
name: 'false',
isUnary: true,
iconName: 'is-false',
logic: (target: boolean) => !target && target !== null && target !== undefined
}, {
name: 'empty',
isUnary: true,
iconName: 'is-empty',
logic: (target: boolean) => target === null || target === undefined
}, {
name: 'notEmpty',
isUnary: true,
iconName: 'not-empty',
logic: (target: boolean) => target !== null && target !== undefined
}].concat(this.operations);
}
}
/**
* @internal
* @hidden
*/
class IgxBaseDateTimeFilteringOperand extends IgxFilteringOperand {
protected constructor() {
super();
this.operations = [{
name: 'empty',
isUnary: true,
iconName: 'is-empty',
logic: (target: Date) => target === null || target === undefined
}, {
name: 'notEmpty',
isUnary: true,
iconName: 'not-empty',
logic: (target: Date) => target !== null && target !== undefined
}].concat(this.operations);
}
/**
* Splits a Date object into parts
*
* @memberof IgxDateFilteringOperand
*/
public static getDateParts(date: Date, dateFormat?: string): IDateParts {
const res = {
day: null,
hours: null,
milliseconds: null,
minutes: null,
month: null,
seconds: null,
year: null
};
if (!date || !dateFormat) {
return res;
}
if (dateFormat.indexOf('y') >= 0) {
res.year = date.getFullYear();
}
if (dateFormat.indexOf('M') >= 0) {
res.month = date.getMonth();
}
if (dateFormat.indexOf('d') >= 0) {
res.day = date.getDate();
}
if (dateFormat.indexOf('h') >= 0) {
res.hours = date.getHours();
}
if (dateFormat.indexOf('m') >= 0) {
res.minutes = date.getMinutes();
}
if (dateFormat.indexOf('s') >= 0) {
res.seconds = date.getSeconds();
}
if (dateFormat.indexOf('f') >= 0) {
res.milliseconds = date.getMilliseconds();
}
return res;
}
protected findValueInSet(target: any, searchVal: Set<any>) {
if (!target) {
return false;
}
return searchVal.has((target instanceof Date) ? target.toISOString() : target);
}
protected validateInputData(target: Date) {
if (!(target instanceof Date)) {
throw new Error('Could not perform filtering on \'date\' column because the datasource object type is not \'Date\'.');
}
}
}
/**
* Provides filtering operations for Dates
*
* @export
*/
export class IgxDateFilteringOperand extends IgxBaseDateTimeFilteringOperand {
protected constructor() {
super();
this.operations = [{
name: 'equals',
isUnary: false,
iconName: 'equals',
logic: (target: Date, searchVal: Date) => {
if (!target) {
return false;
}
this.validateInputData(target);
const targetp = IgxDateFilteringOperand.getDateParts(target, 'yMd');
const searchp = IgxDateFilteringOperand.getDateParts(searchVal, 'yMd');
return targetp.year === searchp.year &&
targetp.month === searchp.month &&
targetp.day === searchp.day;
}
}, {
name: 'doesNotEqual',
isUnary: false,
iconName: 'not-equal',
logic: (target: Date, searchVal: Date) => {
if (!target) {
return true;
}
this.validateInputData(target);
const targetp = IgxDateFilteringOperand.getDateParts(target, 'yMd');
const searchp = IgxDateFilteringOperand.getDateParts(searchVal, 'yMd');
return targetp.year !== searchp.year ||
targetp.month !== searchp.month ||
targetp.day !== searchp.day;
}
}, {
name: 'before',
isUnary: false,
iconName: 'is-before',
logic: (target: Date, searchVal: Date) => {
if (!target) {
return false;
}
this.validateInputData(target);
return target < searchVal;
}
}, {
name: 'after',
isUnary: false,
iconName: 'is-after',
logic: (target: Date, searchVal: Date) => {
if (!target) {
return false;
}
this.validateInputData(target);
return target > searchVal;
}
}, {
name: 'today',
isUnary: true,
iconName: 'today',
logic: (target: Date) => {
if (!target) {
return false;
}
this.validateInputData(target);
const d = IgxDateFilteringOperand.getDateParts(target, 'yMd');
const now = IgxDateFilteringOperand.getDateParts(new Date(), 'yMd');
return d.year === now.year &&
d.month === now.month &&
d.day === now.day;
}
}, {
name: 'yesterday',
isUnary: true,
iconName: 'yesterday',
logic: (target: Date) => {
if (!target) {
return false;
}
this.validateInputData(target);
const td = IgxDateFilteringOperand.getDateParts(target, 'yMd');
const y = ((d) => new Date(d.setDate(d.getDate() - 1)))(new Date());
const yesterday = IgxDateFilteringOperand.getDateParts(y, 'yMd');
return td.year === yesterday.year &&
td.month === yesterday.month &&
td.day === yesterday.day;
}
}, {
name: 'thisMonth',
isUnary: true,
iconName: 'this-month',
logic: (target: Date) => {
if (!target) {
return false;
}
this.validateInputData(target);
const d = IgxDateFilteringOperand.getDateParts(target, 'yM');
const now = IgxDateFilteringOperand.getDateParts(new Date(), 'yM');
return d.year === now.year &&
d.month === now.month;
}
}, {
name: 'lastMonth',
isUnary: true,
iconName: 'last-month',
logic: (target: Date) => {
if (!target) {
return false;
}
this.validateInputData(target);
const d = IgxDateFilteringOperand.getDateParts(target, 'yM');
const now = IgxDateFilteringOperand.getDateParts(new Date(), 'yM');
if (!now.month) {
now.month = 11;
now.year -= 1;
} else {
now.month--;
}
return d.year === now.year &&
d.month === now.month;
}
}, {
name: 'nextMonth',
isUnary: true,
iconName: 'next-month',
logic: (target: Date) => {
if (!target) {
return false;
}
this.validateInputData(target);
const d = IgxDateFilteringOperand.getDateParts(target, 'yM');
const now = IgxDateFilteringOperand.getDateParts(new Date(), 'yM');
if (now.month === 11) {
now.month = 0;
now.year += 1;
} else {
now.month++;
}
return d.year === now.year &&
d.month === now.month;
}
}, {
name: 'thisYear',
isUnary: true,
iconName: 'this-year',
logic: (target: Date) => {
if (!target) {
return false;
}
this.validateInputData(target);
const d = IgxDateFilteringOperand.getDateParts(target, 'y');
const now = IgxDateFilteringOperand.getDateParts(new Date(), 'y');
return d.year === now.year;
}
}, {
name: 'lastYear',
isUnary: true,
iconName: 'last-year',
logic: (target: Date) => {
if (!target) {
return false;
}
this.validateInputData(target);
const d = IgxDateFilteringOperand.getDateParts(target, 'y');
const now = IgxDateFilteringOperand.getDateParts(new Date(), 'y');
return d.year === now.year - 1;
}
}, {
name: 'nextYear',
isUnary: true,
iconName: 'next-year',
logic: (target: Date) => {
if (!target) {
return false;
}
this.validateInputData(target);
const d = IgxDateFilteringOperand.getDateParts(target, 'y');
const now = IgxDateFilteringOperand.getDateParts(new Date(), 'y');
return d.year === now.year + 1;
}
}].concat(this.operations);
}
}
export class IgxDateTimeFilteringOperand extends IgxDateFilteringOperand {
protected constructor() {
super();
let index = this.operations.indexOf(this.condition('equals'));
this.operations.splice(index, 1);
index = this.operations.indexOf(this.condition('doesNotEqual'));
this.operations.splice(index, 1);
this.operations = [{
name: 'equals',
isUnary: false,
iconName: 'equals',
logic: (target: Date, searchVal: Date) => {
if (!target) {
return false;
}
this.validateInputData(target);
const targetp = IgxDateTimeFilteringOperand.getDateParts(target, 'yMdhms');
const searchp = IgxDateTimeFilteringOperand.getDateParts(searchVal, 'yMdhms');
return targetp.year === searchp.year &&
targetp.month === searchp.month &&
targetp.day === searchp.day &&
targetp.hours === searchp.hours &&
targetp.minutes === searchp.minutes &&
targetp.seconds === searchp.seconds;
}
}, {
name: 'doesNotEqual',
isUnary: false,
iconName: 'not-equal',
logic: (target: Date, searchVal: Date) => {
if (!target) {
return true;
}
this.validateInputData(target);
const targetp = IgxDateTimeFilteringOperand.getDateParts(target, 'yMdhms');
const searchp = IgxDateTimeFilteringOperand.getDateParts(searchVal, 'yMdhms');
return targetp.year !== searchp.year ||
targetp.month !== searchp.month ||
targetp.day !== searchp.day ||
targetp.hours !== searchp.hours ||
targetp.minutes !== searchp.minutes ||
targetp.seconds !== searchp.seconds;
}
}].concat(this.operations);
}
}
export class IgxTimeFilteringOperand extends IgxBaseDateTimeFilteringOperand {
protected constructor() {
super();
this.operations = [{
name: 'at',
isUnary: false,
iconName: 'equals',
logic: (target: Date, searchVal: Date) => {
if (!target) {
return false;
}
this.validateInputData(target);
const targetp = IgxTimeFilteringOperand.getDateParts(target, 'hms');
const searchp = IgxTimeFilteringOperand.getDateParts(searchVal, 'hms');
return targetp.hours === searchp.hours &&
targetp.minutes === searchp.minutes &&
targetp.seconds === searchp.seconds;
}
}, {
name: 'not_at',
isUnary: false,
iconName: 'not-equal',
logic: (target: Date, searchVal: Date) => {
if (!target) {
return true;
}
this.validateInputData(target);
const targetp = IgxTimeFilteringOperand.getDateParts(target, 'hms');
const searchp = IgxTimeFilteringOperand.getDateParts(searchVal, 'hms');
return targetp.hours !== searchp.hours ||
targetp.minutes !== searchp.minutes ||
targetp.seconds !== searchp.seconds;
}
}, {
name: 'before',
isUnary: false,
iconName: 'is-before',
logic: (target: Date, searchVal: Date) => {
if (!target) {
return false;
}
this.validateInputData(target);
const targetn = IgxTimeFilteringOperand.getDateParts(target, 'hms');
const search = IgxTimeFilteringOperand.getDateParts(searchVal, 'hms');
return targetn.hours < search.hours ? true : targetn.hours === search.hours && targetn.minutes < search.minutes ?
true : targetn.hours === search.hours && targetn.minutes === search.minutes && targetn.seconds < search.seconds;
}
}, {
name: 'after',
isUnary: false,
iconName: 'is-after',
logic: (target: Date, searchVal: Date) => {
if (!target) {
return false;
}
this.validateInputData(target);
const targetn = IgxTimeFilteringOperand.getDateParts(target, 'hms');
const search = IgxTimeFilteringOperand.getDateParts(searchVal, 'hms');
return targetn.hours > search.hours ? true : targetn.hours === search.hours && targetn.minutes > search.minutes ?
true : targetn.hours === search.hours && targetn.minutes === search.minutes && targetn.seconds > search.seconds;
}
}, {
name: 'at_before',
isUnary: false,
iconName: 'is-before',
logic: (target: Date, searchVal: Date) => {
if (!target) {
return false;
}
this.validateInputData(target);
const targetn = IgxTimeFilteringOperand.getDateParts(target, 'hms');
const search = IgxTimeFilteringOperand.getDateParts(searchVal, 'hms');
return (targetn.hours === search.hours && targetn.minutes === search.minutes && targetn.seconds === search.seconds) ||
targetn.hours < search.hours ? true : targetn.hours === search.hours && targetn.minutes < search.minutes ?
true : targetn.hours === search.hours && targetn.minutes === search.minutes && targetn.seconds < search.seconds;
}
}, {
name: 'at_after',
isUnary: false,
iconName: 'is-after',
logic: (target: Date, searchVal: Date) => {
if (!target) {
return false;
}
this.validateInputData(target);
const targetn = IgxTimeFilteringOperand.getDateParts(target, 'hms');
const search = IgxTimeFilteringOperand.getDateParts(searchVal, 'hms');
return (targetn.hours === search.hours && targetn.minutes === search.minutes && targetn.seconds === search.seconds) ||
targetn.hours > search.hours ? true : targetn.hours === search.hours && targetn.minutes > search.minutes ?
true : targetn.hours === search.hours && targetn.minutes === search.minutes && targetn.seconds > search.seconds;
}
}].concat(this.operations);
}
protected findValueInSet(target: any, searchVal: Set<any>) {
if (!target) {
return false;
}
return searchVal.has(target.toLocaleTimeString());
}
}
/**
* Provides filtering operations for numbers
*
* @export
*/
export class IgxNumberFilteringOperand extends IgxFilteringOperand {
protected constructor() {
super();
this.operations = [{
name: 'equals',
isUnary: false,
iconName: 'equals',
logic: (target: number, searchVal: number) => target === searchVal
}, {
name: 'doesNotEqual',
isUnary: false,
iconName: 'not-equal',
logic: (target: number, searchVal: number) => target !== searchVal
}, {
name: 'greaterThan',
isUnary: false,
iconName: 'greater-than',
logic: (target: number, searchVal: number) => target > searchVal
}, {
name: 'lessThan',
isUnary: false,
iconName: 'less-than',
logic: (target: number, searchVal: number) => target < searchVal
}, {
name: 'greaterThanOrEqualTo',
isUnary: false,
iconName: 'greater-than-or-equal',
logic: (target: number, searchVal: number) => target >= searchVal
}, {
name: 'lessThanOrEqualTo',
isUnary: false,
iconName: 'less-than-or-equal',
logic: (target: number, searchVal: number) => target <= searchVal
}, {
name: 'empty',
isUnary: true,
iconName: 'is-empty',
logic: (target: number) => target === null || target === undefined || isNaN(target)
}, {
name: 'notEmpty',
isUnary: true,
iconName: 'not-empty',
logic: (target: number) => target !== null && target !== undefined && !isNaN(target)
}].concat(this.operations);
}
}
/**
* Provides filtering operations for strings
*
* @export
*/
export class IgxStringFilteringOperand extends IgxFilteringOperand {
protected constructor() {
super();
this.operations = [{
name: 'contains',
isUnary: false,
iconName: 'contains',
logic: (target: string, searchVal: string, ignoreCase?: boolean) => {
const search = IgxStringFilteringOperand.applyIgnoreCase(searchVal, ignoreCase);
target = IgxStringFilteringOperand.applyIgnoreCase(target, ignoreCase);
return target.indexOf(search) !== -1;
}
}, {
name: 'doesNotContain',
isUnary: false,
iconName: 'does-not-contain',
logic: (target: string, searchVal: string, ignoreCase?: boolean) => {
const search = IgxStringFilteringOperand.applyIgnoreCase(searchVal, ignoreCase);
target = IgxStringFilteringOperand.applyIgnoreCase(target, ignoreCase);
return target.indexOf(search) === -1;
}
}, {
name: 'startsWith',
isUnary: false,
iconName: 'starts-with',
logic: (target: string, searchVal: string, ignoreCase?: boolean) => {
const search = IgxStringFilteringOperand.applyIgnoreCase(searchVal, ignoreCase);
target = IgxStringFilteringOperand.applyIgnoreCase(target, ignoreCase);
return target.startsWith(search);
}
}, {
name: 'endsWith',
isUnary: false,
iconName: 'ends-with',
logic: (target: string, searchVal: string, ignoreCase?: boolean) => {
const search = IgxStringFilteringOperand.applyIgnoreCase(searchVal, ignoreCase);
target = IgxStringFilteringOperand.applyIgnoreCase(target, ignoreCase);
return target.endsWith(search);
}
}, {
name: 'equals',
isUnary: false,
iconName: 'equals',
logic: (target: string, searchVal: string, ignoreCase?: boolean) => {
const search = IgxStringFilteringOperand.applyIgnoreCase(searchVal, ignoreCase);
target = IgxStringFilteringOperand.applyIgnoreCase(target, ignoreCase);
return target === search;
}
}, {
name: 'doesNotEqual',
isUnary: false,
iconName: 'not-equal',
logic: (target: string, searchVal: string, ignoreCase?: boolean) => {
const search = IgxStringFilteringOperand.applyIgnoreCase(searchVal, ignoreCase);
target = IgxStringFilteringOperand.applyIgnoreCase(target, ignoreCase);
return target !== search;
}
}, {
name: 'empty',
isUnary: true,
iconName: 'is-empty',
logic: (target: string) => target === null || target === undefined || target.length === 0
}, {
name: 'notEmpty',
isUnary: true,
iconName: 'not-empty',
logic: (target: string) => target !== null && target !== undefined && target.length > 0
}].concat(this.operations);
}
/**
* Applies case sensitivity on strings if provided
*
* @memberof IgxStringFilteringOperand
*/
public static applyIgnoreCase(a: string, ignoreCase: boolean): string {
a = a ?? '';
// bulletproof
return ignoreCase ? ('' + a).toLowerCase() : a;
}
}
/**
* Interface describing filtering operations
*
* @export
*/
export interface IFilteringOperation {
name: string;
isUnary: boolean;
iconName: string;
hidden?: boolean;
logic: (value: any, searchVal?: any, ignoreCase?: boolean) => boolean;
}
/**
* Interface describing Date object in parts
*
* @export
*/
export interface IDateParts {
year: number;
month: number;
day: number;
hours: number;
minutes: number;
seconds: number;
milliseconds: number;
} | the_stack |
๏ปฟ
/**
* BootStrap code. to initializes some class to avoid circular reference.
*/
/** polyfill */
if (typeof Object.assign != 'function') {
// Must be writable: true, enumerable: false, configurable: true
Object.defineProperty(Object, "assign", {
value: function assign(target, varArgs) { // .length of function is 2
'use strict';
if (target == null) { // TypeError if undefined or null
throw new TypeError('Cannot convert undefined or null to object');
}
var to = Object(target);
for (var index = 1; index < arguments.length; index++) {
var nextSource = arguments[index];
if (nextSource != null) { // Skip over if undefined or null
for (var nextKey in nextSource) {
// Avoid bugs when hasOwnProperty is shadowed
if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
to[nextKey] = nextSource[nextKey];
}
}
}
}
return to;
},
writable: true,
configurable: true
});
}
/** Promise type setup */
export { Promise } from "./Promise";
/** XHR setup */
export { IXHRApi, IXHROptions, IXHRProgress, } from "./Interfaces";
export { ConfigurationApi } from "./ConfigurationApi";
export { XHRFactory } from "./XHRFactory";
export { XHRDefault } from "./XHRDefault";
/**Schema Bootstrapping */
import { Schemas } from "./Core/ServiceObjects/Schemas/Schemas";
import { ServiceObjectSchema } from "./Core/ServiceObjects/Schemas/ServiceObjectSchema";
import { ConversationSchema } from "./Core/ServiceObjects/Schemas/ConversationSchema"; // [ServiceObjectSchema]
Schemas.ConversationSchema = <any>ConversationSchema;
import { FolderSchema } from "./Core/ServiceObjects/Schemas/FolderSchema"; // [ServiceObjectSchema]
Schemas.FolderSchema = <any>FolderSchema;
import { SearchFolderSchema } from "./Core/ServiceObjects/Schemas/SearchFolderSchema"; // [FolderSchema]
Schemas.SearchFolderSchema = <any>SearchFolderSchema;
import { ItemSchema } from "./Core/ServiceObjects/Schemas/ItemSchema"; // [ServiceObjectSchema] AppointmentSchema
Schemas.ItemSchema = <any>ItemSchema;
import { AppointmentSchema } from "./Core/ServiceObjects/Schemas/AppointmentSchema"; // [ItemSchema]
Schemas.AppointmentSchema = <any>AppointmentSchema;
import { ContactSchema } from "./Core/ServiceObjects/Schemas/ContactSchema"; // [ItemSchema]
Schemas.ContactSchema = <any>ContactSchema;
import { ContactGroupSchema } from "./Core/ServiceObjects/Schemas/ContactGroupSchema"; // [ItemSchema] ContactSchema
Schemas.ContactGroupSchema = <any>ContactGroupSchema;
import { EmailMessageSchema } from "./Core/ServiceObjects/Schemas/EmailMessageSchema"; // [ItemSchema]
Schemas.EmailMessageSchema = <any>EmailMessageSchema;
import { MeetingMessageSchema } from "./Core/ServiceObjects/Schemas/MeetingMessageSchema"; // [EmailMessageSchema] AppointmentSchema
Schemas.MeetingMessageSchema = <any>MeetingMessageSchema;
import { MeetingCancellationSchema } from "./Core/ServiceObjects/Schemas/MeetingCancellationSchema"; // [MeetingMessageSchema] AppointmentSchema
Schemas.MeetingCancellationSchema = <any>MeetingCancellationSchema;
import { MeetingResponseSchema } from "./Core/ServiceObjects/Schemas/MeetingResponseSchema"; // [MeetingMessageSchema] AppointmentSchema
Schemas.MeetingResponseSchema = <any>MeetingResponseSchema;
import { MeetingRequestSchema } from "./Core/ServiceObjects/Schemas/MeetingRequestSchema"; // [MeetingMessageSchema] AppointmentSchema
Schemas.MeetingRequestSchema = <any>MeetingRequestSchema;
import { PostItemSchema } from "./Core/ServiceObjects/Schemas/PostItemSchema"; // [ItemSchema] EmailMessageSchema
Schemas.PostItemSchema = <any>PostItemSchema;
import { TaskSchema } from "./Core/ServiceObjects/Schemas/TaskSchema"; // [ItemSchema]
Schemas.TaskSchema = <any>TaskSchema;
import { ResponseObjectSchema } from "./Core/ServiceObjects/Schemas/ResponseObjectSchema"; // [ServiceObjectSchema]
Schemas.ResponseObjectSchema = <any>ResponseObjectSchema;
import { PostReplySchema } from "./Core/ServiceObjects/Schemas/PostReplySchema"; // [ServiceObjectSchema] ItemSchema, ResponseObjectSchema
Schemas.PostReplySchema = <any>PostReplySchema;
import { ResponseMessageSchema } from "./Core/ServiceObjects/Schemas/ResponseMessageSchema"; // [ServiceObjectSchema] ItemSchema, EmailMessageSchema, ResponseObjectSchema
Schemas.ResponseMessageSchema = <any>ResponseMessageSchema;
import { CancelMeetingMessageSchema } from "./Core/ServiceObjects/Schemas/CancelMeetingMessageSchema"; // [ServiceObjectSchema] EmailMessageSchema, ResponseObjectSchema
Schemas.CancelMeetingMessageSchema = <any>CancelMeetingMessageSchema;
import { CalendarResponseObjectSchema } from "./Core/ServiceObjects/Schemas/CalendarResponseObjectSchema"; // [ServiceObjectSchema] ItemSchema, EmailMessageSchema, ResponseObjectSchema
Schemas.CalendarResponseObjectSchema = <any>CalendarResponseObjectSchema;
export {
ServiceObjectSchema, ConversationSchema, FolderSchema, SearchFolderSchema, ItemSchema, AppointmentSchema, ContactSchema, ContactGroupSchema, EmailMessageSchema,
MeetingMessageSchema, MeetingCancellationSchema, MeetingResponseSchema, MeetingRequestSchema, PostItemSchema, TaskSchema, ResponseObjectSchema, PostReplySchema,
ResponseMessageSchema, CancelMeetingMessageSchema, CalendarResponseObjectSchema
}
/**
* Bootstrap typecontainer
*/
import { TypeContainer } from "./TypeContainer";
TypeContainer.ServiceObjectSchema = <any>ServiceObjectSchema;
import { ServiceObject } from "./Core/ServiceObjects/ServiceObject";
import { Folder } from "./Core/ServiceObjects/Folders/Folder";
import { CalendarFolder } from "./Core/ServiceObjects/Folders/CalendarFolder";
import { ContactsFolder } from "./Core/ServiceObjects/Folders/ContactsFolder";
import { SearchFolder } from "./Core/ServiceObjects/Folders/SearchFolder";
import { TasksFolder } from "./Core/ServiceObjects/Folders/TasksFolder";
import { Appointment } from "./Core/ServiceObjects/Items/Appointment";
import { Item } from "./Core/ServiceObjects/Items/Item";
import { ItemAttachment } from "./ComplexProperties/ItemAttachment";
import { ItemAttachmentOf } from "./ComplexProperties/ItemAttachmentOf";
import { MeetingCancellation } from "./Core/ServiceObjects/Items/MeetingCancellation";
import { MeetingRequest } from "./Core/ServiceObjects/Items/MeetingRequest";
import { MeetingResponse } from "./Core/ServiceObjects/Items/MeetingResponse";
import { ExchangeService } from "./Core/ExchangeService";
import { IndexedPropertyDefinition } from "./PropertyDefinitions/IndexedPropertyDefinition";
import { ExtendedPropertyDefinition } from "./PropertyDefinitions/ExtendedPropertyDefinition";
TypeContainer.ServiceObject = ServiceObject;
TypeContainer.Folder = Folder;
TypeContainer.CalendarFolder = CalendarFolder;
TypeContainer.ContactsFolder = ContactsFolder;
TypeContainer.SearchFolder = SearchFolder;
TypeContainer.TasksFolder = TasksFolder;
TypeContainer.Item = Item;
TypeContainer.Appointment = Appointment;
TypeContainer.MeetingRequest = MeetingRequest;
TypeContainer.MeetingResponse = MeetingResponse;
TypeContainer.MeetingCancellation = MeetingCancellation;
TypeContainer.ItemAttachment = ItemAttachment;
TypeContainer.ItemAttachmentOf = ItemAttachmentOf
TypeContainer.ExchangeService = ExchangeService;
TypeContainer.IndexedPropertyDefinition = IndexedPropertyDefinition;
TypeContainer.ExtendedPropertyDefinition = ExtendedPropertyDefinition;
export { ServiceObject, Folder, CalendarFolder, ContactsFolder, SearchFolder, TasksFolder }
export { Appointment, ExchangeService, Item, ItemAttachment, ItemAttachmentOf, MeetingCancellation }
export { MeetingRequest, MeetingResponse, IndexedPropertyDefinition, ExtendedPropertyDefinition }
/** TimeZoneTransitions */
export { TimeZoneTransition } from "./ComplexProperties/TimeZones/TimeZoneTransition";
import { AbsoluteDateTransition } from "./ComplexProperties/TimeZones/AbsoluteDateTransition";
import { AbsoluteDayOfMonthTransition } from "./ComplexProperties/TimeZones/AbsoluteDayOfMonthTransition";
//import {AbsoluteMonthTransition} from "./ComplexProperties/TimeZones/AbsoluteMonthTransition";
import { RelativeDayOfMonthTransition } from "./ComplexProperties/TimeZones/RelativeDayOfMonthTransition";
//export { TimeZoneDefinition } from "./ComplexProperties/TimeZones/TimeZoneDefinition";
export { TimeZonePeriod } from "./ComplexProperties/TimeZones/TimeZonePeriod";
TypeContainer.AbsoluteDateTransition = AbsoluteDateTransition;
TypeContainer.AbsoluteDayOfMonthTransition = AbsoluteDayOfMonthTransition;
TypeContainer.RelativeDayOfMonthTransition = RelativeDayOfMonthTransition;
export { AbsoluteDateTransition, AbsoluteDayOfMonthTransition, RelativeDayOfMonthTransition }
import { Recurrence } from "./ComplexProperties/Recurrence/Patterns/Recurrence";
import { DailyPattern } from "./ComplexProperties/Recurrence/Patterns/Recurrence.DailyPattern";
import { DailyRegenerationPattern } from "./ComplexProperties/Recurrence/Patterns/Recurrence.DailyRegenerationPattern";
import { IntervalPattern } from "./ComplexProperties/Recurrence/Patterns/Recurrence.IntervalPattern";
import { MonthlyPattern } from "./ComplexProperties/Recurrence/Patterns/Recurrence.MonthlyPattern";
import { MonthlyRegenerationPattern } from "./ComplexProperties/Recurrence/Patterns/Recurrence.MonthlyRegenerationPattern";
import { RelativeMonthlyPattern } from "./ComplexProperties/Recurrence/Patterns/Recurrence.RelativeMonthlyPattern";
import { RelativeYearlyPattern } from "./ComplexProperties/Recurrence/Patterns/Recurrence.RelativeYearlyPattern";
import { WeeklyPattern } from "./ComplexProperties/Recurrence/Patterns/Recurrence.WeeklyPattern";
import { WeeklyRegenerationPattern } from "./ComplexProperties/Recurrence/Patterns/Recurrence.WeeklyRegenerationPattern";
import { YearlyPattern } from "./ComplexProperties/Recurrence/Patterns/Recurrence.YearlyPattern";
import { YearlyRegenerationPattern } from "./ComplexProperties/Recurrence/Patterns/Recurrence.YearlyRegenerationPattern";
Recurrence.DailyPattern = DailyPattern;
Recurrence.DailyRegenerationPattern = DailyRegenerationPattern;
Recurrence.IntervalPattern = <any>IntervalPattern;
Recurrence.MonthlyPattern = MonthlyPattern;
Recurrence.MonthlyRegenerationPattern = MonthlyRegenerationPattern;
Recurrence.RelativeMonthlyPattern = RelativeMonthlyPattern;
Recurrence.RelativeYearlyPattern = RelativeYearlyPattern;
Recurrence.WeeklyPattern = WeeklyPattern;
Recurrence.WeeklyRegenerationPattern = WeeklyRegenerationPattern;
Recurrence.YearlyPattern = YearlyPattern;
Recurrence.YearlyRegenerationPattern = YearlyRegenerationPattern;
export { Recurrence }
import { SearchFilter } from "./Search/Filters/SearchFilter";
import { ContainsSubstring } from "./Search/Filters/SearchFilter.ContainsSubstring";
import { ExcludesBitmask } from "./Search/Filters/SearchFilter.ExcludesBitmask";
import { Exists } from "./Search/Filters/SearchFilter.Exists";
import { IsEqualTo } from "./Search/Filters/SearchFilter.IsEqualTo";
import { IsGreaterThan } from "./Search/Filters/SearchFilter.IsGreaterThan";
import { IsGreaterThanOrEqualTo } from "./Search/Filters/SearchFilter.IsGreaterThanOrEqualTo";
import { IsLessThan } from "./Search/Filters/SearchFilter.IsLessThan";
import { IsLessThanOrEqualTo } from "./Search/Filters/SearchFilter.IsLessThanOrEqualTo";
import { IsNotEqualTo } from "./Search/Filters/SearchFilter.IsNotEqualTo";
import { Not } from "./Search/Filters/SearchFilter.Not";
import { PropertyBasedFilter } from "./Search/Filters/SearchFilter.PropertyBasedFilter";
import { RelationalFilter } from "./Search/Filters/SearchFilter.RelationalFilter";
import { SearchFilterCollection } from "./Search/Filters/SearchFilter.SearchFilterCollection";
SearchFilter.ContainsSubstring = ContainsSubstring;
SearchFilter.ExcludesBitmask = ExcludesBitmask;
SearchFilter.Exists = Exists;
SearchFilter.IsEqualTo = IsEqualTo;
SearchFilter.IsGreaterThan = IsGreaterThan;
SearchFilter.IsGreaterThanOrEqualTo = IsGreaterThanOrEqualTo;
SearchFilter.IsLessThan = IsLessThan;
SearchFilter.IsLessThanOrEqualTo = IsLessThanOrEqualTo;
SearchFilter.IsNotEqualTo = IsNotEqualTo;
SearchFilter.Not = Not;
SearchFilter.PropertyBasedFilter = <any>PropertyBasedFilter;
SearchFilter.RelationalFilter = <any>RelationalFilter;
SearchFilter.SearchFilterCollection = SearchFilterCollection;
export { SearchFilter };
/**#endregion BootStrap code */
export { AbstractFolderIdWrapper } from "./Misc/AbstractFolderIdWrapper";
export { AbstractItemIdWrapper } from "./Misc/AbstractItemIdWrapper";
export { AcceptMeetingInvitationMessage } from "./Core/ServiceObjects/ResponseObjects/AcceptMeetingInvitationMessage";
export { AccountIsLockedException } from "./Exceptions/AccountIsLockedException";
export { AddDelegateRequest } from "./Core/Requests/AddDelegateRequest";
export { AddressEntity } from "./ComplexProperties/AddressEntity";
export { AddressEntityCollection } from "./ComplexProperties/AddressEntityCollection";
export { AffectedTaskOccurrence } from "./Enumerations/AffectedTaskOccurrence";
export { AggregateType } from "./Enumerations/AggregateType";
export { Dictionary } from "./AltDictionary";
export { AlternateId } from "./Misc/IdConversion/AlternateId";
export { AlternateIdBase } from "./Misc/IdConversion/AlternateIdBase";
export { AlternateMailbox } from "./Autodiscover/AlternateMailbox";
export { AlternateMailboxCollection } from "./Autodiscover/AlternateMailboxCollection";
export { AlternatePublicFolderId } from "./Misc/IdConversion/AlternatePublicFolderId";
export { AlternatePublicFolderItemId } from "./Misc/IdConversion/AlternatePublicFolderItemId";
export { ApplyConversationActionRequest } from "./Core/Requests/ApplyConversationActionRequest";
export { AppointmentOccurrenceId } from "./ComplexProperties/AppointmentOccurrenceId";
export { AppointmentType } from "./Enumerations/AppointmentType";
export { ApprovalRequestData } from "./ComplexProperties/ApprovalRequestData";
export { ArchiveItemRequest } from "./Core/Requests/ArchiveItemRequest";
export { ArchiveItemResponse } from "./Core/Responses/ArchiveItemResponse";
export { ArchiveTag } from "./ComplexProperties/ArchiveTag";
export { AsyncRequestResult } from "./Core/Requests/AsyncRequestResult";
export { Attachment } from "./ComplexProperties/Attachment";
export { AttachmentCollection } from "./ComplexProperties/AttachmentCollection";
export { AttachmentsPropertyDefinition } from "./PropertyDefinitions/AttachmentsPropertyDefinition";
export { Attendee } from "./ComplexProperties/Attendee";
export { AttendeeAvailability } from "./Core/Responses/AttendeeAvailability";
export { AttendeeCollection } from "./ComplexProperties/AttendeeCollection";
export { AttendeeInfo } from "./Misc/Availability/AttendeeInfo";
export { AutodiscoverDnsClient } from "./Autodiscover/AutodiscoverDnsClient";
export { AutodiscoverEndpoints } from "./Enumerations/AutodiscoverEndpoints";
export { AutodiscoverError } from "./Autodiscover/AutodiscoverError";
export { AutodiscoverErrorCode } from "./Enumerations/AutodiscoverErrorCode";
export { AutodiscoverLocalException } from "./Exceptions/AutodiscoverLocalException";
export { AutodiscoverRemoteException } from "./Exceptions/AutodiscoverRemoteException";
export { AutodiscoverRequest } from "./Autodiscover/Requests/AutodiscoverRequest";
export { AutodiscoverResponse } from "./Autodiscover/Responses/AutodiscoverResponse";
export { AutodiscoverResponseCollection } from "./Autodiscover/AutodiscoverResponseCollection";
export { AutodiscoverResponseException } from "./Exceptions/AutodiscoverResponseException";
export { AutodiscoverResponseType } from "./Enumerations/AutodiscoverResponseType";
export { AutodiscoverService } from "./Autodiscover/AutodiscoverService";
export { AutodiscoverRedirectionUrlValidationCallback } from "./Autodiscover/AutodiscoverServiceDelegates";
export { AvailabilityData } from "./Enumerations/AvailabilityData";
export { AvailabilityOptions } from "./Misc/Availability/AvailabilityOptions";
export { BasePropertySet } from "./Enumerations/BasePropertySet";
//export {BasicAuthModuleForUTF8} from "./Credentials/BasicAuthModuleForUTF8";
export { BatchServiceResponseException } from "./Exceptions/BatchServiceResponseException";
export { BodyType } from "./Enumerations/BodyType";
export { BoolPropertyDefinition } from "./PropertyDefinitions/BoolPropertyDefinition";
//export {BulkTransfer} from "./operations/BulkTransfer/BulkTransfer";
export { ByteArrayArray } from "./ComplexProperties/ByteArrayArray";
export { ByteArrayPropertyDefinition } from "./PropertyDefinitions/ByteArrayPropertyDefinition";
export { CalendarActionResults } from "./Misc/CalendarActionResults";
export { CalendarEvent } from "./ComplexProperties/Availability/CalendarEvent";
export { CalendarEventDetails } from "./ComplexProperties/Availability/CalendarEventDetails";
export { CalendarResponseMessage } from "./Core/ServiceObjects/ResponseObjects/CalendarResponseMessage";
export { CalendarResponseMessageBase } from "./Core/ServiceObjects/ResponseObjects/CalendarResponseMessageBase";
export { CalendarView } from "./Search/CalendarView";
export { CancelMeetingMessage } from "./Core/ServiceObjects/ResponseObjects/CancelMeetingMessage";
export { Change } from "./Sync/Change";
export { ChangeCollection } from "./Sync/ChangeCollection";
export { ChangeHighlights } from "./ComplexProperties/ChangeHighlights";
export { ChangeType } from "./Enumerations/ChangeType";
export { ClientAccessTokenRequest } from "./ComplexProperties/ClientAccessTokenRequest";
export { ClientAccessTokenType } from "./Enumerations/ClientAccessTokenType";
export { ClientApp } from "./ComplexProperties/ClientApp";
export { ClientAppMetadata } from "./ComplexProperties/ClientAppMetadata";
export { ClientCertificateCredentials } from "./Credentials/ClientCertificateCredentials";
export { ClientExtension } from "./ComplexProperties/ClientExtension";
export { ClientExtensionProvidedTo } from "./Enumerations/ClientExtensionProvidedTo";
export { ComparisonHelpers } from "./Autodiscover/ComparisonHelpers";
export { ComparisonMode } from "./Enumerations/ComparisonMode";
export { CompleteName } from "./ComplexProperties/CompleteName";
export { ComplexProperty } from "./ComplexProperties/ComplexProperty";
export { ComplexPropertyCollection } from "./ComplexProperties/ComplexPropertyCollection";
export { ComplexPropertyDefinition } from "./PropertyDefinitions/ComplexPropertyDefinition";
export { ComplexPropertyDefinitionBase } from "./PropertyDefinitions/ComplexPropertyDefinitionBase";
export { ConfigurationSettingsBase } from "./Autodiscover/ConfigurationSettings/ConfigurationSettingsBase";
export { Conflict } from "./ComplexProperties/Availability/Conflict";
export { ConflictResolutionMode } from "./Enumerations/ConflictResolutionMode";
export { ConflictType } from "./Enumerations/ConflictType";
export { ConnectingIdType } from "./Enumerations/ConnectingIdType";
export { ConnectionFailureCause } from "./Enumerations/ConnectionFailureCause";
//export {ConnectionStatus} from "./Enumerations/ConnectionStatus";
export { Contact } from "./Core/ServiceObjects/Items/Contact";
export { ContactEntity } from "./ComplexProperties/ContactEntity";
export { ContactEntityCollection } from "./ComplexProperties/ContactEntityCollection";
export { ContactGroup } from "./Core/ServiceObjects/Items/ContactGroup";
export { ContactPhoneEntity } from "./ComplexProperties/ContactPhoneEntity";
export { ContactPhoneEntityCollection } from "./ComplexProperties/ContactPhoneEntityCollection";
export { ContactSource } from "./Enumerations/ContactSource";
export { ContainedPropertyDefinition } from "./PropertyDefinitions/ContainedPropertyDefinition";
export { ContainmentMode } from "./Enumerations/ContainmentMode";
export { Conversation } from "./Core/ServiceObjects/Items/Conversation";
export { ConversationAction } from "./Misc/ConversationAction";
export { ConversationActionType } from "./Enumerations/ConversationActionType";
export { ConversationFlagStatus } from "./Enumerations/ConversationFlagStatus";
export { ConversationId } from "./ComplexProperties/ConversationId";
export { ConversationIndexedItemView } from "./Search/ConversationIndexedItemView";
export { ConversationNode } from "./ComplexProperties/ConversationNode";
export { ConversationNodeCollection } from "./ComplexProperties/ConversationNodeCollection";
export { ConversationQueryTraversal } from "./Enumerations/ConversationQueryTraversal";
export { ConversationRequest } from "./ComplexProperties/ConversationRequest";
export { ConversationResponse } from "./ComplexProperties/ConversationResponse";
export { ConversationSortOrder } from "./Enumerations/ConversationSortOrder";
export { ConvertIdRequest } from "./Core/Requests/ConvertIdRequest";
export { ConvertIdResponse } from "./Core/Responses/ConvertIdResponse";
export { CopyFolderRequest } from "./Core/Requests/CopyFolderRequest";
export { CopyItemRequest } from "./Core/Requests/CopyItemRequest";
export { CreateAttachmentException } from "./Exceptions/CreateAttachmentException";
export { CreateAttachmentRequest } from "./Core/Requests/CreateAttachmentRequest";
export { CreateAttachmentResponse } from "./Core/Responses/CreateAttachmentResponse";
export { CreateFolderRequest } from "./Core/Requests/CreateFolderRequest";
export { CreateFolderResponse } from "./Core/Responses/CreateFolderResponse";
export { CreateItemRequest } from "./Core/Requests/CreateItemRequest";
export { CreateItemRequestBase } from "./Core/Requests/CreateItemRequestBase";
export { CreateItemResponse } from "./Core/Responses/CreateItemResponse";
export { CreateItemResponseBase } from "./Core/Responses/CreateItemResponseBase";
export { CreateRequest } from "./Core/Requests/CreateRequest";
export { CreateResponseObjectRequest } from "./Core/Requests/CreateResponseObjectRequest";
export { CreateResponseObjectResponse } from "./Core/Responses/CreateResponseObjectResponse";
export { CreateRuleOperation } from "./ComplexProperties/CreateRuleOperation";
export { CreateUserConfigurationRequest } from "./Core/Requests/CreateUserConfigurationRequest";
export { DateTime, DateTimeKind } from "./DateTime";
export { TimeSpan } from "./TimeSpan";
export { TimeZoneInfo } from "./TimeZoneInfo";
export { DateTimePrecision } from "./Enumerations/DateTimePrecision";
export { DateTimePropertyDefinition } from "./PropertyDefinitions/DateTimePropertyDefinition";
export { DayOfTheWeek } from "./Enumerations/DayOfTheWeek";
export { DayOfTheWeekCollection } from "./ComplexProperties/Recurrence/DayOfTheWeekCollection";
export { DayOfTheWeekIndex } from "./Enumerations/DayOfTheWeekIndex";
export { DeclineMeetingInvitationMessage } from "./Core/ServiceObjects/ResponseObjects/DeclineMeetingInvitationMessage";
export { DefaultExtendedPropertySet } from "./Enumerations/DefaultExtendedPropertySet";
export { DelegateFolderPermissionLevel } from "./Enumerations/DelegateFolderPermissionLevel";
export { DelegateInformation } from "./Misc/DelegateInformation";
export { DelegateManagementRequestBase } from "./Core/Requests/DelegateManagementRequestBase";
export { DelegateManagementResponse } from "./Core/Responses/DelegateManagementResponse";
export { DelegatePermissions } from "./ComplexProperties/DelegatePermissions";
//export {DelegateTypes} from "./Misc/DelegateTypes";
export { DelegateUser } from "./ComplexProperties/DelegateUser";
export { DelegateUserResponse } from "./Core/Responses/DelegateUserResponse";
export { DeleteAttachmentException } from "./Exceptions/DeleteAttachmentException";
export { DeleteAttachmentRequest } from "./Core/Requests/DeleteAttachmentRequest";
export { DeleteAttachmentResponse } from "./Core/Responses/DeleteAttachmentResponse";
export { DeletedOccurrenceInfo } from "./ComplexProperties/DeletedOccurrenceInfo";
export { DeletedOccurrenceInfoCollection } from "./ComplexProperties/DeletedOccurrenceInfoCollection";
export { DeleteFolderRequest } from "./Core/Requests/DeleteFolderRequest";
export { DeleteItemRequest } from "./Core/Requests/DeleteItemRequest";
export { DeleteMode } from "./Enumerations/DeleteMode";
export { DeleteRequest } from "./Core/Requests/DeleteRequest";
export { DeleteRuleOperation } from "./ComplexProperties/DeleteRuleOperation";
export { DeleteUserConfigurationRequest } from "./Core/Requests/DeleteUserConfigurationRequest";
export { DictionaryEntryProperty } from "./ComplexProperties/DictionaryEntryProperty";
export { DictionaryProperty } from "./ComplexProperties/DictionaryProperty";
export { DirectoryHelper } from "./Autodiscover/DirectoryHelper";
export { DisableAppRequest } from "./Core/Requests/DisableAppRequest";
export { DisableAppResponse } from "./Core/Responses/DisableAppResponse";
export { DisableReasonType } from "./Enumerations/DisableReasonType";
export { DisconnectPhoneCallRequest } from "./Core/Requests/DisconnectPhoneCallRequest";
export { DiscoverySearchConfiguration } from "./MailboxSearch/DiscoverySearchConfiguration";
export { DnsClient } from "./Dns/DnsClient";
// export {DnsException} from "./Exceptions/DnsException";
// export {DnsNativeMethods} from "./Dns/DnsNativeMethods";
// export {DnsQueryOptions} from "./Enumerations/DnsQueryOptions";
export { DnsRecord } from "./Dns/DnsRecord";
export { DnsRecordHeader } from "./Dns/DnsRecordHeader";
export { DnsRecordType } from "./Enumerations/DnsRecordType";
export { DnsSrvRecord } from "./Dns/DnsSrvRecord";
export { DocumentSharingLocation } from "./Autodiscover/DocumentSharingLocation";
export { DocumentSharingLocationCollection } from "./Autodiscover/DocumentSharingLocationCollection";
export { DomainSettingError } from "./Autodiscover/DomainSettingError";
export { DomainSettingName } from "./Enumerations/DomainSettingName";
export { DoublePropertyDefinition } from "./PropertyDefinitions/DoublePropertyDefinition";
export { EffectiveRights } from "./Enumerations/EffectiveRights";
export { EffectiveRightsPropertyDefinition } from "./PropertyDefinitions/EffectiveRightsPropertyDefinition";
export { ElcFolderType } from "./Enumerations/ElcFolderType";
export { EmailAddress } from "./ComplexProperties/EmailAddress";
export { EmailAddressCollection } from "./ComplexProperties/EmailAddressCollection";
export { EmailAddressDictionary } from "./ComplexProperties/EmailAddressDictionary";
export { EmailAddressEntity } from "./ComplexProperties/EmailAddressEntity";
export { EmailAddressEntityCollection } from "./ComplexProperties/EmailAddressEntityCollection";
export { EmailAddressEntry } from "./ComplexProperties/EmailAddressEntry";
export { EmailAddressKey } from "./Enumerations/EmailAddressKey";
export { EmailMessage } from "./Core/ServiceObjects/Items/EmailMessage";
export { EmailPosition } from "./Enumerations/EmailPosition";
export { EmailUserEntity } from "./ComplexProperties/EmailUserEntity";
export { EmailUserEntityCollection } from "./ComplexProperties/EmailUserEntityCollection";
export { EmptyFolderRequest } from "./Core/Requests/EmptyFolderRequest";
export { EndDateRecurrenceRange } from "./ComplexProperties/Recurrence/Ranges/EndDateRecurrenceRange";
export { EnhancedLocation } from "./ComplexProperties/EnhancedLocation";
export { EntityExtractionResult } from "./ComplexProperties/EntityExtractionResult";
export { EventType } from "./Enumerations/EventType";
export { EwsLogging } from "./Core/EwsLogging";
export { EwsServiceJsonReader } from "./Core/EwsServiceJsonReader";
export { EwsServiceMultiResponseXmlReader } from "./Core/EwsServiceMultiResponseXmlReader";
export { EwsServiceXmlReader } from "./Core/EwsServiceXmlReader";
export { EwsServiceXmlWriter } from "./Core/EwsServiceXmlWriter";
export { EwsTraceListener } from "./Misc/EwsTraceListener";
export { EwsUtilities } from "./Core/EwsUtilities";
export { EwsXmlReader } from "./Core/EwsXmlReader";
export { Exception } from "./Exceptions/Exception";
export { ExchangeCredentials } from "./Credentials/ExchangeCredentials";
export { ExchangeServerInfo } from "./Core/ExchangeServerInfo";
export { ExchangeServiceBase } from "./Core/ExchangeServiceBase";
export { ExchangeVersion } from "./Enumerations/ExchangeVersion";
export { ExecuteDiagnosticMethodRequest } from "./Core/Requests/ExecuteDiagnosticMethodRequest";
export { ExecuteDiagnosticMethodResponse } from "./Core/Responses/ExecuteDiagnosticMethodResponse";
export { ExpandGroupRequest } from "./Core/Requests/ExpandGroupRequest";
export { ExpandGroupResponse } from "./Core/Responses/ExpandGroupResponse";
export { ExpandGroupResults } from "./Misc/ExpandGroupResults";
export { ExtendedAttribute } from "./MailboxSearch/ExtendedAttribute";
export { ExtendedProperty } from "./ComplexProperties/ExtendedProperty";
export { ExtendedPropertyCollection } from "./ComplexProperties/ExtendedPropertyCollection";
export { ExtensionInstallScope } from "./Enumerations/ExtensionInstallScope";
export { DOMParser, isNullOrUndefined, Convert, ArrayHelper, base64Helper, EnumHelper, StringHelper, TypeSystem, UriHelper, xml2JsObject } from "./ExtensionMethods";
export { ExtensionType } from "./Enumerations/ExtensionType";
export { ExtractedEntity } from "./ComplexProperties/ExtractedEntity";
export { FailedSearchMailbox } from "./MailboxSearch/FailedSearchMailbox";
export { FileAsMapping } from "./Enumerations/FileAsMapping";
export { FileAttachment } from "./ComplexProperties/FileAttachment";
export { FindConversationRequest } from "./Core/Requests/FindConversationRequest";
export { FindConversationResponse } from "./Core/Responses/FindConversationResponse";
export { FindConversationResults } from "./Search/FindConversationResults";
export { FindFolderRequest } from "./Core/Requests/FindFolderRequest";
export { FindFolderResponse } from "./Core/Responses/FindFolderResponse";
export { FindFoldersResults } from "./Search/FindFoldersResults";
export { FindItemRequest } from "./Core/Requests/FindItemRequest";
export { FindItemResponse } from "./Core/Responses/FindItemResponse";
export { FindItemsResults } from "./Search/FindItemsResults";
export { FindRequest } from "./Core/Requests/FindRequest";
export { Flag } from "./ComplexProperties/Flag";
export { FlaggedForAction } from "./Enumerations/FlaggedForAction";
export { FolderChange } from "./Sync/FolderChange";
export { FolderEvent } from "./Notifications/FolderEvent";
export { FolderId } from "./ComplexProperties/FolderId";
export { FolderIdCollection } from "./ComplexProperties/FolderIdCollection";
export { FolderIdWrapper } from "./Misc/FolderIdWrapper";
export { FolderIdWrapperList } from "./Misc/FolderIdWrapperList";
export { FolderInfo } from "./Core/ServiceObjects/Folders/FolderInfo";
export { FolderPermission } from "./ComplexProperties/FolderPermission";
export { FolderPermissionCollection } from "./ComplexProperties/FolderPermissionCollection";
export { FolderPermissionLevel } from "./Enumerations/FolderPermissionLevel";
export { FolderPermissionReadAccess } from "./Enumerations/FolderPermissionReadAccess";
export { FolderTraversal } from "./Enumerations/FolderTraversal";
export { FolderView } from "./Search/FolderView";
export { FolderWrapper } from "./Misc/FolderWrapper";
export { FreeBusyViewType } from "./Enumerations/FreeBusyViewType";
//export {FreeType} from "./Enumerations/FreeType"; - with DnsNativeMethods
export { GenericPropertyDefinition } from "./PropertyDefinitions/GenericPropertyDefinition";
export { GetAppManifestsRequest } from "./Core/Requests/GetAppManifestsRequest";
export { GetAppManifestsResponse } from "./Core/Responses/GetAppManifestsResponse";
export { GetAppMarketplaceUrlRequest } from "./Core/Requests/GetAppMarketplaceUrlRequest";
export { GetAppMarketplaceUrlResponse } from "./Core/Responses/GetAppMarketplaceUrlResponse";
export { GetAttachmentRequest } from "./Core/Requests/GetAttachmentRequest";
export { GetAttachmentResponse } from "./Core/Responses/GetAttachmentResponse";
export { GetClientAccessTokenRequest } from "./Core/Requests/GetClientAccessTokenRequest";
export { GetClientAccessTokenResponse } from "./Core/Responses/GetClientAccessTokenResponse";
export { GetClientExtensionRequest } from "./Core/Requests/GetClientExtensionRequest";
export { GetClientExtensionResponse } from "./Core/Responses/GetClientExtensionResponse";
export { GetConversationItemsRequest } from "./Core/Requests/GetConversationItemsRequest";
export { GetConversationItemsResponse } from "./Core/Responses/GetConversationItemsResponse";
export { GetDelegateRequest } from "./Core/Requests/GetDelegateRequest";
export { GetDelegateResponse } from "./Core/Responses/GetDelegateResponse";
export { GetDiscoverySearchConfigurationRequest } from "./Core/Requests/GetDiscoverySearchConfigurationRequest";
export { GetDiscoverySearchConfigurationResponse } from "./Core/Responses/GetDiscoverySearchConfigurationResponse";
export { GetDomainSettingsRequest } from "./Autodiscover/Requests/GetDomainSettingsRequest";
export { GetDomainSettingsResponse } from "./Autodiscover/Responses/GetDomainSettingsResponse";
export { GetDomainSettingsResponseCollection } from "./Autodiscover/Responses/GetDomainSettingsResponseCollection";
export { GetEncryptionConfigurationRequest } from "./Core/Requests/GetEncryptionConfigurationRequest";
export { GetEncryptionConfigurationResponse } from "./Core/Responses/GetEncryptionConfigurationResponse";
export { GetEventsRequest } from "./Core/Requests/GetEventsRequest";
export { GetEventsResponse } from "./Core/Responses/GetEventsResponse";
export { GetEventsResults } from "./Notifications/GetEventsResults";
export { GetFolderRequest } from "./Core/Requests/GetFolderRequest";
export { GetFolderRequestBase } from "./Core/Requests/GetFolderRequestBase";
export { GetFolderRequestForLoad } from "./Core/Requests/GetFolderRequestForLoad";
export { GetFolderResponse } from "./Core/Responses/GetFolderResponse";
export { GetHoldOnMailboxesRequest } from "./Core/Requests/GetHoldOnMailboxesRequest";
export { GetHoldOnMailboxesResponse } from "./Core/Responses/GetHoldOnMailboxesResponse";
export { GetInboxRulesRequest } from "./Core/Requests/GetInboxRulesRequest";
export { GetInboxRulesResponse } from "./Core/Responses/GetInboxRulesResponse";
export { GetItemRequest } from "./Core/Requests/GetItemRequest";
export { GetItemRequestBase } from "./Core/Requests/GetItemRequestBase";
export { GetItemRequestForLoad } from "./Core/Requests/GetItemRequestForLoad";
export { GetItemResponse } from "./Core/Responses/GetItemResponse";
export { GetNonIndexableItemDetailsRequest } from "./Core/Requests/GetNonIndexableItemDetailsRequest";
export { GetNonIndexableItemDetailsResponse } from "./Core/Responses/GetNonIndexableItemDetailsResponse";
export { GetNonIndexableItemStatisticsRequest } from "./Core/Requests/GetNonIndexableItemStatisticsRequest";
export { GetNonIndexableItemStatisticsResponse } from "./Core/Responses/GetNonIndexableItemStatisticsResponse";
export { GetPasswordExpirationDateRequest } from "./Core/Requests/GetPasswordExpirationDateRequest";
export { GetPasswordExpirationDateResponse } from "./Core/Responses/GetPasswordExpirationDateResponse";
export { GetPhoneCallRequest } from "./Core/Requests/GetPhoneCallRequest";
export { GetPhoneCallResponse } from "./Core/Responses/GetPhoneCallResponse";
export { GetRequest } from "./Core/Requests/GetRequest";
export { GetRoomListsRequest } from "./Core/Requests/GetRoomListsRequest";
export { GetRoomListsResponse } from "./Core/Responses/GetRoomListsResponse";
export { GetRoomsRequest } from "./Core/Requests/GetRoomsRequest";
export { GetRoomsResponse } from "./Core/Responses/GetRoomsResponse";
export { GetSearchableMailboxesRequest } from "./Core/Requests/GetSearchableMailboxesRequest";
export { GetSearchableMailboxesResponse } from "./Core/Responses/GetSearchableMailboxesResponse";
export { GetServerTimeZonesRequest } from "./Core/Requests/GetServerTimeZonesRequest";
export { GetServerTimeZonesResponse } from "./Core/Responses/GetServerTimeZonesResponse";
export { GetStreamingEventsRequest } from "./Core/Requests/GetStreamingEventsRequest";
export { GetStreamingEventsResponse } from "./Core/Responses/GetStreamingEventsResponse";
export { GetStreamingEventsResults } from "./Notifications/GetStreamingEventsResults";
export { GetUserAvailabilityRequest } from "./Core/Requests/GetUserAvailabilityRequest";
export { GetUserAvailabilityResults } from "./Misc/Availability/GetUserAvailabilityResults";
export { GetUserConfigurationRequest } from "./Core/Requests/GetUserConfigurationRequest";
export { GetUserConfigurationResponse } from "./Core/Responses/GetUserConfigurationResponse";
export { GetUserOofSettingsRequest } from "./Core/Requests/GetUserOofSettingsRequest";
export { GetUserOofSettingsResponse } from "./Core/Responses/GetUserOofSettingsResponse";
export { GetUserRetentionPolicyTagsRequest } from "./Core/Requests/GetUserRetentionPolicyTagsRequest";
export { GetUserRetentionPolicyTagsResponse } from "./Core/Responses/GetUserRetentionPolicyTagsResponse";
export { GetUserSettingsRequest } from "./Autodiscover/Requests/GetUserSettingsRequest";
export { GetUserSettingsResponse } from "./Autodiscover/Responses/GetUserSettingsResponse";
export { GetUserSettingsResponseCollection } from "./Autodiscover/Responses/GetUserSettingsResponseCollection";
export { GroupedFindItemsResults } from "./Search/GroupedFindItemsResults";
export { Grouping } from "./Search/Grouping";
export { GroupMember } from "./ComplexProperties/GroupMember";
export { GroupMemberCollection } from "./ComplexProperties/GroupMemberCollection";
export { GroupMemberPropertyDefinition } from "./PropertyDefinitions/GroupMemberPropertyDefinition";
export { Guid } from "./Guid";
export { HangingRequestDisconnectEventArgs } from "./Core/Requests/HangingRequestDisconnectEventArgs";
export { HangingRequestDisconnectReason } from "./Enumerations/HangingRequestDisconnectReason";
export { HangingServiceRequestBase } from "./Core/Requests/HangingServiceRequestBase";
//export {HangingTraceStream} from "./Misc/HangingTraceStream";
export { HighlightTerm } from "./ComplexProperties/HighlightTerm";
export { HoldAction } from "./Enumerations/HoldAction";
export { HoldStatus } from "./Enumerations/HoldStatus";
export { ICalendarActionProvider } from "./Interfaces/ICalendarActionProvider";
export { IconIndex } from "./Enumerations/IconIndex";
export { ICustomUpdateSerializer } from "./Interfaces/ICustomXmlUpdateSerializer";
export { IdFormat } from "./Enumerations/IdFormat";
//export {IDs} from "./Enumerations/IDs"; - resourcedictionary uses in c#
export { IEwsHttpWebRequest } from "./Interfaces/IEwsHttpWebRequest";
export { IEwsHttpWebRequestFactory } from "./Interfaces/IEwsHttpWebRequestFactory";
export { IEwsHttpWebResponse } from "./Interfaces/IEwsHttpWebResponse";
export { IFileAttachmentContentHandler } from "./Interfaces/IFileAttachmentContentHandler";
export { IJsonCollectionDeserializer } from "./Interfaces/IJsonCollectionDeserializer";
//export {IJSonSerializable} from "./Interfaces/IJSonSerializable";
export { ImAddressDictionary } from "./ComplexProperties/ImAddressDictionary";
export { ImAddressEntry } from "./ComplexProperties/ImAddressEntry";
export { ImAddressKey } from "./Enumerations/ImAddressKey";
export { ImpersonatedUserId } from "./Misc/ImpersonatedUserId";
export { Importance } from "./Enumerations/Importance";
export { InstallAppRequest } from "./Core/Requests/InstallAppRequest";
export { InstallAppResponse } from "./Core/Responses/InstallAppResponse";
export { InternetMessageHeader } from "./ComplexProperties/InternetMessageHeader";
export { InternetMessageHeaderCollection } from "./ComplexProperties/InternetMessageHeaderCollection";
export { IntPropertyDefinition } from "./PropertyDefinitions/IntPropertyDefinition";
export { IOutParam } from "./Interfaces/IOutParam";
export { IOwnedProperty } from "./Interfaces/IOwnedProperty";
export { IRefParam } from "./Interfaces/IRefParam";
export { ISearchStringProvider } from "./Interfaces/ISearchStringProvider";
export { ISelfValidate } from "./Interfaces/ISelfValidate";
export { ItemChange } from "./Sync/ItemChange";
export { ItemCollection } from "./ComplexProperties/ItemCollection";
export { ItemEvent } from "./Notifications/ItemEvent";
export { ItemFlagStatus } from "./Enumerations/ItemFlagStatus";
export { ItemGroup } from "./Search/ItemGroup";
export { ItemId } from "./ComplexProperties/ItemId";
export { ItemIdCollection } from "./ComplexProperties/ItemIdCollection";
export { ItemIdWrapper } from "./Misc/ItemIdWrapper";
export { ItemIdWrapperList } from "./Misc/ItemIdWrapperList";
export { ItemIndexError } from "./Enumerations/ItemIndexError";
export { ItemInfo } from "./Core/ServiceObjects/Items/ItemInfo";
export { ItemTraversal } from "./Enumerations/ItemTraversal";
export { ItemView } from "./Search/ItemView";
export { ItemWrapper } from "./Misc/ItemWrapper";
export { ITraceListener } from "./Interfaces/ITraceListener";
export { JsonDeserializationNotImplementedException } from "./Exceptions/JsonDeserializationNotImplementedException";
export { JsonNames } from "./Core/JsonNames";
export { JsonObject } from "./Core/JsonObject";
export { JsonParser } from "./Core/JsonParser";
export { JsonSerializationNotImplementedException } from "./Exceptions/JsonSerializationNotImplementedException";
export { JsonTokenizer } from "./Core/JsonTokenizer";
export { JsonTokenType } from "./Enumerations/JsonTokenType";
export { KeywordStatisticsSearchResult } from "./MailboxSearch/KeywordStatisticsSearchResult";
export { LazyMember } from "./Core/LazyMember";
export { LegacyAvailabilityTimeZone } from "./Misc/Availability/LegacyAvailabilityTimeZone";
export { LegacyAvailabilityTimeZoneTime } from "./Misc/Availability/LegacyAvailabilityTimeZoneTime";
export { LegacyFreeBusyStatus } from "./Enumerations/LegacyFreeBusyStatus";
export { ListValuePropertyDefinition } from "./PropertyDefinitions/ListValuePropertyDefinition";
export { LobbyBypass } from "./Enumerations/LobbyBypass";
export { LocationSource } from "./Enumerations/LocationSource";
export { LogicalOperator } from "./Enumerations/LogicalOperator";
export { Mailbox } from "./ComplexProperties/Mailbox";
export { MailboxHoldResult } from "./MailboxSearch/MailboxHoldResult";
export { MailboxHoldStatus } from "./MailboxSearch/MailboxHoldStatus";
export { MailboxQuery } from "./MailboxSearch/MailboxQuery";
export { MailboxSearchLocation } from "./Enumerations/MailboxSearchLocation";
export { MailboxSearchScope } from "./MailboxSearch/MailboxSearchScope";
export { MailboxSearchScopeType } from "./Enumerations/MailboxSearchScopeType";
export { MailboxStatisticsItem } from "./MailboxSearch/MailboxStatisticsItem";
export { MailboxType } from "./Enumerations/MailboxType";
//export {MailTips} from "./operations/MailTips/MailTips";
export { ManagedFolderInformation } from "./ComplexProperties/ManagedFolderInformation";
export { ManagementRoles } from "./Misc/ManagementRoles";
export { MapiPropertyType } from "./Enumerations/MapiPropertyType";
export { MapiTypeConverter } from "./Misc/MapiTypeConverter";
export { MapiTypeConverterMapEntry } from "./Misc/MapiTypeConverterMapEntry";
export { MarkAllItemsAsReadRequest } from "./Core/Requests/MarkAllItemsAsReadRequest";
export { MarkAsJunkRequest } from "./Core/Requests/MarkAsJunkRequest";
export { MarkAsJunkResponse } from "./Core/Responses/MarkAsJunkResponse";
export { MeetingAttendeeType } from "./Enumerations/MeetingAttendeeType";
export { MeetingMessage } from "./Core/ServiceObjects/Items/MeetingMessage";
export { MeetingRequestsDeliveryScope } from "./Enumerations/MeetingRequestsDeliveryScope";
export { MeetingRequestType } from "./Enumerations/MeetingRequestType";
export { MeetingResponseType } from "./Enumerations/MeetingResponseType";
export { MeetingSuggestion } from "./ComplexProperties/MeetingSuggestion";
export { MeetingSuggestionCollection } from "./ComplexProperties/MeetingSuggestionCollection";
export { MeetingTimeZone } from "./ComplexProperties/MeetingTimeZone";
export { MeetingTimeZonePropertyDefinition } from "./PropertyDefinitions/MeetingTimeZonePropertyDefinition";
export { MemberStatus } from "./Enumerations/MemberStatus";
export { MessageBody } from "./ComplexProperties/MessageBody";
export { MessageDisposition } from "./Enumerations/MessageDisposition";
//export {MessageTracking} from "./operations/MessageTracking/MessageTracking";
export { MimeContent } from "./ComplexProperties/MimeContent";
export { MimeContentBase } from "./ComplexProperties/MimeContentBase";
export { MimeContentUTF8 } from "./ComplexProperties/MimeContentUTF8";
export { MobilePhone } from "./Misc/MobilePhone";
export { Month } from "./Enumerations/Month";
export { MoveCopyFolderRequest } from "./Core/Requests/MoveCopyFolderRequest";
export { MoveCopyFolderResponse } from "./Core/Responses/MoveCopyFolderResponse";
export { MoveCopyItemRequest } from "./Core/Requests/MoveCopyItemRequest";
export { MoveCopyItemResponse } from "./Core/Responses/MoveCopyItemResponse";
export { MoveCopyRequest } from "./Core/Requests/MoveCopyRequest";
export { MoveFolderRequest } from "./Core/Requests/MoveFolderRequest";
export { MoveItemRequest } from "./Core/Requests/MoveItemRequest";
export { MultiResponseServiceRequest } from "./Core/Requests/MultiResponseServiceRequest";
export { NameResolution } from "./Misc/NameResolution";
export { NameResolutionCollection } from "./Misc/NameResolutionCollection";
export { NoEndRecurrenceRange } from "./ComplexProperties/Recurrence/Ranges/NoEndRecurrenceRange";
export { NonIndexableItem } from "./MailboxSearch/NonIndexableItem";
export { NonIndexableItemDetailsResult } from "./MailboxSearch/NonIndexableItemDetailsResult";
export { NonIndexableItemParameters, GetNonIndexableItemDetailsParameters, GetNonIndexableItemStatisticsParameters } from "./MailboxSearch/NonIndexableItemParameters";
export { NonIndexableItemStatistic } from "./MailboxSearch/NonIndexableItemStatistic";
export { NormalizedBody } from "./ComplexProperties/NormalizedBody";
export { NotificationEvent } from "./Notifications/NotificationEvent";
export { NotificationEventArgs } from "./Notifications/NotificationEventArgs";
export { NotificationGroup } from "./Notifications/NotificationGroup";
export { NumberedRecurrenceRange } from "./ComplexProperties/Recurrence/Ranges/NumberedRecurrenceRange";
export { OAuthCredentials } from "./Credentials/OAuthCredentials";
export { OccurrenceInfo } from "./ComplexProperties/OccurrenceInfo";
export { OccurrenceInfoCollection } from "./ComplexProperties/OccurrenceInfoCollection";
export { OffsetBasePoint } from "./Enumerations/OffsetBasePoint";
export { OnlineMeetingAccessLevel } from "./Enumerations/OnlineMeetingAccessLevel";
export { OnlineMeetingSettings } from "./ComplexProperties/OnlineMeetingSettings";
export { OofExternalAudience } from "./Enumerations/OofExternalAudience";
export { OofReply } from "./Misc/Availability/OofReply";
export { OofSettings } from "./ComplexProperties/Availability/OofSettings";
export { OofState } from "./Enumerations/OofState";
export { OrderByCollection } from "./Search/OrderByCollection";
export { OutlookAccount } from "./Autodiscover/ConfigurationSettings/Outlook/OutlookAccount";
export { OutlookConfigurationSettings } from "./Autodiscover/ConfigurationSettings/Outlook/OutlookConfigurationSettings";
export { OutlookProtocol } from "./Autodiscover/ConfigurationSettings/Outlook/OutlookProtocol";
export { OutlookProtocolType } from "./Enumerations/OutlookProtocolType";
export { OutlookUser } from "./Autodiscover/ConfigurationSettings/Outlook/OutlookUser";
export { PagedView } from "./Search/PagedView";
export { PartnerTokenCredentials } from "./Credentials/PartnerTokenCredentials";
//export {PermissionSetPropertyDefinition} from "./PropertyDefinitions/PermissionCollectionPropertyDefinition";
export { PermissionScope } from "./Enumerations/PermissionScope";
export { PermissionSetPropertyDefinition } from "./PropertyDefinitions/PermissionSetPropertyDefinition";
//export {Persona} from "./operations/Persona/Persona";
export { PersonaPostalAddress } from "./ComplexProperties/PersonaPostalAddress";
export { PhoneCall } from "./UnifiedMessaging/PhoneCall";
export { PhoneCallId } from "./UnifiedMessaging/PhoneCallId";
export { PhoneCallState } from "./Enumerations/PhoneCallState";
export { PhoneEntity } from "./ComplexProperties/PhoneEntity";
export { PhoneEntityCollection } from "./ComplexProperties/PhoneEntityCollection";
export { PhoneNumberDictionary } from "./ComplexProperties/PhoneNumberDictionary";
export { PhoneNumberEntry } from "./ComplexProperties/PhoneNumberEntry";
export { PhoneNumberKey } from "./Enumerations/PhoneNumberKey";
export { PhysicalAddressDictionary } from "./ComplexProperties/PhysicalAddressDictionary";
export { PhysicalAddressEntry } from "./ComplexProperties/PhysicalAddressEntry";
export { PhysicalAddressIndex } from "./Enumerations/PhysicalAddressIndex";
export { PhysicalAddressKey } from "./Enumerations/PhysicalAddressKey";
export { PlayOnPhoneRequest } from "./Core/Requests/PlayOnPhoneRequest";
export { PlayOnPhoneResponse } from "./Core/Responses/PlayOnPhoneResponse";
export { PolicyTag } from "./ComplexProperties/PolicyTag";
export { PostItem } from "./Core/ServiceObjects/Items/PostItem";
export { PostReply } from "./Core/ServiceObjects/ResponseObjects/PostReply";
export { Presenters } from "./Enumerations/Presenters";
export { PreviewItemBaseShape } from "./Enumerations/PreviewItemBaseShape";
export { PreviewItemMailbox } from "./MailboxSearch/PreviewItemMailbox";
export { PreviewItemResponseShape } from "./MailboxSearch/PreviewItemResponseShape";
export { PrivilegedLogonType } from "./Enumerations/PrivilegedLogonType";
export { PrivilegedUserId } from "./Misc/PrivilegedUserId";
export { PrivilegedUserIdBudgetType } from "./Enumerations/PrivilegedUserIdBudgetType";
export { PropertyBag } from "./Core/PropertyBag";
export { PropertyDefinition } from "./PropertyDefinitions/PropertyDefinition";
export { PropertyDefinitionBase } from "./PropertyDefinitions/PropertyDefinitionBase";
export { PropertyDefinitionFlags } from "./Enumerations/PropertyDefinitionFlags";
export { PropertyException } from "./Exceptions/PropertyException";
export { PropertySet } from "./Core/PropertySet";
export { ProtocolConnection } from "./Autodiscover/ProtocolConnection";
export { ProtocolConnectionCollection } from "./Autodiscover/ProtocolConnectionCollection";
export { PullSubscription } from "./Notifications/PullSubscription";
export { PushSubscription } from "./Notifications/PushSubscription";
export { RecurrencePropertyDefinition } from "./PropertyDefinitions/RecurrencePropertyDefinition";
export { RecurrenceRange } from "./ComplexProperties/Recurrence/Ranges/RecurrenceRange";
export { RecurringAppointmentMasterId } from "./ComplexProperties/RecurringAppointmentMasterId";
//export {Reminder} from "./operations/ExchangeMailboxData/Reminder";
export { RemoveDelegateRequest } from "./Core/Requests/RemoveDelegateRequest";
export { RemoveFromCalendar } from "./Core/ServiceObjects/ResponseObjects/RemoveFromCalendar";
export { RenderingMode } from "./Enumerations/RenderingMode";
export { ResolveNameSearchLocation } from "./Enumerations/ResolveNameSearchLocation";
export { ResolveNamesRequest } from "./Core/Requests/ResolveNamesRequest";
export { ResolveNamesResponse } from "./Core/Responses/ResolveNamesResponse";
export { ResponseActions } from "./Enumerations/ResponseActions";
export { ResponseMessage } from "./Core/ServiceObjects/ResponseObjects/ResponseMessage";
export { ResponseMessageType } from "./Enumerations/ResponseMessageType";
export { ResponseObject } from "./Core/ServiceObjects/ResponseObjects/ResponseObject";
export { ResponseObjectsPropertyDefinition } from "./PropertyDefinitions/ResponseObjectsPropertyDefinition";
export { RetentionActionType } from "./Enumerations/RetentionActionType";
export { RetentionPolicyTag } from "./Elc/RetentionPolicyTag";
export { RetentionTagBase } from "./ComplexProperties/RetentionTagBase";
export { RetentionType } from "./Enumerations/RetentionType";
export { Rule } from "./ComplexProperties/Rule";
export { RuleActions } from "./ComplexProperties/RuleActions";
export { RuleCollection } from "./ComplexProperties/RuleCollection";
export { RuleError } from "./ComplexProperties/RuleError";
export { RuleErrorCode } from "./Enumerations/RuleErrorCode";
export { RuleErrorCollection } from "./ComplexProperties/RuleErrorCollection";
export { RuleOperation } from "./ComplexProperties/RuleOperation";
export { RuleOperationError } from "./ComplexProperties/RuleOperationError";
export { RuleOperationErrorCollection } from "./ComplexProperties/RuleOperationErrorCollection";
export { RulePredicateDateRange } from "./ComplexProperties/RulePredicateDateRange";
export { RulePredicates } from "./ComplexProperties/RulePredicates";
export { RulePredicateSizeRange } from "./ComplexProperties/RulePredicateSizeRange";
export { RuleProperty } from "./Enumerations/RuleProperty";
//export {SafeXmlDocument} from "./Security/SafeXmlDocument";
export { SafeXmlFactory } from "./Security/SafeXmlFactory";
//export {SafeXmlSchema} from "./Security/SafeXmlSchema";
export { ScopedDateTimePropertyDefinition } from "./PropertyDefinitions/ScopedDateTimePropertyDefinition";
export { SearchableMailbox } from "./MailboxSearch/SearchableMailbox";
export { SearchFolderParameters } from "./ComplexProperties/SearchFolderParameters";
export { SearchFolderTraversal } from "./Enumerations/SearchFolderTraversal";
export { SearchMailboxesParameters } from "./MailboxSearch/SearchMailboxesParameters";
export { SearchMailboxesRequest } from "./Core/Requests/SearchMailboxesRequest";
export { SearchMailboxesResponse } from "./Core/Responses/SearchMailboxesResponse";
export { SearchMailboxesResult } from "./MailboxSearch/SearchMailboxesResult";
export { SearchPageDirection } from "./Enumerations/SearchPageDirection";
export { SearchPreviewItem } from "./MailboxSearch/SearchPreviewItem";
export { SearchRefinerItem } from "./MailboxSearch/SearchRefinerItem";
export { SearchResultType } from "./Enumerations/SearchResultType";
export { SecurityTimestamp } from "./Security/SecurityTimestamp";
export { SeekToConditionItemView } from "./Search/SeekToConditionItemView";
export { SendCancellationsMode } from "./Enumerations/SendCancellationsMode";
export { SendInvitationsMode } from "./Enumerations/SendInvitationsMode";
export { SendInvitationsOrCancellationsMode } from "./Enumerations/SendInvitationsOrCancellationsMode";
export { SendItemRequest } from "./Core/Requests/SendItemRequest";
export { SendPrompt } from "./Enumerations/SendPrompt";
export { Sensitivity } from "./Enumerations/Sensitivity";
export { ServerBusyException } from "./Exceptions/ServerBusyException";
//export {ServiceConfiguration} from "./operations/ServiceConfiguration/ServiceConfiguration";
export { ServiceError } from "./Enumerations/ServiceError";
export { ServiceErrorHandling } from "./Enumerations/ServiceErrorHandling";
export { ServiceId } from "./ComplexProperties/ServiceId";
export { ServiceJsonDeserializationException } from "./Exceptions/ServiceJsonDeserializationException";
export { ServiceLocalException } from "./Exceptions/ServiceLocalException";
export { ServiceObjectInfo } from "./Core/ServiceObjects/ServiceObjectInfo";
export { ServiceObjectPropertyDefinition } from "./PropertyDefinitions/ServiceObjectPropertyDefinition";
export { ServiceObjectPropertyException } from "./Exceptions/ServiceObjectPropertyException";
export { ServiceObjectType } from "./Enumerations/ServiceObjectType";
export { ServiceRemoteException } from "./Exceptions/ServiceRemoteException";
export { ServiceRequestBase } from "./Core/Requests/ServiceRequestBase";
export { ServiceRequestException } from "./Exceptions/ServiceRequestException";
export { ServiceResponse } from "./Core/Responses/ServiceResponse";
export { ServiceResponseCollection } from "./Core/Responses/ServiceResponseCollection";
export { ServiceResponseException } from "./Exceptions/ServiceResponseException";
export { ServiceResult } from "./Enumerations/ServiceResult";
export { ServiceValidationException } from "./Exceptions/ServiceValidationException";
export { ServiceVersionException } from "./Exceptions/ServiceVersionException";
export { ServiceXmlDeserializationException } from "./Exceptions/ServiceXmlDeserializationException";
export { ServiceXmlSerializationException } from "./Exceptions/ServiceXmlSerializationException";
export { SetClientExtensionAction } from "./ComplexProperties/SetClientExtensionAction";
export { SetClientExtensionActionId } from "./Enumerations/SetClientExtensionActionId";
export { SetClientExtensionRequest } from "./Core/Requests/SetClientExtensionRequest";
export { SetEncryptionConfigurationRequest } from "./Core/Requests/SetEncryptionConfigurationRequest";
export { SetEncryptionConfigurationResponse } from "./Core/Responses/SetEncryptionConfigurationResponse";
export { SetHoldOnMailboxesParameters } from "./MailboxSearch/SetHoldOnMailboxesParameters";
export { SetHoldOnMailboxesRequest } from "./Core/Requests/SetHoldOnMailboxesRequest";
export { SetHoldOnMailboxesResponse } from "./Core/Responses/SetHoldOnMailboxesResponse";
export { SetRuleOperation } from "./ComplexProperties/SetRuleOperation";
export { SetTeamMailboxRequest } from "./Core/Requests/SetTeamMailboxRequest";
export { SetUserOofSettingsRequest } from "./Core/Requests/SetUserOofSettingsRequest";
//export {Sharing} from "./operations/Sharing/Sharing";
export { SimplePropertyBag } from "./Core/SimplePropertyBag";
export { SimpleServiceRequestBase } from "./Core/Requests/SimpleServiceRequestBase";
export { SoapFaultDetails } from "./Misc/SoapFaultDetails";
export { SortDirection } from "./Enumerations/SortDirection";
export { StandardUser } from "./Enumerations/StandardUser";
export { StartTimeZonePropertyDefinition } from "./PropertyDefinitions/StartTimeZonePropertyDefinition";
export { StreamingSubscription } from "./Notifications/StreamingSubscription";
export { StreamingSubscriptionConnection, ResponseHeaderDelegate } from "./Notifications/StreamingSubscriptionConnection";
export { StringList } from "./ComplexProperties/StringList";
export { StringPropertyDefinition } from "./PropertyDefinitions/StringPropertyDefinition";
export { Strings } from "./Strings";
export { SubscribeRequest } from "./Core/Requests/SubscribeRequest";
export { SubscribeResponse } from "./Core/Responses/SubscribeResponse";
export { SubscribeToPullNotificationsRequest } from "./Core/Requests/SubscribeToPullNotificationsRequest";
export { SubscribeToPushNotificationsRequest } from "./Core/Requests/SubscribeToPushNotificationsRequest";
export { SubscribeToStreamingNotificationsRequest } from "./Core/Requests/SubscribeToStreamingNotificationsRequest";
export { SubscriptionBase } from "./Notifications/SubscriptionBase";
export { SubscriptionErrorEventArgs } from "./Notifications/SubscriptionErrorEventArgs";
export { Suggestion } from "./ComplexProperties/Availability/Suggestion";
export { SuggestionQuality } from "./Enumerations/SuggestionQuality";
export { SuggestionsResponse } from "./Core/Responses/SuggestionsResponse";
export { SuppressReadReceipt } from "./Core/ServiceObjects/ResponseObjects/SuppressReadReceipt";
export { SyncFolderHierarchyRequest } from "./Core/Requests/SyncFolderHierarchyRequest";
export { SyncFolderHierarchyResponse } from "./Core/Responses/SyncFolderHierarchyResponse";
export { SyncFolderItemsRequest } from "./Core/Requests/SyncFolderItemsRequest";
export { SyncFolderItemsResponse } from "./Core/Responses/SyncFolderItemsResponse";
export { SyncFolderItemsScope } from "./Enumerations/SyncFolderItemsScope";
export { SyncResponse } from "./Core/Responses/SyncResponse";
export { Task } from "./Core/ServiceObjects/Items/Task";
export { TaskDelegationState } from "./Enumerations/TaskDelegationState";
export { TaskDelegationStatePropertyDefinition } from "./PropertyDefinitions/TaskDelegationStatePropertyDefinition";
export { TaskMode } from "./Enumerations/TaskMode";
export { TaskStatus } from "./Enumerations/TaskStatus";
export { TaskSuggestion } from "./ComplexProperties/TaskSuggestion";
export { TaskSuggestionCollection } from "./ComplexProperties/TaskSuggestionCollection";
export { TeamMailboxLifecycleState } from "./Enumerations/TeamMailboxLifecycleState";
export { TextBody } from "./ComplexProperties/TextBody";
export { Time } from "./Misc/Time";
export { TimeChange } from "./ComplexProperties/TimeChange";
export { TimeChangeRecurrence } from "./ComplexProperties/TimeChangeRecurrence";
export { TimeSpanPropertyDefinition } from "./PropertyDefinitions/TimeSpanPropertyDefinition";
export { TimeSuggestion } from "./ComplexProperties/Availability/TimeSuggestion";
export { TimeWindow } from "./Misc/Availability/TimeWindow";
export { TimeZoneConversionException } from "./Exceptions/TimeZoneConversionException";
export { TimeZonePropertyDefinition } from "./PropertyDefinitions/TimeZonePropertyDefinition";
export { TimeZoneTransitionGroup } from "./ComplexProperties/TimeZones/TimeZoneTransitionGroup";
export { TokenCredentials } from "./Credentials/TokenCredentials";
export { TraceFlags } from "./Enumerations/TraceFlags";
export { TypedPropertyDefinition } from "./PropertyDefinitions/TypedPropertyDefinition";
//export {UnifiedContactStore} from "./operations/UnifiedContactStore/UnifiedContactStore";
export { UnifiedMessaging } from "./UnifiedMessaging/UnifiedMessaging";
export { UninstallAppRequest } from "./Core/Requests/UninstallAppRequest";
export { UninstallAppResponse } from "./Core/Responses/UninstallAppResponse";
export { UniqueBody } from "./ComplexProperties/UniqueBody";
export { UnpinTeamMailboxRequest } from "./Core/Requests/UnpinTeamMailboxRequest";
export { UnsubscribeRequest } from "./Core/Requests/UnsubscribeRequest";
export { UpdateDelegateRequest } from "./Core/Requests/UpdateDelegateRequest";
export { UpdateFolderRequest } from "./Core/Requests/UpdateFolderRequest";
export { UpdateFolderResponse } from "./Core/Responses/UpdateFolderResponse";
export { UpdateInboxRulesException } from "./Exceptions/UpdateInboxRulesException";
export { UpdateInboxRulesRequest } from "./Core/Requests/UpdateInboxRulesRequest";
export { UpdateInboxRulesResponse } from "./Core/Responses/UpdateInboxRulesResponse";
export { UpdateItemRequest } from "./Core/Requests/UpdateItemRequest";
export { UpdateItemResponse } from "./Core/Responses/UpdateItemResponse";
export { UpdateUserConfigurationRequest } from "./Core/Requests/UpdateUserConfigurationRequest";
export { Uri } from "./Uri";
export { UrlEntity } from "./ComplexProperties/UrlEntity";
export { UrlEntityCollection } from "./ComplexProperties/UrlEntityCollection";
export { UserConfiguration } from "./Misc/UserConfiguration";
export { UserConfigurationDictionary } from "./ComplexProperties/UserConfigurationDictionary";
export { UserConfigurationDictionaryObjectType } from "./Enumerations/UserConfigurationDictionaryObjectType";
export { UserConfigurationProperties } from "./Enumerations/UserConfigurationProperties";
export { UserId } from "./ComplexProperties/UserId";
export { UserSettingError } from "./Autodiscover/UserSettingError";
export { UserSettingName } from "./Enumerations/UserSettingName";
//export {Utilities} from "./operations/ExchangeMailboxData/Utilities";
export { DiscoverySchemaChanges } from "./MailboxSearch/Versioning";
export { ViewBase } from "./Search/ViewBase";
export { ViewFilter } from "./Enumerations/ViewFilter";
export { VotingInformation } from "./ComplexProperties/VotingInformation";
export { VotingOptionData } from "./ComplexProperties/VotingOptionData";
export { WebClientUrl } from "./Autodiscover/WebClientUrl";
export { WebClientUrlCollection } from "./Autodiscover/WebClientUrlCollection";
export { WebCredentials } from "./Credentials/WebCredentials";
export { WellKnownFolderName } from "./Enumerations/WellKnownFolderName";
export { WindowsLiveCredentials } from "./Credentials/WindowsLiveCredentials";
export { WorkingHours } from "./ComplexProperties/Availability/WorkingHours";
export { WorkingPeriod } from "./ComplexProperties/Availability/WorkingPeriod";
export { WSSecurityBasedCredentials } from "./Credentials/WSSecurityBasedCredentials";
export { WSSecurityUtilityIdSignedXml } from "./Credentials/WSSecurityUtilityIdSignedXml";
export { X509CertificateCredentials } from "./Credentials/X509CertificateCredentials";
export { XmlAttributeNames } from "./Core/XmlAttributeNames";
//export {XmlDtdException} from "./Security/XmlDtdException";
export { XmlElementNames } from "./Core/XmlElementNames";
export { XmlNamespace } from "./Enumerations/XmlNamespace"; | the_stack |
import * as assert from 'assert';
import * as cp from 'child_process';
import * as sinon from 'sinon';
import * as stream from 'stream';
import { OutputChannel, window } from 'vscode';
import { Constants } from '../../src/Constants';
import * as outputCommandHelper from '../../src/helpers';
import * as shell from '../../src/helpers/shell';
import { GanacheService } from '../../src/services';
import * as GanacheServiceClient from '../../src/services/ganache/GanacheServiceClient';
import { UrlValidator } from '../../src/validators/UrlValidator';
const defaultPort = '8545';
const testPortsList = ['8451', '8452', '8453'];
describe('Unit tests GanacheService', () => {
let streamMock: stream.Readable;
let processMock: cp.ChildProcess;
let channel: OutputChannel;
beforeEach(() => {
streamMock = {
on(_event: 'data', _listener: (chunk: any) => void): any { /* empty */ },
removeAllListeners() { /* empty */ },
} as stream.Readable;
processMock = {
on(_event: 'exit', _listener: (code: number, signal: string) => void): any { /* empty */ },
kill() { /* empty */ },
removeAllListeners() { /* empty */ },
stderr: streamMock,
stdout: streamMock,
} as cp.ChildProcess;
channel = {
appendLine(_value: string): void { /* empty */ },
dispose() { /* empty */ },
show() { /* empty */ },
} as OutputChannel;
});
afterEach(() => {
sinon.restore();
});
['-1', 'qwe', 'asd8545', '65536', '70000', 0].forEach((port) => {
it(`startGanacheServer should throw an exception if port is invalid(${port})`, async () => {
// Arrange
const urlValidatorSpy = sinon.spy(UrlValidator, 'validatePort');
// Act and Assert
await assert.rejects(GanacheService.startGanacheServer(port));
assert.strictEqual(urlValidatorSpy.called, true, 'should call url validator');
});
});
['1', '65535', '8454', 8000, 8454].forEach((port) => {
it(`startGanacheServer should pass validation if port is ${port}`, async () => {
// Arrange
const urlValidatorSpy = sinon.spy(UrlValidator, 'validatePort');
sinon.stub(shell, 'findPid').returns(Promise.resolve(312));
sinon.stub(GanacheServiceClient, 'isGanacheServer').returns(Promise.resolve(true));
// Act
const result = await GanacheService.startGanacheServer(port);
// Assert
assert.strictEqual(urlValidatorSpy.called, true);
assert.deepStrictEqual(result, { pid: 312, port });
});
});
it('startGanacheServer should throw an exception if port is busy', async () => {
// Arrange
sinon.stub(shell, 'findPid').returns(Promise.resolve(312));
sinon.stub(GanacheServiceClient, 'isGanacheServer').returns(Promise.resolve(false));
// Act and Assert
await assert.rejects(GanacheService.startGanacheServer(defaultPort));
});
it('startGanacheServer should execute npx cmd if port is valid and free', async () => {
// Arrange
const urlValidatorSpy = sinon.spy(UrlValidator, 'validatePort');
const spawnStub = sinon.stub(outputCommandHelper, 'spawnProcess').returns(processMock as cp.ChildProcess);
sinon.stub(shell, 'findPid').returns(Promise.resolve(Number.NaN));
sinon.stub(window, 'createOutputChannel').returns(channel as OutputChannel);
sinon.stub(GanacheServiceClient, 'waitGanacheStarted');
// Act
await GanacheService.startGanacheServer(defaultPort);
// Assert
assert.strictEqual(urlValidatorSpy.called, true);
assert.strictEqual(spawnStub.called, true);
assert.strictEqual(spawnStub.getCall(0).args[1], 'npx');
assert.deepStrictEqual(spawnStub.getCall(0).args[2], ['ganache-cli', `-p ${defaultPort}`]);
});
it('startGanacheServer if server was not started should throw exception and dispose all', async () => {
// Arrange
const channelDisposeSpy = sinon.spy(channel, 'dispose');
const killProcessStub = sinon.stub(processMock, 'kill');
const processRemoveAllListenersSpy = sinon.spy(processMock, 'removeAllListeners');
sinon.spy(UrlValidator, 'validatePort');
sinon.stub(shell, 'findPid').returns(Promise.resolve(Number.NaN));
sinon.stub(outputCommandHelper, 'spawnProcess').returns(processMock as cp.ChildProcess);
sinon.stub(GanacheServiceClient, 'waitGanacheStarted')
.throws(new Error(Constants.ganacheCommandStrings.cannotStartServer));
sinon.stub(window, 'createOutputChannel').returns(channel as OutputChannel);
// Act and Assert
await assert.rejects(
GanacheService.startGanacheServer(defaultPort),
Error,
Constants.ganacheCommandStrings.cannotStartServer,
);
assert.strictEqual(killProcessStub.calledOnce, true);
assert.strictEqual(channelDisposeSpy.calledOnce, true);
assert.strictEqual(processRemoveAllListenersSpy.calledOnce, true);
});
describe('Test cases with "ganacheProcesses"', () => {
beforeEach(() => {
GanacheService.ganacheProcesses[testPortsList[0]] = {
output: channel,
port: testPortsList[0],
process: processMock,
} as GanacheService.IGanacheProcess;
GanacheService.ganacheProcesses[testPortsList[1]] = {
output: channel,
port: testPortsList[1],
process: processMock,
} as GanacheService.IGanacheProcess;
GanacheService.ganacheProcesses[testPortsList[2]] = {
pid: 321,
port: testPortsList[2],
} as GanacheService.IGanacheProcess;
});
afterEach(() => {
Object.keys(GanacheService.ganacheProcesses).forEach((port) => {
delete GanacheService.ganacheProcesses[port];
});
});
it('stopGanacheServer should kill process and remove element from "ganacheProcesses" list', async () => {
// Arrange
const killPidStub = sinon.stub(shell, 'killPid');
const killProcessStub = sinon.stub(processMock, 'kill');
const processSpy = sinon.spy(processMock, 'removeAllListeners');
const channelDisposeSpy = sinon.spy(channel, 'dispose');
GanacheService.ganacheProcesses[defaultPort] = {
output: channel,
port: defaultPort,
process: processMock,
} as GanacheService.IGanacheProcess;
// Act
await GanacheService.stopGanacheServer(defaultPort);
// Assert
assert.strictEqual(GanacheService.ganacheProcesses[defaultPort], undefined);
assert.strictEqual(killPidStub.called, false, '"killPid" shouldn\'t be executed for target process');
assert.strictEqual(killProcessStub.calledOnce, true, '"kill" should be executed for target process');
assert.strictEqual(processSpy.calledOnce, true, '"removeAllListeners" should be executed for target process');
assert.strictEqual(channelDisposeSpy.calledOnce, true, '"dispose" should be executed for channel');
});
it('stopGanacheServer should kill out of band process and remove element from ganacheProcesses list', async () => {
// Arrange
const killPidStub = sinon.stub(shell, 'killPid');
const killProcessStub = sinon.stub(processMock, 'kill');
const processSpy = sinon.spy(processMock, 'removeAllListeners');
const channelDisposeSpy = sinon.spy(channel, 'dispose');
GanacheService.ganacheProcesses[defaultPort] = {
pid: 321,
port: defaultPort,
} as GanacheService.IGanacheProcess;
// Act
await GanacheService.stopGanacheServer(defaultPort);
// Assert
assert.strictEqual(GanacheService.ganacheProcesses[defaultPort], undefined);
assert.strictEqual(killPidStub.called, true, '"killPid" should be executed for target process');
assert.strictEqual(killProcessStub.calledOnce, false, '"kill" shouldn\'t be executed for target process');
assert.strictEqual(processSpy.calledOnce, false, '"removeAllListeners" shouldn\'t be executed for process');
assert.strictEqual(channelDisposeSpy.calledOnce, false, '"dispose" shouldn\'t be executed for channel');
});
it('stopGanacheServer should not do anything if passed port not presented in "ganacheProcesses" list', async () => {
// Arrange
const killPidStub = sinon.stub(shell, 'killPid');
const killProcessStub = sinon.stub(processMock, 'kill');
const processSpy = sinon.spy(processMock, 'removeAllListeners');
const channelDisposeSpy = sinon.spy(channel, 'dispose');
// Act
await GanacheService.stopGanacheServer(defaultPort);
// Assert
assert.strictEqual(GanacheService.ganacheProcesses[defaultPort], undefined);
assert.strictEqual(killPidStub.called, false, '"killPid" should be executed for target process');
assert.strictEqual(killProcessStub.called, false, '"kill" should be executed for target process');
assert.strictEqual(processSpy.called, false, '"removeAllListeners" not should be executed for target process');
assert.strictEqual(channelDisposeSpy.called, false, '"dispose" should not be executed for channel');
});
it('dispose should kill all process and cleanup "ganacheProcesses" list', async () => {
// Arrange
const killPidStub = sinon.stub(shell, 'killPid');
const killProcessStub = sinon.stub(processMock, 'kill');
// Act
await GanacheService.dispose();
// Assert
assert.strictEqual(GanacheService.ganacheProcesses[defaultPort], undefined);
assert.strictEqual(GanacheService.ganacheProcesses[testPortsList[0]], undefined);
assert.strictEqual(GanacheService.ganacheProcesses[testPortsList[1]], undefined);
assert.strictEqual(GanacheService.ganacheProcesses[testPortsList[2]], undefined);
assert.strictEqual(killProcessStub.callCount, 2, '"kill" should be executed for two target process');
assert.strictEqual(killPidStub.callCount, 0, '"killPid" shouldn\'t be executed');
});
});
const getPortFromUrlCases = [
{ url: 'http://example.com:8454', expectation: '8454' },
{ url: 'ftp://example.com:123', expectation: '123' },
{ url: 'http://example.com', expectation: Constants.defaultLocalhostPort.toString() },
{ url: 'http:8454', expectation: '8454' },
];
getPortFromUrlCases.forEach((testcase) => {
it(`getPortFromUrl should extract port ${testcase.expectation} from url ${testcase.url}`, async () => {
// Act
const port = await GanacheService.getPortFromUrl(testcase.url);
// Assert
assert.strictEqual(port, testcase.expectation);
});
});
}); | the_stack |
import { useState, useLayoutEffect, useMemo } from 'react';
export interface Position {
position: number;
extent: number;
content: string;
line: number;
}
type History = [Position, string];
const observerSettings = {
characterData: true,
characterDataOldValue: true,
childList: true,
subtree: true,
};
const getCurrentRange = () => window.getSelection()!.getRangeAt(0)!;
const setCurrentRange = (range: Range) => {
const selection = window.getSelection()!;
selection.empty();
selection.addRange(range);
};
const isUndoRedoKey = (event: KeyboardEvent): boolean =>
(event.metaKey || event.ctrlKey) && !event.altKey && event.code === 'KeyZ';
const toString = (element: HTMLElement): string => {
const queue: Node[] = [element.firstChild!];
let content = '';
let node: Node;
while ((node = queue.pop()!)) {
if (node.nodeType === Node.TEXT_NODE) {
content += node.textContent;
} else if (node.nodeType === Node.ELEMENT_NODE && node.nodeName === 'BR') {
content += '\n';
}
if (node.nextSibling) queue.push(node.nextSibling);
if (node.firstChild) queue.push(node.firstChild);
}
// contenteditable Quirk: Without plaintext-only a pre/pre-wrap element must always
// end with at least one newline character
if (content[content.length - 1] !== '\n') content += '\n';
return content;
};
const setStart = (range: Range, node: Node, offset: number) => {
if (offset < node.textContent!.length) {
range.setStart(node, offset);
} else {
range.setStartAfter(node);
}
};
const setEnd = (range: Range, node: Node, offset: number) => {
if (offset < node.textContent!.length) {
range.setEnd(node, offset);
} else {
range.setEndAfter(node);
}
};
const getPosition = (element: HTMLElement): Position => {
// Firefox Quirk: Since plaintext-only is unsupported the position
// of the text here is retrieved via a range, rather than traversal
// as seen in makeRange()
const range = getCurrentRange();
const extent = !range.collapsed ? range.toString().length : 0;
const untilRange = document.createRange();
untilRange.setStart(element, 0);
untilRange.setEnd(range.startContainer, range.startOffset);
let content = untilRange.toString();
const position = content.length;
const lines = content.split('\n');
const line = lines.length - 1;
content = lines[line];
return { position, extent, content, line };
};
const makeRange = (
element: HTMLElement,
start: number,
end?: number
): Range => {
if (start <= 0) start = 0;
if (!end || end < 0) end = start;
const range = document.createRange();
const queue: Node[] = [element.firstChild!];
let current = 0;
let node: Node;
let position = start;
while ((node = queue[queue.length - 1])) {
if (node.nodeType === Node.TEXT_NODE) {
const length = node.textContent!.length;
if (current + length >= position) {
const offset = position - current;
if (position === start) {
setStart(range, node, offset);
if (end !== start) {
position = end;
continue;
} else {
break;
}
} else {
setEnd(range, node, offset);
break;
}
}
current += node.textContent!.length;
} else if (node.nodeType === Node.ELEMENT_NODE && node.nodeName === 'BR') {
if (current + 1 >= position) {
if (position === start) {
setStart(range, node, 0);
if (end !== start) {
position = end;
continue;
} else {
break;
}
} else {
setEnd(range, node, 0);
break;
}
}
current++;
}
queue.pop();
if (node.nextSibling) queue.push(node.nextSibling);
if (node.firstChild) queue.push(node.firstChild);
}
return range;
};
interface State {
observer: MutationObserver;
disconnected: boolean;
onChange(text: string, position: Position): void;
queue: MutationRecord[];
history: History[];
historyAt: number;
position: Position | null;
}
export interface Options {
disabled?: boolean;
indentation?: number;
}
export interface Edit {
/** Replaces the entire content of the editable while adjusting the caret position. */
update(content: string): void;
/** Inserts new text at the caret position while deleting text in range of the offset (which accepts negative offsets). */
insert(append: string, offset?: number): void;
/** Positions the caret where specified */
move(pos: number | { row: number; column: number }): void;
/** Returns the current editor state, as usually received in onChange */
getState(): { text: string; position: Position };
}
export const useEditable = (
elementRef: { current: HTMLElement | undefined | null },
onChange: (text: string, position: Position) => void,
opts?: Options
): Edit => {
if (!opts) opts = {};
const unblock = useState([])[1];
const state: State = useState(() => {
const state: State = {
observer: null as any,
disconnected: false,
onChange,
queue: [],
history: [],
historyAt: -1,
position: null,
};
if (typeof MutationObserver !== 'undefined') {
state.observer = new MutationObserver(batch => {
state.queue.push(...batch);
});
}
return state;
})[0];
const edit = useMemo<Edit>(
() => ({
update(content: string) {
const { current: element } = elementRef;
if (element) {
const position = getPosition(element);
const prevContent = toString(element);
position.position += content.length - prevContent.length;
state.position = position;
state.onChange(content, position);
}
},
insert(append: string, deleteOffset?: number) {
const { current: element } = elementRef;
if (element) {
let range = getCurrentRange();
range.deleteContents();
range.collapse();
const position = getPosition(element);
const offset = deleteOffset || 0;
const start = position.position + (offset < 0 ? offset : 0);
const end = position.position + (offset > 0 ? offset : 0);
range = makeRange(element, start, end);
range.deleteContents();
if (append) range.insertNode(document.createTextNode(append));
setCurrentRange(makeRange(element, start + append.length));
}
},
move(pos: number | { row: number; column: number }) {
const { current: element } = elementRef;
if (element) {
element.focus();
let position = 0;
if (typeof pos === 'number') {
position = pos;
} else {
const lines = toString(element).split('\n').slice(0, pos.row);
if (pos.row) position += lines.join('\n').length + 1;
position += pos.column;
}
setCurrentRange(makeRange(element, position));
}
},
getState() {
const { current: element } = elementRef;
const text = toString(element!);
const position = getPosition(element!);
return { text, position };
},
}),
[]
);
// Only for SSR / server-side logic
if (typeof navigator !== 'object') return edit;
useLayoutEffect(() => {
state.onChange = onChange;
if (!elementRef.current || opts!.disabled) return;
state.disconnected = false;
state.observer.observe(elementRef.current, observerSettings);
if (state.position) {
const { position, extent } = state.position;
setCurrentRange(
makeRange(elementRef.current, position, position + extent)
);
}
return () => {
state.observer.disconnect();
};
});
useLayoutEffect(() => {
if (!elementRef.current || opts!.disabled) {
state.history.length = 0;
state.historyAt = -1;
return;
}
const element = elementRef.current!;
if (state.position) {
element.focus();
const { position, extent } = state.position;
setCurrentRange(makeRange(element, position, position + extent));
}
const prevWhiteSpace = element.style.whiteSpace;
const prevContentEditable = element.contentEditable;
let hasPlaintextSupport = true;
try {
// Firefox and IE11 do not support plaintext-only mode
element.contentEditable = 'plaintext-only';
} catch (_error) {
element.contentEditable = 'true';
hasPlaintextSupport = false;
}
if (prevWhiteSpace !== 'pre') element.style.whiteSpace = 'pre-wrap';
if (opts!.indentation) {
element.style.tabSize = (element.style as any).MozTabSize =
'' + opts!.indentation;
}
const indentPattern = `${' '.repeat(opts!.indentation || 0)}`;
const indentRe = new RegExp(`^(?:${indentPattern})`);
const blanklineRe = new RegExp(`^(?:${indentPattern})*(${indentPattern})$`);
let _trackStateTimestamp: number;
const trackState = (ignoreTimestamp?: boolean) => {
if (!elementRef.current || !state.position) return;
const content = toString(element);
const position = getPosition(element);
const timestamp = new Date().valueOf();
// Prevent recording new state in list if last one has been new enough
const lastEntry = state.history[state.historyAt];
if (
(!ignoreTimestamp && timestamp - _trackStateTimestamp < 500) ||
(lastEntry && lastEntry[1] === content)
) {
_trackStateTimestamp = timestamp;
return;
}
const at = ++state.historyAt;
state.history[at] = [position, content];
state.history.splice(at + 1);
if (at > 500) {
state.historyAt--;
state.history.shift();
}
};
const disconnect = () => {
state.observer.disconnect();
state.disconnected = true;
};
const flushChanges = () => {
state.queue.push(...state.observer.takeRecords());
const position = getPosition(element);
if (state.queue.length) {
disconnect();
const content = toString(element);
state.position = position;
let mutation: MutationRecord | void;
let i = 0;
while ((mutation = state.queue.pop())) {
if (mutation.oldValue !== null)
mutation.target.textContent = mutation.oldValue;
for (i = mutation.removedNodes.length - 1; i >= 0; i--)
mutation.target.insertBefore(
mutation.removedNodes[i],
mutation.nextSibling
);
for (i = mutation.addedNodes.length - 1; i >= 0; i--)
if (mutation.addedNodes[i].parentNode)
mutation.target.removeChild(mutation.addedNodes[i]);
}
state.onChange(content, position);
}
};
const onKeyDown = (event: HTMLElementEventMap['keydown']) => {
if (event.defaultPrevented || event.target !== element) {
return;
} else if (state.disconnected) {
// React Quirk: It's expected that we may lose events while disconnected, which is why
// we'd like to block some inputs if they're unusually fast. However, this always
// coincides with React not executing the update immediately and then getting stuck,
// which can be prevented by issuing a dummy state change.
event.preventDefault();
return unblock([]);
}
if (isUndoRedoKey(event)) {
event.preventDefault();
let history: History;
if (!event.shiftKey) {
const at = --state.historyAt;
history = state.history[at];
if (!history) state.historyAt = 0;
} else {
const at = ++state.historyAt;
history = state.history[at];
if (!history) state.historyAt = state.history.length - 1;
}
if (history) {
disconnect();
state.position = history[0];
state.onChange(history[1], history[0]);
}
return;
} else {
trackState();
}
if (event.key === 'Enter') {
event.preventDefault();
// Firefox Quirk: Since plaintext-only is unsupported we must
// ensure that only newline characters are inserted
const position = getPosition(element);
// We also get the current line and preserve indentation for the next
// line that's created
const match = /\S/g.exec(position.content);
const index = match ? match.index : position.content.length;
const text = '\n' + position.content.slice(0, index);
edit.insert(text);
} else if (
(!hasPlaintextSupport || opts!.indentation) &&
event.key === 'Backspace'
) {
// Firefox Quirk: Since plaintext-only is unsupported we must
// ensure that only a single character is deleted
event.preventDefault();
const range = getCurrentRange();
if (!range.collapsed) {
edit.insert('', 0);
} else {
const position = getPosition(element);
const match = blanklineRe.exec(position.content);
edit.insert('', match ? -match[1].length : -1);
}
} else if (opts!.indentation && event.key === 'Tab') {
event.preventDefault();
const position = getPosition(element);
const start = position.position - position.content.length;
const content = toString(element);
const newContent = event.shiftKey
? content.slice(0, start) +
position.content.replace(indentRe, '') +
content.slice(start + position.content.length)
: content.slice(0, start) +
(opts!.indentation ? ' '.repeat(opts!.indentation) : '\t') +
content.slice(start);
edit.update(newContent);
}
// Flush changes as a key is held so the app can catch up
if (event.repeat) flushChanges();
};
const onKeyUp = (event: HTMLElementEventMap['keyup']) => {
if (event.defaultPrevented || event.isComposing) return;
if (!isUndoRedoKey(event)) trackState();
flushChanges();
// Chrome Quirk: The contenteditable may lose focus after the first edit or so
element.focus();
};
const onSelect = (event: Event) => {
// Chrome Quirk: The contenteditable may lose its selection immediately on first focus
state.position =
window.getSelection()!.rangeCount && event.target === element
? getPosition(element)
: null;
};
const onPaste = (event: HTMLElementEventMap['paste']) => {
event.preventDefault();
trackState(true);
edit.insert(event.clipboardData!.getData('text/plain'));
trackState(true);
flushChanges();
};
document.addEventListener('selectstart', onSelect);
window.addEventListener('keydown', onKeyDown);
element.addEventListener('paste', onPaste);
element.addEventListener('keyup', onKeyUp);
return () => {
document.removeEventListener('selectstart', onSelect);
window.removeEventListener('keydown', onKeyDown);
element.removeEventListener('paste', onPaste);
element.removeEventListener('keyup', onKeyUp);
element.style.whiteSpace = prevWhiteSpace;
element.contentEditable = prevContentEditable;
};
}, [elementRef.current!, opts!.disabled, opts!.indentation]);
return edit;
}; | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";
import * as Models from "../models";
import * as Mappers from "../models/replicationNetworkMappingsMappers";
import * as Parameters from "../models/parameters";
import { SiteRecoveryManagementClientContext } from "../siteRecoveryManagementClientContext";
/** Class representing a ReplicationNetworkMappings. */
export class ReplicationNetworkMappings {
private readonly client: SiteRecoveryManagementClientContext;
/**
* Create a ReplicationNetworkMappings.
* @param {SiteRecoveryManagementClientContext} client Reference to the service client.
*/
constructor(client: SiteRecoveryManagementClientContext) {
this.client = client;
}
/**
* Lists all ASR network mappings for the specified network.
* @summary Gets all the network mappings under a network.
* @param fabricName Primary fabric name.
* @param networkName Primary network name.
* @param [options] The optional parameters
* @returns Promise<Models.ReplicationNetworkMappingsListByReplicationNetworksResponse>
*/
listByReplicationNetworks(fabricName: string, networkName: string, options?: msRest.RequestOptionsBase): Promise<Models.ReplicationNetworkMappingsListByReplicationNetworksResponse>;
/**
* @param fabricName Primary fabric name.
* @param networkName Primary network name.
* @param callback The callback
*/
listByReplicationNetworks(fabricName: string, networkName: string, callback: msRest.ServiceCallback<Models.NetworkMappingCollection>): void;
/**
* @param fabricName Primary fabric name.
* @param networkName Primary network name.
* @param options The optional parameters
* @param callback The callback
*/
listByReplicationNetworks(fabricName: string, networkName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.NetworkMappingCollection>): void;
listByReplicationNetworks(fabricName: string, networkName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.NetworkMappingCollection>, callback?: msRest.ServiceCallback<Models.NetworkMappingCollection>): Promise<Models.ReplicationNetworkMappingsListByReplicationNetworksResponse> {
return this.client.sendOperationRequest(
{
fabricName,
networkName,
options
},
listByReplicationNetworksOperationSpec,
callback) as Promise<Models.ReplicationNetworkMappingsListByReplicationNetworksResponse>;
}
/**
* Gets the details of an ASR network mapping
* @summary Gets network mapping by name.
* @param fabricName Primary fabric name.
* @param networkName Primary network name.
* @param networkMappingName Network mapping name.
* @param [options] The optional parameters
* @returns Promise<Models.ReplicationNetworkMappingsGetResponse>
*/
get(fabricName: string, networkName: string, networkMappingName: string, options?: msRest.RequestOptionsBase): Promise<Models.ReplicationNetworkMappingsGetResponse>;
/**
* @param fabricName Primary fabric name.
* @param networkName Primary network name.
* @param networkMappingName Network mapping name.
* @param callback The callback
*/
get(fabricName: string, networkName: string, networkMappingName: string, callback: msRest.ServiceCallback<Models.NetworkMapping>): void;
/**
* @param fabricName Primary fabric name.
* @param networkName Primary network name.
* @param networkMappingName Network mapping name.
* @param options The optional parameters
* @param callback The callback
*/
get(fabricName: string, networkName: string, networkMappingName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.NetworkMapping>): void;
get(fabricName: string, networkName: string, networkMappingName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.NetworkMapping>, callback?: msRest.ServiceCallback<Models.NetworkMapping>): Promise<Models.ReplicationNetworkMappingsGetResponse> {
return this.client.sendOperationRequest(
{
fabricName,
networkName,
networkMappingName,
options
},
getOperationSpec,
callback) as Promise<Models.ReplicationNetworkMappingsGetResponse>;
}
/**
* The operation to create an ASR network mapping.
* @summary Creates network mapping.
* @param fabricName Primary fabric name.
* @param networkName Primary network name.
* @param networkMappingName Network mapping name.
* @param input Create network mapping input.
* @param [options] The optional parameters
* @returns Promise<Models.ReplicationNetworkMappingsCreateResponse>
*/
create(fabricName: string, networkName: string, networkMappingName: string, input: Models.CreateNetworkMappingInput, options?: msRest.RequestOptionsBase): Promise<Models.ReplicationNetworkMappingsCreateResponse> {
return this.beginCreate(fabricName,networkName,networkMappingName,input,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.ReplicationNetworkMappingsCreateResponse>;
}
/**
* The operation to delete a network mapping.
* @summary Delete network mapping.
* @param fabricName Primary fabric name.
* @param networkName Primary network name.
* @param networkMappingName ARM Resource Name for network mapping.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(fabricName: string, networkName: string, networkMappingName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> {
return this.beginDeleteMethod(fabricName,networkName,networkMappingName,options)
.then(lroPoller => lroPoller.pollUntilFinished());
}
/**
* The operation to update an ASR network mapping.
* @summary Updates network mapping.
* @param fabricName Primary fabric name.
* @param networkName Primary network name.
* @param networkMappingName Network mapping name.
* @param input Update network mapping input.
* @param [options] The optional parameters
* @returns Promise<Models.ReplicationNetworkMappingsUpdateResponse>
*/
update(fabricName: string, networkName: string, networkMappingName: string, input: Models.UpdateNetworkMappingInput, options?: msRest.RequestOptionsBase): Promise<Models.ReplicationNetworkMappingsUpdateResponse> {
return this.beginUpdate(fabricName,networkName,networkMappingName,input,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.ReplicationNetworkMappingsUpdateResponse>;
}
/**
* Lists all ASR network mappings in the vault.
* @summary Gets all the network mappings under a vault.
* @param [options] The optional parameters
* @returns Promise<Models.ReplicationNetworkMappingsListResponse>
*/
list(options?: msRest.RequestOptionsBase): Promise<Models.ReplicationNetworkMappingsListResponse>;
/**
* @param callback The callback
*/
list(callback: msRest.ServiceCallback<Models.NetworkMappingCollection>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
list(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.NetworkMappingCollection>): void;
list(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.NetworkMappingCollection>, callback?: msRest.ServiceCallback<Models.NetworkMappingCollection>): Promise<Models.ReplicationNetworkMappingsListResponse> {
return this.client.sendOperationRequest(
{
options
},
listOperationSpec,
callback) as Promise<Models.ReplicationNetworkMappingsListResponse>;
}
/**
* The operation to create an ASR network mapping.
* @summary Creates network mapping.
* @param fabricName Primary fabric name.
* @param networkName Primary network name.
* @param networkMappingName Network mapping name.
* @param input Create network mapping input.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginCreate(fabricName: string, networkName: string, networkMappingName: string, input: Models.CreateNetworkMappingInput, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
fabricName,
networkName,
networkMappingName,
input,
options
},
beginCreateOperationSpec,
options);
}
/**
* The operation to delete a network mapping.
* @summary Delete network mapping.
* @param fabricName Primary fabric name.
* @param networkName Primary network name.
* @param networkMappingName ARM Resource Name for network mapping.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginDeleteMethod(fabricName: string, networkName: string, networkMappingName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
fabricName,
networkName,
networkMappingName,
options
},
beginDeleteMethodOperationSpec,
options);
}
/**
* The operation to update an ASR network mapping.
* @summary Updates network mapping.
* @param fabricName Primary fabric name.
* @param networkName Primary network name.
* @param networkMappingName Network mapping name.
* @param input Update network mapping input.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginUpdate(fabricName: string, networkName: string, networkMappingName: string, input: Models.UpdateNetworkMappingInput, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
fabricName,
networkName,
networkMappingName,
input,
options
},
beginUpdateOperationSpec,
options);
}
/**
* Lists all ASR network mappings for the specified network.
* @summary Gets all the network mappings under a network.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.ReplicationNetworkMappingsListByReplicationNetworksNextResponse>
*/
listByReplicationNetworksNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ReplicationNetworkMappingsListByReplicationNetworksNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByReplicationNetworksNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.NetworkMappingCollection>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByReplicationNetworksNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.NetworkMappingCollection>): void;
listByReplicationNetworksNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.NetworkMappingCollection>, callback?: msRest.ServiceCallback<Models.NetworkMappingCollection>): Promise<Models.ReplicationNetworkMappingsListByReplicationNetworksNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByReplicationNetworksNextOperationSpec,
callback) as Promise<Models.ReplicationNetworkMappingsListByReplicationNetworksNextResponse>;
}
/**
* Lists all ASR network mappings in the vault.
* @summary Gets all the network mappings under a vault.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.ReplicationNetworkMappingsListNextResponse>
*/
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.ReplicationNetworkMappingsListNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.NetworkMappingCollection>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.NetworkMappingCollection>): void;
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.NetworkMappingCollection>, callback?: msRest.ServiceCallback<Models.NetworkMappingCollection>): Promise<Models.ReplicationNetworkMappingsListNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listNextOperationSpec,
callback) as Promise<Models.ReplicationNetworkMappingsListNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listByReplicationNetworksOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationNetworks/{networkName}/replicationNetworkMappings",
urlParameters: [
Parameters.resourceName,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.fabricName,
Parameters.networkName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.NetworkMappingCollection
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationNetworks/{networkName}/replicationNetworkMappings/{networkMappingName}",
urlParameters: [
Parameters.resourceName,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.fabricName,
Parameters.networkName,
Parameters.networkMappingName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.NetworkMapping
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationNetworkMappings",
urlParameters: [
Parameters.resourceName,
Parameters.resourceGroupName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.NetworkMappingCollection
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginCreateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationNetworks/{networkName}/replicationNetworkMappings/{networkMappingName}",
urlParameters: [
Parameters.resourceName,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.fabricName,
Parameters.networkName,
Parameters.networkMappingName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "input",
mapper: {
...Mappers.CreateNetworkMappingInput,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.NetworkMapping
},
202: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginDeleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationNetworks/{networkName}/replicationNetworkMappings/{networkMappingName}",
urlParameters: [
Parameters.resourceName,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.fabricName,
Parameters.networkName,
Parameters.networkMappingName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
202: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationFabrics/{fabricName}/replicationNetworks/{networkName}/replicationNetworkMappings/{networkMappingName}",
urlParameters: [
Parameters.resourceName,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.fabricName,
Parameters.networkName,
Parameters.networkMappingName
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "input",
mapper: {
...Mappers.UpdateNetworkMappingInput,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.NetworkMapping
},
202: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listByReplicationNetworksNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.NetworkMappingCollection
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.NetworkMappingCollection
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
}; | the_stack |
import React, { Component, ReactInstance, ImgHTMLAttributes } from "react";
import { findDOMNode } from "react-dom";
import ReactQuill, { Quill } from "./quill/index";
import PropTypes from "prop-types";
import classNames from "classnames";
import { addEventListener } from "../../../utils";
import { polyfill } from "react-lifecycles-compat";
import Spin from "../../Spin/index";
import Radio from "../../Radio/index";
import Modal from "../../Modal/index";
import Input from "../../Input/index";
import Button from "../../Button/index";
import message from "../../message/index";
import CustomToolbar from "./toolbar";
import CustomSizeBlot from "./formats/size";
import EmojiBlot from "./formats/emoji";
import LinkBlot from "./formats/link";
import ImageBlot from "./formats/image";
import VideoBlot from "./formats/video";
import PlainClipboard from "./modules/plainClipboard";
import ImageDrop from "./modules/imageDrop";
import FileDrop from "./modules/fileDrop";
import { RichEditorProps, RichEditorState } from './interface'
import ConfigConsumer from '../../Config/Consumer';
import { LocaleProperties } from '../../Locale';
Quill.register(EmojiBlot);
Quill.register(LinkBlot);
Quill.register(ImageBlot);
Quill.register(CustomSizeBlot);
Quill.register(VideoBlot);
Quill.register("modules/imageDrop", ImageDrop, true);
Quill.register("modules/fileDrop", FileDrop, true);
Quill.register(Quill.import('attributors/style/align'), true);
Quill.register(Quill.import('attributors/style/direction'), true);
const getImageSize = function (
url: string,
callback: (width: number | string, height: number | string) => void
) {
let newImage = document.createElement("img");
newImage.onload = function (this: GlobalEventHandlers & { width?: number | string, height?: number | string }) {
// callback(this.width, this.height);
callback(this.width, this.height);
};
newImage.src = url;
};
class Range {
index: number;
length: number;
constructor (index: number, length = 0) {
this.index = index;
this.length = length;
}
}
class RichEditor extends Component<RichEditorProps, RichEditorState> {
reactQuillNode: Element | Text
defaultFontSize: string
defaultLinkPrefix: string
Locale: LocaleProperties['RichEditor']
defaultVideoType: string
isSupportCustomInsertVideo: boolean
prevSelectionFormat: any
handlers: {
link: Function,
video: Function,
emoji: Function,
image: Function,
attachment: Function,
clean: Function,
customInsertValue: Function
}
editorCtner: HTMLDivElement
linkModalInputRef: any
videoModalInputRef: any
toolbarRef: React.ReactInstance
reactQuillRef: ReactQuill
onClickRemoveHandler: any
onClickActionHandler: any
onBlurHandler: any
linkRange: any
static defaultProps = {
customEmoji: [],
customLink: {},
customInsertValue: {},
insertImageTip: true, // ไธบtrueๆถๅฑ็คบๅฏนๅบ่ฏญ่จ็้ป่ฎคๅผ
insertImageModalVisible: true,
insertAttachmentModalVisible: true,
insertVideoTip: true, // ไธบtrueๆถๅฑ็คบๅฏนๅบ่ฏญ่จ็้ป่ฎคๅผ
placeholder: '',
prefixCls: "fishd-richeditor",
popoverPlacement: "top",
tooltipPlacement: "bottom",
loading: false,
imageDrop: false,
fileDrop: false,
resizable: false,
pastePlainText: false,
toolbar: [
["link", "bold", "italic", "underline"],
["size"],
["color"],
[{ align: "" }, { align: "center" }, { align: "right" }],
[{ list: "ordered" }, { list: "bullet" }],
["emoji"],
["image"],
["clean", "formatPainter"]
],
getPopupContainer: () => document.body
};
static getDerivedStateFromProps(nextProps: RichEditorProps, prevState: any) {
let newState = {};
if (nextProps.value !== prevState.lastValue) {
newState["lastValue"] = newState["value"] = nextProps.value;
}
if (nextProps.loading !== prevState.loading) {
newState["loading"] = nextProps.loading;
}
return newState;
}
constructor (props: RichEditorProps) {
super(props);
this.reactQuillNode = document.body;
this.defaultFontSize = "14px";
this.defaultLinkPrefix = "https://";
this.Locale = {};
let {
value,
customLink,
supportFontTag,
pastePlainText,
customInsertVideo
} = this.props;
// ็ฒ่ดดๆถๅฐๅฏๆๆฌ่ฝฌไธบ็บฏๆๆฌ
if (pastePlainText) {
Quill.register("modules/clipboard", PlainClipboard, true);
}
// this.urlValidator = /[-a-zA-Z0-9@:%_+.~#?&//=]{2,256}\.[a-z]{2,63}\b(\/[-a-zA-Z0-9@:%_+.~#?&//=]*)?/i;
this.onBlurHandler = null;
let formatValue = value;
if (supportFontTag) {
formatValue = this.formatFontTag(value);
}
this.defaultVideoType = "video_link";
if (customInsertVideo && typeof customInsertVideo === "function") {
this.isSupportCustomInsertVideo = true;
this.defaultVideoType = "video_local";
}
// ๆ ผๅผๅทไฟๅญ็ๆ ผๅผ
this.prevSelectionFormat = null;
this.state = {
lastValue: value,
value: formatValue || "",
loading: false,
showLinkModal: false,
showVideoModal: false,
showImageModal: false,
toolbarCtner: null,
curRange: null,
curVideoType: this.defaultVideoType,
defaultInputLink: this.defaultLinkPrefix,
linkModalTitle: "",
formatPainterActive: false
};
this.handlers = {
link: (value, fromAction) => {
let { onClickToolbarBtn } = this.props;
if (
typeof onClickToolbarBtn == "function" &&
onClickToolbarBtn("link") === false
) {
return;
}
let quill = this.getEditor(),
range = quill.getSelection();
if (range && range.length !== 0) {
// ้ไปถไธ่ฝ่ฎพ็ฝฎ่ถ
้พๆฅ
let [link, offset] = quill.scroll.descendant(LinkBlot, range.index);
if (link && link.domNode.dataset.qlLinkType == "attachment") {
return;
}
let newState = {
value: quill.getRawHTML(), // ไฝฟ RichEditor ไธ Quill ๅๆญฅ
showLinkModal: true,
defaultInputLink: this.defaultLinkPrefix,
curRange: range
};
// ็นๅป็ผ่พ้พๆฅ่งฆๅ
if (fromAction) {
newState["defaultInputLink"] = value;
newState["linkModalTitle"] = this.Locale.editLink;
} else {
newState["linkModalTitle"] = this.Locale.insertLink;
}
this.setState(newState);
} else {
message.error(this.Locale.noSelectionText);
}
},
video: value => {
let { onClickToolbarBtn } = this.props;
if (
typeof onClickToolbarBtn == "function" &&
onClickToolbarBtn("video") === false
) {
return;
}
let quill = this.getEditor();
this.setState({
value: quill.getRawHTML(), // ไฝฟ RichEditor ไธ Quill ๅๆญฅ
showVideoModal: true,
curRange: quill.getSelection() // ้ฒๆญขๆๅ
ฅ่ง้ขๆถๅ
ๆ ๅฎไฝ้่ฏฏ
});
},
emoji: value => {
let quill = this.getEditor(),
range = quill.getSelection(),
mValue = JSON.parse(value);
quill.insertEmbed(range.index, "emoji", {
type: mValue.type,
alt: mValue.alt,
src: mValue.src && mValue.src.trim(),
width: mValue.width,
height: mValue.height,
id: mValue.id
});
quill.setSelection(range.index + 1);
},
// customColor: (color) => {
// let quill = this.getEditor(),
// range = quill.getSelection();
// if (range.length !== 0) {
// quill.format('color', color);
// }
// },
image: () => {
let { onClickToolbarBtn, insertImageModalVisible } = this.props;
if (
typeof onClickToolbarBtn == "function" &&
onClickToolbarBtn("image") === false
) {
return;
}
let showImageModal = true;
if (!insertImageModalVisible) {
showImageModal = false;
this.handlePickLocalImage();
}
let quill = this.getEditor();
this.setState({
value: quill.getRawHTML(), // ไฝฟ RichEditor ไธ Quill ๅๆญฅ
showImageModal,
curRange: quill.getSelection()
});
},
attachment: () => {
let { onClickToolbarBtn, insertAttachmentModalVisible } = this.props;
if (
typeof onClickToolbarBtn == "function" &&
onClickToolbarBtn("attachment") === false
) {
return;
}
let showAttachmentModal = true;
if (!insertAttachmentModalVisible) {
showAttachmentModal = false;
this.handlePickLocalFile();
}
let quill = this.getEditor();
this.setState({
value: quill.getRawHTML(), // ไฝฟ RichEditor ไธ Quill ๅๆญฅ
showAttachmentModal,
curRange: quill.getSelection()
});
},
clean: () => {
const { parchment: Parchment } = Quill.imports;
let quill = this.getEditor(),
range = quill.getSelection();
if (range == null) return;
if (range.length == 0) {
let formats = quill.getFormat();
Object.keys(formats).forEach(name => {
// Clean functionality in existing apps only clean inline formats
if (Parchment.query(name, Parchment.Scope.INLINE) != null) {
quill.format(name, false);
}
});
} else {
quill.removeFormat(range, Quill.sources.USER);
}
},
// ๅค็ๅฎๅถ็ๆๅ
ฅๅผ
customInsertValue: value => {
let quill = this.getEditor(),
range = quill.getSelection(),
mValue = JSON.parse(value);
if (!range) return;
if (mValue.editable === false) {
quill.insertText(range.index, mValue.value, {
customAttr: { editable: false }
});
} else {
quill.insertText(range.index, mValue.value);
}
}
};
// ๅค็ๅฎๅถ็่ถ
้พๆฅ
Object.keys(customLink).forEach(moduleName => {
const that = this;
this.handlers[`${moduleName}Entry`] = function () {
let range = this.quill.getSelection(),
url = customLink[moduleName].url;
if (range.length !== 0) {
// ้ไปถไธ่ฝ่ฎพ็ฝฎ่ถ
้พๆฅ
let [link, offset] = this.quill.scroll.descendant(
LinkBlot,
range.index
);
if (link && link.domNode.dataset.qlLinkType == "attachment") {
return;
}
if (url) {
// ๅผๆญฅ่ทๅURL
if (Object.prototype.toString.call(url) == "[object Function]") {
let format = this.quill.getFormat(),
prevValue = format && format.link && format.link.url;
url(value => {
this.quill.format("link", {
type: `${moduleName}Entry`,
url: value
});
}, prevValue);
} else {
this.quill.format("link", {
type: `${moduleName}Entry`,
url
});
}
}
} else {
message.error(that.Locale.noSelectionText);
}
};
});
}
componentDidMount() {
/* eslint-disable react/no-did-mount-set-state */
this.setState(
{
toolbarCtner: findDOMNode(this.toolbarRef)
},
() => {
if (!this.reactQuillRef) return;
this.reactQuillNode = findDOMNode(this.reactQuillRef) as Element;
this.onBlurHandler = addEventListener(
this.reactQuillNode.querySelector(".ql-editor"),
"blur",
() => {
if (!this.reactQuillRef) return;
let quill = this.reactQuillRef.getEditor(),
range = quill.getSelection();
if (typeof this.props.onBlur == "function") {
this.props.onBlur(range, "user", quill);
}
}
);
// ็ผ่พ่ถ
้พๆฅ
this.onClickActionHandler = addEventListener(
this.reactQuillNode.querySelector("a.ql-action"),
"click",
event => {
if (!this.reactQuillRef) return;
let quill = this.reactQuillRef.getEditor();
if (!quill) return;
let tooltip = quill.theme && quill.theme.tooltip;
if (tooltip && this.linkRange != null) {
tooltip.linkRange = this.linkRange;
quill.setSelection(this.linkRange);
this.handlers.link(tooltip.preview.getAttribute("href"), true);
}
// if (this.root.classList.contains('ql-editing')) {
// this.save();
// } else {
// this.edit('link', this.preview.textContent);
// }
event.preventDefault();
}
);
// ๅ ้ค่ถ
้พๆฅ
this.onClickRemoveHandler = addEventListener(
this.reactQuillNode.querySelector("a.ql-remove"),
"click",
event => {
if (!this.reactQuillRef) return;
let quill = this.reactQuillRef.getEditor();
if (!quill) return;
let tooltip = quill.theme && quill.theme.tooltip;
if (tooltip && this.linkRange != null) {
tooltip.linkRange = this.linkRange;
quill.formatText(tooltip.linkRange, "link", false, "user");
quill.focus();
delete tooltip.linkRange;
this.linkRange = null;
}
event.preventDefault();
}
);
}
);
this.changePseudoElementText();
setTimeout(() => {
this.changeEditorPlaceholder();
}, 10);
/* eslint-enable react/no-did-mount-set-state */
}
componentDidUpdate(prevProps, prevState, snapshot) {
/* eslint-disable react/no-did-update-set-state */
if (
prevState.lastValue != this.state.lastValue &&
this.props.supportFontTag
) {
this.setState({
value: this.formatFontTag(this.state.lastValue)
});
}
this.changePseudoElementText();
this.changeEditorPlaceholder();
/* eslint-enable react/no-did-update-set-state */
}
componentWillUnmount() {
this.onBlurHandler && this.onBlurHandler.remove();
this.onClickActionHandler && this.onClickActionHandler.remove();
this.onClickRemoveHandler && this.onClickRemoveHandler.remove();
}
formatFontTag = value => {
if (!value) return value;
let fontTagStart = /(<\s*?)font(\s+)(.*?)(>)/gi,
fontTagEnd = /(<\s*?\/\s*?)font(\s*?>)/gi;
value = value.replace(fontTagStart, ($0, $1, $2, $3, $4) => {
let tagStyle = ' style="',
tagAttr = " ";
$3.replace(/(\w+-?\w+)\s*=\s*["']\s*(.*?)\s*["']/gi, ($0, $1, $2) => {
let key = $1,
value = $2;
switch (key) {
case "color": {
tagStyle += "color:" + value + ";";
break;
}
case "size": {
// fontๆ ็ญพsizeๅฑๆง็valueๆฏๆฐๅญ็ฑปๅ๏ผๅๅผ่ๅดๆฏ[1,7]ใ
let size2pxMap = {
"1": "12px",
"2": "13px",
"3": "16px",
"4": "18px",
"5": "24px",
"6": "32px",
"7": "48px"
},
sizeWithUnit = this.defaultFontSize,
val = value && value.trim();
// value้ๆฐๅญๆไธๅจ[1,7]่ๅดๅ
ๆถ๏ผๅ้ป่ฎคๅญไฝๅคงๅฐ
if (!/^\d+$/.test(val) || parseInt(val) > 7 || parseInt(val) < 1) {
sizeWithUnit = this.defaultFontSize;
} else {
sizeWithUnit = size2pxMap[val] || this.defaultFontSize;
}
tagStyle += "font-size:" + sizeWithUnit + ";";
break;
}
case "face": {
tagStyle += "font-family:" + value + ";";
break;
}
default: {
tagAttr += key + "=" + value;
break;
}
}
});
tagStyle += '"';
return $1 + "span" + $2 + tagStyle + tagAttr + $4;
});
return value.replace(fontTagEnd, "$1span$2");
};
focus = () => {
if (!this.reactQuillRef) return;
this.reactQuillRef.focus();
};
blur = () => {
if (!this.reactQuillRef) return;
this.reactQuillRef.blur();
};
getEditor = (): ReactQuill | undefined => {
if (!this.reactQuillRef) return;
return this.reactQuillRef.getEditor() as ReactQuill;
};
handleLinkModalOk = () => {
let el = this.linkModalInputRef.input,
val = el.value.trim();
if (val) {
if (val.length > 1000) {
message.error(this.Locale.linkToolongError);
return;
}
let quill = this.getEditor();
quill.formatText(
this.state.curRange,
"link",
{
// type: 'default',
url: val
},
"user"
);
quill.setSelection(this.state.curRange); // ่ฎพ็ฝฎ่ถ
้พๆฅๅๆขๅค้ๅบ
this.setState({
value: quill.getRawHTML(), // ไฝฟ RichEditor ไธ Quill ๅๆญฅ
showLinkModal: false,
defaultInputLink: this.defaultLinkPrefix
});
} else {
message.error(this.Locale.linkEmptyTip);
}
};
handleLinkModalCancel = () => {
this.setState({
showLinkModal: false,
defaultInputLink: this.defaultLinkPrefix
});
};
handleVideoModalOk = () => {
let val = null;
if (this.videoModalInputRef) {
val = this.videoModalInputRef.input.value.trim();
}
if (val) {
if (val.length > 1000) {
message.error(this.Locale.videoLinkTooLongError);
return;
}
if (val.indexOf("//") < 0) {
message.error(this.Locale.videoUrlFormattingError);
return;
}
let quill = this.getEditor(),
range = this.state.curRange
? this.state.curRange
: quill.getSelection(true), // ่ทๅ้ๅบๅๅ
่็ฆ
{ videoTagAttrs } = this.props;
this.insertVideo(range.index, {
...videoTagAttrs,
src: val
});
this.videoModalInputRef && (this.videoModalInputRef.input.value = "");
this.setState({
value: quill.getRawHTML(), // ไฝฟ RichEditor ไธ Quill ๅๆญฅ
showVideoModal: false,
curRange: null
});
} else {
message.error(this.Locale.noVideoUrlErrorTip);
}
};
handleVideoModalCancel = () => {
if (this.videoModalInputRef) {
this.videoModalInputRef.input.value = "";
}
this.setState({
curVideoType: this.defaultVideoType,
showVideoModal: false,
curRange: null
});
};
handleImageModalCancel = () => {
this.setState({
showImageModal: false,
curRange: null
});
};
handleAttachmentModalCancel = () => {
this.setState({
showAttachmentModal: false,
curRange: null
});
};
handlePickLocalImage = () => {
let { customInsertImage } = this.props,
{ toolbarCtner } = this.state,
quill = this.getEditor(),
fileInput = toolbarCtner.querySelector("input.ql-image[type=file]");
const handleInsertImage = info => {
if (info.src == undefined) {
message.error(this.Locale.noPicSrcTip);
return;
}
info.src = info.src && info.src.trim();
let range = this.state.curRange
? this.state.curRange
: quill.getSelection(true);
if (info.width == undefined || info.height == undefined) {
getImageSize(info.src, (naturalWidth, naturalHeight) => {
info.width = naturalWidth;
info.height = naturalHeight;
quill.insertEmbed(range.index, "myImage", info);
quill.setSelection(range.index + 1, "silent");
this.setState({
value: quill.getRawHTML(), // ไฝฟ RichEditor ไธ Quill ๅๆญฅ
curRange: null
});
});
} else {
quill.insertEmbed(range.index, "myImage", info);
quill.setSelection(range.index + 1, "silent");
this.setState({
value: quill.getRawHTML(), // ไฝฟ RichEditor ไธ Quill ๅๆญฅ
curRange: null
});
}
};
const getImageCb = imgList => {
if (Array.isArray(imgList)) {
imgList.forEach(imgInfo => {
handleInsertImage(imgInfo);
});
} else {
handleInsertImage(imgList);
}
};
this.setState({
showImageModal: false
});
if (customInsertImage && typeof customInsertImage === "function") {
customInsertImage(getImageCb);
} else {
if (fileInput == null) {
fileInput = document.createElement("input");
fileInput.setAttribute("type", "file");
fileInput.setAttribute(
"accept",
"image/jpg, image/jpeg, image/png, image/gif, image/bmp"
);
fileInput.setAttribute("multiple", "multiple");
fileInput.classList.add("ql-image");
fileInput.addEventListener("change", () => {
if (fileInput.files != null && fileInput.files.length) {
for (let i = 0, len = fileInput.files.length; i < len; i++) {
let reader = new FileReader();
reader.onload = e => {
getImageCb({ src: e.target.result });
fileInput.value = "";
};
reader.readAsDataURL(fileInput.files[i]);
}
}
});
toolbarCtner.appendChild(fileInput);
}
fileInput.click();
}
};
handlePickLocalFile = () => {
let { customInsertAttachment } = this.props,
quill = this.getEditor();
const handleInsertFile = file => {
if (!file || !file.url || !file.name) {
message.error(this.Locale.noFileInfoTip);
return;
}
let range = this.state.curRange
? this.state.curRange
: quill.getSelection(true);
if (!range) return;
// ็ปงๆฟๅ่กจ็ๆ ทๅผ
let curFormat = quill.getFormat(range),
listFormat: { list?: any } = {};
if (curFormat && curFormat.list) {
listFormat.list = curFormat.list;
}
let displayFileName = (this.Locale.file) + file.name,
contentsDelta: any[] = [
{
insert: displayFileName,
attributes: {
...listFormat,
link: {
type: "attachment",
url: file.url && file.url.trim(),
name: file.name
}
}
},
{
insert: "\n",
attributes: {
...listFormat
}
}
];
// ๅจๅผๅคดๆๅ
ฅๆถไธ่ฝไฝฟ็จretain
if (range.index > 0) {
contentsDelta.unshift({ retain: range.index });
}
// ๆๅ
ฅ้ไปถ
quill.updateContents(contentsDelta, "silent");
quill.setSelection(range.index + displayFileName.length + 1, "silent");
};
const getFileCb = fileList => {
if (Array.isArray(fileList)) {
fileList
.sort((a, b) => {
// ๅๆฌกๆๅ
ฅๅคไธชไธๅ็ฑปๅ็ๆไปถๆถ๏ผๆโ่ง้ข -> ๅพ็ -> ๅ
ถไปๆไปถโ็้กบๅบๆๅ
let order = ["other", "image", "video"];
return order.indexOf(b.type) - order.indexOf(a.type);
})
.forEach(file => {
handleInsertFile(file);
this.setState({
value: quill.getRawHTML(), // ไฝฟ RichEditor ไธ Quill ๅๆญฅ
curRange: null
});
});
} else {
handleInsertFile(fileList);
this.setState({
value: quill.getRawHTML(), // ไฝฟ RichEditor ไธ Quill ๅๆญฅ
curRange: null
});
}
};
this.setState({
showAttachmentModal: false
});
if (
customInsertAttachment &&
typeof customInsertAttachment === "function"
) {
customInsertAttachment(getFileCb);
}
};
insertVideo = (rangeIndex, attrs) => {
let quill = this.getEditor(),
prevChar = quill.getText(rangeIndex - 1, 1),
nextChar = quill.getText(rangeIndex + 1, 1),
videoNode = document.createElement("video");
videoNode.onerror = () => {
message.error(this.Locale.VideoCantPlayTip);
};
videoNode.src = attrs.src && attrs.src.trim();
videoNode = null;
if (rangeIndex > 0 && prevChar != "\n") {
// ๅจไธ่ก็ไธญ้ดๆๅ
ฅ่ง้ข
if (nextChar && nextChar != "\n") {
quill.insertText(rangeIndex, "\n"); // ๆๅ
ฅ่ง้ขๅๆข่ก๏ผ้ฟๅ
ไธขๅคฑๆๅญ
quill.insertEmbed(rangeIndex + 1, "myVideo", attrs);
quill.setSelection(rangeIndex + 1, "silent");
} else {
// ๅจไธ่ก็ๆซๅฐพๆๅ
ฅ่ง้ข
quill.insertEmbed(rangeIndex + 1, "myVideo", attrs);
quill.insertText(rangeIndex + 2, "\n"); // ๆๅ
ฅ่ง้ขๅๆข่ก๏ผ้ฟๅ
ไธขๅคฑๅ
ๆ
quill.setSelection(rangeIndex + 2, "silent");
}
} else {
// ไธ่ก็ๅผๅคดๆๅ
ฅ่ง้ข
quill.insertEmbed(rangeIndex, "myVideo", attrs);
quill.setSelection(rangeIndex + 1, "silent");
}
};
handlePickLocalVideo = () => {
let { customInsertVideo, videoTagAttrs } = this.props,
quill = this.getEditor(); // ่ทๅ้ๅบๅๅ
่็ฆ
const handleVideoInsert = info => {
if (info.src == undefined) {
message.error(this.Locale.noVideoLinkErrorTip);
return;
}
info.src = info.src && info.src.trim();
let range = this.state.curRange
? this.state.curRange
: quill.getSelection(true);
this.insertVideo(range.index, {
...videoTagAttrs,
...info
});
};
const getVideoCb = videoList => {
if (Array.isArray(videoList)) {
videoList.forEach(videoInfo => {
handleVideoInsert(videoInfo);
});
} else {
handleVideoInsert(videoList);
}
this.setState({
value: quill.getRawHTML(), // ไฝฟ RichEditor ไธ Quill ๅๆญฅ
curRange: null
});
};
this.setState({
showVideoModal: false
});
if (customInsertVideo && typeof customInsertVideo === "function") {
customInsertVideo(getVideoCb);
}
};
handleInsertEmoji = e => {
let { toolbarCtner } = this.state,
target = e.target,
clsList = target.classList.value;
if (
(clsList.indexOf("emoji-item") > -1 ||
clsList.indexOf("emoji-extend-item") > -1) &&
target.hasAttribute("value")
) {
let el = toolbarCtner.querySelector('button.ql-emoji[data-role="emoji"]');
if (el == null) {
el = document.createElement("button");
toolbarCtner.querySelector(".custom-emoji").appendChild(el);
}
el.setAttribute("type", "button");
el.setAttribute("data-role", "emoji");
el.setAttribute("value", target.getAttribute("value"));
el.classList.add("ql-emoji", "hide");
el.click();
}
};
handleFormatBackground = e => {
let { toolbarCtner } = this.state,
target = e.target;
if (
target.classList.value.indexOf("background-item") > -1 &&
target.hasAttribute("value")
) {
let el = toolbarCtner.querySelector(
'button.ql-background[data-role="background"]'
);
if (el == null) {
el = document.createElement("button");
toolbarCtner.querySelector(".custom-background").appendChild(el);
}
el.setAttribute("type", "button");
el.setAttribute("data-role", "background");
el.setAttribute("value", target.getAttribute("value"));
el.classList.add("ql-background", "hide");
el.click();
}
};
handleFormatColor = e => {
let { toolbarCtner } = this.state,
target = e.target;
if (
target.classList.value.indexOf("color-item") > -1 &&
target.hasAttribute("value")
) {
let el = toolbarCtner.querySelector('button.ql-color[data-role="color"]');
if (el == null) {
el = document.createElement("button");
toolbarCtner.querySelector(".custom-color").appendChild(el);
}
el.setAttribute("type", "button");
el.setAttribute("data-role", "color");
el.setAttribute("value", target.getAttribute("value"));
el.classList.add("ql-color", "hide");
el.click();
}
};
handleFormatSize = value => {
let quill = this.getEditor();
quill &&
quill.format("customAttr", {
fontSize: value
});
};
handleInsertValue = e => {
let { toolbarCtner } = this.state,
target = e.target;
if (
target.classList.value.indexOf("insert-value-item") > -1 &&
target.hasAttribute("value")
) {
let el = toolbarCtner.querySelector(
'button.ql-customInsertValue[data-role="customInsertValue"]'
);
if (el == null) {
el = document.createElement("button");
toolbarCtner.querySelector(".custom-insert-value").appendChild(el);
}
el.setAttribute("type", "button");
el.setAttribute("data-role", "customInsertValue");
el.setAttribute("value", target.getAttribute("value"));
el.classList.add("ql-customInsertValue", "hide");
el.click();
}
};
handleChange = (value, delta, source, editor) => {
const { onChange } = this.props;
if (onChange) {
onChange(value, delta, source, editor);
}
};
handleShowTooltip = root => {
if (!root) return;
root.classList.remove("ql-editing");
root.classList.remove("ql-hidden");
root.classList.remove("custom-hide");
root.classList.add("custom-show");
};
handleHideTooltip = root => {
if (!root) return;
root.classList.remove("custom-show");
root.classList.add("ql-hidden");
root.classList.add("custom-hide");
};
handleTooltipPosition(tooltip, reference) {
let left =
reference.left + reference.width / 2 - tooltip.root.offsetWidth / 2;
// root.scrollTop should be 0 if scrollContainer !== root
let top = reference.bottom + tooltip.quill.root.scrollTop;
tooltip.root.style.left = left + "px";
tooltip.root.style.top = top + "px";
tooltip.root.classList.remove("ql-flip");
let containerBounds = tooltip.boundsContainer.getBoundingClientRect();
let rootBounds = tooltip.root.getBoundingClientRect();
let shift = 0,
offset = 15;
if (rootBounds.right > containerBounds.right) {
shift = containerBounds.right - rootBounds.right;
tooltip.root.style.left = left + shift - offset + "px";
}
if (rootBounds.left < containerBounds.left) {
shift = containerBounds.left - rootBounds.left;
tooltip.root.style.left = left + shift + offset + "px";
}
if (rootBounds.bottom > containerBounds.bottom) {
let height = rootBounds.bottom - rootBounds.top;
let verticalShift = reference.bottom - reference.top + height;
tooltip.root.style.top = top - verticalShift + "px";
tooltip.root.classList.add("ql-flip");
}
return shift;
}
handleSelectionChange = (nextSelection, source, editor) => {
// let { toolbarCtner } = this.state;
const { onSelectionChange } = this.props;
onSelectionChange && onSelectionChange(nextSelection, source, editor);
let quill = this.getEditor();
if (!quill) return;
// ๆ ผๅผๅท
if (this.prevSelectionFormat && nextSelection) {
// ๆธ
้คๅฝๅ้ๅบ็ๆ ผๅผ
quill.removeFormat(nextSelection.index, nextSelection.length);
// ่ฎพ็ฝฎๅฝๅ้ๅบ็ๆ ผๅผ
Object.keys(this.prevSelectionFormat).forEach(name => {
quill.format(name, this.prevSelectionFormat[name]);
});
// ๅๆถๆ ผๅผๅท้ซไบฎ
this.setState({
formatPainterActive: false
});
// ้็ฝฎไฟๅญ็ๆ ผๅผ
this.prevSelectionFormat = null;
}
let tooltip = quill.theme && quill.theme.tooltip;
if (!tooltip) return;
// ๅ
ๆ ๅฎไฝๅฐ่ถ
้พๆฅไธๆถๅฑ็คบtooltip
if (nextSelection && nextSelection.length === 0 && source === "user") {
let [link, offset] = quill.scroll.descendant(
LinkBlot,
nextSelection.index
);
if (link != null) {
// ้ไปถ็่ถ
้พๆฅไธๅฏ็ผ่พ
if (link.domNode.dataset.qlLinkType == "attachment") {
return;
}
tooltip.linkRange = new Range(
nextSelection.index - offset,
link.length()
);
this.linkRange = tooltip.linkRange; // ไฟๅญๅฐๅฝๅๅฎไพ๏ผๅจ็ผ่พ/ๅ ้ค่ถ
้พๆฅ็ไบไปถๅ่ฐไธญไฝฟ็จ
let preview = LinkBlot.formats(link.domNode).url;
tooltip.preview.textContent = preview;
tooltip.preview.setAttribute("href", preview);
// ้่ฆๅจๆพ็คบๅ่ฎพ็ฝฎไฝ็ฝฎ
this.handleShowTooltip(tooltip.root);
this.handleTooltipPosition(tooltip, quill.getBounds(tooltip.linkRange));
return;
}
}
this.handleHideTooltip(tooltip.root);
// FixBug: ๅๆถ้ซไบฎๅบๅใaๆ ็ญพๆทปๅ ่ชๅฎไนๅฑๆงๅๆฅๅธฆ่ชๅฎไนๅฑๆง็imgๆ ็ญพๆถ๏ผๅจMACๅๅฎๅ็็ๅพฎไฟกๅ
ฌไผๅทไธญ่ถ
้พๆฅไผๅผๅธธๆพ็คบๅบHTMLๆ ็ญพใ
// ๅบๅ้ป่ฎค็่ถ
้พๆฅๆ้ฎๅ่ชๅฎไน่ถ
้พๆฅๆ้ฎ็้ซไบฎ
// if (nextSelection) {
// let curFormat;
// if (nextSelection.index > 0 && quill.getText(nextSelection.index - 1, 1)!='\n') {
// curFormat = quill.getFormat(nextSelection.index - 1, 1);
// } else {
// curFormat = quill.getFormat(nextSelection.index, 1);
// }
// toolbarCtner.querySelector('.link-active')
// && toolbarCtner.querySelector('.link-active').classList.remove('link-active');
// if ('myLink' in curFormat) {
// let linkType = curFormat['myLink'].type || 'default';
// if (linkType == 'default') {
// toolbarCtner.querySelector('.ql-myLink')
// && toolbarCtner.querySelector('.ql-myLink').classList.add('link-active');
// } else {
// toolbarCtner.querySelector(`.ql-${linkType}`)
// && toolbarCtner.querySelector(`.ql-${linkType}`).classList.add('link-active');
// }
// }
// }
};
handleVideoTypeChange = e => {
this.setState({
curVideoType: e.target.value || this.defaultVideoType
});
};
getCurrentSize = () => {
let quill = this.getEditor();
if (!quill) return null;
let formats = quill.getFormat(),
customAttr = formats && formats.customAttr,
customAttrType = Object.prototype.toString.call(customAttr);
if (!customAttr) return this.defaultFontSize;
if (customAttrType == "[object Object]") {
return customAttr.fontSize || this.defaultFontSize;
}
if (customAttrType == "[object Array]") {
let len = customAttr.length;
if (len) {
let fontSize = customAttr[0].fontSize,
hasMultiFontSize = false;
for (let i = 0; i < len; i++) {
// ้ไธญ็ๅฏๆๆฌๆๅค็งๅญไฝๅคงๅฐๆถไธ้ซไบฎๅญๅท
if (customAttr[i].fontSize != fontSize) {
hasMultiFontSize = true;
break;
}
}
if (hasMultiFontSize) {
return null;
} else {
return fontSize;
}
} else {
return this.defaultFontSize;
}
}
return null;
};
handleSaveSelectionFormat = () => {
let quill = this.getEditor();
if (!quill) return null;
this.prevSelectionFormat = quill.getFormat();
// ๆ ผๅผๅท้ซไบฎ
this.setState({
formatPainterActive: true
});
};
handleUnsaveSelectionFormat = () => {
if (this.prevSelectionFormat) {
this.prevSelectionFormat = null;
}
// ๅๆถๆ ผๅผๅท้ซไบฎ
this.setState({
formatPainterActive: false
});
};
// ๅๆดไผช็ฑป็content
changePseudoElementText = () => {
const { accessLink,edit,deleteText } = this.Locale;
const editorCtner = this.editorCtner;
const elEdit = editorCtner.querySelector('.ql-snow .ql-tooltip a.ql-action');
const elDelete = editorCtner.querySelector('.ql-snow .ql-tooltip a.ql-remove');
const elAccessLink = editorCtner.querySelector('.ql-snow .ql-tooltip');
elEdit && elEdit.setAttribute('data-after-content',edit);
elDelete && elDelete.setAttribute('data-before-content',deleteText);
elAccessLink && elAccessLink.setAttribute('data-before-content',accessLink);
}
// ๅๆด็ผ่พๅจplaceholder
changeEditorPlaceholder = () => {
const root = this.getEditor()?.root;
root && root.setAttribute('data-placeholder', this.props.placeholder || this.Locale.placeholder);
}
render() {
const {
loading,
value,
showLinkModal,
showVideoModal,
showImageModal,
showAttachmentModal,
toolbarCtner,
curVideoType,
defaultInputLink,
linkModalTitle
} = this.state;
const {
className,
prefixCls,
toolbar,
placeholder,
customLink,
customInsertValue,
resizable,
style,
getPopupContainer,
customEmoji,
insertImageTip,
insertAttachmentTip,
insertVideoTip,
insertLinkTip,
onChange,
onSelectionChange,
popoverPlacement,
tooltipPlacement,
imageDrop,
fileDrop,
customDropImage,
customDropFile,
pastePlainText,
...restProps
} = this.props;
delete restProps.customInsertImage;
const cls = classNames(
`${prefixCls}`,
{
resizable: resizable
},
className
);
if (value) {
restProps.value = value;
}
// ไธไผ ๆฌๅฐ่ง้ขๆถModalๆ ็กฎ่ฎคๅๅๆถๆ้ฎ
let videoFooter = {};
if (curVideoType == "video_local") {
videoFooter["footer"] = null;
}
let moduleOpts = {
toolbar: {
container: toolbarCtner,
handlers: this.handlers
}
};
// fileDrop ไธบ true ๆถ๏ผไฝฟ imageDrop ๅคฑๆ
if (fileDrop && customDropFile) {
// customDropFile ่ชๅฎไนๆไปถไธไผ ้ป่พ๏ผๅฟ
้
moduleOpts["fileDrop"] = {
customDropFile
};
} else if (imageDrop) {
// customDropImage ไธๅญๅจๆถ๏ผๅฐๅพ็ๆไปถ่ฝฌไธบ dataUrl ๆ ผๅผ
moduleOpts["imageDrop"] = {
customDropImage
};
}
if (pastePlainText) {
moduleOpts["clipboard"] = {
pastePlainText: true
};
}
return (
<ConfigConsumer componentName='RichEditor'>
{
(Locale: LocaleProperties['RichEditor']) => {
this.Locale = Locale;
return (
<div className={cls} style={style} ref={el => (this.editorCtner = el)}>
<Modal
title={linkModalTitle || this.Locale.linkModalTitle}
className={`${prefixCls}-link-modal`}
visible={showLinkModal}
onOk={this.handleLinkModalOk}
onCancel={this.handleLinkModalCancel}
destroyOnClose
>
<span className="text">{Locale.HyperlinkAddress}</span>
<Input
ref={el => (this.linkModalInputRef = el)}
style={{ width: "420px" }}
defaultValue={defaultInputLink}
/>
{insertLinkTip ? <div className="tip">{insertLinkTip}</div> : null}
</Modal>
<Modal
title={Locale.insertPicture}
className={`${prefixCls}-image-modal`}
visible={showImageModal}
footer={null}
onCancel={this.handleImageModalCancel}
>
<Button type="primary" onClick={this.handlePickLocalImage}>
{Locale.selectLocalImage}
</Button>
{
insertImageTip ? (
<div className="tip">
{(insertImageTip === true) ? Locale.insertImageTip : insertImageTip}
</div>
) : null
}
</Modal>
<Modal
title={Locale.insertAttachment}
className={`${prefixCls}-image-modal`}
visible={showAttachmentModal}
footer={null}
onCancel={this.handleAttachmentModalCancel}
>
<Button type="primary" onClick={this.handlePickLocalFile}>
{Locale.selectLocalFile}
</Button>
{insertAttachmentTip ? (
<div className="tip">{insertAttachmentTip}</div>
) : null}
</Modal>
<Modal
title={Locale.insertVideo}
className={`${prefixCls}-video-modal`}
visible={showVideoModal}
{...videoFooter}
onOk={this.handleVideoModalOk}
onCancel={this.handleVideoModalCancel}
>
<Radio.Group
style={{ marginBottom: 24 }}
onChange={this.handleVideoTypeChange}
value={curVideoType}
>
{this.isSupportCustomInsertVideo ? (
<Radio value="video_local">{Locale.localVideo}</Radio>
) : null}
<Radio value="video_link">{Locale.videoLink}</Radio>
</Radio.Group>
{curVideoType == "video_local" ? (
<React.Fragment>
<Button
style={{ display: "block" }}
type="primary"
onClick={this.handlePickLocalVideo}
>
{Locale.selectLocalVideo}
</Button>
{
insertVideoTip ? (
<div className="tip">
{
(insertVideoTip === true) ?
<React.Fragment>
<span>{Locale.rule1}</span>
<br />
<span>{Locale.rule2}</span>
</React.Fragment> : insertVideoTip
}
</div>
) : null
}
</React.Fragment>
) : (
<Input
ref={el => (this.videoModalInputRef = el)}
style={{ width: "434px" }}
placeholder={Locale.PleaseEnterTheVideolinkURL}
/>
)}
</Modal>
<CustomToolbar
ref={el => (this.toolbarRef = el)}
className={"editor-head"}
toolbar={toolbar}
customEmoji={customEmoji}
customLink={customLink}
customInsertValue={customInsertValue}
handleInsertEmoji={this.handleInsertEmoji}
handleFormatColor={this.handleFormatColor}
handleFormatBackground={this.handleFormatBackground}
handleFormatSize={this.handleFormatSize}
handleInsertValue={this.handleInsertValue}
popoverPlacement={popoverPlacement}
tooltipPlacement={tooltipPlacement}
getPopupContainer={getPopupContainer}
getCurrentSize={this.getCurrentSize}
formatPainterActive={this.state.formatPainterActive}
saveSelectionFormat={this.handleSaveSelectionFormat}
unsaveSelectionFormat={this.handleUnsaveSelectionFormat}
/>
<ReactQuill
{...restProps}
ref={el => (this.reactQuillRef = el)}
bounds={this.editorCtner}
className={"editor-body"}
modules={moduleOpts}
// placeholder={Locale.placeholder}
onChange={this.handleChange}
onSelectionChange={this.handleSelectionChange}
/>
{loading ? (
<Spin
style={{
position: "absolute",
width: "100%",
background: "rgba(255, 255, 255, 0.75)"
}}
/>
) : null}
</div>
)
}
}
</ConfigConsumer>
);
}
}
polyfill(RichEditor);
export { Quill };
export default RichEditor; | the_stack |
import { Address } from "@ganache/ethereum-address";
import {
keccak,
BUFFER_EMPTY,
RPCQUANTITY_EMPTY,
Quantity,
Data
} from "@ganache/utils";
import type { LevelUp } from "levelup";
import Blockchain from "../blockchain";
import AccountManager from "../data-managers/account-manager";
import { GanacheTrie } from "../helpers/trie";
import sub from "subleveldown";
import { CheckpointDB } from "merkle-patricia-tree/dist/checkpointDb";
import * as lexico from "./lexicographic-key-codec";
import { encode } from "@ganache/rlp";
import { Account } from "@ganache/ethereum-utils";
import { KECCAK256_NULL } from "ethereumjs-util";
type KVP = { key: Buffer; value: Buffer };
const DELETED_VALUE = Buffer.allocUnsafe(1).fill(1);
const GET_CODE = "eth_getCode";
const GET_NONCE = "eth_getTransactionCount";
const GET_BALANCE = "eth_getBalance";
const GET_STORAGE_AT = "eth_getStorageAt";
const MetadataSingletons = new WeakMap<LevelUp, LevelUp>();
const LEVELDOWN_OPTIONS = {
keyEncoding: "binary",
valueEncoding: "binary"
};
function isEqualKey(encodedKey: Buffer, address: Buffer, key: Buffer) {
const decodedKey = lexico.decode(encodedKey);
const [_, keyAddress, deletedKey] = decodedKey;
return keyAddress.equals(address) && deletedKey.equals(key);
}
export class ForkTrie extends GanacheTrie {
private accounts: AccountManager;
private address: Buffer | null = null;
private isPreForkBlock = false;
private forkBlockNumber: bigint;
public blockNumber: Quantity;
private metadata: CheckpointDB;
constructor(db: LevelUp | null, root: Buffer, blockchain: Blockchain) {
super(db, root, blockchain);
this.accounts = blockchain.accounts;
this.blockNumber = this.blockchain.fallback.blockNumber;
this.forkBlockNumber = this.blockNumber.toBigInt();
if (MetadataSingletons.has(db)) {
this.metadata = new CheckpointDB(MetadataSingletons.get(db));
} else {
const metadataDb = sub(db, "f", LEVELDOWN_OPTIONS);
MetadataSingletons.set(db, metadataDb);
this.metadata = new CheckpointDB(metadataDb);
}
}
set root(value: Buffer) {
(this as any)._root = value;
}
get root() {
return (this as any)._root;
}
checkpoint() {
super.checkpoint();
this.metadata.checkpoint(this.root);
}
async commit() {
await Promise.all([super.commit(), this.metadata.commit()]);
}
async revert() {
await Promise.all([super.revert(), this.metadata.revert()]);
}
setContext(stateRoot: Buffer, address: Buffer, blockNumber: Quantity) {
(this as any)._root = stateRoot;
this.address = address;
this.blockNumber = blockNumber;
this.isPreForkBlock = blockNumber.toBigInt() < this.forkBlockNumber;
}
async put(key: Buffer, val: Buffer): Promise<void> {
return super.put(key, val);
}
/**
* Removes saved metadata from the given block range (inclusive)
* @param startBlockNumber - (inclusive)
* @param endBlockNumber - (inclusive)
*/
public async revertMetaData(
startBlockNumber: Quantity,
endBlockNumber: Quantity
) {
const db = this.metadata._leveldb;
const stream = db.createKeyStream({
gte: lexico.encode([startBlockNumber.toBuffer()]),
lt: lexico.encode([
Quantity.from(endBlockNumber.toBigInt() + 1n).toBuffer()
])
});
const batch = db.batch();
for await (const key of stream) batch.del(key);
await batch.write();
}
private createDelKey(key: Buffer) {
const blockNum = this.blockNumber.toBuffer();
return lexico.encode([blockNum, this.address, key]);
}
/**
* Checks if the key was deleted (locally -- not on the fork)
* @param key -
*/
private async keyWasDeleted(key: Buffer) {
const selfAddress = this.address === null ? BUFFER_EMPTY : this.address;
// check the uncommitted checkpoints for deleted keys before
// checking the database itself
// TODO(perf): there is probably a better/faster way of doing this for the
// common case.
const checkpoints = this.metadata.checkpoints;
for (let i = checkpoints.length - 1; i >= 0; i--) {
for (let [encodedKeyStr, value] of checkpoints[i].keyValueMap.entries()) {
if (!value || !value.equals(DELETED_VALUE)) continue;
const encodedKey = Buffer.from(encodedKeyStr, "binary");
if (isEqualKey(encodedKey, selfAddress, key)) return true;
}
}
// since we didn't find proof of deletion in a checkpoint let's check the
// database for it.
// We start searching from our database key (blockNum + address + key)
// down to the earliest block we know about.
// TODO(perf): this is just going to be slow once we get lots of keys
// because it just checks every single key we've ever deleted (before this
// one).
const stream = this.metadata._leveldb.createReadStream({
lte: this.createDelKey(key),
reverse: true
});
for await (const data of stream) {
const { key: encodedKey, value } = (data as unknown) as KVP;
if (!value || !value.equals(DELETED_VALUE)) continue;
if (isEqualKey(encodedKey, selfAddress, key)) return true;
}
// we didn't find proof of deletion so we return `false`
return false;
}
async del(key: Buffer) {
await this.lock.wait();
// we only track if the key was deleted (locally) for state tries _after_
// the fork block because we can't possibly delete keys _before_ the fork
// block, since those happened before ganache was even started
// This little optimization can cut debug_traceTransaction time _in half_.
if (!this.isPreForkBlock) {
const delKey = this.createDelKey(key);
const metaDataPutPromise = this.metadata.put(delKey, DELETED_VALUE);
const hash = keccak(key);
const { node, stack } = await this.findPath(hash);
if (node) await this._deleteNode(hash, stack);
await metaDataPutPromise;
} else {
const hash = keccak(key);
const { node, stack } = await this.findPath(hash);
if (node) await this._deleteNode(hash, stack);
}
this.lock.signal();
}
/**
* Gets an account from the fork/fallback.
*
* @param address - the address of the account
* @param blockNumber - the block number at which to query the fork/fallback.
* @param stateRoot - the state root at the given blockNumber
*/
private accountFromFallback = async (
address: Address,
blockNumber: Quantity
) => {
const { fallback } = this.blockchain;
const number = this.blockchain.fallback.selectValidForkBlockNumber(
blockNumber
);
// get nonce, balance, and code from the fork/fallback
const codeProm = fallback.request<string>(GET_CODE, [address, number]);
const promises = [
fallback.request<string>(GET_NONCE, [address, number]),
fallback.request<string>(GET_BALANCE, [address, number]),
null
] as [nonce: Promise<string>, balance: Promise<string>, put: Promise<void>];
// create an account so we can serialize everything later
const account = new Account(address);
// because code requires additional asynchronous processing, we await and
// process it ASAP
try {
const codeHex = await codeProm;
if (codeHex !== "0x") {
const code = Data.from(codeHex).toBuffer();
// the codeHash is just the keccak hash of the code itself
account.codeHash = keccak(code);
if (!account.codeHash.equals(KECCAK256_NULL)) {
// insert the code directly into the database with a key of `codeHash`
promises[2] = this.db.put(account.codeHash, code);
}
}
} catch (e) {
// Since we fired off some promises that may throw themselves we need to
// catch these errors and discard them.
Promise.all(promises).catch(e => {});
throw e;
}
// finally, set the `nonce` and `balance` on the account before returning
// the serialized data
const [nonce, balance] = await Promise.all(promises);
account.nonce =
nonce === "0x0" ? RPCQUANTITY_EMPTY : Quantity.from(nonce, true);
account.balance =
balance === "0x0" ? RPCQUANTITY_EMPTY : Quantity.from(balance);
return account.serialize();
};
private storageFromFallback = async (
address: Buffer,
key: Buffer,
blockNumber: Quantity
) => {
const result = await this.blockchain.fallback.request<string>(
GET_STORAGE_AT,
[
`0x${address.toString("hex")}`,
`0x${key.toString("hex")}`,
this.blockchain.fallback.selectValidForkBlockNumber(blockNumber)
]
);
if (!result) return null;
// remove the `0x` and all leading 0 pairs:
const compressed = result.replace(/^0x(00)*/, "");
const buf = Buffer.from(compressed, "hex");
return encode(buf);
};
async get(key: Buffer): Promise<Buffer> {
const value = await super.get(key);
if (value != null) return value;
// since we don't have this key in our local trie check if we've have
// deleted it (locally)
// we only check if the key was deleted (locally) for state tries _after_
// the fork block because we can't possibly delete keys _before_ the fork
// block, since those happened before ganache was even started
// This little optimization can cut debug_traceTransaction time _in half_.
if (!this.isPreForkBlock && (await this.keyWasDeleted(key))) return null;
if (this.address === null) {
// if the trie context's address isn't set, our key represents an address:
return this.accountFromFallback(Address.from(key), this.blockNumber);
} else {
// otherwise the key represents storage at the given address:
return this.storageFromFallback(this.address, key, this.blockNumber);
}
}
/**
* Returns a copy of the underlying trie with the interface of ForkTrie.
* @param includeCheckpoints - If true and during a checkpoint, the copy will
* contain the checkpointing metadata and will use the same scratch as
* underlying db.
*/
copy(includeCheckpoints: boolean = true) {
const db = this.db.copy() as CheckpointDB;
const secureTrie = new ForkTrie(db._leveldb, this.root, this.blockchain);
secureTrie.accounts = this.accounts;
secureTrie.address = this.address;
secureTrie.blockNumber = this.blockNumber;
if (includeCheckpoints && this.isCheckpoint) {
secureTrie.db.checkpoints = [...this.db.checkpoints];
// Our `metadata.checkpoints` needs to be the same reference to the
// parent's metadata.checkpoints so that we can continue to track these
// changes on this copy, otherwise deletions made to a contract's storage
// may not be tracked.
// Note: db.checkpoints don't need this same treatment because of the way
// the statemanager uses a contract's trie: it doesn't ever save to it.
// Instead, it saves to its own internal cache, which eventually gets
// reverted or committed (flushed). Our metadata doesn't utilize a central
// cache.
secureTrie.metadata.checkpoints = this.metadata.checkpoints;
}
return secureTrie;
}
} | the_stack |
import { getWin } from "./main";
import * as os from "os";
import * as path from "path";
import { exec } from "child_process";
import { promises as fsp } from "fs";
import * as fs from "fs";
import gunzip from "gunzip-maybe";
import * as tar from "tar-fs";
import mkdirp from "mkdirp";
import which from "which";
import {
getReleaseAsset,
getLatestReleaseVersion,
} from "@infra/artifact-helpers";
import { ENVKEY_RELEASES_BUCKET } from "@infra/stack-constants";
import { log } from "@core/lib/utils/logger";
import { dialog } from "electron";
import tempDir from "temp-dir";
import * as sudoPrompt from "@vscode/sudo-prompt";
import { UpgradeProgress } from "@core/types/electron";
import * as R from "ramda";
const MINISIGN_PUBKEY =
"RWQ5lgVbbidOxaoIEsqZjbI6hHdS5Ri/SrDk9rNFFgiQZ4COuk6Li2HK";
const arch = os.arch() == "arm64" ? "arm64" : "amd64";
const platform = os.platform() as "win32" | "darwin" | "linux";
const ext = platform == "win32" ? ".exe" : "";
let platformIdentifier: string = platform;
if (platform === "win32") {
platformIdentifier = "windows";
}
const PROGRESS_INTERVAL = 100;
const throttlingProgress: Record<"cli" | "envkeysource", boolean> = {
cli: false,
envkeysource: false,
};
export const downloadAndInstallCliTools = async (
params: {
cli?: {
nextVersion: string;
currentVersion: string | false;
};
envkeysource?: {
nextVersion: string;
currentVersion: string | false;
};
},
installType: "install" | "upgrade",
onProgress?: (p: UpgradeProgress) => void
) => {
let cliFolder: string | undefined;
let envkeysourceFolder: string | undefined;
try {
[cliFolder, envkeysourceFolder] = await Promise.all([
params.cli
? download("cli", params.cli.nextVersion, onProgress)
: undefined,
params.envkeysource
? download("envkeysource", params.envkeysource.nextVersion, onProgress)
: undefined,
]);
} catch (err) {
log("Error downloading CLI tools upgrade", { err });
throw err;
}
try {
await install(params, cliFolder, envkeysourceFolder, installType);
} catch (err) {
log("Error installing CLI tools upgrade", { err });
throw err;
}
};
export const isLatestCliInstalled = () => isLatestInstalled("cli");
export const isLatestEnvkeysourceInstalled = () =>
isLatestInstalled("envkeysource");
export const getCliBinPath = () => getBinPath("cli");
export const getCliCurrentVersion = () => getCurrentVersion("cli");
export const sudoNeededDialog = async () => {
let button: number | undefined;
try {
button = (
await dialog.showMessageBox(getWin()!, {
title: "EnvKey CLI",
message: `To install the latest EnvKey CLI tools, you will be prompted for administrator access.`,
buttons: ["OK", "Skip"],
})
)?.response;
} catch (ignored) {}
if (button !== 0) {
throw new Error(
`administrator access for installation of EnvKey CLI tools was declined.`
);
}
};
export const installCliAutocomplete = async () => {
const cliPath =
platformIdentifier === "windows"
? path.resolve(getWindowsBin(), "envkey.exe")
: "/usr/local/bin/envkey";
// attempt to install shell tab completion for all supported shells
return Promise.all(
["bash", "zsh", "fish"].map(
(shell) =>
new Promise((resolve, reject) => {
log("attempting to install CLI autocomplete...", { shell });
exec(`${cliPath} completion install --shell ${shell}`, (err) => {
if (err) {
// errors are ok, just resolve with empty string so they can be filtered out
log("CLI autocomplete installation error", { shell, err });
return resolve("");
}
return resolve(shell);
});
})
)
);
};
export const fileExists = async (filepath: string): Promise<boolean> => {
try {
await fsp.stat(filepath);
return true;
} catch (ignored) {
return false;
}
};
const isLatestInstalled = async (
project: "cli" | "envkeysource"
): Promise<true | [string, string | false]> => {
const [currentVersion, nextVersion] = await Promise.all([
getCurrentVersion(project),
getLatestVersion(project),
]);
if (!currentVersion || currentVersion != nextVersion) {
return [nextVersion, currentVersion];
}
return true;
};
const hasV1Envkeysource = async () => {
const expectedBin =
platformIdentifier === "windows"
? path.resolve(getWindowsBin(), `envkey-source.exe`)
: `/usr/local/bin/envkey-source`;
const exists = await fileExists(expectedBin);
if (!exists) {
return false;
}
const version = await new Promise<string | false>((resolve, reject) => {
exec(`${expectedBin} --version`, (err, res) => {
if (err) {
reject(err);
} else {
resolve(res?.trim() || false);
}
});
});
return version && version.startsWith("1.");
};
const getLatestVersion = async (project: "cli" | "envkeysource") =>
getLatestReleaseVersion({
project: project,
bucket: ENVKEY_RELEASES_BUCKET,
});
const getBinPath = async (
project: "cli" | "envkeysource"
): Promise<false | string> => {
const execName = { cli: "envkey", envkeysource: "envkey-source" }[project];
/*
* for envkeysource, first check for envkey-source-v2, which is
* what envkey-source will be installed as if envkey-source v1
* is already installed on the system
*/
const maybeExecSuffix = project == "envkeysource" ? "-v2" : "";
let expectedBin =
platformIdentifier === "windows"
? path.resolve(getWindowsBin(), `${execName}${maybeExecSuffix}.exe`)
: `/usr/local/bin/${execName}${maybeExecSuffix}`;
let exists = await fileExists(expectedBin);
if (!exists && maybeExecSuffix) {
expectedBin =
platformIdentifier === "windows"
? path.resolve(getWindowsBin(), `${execName}.exe`)
: `/usr/local/bin/${execName}`;
exists = await fileExists(expectedBin);
}
if (!exists) {
return false;
}
return expectedBin;
};
const getCurrentVersion = async (
project: "cli" | "envkeysource"
): Promise<false | string> => {
const expectedBin = await getBinPath(project);
if (!expectedBin) {
return false;
}
return new Promise((resolve, reject) => {
exec(`${expectedBin} --version`, (err, res) => {
if (err) {
reject(err);
} else {
resolve(res?.trim() || false);
}
});
});
};
const download = async (
projectType: "cli" | "envkeysource",
nextVersion: string,
onProgress?: (p: UpgradeProgress) => void
) => {
const execName = projectType == "cli" ? "envkey" : "envkey-source";
const assetPrefix = projectType == "cli" ? "envkey-cli" : "envkey-source";
const friendlyName = projectType == "cli" ? "EnvKey CLI" : "envkey-source";
log(`${projectType} upgrade: init`);
const assetName = `${assetPrefix}_${nextVersion}_${platformIdentifier}_${arch}.tar.gz`;
const releaseTag = `${projectType}-v${nextVersion}`;
const [fileBuf, sigBuf] = await Promise.all([
getReleaseAsset({
bucket: ENVKEY_RELEASES_BUCKET,
releaseTag,
assetName,
progress: (totalBytes: number, downloadedBytes: number) => {
const throttling = throttlingProgress[projectType];
if (onProgress && (!throttling || totalBytes == downloadedBytes)) {
onProgress({
clientProject: projectType,
downloadedBytes,
totalBytes,
});
throttlingProgress[projectType] = true;
setTimeout(() => {
throttlingProgress[projectType] = false;
}, PROGRESS_INTERVAL);
}
},
}),
getReleaseAsset({
bucket: ENVKEY_RELEASES_BUCKET,
releaseTag,
assetName: assetName + ".minisig",
}),
]);
log(`${friendlyName} upgrade: fetched latest archive`, {
sizeBytes: Buffer.byteLength(fileBuf),
assetName,
});
const folder = await unpackToFolder(fileBuf, sigBuf, execName);
log(`${friendlyName} upgrade: unpacked to folder`, { folder });
return folder;
};
// resolves to version number installed
const install = async (
params: {
cli?: {
nextVersion: string;
currentVersion: string | false;
};
envkeysource?: {
nextVersion: string;
currentVersion: string | false;
};
},
cliFolder: string | undefined,
envkeysourceFolder: string | undefined,
installType: "install" | "upgrade"
): Promise<void> => {
// installs envkey-source as envkey-source-v2 if envkey-source v1 is already installed to avoid overwriting it and breaking things
if (envkeysourceFolder && (await hasV1Envkeysource())) {
const envkeysourcePath = path.resolve(
envkeysourceFolder,
`envkey-source${ext}`
);
if (await fileExists(envkeysourcePath)) {
await fsp.rename(
envkeysourcePath,
path.resolve(envkeysourceFolder, `envkey-source-v2${ext}`)
);
}
}
let binDir: string;
switch (platform) {
case "darwin":
case "linux":
binDir = "/usr/local/bin";
break;
case "win32":
binDir = getWindowsBin();
break;
default:
throw new Error(
`Cannot install CLI tools to unsupported platform ${platform}`
);
}
await copyExecFiles(cliFolder, envkeysourceFolder, binDir);
if (installType == "install") {
// add `es` alias for envkey-source unless an `es` is already in PATH
let hasExistingEsCommand = false;
try {
hasExistingEsCommand = await new Promise((resolve) => {
which("es", (err, path) => {
if (err) {
log("which('es') error:", { err });
}
resolve(Boolean(path));
});
});
} catch (err) {
log("caught error determining `hasExistingEsCommand`", { err });
}
log("", { hasExistingEsCommand });
const symlinkExists = await fileExists(path.join(binDir, "es"));
log("", { symlinkExists });
if (!hasExistingEsCommand && !symlinkExists) {
// windows requires admin privileges to create a symlink
if (platform == "win32") {
log("attempting to create `es` symlink on Windows");
try {
await sudoNeededDialog();
} catch (err) {
log("error warning user of administrator privileges request", {
err,
});
}
await new Promise<void>((resolve, reject) => {
try {
log("attempting symlink with sudo-prompt on Windows");
sudoPrompt.exec(
`mklink ${path.join(binDir, "es")} ${path.join(
binDir,
"envkey-source.exe"
)}`,
{
name: `EnvKey CLI Tools Installer`,
},
(err: Error | undefined) => {
if (err) {
log(`Windows sudo-prompt create symlink error`, { err });
return reject(err);
}
log("Windows: created symlink with administrator privileges");
resolve();
}
);
} catch (err) {
log(`Windows sudo-prompt create symlink error`, { err });
reject(err);
}
});
} else {
await fsp
.symlink(path.join(binDir, "envkey-source"), path.join(binDir, "es"))
.catch(async (err) => {
log("create symlink err", { err });
});
}
}
}
log(`CLI tools upgrade: completed successfully`, {
cli: params.cli?.nextVersion,
envkeysource: params.envkeysource?.nextVersion,
});
};
const getWindowsBin = () => path.resolve(os.homedir(), "bin");
// resolves to the folder where it unrolled the archive
const unpackToFolder = async (
archiveBuf: Buffer,
sigBuf: Buffer,
execName: string
): Promise<string> => {
return new Promise(async (resolve, reject) => {
const tempFileBase = `${execName}_${+new Date() / 1000}`;
const tempFilePath = path.resolve(tempDir, `${tempFileBase}.tar.gz`);
const tempSigPath = path.resolve(tempDir, `${tempFileBase}.tar.gz.minisig`);
const tempFileTarPath = path.resolve(tempDir, `${tempFileBase}.tar`);
const tempOutputDir = path.resolve(tempDir, tempFileBase);
await Promise.all([
fsp.writeFile(tempFilePath, archiveBuf),
fsp.writeFile(tempSigPath, sigBuf),
]);
// verify binary with vendored minisign
const minisignPath = path.join.apply(this, [
...(process.env.MINISIGN_PATH_FROM_ELECTRON_RESOURCES
? [
process.resourcesPath,
process.env.MINISIGN_PATH_FROM_ELECTRON_RESOURCES,
]
: [process.env.MINISIGN_PATH!]),
...({
win32: ["windows", "minisign.exe"],
darwin: ["mac", arch, "minisign"],
linux: ["linux", "minisign"],
}[platform] ?? []),
]);
log(`Verifying ${execName} with minisign`, {
platform,
arch,
minisignPath,
});
await new Promise((resolve, reject) => {
exec(
`"${minisignPath}" -Vm ${tempFilePath} -P ${MINISIGN_PUBKEY}`,
(error, stdout, stderr) => {
if (stderr) {
log(`Error verifying signature with minisig`, { stderr });
dialog.showMessageBox({
title: "EnvKey CLI Tools",
message: `There was a problem verifying the signature of the \`${execName}\` CLI tool executable. This might indicate a security issue. Please contact support@envkey.com so we can investigate.`,
buttons: ["OK"],
});
return reject(new Error(stderr));
}
if (error) {
log(`Error executing minisign`, { error });
return reject(error);
}
log(`Verified signature with minisig`, { stdout });
resolve(true);
}
);
});
const tarredGzipped = fs.createReadStream(tempFilePath);
const tarredOnlyWrite = fs.createWriteStream(tempFileTarPath);
tarredGzipped.on("error", reject);
tarredOnlyWrite.on("error", reject);
tarredOnlyWrite.on("close", () => {
const tarredOnlyRead = fs.createReadStream(tempFileTarPath);
tarredOnlyRead.on("error", reject);
tarredOnlyRead.on("close", () => {
resolve(tempOutputDir);
});
tarredOnlyRead.pipe(tar.extract(tempOutputDir));
});
tarredGzipped.pipe(gunzip()).pipe(tarredOnlyWrite);
});
};
// cross-platform copy a file and overwrite if it exists.
const copyExecFiles = async (
cliFolder: string | undefined,
envkeysourceFolder: string | undefined,
destinationFolder: string,
withSudoPrompt?: boolean,
argFiles?: [string, string][]
): Promise<void> => {
const files =
argFiles ??
((await Promise.all(
(
[
[envkeysourceFolder, `envkey-source${ext}`],
[envkeysourceFolder, `envkey-source-v2${ext}`],
[cliFolder, `envkey${ext}`],
[cliFolder, "envkey-keytar.node"],
] as [string | undefined, string][]
).map(([folder, file]) => {
if (!folder) {
return undefined;
}
const tmpPath = path.resolve(folder, file);
return fileExists(tmpPath).then((exists) =>
exists ? [folder, file] : undefined
);
})
).then(R.filter(Boolean))) as [string, string][]);
if (withSudoPrompt) {
const cmd = `mkdir -p ${destinationFolder} && chown ${
process.env.USER
} ${destinationFolder} && ${files
.map(
([folder, file]) =>
`cp -f ${path.resolve(folder, file)} ${destinationFolder}`
)
.join(" && ")}`;
log("copy exec files with sudo prompt", { cmd });
await sudoNeededDialog();
return new Promise((resolve, reject) => {
try {
sudoPrompt.exec(
cmd,
{
name: `EnvKey CLI Tools Installer`,
},
(err: Error | undefined) => {
if (err) {
log(`sudo CLI tools installer - handler error`, { err });
return reject(err);
}
log("copy exec files with sudo prompt success");
resolve();
}
);
} catch (err) {
log(`sudo CLI tool installer error - exec error`, { err });
reject(err);
}
});
}
try {
await mkdirp(destinationFolder);
await Promise.all(
files.map(([folder, file]) => {
const tmpPath = path.resolve(folder, file);
const destinationPath = path.resolve(destinationFolder, file);
log(`copying exec files - copy ${tmpPath} to ${destinationPath}...`);
return fsp
.rm(destinationPath)
.catch(async (err) => {})
.then(() => {
return fsp
.copyFile(tmpPath, destinationPath)
.then(() =>
log(`copied exec files - copy ${tmpPath} to ${destinationPath}`)
);
});
})
);
} catch (err) {
if (err.message?.includes("permission denied")) {
log("copy exec files - permission denied error - retrying with sudo", {
err,
});
return copyExecFiles(
cliFolder,
envkeysourceFolder,
destinationFolder,
true,
files
);
} else {
if (platform == "win32" && err.code == "EBUSY") {
await dialog.showMessageBox({
title: "EnvKey CLI",
message: `In order to upgrade, any running envkey-source.exe processes will be closed`,
buttons: ["Continue"],
});
await new Promise<void>((resolve, reject) => {
exec(`taskkill /F /IM envkey-source.exe /T`, (err) =>
err ? reject(err) : resolve()
);
});
return copyExecFiles(
cliFolder,
envkeysourceFolder,
destinationFolder,
withSudoPrompt,
files
);
} else {
log("copy exec files error", { err });
throw err;
}
}
}
}; | the_stack |
import { ValuedProperty } from "./prop";
import { i18n } from "@/i18n";
/**
* ๅ ๆ
*/
export interface BuffData {
id: string;
/** ๅ็งฐ(i18n) */
name: string;
/** ็ฑปๅ */
type: BuffType;
/** ็ๆ็ฎๆ */
target: string;
/** ๅฑๆง [ๅฑๆงๅ็งฐ, ๆฐๅผ] */
props?: [string, number][];
/** ้ๅผบๅบฆๅๅ็ๅฑๆง [ๅฑๆงๅ็งฐ, ๆฐๅผ, ๅบ็กๅผ] */
dynamicProps?: [string, number, number][];
/** ๅ ๅ ๆๆ */
multiLayer?: MultiLayer;
/** ๅๆฐ */
parms?: [string, string];
/** ้ป่ฎคๅๆฐ */
defaultValue?: number;
defaultLayer?: number;
}
export interface MultiLayer {
/** ๆๅคงๅฑๆฐ */
maxStack: number;
baseLayer?: number;
stackableProps?: [string, number][];
unstackableProps?: [string, number][][];
}
export enum BuffType {
Arcane,
Team,
BaseDamage,
TotalDamage,
ElementDamage,
CritDamage,
Speed,
Other,
}
/**
* ๅฎไฝBUFF็ฑป
*/
export class Buff {
data: BuffData;
layer = 1;
baseLayer = 0;
power = 1;
constructor(data: BuffData) {
this.data = data;
if (data.defaultLayer) this.layer = data.defaultLayer;
if (data.multiLayer && data.multiLayer.baseLayer) this.baseLayer = data.multiLayer.baseLayer;
if (data.defaultValue) this.power = data.defaultValue;
}
get name() {
return this.data.name;
}
get shortName() {
return i18n.t(`buff.${this.name}`).replace(/ \(.+?\)/, "");
}
get props() {
let pout = [];
if (this.data.props) pout = pout.concat(this.data.props);
if (this.data.dynamicProps) pout = pout.concat(this.data.dynamicProps.map(([n, v, p]) => [n, v * this.power + p]));
if (this.data.multiLayer) {
if (this.data.multiLayer.stackableProps)
pout = pout.concat(this.data.multiLayer.stackableProps.map(([n, v]) => [n, v * (this.layer + this.baseLayer)]));
if (this.data.multiLayer.unstackableProps)
pout = pout.concat(this.data.multiLayer.unstackableProps[this.layer - 1]);
}
return pout;
}
/**
* ๆพ็คบ็จProps
*
* @readonly
* @memberof NormalMod
*/
get vProps() {
return this.props.map(prop => {
let vp = ValuedProperty.parse(prop);
return {
id: vp.id,
fullName: vp.fullString,
shortName: vp.shortString,
value: vp.value,
};
});
}
get layerEnable() {
return !!this.data.multiLayer;
}
get powerEnable() {
return !!this.data.parms;
}
}
/**
* ้ๆฑๆๆ:
* ๆ้ๆทปๅ ๅธธ็จbuffๅนถไธ็ปๆๅฏไปฅ็ผ่พ
*/
/** ๅ ๆๅ่กจ */
export const BuffList: BuffData[] = [
// ่ต่ฝ
...[
["a3", "arcaneAgility", [["onDamaged"], ["f", 10]], "Warframe+"], // ็ตๆ่ต่ฝ
["a4", "arcaneBarrier", [["onDamaged"], ["fsr", 1]], "Warframe+"], // ๅฃๅ่ต่ฝ
["a5", "arcaneAegis", [["onDamaged"], ["psr", 5]], "Warframe+"], // ็ฅ็พ่ต่ฝ
["a6", "arcaneTrickery", [["onFinish"], ["ivb", 5]], "Warframe"], // ่ฏก่ฎก่ต่ฝ
["a7", "arcaneUltimatum", [["onFinish"], ["ea", 200]], "Warframe"], // ้็่ต่ฝ
["a8", "arcaneArachne", [["onWalllatch"], ["D", 25]], "Weapon"], // ่่่ต่ฝ
["a9", "arcaneGrace", [["onDamaged"], ["phr", 1]], "Warframe+"], // ไผ้
่ต่ฝ
["aA", "arcaneGuardian", [["onDamaged"], ["ea", 150]], "Warframe+"], // ไฟๅซ่
่ต่ฝ
["aB", "arcanePhantasm", [["onBlock"], ["f", 10]], "Warframe+"], // ๅนป่ฑก่ต่ฝ
["aJ", "arcaneAcceleration", [["R", 15]], "Rifle"], // ๅ ้่ต่ฝ
["aK", "arcaneAvenger", [["i0", 7.5]], "Weapon"], // ๅคไป่
่ต่ฝ
["aL", "arcaneAwakening", [["D", 25]], "Secondary"], // ่ง้่ต่ฝ
["aM", "arcaneFury", [["K", 30]], "Melee"], // ็ๆ่ต่ฝ
["aN", "arcaneStrike", [["J", 10]], "Melee"], // ้ๆป่ต่ฝ
["aO", "arcaneMomentum", [["F", 25]], "Sniper"], // ๅจ้่ต่ฝ
["aP", "arcanePrecision", [["D", 50]], "Secondary"], // ็ฒพ็กฎ่ต่ฝ
["aQ", "arcaneRage", [["D", 30]], "Primary"], // ๆคๆ่ต่ฝ
["aR", "arcaneTempo", [["R", 15]], "Shotgun"], // ่ๅฅ่ต่ฝ
["aS", "arcaneVelocity", [["R", 20]], "Secondary"], // ่ฟ
้่ต่ฝ
["aT", "paxBolt", [["t", 7.5], ["x", 7.5]], "Warframe", 3], // ๅๅนณ็ต้ช
["aU", "arcaneTanker", [["onEquip"], ["ea", 200]], "Warframe"], // ๅฆๅ
่ต่ฝ
].map(
v =>
({
id: v[0],
name: v[1],
type: BuffType.Arcane,
target: v[3],
defaultLayer: v[4] || 5,
multiLayer: {
baseLayer: 1,
maxStack: v[4] || 5,
stackableProps: v[2],
},
} as BuffData)
),
...[
["vA", "virtuosNull", [["erc", 5]], "Amp"], // ๆญฃ็ด็ฉบๆ
["vB", "virtuosTempo", [["R", 15]], "Amp"], // ๆญฃ็ด่ๅฅ
["vC", "virtuosFury", [["D", 7.5]], "Amp"], // ๆญฃ็ด็ๆ
["vD", "virtuosStrike", [["1", 15]], "Amp"], // ๆญฃ็ดๆๅป
["vE", "virtuosShadow", [["0", 15]], "Amp"], // ๆญฃ็ดๆๅฝฑ
["vF", "virtuosGhost", [["2", 15]], "Amp"], // ๆญฃ็ด้ฌผ้ญ
["vH", "virtuosSurge", [["vte", 25]], "Amp"], // ๆญฃ็ด็นๆดไผ
["vG", "virtuosTrojan", [["vtv", 25]], "Amp"], // ๆญฃ็ด็ชๆณข
["vI", "virtuosSpike", [["vtp", 25]], "Amp"], // ๆญฃ็ดๅฐๅบ
["vJ", "virtuosForge", [["vth", 25]], "Amp"], // ๆญฃ็ด็็
// ["mA", "magusVigor", [[]], "Operator"],
// ["mB", "magusHusk", [[]], "Operator"],
// ["mC", "magusCloud", [[]], "Operator"],
// ["mD", "magusCadence", [[]], "Operator"],
// ["mE", "magusReplenish", [[]], "Operator"],
// ["mF", "magusElevate", [[]], "Operator"],
// ["mG", "magusNourish", [[]], "Operator"],
// ["mH", "magusOverload", [[]], "Operator"],
// ["mI", "magusGlitch", [[]], "Operator"],
// ["mJ", "magusRevert", [[]], "Operator"],
// ["mK", "magusFirewall", [[]], "Operator"],
// ["mL", "magusDrive", [[]], "Operator"],
// ["mM", "magusLockdown", [[]], "Operator"],
// ["mN", "magusDestruct", [[]], "Operator"],
// ["mO", "magusAnomaly", [[]], "Operator"],
["mP", "magusMelt", [["4", 25]], "Amp"],
// ["mQ", "magusAccelerant", [[]], "Operator"],
// ["mR", "magusRepair", [[]], "Operator"],
].map(
v =>
({
id: v[0],
name: v[1],
type: BuffType.Arcane,
target: v[3],
defaultLayer: v[4] || 3,
multiLayer: {
baseLayer: 1,
maxStack: v[4] || 3,
stackableProps: v[2],
},
} as BuffData)
),
...[
["b4", "kuvaHeat", [["b4", 1, 0]], "Kuva Weapon"], // ๅๅง็ซไผค
["b5", "kuvaCold", [["b5", 1, 0]], "Kuva Weapon"], // ๅๅงๅฐไผค
["b6", "kuvaToxin", [["b6", 1, 0]], "Kuva Weapon"], // ๅๅงๆฏไผค
["b7", "kuvaElectricity", [["b7", 1, 0]], "Kuva Weapon"], // ๅๅง็ตไผค
["b8", "kuvaImpact", [["b8", 1, 0]], "Kuva Weapon"], // ๅๅงๅฒๅป
["bM", "kuvaMagnetic", [["bM", 1, 0]], "Kuva Weapon"], // ๅๅง็ฃๅ
["bR", "kuvaRadiation", [["bR", 1, 0]], "Kuva Weapon"], // ๅๅง่พๅฐ
["t4", "tenetHeat", [["b4", 1, 0]], "Tenet Weapon"], // ๅๅง็ซไผค
["t5", "tenetCold", [["b5", 1, 0]], "Tenet Weapon"], // ๅๅงๅฐไผค
["t6", "tenetToxin", [["b6", 1, 0]], "Tenet Weapon"], // ๅๅงๆฏไผค
["t7", "tenetElectricity", [["b7", 1, 0]], "Tenet Weapon"], // ๅๅง็ตไผค
["t8", "tenetImpact", [["b8", 1, 0]], "Tenet Weapon"], // ๅๅงๅฒๅป
["tM", "tenetMagnetic", [["bM", 1, 0]], "Tenet Weapon"], // ๅๅง็ฃๅ
["tR", "tenetRadiation", [["bR", 1, 0]], "Tenet Weapon"], // ๅๅง่พๅฐ
].map(
v =>
({
id: v[0],
name: v[1],
type: BuffType.ElementDamage,
target: v[3],
dynamicProps: v[2],
parms: ["power", "%"],
defaultValue: 60,
} as BuffData)
),
// ๆ็ฒๅ ๆ
...[
["A0", "growingPower", [["t", 25.5]], "Warframe+"], // ๆ้ฟไนๅ
["A1", "powerDonation", [["t", 30]], "Warframe+"], // ็ฎๅบๅ้
].map(
v =>
({
id: v[0],
name: v[1],
type: BuffType.Team,
target: v[3],
defaultLayer: v[4] || 1,
multiLayer: {
maxStack: v[4] || 6,
stackableProps: v[2],
},
} as BuffData)
),
{
id: "rb",
name: "razorwingBlitz", // ่ถ ๅ็ฟผ้ชๅป
type: BuffType.Speed,
target: "Dex Pixia",
dynamicProps: [["R", 1, 0]],
parms: ["power", "%"],
defaultValue: 100,
},
{
id: "cb4",
name: "chromaticBlade4", // Excalibur ๅๅฝฉๅๅ ็ซ
type: BuffType.Other,
target: "Exalted Blade",
props: [["p4", 100]],
dynamicProps: [["2", 3, 0]],
parms: ["power", "%"],
defaultValue: 100,
},
{
id: "cb5",
name: "chromaticBlade5", // Excalibur ๅๅฝฉๅๅ ๅฐ
type: BuffType.Other,
target: "Exalted Blade",
props: [["p5", 100]],
dynamicProps: [["2", 3, 0]],
parms: ["power", "%"],
defaultValue: 100,
},
{
id: "cb6",
name: "chromaticBlade6", // Excalibur ๅๅฝฉๅๅ ๆฏ
type: BuffType.Other,
target: "Exalted Blade",
props: [["p6", 100]],
dynamicProps: [["2", 3, 0]],
parms: ["power", "%"],
defaultValue: 100,
},
{
id: "cb7",
name: "chromaticBlade7", // Excalibur ๅๅฝฉๅๅ ็ต
type: BuffType.Other,
target: "Exalted Blade",
props: [["p7", 100]],
dynamicProps: [["2", 3, 0]],
parms: ["power", "%"],
defaultValue: 100,
},
{
id: "vm",
name: "vitalityMote", // Wisp ๆดปๅๅฐๅ
type: BuffType.Team,
target: "Warframe+",
dynamicProps: [["eh", 3, 0], ["hps", 0.3, 0]],
parms: ["power", "%"],
defaultValue: 200,
},
{
id: "hm",
name: "hasteMote", // Wisp ๆฅ้ๅฐๅ
type: BuffType.Team,
target: "Warframe+",
dynamicProps: [["f", 0.2, 0]],
parms: ["power", "%"],
defaultValue: 200,
},
{
id: "h",
name: "hasteMote", // Wisp ๆฅ้ๅฐๅ
type: BuffType.Speed,
target: "Weapon",
dynamicProps: [["R", 0.3, 0], ["J", 0.2, 0]],
parms: ["power", "%"],
defaultValue: 200,
},
{
id: "Q",
name: "parasiticLink", // ่3 ๅฏ็้พๆฅ
type: BuffType.Team,
target: "Warframe+",
dynamicProps: [["ovs", 0.25, 0]],
parms: ["power", "%"],
defaultValue: 364,
},
{
id: "q",
name: "provoke", // ๆฟๆ (ๅๅนณๆ่ก
)
type: BuffType.Team,
target: "Warframe+",
dynamicProps: [["t", 1, 0]],
parms: ["power", "%"],
defaultValue: 80,
},
{
id: "y",
name: "commonResistance", // ้็จๅไผค
type: BuffType.Team,
target: "Warframe+",
dynamicProps: [["res", 1, 0]],
parms: ["power", "%"],
defaultValue: 75,
},
{
id: "X",
name: "corruption", // ๅ ่ฝ
type: BuffType.Other,
target: "Warframe+",
props: [["ovs", 100], ["ovr", 100]],
},
{
id: "Ab",
name: "arbitrationsBuff", // ไปฒ่ฃๅ ๆ
type: BuffType.Other,
target: "Warframe",
props: [["t", 300]],
},
{
id: "x",
name: "speed", // ๅ ้ (Volt)
type: BuffType.Team,
target: "Warframe+",
dynamicProps: [["f", 0.5, 0]],
parms: ["power", "%"],
defaultValue: 348,
},
// ๅ ๆณๅบไผค็ฑป
// ๆญปไบกไน็ผๅ
็ฏ็ญ
{
id: "b",
name: "baseDamage", // ้็จๅบไผค
type: BuffType.BaseDamage,
target: "Weapon",
dynamicProps: [["dmg", 1, 0]],
parms: ["power", "%"],
defaultValue: 100,
},
{
id: "ms",
name: "multishot", // ้็จๅบไผค
type: BuffType.BaseDamage,
target: "Gun",
dynamicProps: [["S", 1, 0]],
parms: ["power", "%"],
defaultValue: 100,
},
{
id: "gf",
name: "firerate", // ้็จๆป้
type: BuffType.BaseDamage,
target: "Gun",
dynamicProps: [["R", 1, 0]],
parms: ["power", "%"],
defaultValue: 100,
},
{
id: "gr",
name: "reload", // ่ฃ
ๅกซ้ๅบฆ (้็จ)
type: BuffType.Speed,
target: "Gun",
dynamicProps: [["F", 1, 0]],
parms: ["power", "%"],
defaultValue: 100,
},
{
id: "gm",
name: "magazine", // ๅผนๅฃๅฎน้ (้็จ)
type: BuffType.Speed,
target: "Gun",
dynamicProps: [["L", 1, 0]],
parms: ["power", "%"],
defaultValue: 100,
},
{
id: "B",
name: "ballisticBattery", // ๅฅณๆช1 ๅผน้่่ฝ (ๅ ๆฐๅผ)
type: BuffType.BaseDamage,
target: "Gun",
dynamicProps: [["apd", 16, 0]],
parms: ["power", "%"],
defaultValue: 200,
},
{
id: "G",
name: "shootingGallery", // ๅฅณๆช2 ้ถๅบ
type: BuffType.BaseDamage,
target: "All",
dynamicProps: [["dmg", 0.25, 0]],
parms: ["power", "%"],
defaultValue: 200,
},
{
id: "A",
name: "vexArmor", // ้พ3 ๆจๆๆค็ฒ
type: BuffType.BaseDamage,
target: "Weapon",
dynamicProps: [["dmg", 2.75, 0]],
parms: ["power", "%"],
defaultValue: 348,
},
{
id: "w4",
name: "elementalWard4", // ้พ2 ๅ
็ด ไนๆค ็ซ
type: BuffType.Team,
target: "Warframe+",
dynamicProps: [["h", 2, 0]],
parms: ["power", "%"],
defaultValue: 348,
},
{
id: "w5",
name: "elementalWard5", // ้พ2 ๅ
็ด ไนๆค ๅฐ
type: BuffType.Team,
target: "Warframe+",
dynamicProps: [["a", 1.5, 0]],
parms: ["power", "%"],
defaultValue: 348,
},
{
id: "w6",
name: "elementalWard6", // ้พ2 ๅ
็ด ไนๆค ๆฏ
type: BuffType.Team,
target: "Warframe+",
dynamicProps: [["F", 0.35, 0], ["hr", 0.35, 0]],
parms: ["power", "%"],
defaultValue: 348,
},
{
id: "w7",
name: "elementalWard7", // ้พ2 ๅ
็ด ไนๆค ็ต
type: BuffType.Team,
target: "Warframe+",
dynamicProps: [["s", 1, 0]],
parms: ["power", "%"],
defaultValue: 348,
},
{
id: "A3",
name: "vexArmor", // ้พ3 ๆจๆๆค็ฒ
type: BuffType.Team,
target: "Warframe+",
dynamicProps: [["a", 3.5, 0], ["dmg", 2.75, 0]],
parms: ["power", "%"],
defaultValue: 348,
},
{
id: "A4",
name: "baseArmor", // ้พ3 ๆจๆๆค็ฒ
type: BuffType.Team,
target: "Warframe+",
dynamicProps: [["ea", 1, 0]],
parms: ["power", "%"],
defaultValue: 60,
},
{
id: "J",
name: "mallet", // DJ4 ๅผบ้ณๅขๅน
type: BuffType.BaseDamage,
target: "Weapon",
dynamicProps: [["dmg", 2, 0]],
parms: ["power", "%"],
defaultValue: 348,
},
{
id: "d",
name: "deadEye", // ๆญปไบกไน็ผ Dead Eye
type: BuffType.BaseDamage,
target: "Sniper",
dynamicProps: [["dmg", 52.5, 0]],
parms: ["mul", "x"],
},
{
id: "m",
name: "metamorphosis", // ๆถๅฅน1 ๆผๅคไบคๆฟ
type: BuffType.BaseDamage,
target: "Weapon",
dynamicProps: [["dmg", 0.25, 0]],
parms: ["power", "%"],
defaultValue: 348,
},
{
id: "v",
name: "vigorousSwap", // ๅผบๅๅๆข (MOD)
type: BuffType.BaseDamage,
target: "Weapon",
multiLayer: {
maxStack: 11,
stackableProps: [["dmg", 15]],
},
defaultLayer: 11,
},
{
id: "z",
name: "strength", // ๅผบๅบฆ
type: BuffType.BaseDamage,
target: "Regulators",
dynamicProps: [["dmg", 1.5, 0]],
parms: ["power", "%"],
defaultValue: 100,
},
// ไนๆณๆปไผค็ฑป
{
id: "Z",
name: "strength", // ๅผบๅบฆ
type: BuffType.TotalDamage,
target: "Exalted",
dynamicProps: [["eid", 1, -100]],
parms: ["power", "%"],
defaultValue: 100,
},
{
id: "c",
name: "combo", // ่ฟๅป
type: BuffType.TotalDamage,
target: "Sniper",
dynamicProps: [["oad", 100, -100]],
parms: ["status", ""],
defaultValue: 2,
},
{
id: "mc",
name: "meleeCombo", // ่ฟๅป
type: BuffType.TotalDamage,
target: "Melee",
dynamicProps: [["red", 1, 0]],
parms: ["status", ""],
defaultValue: 25,
},
{
id: "o",
name: "finalDamage", // ้็จ็ปไผค
type: BuffType.TotalDamage,
target: "Weapon",
dynamicProps: [["oad", 1, 0]],
parms: ["power", "%"],
defaultValue: 100,
},
{
id: "R",
name: "roar", // ็ๅผ
type: BuffType.TotalDamage,
target: "Weapon+",
dynamicProps: [["aed", 0.5, 0]],
parms: ["power", "%"],
defaultValue: 348,
},
{
id: "E",
name: "eclipse", // ๅฐไธ3 ้ปฏ็ถๅคฑ่ฒ
type: BuffType.TotalDamage,
target: "Weapon",
dynamicProps: [["oad", 2, 0]],
parms: ["power", "%"],
defaultValue: 348,
},
{
id: "M",
name: "voidStrike", // M่นฒ ่็ฉบ้ๅป
type: BuffType.TotalDamage,
target: "All",
dynamicProps: [["oad", 12, 0]],
parms: ["time", "s"],
defaultValue: 30,
},
{
id: "U",
name: "unairu", // UNAIRU ่็ต
type: BuffType.TotalDamage,
target: "Amp",
multiLayer: {
maxStack: 4,
stackableProps: [["oad", 25]],
},
defaultLayer: 4,
},
{
id: "K",
name: "block", // ๆ ผๆกๅ ๆ
type: BuffType.TotalDamage,
target: "Ack & Brunt",
multiLayer: {
maxStack: 4,
stackableProps: [["oad", 17.5]],
},
defaultLayer: 4,
},
{
id: "sh",
name: "shepherd", // ็ง็พไบบ
type: BuffType.Team,
target: "Companion",
multiLayer: {
maxStack: 4,
stackableProps: [["eh", 300], ["ea", 180]],
},
defaultLayer: 1,
},
{
id: "N",
name: "molecularPrime", // nova4 ๅๅญๅกซๅ
type: BuffType.TotalDamage,
target: "All",
props: [["oad", 100]],
},
{
id: "C",
name: "conditionOverlord", // ๅผๅต่ถ
้ ๆฌกๆน่ฎก็ฎ
type: BuffType.BaseDamage,
target: "All",
multiLayer: {
maxStack: 16,
stackableProps: [["esc", 1]],
},
defaultLayer: 2,
},
{
id: "T",
name: "stealth", // ๅท่ขญ
type: BuffType.TotalDamage,
target: "Melee",
dynamicProps: [["ds", 20, 100], ["sd", 20, 100]],
parms: ["level", ""],
defaultValue: 30,
},
// ้ๅ ๅ
็ด ็ฑป
{
id: "f",
name: "fireballFrenzy", // ็ซ้ธก้ๅข1 ็็ญ็ซ็ ็ซ็ฐไผคๅฎณ
type: BuffType.ElementDamage,
target: "Weapon",
dynamicProps: [["4", 1, 0]],
parms: ["power", "%"],
defaultValue: 348,
},
{
id: "a",
name: "flashAccelerant", // ็ซ้ธก้ๅข2 ้ช่ๅฉ็ ็ซ็ฐไผคๅฎณ
type: BuffType.ElementDamage,
target: "Weapon",
dynamicProps: [["4", 0.5, 0]],
parms: ["power", "%"],
defaultValue: 348,
},
{
id: "F",
name: "freezeForce", // ๅฐ็ท้ๅข1 ๅฏๅฐไนๅ ๅฐๅปไผคๅฎณ
type: BuffType.ElementDamage,
target: "Weapon",
dynamicProps: [["5", 1, 0]],
parms: ["power", "%"],
defaultValue: 348,
},
{
id: "S",
name: "shockTrooper", // ็ต็ท้ๅข1 ็ตๅปๅฅๅ
ต ็ตๅปไผคๅฎณ
type: BuffType.ElementDamage,
target: "Weapon",
dynamicProps: [["7", 1, 0]],
parms: ["power", "%"],
defaultValue: 348,
},
{
id: "O",
name: "smiteInfusion", // ๅฅถ็ธ้ๅข1 ๆฉๅปๆด็คผ ่พๅฐไผคๅฎณ
type: BuffType.ElementDamage,
target: "Weapon",
dynamicProps: [["erd", 1, 0]],
parms: ["power", "%"],
defaultValue: 348,
},
{
id: "D",
name: "venomDose", // ๆฏๅฆ้ๅข1 ็ๆฏ้ๅ ่
่ไผคๅฎณ
type: BuffType.ElementDamage,
target: "Weapon",
dynamicProps: [["ecd", 1, 0]],
parms: ["power", "%"],
defaultValue: 348,
},
{
id: "s",
name: "toxin", // ็ฑณๅฐ็ๅ ๆ
type: BuffType.ElementDamage,
target: "Weapon",
dynamicProps: [["etd", 1, 0]],
parms: ["power", "%"],
defaultValue: 10,
},
// ้ๅบฆ็ฑป
// ็ต็ท2 ๅฅณๆฑๅญ2 ๆฏ้พ2
// Octavia DJ 23
{
id: "P",
name: "speed", // ๅ ้ (Volt)
type: BuffType.Speed,
target: "Melee",
dynamicProps: [["J", 0.5, 0]],
parms: ["power", "%"],
defaultValue: 348,
},
{
id: "W",
name: "warcry", // ๅๅฎ (Valkyr)
type: BuffType.Speed,
target: "Melee",
dynamicProps: [["J", 0.5, 0]],
parms: ["power", "%"],
defaultValue: 250,
},
{
id: "w",
name: "elementalWard", // ๅ
็ด ไนๆค (ๆฏ้พ)
type: BuffType.Speed,
target: "Gun",
dynamicProps: [["F", 0.35, 0]],
parms: ["power", "%"],
defaultValue: 171.4,
},
// ๆดๅป็ฑป
{
id: "t",
name: "critChance", // ้็จๆดๅป
type: BuffType.CritDamage,
target: "All",
dynamicProps: [["i0", 1, 0]],
parms: ["power", "%"],
defaultValue: 60,
},
{
id: "I",
name: "empoweredQuiver", // ๅผๅฆน้ๅข1่ธฉ็บฟ
type: BuffType.CritDamage,
target: "All",
dynamicProps: [["1", 1, 0]],
parms: ["power", "%"],
defaultValue: 348,
},
{
id: "H",
name: "covenant", // ไธปๆ4 ๅบไฝๅฃ็บฆ
type: BuffType.CritDamage,
target: "Weapon",
props: [["i0", 50], ["cwh", 150]],
},
{
id: "l",
name: "gladiator", // ่งๆๅฃซ็ปๅๆๆ
type: BuffType.CritDamage,
target: "Melee",
multiLayer: {
maxStack: 6,
stackableProps: [["bldr", 10]],
},
},
{
id: "vi",
name: "vigilante", // ็งๆณ็ปๅๆๆ
type: BuffType.CritDamage,
target: "Primary",
multiLayer: {
maxStack: 6,
stackableProps: [["ce", 15]],
},
},
{
id: "r",
name: "charm", // ๆ็ฆ
type: BuffType.CritDamage,
target: "Weapon",
props: [["ccl", 200]],
},
// ๅคๅ็ฑป
{
id: "V",
name: "electricShield", // ็ต็พ
type: BuffType.Other,
target: "Ranged",
props: [["e1", 100]],
multiLayer: {
maxStack: 48,
stackableProps: [["eed", 50]],
},
defaultLayer: 6,
},
{
id: "V2",
name: "energyShell", // ่ฝ้ๆค็ฝฉ
type: BuffType.Other,
target: "Ranged",
props: [["e1", 100], ["efd", 50]],
},
{
id: "e",
name: "fireBlast", // ็ซๅ
type: BuffType.Other,
target: "Ranged",
multiLayer: {
maxStack: 6,
stackableProps: [["efd", 50]],
},
},
{
id: "L",
name: "mutalistQuanta", // ๅผ่้ๅญๆชๆฌก่ฆ
type: BuffType.Other,
target: "Ranged",
props: [["e1", 25], ["i0", 25], ["oad", -33.3]],
multiLayer: {
maxStack: 3,
unstackableProps: [[["eed", 100]], [["eed", 366.6]], [["eed", 500]]],
},
defaultLayer: 3,
},
]; | the_stack |
import React from 'react'
import { render, fireEvent, createEvent, waitFor } from '@testing-library/react'
import userEvent, { specialChars } from '@testing-library/user-event'
import { DatePicker } from './DatePicker'
import { sampleLocalization } from './i18n'
import { today } from './utils'
import {
DAY_OF_WEEK_LABELS,
MONTH_LABELS,
VALIDATION_MESSAGE,
} from './constants'
describe('DatePicker component', () => {
beforeEach(() => {
jest.clearAllMocks()
})
const testProps = {
id: 'birthdate',
name: 'birthdate',
}
it('renders witout errors', () => {
const { getByTestId } = render(<DatePicker {...testProps} />)
expect(getByTestId('date-picker')).toBeInTheDocument()
})
it('renders a hidden "internal" input with the name prop', () => {
const { getByTestId } = render(<DatePicker {...testProps} />)
expect(getByTestId('date-picker-internal-input')).toBeInstanceOf(
HTMLInputElement
)
expect(getByTestId('date-picker-internal-input')).toHaveAttribute(
'type',
'text'
)
expect(getByTestId('date-picker-internal-input')).toHaveAttribute(
'aria-hidden',
'true'
)
expect(getByTestId('date-picker-internal-input')).toHaveAttribute(
'name',
testProps.name
)
})
it('renders a visible "external" input with the id prop', () => {
const { getByTestId } = render(<DatePicker {...testProps} />)
expect(getByTestId('date-picker-external-input')).toBeInstanceOf(
HTMLInputElement
)
expect(getByTestId('date-picker-external-input')).toHaveAttribute(
'type',
'text'
)
expect(getByTestId('date-picker-external-input')).toBeVisible()
expect(getByTestId('date-picker-external-input')).toHaveAttribute(
'id',
testProps.id
)
})
it('renders a toggle button', () => {
const { getByTestId } = render(<DatePicker {...testProps} />)
expect(getByTestId('date-picker-button')).toBeInstanceOf(HTMLButtonElement)
expect(getByTestId('date-picker-button')).toHaveAttribute(
'aria-label',
'Toggle calendar'
)
})
it('renders a hidden calendar dialog element', () => {
const { getByTestId } = render(<DatePicker {...testProps} />)
expect(getByTestId('date-picker-calendar')).toBeInstanceOf(HTMLDivElement)
expect(getByTestId('date-picker-calendar')).toHaveAttribute(
'role',
'dialog'
)
expect(getByTestId('date-picker-calendar')).not.toBeVisible()
})
it('renders a screen reader status element', () => {
const { getByTestId } = render(<DatePicker {...testProps} />)
expect(getByTestId('date-picker-status')).toBeInstanceOf(HTMLDivElement)
expect(getByTestId('date-picker-status')).toHaveAttribute('role', 'status')
expect(getByTestId('date-picker-status')).toHaveTextContent('')
})
// https://github.com/uswds/uswds/blob/develop/spec/unit/date-picker/date-picker.spec.js#L933
it('prevents default action if keyup doesnโt originate within the calendar', () => {
const { getByTestId } = render(
<DatePicker {...testProps} defaultValue="2021-01-20" />
)
const calendarEl = getByTestId('date-picker-calendar')
userEvent.click(getByTestId('date-picker-button'))
expect(calendarEl).toBeVisible()
const keyUpEvent = createEvent.keyUp(calendarEl, {
key: 'Enter',
bubbles: true,
keyCode: 13,
})
const preventDefaultSpy = jest.spyOn(keyUpEvent, 'preventDefault')
fireEvent(calendarEl, keyUpEvent)
expect(preventDefaultSpy).toHaveBeenCalled()
})
describe('toggling the calendar', () => {
it('the calendar is hidden on mount', () => {
const { getByTestId } = render(<DatePicker {...testProps} />)
expect(getByTestId('date-picker-calendar')).not.toBeVisible()
expect(getByTestId('date-picker')).not.toHaveClass(
'usa-date-picker--active'
)
})
it('shows the calendar when the toggle button is clicked and focuses on the selected date', async () => {
const { getByTestId, getByText } = render(
<DatePicker {...testProps} defaultValue="2021-01-20" />
)
userEvent.click(getByTestId('date-picker-button'))
expect(getByTestId('date-picker-calendar')).toBeVisible()
expect(getByTestId('date-picker')).toHaveClass('usa-date-picker--active')
expect(getByText('20')).toHaveClass(
'usa-date-picker__calendar__date--selected'
)
await waitFor(() => {
expect(getByText('20')).toHaveFocus()
})
})
it('hides the calendar when the escape key is pressed', () => {
const { getByTestId } = render(<DatePicker {...testProps} />)
userEvent.click(getByTestId('date-picker-button'))
expect(getByTestId('date-picker-calendar')).toBeVisible()
expect(getByTestId('date-picker')).toHaveClass('usa-date-picker--active')
fireEvent.keyDown(getByTestId('date-picker'), { key: 'Escape' })
expect(getByTestId('date-picker-calendar')).not.toBeVisible()
expect(getByTestId('date-picker')).not.toHaveClass(
'usa-date-picker--active'
)
// TODO
// This broke but only seems to be in JSDom (works as expected in Chrome)
// expect(getByTestId('date-picker-external-input')).toHaveFocus()
})
it('hides the calendar when the toggle button is clicked a second time', () => {
const { getByTestId } = render(<DatePicker {...testProps} />)
userEvent.click(getByTestId('date-picker-button'))
expect(getByTestId('date-picker-calendar')).toBeVisible()
expect(getByTestId('date-picker')).toHaveClass('usa-date-picker--active')
userEvent.click(getByTestId('date-picker-button'))
expect(getByTestId('date-picker-calendar')).not.toBeVisible()
expect(getByTestId('date-picker')).not.toHaveClass(
'usa-date-picker--active'
)
expect(getByTestId('date-picker-status')).toHaveTextContent('')
})
it('focus defaults to today if there is no value', async () => {
const todayDate = today()
const todayLabel = `${todayDate.getDate()} ${
MONTH_LABELS[todayDate.getMonth()]
} ${todayDate.getFullYear()} ${DAY_OF_WEEK_LABELS[todayDate.getDay()]}`
const { getByTestId, getByLabelText } = render(
<DatePicker {...testProps} />
)
userEvent.click(getByTestId('date-picker-button'))
await waitFor(() => {
expect(getByLabelText(todayLabel)).toHaveFocus()
})
})
it('adds Selected date to the status text if the selected date and the focused date are the same', async () => {
const { getByTestId, getByText } = render(
<DatePicker {...testProps} defaultValue="2021-01-20" />
)
userEvent.click(getByTestId('date-picker-button'))
expect(getByTestId('date-picker-calendar')).toBeVisible()
expect(getByTestId('date-picker')).toHaveClass('usa-date-picker--active')
await waitFor(() => {
expect(getByText('20')).toHaveFocus()
})
expect(getByTestId('date-picker-status')).toHaveTextContent(
'Selected date'
)
})
it('coerces the display date to a valid value', async () => {
const { getByTestId, getByLabelText } = render(
<DatePicker
{...testProps}
defaultValue="2021-01-06"
minDate="2021-01-10"
maxDate="2021-01-20"
/>
)
userEvent.click(getByTestId('date-picker-button'))
expect(getByLabelText('6 January 2021 Wednesday')).not.toHaveFocus()
await waitFor(() => {
expect(getByLabelText('10 January 2021 Sunday')).toHaveFocus()
})
})
it('hides the calendar if focus moves to another element', () => {
const mockOnBlur = jest.fn()
const { getByTestId } = render(
<>
<DatePicker {...testProps} onBlur={mockOnBlur} />
<input type="text" data-testid="test-external-element" />
</>
)
userEvent.click(getByTestId('date-picker-button'))
expect(getByTestId('date-picker-calendar')).toBeVisible()
getByTestId('test-external-element').focus()
expect(getByTestId('date-picker-calendar')).not.toBeVisible()
expect(mockOnBlur).toHaveBeenCalled()
})
})
describe('status text', () => {
it('shows instructions in the status text when the calendar is opened', () => {
const { getByTestId } = render(
<DatePicker {...testProps} defaultValue="2021-01-20" />
)
userEvent.click(getByTestId('date-picker-button'))
expect(getByTestId('date-picker-calendar')).toBeVisible()
expect(getByTestId('date-picker')).toHaveClass('usa-date-picker--active')
expect(getByTestId('date-picker-status')).toHaveTextContent(
'You can navigate by day using left and right arrows'
)
expect(getByTestId('date-picker-status')).toHaveTextContent(
'Weeks by using up and down arrows'
)
expect(getByTestId('date-picker-status')).toHaveTextContent(
'Months by using page up and page down keys'
)
expect(getByTestId('date-picker-status')).toHaveTextContent(
'Years by using shift plus page up and shift plus page down'
)
expect(getByTestId('date-picker-status')).toHaveTextContent(
'Home and end keys navigate to the beginning and end of a week'
)
})
it('removes instructions from the status text when the calendar is already open and the displayed date changes', async () => {
const { getByTestId, getByLabelText } = render(
<DatePicker {...testProps} defaultValue="2021-01-20" />
)
userEvent.click(getByTestId('date-picker-button'))
expect(getByTestId('date-picker-calendar')).toBeVisible()
expect(getByTestId('date-picker')).toHaveClass('usa-date-picker--active')
expect(getByTestId('date-picker-status')).not.toHaveTextContent(
'January 2021'
)
expect(getByTestId('date-picker-status')).toHaveTextContent(
'You can navigate by day using left and right arrows'
)
expect(getByTestId('date-picker-status')).toHaveTextContent(
'Weeks by using up and down arrows'
)
expect(getByTestId('date-picker-status')).toHaveTextContent(
'Months by using page up and page down keys'
)
expect(getByTestId('date-picker-status')).toHaveTextContent(
'Years by using shift plus page up and shift plus page down'
)
expect(getByTestId('date-picker-status')).toHaveTextContent(
'Home and end keys navigate to the beginning and end of a week'
)
await waitFor(() => {
expect(getByLabelText(/^20 January 2021/)).toHaveFocus()
})
fireEvent.mouseMove(getByLabelText(/^13 January 2021/))
expect(getByLabelText(/^13 January 2021/)).toHaveFocus()
expect(getByTestId('date-picker-status')).toHaveTextContent(
'January 2021'
)
expect(getByTestId('date-picker-status')).not.toHaveTextContent(
'You can navigate by day using left and right arrows'
)
expect(getByTestId('date-picker-status')).not.toHaveTextContent(
'Weeks by using up and down arrows'
)
expect(getByTestId('date-picker-status')).not.toHaveTextContent(
'Months by using page up and page down keys'
)
expect(getByTestId('date-picker-status')).not.toHaveTextContent(
'Years by using shift plus page up and shift plus page down'
)
expect(getByTestId('date-picker-status')).not.toHaveTextContent(
'Home and end keys navigate to the beginning and end of a week'
)
})
it('does not add Selected date to the status text if the selected date and the focused date are not the same', async () => {
const { getByTestId, getByLabelText } = render(
<DatePicker {...testProps} defaultValue="2021-01-20" />
)
userEvent.click(getByTestId('date-picker-button'))
expect(getByTestId('date-picker-calendar')).toBeVisible()
expect(getByTestId('date-picker')).toHaveClass('usa-date-picker--active')
await waitFor(() => {
expect(getByLabelText(/^20 January 2021/)).toHaveFocus()
})
expect(getByTestId('date-picker-status')).toHaveTextContent(
'Selected date'
)
fireEvent.mouseMove(getByLabelText(/^13 January 2021/))
expect(getByLabelText(/^13 January 2021/)).toHaveFocus()
expect(getByTestId('date-picker-status')).not.toHaveTextContent(
'Selected date'
)
fireEvent.mouseMove(getByLabelText(/^20 January 2021/))
expect(getByLabelText(/^20 January 2021/)).toHaveFocus()
expect(getByTestId('date-picker-status')).toHaveTextContent(
'Selected date'
)
})
})
describe('with the required prop', () => {
it('the external input is required, and the internal input is not required', () => {
const { getByTestId } = render(<DatePicker {...testProps} required />)
expect(getByTestId('date-picker-external-input')).toBeRequired()
expect(getByTestId('date-picker-internal-input')).not.toBeRequired()
})
})
describe('with the disabled prop', () => {
it('the toggle button and external inputs are disabled, and the internal input is not disabled', () => {
const { getByTestId } = render(<DatePicker {...testProps} disabled />)
expect(getByTestId('date-picker-button')).toBeDisabled()
expect(getByTestId('date-picker-external-input')).toBeDisabled()
expect(getByTestId('date-picker-internal-input')).not.toBeDisabled()
})
it('does not show the calendar when the toggle button is clicked', () => {
const { getByTestId } = render(<DatePicker {...testProps} disabled />)
userEvent.click(getByTestId('date-picker-button'))
expect(getByTestId('date-picker-calendar')).not.toBeVisible()
expect(getByTestId('date-picker')).not.toHaveClass(
'usa-date-picker--active'
)
})
})
describe('with a default value prop', () => {
it('the internal input value is the date string, and the external input value is the formatted date', () => {
const { getByTestId } = render(
<DatePicker {...testProps} defaultValue="1988-05-16" />
)
expect(getByTestId('date-picker-external-input')).toHaveValue(
'05/16/1988'
)
expect(getByTestId('date-picker-internal-input')).toHaveValue(
'1988-05-16'
)
})
it('validates a valid default value', () => {
const { getByTestId } = render(
<DatePicker {...testProps} defaultValue="1988-05-16" />
)
expect(getByTestId('date-picker-external-input')).toBeValid()
})
it('validates an invalid default value', () => {
const { getByTestId } = render(
<DatePicker
{...testProps}
defaultValue="1990-01-01"
minDate="2020-01-01"
/>
)
expect(getByTestId('date-picker-external-input')).toBeInvalid()
})
})
describe('with localization props', () => {
it('displays abbreviated translations for days of the week', () => {
const { getByText, getByTestId } = render(
<DatePicker {...testProps} i18n={sampleLocalization} />
)
userEvent.click(getByTestId('date-picker-button'))
sampleLocalization.daysOfWeekShort.forEach((translation) => {
expect(getByText(translation)).toBeInTheDocument()
})
})
it('displays translation for month', () => {
const { getByText, getByTestId } = render(
<DatePicker
{...testProps}
i18n={sampleLocalization}
defaultValue="2020-02-01"
/>
)
userEvent.click(getByTestId('date-picker-button'))
expect(getByText('febrero')).toBeInTheDocument()
})
})
describe('selecting a date', () => {
it('clicking a date button selects that date and closes the calendar and focuses the external input', () => {
const mockOnChange = jest.fn()
const { getByTestId, getByText } = render(
<DatePicker
{...testProps}
defaultValue="2021-01-20"
onChange={mockOnChange}
/>
)
userEvent.click(getByTestId('date-picker-button'))
const dateButton = getByText('15')
expect(dateButton).toHaveClass('usa-date-picker__calendar__date')
userEvent.click(dateButton)
expect(getByTestId('date-picker-external-input')).toHaveValue(
'01/15/2021'
)
expect(getByTestId('date-picker-internal-input')).toHaveValue(
'2021-01-15'
)
expect(getByTestId('date-picker-calendar')).not.toBeVisible()
expect(getByTestId('date-picker-external-input')).toHaveFocus()
expect(mockOnChange).toHaveBeenCalledWith('01/15/2021')
})
it('selecting a date and opening the calendar focuses on the selected date', async () => {
const { getByTestId, getByText } = render(<DatePicker {...testProps} />)
// open calendar
userEvent.click(getByTestId('date-picker-button'))
// select date
const dateButton = getByText('12')
userEvent.click(dateButton)
// open calendar again
userEvent.click(getByTestId('date-picker-button'))
await waitFor(() => {
expect(getByText('12')).toHaveFocus()
})
expect(getByText('12')).toHaveClass(
'usa-date-picker__calendar__date--selected'
)
})
})
describe('typing in a date', () => {
it('typing a date in the external input updates the selected date', async () => {
const mockOnChange = jest.fn()
const { getByTestId, getByText } = render(
<DatePicker {...testProps} onChange={mockOnChange} />
)
userEvent.type(getByTestId('date-picker-external-input'), '05/16/1988')
userEvent.click(getByTestId('date-picker-button'))
expect(getByTestId('select-month')).toHaveTextContent('May')
expect(getByTestId('select-year')).toHaveTextContent('1988')
await waitFor(() => {
expect(getByText('16')).toHaveFocus()
})
expect(getByText('16')).toHaveClass(
'usa-date-picker__calendar__date--selected'
)
expect(mockOnChange).toHaveBeenCalledWith('05/16/1988')
})
it('typing a date with a 2-digit year in the external input focuses that year in the current century', async () => {
const { getByTestId, getByLabelText } = render(
<DatePicker {...testProps} />
)
userEvent.type(getByTestId('date-picker-external-input'), '2/29/20')
userEvent.click(getByTestId('date-picker-button'))
expect(getByTestId('select-month')).toHaveTextContent('February')
expect(getByTestId('select-year')).toHaveTextContent('2020')
await waitFor(() => {
expect(getByLabelText(/^29 February 2020/)).toHaveFocus()
})
})
it('typing a date with the calendar open updates the calendar to the entered date', () => {
const { getByTestId, getByText } = render(
<DatePicker {...testProps} defaultValue="2021-01-20" />
)
userEvent.click(getByTestId('date-picker-button'))
expect(getByTestId('select-month')).toHaveTextContent('January')
expect(getByTestId('select-year')).toHaveTextContent('2021')
userEvent.clear(getByTestId('date-picker-external-input'))
userEvent.type(getByTestId('date-picker-external-input'), '05/16/1988')
expect(getByTestId('select-month')).toHaveTextContent('May')
expect(getByTestId('select-year')).toHaveTextContent('1988')
expect(getByText('16')).toHaveClass(
'usa-date-picker__calendar__date--selected'
)
})
it('implements a custom onBlur handler', () => {
const mockOnBlur = jest.fn()
const { getByTestId } = render(
<DatePicker {...testProps} onBlur={mockOnBlur} />
)
userEvent.type(getByTestId('date-picker-external-input'), '05/16/1988')
getByTestId('date-picker-external-input').blur()
expect(mockOnBlur).toHaveBeenCalled()
})
// TODO - this is an outstanding difference in behavior from USWDS. Fails because validation happens onChange.
it.skip('typing in the external input does not validate until blurring', () => {
const { getByTestId } = render(
<DatePicker {...testProps} minDate="2021-01-20" maxDate="2021-02-14" />
)
const externalInput = getByTestId('date-picker-external-input')
expect(externalInput).toBeValid()
userEvent.type(externalInput, '05/16/1988')
expect(externalInput).toBeValid()
externalInput.blur()
expect(externalInput).toBeInvalid()
})
// TODO - this can be implemented if the above test case is implemented
it.skip('pressing the Enter key in the external input validates the date', () => {
const { getByTestId } = render(
<DatePicker {...testProps} minDate="2021-01-20" maxDate="2021-02-14" />
)
const externalInput = getByTestId('date-picker-external-input')
expect(externalInput).toBeValid()
userEvent.type(externalInput, '05/16/1988')
expect(externalInput).toBeValid()
userEvent.type(externalInput, specialChars.enter)
expect(externalInput).toBeInvalid()
})
})
describe('validation', () => {
it('entering an empty value is valid', () => {
const { getByTestId } = render(<DatePicker {...testProps} />)
const externalInput = getByTestId(
'date-picker-external-input'
) as HTMLInputElement
userEvent.type(externalInput, '{space}{backspace}')
externalInput.blur()
expect(externalInput).toHaveTextContent('')
expect(externalInput).toBeValid()
expect(externalInput.validationMessage).toEqual('')
})
it('entering a non-date value sets a validation message', () => {
const mockOnChange = jest.fn()
const { getByTestId } = render(
<DatePicker {...testProps} onChange={mockOnChange} />
)
const externalInput = getByTestId(
'date-picker-external-input'
) as HTMLInputElement
userEvent.type(externalInput, 'abcdefg... That means the convo is done')
expect(mockOnChange).toHaveBeenCalledWith(
'abcdefg... That means the convo is done'
)
expect(externalInput).toBeInvalid()
expect(externalInput.validationMessage).toEqual(VALIDATION_MESSAGE)
})
it('entering a non-date value sets a validation message', () => {
const mockOnChange = jest.fn()
const { getByTestId } = render(
<DatePicker {...testProps} onChange={mockOnChange} />
)
const externalInput = getByTestId(
'date-picker-external-input'
) as HTMLInputElement
userEvent.type(externalInput, 'ab/cd/efg')
expect(mockOnChange).toHaveBeenCalledWith('ab/cd/efg')
expect(externalInput).toBeInvalid()
expect(externalInput.validationMessage).toEqual(VALIDATION_MESSAGE)
})
it('entering an invalid date sets a validation message and becomes valid when selecting a date in the calendar', async () => {
const mockOnChange = jest.fn()
const { getByTestId, getByLabelText } = render(
<DatePicker {...testProps} onChange={mockOnChange} />
)
const externalInput = getByTestId(
'date-picker-external-input'
) as HTMLInputElement
userEvent.type(externalInput, '2/31/2019')
expect(mockOnChange).toHaveBeenCalledWith('2/31/2019')
expect(externalInput).toBeInvalid()
expect(externalInput.validationMessage).toEqual(VALIDATION_MESSAGE)
userEvent.click(getByTestId('date-picker-button'))
expect(getByTestId('date-picker-calendar')).toBeVisible()
userEvent.click(getByLabelText(/^10 February 2019/))
expect(mockOnChange).toHaveBeenCalledWith('02/10/2019')
await waitFor(() => {
expect(externalInput).toBeValid()
})
expect(externalInput.validationMessage).toEqual('')
})
it('entering a valid date outside of the min/max date sets a validation message', () => {
const mockOnChange = jest.fn()
const { getByTestId } = render(
<DatePicker
{...testProps}
minDate="2021-01-20"
maxDate="2021-02-14"
onChange={mockOnChange}
/>
)
const externalInput = getByTestId(
'date-picker-external-input'
) as HTMLInputElement
userEvent.type(externalInput, '05/16/1988')
expect(mockOnChange).toHaveBeenCalledWith('05/16/1988')
expect(externalInput).toBeInvalid()
expect(externalInput.validationMessage).toEqual(VALIDATION_MESSAGE)
})
})
describe('month selection', () => {
it('clicking the selected month updates the status text', () => {
const { getByTestId } = render(<DatePicker {...testProps} />)
userEvent.click(getByTestId('date-picker-button'))
userEvent.click(getByTestId('select-month'))
expect(getByTestId('date-picker-status')).toHaveTextContent(
'Select a month'
)
})
})
describe('year selection', () => {
it('clicking the selected year updates the status text', async () => {
const { getByTestId } = render(
<DatePicker {...testProps} defaultValue="2021-01-20" />
)
userEvent.click(getByTestId('date-picker-button'))
userEvent.click(getByTestId('select-year'))
await waitFor(() => {
expect(getByTestId('date-picker-status')).toHaveTextContent(
'Showing years 2016 to 2027. Select a year.'
)
})
})
it('clicking previous year chunk updates the status text', async () => {
const { getByTestId } = render(
<DatePicker {...testProps} defaultValue="2021-01-20" />
)
userEvent.click(getByTestId('date-picker-button'))
userEvent.click(getByTestId('select-year'))
userEvent.click(getByTestId('previous-year-chunk'))
await waitFor(() => {
expect(getByTestId('date-picker-status')).toHaveTextContent(
'Showing years 2004 to 2015. Select a year.'
)
})
})
it('clicking next year chunk navigates the year picker forward one chunk', async () => {
const { getByTestId } = render(
<DatePicker {...testProps} defaultValue="2021-01-20" />
)
userEvent.click(getByTestId('date-picker-button'))
userEvent.click(getByTestId('select-year'))
userEvent.click(getByTestId('next-year-chunk'))
await waitFor(() => {
expect(getByTestId('date-picker-status')).toHaveTextContent(
'Showing years 2028 to 2039. Select a year.'
)
})
})
})
}) | the_stack |
import { DiagnosticEntry, DiagnosticType } from "../backend/facade";
import { SourceContext } from "./SourceContext";
/**
* ANTLR uses ST templates for generating messages. We use the "antlr" message format which is generated from
* the following template rules:
* location(file, line, column) ::= "<file>:<line>:<column>:"
* message(id, text) ::= "(<id>) <text>"
* report(location, message, type) ::= "<type>(<message.id>): <location> <message.text>"
* wantsSingleLineMessage() ::= "false"
*/
export class ErrorParser {
private static errorPattern = /(\w+)\s*\((\d+)\):\s*([^:]*):(\d*):(\d*):\s*(.+)/;
private static errorCodeToPattern: Map<number, RegExp> = new Map([
[8, /grammar name (\w+)/],
[56, /:\s+(\w+)/],
[57, /rule (\w+) in non-local ref (\w+)/],
[63, /reference (\w+) in (\w+)/],
[64, /parameter (\w+) of rule (\w+) is not accessible in this scope: (\w+)/],
[65, /attribute (\w+) for rule (\w+) in (\w+)/],
[66, /attribute (\w+) isn't a valid property in (\w+)/],
[67, /reference (\w+) in (\w+)/],
[69, /label (\w+)/],
[70, /label (\w+)/],
[72, /label (\w+)/],
[73, /label (\w+)/],
[74, /label (\w+)/],
[75, /label (\w+)[^:]+: (\w+)/],
[76, /value (\w+)/],
[79, /reference: (\w+)/],
[80, /rule (\w+)/],
[84, /value (\w+)/],
[94, /of (\w+)/],
[106, /rule (\w+)/],
[108, /name (\w+)/],
[110, /grammar (\w+)/],
[111, /import \w+ grammar (\w+)/],
[113, /import \w+ grammar (\w+)/],
[160, /file (\w+)/],
[118, /alt (\w+)/],
[122, /rule (\w+)/],
[123, /alt label (\w+) redefined in rule (\w+), originally in rule (\w+)/],
[124, /label (\w+) conflicts with rule (\w+)/],
[125, /of token (\w+)/],
[126, /grammar: (\w+)/],
[128, /actions: (\$\w+)/],
[130, /label (\w+)/],
[131, /block \(\)(\w+)/],
[132, /rule (\w+)/],
[133, /rule (\w+)/],
[134, /symbol (\w+)/],
//[134, /rule reference (\w+)/], Duplicate error code.
[135, /label (\w+)/],
[136, /value (\w+)/],
[137, /value (\w+)/],
[138, /parameter (\w+)/],
[139, /parameter (\w+)/],
[140, /local (\w+)/],
[141, /local (\w+)/],
[142, /local (\w+)/],
[143, /local (\w+)/],
[144, /sets: (\w+)/],
[145, /mode (\w+)/],
[146, /rule (\w+)/],
[147, /rule (\w+)/],
[148, /rule (\w+)/],
[149, /command (\w+)/],
[150, /command (\w+)/],
[151, /command (\w+)/],
[153, /rule (\w+)/],
[154, /rule (\w+)/],
[155, /rule (\w+)/],
[156, /sequence (\w+)/],
[158, /rule (\w+)/],
[159, /name (\w+)/],
[161, /channel (\w+)/],
[162, /channel (\w+)/],
[169, /rule (\w+)/],
[170, /mode (\w+)/],
[171, /name (\w+)/],
[172, /name (\w+)/],
[173, /name (\w+)/],
[174, /empty: (\w+)/],
[175, /(\w+) is not/],
[176, /(\w+) is not/],
[177, /(\w+) is not/],
[178, /command (\w+)/],
[179, /commands (\w+)/],
[180, /used multiple times in set (.+)/],
[181, /parser: ('[^']+'\.\.'[^']+')/],
[182, /range: (\w+)/],
]);
public constructor(private contexts: Set<SourceContext>) {
contexts.forEach((context) => {
context.diagnostics.length = 0; // Remove all own diagnostics. We use ANTLR generated ones now.
});
}
/**
* Converts errors generated by the ANTLR tool into our diagnostics structure for reporting.
*
* @param text The error text.
*
* @returns True if the conversion was successful, false otherwise.
*/
public convertErrorsToDiagnostics(text: string): boolean {
const lines = text.split("\n");
for (const line of lines) {
if (line.length > 0) {
const firstLevelMatches = ErrorParser.errorPattern.exec(line);
if (!firstLevelMatches) {
// If we find something that doesn't conform to an ANTLR error we got probably
// another unexpected error (crash in ANTLR, execution problem etc.).
// Return a flag to indicate that.
return false;
} else {
const fileName = firstLevelMatches[3];
// Find the context this error belongs to.
let context: SourceContext | undefined;
for (const candidate of this.contexts) {
// Usually error messages come with the full path, but in case of grammar <-> filename conflicts
// we only get the base name.
if (candidate.fileName === fileName || candidate.fileName.endsWith(fileName)) {
context = candidate;
break;
}
}
if (!context) {
continue;
}
const errorCode = Number(firstLevelMatches[2]);
const errorText = firstLevelMatches[6];
// The error message contains positioning information if only a single symbol is causing
// the problem. For many error messages, however, there are multiple symbols involved
// (e.g. indirect left recursion) or non-symbol related problems occurred (e.g. grammar name
// doesn't match file name).
// For all these cases we need to scan the error message for details.
if (firstLevelMatches[4].length > 0) {
let range = {
start: { row: Number(firstLevelMatches[4]), column: Number(firstLevelMatches[5]) },
end: { row: Number(firstLevelMatches[4]), column: Number(firstLevelMatches[5]) + 1 },
};
switch (errorCode) {
case 8: // "grammar name <arg> and file name <arg2> differ", ErrorSeverity.ERROR
case 56: // "reference to undefined rule: <arg>", ErrorSeverity.ERROR
case 57: // "reference to undefined rule <arg> in non-local ref <arg3>", ErrorSeverity.ERROR
case 63: // "unknown attribute reference <arg> in <arg2>", ErrorSeverity.ERROR
case 64: // "parameter <arg> of rule <arg2> is not accessible in this scope: <arg3>", ErrorSeverity.ERROR
case 65: // "unknown attribute <arg> for rule <arg2> in <arg3>", ErrorSeverity.ERROR
case 66: // "attribute <arg> isn't a valid property in <arg2>", ErrorSeverity.ERROR
case 67: // "missing attribute access on rule reference <arg> in <arg2>", ErrorSeverity.ERROR
case 75: // "label <arg> type mismatch with previous definition: <arg2>", ErrorSeverity.ERROR
case 79: // "missing argument(s) on rule reference: <arg>", ErrorSeverity.ERROR
case 84: // "unsupported option value <arg>=<arg2>", ErrorSeverity.WARNING
case 94: // "redefinition of <arg> action", ErrorSeverity.ERROR
case 106: // "rule <arg2> is not defined in grammar <arg>", ErrorSeverity.ERROR
case 108: // "token name <arg> is already defined", ErrorSeverity.WARNING
case 110: // "can't find or load grammar <arg>", ErrorSeverity.ERROR
case 111: // "<arg.typeString> grammar <arg.name> cannot import <arg2.typeString> grammar <arg2.name>", ErrorSeverity.ERROR
case 113: // "<arg.typeString> grammar <arg.name> and imported <arg2.typeString> grammar <arg2.name> both generate <arg2.recognizerName>", ErrorSeverity.ERROR
case 118: // deprecated, "all operators of alt <arg> of left-recursive rule must have same associativity", ErrorSeverity.WARNING
case 122: // "rule <arg>: must label all alternatives or none", ErrorSeverity.ERROR
case 123: // "rule alt label <arg> redefined in rule <arg2>, originally in rule <arg3>", ErrorSeverity.ERROR
case 125: // "implicit definition of token <arg> in parser", ErrorSeverity.WARNING
case 126: // "cannot create implicit token for string literal in non-combined grammar: <arg>", ErrorSeverity.ERROR
case 128: // "attribute references not allowed in lexer actions: $<arg>", ErrorSeverity.ERROR
case 130: // "label <arg> assigned to a block which is not a set", ErrorSeverity.ERROR
case 131: // "greedy block ()<arg> contains wildcard; the non-greedy syntax ()<arg>? may be preferred", ErrorSeverity.WARNING
case 132: // "action in lexer rule <arg> must be last element of single outermost alt", ErrorSeverity.ERROR
case 133: // "->command in lexer rule <arg> must be last element of single outermost alt", ErrorSeverity.ERROR
case 134: // "symbol <arg> conflicts with generated code in target language or runtime", ErrorSeverity.ERROR
case 135: // "cannot assign a value to list label <arg>", ErrorSeverity.ERROR
case 136: // "return value <arg> conflicts with rule with same name", ErrorSeverity.ERROR
case 137: // "return value <arg> conflicts with token with same name", ErrorSeverity.ERROR
case 138: // "parameter <arg> conflicts with rule with same name", ErrorSeverity.ERROR
case 139: // "parameter <arg> conflicts with token with same name", ErrorSeverity.ERROR
case 140: // "local <arg> conflicts with rule with same name", ErrorSeverity.ERROR
case 141: // "local <arg> conflicts with rule token same name", ErrorSeverity.ERROR
case 142: // "local <arg> conflicts with parameter with same name", ErrorSeverity.ERROR
case 143: // "local <arg> conflicts with return value with same name", ErrorSeverity.ERROR
case 144: // "multi-character literals are not allowed in lexer sets: <arg>", ErrorSeverity.ERROR
case 145: // "lexer mode <arg> must contain at least one non-fragment rule", ErrorSeverity.ERROR
case 146: // "non-fragment lexer rule <arg> can match the empty string", ErrorSeverity.WARNING
case 147: // "left recursive rule <arg> must contain an alternative which is not left recursive", ErrorSeverity.ERROR
case 148: // "left recursive rule <arg> contains a left recursive alternative which can be followed by the empty string", ErrorSeverity.ERROR
case 149: // "lexer command <arg> does not exist or is not supported by the current target", ErrorSeverity.ERROR
case 150: // "missing argument for lexer command <arg>", ErrorSeverity.ERROR
case 151: // "lexer command <arg> does not take any arguments", ErrorSeverity.ERROR
case 153: // "rule <arg> contains a closure with at least one alternative that can match an empty string", ErrorSeverity.ERROR
case 154: // "rule <arg> contains an optional block with at least one alternative that can match an empty string", ErrorSeverity.WARNING
case 155: // "rule <arg> contains a lexer command with an unrecognized constant value; lexer interpreters may produce incorrect output", ErrorSeverity.WARNING
case 156: // "invalid escape sequence <arg>", ErrorSeverity.WARNING
case 158: // "fragment rule <arg> contains an action or command which can never be executed", ErrorSeverity.WARNING
case 159: // "cannot declare a rule with reserved name <arg>", ErrorSeverity.ERROR
case 160: // "cannot find tokens file <arg>", ErrorSeverity.ERROR
case 161: // "channel <arg> conflicts with token with same name", ErrorSeverity.ERROR
case 162: // "channel <arg> conflicts with mode with same name", ErrorSeverity.ERROR
case 169: // "rule <arg> is left recursive but doesn't conform to a errorPattern ANTLR can handle", ErrorSeverity.ERROR
case 170: // "mode <arg> conflicts with token with same name", ErrorSeverity.ERROR
case 171: // "cannot use or declare token with reserved name <arg>", ErrorSeverity.ERROR
case 172: // "cannot use or declare channel with reserved name <arg>", ErrorSeverity.ERROR
case 173: // "cannot use or declare mode with reserved name <arg>", ErrorSeverity.ERROR
case 174: // "string literals and sets cannot be empty: <arg>", ErrorSeverity.ERROR
case 175: // "<arg> is not a recognized token name", ErrorSeverity.ERROR
case 176: // "<arg> is not a recognized mode name", ErrorSeverity.ERROR
case 177: // "<arg> is not a recognized channel name", ErrorSeverity.ERROR
case 178: // "duplicated command <arg>", ErrorSeverity.WARNING
case 179: // "incompatible commands <arg> and <arg2>", ErrorSeverity.WARNING
case 180: // "chars <arg> used multiple times in set <arg2>", ErrorSeverity.WARNING
case 181: // "token ranges not allowed in parser: <arg>..<arg2>", ErrorSeverity.ERROR
case 182: { // "unicode property escapes not allowed in lexer charset range: <arg>", ErrorSeverity.ERROR
const matches = ErrorParser.errorCodeToPattern.get(errorCode)!.exec(errorText);
if (matches) {
if (matches.length > 2) {
// Multiple symbols in the message.
const symbols: string[] = [];
for (let i = 1; i < symbols.length; ++i) { // Not the first entry
symbols.push(matches[i]);
}
this.addDiagnosticsForSymbols(symbols, errorText, DiagnosticType.Error,
context);
continue;
}
range.end.column += matches[1].length - 1; // -1 for the +1 we use as default.
}
break;
}
case 50: { // "syntax error: <arg>", ErrorSeverity.ERROR
// All kinds of syntax errors. No need to create dozens of error patterns,
// but instead look for a quoted string which usually denotes the input char(s) that
// caused the trouble.
const matches = /\(missing '[^']+'\)?[^']+'([^']+)'/.exec(errorText);
if (matches) {
range.end.column += matches[1].length - 1; // -1 for the +1 we use as default.
}
break;
}
case 69: // "label <arg> conflicts with rule with same name", ErrorSeverity.ERROR
case 70: // "label <arg> conflicts with token with same name", ErrorSeverity.ERROR
case 72: // "label <arg> conflicts with parameter with same name", ErrorSeverity.ERROR
case 73: // "label <arg> conflicts with return value with same name", ErrorSeverity.ERROR
case 74: // "label <arg> conflicts with local with same name", ErrorSeverity.ERROR
case 76: // "return value <arg> conflicts with parameter with same name", ErrorSeverity.ERROR
case 80: // "rule <arg> has no defined parameters", ErrorSeverity.ERROR
case 124: { // "rule alt label <arg> conflicts with rule <arg2>", ErrorSeverity.ERROR
const matches = ErrorParser.errorCodeToPattern.get(errorCode)!.exec(errorText);
if (matches) {
// We're adding two entries here: one for each symbol.
this.addDiagnosticsForSymbols([matches[1]], errorText, DiagnosticType.Warning,
context);
range.end.column += matches[1].length - 1;
}
break;
}
case 83: { // "unsupported option <arg>", ErrorSeverity.WARNING
const matches = /unsupported option (\w+)/.exec(errorText);
if (matches) {
range.end.column += matches[1].length - 1;
}
break;
}
case 105: { // "reference to undefined grammar in rule reference: <arg>.<arg2>", ErrorSeverity.ERROR
const matches = /reference: (\w+).(\w+)/.exec(errorText);
if (matches) {
range.end.column += matches[1].length + matches[2].length;
}
break;
}
case 109: // "options ignored in imported grammar <arg>", ErrorSeverity.WARNING
range.end.column += "options".length - 1;
break;
case 202: { // "tokens {A; B;} syntax is now tokens {A, B} in ANTLR 4", ErrorSeverity.WARNING
const enclosingRange = context.enclosingSymbolAtPosition(range.start.column,
range.start.row, true);
if (enclosingRange && enclosingRange.definition) {
range = enclosingRange.definition.range;
}
break;
}
case 157: // "rule <arg> contains an assoc terminal option in an unrecognized location", ErrorSeverity.WARNING
range.end.column += "assoc".length - 1;
break;
case 204: // "{...}?=> explicitly gated semantic predicates are deprecated in ANTLR 4; use {...}? instead", ErrorSeverity.WARNING
range.end.column += 7; // Arbitrary length, we have no info how long the predicate is.
break;
case 205: // "(...)=> syntactic predicates are not supported in ANTLR 4", ErrorSeverity.ERROR
range.end.column += 1; // Just the arrow.
break;
default: {
const info = context.symbolAtPosition(range.start.column, range.start.row, false);
if (info) {
range.end.column += info.name.length - 1;
}
break;
}
}
const error: DiagnosticEntry = {
type: (firstLevelMatches[1] === "error") ? DiagnosticType.Error : DiagnosticType.Warning,
message: errorText,
range,
};
context.diagnostics.push(error);
} else {
switch (errorCode) {
case 1: // "cannot write file <arg>: <arg2>", ErrorSeverity.ERROR
case 2: // "unknown command-line option <arg>", ErrorSeverity.ERROR
case 4: // "error reading tokens file <arg>: <arg2>", ErrorSeverity.ERROR
case 5: // "directory not found: <arg>", ErrorSeverity.ERROR
case 6: // "output directory is a file: <arg>", ErrorSeverity.ERROR
case 7: // "cannot find or open file: <arg><if(exception&&verbose)>; reason: <exception><endif>", ErrorSeverity.ERROR
case 9: // "invalid -Dname=value syntax: <arg>", ErrorSeverity.ERROR
case 10: // "warning treated as error", ErrorSeverity.ERROR_ONE_OFF
case 11: // "error reading imported grammar <arg> referenced in <arg2>", ErrorSeverity.ERROR
case 20: // "internal error: <arg> <arg2><if(exception&&verbose)>: <exception><stackTrace; separator=\"\\n\"><endif>", ErrorSeverity.ERROR
case 21: // ".tokens file syntax error <arg>:<arg2>", ErrorSeverity.ERROR
case 22: // "template error: <arg> <arg2><if(exception&&verbose)>: <exception><stackTrace; separator=\"\\n\"><endif>", ErrorSeverity.WARNING
case 30: // "can't find code generation templates: <arg>", ErrorSeverity.ERROR
case 31: // "ANTLR cannot generate <arg> code as of version "+ Tool.VERSION, ErrorSeverity.ERROR_ONE_OFF
case 32: // "code generation template <arg> has missing, misnamed, or incomplete arg list; missing <arg2>", ErrorSeverity.ERROR
case 33: // "missing code generation template <arg>", ErrorSeverity.ERROR
case 34: // "no mapping to template name for output model class <arg>", ErrorSeverity.ERROR
case 35: // "<arg3> code generation target requires ANTLR <arg2>; it can't be loaded by the current ANTLR <arg>", ErrorSeverity.ERROR
case 54: // "repeated grammar prequel spec (options, tokens, or import); please merge", ErrorSeverity.ERROR
case 99: // "<if(arg2.implicitLexerOwner)>implicitly generated <endif>grammar <arg> has no rules", ErrorSeverity.ERROR
this.addGenericDiagnosis(errorText, DiagnosticType.Error, context);
break;
case 119: { // "The following sets of rules are mutually left-recursive <arg:{c| [<c:{r|<r.name>}; separator=\", \">]}; separator=\" and \">", ErrorSeverity.ERROR
const matches = /\[([^\]]+)]/.exec(errorText);
if (matches) {
const symbols = matches[1].split(",");
this.addDiagnosticsForSymbols(symbols, errorText, DiagnosticType.Error, context);
}
break;
}
case 180: {
// Charset collision testing is currently buggy. It reports each problem twice, once from the optimizer
// (w/o token position info, which is why we land here) and once with (handled above).
// We ignore the duplicate w/o code position.
break;
}
default:
this.addGenericDiagnosis(
`[Internal Error] Unhandled error message (code ${errorCode}, message: ` +
`${errorText}\nPlease file a bug report at ` +
"https://github.com/mike-lischke/vscode-antlr4/issues)",
DiagnosticType.Error, context);
break;
}
}
}
}
}
return true;
}
private addDiagnosticsForSymbols(symbols: string[], text: string, type: DiagnosticType, context: SourceContext) {
for (const symbol of symbols) {
const info = context.getSymbolInfo(symbol.trim());
if (info) {
const error: DiagnosticEntry = {
type,
message: text,
range: info.definition!.range,
};
context.diagnostics.push(error);
}
}
}
private addGenericDiagnosis(text: string, type: DiagnosticType, context: SourceContext) {
const error: DiagnosticEntry = {
type,
message: text,
range: { start: { column: 0, row: 1 }, end: { column: 0, row: 1 } },
};
context.diagnostics.push(error);
}
} | the_stack |
import { dirname, sep } from '@stoplight/path';
import { NodeType } from '@stoplight/types';
import { escapeRegExp, flow, partial, sortBy } from 'lodash';
import { Group, isDivider, isGroup, isItem, ITableOfContents, Item, NodeData, TableOfContentItem } from './types';
type SchemaType = 'divider' | 'group';
export function generateProjectToC(searchResults: NodeData[]) {
return flow(
() => searchResults,
groupNodesByType,
({ articles, models, httpServices, httpOperations }) => {
const toc: ITableOfContents = { items: [] };
// Articles
flow(() => articles, sortArticlesByTypeAndPath, appendArticlesToToC(toc))();
if (httpServices.length > 0) {
toc.items.push({ type: 'divider', title: 'APIS' });
}
flow(
() => httpServices,
httpServices =>
appendHttpServicesToToC(toc)({
httpServices,
models,
httpOperations,
}),
appendModelsToToc(toc, 'divider'),
)();
return toc;
},
)();
}
export function generateTocSkeleton(searchResults: NodeData[]) {
return flow(
() => searchResults,
groupNodesByType,
({ articles, models, httpServices }) => {
const toc: ITableOfContents = { items: [] };
// Articles
flow(() => articles, sortArticlesByTypeAndPath, appendArticlesToToC(toc))();
// HTTP Services
toc.items.push({ type: 'divider', title: 'APIS' });
flow(() => httpServices, appendHttpServicesItemsToToC(toc))();
// Models
flow(() => models, appendModelsToToc(toc))();
return toc;
},
)();
}
function modifyEach(
items: TableOfContentItem[],
apply: (item: Item) => TableOfContentItem[],
shouldReplace?: (item: Item) => boolean,
) {
for (let i = items.length - 1; i > -1; i--) {
const item = items[i];
if (isItem(item)) {
if (shouldReplace?.(item)) {
items.splice(i, 1, ...apply(item));
} else {
items.splice(i + 1, 0, ...apply(item));
}
}
if (isGroup(item)) {
modifyEach(item.items, apply, shouldReplace);
}
}
}
function cleanDividers(group: Group) {
group.items = group.items.filter(item => !isDivider(item));
group.items.filter(isGroup).forEach(cleanDividers);
}
function cleanToc(toc: ITableOfContents) {
toc.items.filter(isGroup).forEach(cleanDividers);
}
export function resolveHttpServices(searchResults: NodeData[], toc: ITableOfContents) {
cleanToc(toc);
flow(
() => searchResults,
groupNodesByType,
({ models, httpServices, httpOperations }) => {
modifyEach(
toc.items,
item => {
const httpService = httpServices.find(matchesUri(item.uri));
if (!httpService) return [];
const { hasTags, ...subNodes } = filterByUriRegexpAndCheckTags([])({
httpOperations,
models,
regexp: new RegExp(`^${escapeRegExp(httpService.uri)}\/`, 'i'),
});
const items: TableOfContentItem[] = [];
appendHttpServiceItemsToToC({ items })(subNodes, httpService.tags || []);
return [{ type: 'group', title: item.title, items, uri: httpService.uri }];
},
item => httpServices.some(matchesUri(item.uri)),
);
},
)();
}
function matchesUri(uri: string) {
return (item: NodeData) => item.uri.replace(/^\//, '') === uri.replace(/^\//, '');
}
export function groupNodesByType(searchResults: NodeData[]) {
return searchResults.reduce<{
articles: Array<NodeData>;
models: Array<NodeData>;
httpServices: Array<NodeData>;
httpOperations: Array<NodeData>;
}>(
(results, searchResult) => {
switch (searchResult.type) {
case NodeType.Article:
results.articles.push(searchResult);
break;
case NodeType.HttpOperation:
results.httpOperations.push(searchResult);
break;
case NodeType.HttpService:
results.httpServices.push(searchResult);
break;
case NodeType.Model:
results.models.push(searchResult);
break;
}
return results;
},
{ articles: [], models: [], httpServices: [], httpOperations: [] },
);
}
export function sortArticlesByTypeAndPath(articles: NodeData[]) {
return articles.sort((a1, a2) => {
const rootDirs = ['/', '.', '/docs', 'docs'];
const a1DirPath = dirname(a1.uri);
const a2DirPath = dirname(a2.uri);
// articles without a directory are lifted to the top
const dirOrder =
rootDirs.includes(a1DirPath) || rootDirs.includes(a2DirPath) ? a1DirPath.localeCompare(a2DirPath) : 0;
return dirOrder === 0 ? a1.uri.localeCompare(a2.uri) : dirOrder;
});
}
function findOrCreateArticleGroup(toc: ITableOfContents) {
return (dirs: string[]) => {
return dirs.reduce<ITableOfContents | Group>((group, dir, i) => {
if (i === 0) {
// for depth=0 create the dividers
const divider = group.items.filter(isDivider).find(item => item.title === dir);
if (!divider) {
group.items.push({ type: 'divider', title: dir });
}
return group;
} else {
// for depth>0 create groups
const childGroup = group.items.filter(isGroup).find(item => item.title === dir);
if (!childGroup) {
const newGroup: Group = { type: 'group', title: dir, items: [] };
group.items.push(newGroup);
return newGroup;
}
return childGroup;
}
}, toc);
};
}
export function appendArticlesToToC(toc: ITableOfContents) {
return (articles: NodeData[]) => {
return articles.reduce<ITableOfContents>(
(toc, article) =>
flow(partial(getDirsFromUri, article.uri), findOrCreateArticleGroup(toc), group => {
group.items.push({ type: 'item', title: article.name, uri: article.uri });
return toc;
})(),
toc,
);
};
}
function filterByUriRegexpAndCheckTags(standaloneModels: NodeData[]) {
return ({ regexp, httpOperations, models }: { regexp: RegExp; httpOperations: NodeData[]; models: NodeData[] }) => {
let hasTags = false;
return {
httpOperations: httpOperations.filter(n => {
const isRelevant = regexp.test(n.uri);
if (isRelevant && n.tags?.length) {
hasTags = true;
}
return isRelevant;
}),
models: models.filter(n => {
const isRelevant = regexp.test(n.uri);
if (isRelevant) {
if (n.tags?.length) {
hasTags = true;
}
standaloneModels.splice(
standaloneModels.findIndex(m => m === n),
1,
);
}
return isRelevant;
}),
hasTags,
};
};
}
function appendHttpServiceItemsToToC(toc: ITableOfContents) {
return (
{ httpOperations, models }: { httpOperations: NodeData[]; models: NodeData[] },
serviceTagNames: string[],
) => {
const operationsAndModels = [
...httpOperations.map(i => ({ ...i, nodeType: NodeType.HttpOperation })),
...models.map(i => ({ ...i, nodeType: NodeType.Model })),
];
const { groups, ungroupedModels, ungroupedOperations } = operationsAndModels.reduce<{
groups: { [key: string]: Group };
ungroupedOperations: Item[];
ungroupedModels: NodeData[];
}>(
(result, subNode) => {
const [tagName] = subNode.tags || [];
const item: Item = {
type: 'item',
title: subNode.name,
uri: subNode.uri,
};
if (tagName) {
if (result.groups[tagName.toLowerCase()]) {
result.groups[tagName.toLowerCase()].items.push(item);
} else {
const serviceTagName = serviceTagNames.find(tn => tn.toLowerCase() === tagName.toLowerCase());
result.groups[tagName.toLowerCase()] = {
type: 'group',
title: serviceTagName || tagName,
items: [item],
};
}
} else {
if (subNode.nodeType === NodeType.HttpOperation) {
result.ungroupedOperations.push(item);
} else {
result.ungroupedModels.push(subNode);
}
}
return result;
},
{ groups: {}, ungroupedOperations: [], ungroupedModels: [] },
);
ungroupedOperations.forEach(item => toc.items.push(item));
const tagNamesLC = serviceTagNames.map(tn => tn.toLowerCase());
Object.entries(groups)
.sort(([g1], [g2]) => {
const g1LC = g1.toLowerCase();
const g2LC = g2.toLowerCase();
const g1Idx = tagNamesLC.findIndex(tn => tn === g1LC);
const g2Idx = tagNamesLC.findIndex(tn => tn === g2LC);
// Move not-tagged groups to the bottom
if (g1Idx < 0 && g2Idx < 0) return 0;
if (g1Idx < 0) return 1;
if (g2Idx < 0) return -1;
// sort tagged groups according to the order found in HttpService
return g1Idx - g2Idx;
})
.forEach(([, group]) => toc.items.push(group));
appendModelsToToc(toc, 'group')(ungroupedModels);
};
}
function appendHttpServicesItemsToToC(toc: ITableOfContents) {
return (httpServices: NodeData[]) => {
if (httpServices.length) {
httpServices.forEach(httpService =>
toc.items.push({ type: 'item', title: httpService.name, uri: httpService.uri }),
);
}
};
}
export function appendHttpServicesToToC(toc: ITableOfContents) {
return ({
httpServices,
httpOperations,
models,
}: {
httpServices: NodeData[];
httpOperations: NodeData[];
models: NodeData[];
}) => {
const standaloneModels = models.slice();
sortBy(httpServices, 'name').forEach(httpService => {
let tocNode: ITableOfContents | Group;
tocNode = { type: 'group', title: httpService.name, items: [], uri: httpService.uri };
toc.items.push(tocNode);
flow(
() => ({
httpOperations,
models,
regexp: new RegExp(`^${escapeRegExp(httpService.uri)}${httpService.uri.endsWith('/') ? '' : '/'}`, 'i'),
}),
filterByUriRegexpAndCheckTags(standaloneModels),
({ hasTags, ...subNodes }) => appendHttpServiceItemsToToC(tocNode)(subNodes, httpService.tags || []),
)();
});
return standaloneModels;
};
}
export function appendModelsToToc(toc: ITableOfContents, schemaType: SchemaType = 'divider') {
return (models: NodeData[]) => {
if (models.length) {
const { others, groups } = models.reduce<{
groups: { [key: string]: Group };
others: Item[];
}>(
(result, model) => {
const [tagName] = model.tags || [];
const item: Item = { type: 'item', title: model.name, uri: model.uri };
if (tagName) {
if (result.groups[tagName.toLowerCase()]) {
result.groups[tagName.toLowerCase()].items.push(item);
} else {
result.groups[tagName.toLowerCase()] = {
type: 'group',
title: tagName,
items: [item],
};
}
} else {
result.others.push(item);
}
return result;
},
{ groups: {}, others: [] },
);
const childItems: TableOfContentItem[] = [];
Object.entries(groups).forEach(([, group]) => childItems.push(group));
others.forEach(item => childItems.push(item));
if (schemaType === 'divider') {
toc.items.push({ type: 'divider', title: 'Schemas' });
toc.items.push(...childItems);
} else {
toc.items.push({ type: 'group', title: 'Schemas', items: childItems });
}
}
};
}
function getDirsFromUri(uri: string) {
const strippedUri = uri.replace(/^\/?(?:docs\/)?/, '');
return strippedUri.split(sep).slice(0, -1);
} | the_stack |
import assert = require("assert")
import util = require("../test-utils")
//import _=require("underscore")
//import fs = require("fs")
//import abnf = require('abnf');
//import path = require("path")
//import yll=require("../jsyaml/jsyaml2lowLevel")
//import yaml=require("../jsyaml/yamlAST")
//import hl=require("../highLevelAST")
//import tools = require("./testTools")
//import testgen = require("./testgen/testgen")
//import bnfgen = require("./testgen/bnfgen")
//import exgen = require("./testgen/exgen")
//import gu = require("./testgen/gen-util")
//import resgen = require("./testgen/resgen")
//import parser = require("../artifacts/raml10parser");
//import servergen = require("../tools/servergen/servergen")
//import mkdirp = require('mkdirp');
describe('Parser Tests',function() {
// good 1
it ("good-1 #good-1",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-1.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 2
it ("good-2 #good-2",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-2.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 3
it ("good-3 #good-3",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-3.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 4
it ("good-4 #good-4",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-4.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 5
it ("good-5 #good-5",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-5.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 6
it ("good-6 #good-6",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-6.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 7
it ("good-7 #good-7",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-7.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 8
it ("good-8 #good-8",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-8.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 9
it ("good-9 #good-9",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-9.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 10
it ("good-10 #good-10",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-10.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 11
it ("good-11 #good-11",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-11.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 12
it ("good-12 #good-12",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-12.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 13
it ("good-13 #good-13",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-13.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 14
it ("good-14 #good-14",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-14.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 15
it ("good-15 #good-15",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-15.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 16
it ("good-16 #good-16",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-16.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 17
it ("good-17 #good-17",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-17.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 18
it ("good-18 #good-18",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-18.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 19
it ("good-19 #good-19",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-19.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 20
it ("good-20 #good-20",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-20.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 21
it ("good-21 #good-21",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-21.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 22
it ("good-22 #good-22",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-22.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 23
it ("good-23 #good-23",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-23.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 24
it ("good-24 #good-24",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-24.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 25
it ("good-25 #good-25",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-25.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 26
it ("good-26 #good-26",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-26.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 27
it ("good-27 #good-27",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-27.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 28
it ("good-28 #good-28",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-28.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 29
it ("good-29 #good-29",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-29.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 30
it ("good-30 #good-30",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-30.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 31
it ("good-31 #good-31",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-31.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 32
it ("good-32 #good-32",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-32.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 33
it ("good-33 #good-33",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-33.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 34
it ("good-34 #good-34",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-34.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 35
it ("good-35 #good-35",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-35.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 36
it ("good-36 #good-36",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-36.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 37
it ("good-37 #good-37",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-37.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 38
it ("good-38 #good-38",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-38.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 39
it ("good-39 #good-39",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-39.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 40
it ("good-40 #good-40",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-40.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 41
it ("good-41 #good-41",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-41.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 42
it ("good-42 #good-42",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-42.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 43
it ("good-43 #good-43",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-43.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 44
it ("good-44 #good-44",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-44.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 45
it ("good-45 #good-45",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-45.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 46
it ("good-46 #good-46",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-46.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 47
it ("good-47 #good-47",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-47.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 48
it ("good-48 #good-48",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-48.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 49
it ("good-49 #good-49",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-49.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 50
it ("good-50 #good-50",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-50.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 51
it ("good-51 #good-51",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-51.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 52
it ("good-52 #good-52",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-52.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 53
it ("good-53 #good-53",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-53.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 54
it ("good-54 #good-54",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-54.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 55
it ("good-55 #good-55",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-55.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 56
it ("good-56 #good-56",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-56.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 57
it ("good-57 #good-57",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-57.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 58
it ("good-58 #good-58",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-58.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 59
it ("good-59 #good-59",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-59.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 60
it ("good-60 #good-60",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-60.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 61
it ("good-61 #good-61",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-61.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 62
it ("good-62 #good-62",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-62.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 63
it ("good-63 #good-63",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-63.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 64
it ("good-64 #good-64",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-64.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 65
it ("good-65 #good-65",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-65.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 66
it ("good-66 #good-66",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-66.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 67
it ("good-67 #good-67",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-67.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 68
it ("good-68 #good-68",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-68.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 69
it ("good-69 #good-69",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-69.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 70
it ("good-70 #good-70",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-70.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 71
it ("good-71 #good-71",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-71.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 72
it ("good-72 #good-72",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-72.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 73
it ("good-73 #good-73",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-73.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 74
it ("good-74 #good-74",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-74.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 75
it ("good-75 #good-75",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-75.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 76
it ("good-76 #good-76",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-76.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 77
it ("good-77 #good-77",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-77.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 78
it ("good-78 #good-78",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-78.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 79
it ("good-79 #good-79",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-79.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 80
it ("good-80 #good-80",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-80.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 81
it ("good-81 #good-81",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-81.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 82
it ("good-82 #good-82",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-82.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 83
it ("good-83 #good-83",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-83.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 84
it ("good-84 #good-84",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-84.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 85
it ("good-85 #good-85",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-85.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 86
it ("good-86 #good-86",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-86.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 87
it ("good-87 #good-87",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-87.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 88
it ("good-88 #good-88",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-88.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 89
it ("good-89 #good-89",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-89.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 90
it ("good-90 #good-90",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-90.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 91
it ("good-91 #good-91",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-91.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 92
it ("good-92 #good-92",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-92.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 93
it ("good-93 #good-93",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-93.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 94
it ("good-94 #good-94",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-94.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 95
it ("good-95 #good-95",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-95.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 96
it ("good-96 #good-96",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-96.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 97
it ("good-97 #good-97",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-97.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 98
it ("good-98 #good-98",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-98.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 99
it ("good-99 #good-99",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-99.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
// good 100
it ("good-100 #good-100",function(){
var api = util.loadApiWrapper1(util.data("../parser-tests-gen/data/good/good-100.raml"));
assert.equal(util.countErrors(api.highLevel()), 0);
});
});
// footer | the_stack |
export async function invokeHostJsonMethod(target:string, args:{[id:string]:any}) {
const formData = new FormData();
for (var k in args) {
if (!args.hasOwnProperty(k)) continue;
formData.append(k, args[k]);
}
try {
const r = await fetch(`https://host/script`, {
method: "POST",
body: formData
});
const body = await r.text();
if (r.ok)
return body.length > 0 ? JSON.parse(body) : null;
throw body;
} catch (e) {
throw e;
}
}
export async function invokeHostTextMethod(target:string, args:{[id:string]:any}) {
const formData = new FormData();
for (var k in args) {
if (!args.hasOwnProperty(k)) continue;
formData.append(k, args[k]);
}
try {
const r = await fetch(`https://host/script`, {
method: "POST",
body: formData
});
return await r.text();
} catch (e) {
throw e;
}
}
export function combinePaths(...paths: string[]): string {
let parts = [], i, l;
for (i = 0, l = paths.length; i < l; i++) {
const arg = paths[i];
parts = arg.indexOf("://") === -1
? parts.concat(arg.split("/"))
: parts.concat(arg.lastIndexOf("/") === arg.length - 1 ? arg.substring(0, arg.length - 1) : arg);
}
const combinedPaths = [];
for (i = 0, l = parts.length; i < l; i++) {
const part = parts[i];
if (!part || part === ".") continue;
if (part === "..") combinedPaths.pop();
else combinedPaths.push(part);
}
if (parts[0] === "") combinedPaths.unshift("");
return combinedPaths.join("/") || (combinedPaths.length ? "/" : ".");
}
export async function evaluateScript(scriptSrc:string) {
return await invokeHostJsonMethod('script', { 'EvaluateScript':scriptSrc });
}
export async function evaluateCode(scriptSrc:string) {
return await invokeHostJsonMethod('script', { 'EvaluateCode':scriptSrc });
}
export async function evaluateLisp(scriptSrc:string) {
return await invokeHostJsonMethod('script', { 'EvaluateLisp':scriptSrc });
}
export async function renderScript(scriptSrc:string) {
return await invokeHostTextMethod('script', { 'RenderScript':scriptSrc });
}
export async function renderCode(scriptSrc:string) {
return await invokeHostTextMethod('script', { 'RenderCode':scriptSrc });
}
export async function renderLisp(scriptSrc:string) {
return await invokeHostTextMethod('script', { 'RenderLisp':scriptSrc });
}
export async function evaluateScriptAsync(scriptSrc:string) {
return await invokeHostJsonMethod('script', { 'EvaluateScriptAsync':scriptSrc });
}
export async function evaluateCodeAsync(scriptSrc:string) {
return await invokeHostJsonMethod('script', { 'EvaluateCodeAsync':scriptSrc });
}
export async function evaluateLispAsync(scriptSrc:string) {
return await invokeHostJsonMethod('script', { 'EvaluateLispAsync':scriptSrc });
}
export async function renderScriptAsync(scriptSrc:string) {
return await invokeHostTextMethod('script', { 'RenderScriptAsync':scriptSrc });
}
export async function renderCodeAsync(scriptSrc:string) {
return await invokeHostTextMethod('script', { 'RenderCodeAsync':scriptSrc });
}
export async function renderLispAsync(scriptSrc:string) {
return await invokeHostTextMethod('script', { 'RenderLispAsync':scriptSrc });
}
export function quote(text:string) {
return '"' + text.replace('"','\\"') + '"';
}
export interface DesktopInfo {
tool: string;
toolVersion: string;
chromeVersion: string;
}
export async function evalToBool(scriptSrc:string) {
return await evaluateCode(scriptSrc) as boolean;
}
export async function evalToBoolAsync(scriptSrc:string) {
return await evaluateCodeAsync(scriptSrc) as boolean;
}
export async function desktopInfo() { return (await evaluateCode('desktopInfo')) as DesktopInfo; }
export async function openUrl(url:string) { return (await evalToBool(`openUrl(${quote(url)})`)); }
export async function start(url:string) { return (await evalToBool(`start(${quote(url)})`)); }
export async function expandEnvVars(name:string) {
return await evaluateCode(`expandEnvVars(${quote(name)})`);
}
export async function findWindowByName(name:string) {
return parseInt(await evaluateCode(`findWindowByName(${quote(name)})`));
}
/**
* Get Clipboard Contents as a UTF-8 string
*/
export async function clipboard() { return await evaluateCode('clipboard'); }
/**
* Set the Clipboard Contents with a UTF-8 string
*/
export async function setClipboard(contents:string) {
return await evalToBool(`setClipboard(${quote(contents)})`);
}
export interface Size {
width:number;
height:number;
}
export interface Rectangle {
top:number;
left:number;
bottom:number;
right:number;
}
export interface MonitorInfo {
monitor:Rectangle;
work:Rectangle;
flags:number;
}
export async function deviceScreenResolution() {
return (await evaluateCode('deviceScreenResolution')) as Size;
}
export async function primaryMonitorInfo() {
return (await evaluateCode('primaryMonitorInfo')) as MonitorInfo;
}
export async function windowSendToForeground() { return await evalToBool('windowSendToForeground'); }
export async function windowCenterToScreen(useWorkArea?:boolean) {
return await evalToBool(useWorkArea ? `windowCenterToScreen(${useWorkArea})` : `windowCenterToScreen`);
}
export async function windowSetFullScreen() { return await evalToBoolAsync('windowSetFullScreen'); }
export async function windowSetFocus() { return await evalToBool('windowSetFocus'); }
export async function windowShowScrollBar(show:boolean) { return await evalToBoolAsync(`windowShowScrollBar(${show})`); }
export async function windowSetPosition(x:number,y:number,width?:number,height?:number) {
return await evalToBoolAsync(width
? `windowSetPosition(${x},${y},${width},${height})`
: `windowSetPosition(${x},${y})`);
}
export async function windowSetSize(width:number,height:number) {
return await evalToBoolAsync(`windowSetSize(${width},${height})`);
}
export async function windowRedrawFrame() { return await evalToBool('windowRedrawFrame'); }
export async function windowIsVisible() { return await evalToBool('windowIsVisible'); }
export async function windowIsEnabled() { return await evalToBool('windowIsEnabled'); }
export async function windowShow() { return await evalToBool('windowShow'); }
export async function windowHide() { return await evalToBool('windowHide'); }
export async function windowText() { return await evaluateCode('windowText'); }
export async function windowSetText(text:string) { return await evalToBool(`windowSetText(${quote(text)})`); }
export async function windowSize() {
return await evaluateCode('windowSize') as Size;
}
export async function windowClientSize() {
return await evaluateCode('windowClientSize') as Size;
}
export async function windowClientRect() {
return await evaluateCode('windowClientRect') as Rectangle;
}
export async function windowSetState(state:ShowWindowCommands) {
return await evalToBool(`windowSetState(${state})`);
}
export async function knownFolder(folder:KnownFolders) {
return await evaluateCode(`knownFolder(${quote(folder)})`) as string;
}
async function desktopFolderTextFile(folder:string,fileName:string) {
const r = await fetch(`/desktop/${folder}/${fileName}`);
if (!r.ok)
throw `${r.status} ${r.statusText}`;
return await r.text();
}
async function desktopSaveFolderTextFile(folder:string,fileName:string,body:string) {
try {
const r = await fetch(`/desktop/${folder}/${fileName}`, {
method: "POST",
body
});
if (!r.ok)
throw `${r.status} ${r.statusText}`;
const contents = await r.text();
return contents;
} catch (e) {
throw e;
}
}
export async function desktopTextFile(fileName:string) {
return await desktopFolderTextFile('files',fileName);
}
export async function desktopSaveTextFile(fileName:string,body:string) {
return await desktopSaveFolderTextFile('files',fileName,body);
}
export async function desktopDownloadsTextFile(fileName:string) {
return await desktopFolderTextFile('downloads',fileName);
}
export async function desktopSaveDownloadsTextFile(fileName:string,body:string) {
return await desktopSaveFolderTextFile('downloads',fileName,body);
}
export function desktopSaveDownloadUrl(fileName:string, url:string) {
return combinePaths('/desktop/downloads', encodeURIComponent(fileName), 'url', encodeURIComponent(url));
}
/**
* refer to http://pinvoke.net/default.aspx/Enums/ShowWindowCommand.html
*/
export enum ShowWindowCommands {
/**
* Hides the window and activates another window.
*/
Hide = 0,
/**
* Activates and displays a window. If the window is minimized or
* maximized, the system restores it to its original size and position.
* An application should specify this flag when displaying the window
* for the first time.
*/
Normal = 1,
/**
* Activates the window and displays it as a minimized window.
*/
ShowMinimized = 2,
/**
* Maximizes the specified window
*/
Maximize = 3,
/**
* Activates the window and displays it as a maximized window.
*/
ShowMaximized = 3,
/**
* Displays a window in its most recent size and position. This value
* is similar to <see cref="Win32.ShowWindowCommand.Normal"/>, except
* the window is not activated.
*/
ShowNoActivate = 4,
/**
* Activates the window and displays it in its current size and position.
*/
Show = 5,
/**
* Minimizes the specified window and activates the next top-level
* window in the Z order.
*/
Minimize = 6,
/**
* Displays the window as a minimized window. This value is similar to
* <see cref="Win32.ShowWindowCommand.ShowMinimized"/>, except the
* window is not activated.
*/
ShowMinNoActive = ShowMinimized | Show,
/**
* Displays the window in its current size and position. This value is
* similar to <see cref="Win32.ShowWindowCommand.Show"/>, except the
* window is not activated.
*/
ShowNA = 8,
/**
* Activates and displays the window. If the window is minimized or
* maximized, the system restores it to its original size and position.
* An application should specify this flag when restoring a minimized window.
*/
Restore = 9,
/**
* Sets the show state based on the SW_* value specified in the
* STARTUPINFO structure passed to the CreateProcess function by the
* program that started the application.
*/
ShowDefault = 10,
/**
* Windows 2000/XP: Minimizes a window, even if the thread
* that owns the window is not responding. This flag should only be
* used when minimizing windows from a different thread.
*/
ForceMinimize = 11,
}
export enum OpenFolderFlags {
AllowMultiSelect = 0x00000200,
CreatePrompt = 0x00002000,
DontAddToRecent = 0x02000000,
EnableHook = 0x00000020,
EnableIncludeNotify = 0x00400000,
EnableSizing = 0x00800000,
EnableTemplate = 0x00000040,
EnableTemplateHandle = 0x00000080,
Explorer = 0x00080000,
ExtensionIsDifferent = 0x00000400,
FileMustExist = 0x00001000,
ForceShowHidden = 0x10000000,
HideReadOnly = 0x00000004,
LongNames = 0x00200000,
NoChangeDir = 0x00000008,
NoDereferenceLinks = 0x00100000,
NoLongNames = 0x00040000,
NoNetworkButton = 0x00020000,
NoReadOnlyReturn = 0x00008000,
NoTestFileCreate = 0x00010000,
NoValidate = 0x00000100,
OverwritePrompt = 0x00000002,
PathMustExist = 0x00000800,
ReadOnly = 0x00000001,
ShareAware = 0x00004000,
ShowHelp = 0x00000010,
}
/**
* Refer to the Win32 GetOpenFileName options at:
* https://docs.microsoft.com/en-us/windows/win32/api/commdlg/ns-commdlg-openfilenamea
*/
export interface OpenFileOptions {
flags?: OpenFolderFlags;
title?: string;
filter?: string;
filterIndex?: number;
initialDir?: string;
defaultExt?: string;
templateName?: string;
isFolderPicker?: boolean;
}
export interface DialogResult {
file: string|null;
fileTitle: string|null;
ok: boolean|null;
}
export async function openFile(options:OpenFileOptions) {
return (await evaluateCode(`openFile(${JSON.stringify(options)})`)) as DialogResult;
}
export interface OpenFolderOptions {
title?: string;
initialDir?: string;
}
export async function openFolder(options:OpenFolderOptions) {
return (await evaluateCode(`openFolder(${JSON.stringify(options)})`)) as DialogResult;
}
export enum MessageBoxType {
AbortRetryIgnore = 0x00000002,
CancelTryContinue = 0x00000006,
Help = 0x00004000,
Ok = 0x00000000,
OkCancel = 0x00000001,
RetryCancel = 0x00000005,
YesNo = 0x00000004,
YesNoCancel = 0x00000003,
IconExclamation = 0x00000030,
IconWarning = 0x00000030,
IconInformation = 0x00000040,
IconQuestion = 0x00000020,
IconStop = 0x00000010,
DefaultButton1 = 0x00000000,
DefaultButton2 = 0x00000100,
DefaultButton3 = 0x00000200,
DefaultButton4 = 0x00000300,
AppModal = 0x00000000,
SystemModal = 0x00001000,
TaskModal = 0x00002000,
DefaultDesktopOnly = 0x00020000,
RightJustified = 0x00080000,
RightToLeftReading = 0x00100000,
SetForeground = 0x00010000,
TopMost = 0x00040000,
ServiceNotification = 0x00200000,
}
export enum MessageBoxReturn {
Abort = 3,
Cancel = 2,
Continue = 11,
Ignore = 5,
No = 7,
Ok = 1,
Retry = 4,
TryAgain = 10,
Yes = 6,
}
export enum KnownFolders {
Contacts = 'Contacts',
Desktop = 'Desktop',
Documents = 'Documents',
Downloads = 'Downloads',
Favorites = 'Favorites',
Links = 'Links',
Music = 'Music',
Pictures = 'Pictures',
SavedGames = 'SavedGames',
SavedSearches = 'SavedSearches',
Videos = 'Videos',
}
/**
* Refer to Win32 API
* https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-messagebox
* @param title
* @param caption
* @param type
*/
export async function messageBox(title:string, caption:string="", type:MessageBoxType=MessageBoxType.Ok|MessageBoxType.TopMost) {
return (await evaluateCode(`messageBox(${quote(title)},${quote(caption)},${type})`)) as MessageBoxReturn;
} | the_stack |
import {
Controller,
ApiController,
Dino,
HttpGet,
HttpPost,
Parse,
QueryParam,
BindBoolean,
BindInteger,
BindNumber,
BindRegExp,
toInteger,
toNumber,
toBoolean,
request,
HandlerConstants,
IParseHandler,
IParseProps,
DinoModel
} from './index';
import { initializeTests } from './init';
const customHandler: IParseHandler = (props: IParseProps): any => {
const data = props.data === undefined ? 'test_data' : props.data;
return {
value: props.value,
key: props.key,
data: data,
action: props.action,
controller: props.controller.constructor.name
};
};
const modelHandler: IParseHandler = (props: IParseProps, model: DinoModel): any => {
model.isValid = false;
model.values.push({
key: props.key,
value: props.value
});
model.errors.push({
key: props.key,
value: [`${props.value}TestError`]
});
};
@Controller('/test')
class TestController extends ApiController {
@HttpGet('/toBoolean/:val')
toBoolean(@Parse(toBoolean) val: boolean): any {
return { data: val };
}
@HttpGet('/toBooleanQuery/:val')
toBooleanQuery(@QueryParam(toBoolean) val: boolean): any {
return { data: val };
}
@HttpGet('/toInteger/:val')
toInteger(@Parse(toInteger) val: number): any {
return { data: val };
}
@HttpGet('/toNumber/:val')
toNumber(@Parse(toNumber) val: number): any {
return { data: val };
}
@HttpGet('/bindNumber/:val')
bindNumber(@BindNumber() val: number): any {
return { data: val };
}
@HttpGet('/bindBoolean/:val')
bindBoolean(@BindBoolean() val: boolean): any {
return { data: val };
}
@HttpGet('/bindInteger/:val')
bindInteger(@BindInteger() val: number): any {
return { data: val };
}
@HttpGet('/bindRegexp/:val')
bindRegExp(@BindRegExp(/^[0-9]+$/) val: string): any {
return { data: val };
}
// Verify with and without parse
@HttpGet('/user/:id/:user/:old')
userImg(
@Parse(toNumber) id: number,
user: string,
@Parse(toBoolean) old: boolean): any {
return { id: id, user: user, old: old };
}
// Verify with, without parse and without parsed-body
@HttpPost('/add/:user/:op')
add(
body: any,
user: string,
@Parse(toNumber) op: number): any {
return {
body: body,
user: user,
op: op
};
}
@HttpPost('/addParse/:user/:op')
addParse(
@Parse(() => 'test_body') body: any,
@Parse(() => 'test_user') user: string): any {
return {
body: body,
user: user
};
}
@HttpGet('/handler/:id')
handler(@Parse(customHandler) id: any): any {
return id;
}
@HttpGet('/handlerData/:id')
handlerData(@Parse(customHandler, 'custom_data') id: any): any {
return id;
}
@HttpGet('/model/:user/:id')
modelHandler(
@Parse(modelHandler) id: any,
@Parse(modelHandler) user: any): any {
return {
valid: this.model.isValid,
values: this.model.values,
errors: this.model.errors.filter(x => x.key === 'id')[0].value
};
}
}
describe('parse.e2e.spec', () => {
const baseRoute = '/api/test';
function register(dino: Dino): void {
dino.registerController(TestController);
dino.bind();
}
it('parse.toBoolean.parses_boolean', done => {
const x = initializeTests();
const app = x.app;
const dino = x.dino;
register(dino);
request(app)
.get(`${baseRoute}/toBoolean/true`)
.expect('Content-Type', /json/)
.expect(200, { data: true }, done);
});
it('parse.toBoolean.fails_parsing_"hello"_verify_ActionParamException', done => {
const x = initializeTests();
const app = x.app;
const dino = x.dino;
register(dino);
request(app)
.get(`${baseRoute}/toBoolean/hello`)
.expect('Content-Type', /json/)
// For message format
// Refer: builtin.middlewares.ActionParamExceptionMiddleware
.expect(400, {
value: 'hello',
message: HandlerConstants.toBoolean
}, done);
});
it('parse.toInteger.parses_integer', done => {
const x = initializeTests();
const app = x.app;
const dino = x.dino;
register(dino);
request(app)
.get(`${baseRoute}/toInteger/5`)
.expect('Content-Type', /json/)
.expect(200, { data: 5 }, done);
});
it('parse.toNumber.parses_number', done => {
const x = initializeTests();
const app = x.app;
const dino = x.dino;
register(dino);
request(app)
.get(`${baseRoute}/toNumber/-5.5`)
.expect('Content-Type', /json/)
.expect(200, { data: -5.5 }, done);
});
it('BindNumber.parses_number', done => {
const x = initializeTests();
const app = x.app;
const dino = x.dino;
register(dino);
request(app)
.get(`${baseRoute}/bindNumber/75.5`)
.expect('Content-Type', /json/)
.expect(200, { data: 75.5 }, done);
});
it('BindBoolean.parses_boolean', done => {
const x = initializeTests();
const app = x.app;
const dino = x.dino;
register(dino);
request(app)
.get(`${baseRoute}/bindBoolean/true`)
.expect('Content-Type', /json/)
.expect(200, { data: true }, done);
});
it('BindInteger.parses_integer', done => {
const x = initializeTests();
const app = x.app;
const dino = x.dino;
register(dino);
request(app)
.get(`${baseRoute}/bindInteger/85`)
.expect('Content-Type', /json/)
.expect(200, { data: 85 }, done);
});
it('BindRegexp.parses_against_regexp', done => {
const x = initializeTests();
const app = x.app;
const dino = x.dino;
register(dino);
request(app)
.get(`${baseRoute}/bindRegexp/85`)
.expect('Content-Type', /json/)
.expect(200, { data: '85' }, done);
});
it('parse.when_pathParam_and_querystring_are_same_has_no_@QueryParam_injects_pathParam',
done => {
const x = initializeTests();
const app = x.app;
const dino = x.dino;
register(dino);
request(app)
.get(`${baseRoute}/toBoolean/true?val=false`)
.expect('Content-Type', /json/)
.expect(200, { data: true }, done);
});
it('parse.when_pathParam_and_querystring_are_same_has_@QueryParam_injects_queryParam',
done => {
const x = initializeTests();
const app = x.app;
const dino = x.dino;
register(dino);
request(app)
.get(`${baseRoute}/toBooleanQuery/true?val=false`)
.expect('Content-Type', /json/)
.expect(200, { data: false }, done);
});
it('parse.with_and_without_parse', done => {
const x = initializeTests();
const app = x.app;
const dino = x.dino;
register(dino);
request(app)
.get(`${baseRoute}/user/45/john/false`)
.expect('Content-Type', /json/)
.expect(200, { id: 45, user: 'john', old: false }, done);
});
it('parse.with_and_without_parse_and_without_parsed_body', done => {
const x = initializeTests();
const app = x.app;
const dino = x.dino;
const body = { msg: 'test' };
register(dino);
request(app)
.post(`${baseRoute}/add/john/45`)
.send(body)
.expect('Content-Type', /json/)
.expect(200, { body: body, user: 'john', op: 45 }, done);
});
it('parse.with_and_without_parse_and_with_parsed_body', done => {
const x = initializeTests();
const app = x.app;
const dino = x.dino;
const body = { msg: 'test' };
register(dino);
request(app)
.post(`${baseRoute}/addParse/john/45`)
.send(body)
.expect('Content-Type', /json/)
.expect(200, { body: 'test_body', user: 'test_user' }, done);
});
it('parse.custom_handler_without_custom_data', done => {
const x = initializeTests();
const app = x.app;
const dino = x.dino;
const expected = {
value: 45,
key: 'id',
data: 'test_data',
action: 'handler',
controller: 'TestController'
};
register(dino);
request(app)
.get(`${baseRoute}/${expected.action}/${expected.value}`)
.expect('Content-Type', /json/)
.expect(200, expected, done);
});
it('parse.custom_handler_with_custom_data', done => {
const x = initializeTests();
const app = x.app;
const dino = x.dino;
const expected = {
value: 45,
key: 'id',
data: 'custom_data',
action: 'handlerData',
controller: 'TestController'
};
register(dino);
request(app)
.get(`${baseRoute}/${expected.action}/${expected.value}`)
.expect('Content-Type', /json/)
.expect(200, expected, done);
});
it('parse.model_validations_handler', done => {
const x = initializeTests();
const app = x.app;
const dino = x.dino;
const expected = {
valid: false,
values: [{
key: 'user',
value: 'john'
}, {
key: 'id',
value: '45'
}],
errors: ['45TestError']
};
register(dino);
request(app)
.get(`${baseRoute}/model/john/45`)
.expect('Content-Type', /json/)
.expect(200, expected, done);
});
}); | the_stack |
"use strict";
const JSOfOCaml_SDK = require("./client_sdk.bc.js");
const minaSDK = JSOfOCaml_SDK.minaSDK;
import type {
Network,
PublicKey,
Keypair,
PrivateKey,
Signed,
Payment,
StakeDelegation,
Message,
Party,
SignableData,
} from "./TSTypes";
import { isPayment, isMessage, isStakeDelegation, isParty } from "./Utils";
const defaultValidUntil = "4294967295";
// Shut down wasm workers, which are not needed here
if (globalThis.wasm_rayon_poolbuilder) {
globalThis.wasm_rayon_poolbuilder.free();
for (let worker of globalThis.wasm_workers) {
worker.terminate();
}
}
class Client {
private network: Network;
constructor(options: { network: Network }) {
if (!options?.network) {
throw "Invalid Specified Network";
}
const specifiedNetwork = options.network.toLowerCase();
if (specifiedNetwork !== "mainnet" && specifiedNetwork !== "testnet") {
throw "Invalid Specified Network";
}
this.network = specifiedNetwork;
}
/**
* Generates a public/private key pair
*
* @returns A Mina key pair
*/
public genKeys(): Keypair {
return minaSDK.genKeys();
}
/**
* Verifies if a key pair is valid by checking if the public key can be derived from
* the private key and additionally checking if we can use the private key to
* sign a transaction. If the key pair is invalid, an exception is thrown.
*
* @param keypair A key pair
* @returns True if the `keypair` is a verifiable key pair, otherwise throw an exception
*/
public verifyKeypair(keypair: Keypair): boolean {
return minaSDK.validKeypair(keypair);
}
/**
* Derives the public key of the corresponding private key
*
* @param privateKey The private key used to get the corresponding public key
* @returns A public key
*/
public derivePublicKey(privateKey: PrivateKey): PublicKey {
return minaSDK.publicKeyOfPrivateKey(privateKey);
}
/**
* Signs an arbitrary message
*
* @param message An arbitrary string message to be signed
* @param key The key pair used to sign the message
* @returns A signed message
*/
public signMessage(message: string, key: Keypair): Signed<Message> {
return {
signature: minaSDK.signString(this.network, key.privateKey, message),
data: {
publicKey: key.publicKey,
message,
},
};
}
/**
* Verifies that a signature matches a message.
*
* @param signedMessage A signed message
* @returns True if the `signedMessage` contains a valid signature matching
* the message and publicKey.
*/
public verifyMessage(signedMessage: Signed<Message>): boolean {
return minaSDK.verifyStringSignature(
this.network,
signedMessage.signature,
signedMessage.data.publicKey,
signedMessage.data
);
}
/**
* Signs a payment transaction using a private key.
*
* This type of transaction allows a user to transfer funds from one account
* to another over the network.
*
* @param payment An object describing the payment
* @param privateKey The private key used to sign the transaction
* @returns A signed payment transaction
*/
public signPayment(
payment: Payment,
privateKey: PrivateKey
): Signed<Payment> {
const memo = payment.memo ?? "";
const fee = String(payment.fee);
const nonce = String(payment.nonce);
const amount = String(payment.amount);
const validUntil = String(payment.validUntil ?? defaultValidUntil);
return {
signature: minaSDK.signPayment(this.network, privateKey, {
common: {
fee,
feePayer: payment.from,
nonce,
validUntil,
memo,
},
paymentPayload: {
source: payment.from,
receiver: payment.to,
amount,
},
}).signature,
data: {
to: payment.to,
from: payment.from,
fee,
amount,
nonce,
memo,
validUntil,
},
};
}
/**
* Verifies a signed payment.
*
* @param signedPayment A signed payment transaction
* @returns True if the `signed(payment)` is a verifiable payment
*/
public verifyPayment(signedPayment: Signed<Payment>): boolean {
const payload = signedPayment.data;
const memo = payload.memo ?? "";
const fee = String(payload.fee);
const amount = String(payload.amount);
const nonce = String(payload.nonce);
const validUntil = String(payload.validUntil ?? defaultValidUntil);
return minaSDK.verifyPaymentSignature(this.network, {
sender: signedPayment.data.from,
signature: signedPayment.signature,
payment: {
common: {
fee,
feePayer: payload.from,
nonce,
validUntil,
memo,
},
paymentPayload: {
source: payload.from,
receiver: payload.to,
amount,
},
},
});
}
/**
* Signs a stake delegation transaction using a private key.
*
* This type of transaction allows a user to delegate their
* funds from one account to another for use in staking. The
* account that is delegated to is then considered as having these
* funds when determining whether it can produce a block in a given slot.
*
* @param stakeDelegation An object describing the stake delegation
* @param privateKey The private key used to sign the transaction
* @returns A signed stake delegation
*/
public signStakeDelegation(
stakeDelegation: StakeDelegation,
privateKey: PrivateKey
): Signed<StakeDelegation> {
const memo = stakeDelegation.memo ?? "";
const fee = String(stakeDelegation.fee);
const nonce = String(stakeDelegation.nonce);
const validUntil = String(stakeDelegation.validUntil ?? defaultValidUntil);
return {
signature: minaSDK.signStakeDelegation(this.network, privateKey, {
common: {
fee,
feePayer: stakeDelegation.from,
nonce,
validUntil,
memo,
},
delegationPayload: {
newDelegate: stakeDelegation.to,
delegator: stakeDelegation.from,
},
}).signature,
data: {
to: stakeDelegation.to,
from: stakeDelegation.from,
fee,
nonce,
memo,
validUntil,
},
};
}
/**
* Verifies a signed stake delegation.
*
* @param signedStakeDelegation A signed stake delegation
* @returns True if the `signed(stakeDelegation)` is a verifiable stake delegation
*/
public verifyStakeDelegation(
signedStakeDelegation: Signed<StakeDelegation>
): boolean {
const payload = signedStakeDelegation.data;
const memo = payload.memo ?? "";
const fee = String(payload.fee);
const nonce = String(payload.nonce);
const validUntil = String(payload.validUntil ?? defaultValidUntil);
return minaSDK.verifyStakeDelegationSignature(this.network, {
sender: signedStakeDelegation.data.from,
signature: signedStakeDelegation.signature,
stakeDelegation: {
common: {
fee,
feePayer: payload.from,
nonce,
validUntil,
memo,
},
delegationPayload: {
newDelegate: payload.to,
delegator: payload.from,
},
},
});
}
/**
* Compute the hash of a signed payment.
*
* @param signedPayment A signed payment transaction
* @returns A transaction hash
*/
public hashPayment(signedPayment: Signed<Payment>): string {
const payload = signedPayment.data;
const memo = payload.memo ?? "";
const fee = String(payload.fee);
const amount = String(payload.amount);
const nonce = String(payload.nonce);
const validUntil = String(payload.validUntil ?? defaultValidUntil);
return minaSDK.hashPayment({
sender: signedPayment.data.from,
signature: signedPayment.signature,
payment: {
common: {
fee: fee,
feePayer: payload.from,
nonce,
validUntil,
memo,
},
paymentPayload: {
source: payload.from,
receiver: payload.to,
amount,
},
},
});
}
/**
* Compute the hash of a signed stake delegation.
*
* @param signedStakeDelegation A signed stake delegation
* @returns A transaction hash
*/
public hashStakeDelegation(
signedStakeDelegation: Signed<StakeDelegation>
): string {
const payload = signedStakeDelegation.data;
const memo = payload.memo ?? "";
const fee = String(payload.fee);
const nonce = String(payload.nonce);
const validUntil = String(payload.validUntil ?? defaultValidUntil);
return minaSDK.hashStakeDelegation({
sender: signedStakeDelegation.data.from,
signature: signedStakeDelegation.signature,
stakeDelegation: {
common: {
fee,
feePayer: payload.from,
nonce,
validUntil,
memo,
},
delegationPayload: {
newDelegate: payload.to,
delegator: payload.from,
},
},
});
}
/**
* Sign a parties transaction using a private key.
*
* This type of transaction allows a user to update state on a given
* Smart Contract running on Mina.
*
* @param party A object representing a Parties tx
* @param privateKey The fee payer private key
* @returns Signed parties
*/
public signParty(party: Party, privateKey: PrivateKey): Signed<Party> {
const parties = JSON.stringify(party.parties.otherParties);
const memo = party.feePayer.memo ?? "";
const fee = String(party.feePayer.fee);
const nonce = String(party.feePayer.nonce);
const feePayer = String(party.feePayer.feePayer);
const signedParties = minaSDK.signParty(
parties,
{
feePayer,
fee,
nonce,
memo,
},
privateKey
);
return {
signature: JSON.parse(signedParties).feePayer.authorization,
data: {
parties: signedParties,
feePayer: {
feePayer,
fee,
nonce,
memo,
},
},
};
}
/**
* Converts a Rosetta signed transaction to a JSON string that is
* compatible with GraphQL. The JSON string is a representation of
* a `Signed_command` which is what our GraphQL expects.
*
* @param signedRosettaTxn A signed Rosetta transaction
* @returns A string that represents the JSON conversion of a signed Rosetta transaction`.
*/
public signedRosettaTransactionToSignedCommand(
signedRosettaTxn: string
): string {
return minaSDK.signedRosettaTransactionToSignedCommand(signedRosettaTxn);
}
/**
* Return the hex-encoded format of a valid public key. This will throw an exception if
* the key is invalid or the conversion fails.
*
* @param publicKey A valid public key
* @returns A string that represents the hex encoding of a public key.
*/
public publicKeyToRaw(publicKey: string): string {
return minaSDK.rawPublicKeyOfPublicKey(publicKey);
}
/**
* Signs an arbitrary payload using a private key. This function can sign messages,
* payments, stake delegations, and parties. If the payload is unrecognized, an Error
* is thrown.
*
* @param payload A signable payload
* @param key A valid keypair
* @returns A signed payload
*/
public signTransaction(
payload: SignableData,
privateKey: PrivateKey
): Signed<SignableData> {
if (isMessage(payload)) {
return this.signMessage(payload.message, {
publicKey: payload.publicKey,
privateKey,
});
}
if (isPayment(payload)) {
return this.signPayment(payload, privateKey);
}
if (isStakeDelegation(payload)) {
return this.signStakeDelegation(payload, privateKey);
}
if (isParty(payload)) {
return this.signParty(payload, privateKey);
} else {
throw new Error(`Expected signable payload, got '${payload}'.`);
}
}
}
export = Client; | the_stack |
import React, {
ChangeEvent,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react'
import {
Button,
ButtonBase,
Dialog,
DialogActions,
DialogContent,
DialogContentText,
DialogTitle,
Divider,
Fade,
fade,
FormControlLabel,
Grid,
IconButton,
InputBase,
PaletteType,
Paper,
Radio,
RadioGroup,
TextField,
ThemeProvider,
Toolbar,
Typography,
useTheme,
} from '@material-ui/core'
import { makeStyles, createMuiTheme } from '@material-ui/core/styles'
import OutsidePage from 'src/components/blocks/OutsidePage'
import { Alert } from '@material-ui/lab'
import { MIN_WIDTH } from 'src/config/constants'
import EditRoundedIcon from '@material-ui/icons/EditRounded'
import DeleteRoundedIcon from '@material-ui/icons/DeleteRounded'
import BottomDrawer from 'src/components/blocks/BottomDrawer'
import { HexColorPicker } from 'react-colorful'
import { CustomTheme } from 'src/interfaces/UserSettings'
import SaveRoundedIcon from '@material-ui/icons/SaveRounded'
import { useDispatch } from 'react-redux'
import { useSelector } from 'src/hooks'
import { setSettings } from 'src/store/actions/settings'
import { useSnackbar } from 'notistack'
import tinycolor from 'tinycolor2'
import {
deepPurple,
pink,
red,
purple,
indigo,
blue,
lightBlue,
cyan,
teal,
green,
lightGreen,
lime,
yellow,
amber,
orange,
deepOrange,
} from '@material-ui/core/colors'
import { Redirect, useHistory, useParams } from 'react-router'
import { History } from 'history'
import getContrastPaperColor from 'src/utils/getContrastPaperColor'
interface PaletteGridItem {
text: string
color: string
}
interface PaletteItem {
title: string
items: PaletteGridItem[]
}
interface ColorPickerState {
open: boolean
color?: string
item?: string
}
const COLOR_PICKER_PRESET_COLORS = [
red[500],
pink[500],
purple[500],
deepPurple[500],
indigo[500],
blue[500],
lightBlue[500],
cyan[500],
teal[500],
green[500],
lightGreen[500],
lime[500],
yellow[500],
amber[500],
orange[500],
deepOrange[500],
]
const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
flexDirection: 'column',
width: '100%',
},
section: {
backgroundColor: theme.palette.background.paper,
marginTop: theme.spacing(1.5),
[theme.breakpoints.up(MIN_WIDTH)]: {
borderRadius: 8,
},
},
sectionHeader: {
fontSize: 13,
color: theme.palette.text.hint,
textTransform: 'uppercase',
fontWeight: 500,
lineHeight: 'normal',
fontFamily: 'Google Sans',
marginBottom: theme.spacing(1.5),
paddingBottom: '0 !important',
},
padding: {
padding: theme.spacing(1.8, 2),
},
infoAlert: {
backgroundColor: 'rgb(0 107 204 / 7%)',
marginTop: theme.spacing(1.8),
borderRadius: 0,
[theme.breakpoints.up(MIN_WIDTH)]: {
borderRadius: 8,
},
},
themeNameInput: {
marginTop: theme.spacing(3),
},
deleteIcon: {
transition: 'all 225ms cubic-bezier(0.4, 0, 0.2, 1) 0ms !important',
marginRight: ({
isAlreadySavedLocally = false,
}: {
isAlreadySavedLocally?: boolean
}) => (isAlreadySavedLocally ? 0 : -48),
},
code: {
background: getContrastPaperColor(theme),
padding: '3px 6px',
borderRadius: theme.shape.borderRadius,
wordBreak: 'break-word',
},
}))
const usePreviewStyles = makeStyles((theme) => ({
box: {
background: theme.palette.background.default,
margin: theme.spacing(0, 2, 1.8, 2),
borderRadius: 8,
padding: theme.spacing(1.8, 2),
},
paper: {
height: 128,
marginBottom: theme.spacing(1.8),
},
button: {
marginRight: theme.spacing(2),
marginBottom: theme.spacing(1.8),
},
appbar: {
height: 49,
flexGrow: 1,
marginBottom: theme.spacing(2),
borderRadius: 8,
zIndex: 1,
width: '100%',
display: 'flex',
boxSizing: 'border-box',
flexShrink: 0,
flexDirection: 'column',
},
toolbar: {
margin: 'auto',
minHeight: 'unset',
height: 48,
padding: 0,
maxWidth: MIN_WIDTH,
width: '100%',
flexDirection: 'column',
},
headerTitle: {
fontWeight: 800,
height: '100%',
alignItems: 'center',
display: 'flex',
fontFamily: 'Google Sans',
},
appbarContent: {
display: 'flex',
alignItems: 'center',
width: `calc(100% - ${theme.spacing(2) * 2}px)`,
height: '100%',
},
dividerWrapper: {
background: theme.palette.background.paper,
display: 'flex',
width: `calc(100% - ${theme.spacing(2) * 2}px)`,
},
}))
const usePaletteGridItemStyles = makeStyles((theme) => ({
gridItem: {
alignItems: 'center',
display: 'flex',
justifyContent: 'start',
borderRadius: 4,
transition: 'all 250ms 0ms cubic-bezier(0.25, 1, 0.25, 1)',
},
box: {
width: 48,
height: 48,
flexShrink: 0,
marginRight: theme.spacing(1),
borderRadius: 4,
},
gridItemTitle: {
marginTop: theme.spacing(3),
},
textHolder: {
display: 'flex',
flexDirection: 'column',
alignItems: 'baseline',
flexGrow: 1,
},
iconHolder: {
display: 'flex',
height: '100%',
alignItems: 'center',
justifyContent: 'center',
padding: theme.spacing(0, 1),
},
icon: {
transform: 'scale(0.5)',
opacity: 0,
transition: 'all 250ms 0ms cubic-bezier(0.25, 1, 0.25, 1)',
},
checked: {
transform: 'scale(1)',
opacity: 1,
},
checkedBackground: {
background: fade(theme.palette.text.primary, 0.05),
},
}))
const useColorPickerStyles = makeStyles((theme) => ({
picker: {
width: '100% !important',
height: '256px !important',
'& .react-colorful': {
width: '100%',
},
},
swatches: {
display: 'flex',
flexWrap: 'wrap',
marginTop: theme.spacing(1.5),
marginBottom: theme.spacing(1.5),
},
swatch: {
width: 32,
height: 32,
margin: 4,
border: 'none !important',
padding: 0,
borderRadius: 4,
outline: 'none',
cursor: 'pointer',
'-webkit-tap-highlight-color': fade(theme.palette.divider, 0.3),
},
input: {
color: theme.palette.text.primary,
width: '100%',
fontWeight: 500,
},
preview: {
alignItems: 'center',
display: 'flex',
justifyContent: 'start',
borderRadius: 4,
transition: 'all 250ms 0ms cubic-bezier(0.25, 1, 0.25, 1)',
marginBottom: theme.spacing(2),
},
box: {
width: 24,
height: 24,
flexShrink: 0,
marginRight: theme.spacing(2),
borderRadius: '50%',
},
inputHolder: {
display: 'flex',
flexDirection: 'column',
alignItems: 'baseline',
flexGrow: 1,
},
}))
const PaletteGridItem = ({
title,
items,
setColorPickerState,
}: {
title: string
items: PaletteItem['items']
setColorPickerState: React.Dispatch<React.SetStateAction<ColorPickerState>>
}) => {
const theme = useTheme()
const classes = usePaletteGridItemStyles()
const handleClick = (item: PaletteGridItem) => {
setColorPickerState({
open: true,
color: item.color,
item: item.text,
})
}
return (
<>
<Typography gutterBottom className={classes.gridItemTitle}>
{title}
</Typography>
<Grid container spacing={1}>
{items.map((e, i) => (
<Grid
key={i}
item
xs={12}
sm={6}
md={4}
className={classes.gridItem}
component={ButtonBase}
onClick={() => handleClick(e)}
>
<div
className={classes.box}
style={{
backgroundColor: e.color,
border:
'background.paper' === e.text ||
'background.default' === e.text
? '1px solid ' + theme.palette.divider
: null,
}}
/>
<div className={classes.textHolder}>
<Typography variant="body2">{e.text}</Typography>
<Typography variant="body2" color="textSecondary">
{e.color}
</Typography>
</div>
</Grid>
))}
</Grid>
</>
)
}
const paletteTextToThemeField = {
'primary.light': (t: CustomTheme, c: string) => {
t.palette.primary.light = c
return t
},
'primary.main': (t: CustomTheme, c: string) => {
t.palette.primary.main = c
return t
},
'primary.dark': (t: CustomTheme, c: string) => {
t.palette.primary.dark = c
return t
},
'background.paper': (t: CustomTheme, c: string) => {
t.palette.background.paper = c
return t
},
'background.default': (t: CustomTheme, c: string) => {
t.palette.background.default = c
return t
},
'text.primary': (t, c) => {
t.palette.text.primary = c
t.palette.text.secondary = fade(c, 0.54)
t.palette.text.disabled = fade(c, 0.38)
t.palette.text.hint = fade(c, 0.38)
return t
},
}
const CustomColorfulPicker = ({ color, presetColors, onChange, ...props }) => {
const classes = useColorPickerStyles()
const hexString = useMemo(() => {
return color.startsWith('#') ? color : tinycolor(color).toHexString()
}, [color])
return (
<>
<HexColorPicker
className={classes.picker}
onChange={onChange}
color={hexString}
{...props}
/>
<div className={classes.swatches}>
{presetColors.map((presetColor) => (
<button
key={presetColor}
className={classes.swatch}
style={{ background: presetColor }}
onClick={() => onChange(presetColor)}
/>
))}
</div>
</>
)
}
const ColorPicker = ({
setState,
state,
setCurrentTheme,
}: {
setState: React.Dispatch<React.SetStateAction<ColorPickerState>>
state: ColorPickerState
setCurrentTheme: React.Dispatch<React.SetStateAction<CustomTheme>>
}) => {
const classes = useColorPickerStyles()
const theme = useTheme()
const [color, setColor] = useState(state.color)
const handleSubmit = () => {
setCurrentTheme((theme) =>
paletteTextToThemeField[state.item](theme, color)
)
setState({
open: false,
})
}
const handleCancel = () => {
setState({
open: false,
item: state.item,
color,
})
}
const handleInputChange = (event: ChangeEvent<HTMLInputElement>) => {
setColor(event.target.value)
}
useEffect(() => {
state.open && setColor(state.color)
}, [state.color])
return (
<BottomDrawer isOpen={state.open} disableClose headerText={'ะัะฑะพั ัะฒะตัะฐ'}>
<div className={classes.preview}>
<div
className={classes.box}
style={{
backgroundColor: color,
border:
theme.palette.background.paper === color
? '1px solid ' + theme.palette.divider
: null,
}}
/>
<div className={classes.inputHolder}>
<InputBase
endAdornment={<EditRoundedIcon color="disabled" />}
value={color}
onChange={handleInputChange}
className={classes.input}
/>
</div>
</div>
<CustomColorfulPicker
presetColors={COLOR_PICKER_PRESET_COLORS}
color={color}
onChange={setColor}
/>
<Grid container direction="row" spacing={1}>
<Grid item xs={6}>
<Button
fullWidth
variant="text"
disableElevation
onClick={handleCancel}
>
ะัะผะตะฝะฐ
</Button>
</Grid>
<Grid item xs={6}>
<Button
variant="contained"
color="primary"
disableElevation
fullWidth
onClick={handleSubmit}
>
ะกะพั
ัะฐะฝะธัั
</Button>
</Grid>
</Grid>
</BottomDrawer>
)
}
const getPaletteItems = (theme: CustomTheme) => [
{
title: 'ะะบัะตะฝั',
items: [
{
text: 'primary.light',
color: theme.palette.primary.light,
},
{
text: 'primary.main',
color: theme.palette.primary.main,
},
{
text: 'primary.dark',
color: theme.palette.primary.dark,
},
],
},
{
title: 'ะะพะฒะตัั
ะฝะพััะธ',
items: [
{
text: 'background.paper',
color: theme.palette.background.paper,
},
{
text: 'background.default',
color: theme.palette.background.default,
},
],
},
{
title: 'ะขะตะบัั',
items: [
{
text: 'text.primary',
color: theme.palette.text.primary,
},
],
},
]
const PreviewBox = ({ currentTheme }: { currentTheme: CustomTheme }) => {
const rootClasses = useStyles({})
const classes = usePreviewStyles()
const compiledCurrentTheme = useCallback(() => createMuiTheme(currentTheme), [
JSON.stringify(currentTheme),
])
const buttonVariants: ['contained', 'outlined', 'text'] = [
'contained',
'outlined',
'text',
]
return (
<ThemeProvider theme={compiledCurrentTheme}>
<div className={rootClasses.section}>
<Typography
className={[rootClasses.sectionHeader, rootClasses.padding].join(' ')}
>
ะัะตะดะฟัะพัะผะพัั
</Typography>
<div className={classes.box}>
<Grid container spacing={2}>
{[1, 3, 5].map((e, i) => (
<Grid item key={i} xs={4}>
<Paper elevation={e} className={classes.paper} />
</Grid>
))}
</Grid>
<Paper className={classes.appbar} elevation={0}>
<Toolbar className={classes.toolbar}>
<div className={classes.appbarContent}>
<Typography
variant="h6"
color="textPrimary"
className={classes.headerTitle}
>
habra.
</Typography>
</div>
<div className={classes.dividerWrapper}>
<Divider style={{ width: '100%' }} />
</div>
</Toolbar>
</Paper>
<Grid container alignItems="center">
{buttonVariants.map((e, i) => (
<Button
className={classes.button}
key={i}
variant={e}
color="primary"
disableElevation
>
ะะฝะพะฟะบะฐ
</Button>
))}
</Grid>
<Typography color="textPrimary">
ะฃ ััะพะณะพ ัะตะบััะฐ ัะฒะตั text.primary
</Typography>
<Typography color="textSecondary">
ะ ั ััะพะณะพ - text.secondary
</Typography>
</div>
</div>
</ThemeProvider>
)
}
const NewTheme = ({ isEditMode = false }: { isEditMode?: boolean }) => {
const theme = useTheme()
const history = useHistory()
const customThemes = useSelector((store) => store.settings.customThemes)
const { themeType: paramsThemeType } = useParams<{ themeType: string }>()
const editTheme =
isEditMode && customThemes.find((e) => e.type === paramsThemeType)
const [colorPickerState, setColorPickerState] = useState<ColorPickerState>({
open: false,
color: null,
item: null,
})
const defaultTheme = {
name: 'ะะพะฒะฐั ัะตะผะฐ',
type: Date.now().toString(),
palette: {
type: theme.palette.type,
primary: {
main: theme.palette.primary.main,
light: theme.palette.primary.light,
dark: theme.palette.primary.dark,
},
background: {
paper: theme.palette.background.paper,
default: theme.palette.background.default,
},
text: {
primary: theme.palette.text.primary,
secondary: theme.palette.text.secondary,
hint: theme.palette.text.hint,
disabled: theme.palette.text.disabled,
},
},
}
const titleInputRef = useRef<HTMLInputElement>()
const [isTitleEditDialogOpen, setTitleEditDialogOpen] = useState(false)
const [isDeleteDialogOpen, setDeleteDialogOpen] = useState(false)
const [isSaveDialogOpen, setSaveDialogOpen] = useState(false)
const [hasBeenEdited, setHasBeenEdited] = useState<boolean>(false)
const [currentTheme, setCurrentThemeUnwrapped] = useState<CustomTheme>(
isEditMode ? editTheme : defaultTheme
)
const dispatch = useDispatch()
const { enqueueSnackbar } = useSnackbar()
const paletteItems = React.useMemo(() => getPaletteItems(currentTheme), [
JSON.stringify(currentTheme),
])
const isAlreadySavedLocally = React.useMemo(
() => customThemes.some((e) => e.type === currentTheme.type),
[customThemes]
)
const classes = useStyles({ isAlreadySavedLocally })
const setCurrentTheme: React.Dispatch<React.SetStateAction<CustomTheme>> = (
...props
) => {
!hasBeenEdited && setHasBeenEdited(true)
setCurrentThemeUnwrapped(...props)
}
if (isEditMode && !editTheme) {
return <Redirect to="/settings/appearance" />
}
const handleSaveClick = () => {
const newCustomThemes = [...customThemes]
if (isAlreadySavedLocally) {
const themeIndex = newCustomThemes.findIndex(
(e) => e.type === currentTheme.type
)
newCustomThemes.splice(themeIndex, 1, currentTheme)
} else {
newCustomThemes.push(currentTheme)
}
dispatch(
setSettings({
customThemes: newCustomThemes,
})
)
setHasBeenEdited(false)
enqueueSnackbar('ะขะตะผะฐ ัะพั
ัะฐะฝะตะฝะฐ', {
variant: 'success',
autoHideDuration: 3000,
})
}
const handleSaveDialogCancel = () => setSaveDialogOpen(false)
const handleSaveDialogDelete = () => {
setSaveDialogOpen(false)
history.goBack()
}
const handleSaveDialogSubmit = () => {
handleSaveClick()
setSaveDialogOpen(false)
history.goBack()
}
const handleDeleteClick = () => setDeleteDialogOpen(true)
const handleDeleteDialogCancel = () => setDeleteDialogOpen(false)
const handleDeleteDialogSubmit = () => {
const newCustomThemes = [...customThemes]
const themeIndex = newCustomThemes.findIndex(
(e) => e.type === currentTheme.type
)
newCustomThemes.splice(themeIndex, 1)
dispatch(
setSettings({
customThemes: newCustomThemes,
themeType: 'light',
})
)
enqueueSnackbar('ะขะตะผะฐ ัะดะฐะปะตะฝะฐ', {
variant: 'success',
autoHideDuration: 3000,
})
setDeleteDialogOpen(false)
history.goBack()
}
const handleTitleEditClick = () => setTitleEditDialogOpen(true)
const handleTitleEditDialogCancel = () => setTitleEditDialogOpen(false)
const handleTitleEditDialogSubmit = () => {
if (titleInputRef.current.value) {
setCurrentTheme((prev) => ({
...prev,
name: titleInputRef.current.value,
}))
setTitleEditDialogOpen(false)
}
}
const handleThemeTypeChange = (_event, type: string) => {
setCurrentTheme((prev) => ({
...prev,
palette: {
...prev.palette,
type: type as PaletteType,
},
}))
}
const toolbarIcons = (
<>
<IconButton onClick={handleTitleEditClick}>
<EditRoundedIcon />
</IconButton>
<IconButton onClick={handleSaveClick} disabled={!hasBeenEdited}>
<SaveRoundedIcon />
</IconButton>
<Fade in={isAlreadySavedLocally}>
<IconButton onClick={handleDeleteClick} className={classes.deleteIcon}>
<DeleteRoundedIcon />
</IconButton>
</Fade>
{/** Title edit Dialog */}
<Dialog
open={isTitleEditDialogOpen}
onClose={handleTitleEditDialogCancel}
>
<DialogTitle>ะะฐะทะฒะฐะฝะธะต ัะตะผั</DialogTitle>
<DialogContent>
<DialogContentText>
ะะฐะทะฒะฐะฝะธะต ะฑัะดะตั ะพัะพะฑัะฐะถะฐัััั ะฒ ะฝะฐัััะพะนะบะฐั
ััะดะพะผ ั ัะตะผะฐะผะธ ะฟะพ
ัะผะพะปัะฐะฝะธั. ะญัะพ ะฝะฐะทะฒะฐะฝะธะต ะผะพะถะฝะพ ะฑัะดะตั ะฟะพะผะตะฝััั.
</DialogContentText>
<TextField
inputRef={titleInputRef}
autoFocus
margin="dense"
name="title"
label="ะะฐะทะฒะฐะฝะธะต ัะตะผั"
type="text"
autoComplete="off"
fullWidth
/>
</DialogContent>
<DialogActions>
<Button onClick={handleTitleEditDialogCancel} color="primary">
ะัะผะตะฝะฐ
</Button>
<Button color="primary" onClick={handleTitleEditDialogSubmit}>
ะกะพั
ัะฐะฝะธัั
</Button>
</DialogActions>
</Dialog>
{/** Delete theme Dialog */}
<Dialog open={isDeleteDialogOpen} onClose={handleDeleteDialogCancel}>
<DialogTitle>ะฃะดะฐะปะธัั ัะตะผั</DialogTitle>
<DialogContent>
<DialogContentText>
ะกะพะทะดะฐะฝะฝัั ัะตะผั ะฑัะดะตั ะฝะตะฒะพะทะผะพะถะฝะพ ะฒะพัััะฐะฝะพะฒะธัั. ะั ัะพัะฝะพ ั
ะพัะธัะต ะตั
ัะดะฐะปะธัั?
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={handleDeleteDialogCancel} color="primary">
ะัะผะตะฝะฐ
</Button>
<Button
color="primary"
variant="contained"
disableElevation
onClick={handleDeleteDialogSubmit}
>
ะฃะดะฐะปะธัั
</Button>
</DialogActions>
</Dialog>
</>
)
const onBackClick = (
backLinkFunction: (history: History<unknown>) => void
) => {
// We need to update current theme if it was edited, so colors will be updated
if (hasBeenEdited && isEditMode) {
dispatch(
setSettings({
themeType: currentTheme.type,
})
)
}
// If the theme was edited, but user wants to exit, show saving warning dialog
if (hasBeenEdited) {
setSaveDialogOpen(true)
} else {
// Otherwise, exit the page.
backLinkFunction(history)
}
}
return (
<OutsidePage
hidePositionBar
disableShrinking
headerText={currentTheme.name}
backgroundColor={theme.palette.background.paper}
toolbarIcons={toolbarIcons}
onBackClick={(backLinkFunction) =>
onBackClick(backLinkFunction.bind(history))
}
>
<div className={classes.root}>
{/** Save theme Dialog */}
<Dialog open={isSaveDialogOpen} onClose={handleSaveDialogCancel}>
<DialogTitle>Cะพั
ัะฐะฝะตะฝะธะต</DialogTitle>
<DialogContent>
<DialogContentText>
ะััะฐะปะธัั ะฝะตัะพั
ัะฐะฝัะฝะฝัะต ะธะทะผะตะฝะตะฝะธั, ัะพั
ัะฐะฝะธัั? ะะฐะถะผะธัะต{' '}
<code className={classes.code}>Esc</code>, ััะพะฑั ะพัะผะตะฝะธัั.
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={handleSaveDialogDelete} color="primary">
ะัะนัะธ ะฑะตะท ะธะทะผะตะฝะตะฝะธะน
</Button>
<Button
color="primary"
variant="contained"
disableElevation
onClick={handleSaveDialogSubmit}
>
ะกะพั
ัะฐะฝะธัั
</Button>
</DialogActions>
</Dialog>
<Alert severity="info" className={classes.infoAlert}>
ะงัะพะฑั ะฟะพะผะตะฝััั ัะฒะตั ะฒ ัะตะผะต, ะฝะฐะถะผะธัะต ะฝะฐ ะตะณะพ ะฟะพะปะต, ะฐ ะทะฐัะตะผ ะฒัะฑะตัะธัะต
ะฝัะถะฝัะน ัะฒะตั.
</Alert>
<PreviewBox currentTheme={currentTheme} />
<div className={classes.section}>
<div className={classes.padding}>
<Typography className={classes.sectionHeader}>ะะฐะปะธััะฐ</Typography>
<div>
<Typography gutterBottom>ะขะธะฟ ัะตะผั</Typography>
<RadioGroup
value={currentTheme.palette.type}
onChange={handleThemeTypeChange}
>
<FormControlLabel
value="light"
control={<Radio color="primary" />}
label={'ะกะฒะตัะปะฐั'}
/>
<FormControlLabel
value="dark"
control={<Radio color="primary" />}
label={'ะขัะผะฝะฐั'}
/>
</RadioGroup>
{paletteItems.map((e, i) => (
<PaletteGridItem
key={i}
items={e.items}
title={e.title}
setColorPickerState={setColorPickerState}
/>
))}
</div>
</div>
</div>
<ColorPicker
setCurrentTheme={setCurrentTheme}
state={colorPickerState}
setState={setColorPickerState}
/>
</div>
</OutsidePage>
)
}
export default React.memo(NewTheme) | the_stack |
import { MinimalTransaction, TransactionReceipt } from "@connext/types";
import { getGasPrice, stringify } from "@connext/utils";
import { Injectable, OnModuleInit } from "@nestjs/common";
import { providers, BigNumber } from "ethers";
import PriorityQueue from "p-queue";
import { Channel } from "../channel/channel.entity";
import { ConfigService } from "../config/config.service";
import { OnchainTransactionRepository } from "./onchainTransaction.repository";
import { LoggerService } from "../logger/logger.service";
import { OnchainTransaction, TransactionReason } from "./onchainTransaction.entity";
import { ChannelRepository } from "../channel/channel.repository";
const MIN_GAS_LIMIT = BigNumber.from(500_000);
const BAD_NONCE = "the tx doesn't have the correct nonce";
const INVALID_NONCE = "Invalid nonce";
const NO_TX_HASH = "no transaction hash found in tx response";
const UNDERPRICED_REPLACEMENT = "replacement transaction underpriced";
export const MAX_RETRIES = 5;
export const KNOWN_ERRORS = [BAD_NONCE, NO_TX_HASH, UNDERPRICED_REPLACEMENT, INVALID_NONCE];
export type OnchainTransactionResponse = providers.TransactionResponse & {
completed: (confirmations?: number) => Promise<void>; // resolved when tx is properly mined + stored
};
@Injectable()
export class OnchainTransactionService implements OnModuleInit {
private nonces: Map<number, Promise<number>> = new Map();
private queues: Map<number, PriorityQueue> = new Map();
constructor(
private readonly configService: ConfigService,
private readonly onchainTransactionRepository: OnchainTransactionRepository,
private readonly channelRepository: ChannelRepository,
private readonly log: LoggerService,
) {
this.log.setContext("OnchainTransactionService");
this.configService.signers.forEach((signer, chainId) => {
this.nonces.set(chainId, signer.getTransactionCount());
this.queues.set(chainId, new PriorityQueue({ concurrency: 1 }));
});
}
async findByAppId(appIdentityHash: string): Promise<OnchainTransaction | undefined> {
return this.onchainTransactionRepository.findByAppId(appIdentityHash);
}
async sendUserWithdrawal(
channel: Channel,
transaction: MinimalTransaction,
appIdentityHash: string,
): Promise<OnchainTransactionResponse> {
return this.queues.get(channel.chainId)!.add(
() =>
new Promise((resolve, reject) =>
this.sendTransaction(
transaction,
TransactionReason.USER_WITHDRAWAL,
channel,
appIdentityHash,
)
.then((result) => resolve(result))
.catch((error) => reject(error.message)),
),
);
}
async sendWithdrawal(
channel: Channel,
transaction: MinimalTransaction,
appIdentityHash: string,
): Promise<OnchainTransactionResponse> {
return this.queues.get(channel.chainId)!.add(
() =>
new Promise((resolve, reject) =>
this.sendTransaction(
transaction,
TransactionReason.NODE_WITHDRAWAL,
channel,
appIdentityHash,
)
.then((result) => resolve(result))
.catch((error) => reject(error.message)),
),
);
}
async sendDeposit(
channel: Channel,
transaction: MinimalTransaction,
appIdentityHash: string,
): Promise<OnchainTransactionResponse> {
return this.queues.get(channel.chainId)!.add(
() =>
new Promise((resolve, reject) =>
this.sendTransaction(
transaction,
TransactionReason.COLLATERALIZATION,
channel,
appIdentityHash,
)
.then((result) => resolve(result))
.catch((error) => reject(error.message)),
),
);
}
findByHash(hash: string): Promise<OnchainTransaction | undefined> {
return this.onchainTransactionRepository.findByHash(hash);
}
setAppUninstalled(wasUninstalled: boolean, hash: string): Promise<void> {
return this.onchainTransactionRepository.addAppUninstallFlag(wasUninstalled, hash);
}
async sendMultisigDeployment(
transaction: MinimalTransaction,
chainId: number,
multisigAddress: string,
): Promise<providers.TransactionResponse> {
const channel = await this.channelRepository.findByMultisigAddressOrThrow(multisigAddress);
const tx: OnchainTransactionResponse = await new Promise((resolve, reject) => {
this.queues.get(chainId)!.add(() => {
this.sendTransaction(transaction, TransactionReason.MULTISIG_DEPLOY, channel)
.then((result) => resolve(result))
.catch((error) => reject(error.message));
});
});
// make sure the wait function of the response includes the database
// updates required to truly mark the transaction as completed
const wait: Promise<TransactionReceipt> = new Promise(async (resolve, reject) => {
try {
const receipt = await tx.wait();
await this.onchainTransactionRepository.addReceipt(receipt);
resolve(receipt);
} catch (e) {
reject(e);
}
});
return { ...tx, wait: () => wait };
}
async sendDisputeTransaction(
transaction: MinimalTransaction,
chainId: number,
multisigAddress: string,
): Promise<providers.TransactionResponse> {
const channel = await this.channelRepository.findByMultisigAddressOrThrow(multisigAddress);
const queue = this.queues.get(chainId);
if (!queue) {
throw new Error(`Unsupported chainId ${chainId}. Expected one of: ${Array.from(this.queues.keys())}`);
}
const tx: OnchainTransactionResponse = await new Promise((resolve, reject) => {
queue.add(() => {
this.sendTransaction(transaction, TransactionReason.DISPUTE, channel)
.then((result) => resolve(result))
.catch((error) => reject(error.message));
});
});
// make sure the wait function of the response includes the database
// updates required to truly mark the transaction as completed
const wait: Promise<TransactionReceipt> = new Promise(async (resolve, reject) => {
try {
const receipt = await tx.wait();
await this.onchainTransactionRepository.addReceipt(receipt);
resolve(receipt);
} catch (e) {
reject(e);
}
});
return { ...tx, wait: () => wait };
}
private async sendTransaction(
transaction: MinimalTransaction,
reason: TransactionReason,
channel: Channel,
appIdentityHash?: string,
): Promise<OnchainTransactionResponse> {
const wallet = this.configService.getSigner(channel.chainId);
this.log.info(
`sendTransaction: Using provider URL ${
(wallet.provider as providers.JsonRpcProvider)?.connection?.url
} on chain ${channel.chainId}`,
);
const errors: { [k: number]: string } = [];
let tx: providers.TransactionResponse | undefined;
let nonce: number | undefined;
let attempt: number | undefined;
for (attempt = 1; attempt < MAX_RETRIES + 1; attempt += 1) {
try {
this.log.info(`Attempt ${attempt}/${MAX_RETRIES} to send transaction to ${transaction.to}`);
const chainNonce = await wallet.getTransactionCount();
const memoryNonce = (await this.nonces.get(channel.chainId))!;
nonce = chainNonce > memoryNonce ? chainNonce : memoryNonce;
// add pending so we can mark it failed
this.log.info(`Adding pending tx with nonce ${nonce}`);
// TODO: (Med) Generate the transaction hash before sending
// TODO: this wont work if the loop happens more than once
// possible fix: add unique index on from+nonce and use onConflict
// actually this wont work, easiest fix is to look it up by channel+reason+nonce first :/
await this.onchainTransactionRepository.addPending(
transaction,
nonce,
wallet.address,
reason,
channel,
appIdentityHash,
);
this.log.info(`Populating tx with nonce ${nonce}`);
const populatedTx = await wallet.populateTransaction({ ...transaction, nonce });
this.log.info(`Sending tx with nonce ${nonce}`);
tx = await wallet.sendTransaction({
...populatedTx,
gasLimit: BigNumber.from(populatedTx.gasLimit || 0).lt(MIN_GAS_LIMIT)
? MIN_GAS_LIMIT
: populatedTx.gasLimit,
gasPrice: getGasPrice(wallet.provider!, channel.chainId),
});
this.log.info(`Tx submitted, hash: ${tx.hash}`);
if (!tx.hash) {
throw new Error(NO_TX_HASH);
}
this.nonces.set(channel.chainId, Promise.resolve(nonce + 1));
// add fields from tx response
await this.onchainTransactionRepository.addResponse(
tx,
nonce,
reason,
channel,
appIdentityHash,
);
const start = Date.now();
// eslint-disable-next-line no-loop-func
const completed: Promise<void> = new Promise(async (resolve, reject) => {
try {
const receipt = await tx!.wait();
this.log.info(`Tx mined, hash: ${receipt.transactionHash}`);
await this.onchainTransactionRepository.addReceipt(receipt);
resolve();
} catch (e) {
reject(e);
}
});
tx.wait().then(async (receipt) => {
this.log.info(
`Success sending transaction! Tx mined at block ${receipt.blockNumber} on chain ${
channel.chainId
}: ${receipt.transactionHash} in ${Date.now() - start}ms`,
);
await this.onchainTransactionRepository.addReceipt(receipt);
this.log.debug(`added receipt, status should be success`);
});
return { ...tx, completed: () => completed };
} catch (e) {
errors[attempt] = e.message;
const knownErr = KNOWN_ERRORS.find((err) => e.message.includes(err));
if (!knownErr) {
this.log.error(`Transaction failed to send with unknown error: ${e.message}`);
break;
}
// known error, retry
this.log.warn(
`Sending transaction attempt ${attempt}/${MAX_RETRIES} failed: ${e.message}. Retrying.`,
);
}
}
if (tx) {
this.log.info(`Marking failed by tx hash`);
await this.onchainTransactionRepository.markFailedByTxHash(tx, errors, appIdentityHash);
} else if (nonce) {
this.log.info(`Marking failed by nonce`);
await this.onchainTransactionRepository.markFailedByChannelFromAndNonce(
channel.multisigAddress,
wallet.address,
nonce,
errors,
appIdentityHash,
);
} else {
this.log.error(`No nonce or tx hash found to mark failed tx with!`);
}
throw new Error(`Failed to send transaction (errors indexed by attempt): ${stringify(errors)}`);
}
private retryFailedTransactions = async (): Promise<void> => {
this.log.info(`retryFailedTransactions started`);
const toResend = await this.onchainTransactionRepository.findFailedTransactions(KNOWN_ERRORS);
// NOTE: could alternatively look only for withdrawals that are
// finalized but have no onchain tx id. however, no reason not to retry
// all failed txs
this.log.info(`Found ${toResend.length} transactions to resend`);
for (const stored of toResend) {
try {
await this.sendTransaction(
{ to: stored.to, value: stored.value, data: stored.data },
stored.reason,
stored.channel,
);
} catch (e) {
this.log.warn(
`Failed to send transaction, will retry on next startup, hash: ${stored.hash}. ${e.message}`,
);
}
}
this.log.info(`retryFailedTransactions completed`);
};
async onModuleInit(): Promise<void> {
await this.retryFailedTransactions();
}
} | the_stack |
import { describe, expect, it } from '@jest/globals';
import { merge } from 'lodash';
import { quality, quality_1vs1, rate, rate_1vs1, Rating, TrueSkill, winProbability } from '../src';
import { SkillGaussian } from '../src/mathematics';
function generateTeams(sizes: number[], env?: TrueSkill) {
return sizes.map(size => {
const r = Array(size).fill(0);
if (env) {
return r.map(() => env.createRating());
}
return r.map(() => new Rating());
});
}
function generateIndividual(size: number) {
return generateTeams(Array(size).fill(1));
}
function compareRating(result: Rating[][], expected: number[][]) {
const res = result.flat();
expect(result).toBeInstanceOf(Array);
for (let team = 0; team < res.length; team++) {
expect(res[team].mu).toBeCloseTo(expected[team][0], 0.01);
expect(res[team].sigma).toBeCloseTo(expected[team][1], 0.01);
}
}
describe('TrueSkill', () => {
it('should create rating', () => {
const [team1, team2] = generateTeams([5, 5]);
const rated = rate([team1, team2]);
expect(rated.length).toEqual(2);
expect(rated[0]).toBeInstanceOf(Array);
expect(rated[1]).toBeInstanceOf(Array);
expect(rated[0].length).toEqual(5);
expect(rated[1].length).toEqual(5);
});
it('should rate unsorted groups', () => {
const [t1, t2, t3] = generateTeams([1, 1, 1]);
const rated = rate([t1, t2, t3], [2, 1, 0]);
compareRating(rated, [
[18.325, 6.656],
[25.0, 6.208],
[31.675, 6.656],
]);
});
it('should test n vs n', () => {
// 1 vs 1
let teams = generateTeams([1, 1]);
expect(quality(teams)).toBeCloseTo(0.447, 0.01);
compareRating(rate(teams), [
[29.396, 7.171],
[20.604, 7.171],
]);
// 1 vs 1 draw
compareRating(rate(teams, [0, 0]), [
[25.0, 6.458],
[25.0, 6.458],
]);
// 2 vs 2
teams = generateTeams([2, 2]);
expect(quality(teams)).toBeCloseTo(0.447, 0.01);
compareRating(rate(teams), [
[28.108, 7.774],
[28.108, 7.774],
[21.892, 7.774],
[21.892, 7.774],
]);
// 2 vs 2 draw
compareRating(rate(teams, [0, 0]), [
[25.0, 7.455],
[25.0, 7.455],
[25.0, 7.455],
[25.0, 7.455],
]);
// 4 vs 4
teams = generateTeams([4, 4]);
expect(quality(teams)).toBeCloseTo(0.447, 0.01);
compareRating(rate(teams), [
[27.198, 8.059],
[27.198, 8.059],
[27.198, 8.059],
[27.198, 8.059],
[22.802, 8.059],
[22.802, 8.059],
[22.802, 8.059],
[22.802, 8.059],
]);
});
it('should test 1 vs n', () => {
const [t1] = generateTeams([1]);
// 1 vs 2
let [t2] = generateTeams([2]);
expect(quality([t1, t2])).toBeCloseTo(0.135, 0.01);
compareRating(rate([t1, t2]), [
[33.73, 7.317],
[16.27, 7.317],
[16.27, 7.317],
]);
compareRating(rate([t1, t2], [0, 0]), [
[31.66, 7.138],
[18.34, 7.138],
[18.34, 7.138],
]);
// 1 vs 3
[t2] = generateTeams([3]);
expect(quality([t1, t2])).toBeCloseTo(0.012, 0.01);
compareRating(rate([t1, t2]), [
[36.337, 7.527],
[13.663, 7.527],
[13.663, 7.527],
[13.663, 7.527],
]);
compareRating(rate([t1, t2]), [
[36.337, 7.527],
[13.663, 7.527],
[13.663, 7.527],
[13.663, 7.527],
]);
compareRating(rate([t1, t2], [0, 0]), [
[34.99, 7.455],
[15.01, 7.455],
[15.01, 7.455],
[15.01, 7.455],
]);
// 1 vs 7
[t2] = generateTeams([7]);
expect(quality([t1, t2])).toBeCloseTo(0, 0.01);
compareRating(rate([t1, t2]), [
[40.582, 7.917],
[9.418, 7.917],
[9.418, 7.917],
[9.418, 7.917],
[9.418, 7.917],
[9.418, 7.917],
[9.418, 7.917],
[9.418, 7.917],
]);
});
it('should test individual', () => {
// 3 players
let players = generateIndividual(3);
expect(quality(players)).toBeCloseTo(0.2, 0.001);
compareRating(rate(players), [
[31.675, 6.656],
[25.0, 6.208],
[18.325, 6.656],
]);
compareRating(rate(players, Array(players.length).fill(0)), [
[25.0, 5.698],
[25.0, 5.695],
[25.0, 5.698],
]);
// 4 players
players = generateIndividual(4);
expect(quality(players)).toBeCloseTo(0.089, 0.001);
compareRating(rate(players), [
[33.207, 6.348],
[27.401, 5.787],
[22.599, 5.787],
[16.793, 6.348],
]);
// 5 players
players = generateIndividual(5);
expect(quality(players)).toBeCloseTo(0.04, 0.001);
compareRating(rate(players), [
[34.363, 6.136],
[29.058, 5.536],
[25.0, 5.42],
[20.942, 5.536],
[15.637, 6.136],
]);
// 8 players draw
players = generateIndividual(8);
expect(quality(players)).toBeCloseTo(0.004, 0.001);
compareRating(rate(players, Array(players.length).fill(0)), [
[25.0, 4.592],
[25.0, 4.583],
[25.0, 4.576],
[25.0, 4.573],
[25.0, 4.573],
[25.0, 4.576],
[25.0, 4.583],
[25.0, 4.592],
]);
// 16 players
players = generateIndividual(16);
compareRating(rate(players), [
[40.539, 5.276],
[36.81, 4.711],
[34.347, 4.524],
[32.336, 4.433],
[30.55, 4.38],
[28.893, 4.349],
[27.31, 4.33],
[25.766, 4.322],
[24.234, 4.322],
[22.69, 4.33],
[21.107, 4.349],
[19.45, 4.38],
[17.664, 4.433],
[15.653, 4.524],
[13.19, 4.711],
[9.461, 5.276],
]);
});
it('should test multiple teams', () => {
// 2 vs 4 vs 2
let t1 = [new Rating(40, 4), new Rating(45, 3)];
let t2 = [new Rating(20, 7), new Rating(19, 6), new Rating(30, 9), new Rating(10, 4)];
let t3 = [new Rating(50, 5), new Rating(30, 2)];
expect(quality([t1, t2, t3])).toBeCloseTo(0.367, 0.001);
compareRating(rate([t1, t2, t3], [0, 1, 1]), [
[40.877, 3.84],
[45.493, 2.934],
[19.609, 6.396],
[18.712, 5.625],
[29.353, 7.673],
[9.872, 3.891],
[48.83, 4.59],
[29.813, 1.976],
]);
// 1 vs 2 vs 1
t1 = [new Rating()];
t2 = [new Rating(), new Rating()];
t3 = [new Rating()];
expect(quality([t1, t2, t3])).toBeCloseTo(0.047, 0.001);
});
it('should test upset', () => {
// 1 vs 1
let t1 = [new Rating()];
let t2 = [new Rating(50, 12.5)];
expect(quality([t1, t2])).toBeCloseTo(0.11, 0.001);
compareRating(rate([t1, t2], [0, 0]), [
[31.662, 7.137],
[35.01, 7.91],
]);
// 2 vs 2
t1 = [new Rating(20, 8), new Rating(25, 6)];
t2 = [new Rating(35, 7), new Rating(40, 5)];
expect(quality([t1, t2])).toBeCloseTo(0.084, 0.001);
compareRating(rate([t1, t2]), [
[29.698, 7.008],
[30.455, 5.594],
[27.575, 6.346],
[36.211, 4.768],
]);
// 3 vs 2
t1 = [new Rating(28, 7), new Rating(27, 6), new Rating(26, 5)];
t2 = [new Rating(30, 4), new Rating(31, 3)];
expect(quality([t1, t2])).toBeCloseTo(0.254, 0.001);
compareRating(rate([t1, t2], [0, 1]), [
[28.658, 6.77],
[27.484, 5.856],
[26.336, 4.917],
[29.785, 3.958],
[30.879, 2.983],
]);
compareRating(rate([t1, t2], [1, 0]), [
[21.84, 6.314],
[22.474, 5.575],
[22.857, 4.757],
[32.012, 3.877],
[32.132, 2.949],
]);
// 8 players
const players = [
[new Rating(10, 8)],
[new Rating(15, 7)],
[new Rating(20, 6)],
[new Rating(25, 5)],
[new Rating(30, 4)],
[new Rating(35, 3)],
[new Rating(40, 2)],
[new Rating(45, 1)],
];
expect(quality(players)).toBeCloseTo(0.0, 0.001);
compareRating(rate(players), [
[35.135, 4.506],
[32.585, 4.037],
[31.329, 3.756],
[30.984, 3.453],
[31.751, 3.064],
[34.051, 2.541],
[38.263, 1.849],
[44.118, 0.983],
]);
});
it('should test winProbability', () => {
// 1 vs 1
const t1 = [new Rating()];
const t2 = [new Rating(50, 12.5)];
expect(winProbability(t1, t2)).toBeCloseTo(0.06, 0.001);
});
it('should test partial play', () => {
const t1 = [new Rating()];
const t2 = [new Rating(), new Rating()];
expect(rate([t1, t2], null, [[1], [1, 1]])).toEqual(rate([t1, t2]));
compareRating(rate([t1, t2], null, [[1], [1, 1]]), [
[33.73, 7.317],
[16.27, 7.317],
[16.27, 7.317],
]);
compareRating(rate([t1, t2], null, [[0.5], [0.5, 0.5]]), [
[33.939, 7.312],
[16.061, 7.312],
[16.061, 7.312],
]);
compareRating(rate([t1, t2], null, [[1], [0, 1]]), [
[29.44, 7.166],
[25.0, 8.333],
[20.56, 7.166],
]);
compareRating(rate([t1, t2], null, [[1], [0.5, 1]]), [
[32.417, 7.056],
[21.291, 8.033],
[17.583, 7.056],
]);
// Match quality of partial play
const t3 = [new Rating()];
expect(quality([t1, t2, t3], [[1], [0.25, 0.75], [1]])).toBeCloseTo(0.2, 0.001);
expect(quality([t1, t2, t3], [[1], [0.8, 0.9], [1]])).toBeCloseTo(0.0809, 0.001);
});
it('should test microsoft reasearch example', () => {
// Http://research.microsoft.com/en-us/projects/trueskill/details.aspx
const rated = rate([
{ alice: new Rating() },
{ bob: new Rating() },
{ chris: new Rating() },
{ darren: new Rating() },
{ eve: new Rating() },
{ fabien: new Rating() },
{ george: new Rating() },
{ hillary: new Rating() },
]);
let r: any = {};
rated.forEach(n => {
r = merge(r, n);
});
expect(r.alice.mu).toBeCloseTo(36.771, 0.001);
expect(r.alice.sigma).toBeCloseTo(5.749, 0.001);
expect(r.bob.mu).toBeCloseTo(32.242, 0.001);
expect(r.bob.sigma).toBeCloseTo(5.133, 0.001);
expect(r.chris.mu).toBeCloseTo(29.074, 0.001);
expect(r.chris.sigma).toBeCloseTo(4.943, 0.001);
expect(r.darren.mu).toBeCloseTo(26.322, 0.001);
expect(r.darren.sigma).toBeCloseTo(4.874, 0.001);
expect(r.eve.mu).toBeCloseTo(23.678, 0.001);
expect(r.eve.sigma).toBeCloseTo(4.874, 0.001);
expect(r.fabien.mu).toBeCloseTo(20.926, 0.001);
expect(r.fabien.sigma).toBeCloseTo(4.943, 0.001);
expect(r.george.mu).toBeCloseTo(17.758, 0.001);
expect(r.george.sigma).toBeCloseTo(5.133, 0.001);
expect(r.hillary.mu).toBeCloseTo(13.229, 0.001);
expect(r.hillary.sigma).toBeCloseTo(5.749, 0.001);
});
it('should test 1vs1 shortcuts', () => {
const [p1, p2] = rate_1vs1(new Rating(), new Rating());
expect(p1.mu).toBeCloseTo(29.396, 0.001);
expect(p1.sigma).toBeCloseTo(7.171, 0.001);
expect(p2.mu).toBeCloseTo(20.604, 0.001);
expect(p2.sigma).toBeCloseTo(7.171, 0.001);
const q = quality_1vs1(new Rating(), new Rating());
expect(q).toBeCloseTo(0.447, 0.01);
});
});
describe('Gaussian', () => {
it('should test valid gaussian', () => {
const fn = () => new SkillGaussian(0);
expect(fn).toThrowError('sigma argument is needed');
const fn1 = () => new SkillGaussian(0, 0);
expect(fn1).toThrowError(new Error('sigma**2 should be greater than 0'));
});
});
describe('Rating', () => {
it('should print Rating', () => {
expect(new Rating().toString()).toEqual('Rating(mu=25.000, sigma=8.333)');
});
}); | the_stack |
import { Injectable, Pipe, PipeTransform } from '@angular/core';
import { fontList, customFontWeight } from './lists/lists';
import { Storage } from '../_storage/storage.service';
@Injectable()
export class SharedService {
private _optionsToggle: boolean;
private _optionsPreview: boolean;
private _optionsPage: string;
private _zoneGuess: string;
private _time: string;
private _date: string;
private _title: string = 'New Tab';
private _bg: string;
private _bgColor: string;
private _browser: string;
private _status: string;
private _updateType: "major" | "minor" | "quiet" | "hidden";
private _allBookmarks: any;
constructor(
public settings: Storage
) {
}
get optionsToggle(): boolean {
return this._optionsToggle;
}
set optionsToggle(value: boolean) {
this._optionsToggle = value;
}
get optionsPreview(): boolean {
return this._optionsPreview;
}
set optionsPreview(value: boolean) {
this._optionsPreview = value;
}
get optionsPage(): string {
return this._optionsPage;
}
set optionsPage(value: string) {
this._optionsPage = value;
}
get zoneGuess(): string {
return this._zoneGuess;
}
set zoneGuess(value: string) {
this._zoneGuess = value;
}
get title(): string {
return this._title;
}
set title(value: string) {
this._title = value;
}
get time(): string {
return this._time;
}
set time(value: string) {
this._time = value;
}
get date(): string {
return this._date;
}
set date(value: string) {
this._date = value;
}
get bg(): string {
return this._bg;
}
set bg(value: string) {
this._bg = value;
}
get bgColor(): string {
return this._bgColor;
}
set bgColor(value: string) {
this._bgColor = value;
}
get browser(): string {
return this._browser;
}
set browser(value: string) {
this._browser = value;
}
get status(): string {
return this._status;
}
set status(value: string) {
this._status = value;
}
get updateType(): "major" | "minor" | "quiet" | "hidden" {
return this._updateType;
}
set updateType(value: "major" | "minor" | "quiet" | "hidden") {
this._updateType = value;
}
get allBookmarks(): any {
return this._allBookmarks;
}
set allBookmarks(value: any) {
this._allBookmarks = value;
}
public echo(msg: string, str?: any, obj?: any, type?: 'warning' | 'error' | 'success' | 'save') {
let strStyle = 'display:inline-block;background:#f1f3f7;color:black;padding:5px;margin:0 0 0 5px;border-radius:5px;';
let style = 'display:inline-block;background:#ccd0da;color:black;padding:5px;border-radius:5px;';
if (type === 'warning') {
style = 'display:inline-block;background:#ffe000;color:black;padding:5px;border-radius:5px;';
} else if (type === 'error') {
style = 'display:inline-block;background:#c52525;color:white;padding:5px;border-radius:5px;';
} else if (type === 'success') {
style = 'display:inline-block;background:#7aa76b;color:white;padding:5px;border-radius:5px;';
} else if (type === 'save') {
style = 'display:inline-block;background:rgb(0, 106, 183);color:white;padding:5px;border-radius:5px;';
}
if (str) {
console.log(
`%c${msg}%c${str}`,
style,
strStyle
);
}
if (obj) {
console.log(
`%c${msg}`,
style,
obj
);
}
if (!str && !obj) {
console.log(
`%c${msg}`,
style
);
}
}
public createID(prefix: string) {
return prefix + '_' + (
Number(String(Math.random()).slice(2)) +
Date.now() +
Math.round(performance.now())
).toString(36).toUpperCase();
}
public getFont(font: number, custom: string) {
let fontName;
if (font !== 0) {
fontName = fontList.find(f => f.id === font).family;
} else {
fontName = custom;
}
return '"' + fontName + '"';
}
public getFontWeight(font: number, weight: number) {
let fontWeight;
if (font !== 0) {
fontWeight = fontList.find(f => f.id === font).weight;
} else {
fontWeight = customFontWeight.find(w => w.id === weight).weight;
}
return fontWeight;
}
public getFontSize(size: number, baseSize?: number) {
let emBase = baseSize ? baseSize : 10;
return (size / emBase) + 'em';
}
public getImageSize(size: number, baseSize?: number) {
let base = baseSize ? baseSize : 10;
return ((size / base)) + 'em';
}
public getMaxWidth(size: number) {
// Max width will always be based on viewport as opposed to scaling method.
return (size * 1) + 'vw';
}
public getPercentWidth(size: number) {
// Max width will always be based on viewport as opposed to scaling method.
return (size * 1) + '%';
}
public getMargin(height: number, width: number, multiplier = .1) {
return `${height * multiplier}em ${width * multiplier}em`;
}
public getPadding(size: number, multiplier = .1) {
return (size * multiplier) + 'em';
}
public getOffset(size: number) {
let offset = ((size * 5) * -1);
return 'translateY(' + offset + '%)';
}
public getOffsetLarge(size: number) {
let offset = ((size * 10) * -1);
return 'translateY(' + offset + '%)';
}
public toggleOrder(id: string, enabled: boolean, position: string = "c") {
let positionOrder: any[];
switch (position) {
case "nw":
positionOrder = this.settings.config.order.nw;
break;
case "n":
positionOrder = this.settings.config.order.n;
break;
case "ne":
positionOrder = this.settings.config.order.ne;
break;
case "w":
positionOrder = this.settings.config.order.w;
break;
case "c":
positionOrder = this.settings.config.order.items;
break;
case "e":
positionOrder = this.settings.config.order.e;
break;
case "sw":
positionOrder = this.settings.config.order.sw;
break;
case "s":
positionOrder = this.settings.config.order.s;
break;
case "se":
positionOrder = this.settings.config.order.se;
break;
default:
positionOrder = this.settings.config.order.items;
break;
}
if (!enabled) {
this.removeOrder(id);
} else {
this.removeOrder(id);
let sorted = positionOrder;
if (positionOrder.length > 1) {
sorted = positionOrder.sort((a, b) => a.order - b.order);
}
let newOrderNumber = 1;
if (positionOrder.length > 0) {
newOrderNumber = (sorted[sorted.length - 1].order) + 1;
}
positionOrder.push({
id: id,
order: newOrderNumber
});
}
}
private removeOrder(id: string) {
let foundInList = false;
let positionOrder;
let inNW = this.settings.config.order.nw.some(e => e.id === id);
let inN = this.settings.config.order.n.some(e => e.id === id);
let inNE = this.settings.config.order.ne.some(e => e.id === id);
let inW = this.settings.config.order.w.some(e => e.id === id);
let inC = this.settings.config.order.items.some(e => e.id === id);
let inE = this.settings.config.order.e.some(e => e.id === id);
let inSW = this.settings.config.order.sw.some(e => e.id === id);
let inS = this.settings.config.order.s.some(e => e.id === id);
let inSE = this.settings.config.order.se.some(e => e.id === id);
foundInList = (inNW || inN || inNE || inW || inC || inE || inSW || inS || inSE);
if (foundInList) {
if (inNW) {positionOrder = this.settings.config.order.nw}
if (inN) {positionOrder = this.settings.config.order.n}
if (inNE) {positionOrder = this.settings.config.order.ne}
if (inW) {positionOrder = this.settings.config.order.w}
if (inC) {positionOrder = this.settings.config.order.items}
if (inE) {positionOrder = this.settings.config.order.e}
if (inSW) {positionOrder = this.settings.config.order.sw}
if (inS) {positionOrder = this.settings.config.order.s}
if (inSE) {positionOrder = this.settings.config.order.se}
if (positionOrder) {
let elIndex = positionOrder.findIndex(e => e.id === id);
positionOrder.splice(elIndex, 1);
let sorted = positionOrder;
if (positionOrder.length > 1) {
sorted = positionOrder.sort((a, b) => a.order - b.order);
}
sorted.forEach((e, index) => {
e.order = index + 1;
});
}
}
}
public changeOrder(id: string, up: boolean, position: string = "c") {
let positionOrder: any[];
switch (position) {
case "nw":
positionOrder = this.settings.config.order.nw;
break;
case "n":
positionOrder = this.settings.config.order.n;
break;
case "ne":
positionOrder = this.settings.config.order.ne;
break;
case "w":
positionOrder = this.settings.config.order.w;
break;
case "c":
positionOrder = this.settings.config.order.items;
break;
case "e":
positionOrder = this.settings.config.order.e;
break;
case "sw":
positionOrder = this.settings.config.order.sw;
break;
case "s":
positionOrder = this.settings.config.order.s;
break;
case "se":
positionOrder = this.settings.config.order.se;
break;
default:
positionOrder = this.settings.config.order.items;
break;
}
let sibling: any;
let el = positionOrder.find(e => e.id === id);
if (up) {
sibling = positionOrder.find(e => e.order === el.order - 1);
if (sibling) {
sibling.order += 1;
el.order -= 1;
}
} else {
sibling = positionOrder.find(e => e.order === el.order + 1);
if (sibling) {
sibling.order -= 1;
el.order += 1;
}
}
}
public getOrder(id: string, position: string = "c") {
let positionOrder: any[];
switch (position) {
case "nw":
positionOrder = this.settings.config.order.nw;
break;
case "n":
positionOrder = this.settings.config.order.n;
break;
case "ne":
positionOrder = this.settings.config.order.ne;
break;
case "w":
positionOrder = this.settings.config.order.w;
break;
case "c":
positionOrder = this.settings.config.order.items;
break;
case "e":
positionOrder = this.settings.config.order.e;
break;
case "sw":
positionOrder = this.settings.config.order.sw;
break;
case "s":
positionOrder = this.settings.config.order.s;
break;
case "se":
positionOrder = this.settings.config.order.se;
break;
default:
positionOrder = this.settings.config.order.items;
break;
}
let el = positionOrder.find(e => e.id === id);
if (el) {
return el.order;
} else {
return 'unset';
}
}
public isFirst(id: string, position: string = "c"): boolean {
let positionOrder: any[];
switch (position) {
case "nw":
positionOrder = this.settings.config.order.nw;
break;
case "n":
positionOrder = this.settings.config.order.n;
break;
case "ne":
positionOrder = this.settings.config.order.ne;
break;
case "w":
positionOrder = this.settings.config.order.w;
break;
case "c":
positionOrder = this.settings.config.order.items;
break;
case "e":
positionOrder = this.settings.config.order.e;
break;
case "sw":
positionOrder = this.settings.config.order.sw;
break;
case "s":
positionOrder = this.settings.config.order.s;
break;
case "se":
positionOrder = this.settings.config.order.se;
break;
default:
positionOrder = this.settings.config.order.items;
break;
}
let el = positionOrder.find(e => e.id === id);
if (el) {
return el.order === 1;
} else {
return false;
}
}
public isLast(id: string, position: string = "c"): boolean {
let positionOrder: any[];
switch (position) {
case "nw":
positionOrder = this.settings.config.order.nw;
break;
case "n":
positionOrder = this.settings.config.order.n;
break;
case "ne":
positionOrder = this.settings.config.order.ne;
break;
case "w":
positionOrder = this.settings.config.order.w;
break;
case "c":
positionOrder = this.settings.config.order.items;
break;
case "e":
positionOrder = this.settings.config.order.e;
break;
case "sw":
positionOrder = this.settings.config.order.sw;
break;
case "s":
positionOrder = this.settings.config.order.s;
break;
case "se":
positionOrder = this.settings.config.order.se;
break;
default:
positionOrder = this.settings.config.order.items;
break;
}
let el = positionOrder.find(e => e.id === id);
if (el) {
let sorted = positionOrder.sort((a, b) => a.order - b.order);
let last = sorted[sorted.length - 1].order;
return el.order === last;
} else {
return false;
}
}
public saveAll() {
this.echo('Saving all data', '', this.settings.config, "save");
this.settings.setAll(this.settings.config.bookmark, 'ct-bookmark');
this.settings.setAll(this.settings.config.date, 'ct-date');
this.settings.setAll(this.settings.config.design, 'ct-design');
this.settings.setAll(this.settings.config.i18n, 'ct-i18n');
this.settings.setAll(this.settings.config.messages, 'ct-message');
this.settings.setAll(this.settings.config.misc, 'ct-misc');
this.settings.setAll(this.settings.config.covidData, 'ct-covid');
this.settings.setAll(this.settings.config.order, 'ct-order');
this.settings.setAll(this.settings.config.quickLink, 'ct-quick-link');
this.settings.setAll(this.settings.config.search, 'ct-search');
this.settings.setAll(this.settings.config.time, 'ct-time');
this.settings.setAll(this.settings.config.weather, 'ct-weather');
}
public getRandomNumber(min,max): number {
return Math.floor(Math.random() * (max - min)) + min;
};
}
@Pipe({ name: 'translateCut' })
export class TranslateCut implements PipeTransform {
transform(value: string, index: string): string {
const cutIndex = Number(index);
return value.split('|')[cutIndex];
}
} | the_stack |
import {
SchematicContext,
Tree,
externalSchematic,
SchematicsException,
} from '@angular-devkit/schematics';
import { FrameworkTypes } from '@nstudio/xplat-utils';
export { getFileContent } from '@nrwl/workspace/testing';
export function createEmptyWorkspace(
tree: Tree,
framework?: FrameworkTypes
): Tree {
tree.create('/.gitignore', '');
tree.create(
'/angular.json',
JSON.stringify({ version: 1, projects: {}, newProjectRoot: '' })
);
const xplatSettings: any = {
prefix: 'tt',
};
if (framework) {
xplatSettings.framework = framework;
}
tree.create(
'/package.json',
JSON.stringify({
dependencies: {},
devDependencies: {},
xplat: xplatSettings,
})
);
tree.create(
'/nx.json',
JSON.stringify(<any>{ npmScope: 'testing', projects: {} })
);
tree.create(
'/tsconfig.base.json',
JSON.stringify({ compilerOptions: { paths: {} } })
);
tree.create(
'/tslint.json',
JSON.stringify({
rules: {
'nx-enforce-module-boundaries': [
true,
{
npmScope: '<%= npmScope %>',
lazyLoad: [],
allow: [],
},
],
},
})
);
return tree;
}
export function createXplatWithAppsForElectron(tree: Tree): Tree {
tree = createXplatWithApps(tree);
tree.overwrite(
'angular.json',
JSON.stringify({
version: 1,
projects: {
'web-viewer': {
targets: {
build: {
options: {
assets: [],
},
},
serve: {
options: {},
configurations: {
production: {},
},
},
},
},
},
})
);
tree.overwrite(
'/nx.json',
JSON.stringify({
npmScope: 'testing',
projects: {
'web-viewer': {
tags: [],
},
},
})
);
tree.create(
'/tools/tsconfig.tools.json',
JSON.stringify({
extends: '../tsconfig.json',
})
);
return tree;
}
export function createXplatWithApps(
tree: Tree,
framework?: FrameworkTypes
): Tree {
tree = createEmptyWorkspace(tree, framework);
createXplatLibs(tree);
createXplatWebAngular(tree, framework);
createWebAngularApp(tree);
return tree;
}
export function createXplatWithNativeScriptWeb(
tree: Tree,
withRouting?: boolean,
framework?: FrameworkTypes,
withNxLibName?: string
): Tree {
tree = createEmptyWorkspace(tree, framework);
createXplatLibs(tree);
createXplatNativeScriptAngular(tree, framework);
createXplatWebAngular(tree, framework);
createNativeScriptAngularApp(tree, withRouting);
createWebAngularApp(tree, withRouting);
if (withNxLibName) {
// also create a standard Nx library
createNxLib(tree, withNxLibName);
}
return tree;
}
export function createNxLib(tree: Tree, name: string) {
tree.create(`/libs/${name}/src/lib/index.ts`, '');
tree.create(
`/libs/${name}/src/lib/${name}.module.ts`,
`import {
NgModule
} from '@angular/core';
import { APP_BASE_HREF, CommonModule } from '@angular/common';
@NgModule({
imports: [CommonModule]
})
export class ${name}Module {}`
);
const configPaths = {};
configPaths[`@testing/${name}`] = [`libs/${name}/src/index.ts`];
tree.overwrite(
'/tsconfig.base.json',
JSON.stringify({ compilerOptions: { paths: configPaths } })
);
}
export function createXplatLibs(tree: Tree) {
tree.create('/libs/xplat/core/src/lib/index.ts', '');
tree.create(
'/libs/xplat/core/src/lib/core.module.ts',
`import {
NgModule
} from '@angular/core';
import { APP_BASE_HREF, CommonModule } from '@angular/common';
export const BASE_PROVIDERS: any[] = [
{
provide: APP_BASE_HREF,
useValue: '/'
}
];
@NgModule({
imports: [CommonModule]
})
export class CoreModule {}`
);
tree.create(
'/libs/xplat/core/src/lib/services/index.ts',
`export * from './log.service';
export * from './window.service';
export * from './tokens';
`
);
tree.create('/libs/xplat/features/src/lib/index.ts', '');
tree.create(
'/libs/xplat/features/src/lib/ui/ui.module.ts',
`import { NgModule } from '@angular/core';
import { TranslateModule } from '@ngx-translate/core';
import { UI_PIPES } from './pipes';
const MODULES = [TranslateModule];
@NgModule({
imports: [...MODULES],
declarations: [...UI_PIPES],
exports: [...MODULES, ...UI_PIPES]
})
export class UISharedModule {}
`
);
tree.create('/libs/xplat/utils/src/lib/index.ts', '');
}
export function createXplatNativeScriptAngular(
tree: Tree,
framework?: FrameworkTypes
) {
const frameworkSuffix = framework === 'angular' ? '' : '-angular';
// tree.create(`/libs/xplat/nativescript${frameworkSuffix}/index.ts`, '');
// tree.create(`/libs/xplat/nativescript${frameworkSuffix}/package.json`, '');
tree.create(
`/libs/xplat/nativescript${frameworkSuffix}/core/src/lib/index.ts`,
''
);
tree.create(
`/libs/xplat/nativescript${frameworkSuffix}/core/src/lib/core.module.ts`,
`import { NgModule, Optional, SkipSelf } from '@angular/core';
// nativescript
import { NativeScriptModule, NativeScriptHttpClientModule } from '@nativescript/angular';
import { Device } from '@nativescript/core';
import { TNSFontIconModule } from 'nativescript-ngx-fonticon';
// libs
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { CoreModule, PlatformLanguageToken, PlatformWindowToken } from '@<%= npmScope %>/xplat/core';
import { throwIfAlreadyLoaded } from '@<%= npmScope %>/xplat/utils';
// app
import { MobileWindowService } from './services/mobile-window.service';
import { MobileTranslateLoader } from './services/mobile-translate.loader';
// factories
export function platformLangFactory() {
return Device.language;
}
export function createTranslateLoader() {
return new MobileTranslateLoader('/assets/i18n/');
}
@NgModule({
imports: [
NativeScriptModule,
NativeScriptHttpClientModule,
TNSFontIconModule.forRoot({
fa: './assets/fontawesome.min.css'
}),
CoreModule.forRoot([
{
provide: PlatformLanguageToken,
useFactory: platformLangFactory
},
{
provide: PlatformWindowToken,
useClass: MobileWindowService
}
]),
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: createTranslateLoader
}
}),
]
})
export class TTCoreModule {
constructor(
@Optional()
@SkipSelf()
parentModule: TTCoreModule
) {
throwIfAlreadyLoaded(parentModule, 'TTCoreModule');
}
}
`
);
tree.create(
`/libs/xplat/nativescript${frameworkSuffix}/core/src/lib/services/index.ts`,
`export * from './app.service';`
);
tree.create(
`/libs/xplat/nativescript${frameworkSuffix}/features/src/lib/ui/index.ts`,
''
);
tree.create(
`/libs/xplat/nativescript${frameworkSuffix}/features/src/lib/ui/ui.module.ts`,
`import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';
import { NativeScriptCommonModule, NativeScriptFormsModule, NativeScriptRouterModule } from '@nativescript/angular';
import { TNSFontIconModule } from 'nativescript-ngx-fonticon';
import { UISharedModule } from '@<%= npmScope %>/xplat/features';
import { UI_COMPONENTS } from './components';
const MODULES = [
NativeScriptCommonModule,
NativeScriptFormsModule,
NativeScriptRouterModule,
TNSFontIconModule,
UISharedModule
];
@NgModule({
imports: [...MODULES],
declarations: [...UI_COMPONENTS],
exports: [...MODULES, ...UI_COMPONENTS],
schemas: [NO_ERRORS_SCHEMA]
})
export class UIModule {}
`
);
tree.create(
`/libs/xplat/nativescript${frameworkSuffix}/features/src/lib/index.ts`,
''
);
tree.create(
`/libs/xplat/nativescript${frameworkSuffix}/scss/src/_variables.scss`,
''
);
tree.create(
`/libs/xplat/nativescript${frameworkSuffix}/utils/src/lib/index.ts`,
``
);
}
export function createXplatWebAngular(tree: Tree, framework?: FrameworkTypes) {
const frameworkSuffix = framework === 'angular' ? '' : '-angular';
// tree.create(`/libs/xplat/web${frameworkSuffix}/index.ts`, '');
// tree.create(`/libs/xplat/web${frameworkSuffix}/package.json`, '');
tree.create(`/libs/xplat/web${frameworkSuffix}/core/src/lib/index.ts`, '');
tree.create(
`/libs/xplat/web${frameworkSuffix}/features/src/lib/ui/index.ts`,
''
);
tree.create(
`/libs/xplat/web${frameworkSuffix}/features/src/lib/ui/ui.module.ts`,
`import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';
// libs
import { UISharedModule } from '@<%= npmScope %>/xplat/features';
import { UI_COMPONENTS } from './components';
const MODULES = [
CommonModule,
RouterModule,
FormsModule,
ReactiveFormsModule,
UISharedModule
];
@NgModule({
imports: [...MODULES],
declarations: [...UI_COMPONENTS],
exports: [...MODULES, ...UI_COMPONENTS]
})
export class UIModule {}
`
);
tree.create(
`/libs/xplat/web${frameworkSuffix}/features/src/lib/index.ts`,
''
);
tree.create(`/libs/xplat/web${frameworkSuffix}/scss/src/_variables.scss`, '');
}
export function createWebAngularApp(tree: Tree, withRouting?: boolean) {
tree.create('/apps/web-viewer/src/index.html', '');
tree.create('/apps/web-viewer/src/app/features/index.ts', '');
tree.create('/apps/web-viewer/src/app/features/core/core.module.ts', '');
tree.create('/apps/web-viewer/src/app/app.module.ts', '');
if (withRouting) {
tree.create(
`/apps/web-viewer/src/app/features/home/components/home.component.html`,
''
);
tree.create(
'/apps/web-viewer/src/app/app.routing.ts',
`// angular
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
// app
import { SharedModule } from './features/shared/shared.module';
const routes: Routes = [
{
path: '',
redirectTo: '/home',
pathMatch: 'full'
},
{
path: 'home',
loadChildren: () =>
import('./features/home/home.module').then(m => m.HomeModule)
}
];
@NgModule({
imports: [SharedModule, RouterModule.forRoot(routes)]
})
export class AppRoutingModule {}
`
);
}
}
export function createNativeScriptAngularApp(
tree: Tree,
withRouting?: boolean
) {
tree.create('/apps/nativescript-viewer/package.json', '');
tree.create('/apps/nativescript-viewer/tsconfig.json', '');
tree.create('/apps/nativescript-viewer/src/core/core.module.ts', '');
tree.create(
'/apps/nativescript-viewer/src/features/shared/shared.module.ts',
''
);
tree.create('/apps/nativescript-viewer/src/scss/_index.scss', '');
tree.create('/apps/nativescript-viewer/src/app.module.ts', '');
tree.create('/apps/nativescript-viewer/src/main.ts', '');
if (withRouting) {
tree.create(
`/apps/nativescript-viewer/src/features/home/components/home.component.html`,
''
);
tree.create(
'/apps/nativescript-viewer/src/app.routing.ts',
`// angular
import { NgModule } from '@angular/core';
import { Routes } from '@angular/router';
// nativescript
import { NativeScriptRouterModule } from '@nativescript/angular';
// app
import { SharedModule } from './features/shared/shared.module';
const routes: Routes = [
{
path: '',
redirectTo: '/home',
pathMatch: 'full'
},
{
path: 'home',
loadChildren: () =>
import('./features/home/home.module').then(m => m.HomeModule)
}
];
@NgModule({
imports: [SharedModule, NativeScriptRouterModule.forRoot(routes)]
})
export class AppRoutingModule {}
`
);
}
}
export const isInModuleMetadata = (
moduleName: string,
property: string,
value: string,
inArray: boolean
) => isInDecoratorMetadata(moduleName, property, value, 'NgModule', inArray);
export const isInComponentMetadata = (
componentName: string,
property: string,
value: string,
inArray: boolean
) =>
isInDecoratorMetadata(componentName, property, value, 'Component', inArray);
export const isInDecoratorMetadata = (
moduleName: string,
property: string,
value: string,
decoratorName: string,
inArray: boolean
) =>
new RegExp(
`@${decoratorName}\\(\\{([^}]*)` +
objectContaining(property, value, inArray) +
'[^}]*\\}\\)' +
'\\s*' +
`(export )?class ${moduleName}`
);
const objectContaining = (property: string, value: string, inArray: boolean) =>
inArray ? keyValueInArray(property, value) : keyValueString(property, value);
const keyValueInArray = (property: string, value: string) =>
`${property}: \\[` +
nonLastValueInArrayMatcher +
`${value},?` +
nonLastValueInArrayMatcher +
lastValueInArrayMatcher +
`\\s*]`;
const nonLastValueInArrayMatcher = `(\\s*|(\\s*(\\w+,)*)\\s*)*`;
const lastValueInArrayMatcher = `(\\s*|(\\s*(\\w+)*)\\s*)?`;
const keyValueString = (property: string, value: string) =>
`${property}: ${value}`; | the_stack |
import * as utils from "./utilities/utils";
describe("convert schema xml string to ts", () => {
const testCases: utils.SchemaTestCase[] = [
// Test Case: Class with long description
{
testName: `Class with long description`,
referenceXmls: [],
schemaXml: `<?xml version="1.0" encoding="utf-8"?>
<ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2">
<ECEntityClass typeName="EntityTest"
description="This is a long description for a class. This is a long description for a class. This is a long description for a class. This is a long description for a class."
modifier="None">
<ECProperty propertyName="booleanProps" typeName="boolean"/>
<ECProperty propertyName="stringProps" typeName="string"/>
</ECEntityClass>
</ECSchema>`,
expectedSchemaImportTs: utils.createExpectedSchemaImportTs("TestSchema"),
expectedSchemaTs: utils.createExpectedSchemaTsString("TestSchema"),
expectedPropsImportTs: [ new RegExp(`import { EntityProps } from "@itwin/core-common";`) ],
expectedPropsTs: [utils.dedent`
export interface EntityTestProps extends EntityProps {
booleanProps?: boolean;
stringProps?: string;
}`,
],
expectedElemImportTs: [
new RegExp(`import { (?=.*\\b(Entity)\\b)(?=.*\\b(IModelDb)\\b).* } from "@itwin/core-backend";`),
new RegExp(`import { EntityTestProps } from "./TestSchemaElementProps";`),
],
expectedElemTs: [utils.dedent`
/**
* This is a long description for a class. This is a long description for a class. This is a long
* description for a class. This is a long description for a class.
*/
export class EntityTest extends Entity implements EntityTestProps {
public static get className(): string { return "EntityTest"; }
public constructor (props: EntityTestProps, iModel: IModelDb) {
super(props, iModel);
}
}`,
],
},
// Test Case: Entity class with only primitive properties
{
testName: `Entity class with only primitive properties`,
referenceXmls: [],
schemaXml: `<?xml version="1.0" encoding="utf-8"?>
<ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2">
<ECEntityClass typeName="EntityTest" description="Instantiable" modifier="None">
<ECProperty propertyName="booleanProps" typeName="boolean"/>
<ECProperty propertyName="stringProps" typeName="string"/>
<ECProperty propertyName="binaryProps" typeName="binary"/>
<ECProperty propertyName="intProps" typeName="int"/>
<ECProperty propertyName="doubleProps" typeName="double"/>
<ECProperty propertyName="longProps" typeName="long"/>
<ECProperty propertyName="point2DProps" typeName="point2d"/>
<ECProperty propertyName="point3DProps" typeName="point3d"/>
</ECEntityClass>
</ECSchema>`,
expectedSchemaImportTs: utils.createExpectedSchemaImportTs("TestSchema"),
expectedSchemaTs: utils.createExpectedSchemaTsString("TestSchema"),
expectedPropsImportTs: [
new RegExp(`import { EntityProps } from "@itwin/core-common";`),
new RegExp(`import { (?=.*\\b(Point2d)\\b)(?=.*\\b(Point3d)\\b).* } from "@itwin/core-geometry";`),
],
expectedPropsTs: [utils.dedent`
export interface EntityTestProps extends EntityProps {
booleanProps?: boolean;
stringProps?: string;
binaryProps?: any;
intProps?: number;
doubleProps?: number;
longProps?: any;
point2DProps?: Point2d;
point3DProps?: Point3d;
}`,
],
expectedElemImportTs: [
new RegExp(`import { (?=.*\\b(Entity)\\b)(?=.*\\b(IModelDb)\\b).* } from "@itwin/core-backend";`),
new RegExp(`import { EntityTestProps } from "./TestSchemaElementProps";`),
],
expectedElemTs: [utils.dedent`
export class EntityTest extends Entity implements EntityTestProps {
public static get className(): string { return "EntityTest"; }
public constructor (props: EntityTestProps, iModel: IModelDb) {
super(props, iModel);
}
}`,
],
},
// Test Case: Struct class with only primitive properties
{
testName: `struct class with only primitive properties`,
referenceXmls: [],
schemaXml: `<?xml version="1.0" encoding="utf-8"?>
<ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2">
<ECStructClass typeName="StructTest" description="struct" modifier="None">
<ECProperty propertyName="booleanProps" typeName="boolean"/>
<ECProperty propertyName="stringProps" typeName="string"/>
<ECProperty propertyName="binaryProps" typeName="binary"/>
<ECProperty propertyName="point2DProps" typeName="point2d"/>
<ECProperty propertyName="point3DProps" typeName="point3d"/>
</ECStructClass>
</ECSchema>`,
expectedSchemaImportTs: utils.createExpectedSchemaImportTs("TestSchema"),
expectedSchemaTs: utils.createExpectedSchemaTsString("TestSchema"),
expectedPropsImportTs: [ new RegExp(`import { (?=.*\\b(Point2d)\\b)(?=.*\\b(Point3d)\\b).* } from "@itwin/core-geometry";`) ],
expectedPropsTs: [utils.dedent`
export interface StructTest {
booleanProps?: boolean;
stringProps?: string;
binaryProps?: any;
point2DProps?: Point2d;
point3DProps?: Point3d;
}`,
],
expectedElemImportTs: [],
expectedElemTs: [],
},
// Test Case: Mixin with only primitive properties
{
testName: `Mixin class with only primitive properties`,
referenceXmls: [],
schemaXml: `<?xml version="1.0" encoding="utf-8"?>
<ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2">
<ECSchemaReference name="CoreCustomAttributes" version="01.00.00" alias="CoreCA"/>
<ECEntityClass typeName="MixinTest" description="mixin" modifier="None">
<ECCustomAttributes>
<IsMixin xmlns="CoreCustomAttributes.01.00.00">
<AppliesToEntityClass>BaseEntity</AppliesToEntityClass>
</IsMixin>
</ECCustomAttributes>
<ECProperty propertyName="booleanProps" typeName="boolean"/>
<ECProperty propertyName="stringProps" typeName="string"/>
<ECProperty propertyName="binaryProps" typeName="binary"/>
<ECProperty propertyName="doubleProps" typeName="double"/>
</ECEntityClass>
<ECEntityClass typeName="BaseEntity" modifier="None">
</ECEntityClass>
</ECSchema>`,
expectedSchemaImportTs: utils.createExpectedSchemaImportTs("TestSchema"),
expectedSchemaTs: utils.createExpectedSchemaTsString("TestSchema"),
expectedPropsImportTs: [],
expectedPropsTs: [utils.dedent`
export interface MixinTest {
booleanProps?: boolean;
stringProps?: string;
binaryProps?: any;
doubleProps?: number;
}`,
],
expectedElemImportTs: [
new RegExp(`import { (?=.*\\b(Entity)\\b)(?=.*\\b(IModelDb)\\b).* } from "@itwin/core-backend";`),
],
expectedElemTs: [utils.dedent`
export class BaseEntity extends Entity {
public static get className(): string { return "BaseEntity"; }
public constructor (props: EntityProps, iModel: IModelDb) {
super(props, iModel);
}
}`,
],
},
// Test Case: Enumeration
{
testName: `convert Enumeration to Ts`,
referenceXmls: [],
schemaXml: `<?xml version="1.0" encoding="utf-8"?>
<ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2">
<ECEnumeration typeName="IntEnumeration" backingTypeName="int" description="Int Enumeration" displayLabel="This is a display label." isStrict="true">
<ECEnumerator name="IntEnumeration1" value="1" displayLabel="First"/>
<ECEnumerator name="IntEnumeration2" value="2" displayLabel="Second"/>
<ECEnumerator name="IntEnumeration3" value="3" displayLabel="Third"/>
</ECEnumeration>
<ECEnumeration typeName="StringEnumeration" backingTypeName="string" description="String Enumeration" isStrict="true">
<ECEnumerator name="spring" value="spring" displayLabel="FirstSeason"/>
<ECEnumerator name="summer" value="summer" displayLabel="SecondSeason"/>
<ECEnumerator name="fall" value="fall" displayLabel="ThirdSeason"/>
<ECEnumerator name="winter" value="winter" displayLabel="FourthSeason"/>
</ECEnumeration>
<ECEntityClass typeName="BaseEntity" modifier="None">
<ECProperty propertyName="intEnumProps" typeName="IntEnumeration"/>
<ECProperty propertyName="stringEnumProps" typeName="StringEnumeration"/>
</ECEntityClass>
</ECSchema>`,
expectedSchemaImportTs: utils.createExpectedSchemaImportTs("TestSchema"),
expectedSchemaTs: utils.createExpectedSchemaTsString("TestSchema"),
expectedPropsImportTs: [
new RegExp(`import { (?=.*\\b(IntEnumeration)\\b)(?=.*\\b(StringEnumeration)\\b).* } from "./TestSchemaElements";`),
new RegExp(`import { EntityProps } from "@itwin/core-common";`),
],
expectedPropsTs: [utils.dedent`
export interface BaseEntityProps extends EntityProps {
intEnumProps?: IntEnumeration;
stringEnumProps?: StringEnumeration;
}`,
],
expectedElemImportTs: [
new RegExp(`import { (?=.*\\b(Entity)\\b)(?=.*\\b(IModelDb)\\b).* } from "@itwin/core-backend";`),
new RegExp(`import { BaseEntityProps } from "./TestSchemaElementProps";`),
],
expectedElemTs: [utils.dedent`
export const enum IntEnumeration {
First = 1,
Second = 2,
Third = 3,
}`, utils.dedent`
export const enum StringEnumeration {
FirstSeason = "spring",
SecondSeason = "summer",
ThirdSeason = "fall",
FourthSeason = "winter",
}`, utils.dedent`
export class BaseEntity extends Entity implements BaseEntityProps {
public static get className(): string { return "BaseEntity"; }
public constructor (props: BaseEntityProps, iModel: IModelDb) {
super(props, iModel);
}
}`,
],
},
// Test Case: Entity class with struct, enumeration, primitive and struct array properties
{
testName: `convert Entity class derived from another entity class to Ts`,
referenceXmls: [],
schemaXml: `<?xml version="1.0" encoding="utf-8"?>
<ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2">
<ECEntityClass typeName="EntityTest" modifier="None">
<ECStructProperty propertyName="structProps" typeName="StructTest"/>
<ECProperty propertyName="intEnumProps" typeName="IntEnumeration"/>
<ECProperty propertyName="stringEnumProps" typeName="StringEnumeration"/>
<ECArrayProperty propertyName="stringArrayProps" typeName="string" minOccurs="0" maxOccurs="unbounded"/>
<ECStructArrayProperty propertyName="structArrayProps" typeName="StructTest" minOccurs="0" maxOccurs="unbounded"/>
</ECEntityClass>
<ECStructClass typeName="StructTest" description="struct" modifier="None">
<ECProperty propertyName="booleanProps" typeName="boolean"/>
<ECProperty propertyName="stringProps" typeName="string"/>
<ECProperty propertyName="binaryProps" typeName="binary"/>
<ECProperty propertyName="point2DProps" typeName="point2d"/>
<ECProperty propertyName="point3DProps" typeName="point3d"/>
</ECStructClass>
<ECEnumeration typeName="IntEnumeration" backingTypeName="int" description="Int Enumeration" displayLabel="This is a display label." isStrict="true">
<ECEnumerator name="IntEnumeration1" value="1" displayLabel="First"/>
<ECEnumerator name="IntEnumeration2" value="2" displayLabel="Second"/>
<ECEnumerator name="IntEnumeration3" value="3" displayLabel="Third"/>
</ECEnumeration>
<ECEnumeration typeName="StringEnumeration" backingTypeName="string" description="String Enumeration" isStrict="true">
<ECEnumerator name="spring" value="spring" displayLabel="FirstSeason"/>
<ECEnumerator name="summer" value="summer" displayLabel="SecondSeason"/>
<ECEnumerator name="fall" value="fall" displayLabel="ThirdSeason"/>
<ECEnumerator name="winter" value="winter" displayLabel="FourthSeason"/>
</ECEnumeration>
</ECSchema>`,
expectedSchemaImportTs: utils.createExpectedSchemaImportTs("TestSchema"),
expectedSchemaTs: utils.createExpectedSchemaTsString("TestSchema"),
expectedPropsImportTs: [
new RegExp(`import { (?=.*\\b(EntityProps)\\b).* } from "@itwin/core-common";`),
new RegExp(`import { (?=.*\\b(Point2d)\\b)(?=.*\\b(Point3d)\\b).* } from "@itwin/core-geometry";`),
new RegExp(`import { (?=.*\\b(IntEnumeration)\\b)(?=.*\\b(StringEnumeration)\\b).* } from "./TestSchemaElements";`),
],
expectedPropsTs: [utils.dedent`
export interface StructTest {
booleanProps?: boolean;
stringProps?: string;
binaryProps?: any;
point2DProps?: Point2d;
point3DProps?: Point3d;
}`, utils.dedent`
export interface EntityTestProps extends EntityProps {
structProps?: StructTest;
intEnumProps?: IntEnumeration;
stringEnumProps?: StringEnumeration;
stringArrayProps?: string[];
structArrayProps?: StructTest[];
}`,
],
expectedElemImportTs: [
new RegExp(`import { (?=.*\\b(Entity)\\b)(?=.*\\b(IModelDb)\\b).* } from "@itwin/core-backend";`),
new RegExp(`import { (?=.*\\b(EntityTestProps)\\b).* } from "./TestSchemaElementProps";`),
],
expectedElemTs: [utils.dedent`
export const enum IntEnumeration {
First = 1,
Second = 2,
Third = 3,
}`, utils.dedent`
export const enum StringEnumeration {
FirstSeason = "spring",
SecondSeason = "summer",
ThirdSeason = "fall",
FourthSeason = "winter",
}`, utils.dedent`
export class EntityTest extends Entity implements EntityTestProps {
public static get className(): string { return "EntityTest"; }
public constructor (props: EntityTestProps, iModel: IModelDb) {
super(props, iModel);
}
}`,
],
},
// Test Case: Entity class derived from another entity class (only one inheritance)
{
testName: `convert Entity class derived from another entity class to Ts`,
referenceXmls: [],
schemaXml: `<?xml version="1.0" encoding="utf-8"?>
<ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2">
<ECEntityClass typeName="DerivedEntityTest" modifier="None">
<BaseClass>BaseEntityTest</BaseClass>
<ECProperty propertyName="derivedIntProps" typeName="int"/>
</ECEntityClass>
<ECEntityClass typeName="BaseEntityTest" modifier="None">
<ECProperty propertyName="intProps" typeName="int"/>
<ECProperty propertyName="stringProps" typeName="string"/>
</ECEntityClass>
</ECSchema>`,
expectedSchemaImportTs: utils.createExpectedSchemaImportTs("TestSchema"),
expectedSchemaTs: utils.createExpectedSchemaTsString("TestSchema"),
expectedPropsImportTs: [
new RegExp(`import { EntityProps } from "@itwin/core-common";`),
],
expectedPropsTs: [utils.dedent`
export interface BaseEntityTestProps extends EntityProps {
intProps?: number;
stringProps?: string;
}`, utils.dedent`
export interface DerivedEntityTestProps extends BaseEntityTestProps {
derivedIntProps?: number;
}`,
],
expectedElemImportTs: [
new RegExp(`import { (?=.*\\b(Entity)\\b)(?=.*\\b(IModelDb)\\b).* } from "@itwin/core-backend";`),
new RegExp(`import { (?=.*\\b(DerivedEntityTestProps)\\b)(?=.*\\b(BaseEntityTestProps)\\b).* } from "./TestSchemaElementProps";`),
],
expectedElemTs: [utils.dedent`
export class BaseEntityTest extends Entity implements BaseEntityTestProps {
public static get className(): string { return "BaseEntityTest"; }
public constructor (props: BaseEntityTestProps, iModel: IModelDb) {
super(props, iModel);
}
}`, utils.dedent`
export class DerivedEntityTest extends BaseEntityTest implements DerivedEntityTestProps {
public static get className(): string { return "DerivedEntityTest"; }
public constructor (props: DerivedEntityTestProps, iModel: IModelDb) {
super(props, iModel);
}
}`,
],
},
// Test Case: convert Entity class derived from another entity and mixin to ts
{
testName: `convert Entity class derived from another entity class and mixin to Ts`,
referenceXmls: [],
schemaXml: `<?xml version="1.0" encoding="utf-8"?>
<ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2">
<ECEntityClass typeName="DerivedEntityTest" modifier="None">
<BaseClass>BaseEntityTest</BaseClass>
<BaseClass>MixinTest</BaseClass>
<BaseClass>DerivedMixinTest</BaseClass>
<ECProperty propertyName="derivedIntProps" typeName="int"/>
</ECEntityClass>
<ECEntityClass typeName="BaseEntityTest" modifier="None">
<ECProperty propertyName="intProps" typeName="int"/>
<ECProperty propertyName="stringProps" typeName="string"/>
</ECEntityClass>
<ECEntityClass typeName="DerivedMixinTest" description="derived mixin" modifier="None">
<ECCustomAttributes>
<IsMixin xmlns="CoreCustomAttributes.01.00.00">
<AppliesToEntityClass>DerivedEntityTest</AppliesToEntityClass>
</IsMixin>
</ECCustomAttributes>
<BaseClass>MixinTest</BaseClass>
<ECProperty propertyName="binaryProps" typeName="binary"/>
<ECProperty propertyName="doubleProps" typeName="double"/>
</ECEntityClass>
<ECEntityClass typeName="MixinTest" description="mixin" modifier="None">
<ECCustomAttributes>
<IsMixin xmlns="CoreCustomAttributes.01.00.00">
<AppliesToEntityClass>DerivedEntityTest</AppliesToEntityClass>
</IsMixin>
</ECCustomAttributes>
<ECProperty propertyName="booleanProps" typeName="boolean"/>
<ECProperty propertyName="stringProps" typeName="string"/>
<ECProperty propertyName="binaryProps" typeName="binary"/>
<ECProperty propertyName="doubleProps" typeName="double"/>
</ECEntityClass>
</ECSchema>`,
expectedSchemaImportTs: utils.createExpectedSchemaImportTs("TestSchema"),
expectedSchemaTs: utils.createExpectedSchemaTsString("TestSchema"),
expectedPropsImportTs: [
new RegExp(`import { EntityProps } from "@itwin/core-common";`),
],
expectedPropsTs: [utils.dedent`
export interface MixinTest {
booleanProps?: boolean;
stringProps?: string;
binaryProps?: any;
doubleProps?: number;
}`, utils.dedent`
export interface DerivedMixinTest extends MixinTest {
binaryProps?: any;
doubleProps?: number;
}`, utils.dedent`
export interface BaseEntityTestProps extends EntityProps {
intProps?: number;
stringProps?: string;
}`, utils.dedent`
export interface DerivedEntityTestProps extends BaseEntityTestProps, MixinTest, DerivedMixinTest {
derivedIntProps?: number;
}`,
],
expectedElemImportTs: [
new RegExp(`import { (?=.*\\b(Entity)\\b)(?=.*\\b(IModelDb)\\b).* } from "@itwin/core-backend";`),
new RegExp(`import { (?=.*\\b(DerivedEntityTestProps)\\b)(?=.*\\b(BaseEntityTestProps)\\b).* } from "./TestSchemaElementProps";`),
],
expectedElemTs: [utils.dedent`
export class BaseEntityTest extends Entity implements BaseEntityTestProps {
public static get className(): string { return "BaseEntityTest"; }
public constructor (props: BaseEntityTestProps, iModel: IModelDb) {
super(props, iModel);
}
}`, utils.dedent`
export class DerivedEntityTest extends BaseEntityTest implements DerivedEntityTestProps {
public static get className(): string { return "DerivedEntityTest"; }
public constructor (props: DerivedEntityTestProps, iModel: IModelDb) {
super(props, iModel);
}
}`,
],
},
// Test Case: convert Struct class derived from another struct to Ts
{
testName: `convert struct class derived from another struct class to Ts`,
referenceXmls: [],
schemaXml: `<?xml version="1.0" encoding="utf-8"?>
<ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2">
<ECStructClass typeName="DerivedStructTest" description="derived struct" modifier="None">
<BaseClass>StructTest</BaseClass>
<ECProperty propertyName="derivedIntProps" typeName="int"/>
</ECStructClass>
<ECStructClass typeName="StructTest" description="struct" modifier="None">
<ECProperty propertyName="booleanProps" typeName="boolean"/>
<ECProperty propertyName="stringProps" typeName="string"/>
<ECProperty propertyName="binaryProps" typeName="binary"/>
<ECProperty propertyName="point2DProps" typeName="point2d"/>
<ECProperty propertyName="point3DProps" typeName="point3d"/>
</ECStructClass>
</ECSchema>`,
expectedSchemaImportTs: utils.createExpectedSchemaImportTs("TestSchema"),
expectedSchemaTs: utils.createExpectedSchemaTsString("TestSchema"),
expectedPropsImportTs: [
new RegExp(`import { (?=.*\\b(Point2d)\\b)(?=.*\\b(Point3d)\\b).* } from "@itwin/core-geometry";`),
],
expectedPropsTs: [utils.dedent`
export interface StructTest {
booleanProps?: boolean;
stringProps?: string;
binaryProps?: any;
point2DProps?: Point2d;
point3DProps?: Point3d;
}`, utils.dedent`
export interface DerivedStructTest extends StructTest {
derivedIntProps?: number;
}`,
],
expectedElemImportTs: [],
expectedElemTs: [],
},
// Test Case: Entity class derived from one of the class in the BisCore
{
testName: `convert entity class derived from one of the class in BisCore to Ts`,
referenceXmls: [],
schemaXml: `<?xml version="1.0" encoding="utf-8"?>
<ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2">
<ECSchemaReference name="CoreCustomAttributes" version="01.00.00" alias="CoreCA"/>
<ECSchemaReference name="BisCore" version="01.00.00" alias="bis"/>
<ECEntityClass typeName="DerivedGeometricElement2d" modifier="None">
<BaseClass>bis:GeometricElement2d</BaseClass>
<ECProperty propertyName="intProps" typeName="int"/>
<ECProperty propertyName="doubleProps" typeName="double"/>
</ECEntityClass>
<ECEntityClass typeName="DerivedElement" modifier="None">
<BaseClass>bis:Element</BaseClass>
<ECProperty propertyName="intProps" typeName="int"/>
</ECEntityClass>
<ECEntityClass typeName="DerivedAnnotationElement2d" modifier="None">
<BaseClass>bis:AnnotationElement2d</BaseClass>
</ECEntityClass>
</ECSchema>`,
expectedSchemaImportTs: utils.createExpectedSchemaImportTs("TestSchema"),
expectedSchemaTs: utils.createExpectedSchemaTsString("TestSchema"),
expectedPropsImportTs: [
new RegExp(`import { (?=.*\\b(GeometricElement2dProps)\\b)(?=.*\\b(ElementProps)\\b).* } from "@itwin/core-common";`),
],
expectedPropsTs: [utils.dedent`
export interface DerivedGeometricElement2dProps extends GeometricElement2dProps {
intProps?: number;
doubleProps?: number;
}`, utils.dedent`
export interface DerivedElementProps extends ElementProps {
intProps?: number;
}`,
],
expectedElemImportTs: [
new RegExp(`import { (?=.*\\b(IModelDb)\\b)(?=.*\\b(Element)\\b)(?=.*\\b(AnnotationElement2d)\\b)(?=.*\\b(GeometricElement2d)\\b).* } from "@itwin/core-backend";`),
new RegExp(`import { (?=.*\\b(GeometricElement2dProps)\\b).* } from "@itwin/core-common";`),
new RegExp(`import { (?=.*\\b(DerivedGeometricElement2dProps)\\b)(?=.*\\b(DerivedElementProps)\\b).* } from "./TestSchemaElementProps";`),
],
expectedElemTs: [utils.dedent`
export class DerivedGeometricElement2d extends GeometricElement2d implements DerivedGeometricElement2dProps {
public static get className(): string { return "DerivedGeometricElement2d"; }
public constructor (props: DerivedGeometricElement2dProps, iModel: IModelDb) {
super(props, iModel);
}
}`, utils.dedent`
export class DerivedElement extends Element implements DerivedElementProps {
public static get className(): string { return "DerivedElement"; }
public constructor (props: DerivedElementProps, iModel: IModelDb) {
super(props, iModel);
}
}`, utils.dedent`
export class DerivedAnnotationElement2d extends AnnotationElement2d {
public static get className(): string { return "DerivedAnnotationElement2d"; }
public constructor (props: GeometricElement2dProps, iModel: IModelDb) {
super(props, iModel);
}
}`,
],
},
// Test Case: Entity class has no properties
{
testName: `convert entity class has no properties to Ts`,
referenceXmls: [],
schemaXml: `<?xml version="1.0" encoding="utf-8"?>
<ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2">
<ECSchemaReference name="CoreCustomAttributes" version="01.00.00" alias="CoreCA"/>
<ECSchemaReference name="BisCore" version="01.00.00" alias="bis"/>
<ECEntityClass typeName="DerivedElementTest" description="Derived Element Test class" modifier="None">
<BaseClass>bis:Element</BaseClass>
</ECEntityClass>
<ECEntityClass typeName="DerivedEntityTest" description="Derived Entity Test class" modifier="None">
<BaseClass>BaseEntityTest</BaseClass>
</ECEntityClass>
<ECEntityClass typeName="BaseEntityTest" description="Base Entity Test class" modifier="None">
<ECProperty propertyName="intProps" typeName="int"/>
<ECProperty propertyName="stringProps" typeName="string"/>
</ECEntityClass>
</ECSchema>`,
expectedSchemaImportTs: utils.createExpectedSchemaImportTs("TestSchema"),
expectedSchemaTs: utils.createExpectedSchemaTsString("TestSchema"),
expectedPropsImportTs: [
new RegExp(`import { (?=.*\\b(EntityProps)\\b).* } from "@itwin/core-common";`),
],
expectedPropsTs: [utils.dedent`
export interface BaseEntityTestProps extends EntityProps {
intProps?: number;
stringProps?: string;
}`,
],
expectedElemImportTs: [
new RegExp(`import { (?=.*\\b(Entity)\\b)(?=.*\\b(IModelDb)\\b)(?=.*\\b(Element)\\b).* } from "@itwin/core-backend";`),
new RegExp(`import { (?=.*\\b(ElementProps)\\b).* } from "@itwin/core-common";`),
new RegExp(`import { (?=.*\\b(BaseEntityTestProps)\\b).* } from "./TestSchemaElementProps";`),
],
expectedElemTs: [utils.dedent`
export class DerivedElementTest extends Element {
public static get className(): string { return "DerivedElementTest"; }
public constructor (props: ElementProps, iModel: IModelDb) {
super(props, iModel);
}
}`, utils.dedent`
export class BaseEntityTest extends Entity implements BaseEntityTestProps {
public static get className(): string { return "BaseEntityTest"; }
public constructor (props: BaseEntityTestProps, iModel: IModelDb) {
super(props, iModel);
}
}`, utils.dedent`
export class DerivedEntityTest extends BaseEntityTest {
public static get className(): string { return "DerivedEntityTest"; }
public constructor (props: BaseEntityTestProps, iModel: IModelDb) {
super(props, iModel);
}
}`,
],
},
// Test Case: correct order of base classes
{
testName: `Test Order of Base Classes`,
referenceXmls: [],
schemaXml: `<?xml version="1.0" encoding="utf-8"?>
<ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2">
<ECSchemaReference name="CoreCustomAttributes" version="01.00.00" alias="CoreCA"/>
<ECSchemaReference name="BisCore" version="01.00.00" alias="bis"/>
<ECEntityClass typeName="DerivedElementTest" description="Derived Element Test class" modifier="None">
<BaseClass>BaseEntity</BaseClass>
<ECProperty propertyName="stringProps" typeName="string"/>
</ECEntityClass>
<ECEntityClass typeName="BaseEntity" description="Base Entity Test class" modifier="None">
<BaseClass>NormalEntity</BaseClass>
<ECProperty propertyName="intProps" typeName="int"/>
</ECEntityClass>
<ECEntityClass typeName="Mixin" description="This Is A Mixin class" modifier="None">
<ECCustomAttributes>
<IsMixin xmlns="CoreCustomAttributes.01.00.00">
<AppliesToEntityClass>NormalEntity</AppliesToEntityClass>
</IsMixin>
</ECCustomAttributes>
<ECProperty propertyName="booleanProps" typeName="boolean"/>
<ECProperty propertyName="stringProps" typeName="string"/>
<ECProperty propertyName="binaryProps" typeName="binary"/>
<ECProperty propertyName="doubleProps" typeName="double"/>
</ECEntityClass>
<ECEntityClass typeName="NormalEntity" description="Normal Test class" modifier="None">
<BaseClass>bis:AnnotationElement2d</BaseClass>
<BaseClass>Mixin</BaseClass>
<ECProperty propertyName="intProps" typeName="int"/>
<ECProperty propertyName="stringProps" typeName="string"/>
</ECEntityClass>
</ECSchema>`,
expectedSchemaImportTs: utils.createExpectedSchemaImportTs("TestSchema"),
expectedSchemaTs: utils.createExpectedSchemaTsString("TestSchema"),
expectedPropsImportTs: [
new RegExp(`import { (?=.*\\b(GeometricElement2dProps)\\b).* } from "@itwin/core-common";`),
],
expectedPropsTs: [utils.dedent`
/**
* This Is A Mixin class
*/
export interface Mixin {
booleanProps?: boolean;
stringProps?: string;
binaryProps?: any;
doubleProps?: number;
}
export interface NormalEntityProps extends GeometricElement2dProps, Mixin {
intProps?: number;
stringProps?: string;
}
export interface BaseEntityProps extends NormalEntityProps {
intProps?: number;
}
export interface DerivedElementTestProps extends BaseEntityProps {
stringProps?: string;
}`,
],
expectedElemImportTs: [
new RegExp(`import { (?=.*\\b(AnnotationElement2d)\\b)(?=.*\\b(IModelDb)\\b).* } from "@itwin/core-backend";`),
new RegExp(`import { (?=.*\\b(NormalEntityProps)\\b)(?=.*\\b(BaseEntityProps)\\b)(?=.*\\b(DerivedElementTestProps)\\b).* } from "./TestSchemaElementProps";`),
],
expectedElemTs: [utils.dedent`
/**
* Normal Test class
*/
export class NormalEntity extends AnnotationElement2d implements NormalEntityProps {
public static get className(): string { return "NormalEntity"; }
public constructor (props: NormalEntityProps, iModel: IModelDb) {
super(props, iModel);
}
}
/**
* Base Entity Test class
*/
export class BaseEntity extends NormalEntity implements BaseEntityProps {
public static get className(): string { return "BaseEntity"; }
public constructor (props: BaseEntityProps, iModel: IModelDb) {
super(props, iModel);
}
}
/**
* Derived Element Test class
*/
export class DerivedElementTest extends BaseEntity implements DerivedElementTestProps {
public static get className(): string { return "DerivedElementTest"; }
public constructor (props: DerivedElementTestProps, iModel: IModelDb) {
super(props, iModel);
}
}`,
],
},
// Test Case: Xml Deserialization should not crash when references Units and Formats
{
testName: "Xml Deserialization should not crash when parsing Units and Formats",
referenceXmls: [],
schemaXml: `<?xml version="1.0" encoding="utf-8"?>
<ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2">
<ECSchemaReference name="Units" version="01.00.00" alias="u"/>
<ECSchemaReference name="Formats" version="01.00.00" alias="f"/>
</ECSchema>`,
expectedSchemaImportTs: utils.createExpectedSchemaImportTs("TestSchema"),
expectedSchemaTs: utils.createExpectedSchemaTsString("TestSchema"),
expectedPropsImportTs: [],
expectedPropsTs: [],
expectedElemImportTs: [],
expectedElemTs: [],
},
// Test Case: Xml Deserialization should not crash when parsing KoQ's persistentUnit and presentationUnits
{
testName: "Xml Deserialization should not crash when parsing KoQ's persistentUnit and presentationUnits",
referenceXmls: [],
schemaXml: `<?xml version="1.0" encoding="utf-8"?>
<ECSchema schemaName="TestSchema" alias="ts" version="1.0.0" xmlns="http://www.bentley.com/schemas/Bentley.ECXML.3.2">
<ECSchemaReference name="Units" version="01.00.00" alias="u"/>
<ECSchemaReference name="Formats" version="01.00.00" alias="f"/>
<ECEntityClass typeName="TestEntity" description="TestEntity Test class" modifier="None">
<ECArrayProperty propertyName="intArrayProp" typeName="int" minimumValue="0" maximumValue="10000" kindOfQuantity="KindOfQuantity"/>
<ECProperty propertyName="doubleProp" typeName="double" minimumValue="0" maximumValue="10000" kindOfQuantity="KindOfQuantityAlternative"/>
</ECEntityClass>
<KindOfQuantity typeName="KindOfQuantity"
description="Kind of Quantity Description"
displayLabel="Kind of Quantity"
persistenceUnit="u:CM"
relativeError="0.001"
presentationUnits="f:DefaultReal(6)[u:FT|feet];f:DefaultReal[u:IN|inch];f:DefaultReal(8)[u:CM|centimeter][u:M|meter]"/>
<KindOfQuantity typeName="KindOfQuantityAlternative"
description="Kind of Quantity Description"
displayLabel="Kind of Quantity"
persistenceUnit="u:CM"
relativeError="1E-3"
presentationUnits="f:DefaultReal(6)[u:FT|feet];f:DefaultReal[u:IN|inch];f:DefaultReal(8)[u:CM|centimeter][u:M|meter]"/>
</ECSchema>`,
expectedSchemaImportTs: utils.createExpectedSchemaImportTs("TestSchema"),
expectedSchemaTs: utils.createExpectedSchemaTsString("TestSchema"),
expectedPropsImportTs: [
new RegExp(`import { EntityProps } from "@itwin/core-common";`),
],
expectedPropsTs: [utils.dedent`
export interface TestEntityProps extends EntityProps {
intArrayProp?: number[];
doubleProp?: number;
}`,
],
expectedElemImportTs: [
new RegExp(`import { (?=.*\\b(Entity)\\b)(?=.*\\b(IModelDb)\\b).* } from "@itwin/core-backend";`),
new RegExp(`import { TestEntityProps } from "./TestSchemaElementProps";`),
],
expectedElemTs: [utils.dedent`
export class TestEntity extends Entity implements TestEntityProps {
public static get className(): string { return "TestEntity"; }
public constructor (props: TestEntityProps, iModel: IModelDb) {
super(props, iModel);
}
}`,
],
},
];
utils.testGeneratedSchemaTypescript(testCases);
}); | the_stack |
export interface Adapter<P = unknown> {
/**
* Returns the client that is passed as a parameter to `migrate()` and `rollback()`.
*/
connect(): Promise<P>;
/**
* Releases the resources (if any) allocated by the adapter internally.
*/
disconnect(): Promise<void>;
/**
* Returns an absolute path to the template that is used by `east create <migration-name>`
* If adapter supports multiple languages it should check for the extension
* name and return the path to the appropriate template for the given
* file extension, otherwise an error should be thrown.
*
* @param sourceMigrationExtension defines the file extension for the created
* migration without the leading dot (e.g. 'js', 'ts', etc.)
*/
getTemplatePath(sourceMigrationExtension: string): string;
/**
* Returns the entire list of all executed migration names.
*/
getExecutedMigrationNames(): Promise<string[]>;
/**
* Marks the migration under `migrationName` as executed in the backing migration state storage.
*/
markExecuted(migrationName: string): Promise<void>;
/**
* Unmarks migration under `migrationName` as executed in the backing migration state storage.
*/
unmarkExecuted(migrationName: string): Promise<void>;
}
export interface AdapterConstructorParams<P = unknown> extends MigratorParams<P> {
/**
* Adapter constructor is invoked only when the property `adapter` of `MigratorParams`
* is a string that is the path leading to the adapter module itself.
*/
adapter: string;
/**
* Any other additional parameters that are required by the adapter.
* The adapter should check their presense and validity by himself.
*/
[additionalParams: string]: unknown;
}
/**
* Creates an instance of `Adapter` passing the config object (that will also
* contain properties from `.eastrc` if not overriden in code).
*/
export type AdapterConstructor<P = unknown> = new (params: AdapterConstructorParams<P>) => Adapter<P>;
export interface MigratorParams<P = unknown> {
/**
* Path to migration executable scripts dir.
*
* Default: `"./migrations"`
*/
dir: string;
/**
* Path to the adapter to require or the `AdpaterConstructor` itself.
*
* Default: path to the builtin adapter that stores executed migration names
* at file `.migrations` in dir which is located at `dir` and passes `null`
* to `migrate()/rollback()`
*/
adapter: string | AdapterConstructor<P>;
/**
* File extension of migrations at `dir` (without the leading dot, e.g. `"js"`, `"ts"`)
*
* Default: `"js"`
*/
migrationExtension: string;
/**
* Dir with migration source files (for transpiled languages e.g. ts)
*
* Default: the same as `dir`
*/
sourceDir: string;
/**
* File extension of migrations at `sourceDir` (without the leading dot, e.g. `"js"`, `"ts"`)
*
* Default: the same as `migrationExtension`
*/
sourceMigrationExtension: string;
/**
* Execution timeout in milliseconds.
*
* Default: one week (unreal)
*/
timeout: number;
/**
* Database url. This is not used by `east` itself, it is just passed to the
* adapter and only the adapter determines what to do with it. By convention,
* adapters * should use `url` for passing the target database cluster domain
* endpoint.
*
* Default: `null`
*/
url: null | string;
/**
* Numbering format for migration file names.
*
* Default: `"sequentialNumber"`
*/
migrationNumberFormat: MigrationNumberFormat;
/**
* Whether to turn on verbose mode (includes error stack trace).
*
* Default: `false`
*/
trace: boolean;
/**
* Whether to load the `config` file. Its contents will be merged with
* these parameters, though if some parameters passed here also appear
* in `config` file, the former will take precedence.
*
* Default: `true`
*/
loadConfig: boolean;
/**
* Path to the config file. This may be a `json` file or a `js` file that
* exports the config object as `module.exports`.
*
* Default: `"./.eastrc"`
*/
config: string;
/**
* Path to the template file for new migrations.
*
* Default: builtin `"js"` or `"ts"` template according to `sourceMigrationExtension`
*/
template: string;
/**
* Array of paths to plugin modules or plugin objects themselves.
* `module.exports` of the plugin module should conform to `Plugin` interface.
*
* Default: `undefined`
*/
plugins?: (string | Plugin<P>)[];
/**
* Whether to load config, migrations, adapter and plugins using import
* expression. It allows to provide those entities like commonjs or es
* modules.
*
* Default: `false`
*/
esModules: boolean;
}
export interface Plugin<P = unknown> {
register(params: RegisterPluginParams<P>): Promise<void>;
}
export interface RegisterPluginParams<P = unknown> {
migratorParams: MigratorParams<P>;
migratorHooks: Hooks<P>;
}
export interface OkHookParams<P = unknown> {
migrationName: string;
/**
* Parameter value that is passed to `migrate(param: P)/rollback(param: P)`
*/
migrationParams: P;
}
export interface ErrHookParams<P = unknown> extends OkHookParams<P> {
error: unknown;
}
type OkHook<P = unknown> = (params: OkHookParams<P>) => void;
type ErrHook<P = unknown> = (params: ErrHookParams<P>) => void;
export interface Hooks<P = unknown> {
on(event: 'beforeMigrate', listener: OkHook<P>): this;
on(event: 'afterMigrate', listener: OkHook<P>): this;
on(event: 'migrateError', listener: ErrHook<P>): this;
on(event: 'beforeRollback', listener: OkHook<P>): this;
on(event: 'afterRollback', listener: OkHook<P>): this;
on(event: 'rollbackError', listener: ErrHook<P>): this;
}
/**
* The default format for migration file names is to prepend a number to the filename
* which is incremented with every new file.
* This creates migration files such as
* - `migrations/1_doSomething.js`,
* - `migrations/2_doSomethingElse.js`.
*
* If you prefer your files to be created with a date time instead of sequential numbers,
* you can choose the `dateTime` format.
* This will create migration files with date time prefix in `YYYYMMDDhhmmss` format such as
* - `migrations/20190720172730_doSomething.js`
*/
export type MigrationNumberFormat = "sequentialNumber" | "dateTime";
/**
* Parameters for the default builtin adapter that stores the migration state in
* a file on the local filesystem.
*/
export interface FileStorageAdapterParams {
/**
* Path to the file where the migration state is stored.
*
* Default: `"${dir}/.migrations"`
*/
migrationsFile?: string;
}
export interface CreateResult {
/**
* Name of the migration that was created. Doesn't include the file
* extension. It has the following format: `<migrationNumber>_<basename>`
*/
name: string;
}
export type MigrationFileType = "executable" | "source";
export type GetMigrationNamesParams = MigrationFilters & {
/**
* If true then result array will be reversed.
*
* Default: `false`
*/
reverseOrderResult?: boolean;
};
type MigrationFilters =
{
/**
* Tag expression to filter migrations e.g. 'tag1 & !tag2'
*
* Default: `undefined`
*/
tag?: string;
} & ({
/**
* Array of target migrations, each migration could be defined by basename,
* full name, path or number
*/
migrations: string[];
status?: undefined;
} | {
/**
* Status to filter migrations by.
*/
status: MigrationStatusFilter;
migrations?: undefined;
});
export type MigrationStatusFilter = "new" | "executed" | "all";
export type MigrateParams = Partial<MigrationFilters> & {
/**
* Whether to allow executing/rollbacking already executed/rollbacked migrations.
*
* Default: `false`
*/
force?: boolean;
};
export type RollbackParams = MigrateParams;
/**
* `P` defines the type of the parameter that is passed to `migrate(param: P)/rollback(param: P)`
* most of the time this will be the database api client instance.
*
* `U` defines the object type of configurations for the adapter.
*/
export class MigrationManager<P = unknown, U extends object = FileStorageAdapterParams> {
/**
* Configures migration process (dir, adapter, etc). Merges `params` with loaded config
* (when `loadConfig` param is truthy - `true` by default).
* This method should be called before any other methods.
*/
configure(params: Partial<MigratorParams<P> & U>): Promise<void>;
/**
* Connects to database management system (if supposed by adapter).
*/
connect(): Promise<void>;
/**
* Disconnects from database management system (if supposed by adapter).
*/
disconnect(): Promise<void>;
/**
* Returns parameters used by migration process after configuration(`configure()` method).
*/
getParams(): Promise<MigratorParams<P> & U>;
/**
* Initiates migration process for a project. Should be called once per project.
*/
init(): Promise<void>;
/**
* Returns a boolean whether init was made or not.
*/
isInitialized(): Promise<boolean>;
/**
* Creates migration file with the template as a placeholder.
*
* @param basename Name of migration to be used as a base of the file name.
* It should not contain commas
*/
create(basename: string): Promise<CreateResult>;
/**
* Returns an absolute path of the migration on disk by name of the migration.
* Doesn't throw if the migration file doesn't exist, it only returns
* the path where the migration file is **supposed** to be located.
*
* @param name Name of the migration
* @param migrationFileType Type of the migration file to locate, `"executable"` by default
*/
getMigrationPath(name: string, migrationFileType?: MigrationFileType): Promise<string>;
/**
* Returns migrations names, `migrations` and `status` are mutually exclusive.
* If migrations `status` is not provided then all migrations will be processed
* (but also filtered by `tag`).
*/
getMigrationNames(params: GetMigrationNamesParams): Promise<string[]>;
/**
* Executes target migrations. By default migrations with `status` `"new"` are chosen.
*/
migrate(params: MigrateParams): Promise<void>;
/**
* Rollbacks target migrations. By default migrations with `status` `"executed"` are chosen.
*/
rollback(params: RollbackParams): Promise<void>;
}
interface MigrationManager extends MigrationManagerSubscriptionProvider {}
type MigrationManagerSubscriptionProvider = (
& Subscribable<"beforeMigrateOne", MigrateOneEvent>
& Subscribable<"afterMigrateOne", MigrateOneEvent>
& Subscribable<"beforeRollbackOne", RollbackOneEvent>
& Subscribable<"afterRollbackOne", RollbackOneEvent>
& Subscribable<"beforeMigrateMany", MigrateManyEvent>
& Subscribable<"afterMigrateMany", MigrateManyEvent>
& Subscribable<"beforeRollbackMany", RollbackManyEvent>
& Subscribable<"afterRollbackMany", RollbackManyEvent>
& Subscribable<"onSkipMigration", SkipMigrationEvent>
);
interface Subscribable<E, P> {
addListener(event: E, listener: (param: P) => void): this;
on(event: E, listener: (param: P) => void): this;
once(event:E, listener: (param: P) => void): this;
prependListener(event: E, listener: (param: P) => void): this;
prependOnceListener(event: E, listener: (param: P) => void): this;
}
export interface SkipMigrationEvent {
migration: {
name: string;
};
reason: SkipMigrationReason;
}
export type SkipMigrationReason =
| "cannotMigrateAlreadyExecuted"
| "cannotRollbackNotExecuted"
| "cannotRollbackWithoutRollback";
export type RollbackManyEvent = MigrateManyEvent;
export interface MigrateManyEvent {
migrationNames: string[];
}
export type RollbackOneEvent = MigrateOneEvent;
export interface MigrateOneEvent {
name: string;
tags?: string[];
} | the_stack |
import BatteryViewModel from "./battery-vm";
import { IBatteryStateCardConfig, IFilter, FilterOperator, IBatteryEntity, IHomeAssistantGroupProps, IBatteriesResultViewData, IGroupDataMap } from "./types";
import { HassEntity, HomeAssistant } from "./ha-types";
import { log, safeGetConfigObject } from "./utils";
import { ActionFactory } from "./action";
import { getBatteryCollections } from "./grouping";
/**
* Properties which should be copied over to individual entities from the card
*/
const entititesGlobalProps = [ "tap_action", "state_map", "charging_state", "secondary_info", "color_thresholds", "color_gradient", "bulk_rename", "icon" ];
const regExpPattern = /\/([^/]+)\/([igmsuy]*)/;
/**
* Functions to check if filter condition is met
*/
const operatorHandlers: { [key in FilterOperator]: (val: string | number | undefined, expectedVal: string | number) => boolean } = {
"exists": val => val !== undefined,
"contains": (val, searchString) => val !== undefined && val.toString().indexOf(searchString.toString()) != -1,
"=": (val, expectedVal) => val == expectedVal,
">": (val, expectedVal) => Number(val) > expectedVal,
"<": (val, expectedVal) => Number(val) < expectedVal,
">=": (val, expectedVal) => Number(val) >= expectedVal,
"<=": (val, expectedVal) => Number(val) <= expectedVal,
"matches": (val, pattern) => {
if (val === undefined) {
return false;
}
pattern = pattern.toString();
let exp: RegExp | undefined;
const regexpMatch = pattern.match(regExpPattern);
if (regexpMatch) {
// create regexp after removing slashes
exp = new RegExp(regexpMatch[1], regexpMatch[2]);
} else if (pattern.indexOf("*") != -1) {
exp = new RegExp("^" + pattern.replace(/\*/g, ".*") + "$");
}
return exp ? exp.test(val.toString()) : val === pattern;
}
}
/**
* Filter class
*/
class Filter {
/**
* Whether filter is permanent.
*
* Permanent filters removes entities/batteries from collections permanently
* instead of making them hidden.
*/
get is_permanent(): boolean {
return this.config.name != "state";
}
constructor(private config: IFilter) {
}
/**
* Checks whether entity meets the filter conditions.
* @param entity Hass entity
* @param state State override - battery state/level
*/
isValid(entity: HassEntity, state?: string): boolean {
const val = this.getValue(entity, state);
return this.meetsExpectations(val);
}
/**
* Gets the value to validate.
* @param entity Hass entity
* @param state State override - battery state/level
*/
private getValue(entity: HassEntity, state?: string): string | undefined {
if (!this.config.name) {
log("Missing filter 'name' property");
return;
}
if (this.config.name.indexOf("attributes.") == 0) {
return entity.attributes[this.config.name.substr(11)];
}
if (this.config.name == "state" && state !== undefined) {
return state;
}
return (<any>entity)[this.config.name];
}
/**
* Checks whether value meets the filter conditions.
* @param val Value to validate
*/
private meetsExpectations(val: string | number | undefined): boolean {
let operator = this.config.operator;
if (!operator) {
if (this.config.value === undefined) {
operator = "exists";
}
else {
const expectedVal = this.config.value.toString();
operator = expectedVal.indexOf("*") != -1 || (expectedVal[0] == "/" && expectedVal[expectedVal.length - 1] == "/") ?
"matches" :
"=";
}
}
const func = operatorHandlers[operator];
if (!func) {
log(`Operator '${this.config.operator}' not supported. Supported operators: ${Object.keys(operatorHandlers).join(", ")}`);
return false;
}
return func(val, this.config.value);
}
}
/**
* Class responsible for intializing Battery view models based on given configuration.
*/
export class BatteryProvider {
/**
* Filters for automatic adding entities.
*/
private include: Filter[] | undefined;
/**
* Filters to remove entitites from collection.
*/
private exclude: Filter[] | undefined;
/**
* Battery view models.
*/
private batteries: BatteryViewModel[] = [];
/**
* Groups to be resolved on HA state update.
*/
private groupsToResolve: string[] = [];
/**
* Collection of groups and their properties taken from HA
*/
private groupsData: IGroupDataMap = {};
/**
* Whether include filters were processed already.
*/
private initialized: boolean = false;
constructor(private config: IBatteryStateCardConfig, private cardNode: Node) {
this.include = config.filter?.include?.map(f => new Filter(f));
this.exclude = config.filter?.exclude?.map(f => new Filter(f));
if (!this.include) {
this.initialized = false;
}
this.processExplicitEntities();
}
update(hass: HomeAssistant): boolean {
let updated = false;
if (!this.initialized) {
// groups and includes should be processed just once
this.initialized = true;
updated = this.processGroups(hass) || updated;
updated = this.processIncludes(hass) || updated;
}
updated = this.updateBatteries(hass) || updated;
if (updated) {
this.processExcludes(hass);
}
return updated;
}
/**
* Return batteries
* @param hass Home Assistant instance
*/
getBatteries(): IBatteriesResultViewData {
return getBatteryCollections(this.config.collapse, this.batteries, this.groupsData);
}
/**
* Creates and returns new Battery View Model
*/
private createBattery(entity: IBatteryEntity) {
// assing card-level values if they were not defined on entity-level
entititesGlobalProps
.filter(p => (<any>entity)[p] == undefined)
.forEach(p => (<any>entity)[p] = (<any>this.config)[p]);
return new BatteryViewModel(
entity,
ActionFactory.getAction({
card: this.cardNode,
config: safeGetConfigObject(entity.tap_action || this.config.tap_action || <any>null, "action"),
entity: entity
})
);
}
/**
* Adds batteries based on entities from config.
*/
private processExplicitEntities() {
let entities = this.config.entity
? [this.config]
: (this.config.entities || []).map((entity: string | IBatteryEntity) => {
// check if it is just the id string
if (typeof (entity) === "string") {
entity = <IBatteryEntity>{ entity: entity };
}
return entity;
});
// remove groups to add them later
entities = entities.filter(e => {
if (!e.entity) {
throw new Error("Invalid configuration - missing property 'entity' on:\n" + JSON.stringify(e));
}
if (e.entity.startsWith("group.")) {
this.groupsToResolve.push(e.entity);
return false;
}
return true;
});
// processing groups and entities from collapse property
// this way user doesn't need to put same IDs twice in the configuration
if (this.config.collapse && Array.isArray(this.config.collapse)) {
this.config.collapse.forEach(group => {
if (group.group_id) {
// check if it's not there already
if (this.groupsToResolve.indexOf(group.group_id) == -1) {
this.groupsToResolve.push(group.group_id);
}
}
else if (group.entities) {
group.entities.forEach(entity_id => {
// check if it's not there already
if (!entities.some(e => e.entity == entity_id)) {
entities.push({ entity: entity_id });
}
});
}
});
}
this.batteries = entities.map(entity => this.createBattery(entity));
}
/**
* Adds batteries based on filter.include config.
* @param hass Home Assistant instance
*/
private processIncludes(hass: HomeAssistant): boolean {
let updated = false;
if (!this.include) {
return updated;
}
Object.keys(hass.states).forEach(entity_id => {
// check if entity matches filter conditions
if (this.include?.some(filter => filter.isValid(hass.states[entity_id])) &&
// check if battery is not added already (via explicit entities)
!this.batteries.some(b => b.entity_id == entity_id)) {
updated = true;
this.batteries.push(this.createBattery({ entity: entity_id }));
}
});
return updated;
}
/**
* Adds batteries from group entities (if they were on the list)
* @param hass Home Assistant instance
*/
private processGroups(hass: HomeAssistant): boolean {
let updated = false;
this.groupsToResolve.forEach(group_id => {
const groupEntity = hass.states[group_id];
if (!groupEntity) {
log(`Group "${group_id}" not found`);
return;
}
const groupData = groupEntity.attributes as IHomeAssistantGroupProps;
if (!Array.isArray(groupData.entity_id)) {
log(`Entities not found in "${group_id}"`);
return;
}
groupData.entity_id.forEach(entity_id => {
// check if battery is on the list already
if (this.batteries.some(b => b.entity_id == entity_id)) {
return;
}
updated = true;
this.batteries.push(this.createBattery({ entity: entity_id }));
});
this.groupsData[group_id] = groupData;
});
this.groupsToResolve = [];
return updated;
}
/**
* Removes or hides batteries based on filter.exclude config.
* @param hass Home Assistant instance
*/
private processExcludes(hass: HomeAssistant) {
if (this.exclude == undefined) {
return;
}
const filters = this.exclude;
const toBeRemoved: number[] = [];
this.batteries.forEach((battery, index) => {
let is_hidden = false;
for (let filter of filters) {
// passing HA entity state together with VM battery level as the source of this value can vary
if (filter.isValid(hass.states[battery.entity_id], battery.level)) {
if (filter.is_permanent) {
// permanent filters have conditions based on static values so we can safely
// remove such battery to avoid updating it unnecessarily
toBeRemoved.push(index);
}
else {
is_hidden = true;
}
}
}
// we keep the view model to keep updating it
// it might be shown/not-hidden next time
battery.is_hidden = is_hidden;
});
// we need to reverse otherwise the indexes will be messed up after removing
toBeRemoved.reverse().forEach(i => this.batteries.splice(i, 1));
}
/**
* Updates battery view models based on HA states.
* @param hass Home Assistant instance
*/
private updateBatteries(hass: HomeAssistant): boolean {
let updated = false;
this.batteries.forEach((battery, index) => {
battery.update(hass);
updated = updated || battery.updated;
});
if (updated) {
switch (this.config.sort_by_level) {
case "asc":
this.batteries.sort((a, b) => this.sort(a.level, b.level));
break;
case "desc":
this.batteries.sort((a, b) => this.sort(b.level, a.level));
break;
default:
if (this.config.sort_by_level) {
log("Unknown sort option. Allowed values: 'asc', 'desc'");
}
}
// trigger the UI update
this.batteries = [...this.batteries];
}
return updated;
}
/**
* Sorting function for battery levels which can have "Unknown" state.
* @param a First value
* @param b Second value
*/
private sort(a: string, b: string): number {
let aNum = Number(a);
let bNum = Number(b);
aNum = isNaN(aNum) ? -1 : aNum;
bNum = isNaN(bNum) ? -1 : bNum;
return aNum - bNum;
}
} | the_stack |
import ServiceElectron, { IPCMessages as IPCElectronMessages, Subscription } from '../../services/service.electron';
import Logger from '../../tools/env.logger';
import ControllerStreamFileReader from '../stream.main/file.reader';
import ControllerStreamProcessor from '../stream.main/controller';
import State from './state';
import { EventsHub } from '../stream.common/events';
import { ChartingEngine, TChartData, IMatch, IChartRequest } from './engine/controller';
import * as Tools from '../../tools/index';
import { IMapItem } from '../stream.main/file.map';
export interface IRange {
from: number;
to: number;
}
export interface IRangeMapItem {
rows: IRange;
bytes: IRange;
}
export default class ControllerStreamCharts {
private _logger: Logger;
private _reader: ControllerStreamFileReader;
private _subscriptions: { [key: string ]: Subscription | undefined } = { };
private _state: State;
private _charting: ChartingEngine;
private _events: EventsHub;
private _processor: ControllerStreamProcessor;
private _charts: IChartRequest[] = [];
private _pending: {
bytesToRead: IRange,
rowOffset: number,
} = {
bytesToRead: { from: -1, to: -1 },
rowOffset: -1,
};
constructor(guid: string, streamFile: string, searchFile: string, stream: ControllerStreamProcessor, streamState: EventsHub) {
this._events = streamState;
this._processor = stream;
// Create controllers
this._state = new State(guid, streamFile, searchFile);
this._logger = new Logger(`ControllerStreamCharts: ${this._state.getGuid()}`);
this._charting = new ChartingEngine(this._state);
this._reader = new ControllerStreamFileReader(this._state.getGuid(), this._state.getStreamFile());
// Listen stream update event
this._subscriptions.onStreamBytesMapUpdated = this._events.getSubject().onStreamBytesMapUpdated.subscribe(this._stream_onUpdate.bind(this));
// Listen IPC messages
ServiceElectron.IPC.subscribe(IPCElectronMessages.ChartRequest, this._ipc_onChartRequest.bind(this)).then((subscription: Subscription) => {
this._subscriptions.ChartRequest = subscription;
}).catch((error: Error) => {
this._logger.warn(`Fail to subscribe to render event "ChartRequest" due error: ${error.message}. This is not blocked error, loading will be continued.`);
});
ServiceElectron.IPC.subscribe(IPCElectronMessages.ChartRequestCancelRequest, this._ipc_onChartRequestCancelRequest.bind(this)).then((subscription: Subscription) => {
this._subscriptions.ChartRequestCancelRequest = subscription;
}).catch((error: Error) => {
this._logger.warn(`Fail to subscribe to render event "ChartRequestCancelRequest" due error: ${error.message}. This is not blocked error, loading will be continued.`);
});
}
public destroy(): Promise<void> {
return new Promise((resolve, reject) => {
// Unsubscribe IPC messages / events
Object.keys(this._subscriptions).forEach((key: string) => {
(this._subscriptions as any)[key].destroy();
});
// Clear results file
this._clear().catch((error: Error) => {
this._logger.error(`Error while killing: ${error.message}`);
}).finally(() => {
// Kill executor
this._charting.destroy();
// Kill reader
this._reader.destroy();
// Done
resolve();
});
});
}
private _extract(charts: IChartRequest[], requestId: string, from?: number, to?: number, rowOffset?: number): Promise<TChartData> {
return new Promise((resolve, reject) => {
if (this._processor.getStreamSize() === 0) {
// Save requests
this._charts = charts;
// Stream file doesn't exist yet
return resolve({});
}
// Start inspecting
const inspecting = this._charting.extract(charts, from, to, rowOffset);
if (inspecting instanceof Error) {
this._logger.warn(`Fail to start extract chart data due error: ${inspecting.message}`);
return;
}
inspecting.then((data: TChartData) => {
this._charts = charts;
resolve(data);
}).catch((execErr: Error) => {
reject(execErr);
this._logger.warn(`Fail to make extract chart data due error: ${execErr.message}`);
});
});
}
private _append(updated?: IMapItem): void {
if (this._charts.length === 0) {
return;
}
if (updated !== undefined) {
if (this._pending.rowOffset === -1) {
this._pending.rowOffset = updated.rows.from;
}
if (this._pending.bytesToRead.from === -1 || this._pending.bytesToRead.from > updated.bytes.from) {
this._pending.bytesToRead.from = updated.bytes.from;
}
if (this._pending.bytesToRead.to === -1 || this._pending.bytesToRead.to < updated.bytes.to) {
this._pending.bytesToRead.to = updated.bytes.to;
}
}
if (this._charting.isWorking()) {
return;
}
const bytes: IRange = { from: this._pending.bytesToRead.from, to: this._pending.bytesToRead.to };
const rowsOffset: number = this._pending.rowOffset;
this._pending.bytesToRead = { from: -1, to: -1 };
this._pending.rowOffset = -1;
this._extract(this._charts, Tools.guid(), bytes.from, bytes.to, rowsOffset).then((data: TChartData) => {
ServiceElectron.IPC.send(new IPCElectronMessages.ChartResultsUpdated({
streamId: this._state.getGuid(),
results: data,
})).catch((sendMsgErr: Error) => {
this._logger.error(`Fail notify render due error: ${sendMsgErr.message}`);
});
}).catch((searchErr: Error) => {
this._logger.warn(`Fail to append search results (range: ${bytes.from} - ${bytes.to}) due error: ${searchErr.message}`);
}).finally(() => {
this._reappend();
});
}
private _reappend() {
if (this._pending.bytesToRead.from !== -1 && this._pending.bytesToRead.to !== -1) {
this._append();
}
}
private _clear(): Promise<void> {
return new Promise((resolve, reject) => {
// Cancel current task if exist
this._charting.cancel();
resolve();
});
}
private _ipc_onChartRequest(message: IPCElectronMessages.TMessage, response: (instance: any) => any) {
const request: IPCElectronMessages.ChartRequest = message as IPCElectronMessages.ChartRequest;
// Store starting tile
const started: number = Date.now();
// Check target stream
if (this._state.getGuid() !== request.streamId) {
return;
}
// Check count of requests
if (request.requests.length === 0) {
return this._ipc_chartResultsResponse(response, {
id: request.requestId,
started: started,
results: {},
});
}
// Clear results file
this._clear().then(() => {
// Create regexps
const requests: IChartRequest[] = request.requests.map((regInfo: IPCElectronMessages.IChartRegExpStr) => {
return {
regExp: new RegExp(regInfo.source, regInfo.flags),
groups: regInfo.groups,
};
});
this._extract(requests, request.requestId).then((data: TChartData) => {
// Responce with results
this._ipc_chartResultsResponse(response, {
id: request.requestId,
started: started,
results: data,
});
}).catch((searchErr: Error) => {
return this._ipc_chartResultsResponse(response, {
id: request.requestId,
started: started,
error: searchErr.message,
});
});
}).catch((droppingErr: Error) => {
this._logger.error(`Fail drop search file due error: ${droppingErr.message}`);
return this._ipc_chartResultsResponse(response, {
id: request.requestId,
started: started,
error: droppingErr.message,
});
});
}
private _ipc_chartResultsResponse(response: (instance: any) => any, res: {
id: string, started: number, error?: string, results?: TChartData,
}) {
response(new IPCElectronMessages.ChartRequestResults({
streamId: this._state.getGuid(),
requestId: res.id,
error: res.error,
results: res.results === undefined ? {} : res.results,
duration: Date.now() - res.started,
}));
}
private _ipc_onChartRequestCancelRequest(message: IPCElectronMessages.TMessage, response: (instance: any) => any) {
const request: IPCElectronMessages.ChartRequestCancelRequest = message as IPCElectronMessages.ChartRequestCancelRequest;
// Clear results file
this._clear().then(() => {
response(new IPCElectronMessages.ChartRequestCancelResponse({
streamId: this._state.getGuid(),
requestId: request.requestId,
}));
}).catch((error: Error) => {
response(new IPCElectronMessages.ChartRequestCancelResponse({
streamId: this._state.getGuid(),
requestId: request.requestId,
error: error.message,
}));
});
}
private _stream_onUpdate(map: IMapItem) {
this._append(map);
}
} | the_stack |
import { dirname, join } from 'path';
import { readFileSync, writeFileSync } from 'fs';
import { EmittedFile } from '../run-webpack';
import { ExtraEntryPoint } from '../shared-models';
import { interpolateEnvironmentVariablesToIndex } from '../interpolate-env-variables-to-index';
import { generateEntryPoints } from './package-chunk-sort';
import { createHash } from 'crypto';
import { RawSource, ReplaceSource } from 'webpack-sources';
function stripBom(data: string) {
return data.replace(/^\uFEFF/, '');
}
const parse5 = require('parse5');
export type LoadOutputFileFunctionType = (file: string) => string;
export type CrossOriginValue = 'none' | 'anonymous' | 'use-credentials';
export interface AugmentIndexHtmlOptions {
/* Input file name (e. g. index.html) */
input: string;
/* Input contents */
inputContent: string;
baseHref?: string;
deployUrl?: string;
sri: boolean;
/** crossorigin attribute setting of elements that provide CORS support */
crossOrigin?: CrossOriginValue;
/*
* Files emitted by the build.
* Js files will be added without 'nomodule' nor 'module'.
*/
files: FileInfo[];
/** Files that should be added using 'nomodule'. */
noModuleFiles?: FileInfo[];
/** Files that should be added using 'module'. */
moduleFiles?: FileInfo[];
/*
* Function that loads a file used.
* This allows us to use different routines within the IndexHtmlWebpackPlugin and
* when used without this plugin.
*/
loadOutputFile: LoadOutputFileFunctionType;
/** Used to sort the inseration of files in the HTML file */
entrypoints: string[];
}
export interface FileInfo {
file: string;
name: string;
extension: string;
}
/*
* Helper function used by the IndexHtmlWebpackPlugin.
* Can also be directly used by builder, e. g. in order to generate an index.html
* after processing several configurations in order to build different sets of
* bundles for differential serving.
*/
export function augmentIndexHtml(params: AugmentIndexHtmlOptions): string {
const {
loadOutputFile,
files,
noModuleFiles = [],
moduleFiles = [],
entrypoints,
} = params;
let { crossOrigin = 'none' } = params;
if (params.sri && crossOrigin === 'none') {
crossOrigin = 'anonymous';
}
const stylesheets = new Set<string>();
const scripts = new Set<string>();
// Sort files in the order we want to insert them by entrypoint and dedupes duplicates
const mergedFiles = [...moduleFiles, ...noModuleFiles, ...files];
for (const entrypoint of entrypoints) {
for (const { extension, file, name } of mergedFiles) {
if (name !== entrypoint) {
continue;
}
switch (extension) {
case '.js':
scripts.add(file);
break;
case '.css':
stylesheets.add(file);
break;
}
}
}
// Find the head and body elements
const treeAdapter = parse5.treeAdapters.default;
const document = parse5.parse(params.inputContent, {
treeAdapter,
locationInfo: true,
});
let headElement;
let bodyElement;
for (const docChild of document.childNodes) {
if (docChild.tagName === 'html') {
for (const htmlChild of docChild.childNodes) {
if (htmlChild.tagName === 'head') {
headElement = htmlChild;
} else if (htmlChild.tagName === 'body') {
bodyElement = htmlChild;
}
}
}
}
if (!headElement || !bodyElement) {
throw new Error('Missing head and/or body elements');
}
// Determine script insertion point
let scriptInsertionPoint;
if (bodyElement.__location && bodyElement.__location.endTag) {
scriptInsertionPoint = bodyElement.__location.endTag.startOffset;
} else {
// Less accurate fallback
// parse5 4.x does not provide locations if malformed html is present
scriptInsertionPoint = params.inputContent.indexOf('</body>');
}
let styleInsertionPoint;
if (headElement.__location && headElement.__location.endTag) {
styleInsertionPoint = headElement.__location.endTag.startOffset;
} else {
// Less accurate fallback
// parse5 4.x does not provide locations if malformed html is present
styleInsertionPoint = params.inputContent.indexOf('</head>');
}
// Inject into the html
const indexSource = new ReplaceSource(
new RawSource(params.inputContent),
params.input
);
let scriptElements = '';
for (const script of scripts) {
const attrs: { name: string; value: string | null }[] = [
{ name: 'src', value: (params.deployUrl || '') + script },
];
if (crossOrigin !== 'none') {
attrs.push({ name: 'crossorigin', value: crossOrigin });
}
// We want to include nomodule or module when a file is not common amongs all
// such as runtime.js
const scriptPredictor = ({ file }: FileInfo): boolean => file === script;
if (!files.some(scriptPredictor)) {
// in some cases for differential loading file with the same name is avialable in both
// nomodule and module such as scripts.js
// we shall not add these attributes if that's the case
const isNoModuleType = noModuleFiles.some(scriptPredictor);
const isModuleType = moduleFiles.some(scriptPredictor);
if (isNoModuleType && !isModuleType) {
attrs.push({ name: 'nomodule', value: null });
if (!script.startsWith('polyfills-nomodule-es5')) {
attrs.push({ name: 'defer', value: null });
}
} else if (isModuleType && !isNoModuleType) {
attrs.push({ name: 'type', value: 'module' });
} else {
attrs.push({ name: 'defer', value: null });
}
} else {
attrs.push({ name: 'defer', value: null });
}
if (params.sri) {
const content = loadOutputFile(script);
attrs.push(..._generateSriAttributes(content));
}
const attributes = attrs
.map((attr) =>
attr.value === null ? attr.name : `${attr.name}="${attr.value}"`
)
.join(' ');
scriptElements += `<script ${attributes}></script>`;
}
indexSource.insert(scriptInsertionPoint, scriptElements);
// Adjust base href if specified
if (typeof params.baseHref == 'string') {
let baseElement;
for (const headChild of headElement.childNodes) {
if (headChild.tagName === 'base') {
baseElement = headChild;
}
}
const baseFragment = treeAdapter.createDocumentFragment();
if (!baseElement) {
baseElement = treeAdapter.createElement('base', undefined, [
{ name: 'href', value: params.baseHref },
]);
treeAdapter.appendChild(baseFragment, baseElement);
indexSource.insert(
headElement.__location.startTag.endOffset,
parse5.serialize(baseFragment, { treeAdapter })
);
} else {
let hrefAttribute;
for (const attribute of baseElement.attrs) {
if (attribute.name === 'href') {
hrefAttribute = attribute;
}
}
if (hrefAttribute) {
hrefAttribute.value = params.baseHref;
} else {
baseElement.attrs.push({ name: 'href', value: params.baseHref });
}
treeAdapter.appendChild(baseFragment, baseElement);
indexSource.replace(
baseElement.__location.startOffset,
baseElement.__location.endOffset,
parse5.serialize(baseFragment, { treeAdapter })
);
}
}
const styleElements = treeAdapter.createDocumentFragment();
for (const stylesheet of stylesheets) {
const attrs = [
{ name: 'rel', value: 'stylesheet' },
{ name: 'href', value: (params.deployUrl || '') + stylesheet },
];
if (crossOrigin !== 'none') {
attrs.push({ name: 'crossorigin', value: crossOrigin });
}
if (params.sri) {
const content = loadOutputFile(stylesheet);
attrs.push(..._generateSriAttributes(content));
}
const element = treeAdapter.createElement('link', undefined, attrs);
treeAdapter.appendChild(styleElements, element);
}
indexSource.insert(
styleInsertionPoint,
parse5.serialize(styleElements, { treeAdapter })
);
return indexSource.source();
}
function _generateSriAttributes(content: string) {
const algo = 'sha384';
const hash = createHash(algo).update(content, 'utf8').digest('base64');
return [{ name: 'integrity', value: `${algo}-${hash}` }];
}
type ExtensionFilter = '.js' | '.css';
export interface WriteIndexHtmlOptions {
outputPath: string;
indexPath: string;
files?: EmittedFile[];
noModuleFiles?: EmittedFile[];
moduleFiles?: EmittedFile[];
baseHref?: string;
deployUrl?: string;
sri?: boolean;
scripts?: ExtraEntryPoint[];
styles?: ExtraEntryPoint[];
postTransform?: IndexHtmlTransform;
crossOrigin?: CrossOriginValue;
}
export type IndexHtmlTransform = (content: string) => Promise<string>;
export async function writeIndexHtml({
outputPath,
indexPath,
files = [],
noModuleFiles = [],
moduleFiles = [],
baseHref,
deployUrl,
sri = false,
scripts = [],
styles = [],
postTransform,
crossOrigin,
}: WriteIndexHtmlOptions) {
let content = readFileSync(indexPath).toString();
content = stripBom(content);
content = augmentIndexHtml({
input: outputPath,
inputContent: interpolateEnvironmentVariablesToIndex(content, deployUrl),
baseHref,
deployUrl,
crossOrigin,
sri,
entrypoints: generateEntryPoints({ scripts, styles }),
files: filterAndMapBuildFiles(files, ['.js', '.css']),
noModuleFiles: filterAndMapBuildFiles(noModuleFiles, '.js'),
moduleFiles: filterAndMapBuildFiles(moduleFiles, '.js'),
loadOutputFile: (filePath) =>
readFileSync(join(dirname(outputPath), filePath)).toString(),
});
if (postTransform) {
content = await postTransform(content);
}
writeFileSync(outputPath, content);
}
function filterAndMapBuildFiles(
files: EmittedFile[],
extensionFilter: ExtensionFilter | ExtensionFilter[]
): FileInfo[] {
const filteredFiles: FileInfo[] = [];
const validExtensions: string[] = Array.isArray(extensionFilter)
? extensionFilter
: [extensionFilter];
for (const { file, name, extension, initial } of files) {
if (name && initial && validExtensions.includes(extension)) {
filteredFiles.push({ file, extension, name });
}
}
return filteredFiles;
} | the_stack |
import { expect } from "chai";
import * as sinon from "sinon";
import {
ArcGISTileMap, QuadId,
} from "../../../tile/internal";
const fakeArcGisUrl = "https:localhost/test/rest";
// This tilemap for parent tile (9,5,5),
// children: [10,10,10],[10,10,11],[10,11,10], [10,11,11]
// From tilemap, only [10,10,10], 10,11,11] are availability
const dataset1 = {
tilemap: {
adjusted:false,
location:{left:9,top:9,width:4,height:4},
data: [
0,0,0,0,
0,1,0,0,
0,0,1,0,
0,0,0,0],
},
available:[true,false,false,true],
parentContentId: "9_5_5", // NOTE: format is <level>_<column>_<row>
};
const dataset2 = {
tilemap: {
adjusted:true,
location:{left:9,top:9,width:3,height:3},
data:[
0,0,0,
0,1,0,
0,0,1]},
available:[true,false,false,true],
parentContentId: "9_5_5",
};
const dataset3 = {
tilemap: {
adjusted:false,
location:{left:0,top:0,width:4,height:4},
data:[
1,1,0,0,
1,1,0,0,
0,0,0,0]},
available:[true,true,true,true],
parentContentId: "9_0_0",
};
const dataset4 = {
tilemap: {
adjusted:true,
location:{left:9,top:9,width:2,height:2},
data:[
1,1,
1,1]},
available:[true,true,true,true],
parentContentId: "9_5_5",
};
const dataset5 = {
tilemap: {
adjusted:true,
location:{left:10,top:10,width:1,height:1},
data:[
1]},
available:[true,true,true,true],
parentContentId: "9_5_5",
};
// 8x8 dataset, 2 parent tiles are visible in the same tilemap
// the second one is only half visible
const dataset6 = {
tilemap: {
adjusted:false,
location:{left:7,top:7,width:8,height:8},
data: [
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 1, 1, 0, 0,
0, 0, 0, 1, 1, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0],
},
available1:[true,true,true,true], // first parent, fully visible
available2:[true,false,true,false], // second parent tile: half of it is visible
parentContentId1: "14_20_20", // NOTE: format is <level>_<column>_<row>
parentContentId2: "14_21_20", // NOTE: format is <level>_<column>_<row>
};
const emptyBundleError = {
error: {
code: 422,
},
};
describe("ArcGISTileMap", () => {
const sandbox = sinon.createSandbox();
const getRequestTile = (parentTile: QuadId, tileMapRequestSize?: number) => {
const childRow = parentTile.row * 2;
const childColumn = parentTile.column * 2;
const childLevel = parentTile.level + 1;
let offset = 0;
if (tileMapRequestSize !== undefined) {
offset = (tileMapRequestSize/2.0)-1;
}
const row = Math.max(childRow - offset, 0);
const column = Math.max(childColumn - offset, 0);
return {level:childLevel, row, column};
};
afterEach(async () => {
sandbox.restore();
});
it("Test simple 4x4 tilemap request", async () => {
const getTileMapStub = sandbox.stub(ArcGISTileMap.prototype, "fetchTileMapFromServer" as any).callsFake(async function _(_level: number, _row: number, _column: number, _width: number, _height: number): Promise<any> {
return dataset1.tilemap;
});
const parentQuadId = QuadId.createFromContentId(dataset1.parentContentId);
// ArcGISTileMap assumes QuadId.getChildIds to return children in row major orientation.
// lets make sure this is true
const children = parentQuadId.getChildIds();
const level = 10;
const row = 10;
const column = 10;
for (let j=0, k=0; j < 2; j++) {
for (let i=0; i < 2; i++) {
const child = children[k++];
expect(child.level).to.be.equals(level);
expect(child.row).to.be.equals(row+j);
expect(child.column).to.be.equals(column+i);
}
}
const tileMap = new ArcGISTileMap(fakeArcGisUrl);
tileMap.tileMapRequestSize = 4;
let available = await tileMap.getChildrenAvailability(parentQuadId.getChildIds());
// [10,10,10], 10,11,11] should be visible
expect(available).to.eql(dataset1.available);
expect(getTileMapStub.calledOnce).to.be.true;
// Make sure that tile [10,10,10] was put in the middle of tilemap, so the request tile should be [10,9,9], size: 4x4
const requestTile1 = getRequestTile(parentQuadId, tileMap.tileMapRequestSize);
expect(getTileMapStub.calledWithExactly(requestTile1.level, requestTile1.row, requestTile1.column, tileMap.tileMapRequestSize,tileMap.tileMapRequestSize)).to.be.true;
// Make sure values got cached correctly
const tileInfo = (tileMap as any).getAvailableTilesFromCache(children);
expect(tileInfo.allTilesFound).to.be.true;
expect(tileInfo.available).to.eql(dataset1.available);
// Result in cache, no server request should be made
getTileMapStub.resetHistory();
available = await tileMap.getChildrenAvailability(QuadId.createFromContentId(dataset1.parentContentId).getChildIds());
expect(tileInfo.allTilesFound).to.be.true;
expect(available).to.eql(dataset1.available);
expect(getTileMapStub.called).to.be.false;
// Request parent tile next to the initial one, so 9,6,5, a server quest should be made.
const nextParentTile = QuadId.createFromContentId("9_5_6");
available = await tileMap.getChildrenAvailability(nextParentTile.getChildIds());
const requestTile2 = getRequestTile(nextParentTile, tileMap.tileMapRequestSize);
expect(getTileMapStub.calledWithExactly(requestTile2.level, requestTile2.row, requestTile2.column, tileMap.tileMapRequestSize,tileMap.tileMapRequestSize)).to.be.true;
});
it("Test 4x4 tilemap request, using call queue", async () => {
const getTileMapStub = sandbox.stub(ArcGISTileMap.prototype, "fetchTileMapFromServer" as any).callsFake(async function _(_level: number, _row: number, _column: number, _width: number, _height: number): Promise<any> {
return dataset1.tilemap;
});
const parentQuadId = QuadId.createFromContentId(dataset1.parentContentId);
const tileMap = new ArcGISTileMap(fakeArcGisUrl, 24);
tileMap.tileMapRequestSize = 4;
const available = await tileMap.getChildrenAvailability(parentQuadId.getChildIds());
expect(available).to.eql(dataset1.available);
// Make sure that tile [10,10,10] was put in the middle of tilemap, so the request tile should be [10,9,9], size: 4x4
const requestTile1 = getRequestTile(parentQuadId, tileMap.tileMapRequestSize);
expect(getTileMapStub.calledWithExactly(requestTile1.level, requestTile1.row, requestTile1.column, tileMap.tileMapRequestSize,tileMap.tileMapRequestSize)).to.be.true;
});
// Since the parent tile is located on the top-left corner of the LOD,
// no offset should be applied the requested tile (i.e we should not end up with negatives values for row,columns)
it("Test 4x4 tilemap request, top-left tile of LOD", async () => {
const getTileMapStub = sandbox.stub(ArcGISTileMap.prototype, "fetchTileMapFromServer" as any).callsFake(async function _(_level: number, _row: number, _column: number, _width: number, _height: number): Promise<any> {
return dataset3.tilemap;
});
const parentQuadId = QuadId.createFromContentId(dataset3.parentContentId);
const tileMap = new ArcGISTileMap(fakeArcGisUrl, 24);
tileMap.tileMapRequestSize = 4;
const available = await tileMap.getChildrenAvailability(parentQuadId.getChildIds());
expect(available).to.eql(dataset3.available);
const requestTile1 = getRequestTile(parentQuadId, tileMap.tileMapRequestSize);
expect(getTileMapStub.calledWithExactly(requestTile1.level, requestTile1.row, requestTile1.column, tileMap.tileMapRequestSize,tileMap.tileMapRequestSize)).to.be.true;
});
// Response contains an adjusted tilemap, tiles we are looking for are still part
// tile map, we need to make sure we can still get the tight tiles visibility.
it("Test 4x4 tilemap request, response got adjusted to 3x3", async () => {
const getTileMapStub = sandbox.stub(ArcGISTileMap.prototype, "fetchTileMapFromServer" as any).callsFake(async function _(_level: number, _row: number, _column: number, _width: number, _height: number): Promise<any> {
return dataset2.tilemap;
});
const tileMap = new ArcGISTileMap(fakeArcGisUrl);
tileMap.tileMapRequestSize = 4;
const available = await tileMap.getChildrenAvailability(QuadId.createFromContentId(dataset2.parentContentId).getChildIds());
expect(getTileMapStub.calledOnce).to.be.true;
expect(available).to.eql(dataset2.available);
});
// Response contains an adjusted tilemap, tiles we were looking for got clipped:
// As a fallback, a second request should be made with a smaller tilemap should be made
it("Test 4x4 tilemap request, response got adjusted to 2x2", async () => {
const getTileMapStub = sandbox.stub(ArcGISTileMap.prototype, "fetchTileMapFromServer" as any).callsFake(async function _(_level: number, _row: number, _column: number, _width: number, _height: number): Promise<any> {
return dataset4.tilemap;
});
const tileMap = new ArcGISTileMap(fakeArcGisUrl);
tileMap.tileMapRequestSize = 4;
const parentQuadId = QuadId.createFromContentId(dataset4.parentContentId);
const available = await tileMap.getChildrenAvailability(parentQuadId.getChildIds());
expect(getTileMapStub.calledTwice).to.be.true;
const requestTile = getRequestTile(parentQuadId, tileMap.fallbackTileMapRequestSize);
expect(getTileMapStub.lastCall.calledWithExactly(requestTile.level, requestTile.row, requestTile.column, tileMap.fallbackTileMapRequestSize, tileMap.fallbackTileMapRequestSize)).to.be.true;
expect(available).to.eql(dataset4.available);
});
// In this test, tilemap got adjusted and tiles we were looking for got clipped!
// A second request should be made with a smaller tilemap.
// The second request will return the 1x1 tilemap. available array should have a single tile available.
it("Test 4x4 tilemap request, response got adjusted to 1x1", async () => {
const getTileMapStub = sandbox.stub(ArcGISTileMap.prototype, "fetchTileMapFromServer" as any).callsFake(async function _(_level: number, _row: number, _column: number, _width: number, _height: number): Promise<any> {
return dataset5.tilemap; // always returns an 1x1 tilemap
});
const tileMap = new ArcGISTileMap(fakeArcGisUrl);
tileMap.tileMapRequestSize = 4;
const parentQuadId = QuadId.createFromContentId(dataset4.parentContentId);
const available = await tileMap.getChildrenAvailability(QuadId.createFromContentId(dataset4.parentContentId).getChildIds());
expect(getTileMapStub.calledTwice).to.be.true;
expect(available).to.eql([true,false,false,false]);
const requestTile1 = getRequestTile(parentQuadId, tileMap.tileMapRequestSize);
expect(getTileMapStub.getCalls()[0].calledWithExactly(requestTile1.level, requestTile1.row, requestTile1.column, tileMap.tileMapRequestSize, tileMap.tileMapRequestSize)).to.be.true;
// Second tilemap request should have the fallbackTileMapRequestSize size, and no offset applied
const requestTile2 = getRequestTile(parentQuadId);
expect(getTileMapStub.getCalls()[1].calledWithExactly(requestTile2.level, requestTile2.row, requestTile2.column, tileMap.fallbackTileMapRequestSize, tileMap.fallbackTileMapRequestSize)).to.be.true;
// When fallbackTileMapRequestSize is the same as the tileMapRequestSize, no second request is made
// Also no offset should be applied
tileMap.fallbackTileMapRequestSize = tileMap.tileMapRequestSize;
getTileMapStub.resetHistory();
const available2 = await tileMap.getChildrenAvailability(QuadId.createFromContentId(dataset4.parentContentId).getChildIds());
expect(available2).to.eql([true,false,false,false]);
expect(getTileMapStub.calledOnce).to.be.true;
// Tilemap request should have the fallbackTileMapRequestSize size, and no offset applied
expect(getTileMapStub.calledWithExactly(requestTile2.level, requestTile2.row, requestTile2.column, tileMap.fallbackTileMapRequestSize, tileMap.fallbackTileMapRequestSize)).to.be.true;
});
it("Test empty tilemap response", async () => {
const getTileMapStub = sandbox.stub(ArcGISTileMap.prototype, "fetchTileMapFromServer" as any).callsFake(async function _(_level: number, _row: number, _column: number, _width: number, _height: number): Promise<any> {
return emptyBundleError;
});
const allFalse = [false,false,false,false];
const tileMap = new ArcGISTileMap(fakeArcGisUrl);
tileMap.tileMapRequestSize = 4;
const available = await tileMap.getChildrenAvailability(QuadId.createFromContentId(dataset2.parentContentId).getChildIds());
expect(getTileMapStub.calledOnce).to.be.true;
expect(available).to.eql(allFalse);
const children = QuadId.createFromContentId(dataset1.parentContentId).getChildIds();
const tileInfo = (tileMap as any).getAvailableTilesFromCache(children);
expect(tileInfo.allTilesFound).to.be.true;
expect(tileInfo.available).to.eql(allFalse);
});
it("Test 8x8 tilemap request", async () => {
const getTileMapStub = sandbox.stub(ArcGISTileMap.prototype, "fetchTileMapFromServer" as any).callsFake(async function _(_level: number, _row: number, _column: number, _width: number, _height: number): Promise<any> {
return dataset6.tilemap;
});
const parentQuadId = QuadId.createFromContentId(dataset6.parentContentId1);
const tileMap = new ArcGISTileMap(fakeArcGisUrl);
tileMap.tileMapRequestSize = 8;
let available = await tileMap.getChildrenAvailability(parentQuadId.getChildIds());
expect(available).to.eql(dataset6.available1);
expect(getTileMapStub.calledOnce).to.be.true;
// Make sure the request tile was put in the middle of the tilemap
const requestTile1 = getRequestTile(parentQuadId, tileMap.tileMapRequestSize);
expect(getTileMapStub.calledWithExactly(requestTile1.level, requestTile1.row, requestTile1.column, tileMap.tileMapRequestSize, tileMap.tileMapRequestSize)).to.be.true;
// Request parent tile next to the initial one (on the right), only the bottom,right child should exist
// no server request should be made
getTileMapStub.resetHistory();
const reqParentTile2 = QuadId.createFromContentId(dataset6.parentContentId2);
expect(getTileMapStub.called).to.be.false;
available = await tileMap.getChildrenAvailability(reqParentTile2.getChildIds());
expect(available).to.eql(dataset6.available2);
expect(getTileMapStub.calledOnce).to.be.false;
});
}); | the_stack |
import xs, {Stream, Listener} from '../../src/index';
import fromDiagram from '../../src/extra/fromDiagram';
import * as assert from 'assert';
describe('Stream.prototype.flatten', () => {
describe('with map+debug to break the fusion', () => {
it('should not restart inner stream if switching to the same inner stream', (done: any) => {
const outer = fromDiagram('-A---------B----------C--------|');
const nums = fromDiagram( '-a-b-c-----------------------|', {
values: {a: 1, b: 2, c: 3}
});
const inner = nums.map(x => 10 * x);
const stream = outer.map(() => inner).debug(() => { }).flatten();
const expected = [10, 20, 30];
stream.addListener({
next: (x: number) => {
assert.equal(x, expected.shift());
},
error: (err: any) => done(err),
complete: () => {
assert.equal(expected.length, 0);
done();
}
});
});
});
describe('with map', () => {
it('should expand each periodic event with 3 sync events', (done: any) => {
const source: Stream<Stream<number>> = xs.periodic(100).take(3)
.map((i: number) => xs.of(1 + i, 2 + i, 3 + i));
const stream = source.flatten();
const expected = [1, 2, 3, 2, 3, 4, 3, 4, 5];
stream.addListener({
next: (x: number) => {
assert.equal(x, expected.shift());
},
error: (err: any) => done(err),
complete: () => {
assert.equal(expected.length, 0);
done();
}
});
});
it('should return a flat stream with correct TypeScript types', (done: any) => {
const streamStrings: Stream<string> = Stream.create({
start: (listener: Listener<string>) => {},
stop: () => {}
});
const streamBooleans: Stream<boolean> = Stream.create({
start: (listener: Listener<boolean>) => {},
stop: () => {}
});
// Type checked by the compiler. Without Stream<boolean> it does not compile.
const flat: Stream<boolean> = streamStrings.map(x => streamBooleans).flatten();
done();
});
it('should expand 3 sync events as a periodic, only last one passes', (done: any) => {
const stream = xs.fromArray([1, 2, 3])
.map(i => xs.periodic(100 * i).take(2).map(x => `${i}${x}`))
.flatten();
// ---x---x---x---x---x---x
// ---10--11
// -------20------21
// -----------30----------31
const expected = ['30', '31'];
stream.addListener({
next: (x: string) => {
assert.equal(x, expected.shift());
},
error: (err: any) => done(err),
complete: () => {
assert.equal(expected.length, 0);
done();
}
});
});
it('should expand 3 async events as a periodic each', (done: any) => {
const stream = xs.periodic(140).take(3)
.map(i =>
xs.periodic(100 * (i < 2 ? 1 : i)).take(3).map(x => `${i}${x}`)
)
.flatten();
// ---x---x---x---x---x---x---x---x---x---x---x---x
// ---00--01--02
// ----10--11--12
// ------------20-----------21----------22
const expected = ['00', '10', '20', '21', '22'];
stream.addListener({
next: (x: string) => {
assert.equal(x, expected.shift());
},
error: (err: any) => done(err),
complete: () => {
assert.equal(expected.length, 0);
done();
}
});
});
it('should expand 3 async events as a periodic each, no optimization', (done: any) => {
const stream = xs.periodic(140).take(3)
.map(i =>
xs.periodic(100 * (i < 2 ? 1 : i)).take(3).map(x => `${i}${x}`)
)
.filter(() => true) // breaks the optimization map+flattenConcurrently
.flatten();
// ---x---x---x---x---x---x---x---x---x---x---x---x
// ---00--01--02
// ----10--11--12
// ------------20-----------21----------22
const expected = ['00', '10', '20', '21', '22'];
stream.addListener({
next: (x: string) => {
assert.equal(x, expected.shift());
},
error: (err: any) => done(err),
complete: () => {
assert.equal(expected.length, 0);
done();
}
});
});
it('should propagate user mistakes in project as errors', (done: any) => {
const source = xs.periodic(30).take(1);
const stream = source.map(
x => {
const y = (<string> <any> x).toLowerCase();
return xs.of(y);
}
).flatten();
stream.addListener({
next: () => done('next should not be called'),
error: (err) => {
assert.notStrictEqual(err.message.match(/is not a function$/), null);
done();
},
complete: () => {
done('complete should not be called');
},
});
});
it('should not leak when used in a withLatestFrom-like case', (done: any) => {
const a$ = xs.periodic(100);
const b$ = xs.periodic(220);
let innerAEmissions = 0;
// a$.withLatestFrom(b$, (a, b) => a + b)
const c$ = b$.map(b =>
a$.map(a => a + b).debug(a => { innerAEmissions += 1; })
).flatten().take(1);
let cEmissions = 0;
c$.addListener({
next: (c) => {
assert.strictEqual(cEmissions, 0);
assert.strictEqual(c, 0);
cEmissions += 1;
},
error: (err: any) => done(err),
complete: () => { },
});
setTimeout(() => {
assert.strictEqual(innerAEmissions, 1);
assert.strictEqual(cEmissions, 1);
done();
}, 800);
});
it('should not error when stopping, and outer stream was empty', (done: any) => {
const outer = xs.never();
const stream = outer.map(x => xs.of(1, 2, 3)).flatten();
const listener = {
next: () => {},
error: () => {},
complete: () => {},
};
assert.doesNotThrow(() => {
stream.addListener(listener);
stream.removeListener(listener);
});
setTimeout(() => done(), 500);
});
it('should allow switching inners asynchronously without restarting source', (done: any) => {
const outer = fromDiagram( '-A---------B----------C------|');
const periodic = fromDiagram('---a-b--c----d--e--f----g--h-|', {
values: { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8 }
});
const stream = outer.map(x => {
if (x === 'A') {
return periodic.map(i => i * 10);
} else if (x === 'B') {
return periodic.map(i => i * 100);
} else if (x === 'C') {
return periodic.map(i => i * 1000);
} else {
return xs.never();
}
}).flatten();
const expected = [10, 20, 30, 400, 500, 600, 7000, 8000];
stream.addListener({
next: (x: number) => {
assert.equal(x, expected.shift());
},
error: (err: any) => done(err),
complete: () => {
assert.equal(expected.length, 0);
done();
}
});
});
it('should not restart inner stream if switching to the same inner stream', (done: any) => {
const outer = fromDiagram('-A---------B----------C--------|');
const nums = fromDiagram( '-a-b-c-----------------------|', {
values: {a: 1, b: 2, c: 3}
});
const inner = nums.map(x => 10 * x);
const stream = outer.map(() => inner).flatten();
const expected = [10, 20, 30];
stream.addListener({
next: (x: number) => {
assert.equal(x, expected.shift());
},
error: (err: any) => done(err),
complete: () => {
assert.equal(expected.length, 0);
done();
}
});
});
it('should not run multiple executions of the inner', (done: any) => {
const inner = xs.periodic(350).take(2).map(i => i * 100);
const outer = xs.periodic(200).take(4);
const stream = outer.map(() => inner).flatten();
const expected = [0, 100];
stream.addListener({
next: (x: number) => {
assert.equal(x, expected.shift());
},
error: (err: any) => done(err),
complete: () => {
assert.equal(expected.length, 0);
done();
}
});
});
});
describe('with filter and map', () => {
it('should execute the predicate, the projection, and the flattening', (done: any) => {
let predicateCallCount = 0;
let projectCallCount = 0;
const stream = xs.periodic(140).take(3)
.filter(i => {
predicateCallCount += 1;
return i % 2 === 0;
})
.map(i => {
projectCallCount += 1;
return xs.periodic(100 * (i < 2 ? 1 : i)).take(3).map(x => `${i}${x}`);
})
.flatten();
// ---x---x---x---x---x---x---x---x---x---x---x---x
// ---00--01--02
// ------------20-----------21----------22
const expected = ['00', '01', '20', '21', '22'];
stream.addListener({
next: (x: string) => {
assert.equal(x, expected.shift());
},
error: (err: any) => done(err),
complete: () => {
assert.equal(expected.length, 0);
assert.equal(predicateCallCount, 3);
assert.equal(projectCallCount, 2);
done();
}
});
});
});
describe('with mapTo', () => {
it('should not restart inner stream if switching to the same inner stream', (done: any) => {
const outer = fromDiagram('-A---------B----------C--------|');
const nums = fromDiagram( '-a-b-c-----------------------|', {
values: {a: 1, b: 2, c: 3}
});
const inner = nums.map(x => 10 * x);
const stream = outer.mapTo(inner).flatten();
const expected = [10, 20, 30];
stream.addListener({
next: (x: number) => {
assert.equal(x, expected.shift());
},
error: (err: any) => done(err),
complete: () => {
assert.equal(expected.length, 0);
done();
}
});
});
});
it('should allow to flatten while playing around with MemoryStream(s) and correct type signature', function() {
xs.of(xs.of(1)).flatten() // Stream<Stream<number>> => Stream<number>
xs.of(xs.of(1).remember()).flatten() // Stream<MemoryStream<number>> => Stream<number>
xs.of(xs.of(1)).remember().flatten() // MemoryStream<Stream<number>> => Stream<number>
xs.of(xs.of(1).remember()).remember().flatten() // Flaky typehint: MemoryStream<MemoryStream<number>> => Stream<{}>
xs.of(xs.of(1).remember()).remember().flatten<number>() // MemoryStream<MemoryStream<number>> => Stream<number>
})
}); | the_stack |
import { EventEmitter } from 'events'
const fromPairs = require('lodash/fromPairs')
const sortBy = require('lodash/sortBy')
const pluralize = require('pluralize')
import {
isConnectsRelationship,
isChildOfRelationship,
isRelationshipReference,
getChildOfRelationshipTarget,
SingleChildOfRelationship,
} from './types/relationships'
import { CollectionDefinitions, CollectionDefinition, CollectionDefinitionMap } from './types/collections'
import { IndexSourceField } from './types/indices'
import { FieldTypeRegistry } from './fields'
export interface RegistryCollections {
[collName: string]: CollectionDefinition
}
export interface RegistryCollectionsVersionMap {
[collVersion: number]: CollectionDefinition[]
}
export type SchemaHistory = SchemaHistoryEntry[]
export interface SchemaHistoryEntry {
version: Date
collections: RegistryCollections
}
export default class StorageRegistry extends EventEmitter {
public collections: RegistryCollections = {}
public _collectionsByVersion: RegistryCollectionsVersionMap = {}
public _collectionVersionMap: { [name: string]: RegistryCollections } = {}
public fieldTypes: FieldTypeRegistry
constructor({ fieldTypes }: { fieldTypes?: FieldTypeRegistry } = {}) {
super()
this.fieldTypes = fieldTypes || new FieldTypeRegistry()
}
registerCollection(name: string, defs: CollectionDefinitions) {
if (!(defs instanceof Array)) {
defs = [defs]
}
defs
.sort((a, b) => a.version.getTime() - b.version.getTime())
.forEach(def => {
this.collections[name] = def
def.name = name
def.indices = def.indices || []
this._preprocessFieldTypes(def)
this._autoAssignCollectionPk(def)
this._preprocessCollectionRelationships(name, def)
this._preprocessCollectionIndices(name, def)
const version = def.version.getTime()
this._collectionsByVersion[version] =
this._collectionsByVersion[version] || []
this._collectionsByVersion[version].push(def)
this._collectionVersionMap[version] = this._collectionVersionMap[version] || {}
this._collectionVersionMap[version][name] = def
})
this.emit('registered-collection', { collection: this.collections[name] })
}
registerCollections(collections: CollectionDefinitionMap) {
for (const [name, def] of Object.entries(collections)) {
this.registerCollection(name, def)
}
}
async finishInitialization() {
this._connectReverseRelationships()
return Promise.all(
this.listeners('initialized').map(
list => list.call(this),
),
).then(() => {})
}
get collectionVersionMap() {
this._deprecationWarning('StorageRegistry.collectionVersionMap is deprecated, use StorageRegistry.getCollectionsByVersion() instead')
return this._collectionVersionMap
}
getCollectionsByVersion(targetVersion: Date): RegistryCollections {
const collections = {}
for (const collectionDefinitions of Object.values(this.collectionVersionMap)) {
for (const [collectionName, collectionDefinition] of Object.entries(collectionDefinitions)) {
const savedCollectionDefinition = collections[collectionName]
if (!savedCollectionDefinition || (collectionDefinition.version.getTime() > savedCollectionDefinition.version.getTime())) {
if (collectionDefinition.version.getTime() <= targetVersion.getTime()) {
collections[collectionName] = collectionDefinition
}
}
}
}
return collections
}
get collectionsByVersion() {
this._deprecationWarning('StorageRegistry.collectionsByVersion is deprecated, use StorageRegistry.getSchemaHistory() instead')
return this._collectionsByVersion
}
getSchemaHistory(): SchemaHistory {
const entries = Object.entries(this._collectionsByVersion)
const sorted = sortBy(entries, ([version]) => parseInt(version))
return sorted.map(([version, collectionsArray]) => {
const collections = fromPairs(collectionsArray.map(
collection => [collection.name, collection]
))
return { version: new Date(parseInt(version)), collections }
})
}
_preprocessFieldTypes(def: CollectionDefinition) {
def.fieldsWithCustomType = []
const fields = def.fields
Object.entries(fields).forEach(([fieldName, fieldDef]) => {
const FieldType = this.fieldTypes.fieldTypes[fieldDef.type]
if (!FieldType) {
return
}
fieldDef.fieldObject = new FieldType()
def.fieldsWithCustomType.push(fieldName)
})
}
/**
* Handles mutating a collection's definition to flag all fields that are declared to be
* indexable as indexed fields.
*/
_preprocessCollectionIndices(collectionName: string, def: CollectionDefinition) {
const flagField = (fieldName: string, indexDefIndex: number) => {
if (!def.fields[fieldName]) {
throw new Error(`Flagging field ${fieldName} of collection ${collectionName} as index, but field does not exist`)
}
def.fields[fieldName]._index = indexDefIndex
}
const flagIndexSourceField = (indexSource: IndexSourceField, indexDefIndex: number) => {
if (typeof indexSource === 'string') {
flagField(indexSource, indexDefIndex)
}
}
const indices = def.indices || []
indices.forEach((indexDef, indexDefIndex) => {
const { field: indexSourceFields } = indexDef
// Compound indexes need to flag all specified fields
if (indexSourceFields instanceof Array) {
indexSourceFields.forEach(indexSource => { flagIndexSourceField(indexSource, indexDefIndex) })
} else {
flagIndexSourceField(indexSourceFields, indexDefIndex)
}
})
}
_autoAssignCollectionPk(def: CollectionDefinition) {
const indices = def.indices || []
indices.forEach(({ field: indexSourceFields, pk: isPk }, indexDefIndex) => {
if (isPk) {
def.pkIndex = indexSourceFields
}
})
if (!def.pkIndex) {
indices.unshift({ field: 'id', pk: true })
def.pkIndex = 'id'
}
if (typeof def.pkIndex === 'string' && !def.fields[def.pkIndex]) {
def.fields[def.pkIndex] = { type: 'auto-pk' }
}
}
/**
* Creates the fields and indices for relationships
*/
_preprocessCollectionRelationships(name: string, def: CollectionDefinition) {
def.relationships = def.relationships || []
def.relationshipsByAlias = {}
def.reverseRelationshipsByAlias = {}
for (const relationship of def.relationships) {
if (isConnectsRelationship(relationship)) {
relationship.aliases = relationship.aliases || relationship.connects
relationship.fieldNames = relationship.fieldNames || [
`${relationship.aliases[0]}Rel`,
`${relationship.aliases[1]}Rel`
]
relationship.reverseAliases = relationship.reverseAliases || [
pluralize(relationship.connects[1]),
pluralize(relationship.connects[0]),
]
} else if (isChildOfRelationship(relationship)) {
relationship.sourceCollection = name
relationship.targetCollection = getChildOfRelationshipTarget(relationship)
relationship.single = !!(<SingleChildOfRelationship>relationship).singleChildOf
relationship.alias = relationship.alias || relationship.targetCollection
def.relationshipsByAlias[relationship.alias] = relationship
if (!relationship.reverseAlias) {
relationship.reverseAlias = relationship.single ? name : pluralize(name)
}
relationship.fieldName = relationship.fieldName || `${relationship.alias}Rel`
} else {
throw new Error("Invalid relationship detected: " + JSON.stringify(relationship))
}
}
}
_connectReverseRelationships() {
Object.values(this.collections).forEach(sourceCollectionDef => {
for (const relationship of sourceCollectionDef.relationships) {
if (isConnectsRelationship(relationship)) {
const connected = [this.collections[relationship.connects[0]], this.collections[relationship.connects[1]]]
for (let idx = 0; idx < connected.length; ++idx) {
if (!connected[idx]) {
throw new Error(
`Collection '${sourceCollectionDef.name!}' defined ` +
`a 'connects' relation involving non-existing ` +
`collection '${relationship.connects[idx]}`
)
}
}
connected[0].reverseRelationshipsByAlias[relationship.reverseAliases[0]] = relationship
connected[1].reverseRelationshipsByAlias[relationship.reverseAliases[1]] = relationship
} else if (isChildOfRelationship(relationship)) {
const targetCollectionDef = this.collections[relationship.targetCollection]
if (!targetCollectionDef) {
const relationshipType = relationship.single ? 'singleChildOf' : 'childOf'
throw new Error(
`Collection '${sourceCollectionDef.name!}' defined ` +
`a '${relationshipType}' relationship to non-existing ` +
`collection '${relationship.targetCollection}`
)
}
targetCollectionDef.reverseRelationshipsByAlias[relationship.reverseAlias] = relationship
}
}
})
}
_deprecationWarning(message) {
console.warn(`DEPRECATED: ${message}`)
}
} | the_stack |
import {
NgModule,
Component,
Input,
Output,
EventEmitter,
OnInit,
QueryList,
ViewChildren,
Optional,
forwardRef,
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Injector
} from "@angular/core";
import { CommonModule } from "@angular/common";
import { FormsModule } from "@angular/forms";
import { JigsawSelectModule } from "../select/index";
import { JigsawInputModule } from "../input/input";
import { AbstractJigsawComponent } from "../../common/common";
import { TranslateModule, TranslateService } from "@ngx-translate/core";
import { InternalUtils } from "../../common/core/utils/internal-utils";
import { TranslateHelper } from "../../common/core/utils/translate-helper";
import { IPageable, PagingInfo } from "../../common/core/data/component-data";
import { CommonUtils } from "../../common/core/utils/common-utils";
import { RequireMarkForCheck } from "../../common/decorator/mark-for-check";
import { JigsawSearchInputModule, JigsawSearchInput } from "../input/search-input";
export class PageSizeData {
value: number;
label: string;
}
@Component({
selector: "jigsaw-pagination, j-pagination",
templateUrl: "pagination.html",
host: {
"[style.width]": "width",
"[style.height]": "height",
"[class.jigsaw-paging]": "true",
"[class.jigsaw-paging-simple]": 'mode == "simple"',
"[class.jigsaw-paging-complex]": 'mode == "complex" || mode == "folding"',
"[class.jigsaw-paging-small]": 'size == "small"',
"[class.jigsaw-paging-medium]": 'size == "medium"',
"[class.jigsaw-paging-large]": 'size == "large"'
},
changeDetection: ChangeDetectionStrategy.OnPush
})
export class JigsawPagination extends AbstractJigsawComponent implements OnInit, AfterViewInit {
constructor(
private _translateService: TranslateService,
private _changeDetectorRef: ChangeDetectorRef,
// @RequireMarkForCheck ้่ฆ็จๅฐ๏ผๅฟๅ
private _injector: Injector
) {
super();
}
private _totalRecord: number; // ๆฐๆฎๆปๆฐ
private _totalPage: number;
private _firstPage: JigsawPagingItem;
private _lastPage: JigsawPagingItem;
private _pageSizeOptions: any[];
/**
* @internal
* ้่ฆๆพ็คบ็ๅ้กตๆ้ฎๆฐๅญ้ๅ
*/
public _$pageNums: number[] = [];
/**
* @internal
*/
public _$pageSize: PageSizeData = {
value: null,
label: "--/" + this._translateService.instant("pagination.page")
};
/**
* @internal
*/
public _$prevDisabled: boolean = false;
/**
* @internal
*/
public _$nextDisabled: boolean = false;
private _data: IPageable;
/**
* @NoMarkForCheckRequired
*/
@Input()
public get data(): IPageable {
return this._data;
}
public set data(value: IPageable) {
if (CommonUtils.isUndefined(value) || !(value.pagingInfo instanceof PagingInfo)) {
return;
}
this._data = value;
if (typeof this._data.onRefresh == "function") {
this._data.onRefresh(() => {
this._renderPages();
});
}
}
/**
* ๆๅฎๆฏ้กตๅฏไปฅๆพ็คบๅคๅฐๆก
*
* @NoMarkForCheckRequired
*/
@Input()
public get pageSizeOptions() {
return this._pageSizeOptions;
}
public set pageSizeOptions(newValue: number[]) {
this._pageSizeOptions = [];
(newValue || []).forEach(num => {
let option = { value: num, label: num + "/" + this._translateService.instant("pagination.page") };
this._pageSizeOptions.push(option);
});
}
/**
* ๆ็ดขๅ่ฝๅผๅ
ณ
*/
@RequireMarkForCheck()
@Input()
public searchable: boolean = false;
/**
* ๆฏๅฆๅฏไปฅๅฟซ้่ทณ่ฝฌ่ณๆ้กต
*/
@RequireMarkForCheck()
@Input()
public showQuickJumper: boolean = false;
/**
* ๅฝไธบใsimpleใๆถ๏ผๆฏๅฐๅฐบๅฏธๅ้กต
*/
@RequireMarkForCheck()
@Input()
public mode: "complex" | "simple" | "folding" = "complex";
/**
* ่ฎพ็ฝฎๅ้กต็sizeๅคงๅฐ
*
* @NoMarkForCheckRequired
*/
@Input()
public size: "small" | "medium" | "large" = "medium";
/**
* searchไบไปถ
*/
@Output()
public search = new EventEmitter<string>();
/**
* @internal
* @param $event
*/
public _$searchEvent($event) {
this.search.emit($event);
}
/**
* ่ฎพ็ฝฎไบๆญคๅฑๆงไผ็ปๆ็ดขๅขๅ ไธไธช้ฒๆๅ่ฝ๏ผๅนถๅขๅ enterๅ่ฝฆ็ซๅปๆ็ดข
* ่ฎพไธบ'none'ใNaNใๅฐไบ0๏ผๆ่
ไธ่ฎพ็ฝฎๅ่กจ็คบไธ่ฎพ็ฝฎ้ฒๆ
*
* @NoMarkForCheckRequired
*/
@Input()
public searchDebounce: number | "none" = NaN;
/**
* ่ฎพ็ฝฎๆ็ดขๆจกๅผ๏ผ่ชๅจ/ๆๅจ๏ผ
*
* @NoMarkForCheckRequired
*/
@Input()
public autoSearch: boolean = true;
/**
* ้กต็ ๆนๅ็ไบไปถ
*/
@Output()
public currentChange: EventEmitter<any> = new EventEmitter<any>();
/**
* pageSize ๅๅ็ไบไปถ
*/
@Output()
public pageSizeChange: EventEmitter<number> = new EventEmitter<number>();
@ViewChildren(forwardRef(() => JigsawPagingItem))
private _pages: QueryList<JigsawPagingItem> = null;
@ViewChildren(JigsawSearchInput)
private _inputs: QueryList<JigsawSearchInput>;
private _current: number;
/**
* ๅฝๅ้กต
*/
public get current(): number {
return this._current;
}
public set current(newValue: number) {
newValue = newValue ? newValue : 1; //ๅ็ปๅๅงๅผไธบundefinedๆnullๆถ๏ผ่ฎพ้ป่ฎคๅผไธบ1
if (this.current != newValue) {
this._current = newValue;
this.currentChange.emit(newValue);
if (this.data.pagingInfo.currentPage != newValue) {
// pagingInfo.currentPage้็จ็getter&setter๏ผไธๅฏ้ไพฟ่ตๅผ
this.data.pagingInfo.currentPage = newValue;
}
this._changeDetectorRef.detectChanges();
}
}
/**
* ๆฏ้กตๆกๆฐ
*/
public get pageSize(): number {
return this._$pageSize ? this._$pageSize.value : null;
}
public set pageSize(newValue: number) {
newValue = newValue ? newValue : 10;
if (this.pageSize != newValue) {
this._$pageSize = {
value: newValue,
label: newValue + "/" + this._translateService.instant("pagination.page")
};
this.pageSizeChange.emit(newValue);
if (this.data.pagingInfo.pageSize != newValue) {
// pagingInfo.pageSize้็จ็getter&setter๏ผไธๅฏ้ไพฟ่ตๅผ
this.data.pagingInfo.pageSize = newValue;
}
}
}
/**
* ๆ นๆฎcurrentๆดๆฐPageItem็ปไปถ็ๆพ็คบ๏ผไธไธ้กต๏ผไธไธ้กต๏ผไธไบ้กต๏ผไธไบ้กต๏ผๅฝๅ้กต
* */
private _updatePageItems() {
// ๆพๅฐ็ฌฌไธไธชๅๆๅไธไธชPageItem็ปไปถ
this._setFirstLastPageItem();
//prevPages nextPages ๆพ็คบ
this._showPrevAndNextBtn();
//prevPage nextPage ไธๅฏ็น
this._updatePrevAndNextStatus();
//่ฎพ็ฝฎๅฝๅ้กต
this._setCurrentPage();
}
/**
* ๆ นๆฎcurrent่ฎพ็ฝฎๅฝๅ้กต
* */
private _setCurrentPage(): void {
this._pages.forEach(page => {
page.current = page.pageNumber == this.current;
});
this._changeDetectorRef.detectChanges();
}
/**
* ๆ นๆฎcurrentๆงๅถpageๆพ็คบ
* */
private _setPageNums(): void {
if (this.mode === "folding") {
if (this._totalPage > 10) {
if (this.current <= 3) {
this._$pageNums = [1, 2, 3, 4, 5, this._totalPage];
} else if (this.current >= this._totalPage - 2) {
this._$pageNums = [
1,
this._totalPage - 4,
this._totalPage - 3,
this._totalPage - 2,
this._totalPage - 1,
this._totalPage
];
} else {
this._$pageNums = [1, this.current - 1, this.current, this.current + 1, this._totalPage];
}
} else {
// ๅฐไบ10้กตไธ้่ฆ็็ฅๆพ็คบ
this._$pageNums = Array.from(new Array(this._totalPage)).map((item, index) => ++index);
}
} else {
if (this._totalPage > 5) {
if (this.current >= this._totalPage - 2) {
this._$pageNums = [
this._totalPage - 4,
this._totalPage - 3,
this._totalPage - 2,
this._totalPage - 1,
this._totalPage
];
} else if (this.current <= 3) {
this._$pageNums = [1, 2, 3, 4, 5];
} else {
this._$pageNums = [this.current - 2, this.current - 1, this.current, this.current + 1, this.current + 2];
}
} else {
// ๅฐไบ10้กตไธ้่ฆ็็ฅๆพ็คบ
this._$pageNums = Array.from(new Array(this._totalPage)).map((item, index) => ++index);
}
}
this._changeDetectorRef.detectChanges();
}
/**
* ไธไธ้กต
* @internal
*/
public _$pagePrev(): void {
if (this.current == 1) {
return;
}
this.current--;
this._changeDetectorRef.markForCheck();
}
/**
* ไธไธ้กต
* @internal
*/
public _$pageNext(): void {
if (this.current == this._totalPage) {
return;
}
this.current++;
this._changeDetectorRef.markForCheck();
}
/**
* ไธไบ้กต
* */
public pagesNext(): void {
let pageNum = this.current + 5;
pageNum = pageNum > this._totalPage ? this._totalPage : pageNum;
this.current = pageNum;
this._changeDetectorRef.markForCheck();
}
/**
* ไธไบ้กต
* */
public pagesPrev(): void {
let pageNum = this.current - 5;
pageNum = pageNum < 1 ? 1 : pageNum;
this.current = pageNum;
this._changeDetectorRef.markForCheck();
}
/**
* ๆพ็คบไธไบ้กตใไธไบ้กตๆ้ฎ
* */
private _showPrevAndNextBtn(): void {
if (!this._firstPage || !this._lastPage) {
return;
}
if (this._totalPage <= 10) {
this._firstPage.showPrev = false;
this._lastPage.showNext = false;
} else if (this.current == 4) {
this._firstPage.showPrev = true;
this._lastPage.showNext = true;
} else if (this.current < 4) {
this._firstPage.showPrev = false;
this._lastPage.showNext = true;
} else if (this.current > this._totalPage - 3) {
this._firstPage.showPrev = true;
this._lastPage.showNext = false;
} else if (this.current == this._totalPage - 3) {
this._firstPage.showPrev = true;
this._lastPage.showNext = true;
} else {
this._firstPage.showPrev = true;
this._lastPage.showNext = true;
}
this._firstPage._changeDetectorRef.markForCheck();
this._lastPage._changeDetectorRef.markForCheck();
}
/**
* ่ทๅ็ฌฌไธไธชๅๆๅไธไธชpage็ปไปถๅฎไพ
* */
private _setFirstLastPageItem(): void {
this._firstPage = this._pages.find(page => page.pageNumber == 1);
this._lastPage = this._pages.find(page => page.pageNumber == this._totalPage);
}
/**
* ไธไธ้กตใไธไธ้กตๆ้ฎ่ฎพ็ฝฎ
* */
private _updatePrevAndNextStatus(): void {
if (this._totalPage <= 1) {
this._$prevDisabled = true;
this._$nextDisabled = true;
} else if (this.current == 1) {
this._$prevDisabled = true;
this._$nextDisabled = false;
} else if (this.current == this._totalPage) {
this._$nextDisabled = true;
this._$prevDisabled = false;
} else {
this._$prevDisabled = false;
this._$nextDisabled = false;
}
this._changeDetectorRef.markForCheck();
}
/**
* @internal
* gotoๅ่ฝ
* */
public _goto(pageNum): void {
pageNum = parseInt(pageNum);
if (pageNum <= this._totalPage && pageNum >= 1) {
this.current = pageNum;
}
this._changeDetectorRef.markForCheck();
}
/**
* @internal
* select็ปไปถๆนๅpageSize
* */
public _$changePageSize(pageSize: {value?: number}): void {
const value = pageSize?.value;
if (isNaN(value)) {
return;
}
if (this.pageSize != value) {
this.pageSize = value;
this.current = 1;
}
this._changeDetectorRef.markForCheck();
}
/**
* ๆธฒๆpageๆ้ฎ
* */
private _renderPages(): void {
if (!this.data || !this.data.pagingInfo) {
return;
}
this._calcPagingInfo();
this._showPages();
this._changeDetectorRef.markForCheck();
}
private _calcPagingInfo() {
this.current = this.data.pagingInfo.currentPage;
this._totalRecord = this.data.pagingInfo.totalRecord;
this.pageSize = this.data.pagingInfo.pageSize;
//่ฎก็ฎๆป้กตๆฐ
this._totalPage = Math.ceil(this._totalRecord / this.pageSize);
if (isNaN(this._totalPage) || this._totalPage < 0) {
this._totalPage = 0;
}
//้ช่ฏcurrentๅๆณๆง
if (this.current <= 0 || this.current > this._totalPage) {
this.current = 1;
}
}
/**
* ๆ นๆฎๆฐๆฎๆพ็คบๅ้กตๆ้ฎ
* @private
*/
private _showPages() {
this._setPageNums();
this.runMicrotask(() => {
// ็ญๅพ
_$pageNumsๆธฒๆ็ปไปถ
this._updatePageItems();
});
this._changeDetectorRef.markForCheck();
}
/**
* ๅทๆฐๆฐๆฎๆถๆธ
็ฉบๆ็ดขๆก
*/
public reset() {
if (!this._inputs) {
return;
}
this._inputs.forEach(input => (input.value = ""));
}
ngOnInit() {
super.ngOnInit();
this._renderPages();
// ๅฝ้
ๅ
TranslateHelper.languageChangEvent.subscribe(langInfo => {
this._translateService.use(langInfo.curLang);
if (this._pageSizeOptions instanceof Array && this._pageSizeOptions.length) {
this.pageSizeOptions = this._pageSizeOptions.reduce((arr, option) => {
arr.push(option.value);
return arr;
}, []);
}
if (this._$pageSize) {
this._$pageSize = {
value: this._$pageSize.value,
label: this._$pageSize.value + "/" + this._translateService.instant("pagination.page")
};
}
});
}
ngAfterViewInit() {
this._pages.changes.subscribe(() => {
this.runMicrotask(() => {
//ไนๅ็ไธไบ้กตๅไธไบ้กตๆ้ฎๅฑ
็ถๆๆฎ็
this._pages.forEach(page => {
page.showPrev = false;
page.showNext = false;
page.current = false;
page._changeDetectorRef.markForCheck();
});
// ้่ฆ็จๅฐPageItem็ปไปถ
this._updatePageItems();
});
});
}
}
/**
* @internal
*/
@Component({
selector: "jigsaw-paging-item, j-paging-item",
templateUrl: "pagination-item.html",
host: {
"(click)": "_onClick()",
"[class.jigsaw-page-current]": "current",
"[class.jigsaw-page-item]": "true"
},
changeDetection: ChangeDetectionStrategy.OnPush
})
export class JigsawPagingItem {
public current: boolean = false;
public showPrev: boolean = false;
public showNext: boolean = false;
private _pagination: JigsawPagination;
/**
* @NoMarkForCheckRequired
*/
@Input()
public pageNumber: number;
constructor(@Optional() pagination: JigsawPagination,
/**
* @internal
*/
public _changeDetectorRef: ChangeDetectorRef) {
this._pagination = pagination;
}
/**
* @internal
*/
public _onClick(): void {
if (!this.current) {
this._pagination.current = this.pageNumber;
this._changeDetectorRef.markForCheck();
}
}
/**
* @internal
*/
public _prevPages(): void {
event.stopPropagation();
this._pagination.pagesPrev();
}
/**
* @internal
*/
public _nextPages(): void {
event.stopPropagation();
this._pagination.pagesNext();
}
}
@NgModule({
imports: [
CommonModule,
FormsModule,
JigsawSelectModule,
JigsawInputModule,
JigsawSearchInputModule,
TranslateModule.forChild()
],
declarations: [JigsawPagination, JigsawPagingItem],
exports: [JigsawPagination],
providers: [TranslateService]
})
export class JigsawPaginationModule {
constructor(translateService: TranslateService) {
InternalUtils.initI18n(translateService, "pagination", {
zh: {
page: "้กต",
goto: "ๅๅพ"
},
en: {
page: "Page",
goto: "Goto"
}
});
translateService.setDefaultLang(translateService.getBrowserLang());
}
} | the_stack |
import { HTMLElement, TextNode, HTMLDocument, HTMLComment, Node } from "../../chef/html/html";
import { ValueTypes } from "../../chef/javascript/components/value/value";
import { VariableReference } from "../../chef/javascript/components/value/expression";
import { aliasVariables, cloneAST } from "../../chef/javascript/utils/variables";
import { NodeData } from "../template";
import { ForIteratorExpression } from "../../chef/javascript/components/statements/for";
import { inbuiltTypes, IType } from "../../chef/javascript/utils/types";
import { Component } from "../../component";
const dataVariable = new VariableReference("data");
export type ServerRenderChunk = string
| ConditionalServerRenderExpression
| LoopServerRenderExpression
| ServerRenderExpression
| FunctionCallServerRenderExpression;
export type ServerRenderedChunks = Array<ServerRenderChunk>;
export interface IServerRenderSettings {
minify: boolean,
addDisableToElementWithEvents: boolean
}
export interface ServerRenderExpression {
value: ValueTypes,
escape: boolean
}
export interface FunctionCallServerRenderExpression {
component: Component,
args: Map<
string, [ServerRenderChunk | ServerRenderedChunks | { argument: ValueTypes }, IType]
>
}
export interface ConditionalServerRenderExpression {
condition: ValueTypes,
truthyRenderExpression: ServerRenderedChunks,
falsyRenderExpression: ServerRenderedChunks
}
export interface LoopServerRenderExpression {
subject: ValueTypes,
variable: string,
childRenderExpression: ServerRenderedChunks
}
function addChunk(chunk: ServerRenderChunk, chunks: Array<ServerRenderChunk>) {
if (typeof chunk === "string" && chunks.length > 0 && typeof chunks[chunks.length - 1] === "string") {
chunks[chunks.length - 1] += chunk;
} else {
chunks.push(chunk);
}
}
/**
* Builds parts to build up the template literal
* TODO generator ???
*/
export function serverRenderPrismNode(
element: Node | HTMLDocument,
nodeData: WeakMap<Node, NodeData>,
serverRenderSettings: IServerRenderSettings,
locals: Array<VariableReference> = [],
skipOverServerExpression: boolean = false,
aliasWithDataVariable: boolean = true
): ServerRenderedChunks {
const chunks: ServerRenderedChunks = []; // Entries is unique for each execution for indentation benefits
if (element instanceof HTMLElement) {
const elementData = nodeData.get(element);
if (elementData?.slotFor) {
addChunk({ value: new VariableReference(`${elementData?.slotFor}Slot`), escape: false }, chunks);
return chunks;
}
// If node
if (elementData?.conditionalExpression && !skipOverServerExpression) {
const truthyRenderExpression = serverRenderPrismNode(element, nodeData, serverRenderSettings, locals, true, aliasWithDataVariable);
const falsyRenderExpression = serverRenderPrismNode(elementData.elseElement!, nodeData, serverRenderSettings, locals, false, aliasWithDataVariable);
let serverAliasedExpression = elementData.conditionalExpression;
if (aliasWithDataVariable) {
serverAliasedExpression = cloneAST(serverAliasedExpression);
aliasVariables(serverAliasedExpression, dataVariable, locals);
}
return [{
condition: serverAliasedExpression,
truthyRenderExpression,
falsyRenderExpression,
}];
}
if (elementData?.component) {
const component = elementData.component;
// Components data
const componentsData: ValueTypes | null = elementData.dynamicAttributes?.get("data") ?? null;
// A render function for a component goes attributes, componentData, contentSlot, ...context. With all of those being optional apart from contentSlot
const renderArgs: Map<
string,
[
ServerRenderedChunks | ServerRenderChunk | { argument: ValueTypes },
IType
]
> = new Map();
renderArgs.set(
"attributes",
[
element.attributes ? serverRenderNodeAttribute(element, nodeData, locals, aliasWithDataVariable) : [],
inbuiltTypes.get("string")!
]
);
if (component.hasSlots) {
const slotRenderFunction: ServerRenderedChunks = [];
if (element.children.length > 0) {
for (let i = 0; i < element.children.length; i++) {
const child = element.children[i];
slotRenderFunction.push(
...serverRenderPrismNode(
child,
nodeData,
serverRenderSettings,
locals,
skipOverServerExpression,
aliasWithDataVariable
)
);
if (!serverRenderSettings.minify && i !== element.children.length - 1) chunks.push("\n");
}
}
renderArgs.set("contentSlot", [slotRenderFunction, inbuiltTypes.get("string")!]);
}
if (componentsData) {
if (aliasWithDataVariable) {
const aliasedData: ValueTypes = cloneAST(componentsData);
aliasVariables(aliasedData, dataVariable, locals)
renderArgs.set("data", [{ argument: aliasedData }, component.componentDataType!]);
} else {
renderArgs.set("data", [{ argument: componentsData }, component.componentDataType!]);
}
}
if (component.clientGlobals) {
for (const clientGlobal of component.clientGlobals) {
renderArgs.set(
(clientGlobal[0].tail as VariableReference).name,
[
{ argument: clientGlobal[0] },
null!, // TODO :/
]
);
}
}
chunks.push({
component,
args: renderArgs
});
return chunks;
}
addChunk(`<${element.tagName}`, chunks);
serverRenderNodeAttribute(element, nodeData, locals, aliasWithDataVariable).forEach(chunk => addChunk(chunk, chunks), aliasWithDataVariable);
// If the element has any events disable it by default TODO explain why
if (serverRenderSettings.addDisableToElementWithEvents && elementData?.events?.some(event => event.required)) {
addChunk(" disabled", chunks)
}
if (element.closesSelf) addChunk("/", chunks);
addChunk(">", chunks);
if (!serverRenderSettings.minify && element.children.length > 0) addChunk("\n ", chunks);
if (HTMLElement.selfClosingTags.has(element.tagName) || element.closesSelf) return chunks;
if (elementData?.iteratorExpression) {
let serverAliasedExpression: ForIteratorExpression = elementData.iteratorExpression;
if (aliasWithDataVariable) {
serverAliasedExpression = cloneAST(serverAliasedExpression);
aliasVariables(serverAliasedExpression, dataVariable, locals);
}
addChunk({
subject: serverAliasedExpression.subject,
variable: serverAliasedExpression.variable.name,
childRenderExpression: serverRenderPrismNode(
element.children[0],
nodeData,
serverRenderSettings,
[serverAliasedExpression.variable.toReference(), ...locals],
skipOverServerExpression,
aliasWithDataVariable
)
}, chunks)
} else if (elementData?.rawInnerHTML) {
let aliasedRawInnerHTML: ValueTypes = elementData?.rawInnerHTML;
if (aliasWithDataVariable) {
aliasedRawInnerHTML = cloneAST(aliasedRawInnerHTML);
aliasVariables(aliasedRawInnerHTML, dataVariable, locals);
}
addChunk({
value: aliasedRawInnerHTML,
escape: false
}, chunks);
} else {
for (const child of element.children) {
const parts = serverRenderPrismNode(
child,
nodeData,
serverRenderSettings,
locals,
skipOverServerExpression,
aliasWithDataVariable
);
// Indent children
if (!serverRenderSettings.minify) {
for (let i = 0; i < parts.length; i++) {
if (typeof parts[i] === "string" && (parts[i] as string).startsWith("\n")) {
parts[i] = parts[i] + " ".repeat(4);
}
}
// Comments
if (child.next) {
const isFragment =
(child instanceof HTMLComment && nodeData.get(child)?.isFragment && child.next instanceof TextNode) ||
(child instanceof TextNode && child.next instanceof HTMLComment && (nodeData.get(child.next)?.isFragment));
if (!isFragment) {
parts.push("\n" + " ".repeat(4));
}
}
}
parts.forEach(part => addChunk(part, chunks));
}
}
if (!serverRenderSettings.minify && element.children.length > 0) addChunk("\n", chunks);
addChunk(`</${element.tagName}>`, chunks);
} else if (element instanceof TextNode) {
const value = nodeData.get(element)?.textNodeValue;
if (value) {
if (aliasWithDataVariable) {
const aliasedPart = cloneAST(value);
aliasVariables(aliasedPart, dataVariable, locals);
addChunk({ value: aliasedPart, escape: true }, chunks);
} else {
addChunk({ value, escape: true }, chunks);
}
} else {
addChunk(element.text, chunks);
}
} else if (element instanceof HTMLComment) {
// If the comment is used to fragment text nodes:
if (nodeData.get(element)?.isFragment) {
addChunk(`<!--${element.comment}-->`, chunks);
}
} else if (element instanceof HTMLDocument) {
for (let i = 0; i < element.children.length; i++) {
const child = element.children[i];
serverRenderPrismNode(
child,
nodeData,
serverRenderSettings,
locals,
skipOverServerExpression,
aliasWithDataVariable
).forEach(chunk => addChunk(chunk, chunks));
if (!serverRenderSettings.minify && i !== element.children.length - 1) addChunk("\n", chunks);
}
} else {
throw Error(`Cannot build render string from construct ${(element as any).constructor.name}`)
}
return chunks;
}
export function serverRenderNodeAttribute(
element: HTMLElement,
nodeData: WeakMap<Node, NodeData>,
locals: Array<VariableReference>,
aliasWithDataVariable: boolean = true
) {
const chunks: ServerRenderedChunks = [];
if (element.attributes) {
for (const [name, value] of element.attributes) {
addChunk(" " + name, chunks);
if (value !== null) {
addChunk(`="${value}"`, chunks)
}
}
}
const rawAttribute = nodeData.get(element)?.rawAttribute;
if (rawAttribute) {
addChunk(" ", chunks);
addChunk({ value: rawAttribute, escape: false }, chunks);
}
const dynamicAttributes = nodeData.get(element)?.dynamicAttributes;
if (dynamicAttributes) {
for (let [name, value] of dynamicAttributes) {
if (aliasWithDataVariable) {
value = cloneAST(value);
aliasVariables(value, dataVariable, locals);
}
if (HTMLElement.booleanAttributes.has(name)) {
addChunk({
condition: value,
truthyRenderExpression: [" " + name],
falsyRenderExpression: [""]
}, chunks);
} else {
if (name === "data") continue;
addChunk(" " + name, chunks);
if (value !== null) {
addChunk(`="`, chunks);
addChunk({ value, escape: true }, chunks);
addChunk(`"`, chunks);
}
}
}
}
return chunks;
} | the_stack |
import * as _ from 'lodash';
import {
Component,
ElementRef,
EventEmitter,
HostListener,
Injector,
OnDestroy,
OnInit,
Output,
ViewChild
} from '@angular/core';
import {StringUtil} from '@common/util/string.util';
import {AbstractComponent} from '@common/component/abstract.component';
import {FieldRole, IngestionRuleType, LogicalType} from '@domain/datasource/datasource';
import {ColumnSelectBoxComponent} from './column-select-box.component';
@Component({
selector: 'add-column-component',
templateUrl: './add-column.component.html'
})
export class AddColumnComponent extends AbstractComponent implements OnInit, OnDestroy {
@ViewChild('latitude_select')
private readonly _latitudeSelectComponent: ColumnSelectBoxComponent;
@ViewChild('longitude_select')
private readonly _longitudeSelectComponent: ColumnSelectBoxComponent;
// column list
private _columnList: any;
// method list
public methodTypeList: any = [
{
label: this.translateService.instant('msg.storage.ui.list.geo.point'),
icon: 'ddp-icon-type-point',
value: LogicalType.GEO_POINT
},
// {label: this.translateService.instant('msg.storage.ui.list.geo.line'), icon: 'ddp-icon-type-line', value: LogicalType.GEO_LINE},
// {label: this.translateService.instant('msg.storage.ui.list.geo.polygon'), icon: 'ddp-icon-type-polygon', value: LogicalType.GEO_POLYGON},
{
label: this.translateService.instant('msg.storage.ui.list.expression'),
icon: 'ddp-icon-type-expression',
value: LogicalType.USER_DEFINED
}
];
// selected method type
public selectedMethodType: any = {
label: this.translateService.instant('msg.storage.ui.list.geo.point'),
icon: 'ddp-icon-type-point',
value: LogicalType.GEO_POINT
};
// method type show flag
public isMethodTypeListShow: boolean = false;
// latitude column list
public latitudeColumnList: any = [];
// selected latitude column
public selectedLatitudeColumn: any;
// latitude column valid error
public latitudeColumnValid: boolean;
// longitude column list
public longitudeColumnList: any = [];
// selected longitude column
public selectedLongitudeColumn: any;
// longitude column valid error
public longitudeColumnValid: boolean;
// column name
public columnName: string;
// column name invalid message
public columnNameInvalidMessage: string;
// column name valid error
public columnNameValid: boolean;
// expression
public expression: string;
// expression invalid message
public expressionInvalidMessage: string;
// expression valid error
public expressionValid: boolean;
// output event
@Output()
public addedColumn: EventEmitter<any> = new EventEmitter();
// constructor
constructor(protected element: ElementRef,
protected injector: Injector) {
super(element, injector);
}
/**
* ngOnInit
*/
public ngOnInit() {
super.ngOnInit();
}
/**
* ngOnDestroy
*/
public ngOnDestroy() {
super.ngOnDestroy();
}
/**
* Window resize
* @param _event
*/
@HostListener('window:resize', ['$event'])
public onResize(_event) {
// #1925
this.closeSelectBoxes();
}
/**
* Close select box
*/
public closeSelectBoxes(): void {
if (this.isMethodTypeListShow === true) {
this.isMethodTypeListShow = false;
}
if (this.selectedMethodType.value !== 'user_defined') {
if (this._latitudeSelectComponent && this._latitudeSelectComponent.isListShow === true) {
this._latitudeSelectComponent.isListShow = false;
} else if (this._longitudeSelectComponent && this._longitudeSelectComponent.isListShow === true) {
this._longitudeSelectComponent.isListShow = false;
}
}
}
/**
* Init
* @param columnList
*/
public init(columnList: any): void {
// set column list
this.longitudeColumnList = this.latitudeColumnList = this._columnList = _.filter(columnList, column => !column.unloaded && !column.derived);
// if exist longitude column
if (this.selectedLongitudeColumn) {
// set latitude column list
this.latitudeColumnList = this._columnList.filter(column => column.name !== this.selectedLongitudeColumn.name);
// if unloaded column
if (this.selectedLongitudeColumn.unloaded) {
// init selected longitude column
this.selectedLongitudeColumn = null;
}
}
// if exist latitude column
if (this.selectedLatitudeColumn) {
// set longitude column list
this.longitudeColumnList = this._columnList.filter(column => column.name !== this.selectedLatitudeColumn.name);
// if unloaded column
if (this.selectedLatitudeColumn.unloaded) {
// init selected latitude column
this.selectedLatitudeColumn = null;
}
}
}
/**
* Close
*/
public close(): void {
this.addedColumn.emit();
}
/**
* Add
*/
public onClickAdd(): void {
// if enable add
if (this._isEnableAddColumn()) {
// add column
this.addedColumn.emit(this._makeColumn());
// init view
this._initView();
}
}
/**
* Method type change event
* @param type
*/
public onChangeSelectedMethodType(type: any): void {
// if change type
if (type.value !== this.selectedMethodType.value) {
// set selected method type
this.selectedMethodType = type;
}
}
/**
* Latitude column change event
* @param column
*/
public onChangeSelectedLatitudeColumn(column: any): void {
// if not exist selected latitude column or different column
if (!this.selectedLatitudeColumn || this.selectedLatitudeColumn.name !== column.name) {
// set longitude column list
this.longitudeColumnList = _.filter(this._columnList, item => column.name !== item.name);
// set selected latitude column
this.selectedLatitudeColumn = column;
// set valid
this.latitudeColumnValid = true;
}
}
/**
* Longitude column change event
* @param column
*/
public onChangeSelectedLongitudeColumn(column: any): void {
// if not exist selected longitude column or different column
if (!this.selectedLongitudeColumn || this.selectedLongitudeColumn.name !== column.name) {
// set latitude column list
this.latitudeColumnList = _.filter(this._columnList, item => column.name !== item.name);
// set selected latitude column
this.selectedLongitudeColumn = column;
// set valid
this.longitudeColumnValid = true;
}
}
/**
* Column name focus out event
*/
public onFocusOutColumnNameField(): void {
// check column name valid
this._checkColumnNameValid();
}
/**
* Expression focus out event
*/
public onFocusOutExpressionField(): void {
// check expression valid
this._checkExpressionValid();
}
/**
* Init UI
* @private
*/
private _initView(): void {
// init column
this.columnName = '';
this.columnNameValid = null;
// init expression
this.expression = '';
this.expressionValid = null;
// init column
this.selectedLatitudeColumn = null;
this.latitudeColumnValid = null;
this.selectedLongitudeColumn = null;
this.longitudeColumnValid = null;
// init selected method type
this.selectedMethodType = this.methodTypeList[0];
}
/**
* Is enable add column
* @returns {boolean}
* @private
*/
private _isEnableAddColumn(): boolean {
// check name valid
this._checkColumnNameValid();
// if method type expression
if (this.selectedMethodType.value === LogicalType.USER_DEFINED) {
// check expression valid
this._checkExpressionValid();
// return
return this.columnNameValid && this.expressionValid;
} else {
// check column valid
this._checkGeoColumnValid();
// return
return this.columnNameValid && this.latitudeColumnValid && this.longitudeColumnValid;
}
}
/**
* Check column name valid
* @private
*/
private _checkColumnNameValid(): void {
// is empty
if (StringUtil.isEmpty(this.columnName)) {
// set invalid message
this.columnNameInvalidMessage = this.translateService.instant('msg.storage.ui.required');
// set valid error
this.columnNameValid = false;
// return
return;
}
// duplicated name
if (_.some(this._columnList, column => this.columnName.trim() === column.name)) {
// set invalid message
this.columnNameInvalidMessage = this.translateService.instant('msg.storage.ui.duplicated');
// set valid error
this.columnNameValid = false;
// return
return;
}
// set valid
this.columnNameValid = true;
}
/**
* Check expression valid
* @private
*/
private _checkExpressionValid(): void {
// is empty
if (StringUtil.isEmpty(this.expression)) {
// set invalid message
this.expressionInvalidMessage = this.translateService.instant('msg.storage.ui.required');
// set valid error
this.expressionValid = false;
// return
return;
}
// set valid
this.expressionValid = true;
}
/**
* Check geo column valid
* @private
*/
private _checkGeoColumnValid(): void {
// if empty latitude column
if (!this.selectedLatitudeColumn) {
// set valid error
this.latitudeColumnValid = false;
}
// if empty longitude column
if (!this.selectedLongitudeColumn) {
// set valid error
this.longitudeColumnValid = false;
}
}
/**
* Make column
* @returns {Object}
* @private
*/
private _makeColumn(): object {
const column = {
name: this.columnName.trim(),
derived: true,
role: FieldRole.DIMENSION,
ingestionRule: {
type: IngestionRuleType.DEFAULT
},
derivationRule: {
type: this.selectedMethodType.value.toLowerCase()
}
};
// if method type Expression
if (this.selectedMethodType.value === LogicalType.USER_DEFINED) {
column['type'] = LogicalType.STRING;
column['logicalType'] = LogicalType.STRING;
column.derivationRule['expr'] = this.expression.trim();
} else { // if method type not Expression
column['type'] = LogicalType.STRUCT;
column['logicalType'] = this.selectedMethodType.value;
// add format
column['format'] = {
type: this.selectedMethodType.value.toLowerCase(),
originalSrsName: 'EPSG:4326'
};
column.derivationRule['latField'] = this.selectedLatitudeColumn.name;
column.derivationRule['lonField'] = this.selectedLongitudeColumn.name;
}
return column;
}
} | the_stack |
import { Z80Tester } from "./z80-tester";
describe("Disassembler - bit instructions", function () {
this.timeout(10000);
it("Bit instructions 0x00-0x0F work as expected", async () => {
// --- Act
await Z80Tester.Test("rlc b", 0xcb, 0x00);
await Z80Tester.Test("rlc c", 0xcb, 0x01);
await Z80Tester.Test("rlc d", 0xcb, 0x02);
await Z80Tester.Test("rlc e", 0xcb, 0x03);
await Z80Tester.Test("rlc h", 0xcb, 0x04);
await Z80Tester.Test("rlc l", 0xcb, 0x05);
await Z80Tester.Test("rlc (hl)", 0xcb, 0x06);
await Z80Tester.Test("rlc a", 0xcb, 0x07);
await Z80Tester.Test("rrc b", 0xcb, 0x08);
await Z80Tester.Test("rrc c", 0xcb, 0x09);
await Z80Tester.Test("rrc d", 0xcb, 0x0a);
await Z80Tester.Test("rrc e", 0xcb, 0x0b);
await Z80Tester.Test("rrc h", 0xcb, 0x0c);
await Z80Tester.Test("rrc l", 0xcb, 0x0d);
await Z80Tester.Test("rrc (hl)", 0xcb, 0x0e);
await Z80Tester.Test("rrc a", 0xcb, 0x0f);
});
it("Bit instructions 0x10-0x1F work as expected", async () => {
// --- Act
await Z80Tester.Test("rl b", 0xcb, 0x10);
await Z80Tester.Test("rl c", 0xcb, 0x11);
await Z80Tester.Test("rl d", 0xcb, 0x12);
await Z80Tester.Test("rl e", 0xcb, 0x13);
await Z80Tester.Test("rl h", 0xcb, 0x14);
await Z80Tester.Test("rl l", 0xcb, 0x15);
await Z80Tester.Test("rl (hl)", 0xcb, 0x16);
await Z80Tester.Test("rl a", 0xcb, 0x17);
await Z80Tester.Test("rr b", 0xcb, 0x18);
await Z80Tester.Test("rr c", 0xcb, 0x19);
await Z80Tester.Test("rr d", 0xcb, 0x1a);
await Z80Tester.Test("rr e", 0xcb, 0x1b);
await Z80Tester.Test("rr h", 0xcb, 0x1c);
await Z80Tester.Test("rr l", 0xcb, 0x1d);
await Z80Tester.Test("rr (hl)", 0xcb, 0x1e);
await Z80Tester.Test("rr a", 0xcb, 0x1f);
});
it("Bit instructions 0x20-0x2F work as expected", async () => {
// --- Act
await Z80Tester.Test("sla b", 0xcb, 0x20);
await Z80Tester.Test("sla c", 0xcb, 0x21);
await Z80Tester.Test("sla d", 0xcb, 0x22);
await Z80Tester.Test("sla e", 0xcb, 0x23);
await Z80Tester.Test("sla h", 0xcb, 0x24);
await Z80Tester.Test("sla l", 0xcb, 0x25);
await Z80Tester.Test("sla (hl)", 0xcb, 0x26);
await Z80Tester.Test("sla a", 0xcb, 0x27);
await Z80Tester.Test("sra b", 0xcb, 0x28);
await Z80Tester.Test("sra c", 0xcb, 0x29);
await Z80Tester.Test("sra d", 0xcb, 0x2a);
await Z80Tester.Test("sra e", 0xcb, 0x2b);
await Z80Tester.Test("sra h", 0xcb, 0x2c);
await Z80Tester.Test("sra l", 0xcb, 0x2d);
await Z80Tester.Test("sra (hl)", 0xcb, 0x2e);
await Z80Tester.Test("sra a", 0xcb, 0x2f);
});
it("Bit instructions 0x30-0x3F work as expected", async () => {
// --- Act
await Z80Tester.Test("sll b", 0xcb, 0x30);
await Z80Tester.Test("sll c", 0xcb, 0x31);
await Z80Tester.Test("sll d", 0xcb, 0x32);
await Z80Tester.Test("sll e", 0xcb, 0x33);
await Z80Tester.Test("sll h", 0xcb, 0x34);
await Z80Tester.Test("sll l", 0xcb, 0x35);
await Z80Tester.Test("sll (hl)", 0xcb, 0x36);
await Z80Tester.Test("sll a", 0xcb, 0x37);
await Z80Tester.Test("srl b", 0xcb, 0x38);
await Z80Tester.Test("srl c", 0xcb, 0x39);
await Z80Tester.Test("srl d", 0xcb, 0x3a);
await Z80Tester.Test("srl e", 0xcb, 0x3b);
await Z80Tester.Test("srl h", 0xcb, 0x3c);
await Z80Tester.Test("srl l", 0xcb, 0x3d);
await Z80Tester.Test("srl (hl)", 0xcb, 0x3e);
await Z80Tester.Test("srl a", 0xcb, 0x3f);
});
it("Bit instructions 0x40-0x4F work as expected", async () => {
// --- Act
await Z80Tester.Test("bit 0,b", 0xcb, 0x40);
await Z80Tester.Test("bit 0,c", 0xcb, 0x41);
await Z80Tester.Test("bit 0,d", 0xcb, 0x42);
await Z80Tester.Test("bit 0,e", 0xcb, 0x43);
await Z80Tester.Test("bit 0,h", 0xcb, 0x44);
await Z80Tester.Test("bit 0,l", 0xcb, 0x45);
await Z80Tester.Test("bit 0,(hl)", 0xcb, 0x46);
await Z80Tester.Test("bit 0,a", 0xcb, 0x47);
await Z80Tester.Test("bit 1,b", 0xcb, 0x48);
await Z80Tester.Test("bit 1,c", 0xcb, 0x49);
await Z80Tester.Test("bit 1,d", 0xcb, 0x4a);
await Z80Tester.Test("bit 1,e", 0xcb, 0x4b);
await Z80Tester.Test("bit 1,h", 0xcb, 0x4c);
await Z80Tester.Test("bit 1,l", 0xcb, 0x4d);
await Z80Tester.Test("bit 1,(hl)", 0xcb, 0x4e);
await Z80Tester.Test("bit 1,a", 0xcb, 0x4f);
});
it("Bit instructions 0x50-0x5F work as expected", async () => {
// --- Act
await Z80Tester.Test("bit 2,b", 0xcb, 0x50);
await Z80Tester.Test("bit 2,c", 0xcb, 0x51);
await Z80Tester.Test("bit 2,d", 0xcb, 0x52);
await Z80Tester.Test("bit 2,e", 0xcb, 0x53);
await Z80Tester.Test("bit 2,h", 0xcb, 0x54);
await Z80Tester.Test("bit 2,l", 0xcb, 0x55);
await Z80Tester.Test("bit 2,(hl)", 0xcb, 0x56);
await Z80Tester.Test("bit 2,a", 0xcb, 0x57);
await Z80Tester.Test("bit 3,b", 0xcb, 0x58);
await Z80Tester.Test("bit 3,c", 0xcb, 0x59);
await Z80Tester.Test("bit 3,d", 0xcb, 0x5a);
await Z80Tester.Test("bit 3,e", 0xcb, 0x5b);
await Z80Tester.Test("bit 3,h", 0xcb, 0x5c);
await Z80Tester.Test("bit 3,l", 0xcb, 0x5d);
await Z80Tester.Test("bit 3,(hl)", 0xcb, 0x5e);
await Z80Tester.Test("bit 3,a", 0xcb, 0x5f);
});
it("Bit instructions 0x60-0x6F work as expected", async () => {
// --- Act
await Z80Tester.Test("bit 4,b", 0xcb, 0x60);
await Z80Tester.Test("bit 4,c", 0xcb, 0x61);
await Z80Tester.Test("bit 4,d", 0xcb, 0x62);
await Z80Tester.Test("bit 4,e", 0xcb, 0x63);
await Z80Tester.Test("bit 4,h", 0xcb, 0x64);
await Z80Tester.Test("bit 4,l", 0xcb, 0x65);
await Z80Tester.Test("bit 4,(hl)", 0xcb, 0x66);
await Z80Tester.Test("bit 4,a", 0xcb, 0x67);
await Z80Tester.Test("bit 5,b", 0xcb, 0x68);
await Z80Tester.Test("bit 5,c", 0xcb, 0x69);
await Z80Tester.Test("bit 5,d", 0xcb, 0x6a);
await Z80Tester.Test("bit 5,e", 0xcb, 0x6b);
await Z80Tester.Test("bit 5,h", 0xcb, 0x6c);
await Z80Tester.Test("bit 5,l", 0xcb, 0x6d);
await Z80Tester.Test("bit 5,(hl)", 0xcb, 0x6e);
await Z80Tester.Test("bit 5,a", 0xcb, 0x6f);
});
it("Bit instructions 0x70-0x7F work as expected", async () => {
// --- Act
await Z80Tester.Test("bit 6,b", 0xcb, 0x70);
await Z80Tester.Test("bit 6,c", 0xcb, 0x71);
await Z80Tester.Test("bit 6,d", 0xcb, 0x72);
await Z80Tester.Test("bit 6,e", 0xcb, 0x73);
await Z80Tester.Test("bit 6,h", 0xcb, 0x74);
await Z80Tester.Test("bit 6,l", 0xcb, 0x75);
await Z80Tester.Test("bit 6,(hl)", 0xcb, 0x76);
await Z80Tester.Test("bit 6,a", 0xcb, 0x77);
await Z80Tester.Test("bit 7,b", 0xcb, 0x78);
await Z80Tester.Test("bit 7,c", 0xcb, 0x79);
await Z80Tester.Test("bit 7,d", 0xcb, 0x7a);
await Z80Tester.Test("bit 7,e", 0xcb, 0x7b);
await Z80Tester.Test("bit 7,h", 0xcb, 0x7c);
await Z80Tester.Test("bit 7,l", 0xcb, 0x7d);
await Z80Tester.Test("bit 7,(hl)", 0xcb, 0x7e);
await Z80Tester.Test("bit 7,a", 0xcb, 0x7f);
});
it("Bit instructions 0x80-0x8F work as expected", async () => {
// --- Act
await Z80Tester.Test("res 0,b", 0xcb, 0x80);
await Z80Tester.Test("res 0,c", 0xcb, 0x81);
await Z80Tester.Test("res 0,d", 0xcb, 0x82);
await Z80Tester.Test("res 0,e", 0xcb, 0x83);
await Z80Tester.Test("res 0,h", 0xcb, 0x84);
await Z80Tester.Test("res 0,l", 0xcb, 0x85);
await Z80Tester.Test("res 0,(hl)", 0xcb, 0x86);
await Z80Tester.Test("res 0,a", 0xcb, 0x87);
await Z80Tester.Test("res 1,b", 0xcb, 0x88);
await Z80Tester.Test("res 1,c", 0xcb, 0x89);
await Z80Tester.Test("res 1,d", 0xcb, 0x8a);
await Z80Tester.Test("res 1,e", 0xcb, 0x8b);
await Z80Tester.Test("res 1,h", 0xcb, 0x8c);
await Z80Tester.Test("res 1,l", 0xcb, 0x8d);
await Z80Tester.Test("res 1,(hl)", 0xcb, 0x8e);
await Z80Tester.Test("res 1,a", 0xcb, 0x8f);
});
it("Bit instructions 0x90-0x9F work as expected", async () => {
// --- Act
await Z80Tester.Test("res 2,b", 0xcb, 0x90);
await Z80Tester.Test("res 2,c", 0xcb, 0x91);
await Z80Tester.Test("res 2,d", 0xcb, 0x92);
await Z80Tester.Test("res 2,e", 0xcb, 0x93);
await Z80Tester.Test("res 2,h", 0xcb, 0x94);
await Z80Tester.Test("res 2,l", 0xcb, 0x95);
await Z80Tester.Test("res 2,(hl)", 0xcb, 0x96);
await Z80Tester.Test("res 2,a", 0xcb, 0x97);
await Z80Tester.Test("res 3,b", 0xcb, 0x98);
await Z80Tester.Test("res 3,c", 0xcb, 0x99);
await Z80Tester.Test("res 3,d", 0xcb, 0x9a);
await Z80Tester.Test("res 3,e", 0xcb, 0x9b);
await Z80Tester.Test("res 3,h", 0xcb, 0x9c);
await Z80Tester.Test("res 3,l", 0xcb, 0x9d);
await Z80Tester.Test("res 3,(hl)", 0xcb, 0x9e);
await Z80Tester.Test("res 3,a", 0xcb, 0x9f);
});
it("Bit instructions 0xA0-0xAF work as expected", async () => {
// --- Act
await Z80Tester.Test("res 4,b", 0xcb, 0xa0);
await Z80Tester.Test("res 4,c", 0xcb, 0xa1);
await Z80Tester.Test("res 4,d", 0xcb, 0xa2);
await Z80Tester.Test("res 4,e", 0xcb, 0xa3);
await Z80Tester.Test("res 4,h", 0xcb, 0xa4);
await Z80Tester.Test("res 4,l", 0xcb, 0xa5);
await Z80Tester.Test("res 4,(hl)", 0xcb, 0xa6);
await Z80Tester.Test("res 4,a", 0xcb, 0xa7);
await Z80Tester.Test("res 5,b", 0xcb, 0xa8);
await Z80Tester.Test("res 5,c", 0xcb, 0xa9);
await Z80Tester.Test("res 5,d", 0xcb, 0xaa);
await Z80Tester.Test("res 5,e", 0xcb, 0xab);
await Z80Tester.Test("res 5,h", 0xcb, 0xac);
await Z80Tester.Test("res 5,l", 0xcb, 0xad);
await Z80Tester.Test("res 5,(hl)", 0xcb, 0xae);
await Z80Tester.Test("res 5,a", 0xcb, 0xaf);
});
it("Bit instructions 0xB0-0xBF work as expected", async () => {
// --- Act
await Z80Tester.Test("res 6,b", 0xcb, 0xb0);
await Z80Tester.Test("res 6,c", 0xcb, 0xb1);
await Z80Tester.Test("res 6,d", 0xcb, 0xb2);
await Z80Tester.Test("res 6,e", 0xcb, 0xb3);
await Z80Tester.Test("res 6,h", 0xcb, 0xb4);
await Z80Tester.Test("res 6,l", 0xcb, 0xb5);
await Z80Tester.Test("res 6,(hl)", 0xcb, 0xb6);
await Z80Tester.Test("res 6,a", 0xcb, 0xb7);
await Z80Tester.Test("res 7,b", 0xcb, 0xb8);
await Z80Tester.Test("res 7,c", 0xcb, 0xb9);
await Z80Tester.Test("res 7,d", 0xcb, 0xba);
await Z80Tester.Test("res 7,e", 0xcb, 0xbb);
await Z80Tester.Test("res 7,h", 0xcb, 0xbc);
await Z80Tester.Test("res 7,l", 0xcb, 0xbd);
await Z80Tester.Test("res 7,(hl)", 0xcb, 0xbe);
await Z80Tester.Test("res 7,a", 0xcb, 0xbf);
});
it("Bit instructions 0xC0-0xCF work as expected", async () => {
// --- Act
await Z80Tester.Test("set 0,b", 0xcb, 0xc0);
await Z80Tester.Test("set 0,c", 0xcb, 0xc1);
await Z80Tester.Test("set 0,d", 0xcb, 0xc2);
await Z80Tester.Test("set 0,e", 0xcb, 0xc3);
await Z80Tester.Test("set 0,h", 0xcb, 0xc4);
await Z80Tester.Test("set 0,l", 0xcb, 0xc5);
await Z80Tester.Test("set 0,(hl)", 0xcb, 0xc6);
await Z80Tester.Test("set 0,a", 0xcb, 0xc7);
await Z80Tester.Test("set 1,b", 0xcb, 0xc8);
await Z80Tester.Test("set 1,c", 0xcb, 0xc9);
await Z80Tester.Test("set 1,d", 0xcb, 0xca);
await Z80Tester.Test("set 1,e", 0xcb, 0xcb);
await Z80Tester.Test("set 1,h", 0xcb, 0xcc);
await Z80Tester.Test("set 1,l", 0xcb, 0xcd);
await Z80Tester.Test("set 1,(hl)", 0xcb, 0xce);
await Z80Tester.Test("set 1,a", 0xcb, 0xcf);
});
it("Bit instructions 0xD0-0xDF work as expected", async () => {
// --- Act
await Z80Tester.Test("set 2,b", 0xcb, 0xd0);
await Z80Tester.Test("set 2,c", 0xcb, 0xd1);
await Z80Tester.Test("set 2,d", 0xcb, 0xd2);
await Z80Tester.Test("set 2,e", 0xcb, 0xd3);
await Z80Tester.Test("set 2,h", 0xcb, 0xd4);
await Z80Tester.Test("set 2,l", 0xcb, 0xd5);
await Z80Tester.Test("set 2,(hl)", 0xcb, 0xd6);
await Z80Tester.Test("set 2,a", 0xcb, 0xd7);
await Z80Tester.Test("set 3,b", 0xcb, 0xd8);
await Z80Tester.Test("set 3,c", 0xcb, 0xd9);
await Z80Tester.Test("set 3,d", 0xcb, 0xda);
await Z80Tester.Test("set 3,e", 0xcb, 0xdb);
await Z80Tester.Test("set 3,h", 0xcb, 0xdc);
await Z80Tester.Test("set 3,l", 0xcb, 0xdd);
await Z80Tester.Test("set 3,(hl)", 0xcb, 0xde);
await Z80Tester.Test("set 3,a", 0xcb, 0xdf);
});
it("Bit instructions 0xE0-0xEF work as expected", async () => {
// --- Act
await Z80Tester.Test("set 4,b", 0xcb, 0xe0);
await Z80Tester.Test("set 4,c", 0xcb, 0xe1);
await Z80Tester.Test("set 4,d", 0xcb, 0xe2);
await Z80Tester.Test("set 4,e", 0xcb, 0xe3);
await Z80Tester.Test("set 4,h", 0xcb, 0xe4);
await Z80Tester.Test("set 4,l", 0xcb, 0xe5);
await Z80Tester.Test("set 4,(hl)", 0xcb, 0xe6);
await Z80Tester.Test("set 4,a", 0xcb, 0xe7);
await Z80Tester.Test("set 5,b", 0xcb, 0xe8);
await Z80Tester.Test("set 5,c", 0xcb, 0xe9);
await Z80Tester.Test("set 5,d", 0xcb, 0xea);
await Z80Tester.Test("set 5,e", 0xcb, 0xeb);
await Z80Tester.Test("set 5,h", 0xcb, 0xec);
await Z80Tester.Test("set 5,l", 0xcb, 0xed);
await Z80Tester.Test("set 5,(hl)", 0xcb, 0xee);
await Z80Tester.Test("set 5,a", 0xcb, 0xef);
});
it("Bit instructions 0xF0-0xFF work as expected", async () => {
// --- Act
await Z80Tester.Test("set 6,b", 0xcb, 0xf0);
await Z80Tester.Test("set 6,c", 0xcb, 0xf1);
await Z80Tester.Test("set 6,d", 0xcb, 0xf2);
await Z80Tester.Test("set 6,e", 0xcb, 0xf3);
await Z80Tester.Test("set 6,h", 0xcb, 0xf4);
await Z80Tester.Test("set 6,l", 0xcb, 0xf5);
await Z80Tester.Test("set 6,(hl)", 0xcb, 0xf6);
await Z80Tester.Test("set 6,a", 0xcb, 0xf7);
await Z80Tester.Test("set 7,b", 0xcb, 0xf8);
await Z80Tester.Test("set 7,c", 0xcb, 0xf9);
await Z80Tester.Test("set 7,d", 0xcb, 0xfa);
await Z80Tester.Test("set 7,e", 0xcb, 0xfb);
await Z80Tester.Test("set 7,h", 0xcb, 0xfc);
await Z80Tester.Test("set 7,l", 0xcb, 0xfd);
await Z80Tester.Test("set 7,(hl)", 0xcb, 0xfe);
await Z80Tester.Test("set 7,a", 0xcb, 0xff);
});
}); | the_stack |
import * as fse from "fs-extra";
import { expect } from "chai";
import path from "./assert_path";
import helper from "./helper";
import * as jetpack from "..";
import { InspectResult } from "../types";
describe("copy", () => {
beforeEach(helper.setCleanTestCwd);
afterEach(helper.switchBackToCorrectCwd);
describe("copies a file", () => {
const preparations = () => {
fse.outputFileSync("file.txt", "abc");
};
const expectations = () => {
path("file.txt").shouldBeFileWithContent("abc");
path("file_copied.txt").shouldBeFileWithContent("abc");
};
it("sync", () => {
preparations();
jetpack.copy("file.txt", "file_copied.txt");
expectations();
});
it("async", done => {
preparations();
jetpack.copyAsync("file.txt", "file_copied.txt").then(() => {
expectations();
done();
});
});
});
describe("can copy file to nonexistent directory (will create directory)", () => {
const preparations = () => {
fse.outputFileSync("file.txt", "abc");
};
const expectations = () => {
path("file.txt").shouldBeFileWithContent("abc");
path("dir/dir/file.txt").shouldBeFileWithContent("abc");
};
it("sync", () => {
preparations();
jetpack.copy("file.txt", "dir/dir/file.txt");
expectations();
});
it("async", done => {
preparations();
jetpack.copyAsync("file.txt", "dir/dir/file.txt").then(() => {
expectations();
done();
});
});
});
describe("copies empty directory", () => {
const preparations = () => {
fse.mkdirsSync("dir");
};
const expectations = () => {
path("copied/dir").shouldBeDirectory();
};
it("sync", () => {
preparations();
jetpack.copy("dir", "copied/dir");
expectations();
});
it("async", done => {
preparations();
jetpack.copyAsync("dir", "copied/dir").then(() => {
expectations();
done();
});
});
});
describe("copies a tree of files", () => {
const preparations = () => {
fse.outputFileSync("a/f1.txt", "abc");
fse.outputFileSync("a/b/f2.txt", "123");
fse.mkdirsSync("a/b/c");
};
const expectations = () => {
path("copied/a/f1.txt").shouldBeFileWithContent("abc");
path("copied/a/b/c").shouldBeDirectory();
path("copied/a/b/f2.txt").shouldBeFileWithContent("123");
};
it("sync", () => {
preparations();
jetpack.copy("a", "copied/a");
expectations();
});
it("async", done => {
preparations();
jetpack.copyAsync("a", "copied/a").then(() => {
expectations();
done();
});
});
});
describe("generates nice error if source path doesn't exist", () => {
const expectations = (err: any) => {
expect(err.code).to.equal("ENOENT");
expect(err.message).to.have.string("Path to copy doesn't exist");
};
it("sync", () => {
try {
jetpack.copy("a", "b");
throw new Error("Expected error to be thrown");
} catch (err) {
expectations(err);
}
});
it("async", done => {
jetpack.copyAsync("a", "b").catch(err => {
expectations(err);
done();
});
});
});
describe("respects internal CWD of jetpack instance", () => {
const preparations = () => {
fse.outputFileSync("a/b.txt", "abc");
};
const expectations = () => {
path("a/b.txt").shouldBeFileWithContent("abc");
path("a/x.txt").shouldBeFileWithContent("abc");
};
it("sync", () => {
const jetContext = jetpack.cwd("a");
preparations();
jetContext.copy("b.txt", "x.txt");
expectations();
});
it("async", done => {
const jetContext = jetpack.cwd("a");
preparations();
jetContext.copyAsync("b.txt", "x.txt").then(() => {
expectations();
done();
});
});
});
describe("overwriting behaviour", () => {
describe("does not overwrite by default", () => {
const preparations = () => {
fse.outputFileSync("a/file.txt", "abc");
fse.mkdirsSync("b");
};
const expectations = (err: any) => {
expect(err.code).to.equal("EEXIST");
expect(err.message).to.have.string("Destination path already exists");
};
it("sync", () => {
preparations();
try {
jetpack.copy("a", "b");
throw new Error("Expected error to be thrown");
} catch (err) {
expectations(err);
}
});
it("async", done => {
preparations();
jetpack.copyAsync("a", "b").catch(err => {
expectations(err);
done();
});
});
});
describe("overwrites if it was specified", () => {
const preparations = () => {
fse.outputFileSync("a/file.txt", "abc");
fse.outputFileSync("b/file.txt", "xyz");
};
const expectations = () => {
path("a/file.txt").shouldBeFileWithContent("abc");
path("b/file.txt").shouldBeFileWithContent("abc");
};
it("sync", () => {
preparations();
jetpack.copy("a", "b", { overwrite: true });
expectations();
});
it("async", done => {
preparations();
jetpack.copyAsync("a", "b", { overwrite: true }).then(() => {
expectations();
done();
});
});
});
describe("overwrites according to what function returns", () => {
const preparations = () => {
fse.outputFileSync("from-here/foo/canada.txt", "abc");
fse.outputFileSync("to-here/foo/canada.txt", "xyz");
fse.outputFileSync("from-here/foo/eh.txt", "abc");
fse.outputFileSync("to-here/foo/eh.txt", "xyz");
};
const expectations = () => {
// canada is copied
path("from-here/foo/canada.txt").shouldBeFileWithContent("abc");
path("to-here/foo/canada.txt").shouldBeFileWithContent("abc");
// eh is not copied
path("from-here/foo/eh.txt").shouldBeFileWithContent("abc");
path("to-here/foo/eh.txt").shouldBeFileWithContent("xyz");
};
const overwrite = (
srcInspectData: InspectResult,
destInspectData: InspectResult
) => {
expect(srcInspectData).to.have.property("name");
expect(srcInspectData).to.have.property("type");
expect(srcInspectData).to.have.property("mode");
expect(srcInspectData).to.have.property("accessTime");
expect(srcInspectData).to.have.property("modifyTime");
expect(srcInspectData).to.have.property("changeTime");
expect(srcInspectData).to.have.property("absolutePath");
expect(destInspectData).to.have.property("name");
expect(destInspectData).to.have.property("type");
expect(destInspectData).to.have.property("mode");
expect(destInspectData).to.have.property("accessTime");
expect(destInspectData).to.have.property("modifyTime");
expect(destInspectData).to.have.property("changeTime");
expect(destInspectData).to.have.property("absolutePath");
return srcInspectData.name.includes("canada");
};
it("sync", () => {
preparations();
jetpack.copy("from-here", "to-here", { overwrite });
expectations();
});
it("async", done => {
preparations();
jetpack.copyAsync("from-here", "to-here", { overwrite }).then(() => {
expectations();
done();
});
});
});
});
describe("async overwrite function can return promise", () => {
const preparations = () => {
fse.outputFileSync("from-here/foo/canada.txt", "abc");
fse.outputFileSync("to-here/foo/canada.txt", "xyz");
fse.outputFileSync("from-here/foo/eh.txt", "123");
fse.outputFileSync("to-here/foo/eh.txt", "456");
};
const expectations = () => {
// canada is copied
path("from-here/foo/canada.txt").shouldBeFileWithContent("abc");
path("to-here/foo/canada.txt").shouldBeFileWithContent("abc");
// eh is not copied
path("from-here/foo/eh.txt").shouldBeFileWithContent("123");
path("to-here/foo/eh.txt").shouldBeFileWithContent("456");
};
const overwrite = (
srcInspectData: InspectResult,
destInspectData: InspectResult
): Promise<boolean> => {
return new Promise((resolve, reject) => {
jetpack.readAsync(srcInspectData.absolutePath).then(data => {
resolve(data === "abc");
});
});
};
it("async", done => {
preparations();
jetpack
.copyAsync("from-here", "to-here", { overwrite })
.then(() => {
expectations();
done();
})
.catch(done);
});
});
describe("filter what to copy", () => {
describe("by simple pattern", () => {
const preparations = () => {
fse.outputFileSync("dir/file.txt", "1");
fse.outputFileSync("dir/file.md", "m1");
fse.outputFileSync("dir/a/file.txt", "2");
fse.outputFileSync("dir/a/file.md", "m2");
};
const expectations = () => {
path("copy/file.txt").shouldBeFileWithContent("1");
path("copy/file.md").shouldNotExist();
path("copy/a/file.txt").shouldBeFileWithContent("2");
path("copy/a/file.md").shouldNotExist();
};
it("sync", () => {
preparations();
jetpack.copy("dir", "copy", { matching: "*.txt" });
expectations();
});
it("async", done => {
preparations();
jetpack.copyAsync("dir", "copy", { matching: "*.txt" }).then(() => {
expectations();
done();
});
});
});
describe("by pattern anchored to copied directory", () => {
const preparations = () => {
fse.outputFileSync("x/y/dir/file.txt", "1");
fse.outputFileSync("x/y/dir/a/file.txt", "2");
fse.outputFileSync("x/y/dir/a/b/file.txt", "3");
};
const expectations = () => {
path("copy/file.txt").shouldNotExist();
path("copy/a/file.txt").shouldBeFileWithContent("2");
path("copy/a/b/file.txt").shouldNotExist();
};
it("sync", () => {
preparations();
jetpack.copy("x/y/dir", "copy", { matching: "a/*.txt" });
expectations();
});
it("async", done => {
preparations();
jetpack
.copyAsync("x/y/dir", "copy", { matching: "a/*.txt" })
.then(() => {
expectations();
done();
});
});
});
describe("can use ./ as indication of anchor directory", () => {
const preparations = () => {
fse.outputFileSync("x/y/a.txt", "123");
fse.outputFileSync("x/y/b/a.txt", "456");
};
const expectations = () => {
path("copy/a.txt").shouldBeFileWithContent("123");
path("copy/b/a.txt").shouldNotExist();
};
it("sync", () => {
preparations();
jetpack.copy("x/y", "copy", { matching: "./a.txt" });
expectations();
});
it("async", done => {
preparations();
jetpack.copyAsync("x/y", "copy", { matching: "./a.txt" }).then(() => {
expectations();
done();
});
});
});
describe("matching works also if copying single file", () => {
const preparations = () => {
fse.outputFileSync("a", "123");
fse.outputFileSync("x", "456");
};
const expectations = () => {
path("a-copy").shouldNotExist();
path("x-copy").shouldBeFileWithContent("456");
};
it("sync", () => {
preparations();
jetpack.copy("a", "a-copy", { matching: "x" });
jetpack.copy("x", "x-copy", { matching: "x" });
expectations();
});
it("async", done => {
preparations();
jetpack
.copyAsync("a", "a-copy", { matching: "x" })
.then(() => {
return jetpack.copyAsync("x", "x-copy", { matching: "x" });
})
.then(() => {
expectations();
done();
});
});
});
describe("can use negation in patterns", () => {
const preparations = () => {
fse.mkdirsSync("x/y/dir/a/b");
fse.mkdirsSync("x/y/dir/a/x");
fse.mkdirsSync("x/y/dir/a/y");
fse.mkdirsSync("x/y/dir/a/z");
};
const expectations = () => {
path("copy/dir/a/b").shouldBeDirectory();
path("copy/dir/a/x").shouldNotExist();
path("copy/dir/a/y").shouldNotExist();
path("copy/dir/a/z").shouldNotExist();
};
it("sync", () => {
preparations();
jetpack.copy("x/y", "copy", {
matching: [
"**",
// Three different pattern types to test:
"!x",
"!dir/a/y",
"!./dir/a/z"
]
});
expectations();
});
it("async", done => {
preparations();
jetpack
.copyAsync("x/y", "copy", {
matching: [
"**",
// Three different pattern types to test:
"!x",
"!dir/a/y",
"!./dir/a/z"
]
})
.then(() => {
expectations();
done();
});
});
});
describe("wildcard copies everything", () => {
const preparations = () => {
// Just a file
fse.outputFileSync("x/file.txt", "123");
// Dot file
fse.outputFileSync("x/y/.dot", "dot");
// Empty directory
fse.mkdirsSync("x/y/z");
};
const expectations = () => {
path("copy/file.txt").shouldBeFileWithContent("123");
path("copy/y/.dot").shouldBeFileWithContent("dot");
path("copy/y/z").shouldBeDirectory();
};
it("sync", () => {
preparations();
jetpack.copy("x", "copy", { matching: "**" });
expectations();
});
it("async", done => {
preparations();
jetpack.copyAsync("x", "copy", { matching: "**" }).then(() => {
expectations();
done();
});
});
});
});
describe("can copy symlink", () => {
const preparations = () => {
fse.mkdirsSync("to_copy");
fse.symlinkSync("some/file", "to_copy/symlink");
};
const expectations = () => {
expect(fse.lstatSync("copied/symlink").isSymbolicLink()).to.equal(true);
expect(fse.readlinkSync("copied/symlink")).to.equal(
helper.osSep("some/file")
);
};
it("sync", () => {
preparations();
jetpack.copy("to_copy", "copied");
expectations();
});
it("async", done => {
preparations();
jetpack.copyAsync("to_copy", "copied").then(() => {
expectations();
done();
});
});
});
describe("can overwrite symlink", () => {
const preparations = () => {
fse.mkdirsSync("to_copy");
fse.symlinkSync("some/file", "to_copy/symlink");
fse.mkdirsSync("copied");
fse.symlinkSync("some/other_file", "copied/symlink");
};
const expectations = () => {
expect(fse.lstatSync("copied/symlink").isSymbolicLink()).to.equal(true);
expect(fse.readlinkSync("copied/symlink")).to.equal(
helper.osSep("some/file")
);
};
it("sync", () => {
preparations();
jetpack.copy("to_copy", "copied", { overwrite: true });
expectations();
});
it("async", done => {
preparations();
jetpack.copyAsync("to_copy", "copied", { overwrite: true }).then(() => {
expectations();
done();
});
});
});
describe("if ignoreCase=true it ignores case in patterns", () => {
// This test actually tests nothing if performed on case-insensitive file system.
const preparations = () => {
fse.mkdirsSync("orig/FoO/BaR/x");
};
const expectations = () => {
path("copy/FoO/BaR/x").shouldBeDirectory();
};
it("sync", () => {
preparations();
jetpack.copy("orig", "copy", {
matching: ["foo/bar/x"],
ignoreCase: true
});
expectations();
});
it("async", done => {
preparations();
jetpack
.copyAsync("orig", "copy", {
matching: ["foo/bar/x"],
ignoreCase: true
})
.then(() => {
expectations();
done();
});
});
});
if (process.platform !== "win32") {
describe("copies also file permissions (unix only)", () => {
const preparations = () => {
fse.outputFileSync("a/b/c.txt", "abc");
fse.chmodSync("a/b", "700");
fse.chmodSync("a/b/c.txt", "711");
};
const expectations = () => {
path("x/b").shouldHaveMode("700");
path("x/b/c.txt").shouldHaveMode("711");
};
it("sync", () => {
preparations();
jetpack.copy("a", "x");
expectations();
});
it("async", done => {
preparations();
jetpack.copyAsync("a", "x").then(() => {
expectations();
done();
});
});
});
}
describe("input validation", () => {
const tests = [
{ type: "sync", method: jetpack.copy as any, methodName: "copy" },
{
type: "async",
method: jetpack.copyAsync as any,
methodName: "copyAsync"
}
];
describe('"from" argument', () => {
tests.forEach(test => {
it(test.type, () => {
expect(() => {
test.method(undefined, "xyz");
}).to.throw(
`Argument "from" passed to ${
test.methodName
}(from, to, [options]) must be a string. Received undefined`
);
});
});
});
describe('"to" argument', () => {
tests.forEach(test => {
it(test.type, () => {
expect(() => {
test.method("abc");
}).to.throw(
`Argument "to" passed to ${
test.methodName
}(from, to, [options]) must be a string. Received undefined`
);
});
});
});
describe('"options" object', () => {
describe('"overwrite" argument', () => {
tests.forEach(test => {
it(test.type, () => {
expect(() => {
test.method("abc", "xyz", { overwrite: 1 });
}).to.throw(
`Argument "options.overwrite" passed to ${
test.methodName
}(from, to, [options]) must be a boolean or a function. Received number`
);
});
});
});
describe('"matching" argument', () => {
tests.forEach(test => {
it(test.type, () => {
expect(() => {
test.method("abc", "xyz", { matching: 1 });
}).to.throw(
`Argument "options.matching" passed to ${
test.methodName
}(from, to, [options]) must be a string or an array of string. Received number`
);
});
});
});
describe('"ignoreCase" argument', () => {
tests.forEach(test => {
it(test.type, () => {
expect(() => {
test.method("abc", "xyz", { ignoreCase: 1 });
}).to.throw(
`Argument "options.ignoreCase" passed to ${
test.methodName
}(from, to, [options]) must be a boolean. Received number`
);
});
});
});
});
});
}); | the_stack |
import ApoloQuery from './graphqQuerry'
import PageNavigationBar from './pageNavigationBar'
import { CreateComment } from './createComment'
import queryCommentListById from '../graphql/queryCommentListById.gql'
import queryCommentChildListById from '../graphql/queryCommentChildListById.gql'
interface Data {
data: {
commentListById?: NavData
commentChildListById?: NavData
}
}
interface NavData {
wpDbId: number
totalPage: number
targetPage: number
pageSize: number
comments: string
}
interface Comment {
comment_ID: number
comment_parent: number
comment_author: string
comment_author_avatar: string
url: string
content: string
date: string
ua: Ua
location: string
level: number
role: string
like: number
dislike: number
child: {
has_comment: boolean
child_count: number
preview_list: Comment[]
}
}
interface Ua {
os: string[]
browsers: string[]
}
export default class ShowCommentList {
public constructor(postId: number, pageSize: number, targetPage: number) {
let list_comment = new ListComments(postId, pageSize, targetPage)
}
}
/**
* This class is used to get a post's comment list by postId
* main() method has been called by constructor()
*/
class ListComments {
public db_id: number
public page_size: number
public target_page: number
public total_page: number
public data: Data
public comments: Comment[]
/**
* the type of current process:
* `comment`: get comment by postId, display preview
* `child`: get comment child by commentId, display with navigation
* `preview`: get comment child previed by commentId, display without navigation
* @var string
*/
// public type: string
/**
* constructor
* @param postId int
* @param pageSize int
* @param targetPage int
*/
public constructor(postId: number, pageSize: number, targetPage: number) {
this.db_id = postId
this.page_size = pageSize
this.target_page = targetPage
this.main()
}
/**
* decode comments field
* @since 4.0.0
* @param encoded
* @return Comment[]
*/
protected static get_comment_decode(encoded: string): Comment[] {
return JSON.parse(encoded)
}
/**
* query callback function
* @since 4.0.0
* @param data
*/
protected query_callback(data: Data): void {
// initial
this.data = data
this.total_page = this.data.data.commentListById.totalPage
let comment_list_ul: HTMLElement = document.getElementById('comment-list-ul-root')
// decode
this.comments = JSON.parse(this.data.data.commentListById.comments)
// remove old html and listener
// TODO: remove listener?
ListComments.remove_element_child(comment_list_ul)
// print list html
// - add listener for collapes
let comments_html_list: { [id: number]: DocumentFragment; } = ListComments.gen_comment_list_html(this.comments)
for (let i in comments_html_list) {
// ps: the i is the comment id
// push item to DOM
comment_list_ul.appendChild(comments_html_list[i])
// add click event listener on collapse open button to show child detail
if (document.getElementById(`open-comment-${i}`)) {
let open: HTMLElement = document.getElementById(`open-comment-${i}`)
open.addEventListener('click', ListComments.collapse.bind(event), true)
}
}
// add reply event listener
CreateComment.reply_to_listener()
// print nav html
// - add listener for nav bar
const nav: PageNavigationBar = new PageNavigationBar(this.target_page, this.total_page)
let nav_html: Element = nav.dom
nav_html.setAttribute('id', `comment-list-nav-${this.db_id}`)
comment_list_ul.appendChild(nav_html)
let buttons: NodeList = document.querySelectorAll(`#comment-list-nav-${this.db_id} button`)
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', this.nav_turn.bind(this, buttons[i], this.db_id), false)
}
// TODO: should I add a listener to the url and destroy class itself while leaving page?
}
public static collapse(event: MouseEvent) {
let element = event['path'][0]
let commentId = element.getAttribute('data-comment')
let list_comment_child = new ListCommentChild(Number(commentId), 10, 1)
CreateComment.reset_comment_form()
}
/**
* turn page function
* @param element
* @param db_id
*/
protected nav_turn(element: HTMLElement, db_id: number) {
this.db_id = db_id
this.target_page = Number(element.getAttribute('data-nav'))
if (this.target_page !== undefined && this.target_page !== 0) {
this.main()
CreateComment.reset_comment_form()
CreateComment.reply_to_listener()
}
}
/**
* remove element child
* @since 4.0.0
* @param element
*/
protected static remove_element_child(element: Element): void {
while (element.firstChild) {
element.removeChild(element.firstChild)
}
}
/**
* generate a list of DocumentFragment by comment items in comments
* @since 4.0.0
* @param comments Comment[]
* @return DocumentFragment[]
*/
protected static gen_comment_list_html(comments: Comment[]): { [id: number]: DocumentFragment; } {
let li: HTMLTemplateElement = document.querySelector('#comment-list-li-template')
let li_list: { [id: number]: DocumentFragment; } = {}
for (let i in comments) {
let comment: Comment = comments[i]
// copy the template
let li_clone: DocumentFragment = document.importNode(li.content, true)
// insert data
li_clone.querySelector('.comment-item').setAttribute('id', `comment-${comment.comment_ID}`)
li_clone.querySelector('.reply').setAttribute('data-reply-to', String(comment.comment_ID))
li_clone.querySelector('.content').innerHTML = (comment.content ? comment.content : '').trim()
li_clone.querySelector('.time').textContent = comment.date
li_clone.querySelector('.name').textContent = comment.comment_author
li_clone.querySelector('.avatar img').setAttribute('src', comment.comment_author_avatar)
li_clone.querySelector('a.avatar').setAttribute('href', comment.url)
li_clone.querySelector('a.name').setAttribute('href', comment.url)
li_clone.querySelector('.location').textContent = comment.location
li_clone.querySelector('.like .num').textContent = String(comment.like)
li_clone.querySelector('.dislike .num').textContent = String(comment.dislike)
// insert preview to child
if (comment.child.has_comment) {
let preview_html_list: { [id: number]: DocumentFragment; } = ListComments.gen_comment_list_html(comment.child.preview_list)
for (let t in preview_html_list) {
li_clone.querySelector('.comment-list-ul').appendChild(preview_html_list[t])
}
// add event listener to reply
CreateComment.reply_to_listener()
// add collapse
if (comment.child.child_count > 3) {
let collapse: Element = document.createElement('div'),
collapseText: string = `
<div class="mdc-chip-set" role="grid">
<div class="mdc-chip open" id="open-comment-${comment.comment_ID}" data-comment="${comment.comment_ID}" role="row">
<div class="mdc-chip__ripple open"></div>
<i class="material-icons mdc-chip__icon mdc-chip__icon--leading" data-comment="${comment.comment_ID}">expand_more</i>
<span role="gridcell">
<span role="button" tabindex="0" class="mdc-chip__text" data-comment="${comment.comment_ID}">Expand</span>
</span>
</div>
<strong>${comment.child.child_count}</strong> replies in total
<div>`
// TODO: also add a Collapse button to detail list (material-icons: expand_less)
collapse.classList.add('child-collapse')
collapse.innerHTML = collapseText.trim()
li_clone.querySelector('.comment-list-ul').appendChild(collapse)
}
// the DOM has not been created new, so we cannot add event listener here
}
// array push
li_list[comment.comment_ID] = li_clone
}
return li_list
}
/**
* main function
* @since 4.0.0
*
* @method query
* @method query_callback
*/
protected main(): void {
const query = {
query: queryCommentListById,
variables: {
"postId": this.db_id,
"pageSize": this.page_size,
"targetPage": this.target_page
}
}
const client: ApoloQuery = new ApoloQuery(query, this.query_callback.bind(this))
client.do()
}
}
/**
* This class is used to get a comment's child comment list by commentId
* main() method has been called by constructor()
*/
class ListCommentChild extends ListComments {
public constructor(commentId: number, pageSize: number, targetPage: number) {
super(commentId, pageSize, targetPage)
this.db_id = commentId
this.page_size = pageSize
this.target_page = targetPage
this.main()
}
/**
* main function
* @since 4.0.0
*
* @method query
* @method query_callback
*/
public main() {
const query = {
query: queryCommentChildListById,
variables: {
"commentId": this.db_id,
"pageSize": this.page_size,
"targetPage": this.target_page
}
}
const client: ApoloQuery = new ApoloQuery(query, this.query_callback.bind(this))
client.do()
}
/**
* query callback function
* @since 4.0.0
* @param data
*/
protected query_callback(data: Data): void {
// initial
this.data = data
this.total_page = this.data.data.commentChildListById.totalPage
let comment_list_ul: HTMLElement = document.querySelector(`#comment-${this.db_id} .comment-list-ul`)
// decode
this.comments = JSON.parse(this.data.data.commentChildListById.comments)
// remove old html and listener
// TODO: remove listener?
ListCommentChild.remove_element_child(comment_list_ul)
// print list html
let comments_html_list = <DocumentFragment[]>ListCommentChild.gen_comment_list_html(this.comments)
for (let i in comments_html_list) {
comment_list_ul.appendChild(comments_html_list[i])
}
// Add reply event listener
CreateComment.reply_to_listener()
// print nav html
// - add listener for nav bar
const nav: PageNavigationBar = new PageNavigationBar(this.target_page, this.total_page, 'left')
let nav_html: Element = nav.dom
nav_html.setAttribute('id', `comment-child-list-nav-${this.db_id}`)
comment_list_ul.appendChild(nav_html)
let buttons: NodeList = document.querySelectorAll(`#comment-child-list-nav-${this.db_id} button`)
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', this.nav_turn.bind(this, buttons[i], this.db_id), false)
}
// TODO: should I add a listener to the url and destroy self when leaving page?
}
} | the_stack |
import crypto from 'crypto'
import { CookieJar } from 'tough-cookie'
import tools from './tools'
import { IncomingHttpHeaders } from 'http'
/**
* ็ปๅฝ็ถๆ
*
* @enum {number}
*/
enum appStatus {
'success',
'error',
'httpError',
'captcha',
'validate',
'authcode',
}
/**
* ๆจกๆapp็ปๅฝ
*
* @abstract
* @class AppClient
*/
abstract class AppClient {
public static readonly actionKey: string = 'appkey'
// bilibili ๅฎขๆท็ซฏ
protected static readonly __loginSecretKey: string = '60698ba2f68e01ce44738920a0ffe768'
public static readonly loginAppKey: string = 'bca7e84c2d947ac6'
protected static readonly __secretKey: string = '560c52ccd288fed045859ed18bffd973'
public static readonly appKey: string = '1d8b6e7d45233436'
public static get biliLocalId(): string { return this.RandomID(64) }
public static readonly build: string = '5570300'
public static get buvid(): string { return this.RandomID(37).toLocaleUpperCase() }
public static readonly channel: string = 'bili'
public static readonly device: string = 'phone'
// ๅไธๅฎขๆท็ซฏไธbiliLocalId็ธๅ
public static get deviceId(): string { return this.biliLocalId }
public static readonly deviceName: string = 'SonyJ9110'
public static readonly devicePlatform: string = 'Android10SonyJ9110'
// ๅไธๅฎขๆท็ซฏไธbuvid็ธๅ
public static get localId(): string { return this.buvid }
public static readonly mobiApp: string = 'android'
public static readonly platform: string = 'android'
public static readonly statistics: string = '%7B%22appId%22%3A1%2C%22platform%22%3A3%2C%22version%22%3A%225.57.0%22%2C%22abtest%22%3A%22%22%7D'
// bilibili ๅฝ้
็
// protected static readonly __loginSecretKey: string = 'c75875c596a69eb55bd119e74b07cfe3'
// public static readonly loginAppKey: string = 'ae57252b0c09105d'
// protected static readonly __secretKey: string = '36efcfed79309338ced0380abd824ac1'
// public static readonly appKey: string = 'bb3101000e232e27'
// public static readonly build: string = '112000'
// public static readonly mobiApp: string = 'android_i'
// bilibili ๆฆๅฟต็
// protected static readonly __loginSecretKey: string = '34381a26236dd1171185c0beb042e1c6'
// public static readonly loginAppKey: string = '178cf125136ca8ea'
// protected static readonly __secretKey: string = '25bdede4e1581c836cab73a48790ca6e'
// public static readonly appKey: string = '07da50c9a0bf829f'
// public static readonly build: string = '5380400'
// public static readonly mobiApp: string = 'android_b'
// bilibili TV
// protected static readonly __loginSecretKey: string = '59b43e04ad6965f34319062b478f83dd'
// public static readonly loginAppKey: string = '4409e2ce8ffd12b8'
// protected static readonly __secretKey: string = '59b43e04ad6965f34319062b478f83dd'
// public static readonly appKey: string = '4409e2ce8ffd12b8'
// public static readonly biliLocalId: string = AppClient.RandomID(20)
// public static readonly build: string = '102401'
// public static readonly buvid: string = AppClient.RandomID(37).toLocaleUpperCase()
// public static readonly channel: string = 'master'
// public static readonly device: string = 'Sony'
// public static readonly deviceId: string = AppClient.biliLocalId
// public static readonly deviceName: string = 'J9110'
// public static readonly devicePlatform: string = 'Android10SonyJ9110'
// public static get fingerprint(): string { return this.RandomID(62) }
// public static readonly guid: string = AppClient.buvid
// // ๅไธๅฎขๆท็ซฏไธfingerprint็ธๅ
// public static get localFingerprint(): string { return this.fingerprint }
// public static readonly localId: string = AppClient.buvid
// public static readonly mobiApp: string = 'android_tv_yst'
// public static readonly networkstate: string = 'wifi'
// public static readonly platform: string = 'android'
// bilibili link
// protected static readonly __loginSecretKey: string = 'e988e794d4d4b6dd43bc0e89d6e90c43'
// public static readonly loginAppKey: string = '37207f2beaebf8d7'
// protected static readonly __secretKey: string = 'e988e794d4d4b6dd43bc0e89d6e90c43'
// public static readonly appKey: string = '37207f2beaebf8d7'
// public static readonly build: string = '4610002'
// public static readonly mobiApp: string = 'biliLink'
// public static readonly platform: string = 'android_link'
/**
* ่ฐไธๆ ท็TS
*
* @readonly
* @static
* @type {number}
* @memberof AppClient
*/
public static get TS(): number { return Math.floor(Date.now() / 1000) }
/**
* ่ฐไธๆ ท็RND
*
* @readonly
* @static
* @type {number}
* @memberof AppClient
*/
public static get RND(): number { return AppClient.RandomNum(9) }
/**
* ่ฐไธๆ ท็RandomNum
*
* @static
* @param {number} length
* @returns {number}
* @memberof AppClient
*/
public static RandomNum(length: number): number {
const words = '0123456789'
let randomNum = ''
randomNum += words[Math.floor(Math.random() * 9) + 1]
for (let i = 0; i < length - 1; i++) randomNum += words[Math.floor(Math.random() * 10)]
return +randomNum
}
/**
* ่ฐไธๆ ท็RandomID
*
* @static
* @param {number} length
* @returns {string}
* @memberof AppClient
*/
public static RandomID(length: number): string {
const words = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
let randomID = ''
randomID += words[Math.floor(Math.random() * 61) + 1]
for (let i = 0; i < length - 1; i++) randomID += words[Math.floor(Math.random() * 62)]
return randomID
}
/**
* ่ฏทๆฑๅคด
*
* @readonly
* @static
* @type {IncomingHttpHeaders}
* @memberof AppClient
*/
public static get headers(): IncomingHttpHeaders {
return {
'User-Agent': 'Mozilla/5.0 BiliDroid/5.57.0 (bbcallen@gmail.com) os/android model/J9110 mobi_app/android build/5570300 channel/bili innerVer/5570300 osVer/10 network/2',
'APP-KEY': this.mobiApp,
'Buvid': this.buvid,
'Device-ID': this.deviceId,
'Display-ID': `${this.buvid}-${this.TS}`,
'env': 'prod'
}
}
/**
* ๅบๆฌ่ฏทๆฑๅๆฐ
*
* @readonly
* @static
* @type {string}
* @memberof AppClient
*/
public static get baseQuery(): string {
return `actionKey=${this.actionKey}&appkey=${this.appKey}&build=${this.build}&channel=${this.channel}\
&device=${this.device}&mobi_app=${this.mobiApp}&platform=${this.platform}&statistics=${this.statistics}`
}
/**
* ็ปๅฝ่ฏทๆฑๅๆฐ
*
* @readonly
* @static
* @type {string}
* @memberof AppClient
*/
public static get loginQuery(): string {
return `appkey=${this.loginAppKey}&bili_local_id=${this.biliLocalId}&build=${this.build}&buvid=${this.buvid}&channel=${this.channel}\
&device=${this.device}&device_id=${this.deviceId}&device_name=${this.deviceName}&device_platform=${this.devicePlatform}&local_id=${this.localId}\
&mobi_app=${this.mobiApp}&platform=${this.platform}&statistics=${this.statistics}`
}
/**
* ๅฏนๅๆฐ็ญพๅ
*
* @static
* @param {string} params
* @param {boolean} [ts=true]
* @param {string} [secretKey=this.__secretKey]
* @returns {string}
* @memberof AppClient
*/
public static signQuery(params: string, ts: boolean = true, secretKey: string = this.__secretKey): string {
let paramsSort = params
if (ts) paramsSort = `${params}&ts=${this.TS}`
paramsSort = paramsSort.split('&').sort().join('&')
const paramsSecret = paramsSort + secretKey
const paramsHash = tools.Hash('md5', paramsSecret)
return `${paramsSort}&sign=${paramsHash}`
}
/**
* ๅฏนๅๆฐๅ ๅๅ็ญพๅ
*
* @static
* @param {string} [params]
* @returns {string}
* @memberof AppClient
*/
public static signBaseQuery(params?: string): string {
const paramsBase = params === undefined ? this.baseQuery : `${params}&${this.baseQuery}`
return this.signQuery(paramsBase)
}
/**
* ๅฏนๅๆฐๅ ๅๅ็ญพๅ
*
* @static
* @param {string} [params]
* @returns {string}
* @memberof AppClient
*/
public static signQueryBase(params?: string): string {
return this.signBaseQuery(params)
}
/**
* ๅฏน็ปๅฝๅๆฐๅ ๅๅ็ญพๅ
*
* @static
* @param {string} [params]
* @returns {string}
* @memberof AppClient
*/
public static signLoginQuery(params?: string): string {
const paramsBase = params === undefined ? this.loginQuery : `${params}&${this.loginQuery}`
return this.signQuery(paramsBase, true, this.__loginSecretKey)
}
// ๅบๅฎๅๆฐ
public actionKey: string = AppClient.actionKey
protected __loginSecretKey: string = AppClient.__loginSecretKey
public loginAppKey: string = AppClient.loginAppKey
protected __secretKey: string = AppClient.__secretKey
public appKey: string = AppClient.appKey
public biliLocalId = AppClient.biliLocalId
public build: string = AppClient.build
public buvid = AppClient.buvid
public channel: string = AppClient.channel
public device: string = AppClient.device
public deviceId: string = this.biliLocalId
public deviceName: string = AppClient.deviceName
public devicePlatform: string = AppClient.devicePlatform
public localId: string = this.buvid
public mobiApp: string = AppClient.mobiApp
public platform: string = AppClient.platform
public statistics: string = AppClient.statistics
/**
* ่ฏทๆฑๅคด
*
* @type {IncomingHttpHeaders}
* @memberof AppClient
*/
public headers: IncomingHttpHeaders = {
'User-Agent': 'Mozilla/5.0 BiliDroid/5.57.0 (bbcallen@gmail.com) os/android model/J9110 mobi_app/android build/5570300 channel/bili innerVer/5570300 osVer/10 network/2',
'APP-KEY': this.mobiApp,
'Buvid': this.buvid,
'Device-ID': this.deviceId,
'Display-ID': `${this.buvid}-${AppClient.TS}`,
'env': 'prod'
}
/**
* ๅบๆฌ่ฏทๆฑๅๆฐ
*
* @type {string}
* @memberof AppClient
*/
public baseQuery: string = `actionKey=${this.actionKey}&appkey=${this.appKey}&build=${this.build}&channel=${this.channel}\
&device=${this.device}&mobi_app=${this.mobiApp}&platform=${this.platform}&statistics=${this.statistics}`
/**
* ็ปๅฝ่ฏทๆฑๅๆฐ
*
* @type {string}
* @memberof AppClient
*/
public loginQuery: string = `appkey=${this.loginAppKey}&bili_local_id=${this.biliLocalId}&build=${this.build}&buvid=${this.buvid}&channel=${this.channel}\
&device=${this.device}&device_id=${this.deviceId}&device_name=${this.deviceName}&device_platform=${this.devicePlatform}&local_id=${this.localId}\
&mobi_app=${this.mobiApp}&platform=${this.platform}&statistics=${this.statistics}`
/**
* ๅฏนๅๆฐ็ญพๅ
*
* @param {string} params
* @param {boolean} [ts=true]
* @param {string} [secretKey=this.__secretKey]
* @returns {string}
* @memberof AppClient
*/
public signQuery(params: string, ts: boolean = true, secretKey: string = this.__secretKey): string {
return AppClient.signQuery(params, ts, secretKey)
}
/**
* ๅฏนๅๆฐๅ ๅๅ็ญพๅ
*
* @param {string} [params]
* @returns {string}
* @memberof AppClient
*/
public signBaseQuery(params?: string): string {
const paramsBase = params === undefined ? this.baseQuery : `${params}&${this.baseQuery}`
return this.signQuery(paramsBase)
}
/**
* ๅฏน็ปๅฝๅๆฐๅ ๅๅ็ญพๅ
*
* @param {string} [params]
* @returns {string}
* @memberof AppClient
*/
public signLoginQuery(params?: string): string {
const paramsBase = params === undefined ? this.loginQuery : `${params}&${this.loginQuery}`
return this.signQuery(paramsBase, true, this.__loginSecretKey)
}
/**
* ็ปๅฝ็ถๆ
*
* @static
* @type {typeof appStatus}
* @memberof AppClient
*/
public static readonly status: typeof appStatus = appStatus
/**
* ้ช่ฏ็ , ็ปๅฝๆถไผ่ชๅจๆธ
็ฉบ
*
* @type {string}
* @memberof AppClient
*/
public captcha: string = ''
/**
* ๆปๅจ้ช่ฏ็ , ็ปๅฝๆถไผ่ชๅจๆธ
็ฉบ
*
* @type {string}
* @memberof AppClient
*/
public validate: string = ''
/**
* ๆปๅจ้ช่ฏ้กต้ข, ็ปๅฝๆถไผ่ชๅจๆธ
็ฉบ
*
* @type {string}
* @memberof AppClient
*/
public validateURL: string = ''
/**
* ็จๆทๅ, ๆจ่้ฎ็ฎฑๆ็ต่ฏๅท
*
* @abstract
* @type {string}
* @memberof AppClient
*/
public abstract userName: string
/**
* ๅฏ็
*
* @abstract
* @type {string}
* @memberof AppClient
*/
public abstract passWord: string
/**
* ็ปๅฝๅ่ทๅ็B็ซUID
*
* @abstract
* @type {number}
* @memberof AppClient
*/
public abstract biliUID: number
/**
* ็ปๅฝๅ่ทๅ็access_token
*
* @abstract
* @type {string}
* @memberof AppClient
*/
public abstract accessToken: string
/**
* ็ปๅฝๅ่ทๅ็refresh_token
*
* @abstract
* @type {string}
* @memberof AppClient
*/
public abstract refreshToken: string
/**
* ็ปๅฝๅ่ทๅ็cookieString
*
* @abstract
* @type {string}
* @memberof AppClient
*/
public abstract cookieString: string
/**
* ็ปๅฝๅๅๅปบ็CookieJar
*
* @abstract
* @type {CookieJar}
* @memberof AppClient
*/
public abstract jar: CookieJar
/**
* cookieJar
*
* @protected
* @type {CookieJar}
* @memberof AppClient
*/
protected __jar: CookieJar = new CookieJar()
/**
* ๅฏนๅฏ็ ่ฟ่กๅ ๅฏ
*
* @protected
* @param {getKeyResponseData} publicKey
* @returns {string}
* @memberof AppClient
*/
protected _RSAPassWord(publicKey: getKeyResponseData): string {
const padding = {
key: publicKey.key,
padding: crypto.constants.RSA_PKCS1_PADDING
}
const hashPassWord = publicKey.hash + this.passWord
const encryptPassWord = crypto.publicEncrypt(padding, Buffer.from(hashPassWord)).toString('base64')
return encodeURIComponent(encryptPassWord)
}
/**
* ่ทๅๅ
ฌ้ฅ
*
* @protected
* @returns {(Promise<response<getKeyResponse> | undefined>)}
* @memberof AppClient
*/
protected _getKey(): Promise<XHRresponse<getKeyResponse> | undefined> {
const getKey: XHRoptions = {
method: 'POST',
uri: 'https://passport.bilibili.com/api/oauth2/getKey',
body: this.signLoginQuery(),
jar: this.__jar,
json: true,
headers: this.headers
}
return tools.XHR<getKeyResponse>(getKey, 'Android')
}
/**
* ้ช่ฏ็ปๅฝไฟกๆฏ
*
* @protected
* @param {getKeyResponseData} publicKey
* @returns {Promise<response<authResponse> | undefined>)}
* @memberof AppClient
*/
protected _auth(publicKey: getKeyResponseData): Promise<XHRresponse<authResponse> | undefined> {
const passWord = this._RSAPassWord(publicKey)
const validate = this.validate === '' ? '' : `&validate=${this.validate}`
const authQuery = `username=${encodeURIComponent(this.userName)}&password=${passWord}${validate}`
const auth: XHRoptions = {
method: 'POST',
uri: 'https://passport.bilibili.com/api/v3/oauth2/login',
body: this.signLoginQuery(authQuery),
jar: this.__jar,
json: true,
headers: this.headers
}
this.validate = ''
return tools.XHR<authResponse>(auth, 'Android')
}
/**
* ๆดๆฐ็จๆทๅญ่ฏ
*
* @protected
* @param {authResponseData} authResponseData
* @memberof AppClient
*/
protected _update(authResponseData: authResponseData) {
const tokenInfo = authResponseData.token_info
const cookies = authResponseData.cookie_info.cookies
this.biliUID = +tokenInfo.mid
this.accessToken = tokenInfo.access_token
this.refreshToken = tokenInfo.refresh_token
this.cookieString = cookies.reduce((cookieString, cookie) => cookieString === ''
? `${cookie.name}=${cookie.value}`
: `${cookieString}; ${cookie.name}=${cookie.value}`
, '')
}
/**
* ่ทๅ้ช่ฏ็
*
* @returns {Promise<captchaResponse>}
* @memberof AppClient
*/
public async getCaptcha(): Promise<captchaResponse> {
const captcha: XHRoptions = {
uri: 'https://passport.bilibili.com/captcha',
encoding: null,
jar: this.__jar,
headers: this.headers
}
const captchaResponse = await tools.XHR<Buffer>(captcha, 'Android')
if (captchaResponse !== undefined && captchaResponse.response.statusCode === 200)
return { status: AppClient.status.success, data: captchaResponse.body, }
return { status: AppClient.status.error, data: captchaResponse }
}
/**
* ๅฎขๆท็ซฏ็ปๅฝ
*
* @returns {Promise<loginResponse>}
* @memberof AppClient
*/
public async login(): Promise<loginResponse> {
const getKeyResponse = await this._getKey()
if (getKeyResponse !== undefined && getKeyResponse.response.statusCode === 200 && getKeyResponse.body.code === 0) {
const authResponse = await this._auth(getKeyResponse.body.data)
if (authResponse !== undefined && authResponse.response.statusCode === 200) {
if (authResponse.body.code === 0) {
if (authResponse.body.data.token_info !== undefined && authResponse.body.data.cookie_info !== undefined) {
this._update(authResponse.body.data)
return { status: AppClient.status.success, data: authResponse.body }
}
return { status: AppClient.status.error, data: authResponse.body }
}
if (authResponse.body.code === -105) {
this.validateURL = authResponse.body.data.url
return { status: AppClient.status.validate, data: authResponse.body }
}
return { status: AppClient.status.error, data: authResponse.body }
}
return { status: AppClient.status.httpError, data: authResponse }
}
return { status: AppClient.status.httpError, data: getKeyResponse }
}
/**
* ๅฎขๆท็ซฏ็ปๅบ
*
* @returns {Promise<logoutResponse>}
* @memberof AppClient
*/
public async logout(): Promise<logoutResponse> {
const revokeQuery = `access_token=${this.accessToken}`
const revoke: XHRoptions = {
method: 'POST',
uri: 'https://passport.bilibili.com/x/passport-login/revoke',
body: this.signLoginQuery(revokeQuery),
json: true,
headers: this.headers
}
const revokeResponse = await tools.XHR<revokeResponse>(revoke, 'Android')
if (revokeResponse !== undefined && revokeResponse.response.statusCode === 200) {
if (revokeResponse.body.code === 0) return { status: AppClient.status.success, data: revokeResponse.body }
return { status: AppClient.status.error, data: revokeResponse.body }
}
return { status: AppClient.status.httpError, data: revokeResponse }
}
/**
* ๆดๆฐaccess_token
*
* @returns {Promise<loginResponse>}
* @memberof AppClient
*/
public async refresh(): Promise<loginResponse> {
const refreshQuery = `refresh_token=${this.refreshToken}`
const refresh: XHRoptions = {
method: 'POST',
uri: 'https://passport.bilibili.com/x/passport-login/oauth2/refresh_token',
body: this.signLoginQuery(refreshQuery),
json: true,
headers: this.headers
}
const refreshResponse = await tools.XHR<authResponse>(refresh, 'Android')
if (refreshResponse !== undefined && refreshResponse.response.statusCode === 200) {
if (refreshResponse.body !== undefined && refreshResponse.body.code === 0) {
this._update(refreshResponse.body.data)
return { status: AppClient.status.success, data: refreshResponse.body }
}
return { status: AppClient.status.error, data: refreshResponse.body }
}
return { status: AppClient.status.httpError, data: refreshResponse }
}
}
export default AppClient | the_stack |
import { maskAreEqual, maskIncludes, maskIntersection, maskNew, maskNext, maskUnion }
from './mask';
import type { Mask } from './mask';
import { MaskSet } from './mask-index';
import type util from 'util';
import type { InspectOptionsStylized } from 'util';
declare module 'util'
{
function inspect(obj: any, options?: InspectOptions): string;
}
export type AttributeMap = { readonly [AttributeName in string]: string | null; };
export interface CompatibilityInfo
{
readonly family: string;
readonly featureName: string;
readonly version: EngineVersion;
readonly tag?: string;
readonly shortTag?: string;
}
export interface EngineEntry
{
readonly family: string;
readonly compatibilities: readonly CompatibilityInfo[];
}
export type EngineVersion = string | Readonly<{ from: string; to?: string; dense: boolean; }>;
export interface Feature
{
readonly canonicalNames: string[];
readonly elementary: boolean;
readonly elementaryNames: string[];
readonly mask: Mask;
name?: string;
includes(...features: FeatureElementOrCompatibleArray[]): boolean;
toString(): string;
}
export interface FeatureConstructor
{
(...features: FeatureElementOrCompatibleArray[]): Feature;
readonly ALL:
{ readonly [FeatureName in string]: PredefinedFeature; };
readonly ELEMENTARY: readonly PredefinedFeature[];
readonly ENGINE: readonly PredefinedFeature[];
readonly FAMILIES:
{ readonly [Family in string]: readonly CompatibilityInfo[]; };
new (...features: FeatureElementOrCompatibleArray[]): Feature;
_fromMask(mask: Mask): Feature | null;
_getMask(feature?: FeatureElementOrCompatibleArray): Mask;
areCompatible(...features: FeatureElement[]): boolean;
/** @deprecated */
areCompatible(features: readonly FeatureElement[]): boolean;
areEqual(...features: FeatureElementOrCompatibleArray[]): boolean;
commonOf(...features: FeatureElementOrCompatibleArray[]): Feature | null;
descriptionFor(name: string): string | undefined;
}
export type FeatureElement = Feature | string;
export type FeatureElementOrCompatibleArray = FeatureElement | readonly FeatureElement[];
export type FeatureInfo =
(
{
readonly aliasFor: string;
} |
{
readonly attributes?: { readonly [AttributeName in string]: string | null | undefined; };
readonly check?: () => unknown;
readonly excludes?: readonly string[];
readonly includes?: readonly string[] | IncludeDifferenceMap;
readonly inherits?: string;
} &
({ } | { readonly families?: readonly string[]; readonly versions: readonly VersionInfo[]; }) &
({ } | { readonly compatibilityTag: string; readonly compatibilityShortTag: string; })
) &
{ readonly description?: string; };
export type IncludeDifferenceMap = { readonly [FeatureName in string]: boolean; };
export interface PredefinedFeature extends Feature
{
readonly attributes: AttributeMap;
readonly check: (() => boolean) | null;
readonly name: string;
}
export type VersionInfo =
string | readonly [from: string, to?: string] | readonly [from: string, _: never, to?: string];
const _Array_isArray = Array.isArray as (value: unknown) => value is readonly unknown[];
const _Error = Error;
const _JSON_stringify = JSON.stringify;
const
{
create: _Object_create,
defineProperty: _Object_defineProperty,
freeze: _Object_freeze,
getOwnPropertyDescriptor: _Object_getOwnPropertyDescriptor,
keys: _Object_keys,
} =
Object;
const _String = String;
const _TypeError = TypeError;
function assignNoEnum(target: object, source: object): void
{
const names = _Object_keys(source);
for (const name of names)
{
const descriptor = _Object_getOwnPropertyDescriptor(source, name)!;
descriptor.enumerable = false;
_Object_defineProperty(target, name, descriptor);
}
}
export function createFeatureClass
(
featureInfos: { readonly [FeatureName in string]: FeatureInfo; },
formatEngineDescription?: (compatibilities: CompatibilityInfo[]) => string,
):
FeatureConstructor
{
const ALL = createMap<PredefinedFeature>();
const DESCRIPTION_MAP = createMap<string | undefined>();
const ELEMENTARY: PredefinedFeature[] = [];
const ENGINE: PredefinedFeature[] = [];
const FAMILIES = createMap<CompatibilityInfo[]>();
const FEATURE_PROTOTYPE = Feature.prototype as object;
const INCOMPATIBLE_MASK_LIST: Mask[] = [];
let PRISTINE_ELEMENTARY: PredefinedFeature[];
function Feature(this: Feature, ...features: FeatureElementOrCompatibleArray[]): Feature
{
let mask = maskNew();
for (const feature of features)
{
const otherMask = validMaskFromArrayOrStringOrFeature(feature);
mask = maskUnion(mask, otherMask);
}
if (features.length > 1)
validateMask(mask);
const featureObj =
this instanceof Feature ? this : _Object_create(FEATURE_PROTOTYPE) as Feature;
initMask(featureObj, mask);
return featureObj;
}
function _fromMask(mask: Mask): Feature | null
{
if (isMaskCompatible(mask))
{
let includedMask = maskNew();
for (const { mask: featureMask } of ELEMENTARY)
{
if (maskIncludes(mask, featureMask))
includedMask = maskUnion(includedMask, featureMask);
}
if (maskAreEqual(mask, includedMask))
{
const featureObj = featureFromMask(mask);
return featureObj;
}
}
return null;
}
function _getMask(feature?: FeatureElementOrCompatibleArray): Mask
{
const mask =
feature !== undefined ? validMaskFromArrayOrStringOrFeature(feature) : maskNew();
return mask;
}
function areCompatible(): boolean
{
let arg0: FeatureElement | readonly FeatureElement[];
const features: ArrayLike<FeatureElement> =
arguments.length === 1 &&
// eslint-disable-next-line prefer-rest-params
_Array_isArray(arg0 = arguments[0] as FeatureElement | readonly FeatureElement[]) ?
// eslint-disable-next-line prefer-rest-params
arg0 : arguments as ArrayLike<FeatureElement>;
const mask = featureArrayLikeToMask(features);
const compatible = isMaskCompatible(mask);
return compatible;
}
function areEqual(...features: FeatureElementOrCompatibleArray[]): boolean
{
let mask: Mask;
const equal =
features.every
(
(feature, index): boolean =>
{
let returnValue: boolean;
const otherMask = validMaskFromArrayOrStringOrFeature(feature);
if (index)
returnValue = maskAreEqual(otherMask, mask);
else
{
mask = otherMask;
returnValue = true;
}
return returnValue;
},
);
return equal;
}
function commonOf(...features: FeatureElementOrCompatibleArray[]): Feature | null
{
let featureObj: Feature | null;
if (features.length)
{
let mask: Mask | undefined;
for (const feature of features)
{
const otherMask = validMaskFromArrayOrStringOrFeature(feature);
if (mask != null)
mask = maskIntersection(mask, otherMask);
else
mask = otherMask;
}
featureObj = featureFromMask(mask!);
}
else
featureObj = null;
return featureObj;
}
function createFeature
(
name: string,
mask: Mask,
check: (() => boolean) | null,
attributes: AttributeMap,
elementary?: unknown,
):
PredefinedFeature
{
_Object_freeze(attributes);
const descriptors: PropertyDescriptorMap =
{ attributes: { value: attributes }, check: { value: check }, name: { value: name } };
if (elementary)
descriptors.elementary = { value: true };
const featureObj = _Object_create(FEATURE_PROTOTYPE, descriptors) as PredefinedFeature;
initMask(featureObj, mask);
return featureObj;
}
function descriptionFor(name: string): string | undefined
{
name = esToString(name);
if (!(name in DESCRIPTION_MAP))
throwUnknownFeatureError(name);
const description = DESCRIPTION_MAP[name];
return description;
}
function featureArrayLikeToMask(features: ArrayLike<FeatureElement>): Mask
{
let mask = maskNew();
const { length } = features;
for (let index = 0; index < length; ++index)
{
const feature = features[index];
const otherMask = maskFromStringOrFeature(feature);
mask = maskUnion(mask, otherMask);
}
return mask;
}
function featureFromMask(mask: Mask): Feature
{
const featureObj = _Object_create(FEATURE_PROTOTYPE) as Feature;
initMask(featureObj, mask);
return featureObj;
}
/**
* Node.js custom inspection function.
* Set on `Feature.prototype` with name `"inspect"` for Node.js โค 8.6.x and with symbol
* `Symbol.for("nodejs.util.inspect.custom")` for Node.js โฅ 6.6.x.
*
* @see
* {@link https://nodejs.org/api/util.html#util_custom_inspection_functions_on_objects} for
* further information.
*/
// opts can be undefined in Node.js 0.10.0.
function inspect(this: Feature, depth: never, opts?: InspectOptionsStylized): string
{
const breakLength = opts?.breakLength ?? 80;
const compact = opts?.compact ?? true;
let { name } = this;
if (name === undefined)
name = joinParts(compact, '<', '', this.canonicalNames, ',', '>', breakLength - 3);
const parts = [name];
if (this.elementary)
parts.push('(elementary)');
if ((this as PredefinedFeature).check)
parts.push('(check)');
{
const { attributes } = this as PredefinedFeature;
if (typeof attributes === 'object')
{
const str = utilInspect!({ ...attributes }, opts);
parts.push(str);
}
}
const str = joinParts(compact, '[Feature', ' ', parts, '', ']', breakLength - 1);
return str;
}
function isMaskCompatible(mask: Mask): boolean
{
const compatible =
INCOMPATIBLE_MASK_LIST.every
((incompatibleMask): boolean => !maskIncludes(mask, incompatibleMask));
return compatible;
}
function maskFromStringOrFeature(feature: FeatureElement): Mask
{
let featureObj: Feature;
if (feature instanceof Feature)
featureObj = feature as Feature;
else
{
const name = esToString(feature);
if (!(name in ALL))
throwUnknownFeatureError(name);
featureObj = ALL[name];
}
const { mask } = featureObj;
return mask;
}
function validMaskFromArrayOrStringOrFeature(feature: FeatureElementOrCompatibleArray): Mask
{
let mask: Mask;
if (_Array_isArray(feature))
{
mask = featureArrayLikeToMask(feature);
if (feature.length > 1)
validateMask(mask);
}
else
mask = maskFromStringOrFeature(feature);
return mask;
}
function validateMask(mask: Mask): void
{
if (!isMaskCompatible(mask))
throw new _Error('Incompatible features');
}
let utilInspect: typeof util.inspect | undefined;
try
{
// eslint-disable-next-line @typescript-eslint/no-var-requires
utilInspect = (require('util') as typeof util).inspect;
}
catch
{ }
{
const protoSource =
{
get canonicalNames(): string[]
{
const { mask } = this;
const names: string[] = [];
let includedMask = maskNew();
for (let index = PRISTINE_ELEMENTARY.length; index--;)
{
const featureObj = PRISTINE_ELEMENTARY[index];
const featureMask = featureObj.mask;
if (maskIncludes(mask, featureMask) && !maskIncludes(includedMask, featureMask))
{
includedMask = maskUnion(includedMask, featureMask);
names.push(featureObj.name);
}
}
names.sort();
return names;
},
elementary: false,
get elementaryNames(): string[]
{
const names: string[] = [];
const { mask } = this;
for (const featureObj of ELEMENTARY)
{
const included = maskIncludes(mask, featureObj.mask);
if (included)
names.push(featureObj.name);
}
return names;
},
includes(...features: FeatureElementOrCompatibleArray[]): boolean
{
const { mask } = this;
const included =
features.every
(
(feature): boolean =>
{
const otherMask = validMaskFromArrayOrStringOrFeature(feature);
const returnValue = maskIncludes(mask, otherMask);
return returnValue;
},
);
return included;
},
name: undefined,
toString(): string
{
const name = this.name ?? `<${this.canonicalNames.join(', ')}>`;
const str = `[Feature ${name}]`;
return str;
},
} as { [PropName in string]: unknown; } & ThisType<Feature>;
if (utilInspect)
protoSource.inspect = inspect;
assignNoEnum(FEATURE_PROTOTYPE, protoSource);
}
((): void =>
{
const compareFeatureNames =
(feature1: PredefinedFeature, feature2: PredefinedFeature): number =>
feature1.name < feature2.name ? -1 : 1;
function completeExclusions(): void
{
const incompatibleMaskSet = new MaskSet();
for (const name of featureNames)
{
const { excludes } =
featureInfos[name] as { readonly excludes?: readonly string[]; };
if (excludes)
{
const { mask } = ALL[name];
for (const exclude of excludes)
{
const excludeMask = completeFeature(exclude);
const incompatibleMask = maskUnion(mask, excludeMask);
if (!incompatibleMaskSet.has(incompatibleMask))
{
INCOMPATIBLE_MASK_LIST.push(incompatibleMask);
incompatibleMaskSet.add(incompatibleMask);
}
}
}
}
}
function completeFeature(name: string): Mask
{
let mask: Mask;
if (name in ALL)
({ mask } = ALL[name]);
else
{
const info = featureInfos[name];
const getInfoStringField =
<FieldNameType extends string>(fieldName: FieldNameType): string | undefined =>
fieldName in info ?
esToString((info as { [Name in FieldNameType]: unknown; })[fieldName]) : undefined;
let description = getInfoStringField('description');
let featureObj: PredefinedFeature;
if ('aliasFor' in info)
{
const aliasFor = esToString(info.aliasFor);
mask = completeFeature(aliasFor);
featureObj = ALL[aliasFor];
if (description == null)
description = DESCRIPTION_MAP[aliasFor];
}
else
{
const inherits = getInfoStringField('inherits');
if (inherits != null)
completeFeature(inherits);
let wrappedCheck: (() => boolean) | null;
let compatibilities: CompatibilityInfo[] | undefined;
const { check } = info;
if (check !== undefined)
{
mask = maskNext(unionMask);
unionMask = maskUnion(unionMask, mask);
wrappedCheck = wrapCheck(check);
}
else
{
mask = maskNew();
wrappedCheck = null;
}
{
const { includes } = info;
const includeSet = includeSetMap[name] = createMap<null>();
if (_Array_isArray(includes))
{
for (const include of includes)
includeSet[include] = null;
}
else
{
if (inherits != null)
{
const inheritedIncludeSet = includeSetMap[inherits];
for (const include in inheritedIncludeSet)
includeSet[include] = null;
}
if (includes)
{
const includeDiffNames = _Object_keys(includes);
for (const include of includeDiffNames)
{
if (includes[include])
includeSet[include] = null;
else
delete includeSet[include];
}
}
}
for (const include in includeSet)
{
const includeMask = completeFeature(include);
mask = maskUnion(mask, includeMask);
}
}
if ('versions' in info)
{
let { families } = info;
const { versions } = info;
if (inherits != null)
families ??= familiesMap[inherits];
familiesMap[name] = families!;
const tag = getInfoStringField('compatibilityTag');
const shortTag = getInfoStringField('compatibilityShortTag');
compatibilities =
families!.map
(
(family: string, index: number): CompatibilityInfo =>
{
family = esToString(family);
const versionInfo = versions[index];
let version: EngineVersion;
if (_Array_isArray(versionInfo))
{
const { length } = versionInfo;
const from = esToString(versionInfo[0]);
const to =
length < 2 ? undefined : esToString(versionInfo[length - 1]);
const dense = versionInfo.length === 2;
version = _Object_freeze({ from, to, dense });
}
else
version = esToString(versionInfo);
const compatibility =
_Object_freeze
({ family, featureName: name, version, tag, shortTag });
const familyCompatibilities =
(FAMILIES[family] as CompatibilityInfo[] | undefined) ??
(FAMILIES[family] = []);
familyCompatibilities.push(compatibility);
return compatibility;
},
);
if (description == null)
description = formatEngineDescription?.(compatibilities);
}
const attributes = createMap<string | null>();
if (inherits != null)
{
const inheritedAttributes = ALL[inherits].attributes;
for (const attributeName in inheritedAttributes)
attributes[attributeName] = inheritedAttributes[attributeName];
}
{
const infoAttributes = info.attributes;
if (infoAttributes !== undefined)
{
const attributeNames = _Object_keys(infoAttributes);
for (const attributeName of attributeNames)
{
const attributeValue = infoAttributes[attributeName];
if (attributeValue !== undefined)
{
attributes[attributeName] =
typeof attributeValue === 'string' ? attributeValue : null;
}
else
delete attributes[attributeName];
}
}
}
const elementary: unknown = wrappedCheck ?? info.excludes;
featureObj = createFeature(name, mask, wrappedCheck, attributes, elementary);
if (elementary)
ELEMENTARY.push(featureObj);
if (compatibilities)
ENGINE.push(featureObj);
}
ALL[name] = featureObj;
DESCRIPTION_MAP[name] = description;
}
return mask;
}
{
const constructorSource =
{
ALL,
ELEMENTARY,
ENGINE,
FAMILIES,
_fromMask,
_getMask,
areCompatible,
areEqual,
commonOf,
descriptionFor,
};
assignNoEnum(Feature, constructorSource);
}
if (utilInspect)
{
const inspectKey = utilInspect.custom as symbol | undefined;
if (inspectKey)
{
_Object_defineProperty
(
FEATURE_PROTOTYPE,
inspectKey,
{ configurable: true, value: inspect, writable: true },
);
}
}
const featureNames = _Object_keys(featureInfos);
const includeSetMap = createMap<{ readonly [FeatureName in string]: null; }>();
const familiesMap = createMap<readonly string[]>();
let unionMask = maskNew();
featureNames.forEach(completeFeature);
completeExclusions();
PRISTINE_ELEMENTARY = ELEMENTARY.slice();
ELEMENTARY.sort(compareFeatureNames);
_Object_freeze(ELEMENTARY);
ENGINE.sort(compareFeatureNames);
_Object_freeze(ENGINE);
_Object_freeze(ALL);
_Object_freeze(FAMILIES);
for (const family in FAMILIES)
_Object_freeze(FAMILIES[family]);
}
)();
return Feature as FeatureConstructor;
}
const createMap = <T>(): { [Key in string]: T; } => _Object_create(null) as { };
function esToString(name: unknown): string
{
if (typeof name === 'symbol')
throw new _TypeError('Cannot convert a symbol to a string');
const str = _String(name);
return str;
}
export function featuresToMask(featureObjs: readonly Feature[]): Mask
{
const mask =
featureObjs.reduce((mask, featureObj): Mask => maskUnion(mask, featureObj.mask), maskNew());
return mask;
}
function indent(text: string): string
{
const returnValue = text.replace(/^/gm, ' ');
return returnValue;
}
function initMask(featureObj: Feature, mask: Mask): void
{
_Object_defineProperty(featureObj, 'mask', { value: mask });
}
function joinParts
(
compact: boolean | number,
intro: string,
preSeparator: string,
parts: readonly string[],
partSeparator: string,
outro: string,
maxLength: number,
):
string
{
function isMultiline(): boolean
{
let length =
intro.length +
preSeparator.length +
(parts.length - 1) * (partSeparator.length + 1) +
outro.length;
for (const part of parts)
{
if (~part.indexOf('\n'))
return true;
length += part.replace(/\x1b\[\d+m/g, '').length;
if (length > maxLength)
return true;
}
return false;
}
const str =
parts.length && (!compact || isMultiline()) ?
`${intro}\n${indent(parts.join(`${partSeparator}\n`))}\n${outro}` :
`${intro}${preSeparator}${parts.join(`${partSeparator} `)}${outro}`;
return str;
}
function throwUnknownFeatureError(name: string): never
{
throw new _Error(`Unknown feature ${_JSON_stringify(name)}`);
}
function wrapCheck(check: () => unknown): () => boolean
{
const wrappedCheck = (): boolean => !!check();
return wrappedCheck;
} | the_stack |
import Notifications from '../lib/collections/notifications/collection';
import Conversations from '../lib/collections/conversations/collection';
import Reports from '../lib/collections/reports/collection';
import { Bans } from '../lib/collections/bans/collection';
import Users from '../lib/collections/users/collection';
import { Votes } from '../lib/collections/votes';
import { clearVotesServer } from './voteServer';
import { Posts } from '../lib/collections/posts/collection';
import { postStatuses } from '../lib/collections/posts/constants';
import { Comments } from '../lib/collections/comments'
import { ReadStatuses } from '../lib/collections/readStatus/collection';
import { VoteableCollections } from '../lib/make_voteable';
import { getCollection, createMutator, updateMutator, deleteMutator, runQuery, getCollectionsByName } from './vulcan-lib';
import { postReportPurgeAsSpam, commentReportPurgeAsSpam } from './akismet';
import { capitalize } from '../lib/vulcan-lib/utils';
import { getCollectionHooks } from './mutationCallbacks';
import { asyncForeachSequential } from '../lib/utils/asyncUtils';
import Tags from '../lib/collections/tags/collection';
import Revisions from '../lib/collections/revisions/collection';
import { syncDocumentWithLatestRevision } from './editor/utils';
import { createAdminContext } from './vulcan-lib/query';
getCollectionHooks("Messages").newAsync.add(async function updateConversationActivity (message: DbMessage) {
// Update latest Activity timestamp on conversation when new message is added
const user = await Users.findOne(message.userId);
const conversation = await Conversations.findOne(message.conversationId);
if (!conversation) throw Error(`Can't find conversation for message ${message}`)
await updateMutator({
collection: Conversations,
documentId: conversation._id,
set: {latestActivity: message.createdAt},
currentUser: user,
validate: false,
});
});
getCollectionHooks("Users").editAsync.add(async function userEditNullifyVotesCallbacksAsync(user: DbUser, oldUser: DbUser) {
if (user.nullifyVotes && !oldUser.nullifyVotes) {
await nullifyVotesForUser(user);
}
});
getCollectionHooks("Users").editAsync.add(async function userEditChangeDisplayNameCallbacksAsync(user: DbUser, oldUser: DbUser) {
// if the user is setting up their profile and their username changes from that form,
// we don't want this action to count toward their one username change
const isSettingUsername = oldUser.usernameUnset && !user.usernameUnset
if (user.displayName !== oldUser.displayName && !isSettingUsername) {
await updateMutator({
collection: Users,
documentId: user._id,
set: {previousDisplayName: oldUser.displayName},
currentUser: user,
validate: false,
});
}
});
getCollectionHooks("Users").updateAsync.add(function userEditDeleteContentCallbacksAsync({newDocument, oldDocument, currentUser}) {
if (newDocument.deleteContent && !oldDocument.deleteContent && currentUser) {
void userDeleteContent(newDocument, currentUser);
}
});
getCollectionHooks("Users").editAsync.add(function userEditBannedCallbacksAsync(user: DbUser, oldUser: DbUser) {
if (new Date(user.banned) > new Date() && !(new Date(oldUser.banned) > new Date())) {
void userIPBanAndResetLoginTokens(user);
}
});
const reverseVote = async (vote: DbVote, context: ResolverContext) => {
const collection = getCollection(vote.collectionName as VoteableCollectionName);
const document = await collection.findOne({_id: vote.documentId});
const user = await Users.findOne({_id: vote.userId});
if (document && user) {
await clearVotesServer({document, collection, user, context})
} else {
//eslint-disable-next-line no-console
console.info("No item or user found corresponding to vote: ", vote, document, user);
}
}
export const nullifyVotesForUser = async (user: DbUser) => {
for (let collection of VoteableCollections) {
await nullifyVotesForUserAndCollection(user, collection);
}
}
const nullifyVotesForUserAndCollection = async (user: DbUser, collection: CollectionBase<DbVoteableType>) => {
const collectionName = capitalize(collection.collectionName);
const context = await createAdminContext();
const votes = await Votes.find({
collectionName: collectionName,
userId: user._id,
cancelled: false,
}).fetch();
for (let vote of votes) {
//eslint-disable-next-line no-console
console.log("reversing vote: ", vote)
await reverseVote(vote, context);
};
//eslint-disable-next-line no-console
console.info(`Nullified ${votes.length} votes for user ${user.username}`);
}
export async function userDeleteContent(user: DbUser, deletingUser: DbUser, deleteTags=true) {
//eslint-disable-next-line no-console
console.warn("Deleting all content of user: ", user)
const posts = await Posts.find({userId: user._id}).fetch();
//eslint-disable-next-line no-console
console.info("Deleting posts: ", posts);
for (let post of posts) {
await updateMutator({
collection: Posts,
documentId: post._id,
set: {status: postStatuses.STATUS_DELETED},
unset: {},
currentUser: deletingUser,
validate: false,
})
const notifications = await Notifications.find({documentId: post._id}).fetch();
//eslint-disable-next-line no-console
console.info(`Deleting notifications for post ${post._id}: `, notifications);
for (let notification of notifications) {
await deleteMutator({
collection: Notifications,
documentId: notification._id,
validate: false,
})
}
const reports = await Reports.find({postId: post._id}).fetch();
//eslint-disable-next-line no-console
console.info(`Deleting reports for post ${post._id}: `, reports);
for (let report of reports) {
await updateMutator({
collection: Reports,
documentId: report._id,
set: {closedAt: new Date()},
unset: {},
currentUser: deletingUser,
validate: false,
})
}
await postReportPurgeAsSpam(post);
}
const comments = await Comments.find({userId: user._id}).fetch();
//eslint-disable-next-line no-console
console.info("Deleting comments: ", comments);
for (let comment of comments) {
if (!comment.deleted) {
try {
await updateMutator({
collection: Comments,
documentId: comment._id,
set: {deleted: true, deletedDate: new Date()},
unset: {},
currentUser: deletingUser,
validate: false,
})
} catch(err) {
//eslint-disable-next-line no-console
console.error("Failed to delete comment")
//eslint-disable-next-line no-console
console.error(err)
}
}
const notifications = await Notifications.find({documentId: comment._id}).fetch();
//eslint-disable-next-line no-console
console.info(`Deleting notifications for comment ${comment._id}: `, notifications);
for (let notification of notifications) {
await deleteMutator({ // TODO: This should be a soft-delete not a hard-delete
collection: Notifications,
documentId: notification._id,
validate: false,
})
}
const reports = await Reports.find({commentId: comment._id}).fetch();
//eslint-disable-next-line no-console
console.info(`Deleting reports for comment ${comment._id}: `, reports);
for (let report of reports) {
await updateMutator({
collection: Reports,
documentId: report._id,
set: {closedAt: new Date()},
unset: {},
currentUser: deletingUser,
validate: false,
})
}
await commentReportPurgeAsSpam(comment);
}
if (deleteTags) {
await deleteUserTagsAndRevisions(user, deletingUser)
}
//eslint-disable-next-line no-console
console.info("Deleted n posts and m comments: ", posts.length, comments.length);
}
async function deleteUserTagsAndRevisions(user: DbUser, deletingUser: DbUser) {
const tags = await Tags.find({userId: user._id}).fetch()
// eslint-disable-next-line no-console
console.info("Deleting tags: ", tags)
for (let tag of tags) {
if (!tag.deleted) {
try {
await updateMutator({
collection: Tags,
documentId: tag._id,
set: {deleted: true},
currentUser: deletingUser,
validate: false
})
} catch(err) {
// eslint-disable-next-line no-console
console.error("Failed to delete tag")
// eslint-disable-next-line no-console
console.error(err)
}
}
}
const tagRevisions = await Revisions.find({userId: user._id, collectionName: 'Tags'}).fetch()
// eslint-disable-next-line no-console
console.info("Deleting tag revisions: ", tagRevisions)
await Revisions.rawRemove({userId: user._id})
// Revert revision documents
for (let revision of tagRevisions) {
const collection = getCollectionsByName()[revision.collectionName] as CollectionBase<DbObject, any>
const document = await collection.findOne({_id: revision.documentId})
if (document) {
await syncDocumentWithLatestRevision(
collection,
document,
revision.fieldName
)
}
}
}
/**
* Add user IP address to IP ban list for a day and remove their login tokens
*
* NB: We haven't tested the IP ban list in like 3 years and it should not be
* assumed to work.
*/
export async function userIPBanAndResetLoginTokens(user: DbUser) {
// IP ban
const query = `
query UserIPBan($userId:String) {
user(input:{selector: {_id: $userId}}) {
result {
IPs
}
}
}
`;
const IPs: any = await runQuery(query, {userId: user._id});
if (IPs) {
await asyncForeachSequential(IPs.data.user.result.IPs as Array<string>, async ip => {
let tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
const ban: Partial<DbBan> = {
expirationDate: tomorrow,
userId: user._id,
reason: "User account banned",
comment: "Automatic IP ban",
ip: ip,
}
await createMutator({
collection: Bans,
document: ban,
currentUser: user,
validate: false,
})
})
}
// Remove login tokens
await Users.rawUpdateOne({_id: user._id}, {$set: {"services.resume.loginTokens": []}});
}
getCollectionHooks("LWEvents").newSync.add(async function updateReadStatus(event: DbLWEvent) {
if (event.userId && event.documentId) {
// Upsert. This operation is subtle and fragile! We have a unique index on
// (postId,userId,tagId). If two copies of a page-view event fire at the
// same time, this creates a race condition. In order to not have this throw
// an exception, we need to meet the conditions in
// https://docs.mongodb.com/manual/core/retryable-writes/#retryable-update-upsert
// In particular, this means the selector has to exactly match the unique
// index's keys.
await ReadStatuses.rawUpdateOne({
postId: event.documentId,
userId: event.userId,
tagId: null,
}, {
$set: {
isRead: true,
lastUpdated: event.createdAt
}
}, {
upsert: true
});
}
return event;
}); | the_stack |
import rule, {
defaultOrder,
MessageIds,
Options,
} from '../../src/rules/member-ordering';
import { RuleTester } from '../RuleTester';
import { TSESLint } from '@typescript-eslint/experimental-utils';
const ruleTester = new RuleTester({
parser: '@typescript-eslint/parser',
});
const sortedCiWithoutGrouping: TSESLint.RunTests<MessageIds, Options> = {
valid: [
// default option + interface + lower/upper case
{
code: `
interface Foo {
a : b;
B : b;
}
`,
options: [
{
default: {
memberTypes: 'never',
order: 'alphabetically-case-insensitive',
},
},
],
},
// default option + type literal + lower/upper case
{
code: `
type Foo = {
a : b;
B : b;
}
`,
options: [
{
default: {
memberTypes: 'never',
order: 'alphabetically-case-insensitive',
},
},
],
},
// default option + class + lower/upper case
{
code: `
class Foo {
public static a : string;
public static B : string;
}
`,
options: [
{
default: {
memberTypes: 'never',
order: 'alphabetically-case-insensitive',
},
},
],
},
// default option + class expression + lower/upper case
{
code: `
const foo = class Foo {
public static a : string;
public static B : string;
}
`,
options: [
{
default: {
memberTypes: 'never',
order: 'alphabetically-case-insensitive',
},
},
],
},
// default option + class + decorators
{
code: `
class Foo {
public static a : string;
@Dec() static B : string;
public static c : string;
}
`,
options: [
{
default: {
memberTypes: 'never',
order: 'alphabetically-case-insensitive',
},
},
],
},
],
invalid: [
// default option + interface + wrong order (multiple)
{
code: `
interface Foo {
c : string;
B : string;
a : string;
}
`,
options: [
{
default: {
memberTypes: 'never',
order: 'alphabetically-case-insensitive',
},
},
],
errors: [
{
messageId: 'incorrectOrder',
data: {
member: 'B',
beforeMember: 'c',
},
},
{
messageId: 'incorrectOrder',
data: {
member: 'a',
beforeMember: 'B',
},
},
],
},
// default option + interface + lower/upper case wrong order
{
code: `
interface Foo {
B : b;
a : b;
}
`,
options: [
{
default: {
memberTypes: 'never',
order: 'alphabetically-case-insensitive',
},
},
],
errors: [
{
messageId: 'incorrectOrder',
data: {
member: 'a',
beforeMember: 'B',
},
},
],
},
// default option + type literal + lower/upper case wrong order
{
code: `
type Foo = {
B : b;
a : b;
}
`,
options: [
{
default: {
memberTypes: 'never',
order: 'alphabetically-case-insensitive',
},
},
],
errors: [
{
messageId: 'incorrectOrder',
data: {
member: 'a',
beforeMember: 'B',
},
},
],
},
// default option + class + lower/upper case wrong order
{
code: `
class Foo {
public static B : string;
public static a : string;
}
`,
options: [
{
default: {
memberTypes: 'never',
order: 'alphabetically-case-insensitive',
},
},
],
errors: [
{
messageId: 'incorrectOrder',
data: {
member: 'a',
beforeMember: 'B',
},
},
],
},
// default option + class expression + lower/upper case wrong order
{
code: `
const foo = class Foo {
public static B : string;
public static a : string;
}
`,
options: [
{
default: {
memberTypes: 'never',
order: 'alphabetically-case-insensitive',
},
},
],
errors: [
{
messageId: 'incorrectOrder',
data: {
member: 'a',
beforeMember: 'B',
},
},
],
},
],
};
const sortedCiWithGrouping: TSESLint.RunTests<MessageIds, Options> = {
valid: [
// default option + interface + default order + alphabetically
{
code: `
interface Foo {
[a: string] : number;
() : Baz;
a : x;
B : x;
c : x;
new () : Bar;
a() : void;
B() : void;
c() : void;
}
`,
options: [
{
default: {
memberTypes: defaultOrder,
order: 'alphabetically-case-insensitive',
},
},
],
},
// default option + interface + custom order + alphabetically
{
code: `
interface Foo {
new () : Bar;
a() : void;
B() : void;
c() : void;
a : x;
B : x;
c : x;
[a: string] : number;
() : Baz;
}
`,
options: [
{
default: {
memberTypes: ['constructor', 'method', 'field'],
order: 'alphabetically-case-insensitive',
},
},
],
},
// default option + type literal + default order + alphabetically
{
code: `
type Foo = {
[a: string] : number;
() : Baz;
a : x;
B : x;
c : x;
new () : Bar;
a() : void;
B() : void;
c() : void;
}
`,
options: [
{
default: {
memberTypes: defaultOrder,
order: 'alphabetically-case-insensitive',
},
},
],
},
// default option + type literal + custom order + alphabetically
{
code: `
type Foo = {
[a: string] : number;
new () : Bar;
a() : void;
B() : void;
c() : void;
a : x;
B : x;
c : x;
() : Baz;
}
`,
options: [
{
default: {
memberTypes: ['constructor', 'method', 'field'],
order: 'alphabetically-case-insensitive',
},
},
],
},
// default option + class + default order + alphabetically
{
code: `
class Foo {
public static a: string;
protected static b: string = "";
private static c: string = "";
public d: string = "";
protected E: string = "";
private f: string = "";
constructor() {}
}
`,
options: [
{
default: {
memberTypes: defaultOrder,
order: 'alphabetically-case-insensitive',
},
},
],
},
// default option + class + decorators + default order + alphabetically
{
code: `
class Foo {
public static a: string;
protected static b: string = "";
private static c: string = "";
@Dec() public d: string;
@Dec() protected E: string;
@Dec() private f: string;
public g: string = "";
protected h: string = "";
private i: string = "";
constructor() {}
}
`,
options: [
{
default: {
memberTypes: defaultOrder,
order: 'alphabetically-case-insensitive',
},
},
],
},
// default option + class + custom order + alphabetically
{
code: `
class Foo {
constructor() {}
public d: string = "";
protected E: string = "";
private f: string = "";
public static a: string;
protected static b: string = "";
private static c: string = "";
}
`,
options: [
{
default: {
memberTypes: ['constructor', 'instance-field', 'static-field'],
order: 'alphabetically-case-insensitive',
},
},
],
},
// default option + class expression + default order + alphabetically
{
code: `
const foo = class Foo {
public static a: string;
protected static b: string = "";
private static c: string = "";
public d: string = "";
protected E: string = "";
private f: string = "";
constructor() {}
}
`,
options: [
{
default: {
memberTypes: defaultOrder,
order: 'alphabetically-case-insensitive',
},
},
],
},
// default option + class expression + custom order + alphabetically
{
code: `
const foo = class Foo {
constructor() {}
public d: string = "";
protected E: string = "";
private f: string = "";
public static a: string;
protected static b: string = "";
private static c: string = "";
}
`,
options: [
{
default: {
memberTypes: ['constructor', 'instance-field', 'static-field'],
order: 'alphabetically-case-insensitive',
},
},
],
},
],
invalid: [
// default option + interface + wrong order within group and wrong group order + alphabetically
{
code: `
interface Foo {
[a: string] : number;
a : x;
B : x;
c : x;
c() : void;
B() : void;
a() : void;
() : Baz;
new () : Bar;
}
`,
options: [
{
default: {
memberTypes: defaultOrder,
order: 'alphabetically-case-insensitive',
},
},
],
errors: [
{
messageId: 'incorrectGroupOrder',
data: {
name: 'call',
rank: 'field',
},
},
{
messageId: 'incorrectGroupOrder',
data: {
name: 'new',
rank: 'method',
},
},
],
},
// default option + type literal + wrong order within group and wrong group order + alphabetically
{
code: `
type Foo = {
[a: string] : number;
a : x;
B : x;
c : x;
c() : void;
B() : void;
a() : void;
() : Baz;
new () : Bar;
}
`,
options: [
{
default: {
memberTypes: defaultOrder,
order: 'alphabetically-case-insensitive',
},
},
],
errors: [
{
messageId: 'incorrectGroupOrder',
data: {
name: 'call',
rank: 'field',
},
},
{
messageId: 'incorrectGroupOrder',
data: {
name: 'new',
rank: 'method',
},
},
],
},
// default option + class + wrong order within group and wrong group order + alphabetically
{
code: `
class Foo {
public static c: string = "";
public static B: string = "";
public static a: string;
constructor() {}
public d: string = "";
}
`,
options: [
{
default: {
memberTypes: defaultOrder,
order: 'alphabetically-case-insensitive',
},
},
],
errors: [
{
messageId: 'incorrectGroupOrder',
data: {
name: 'd',
rank: 'public constructor',
},
},
],
},
// default option + class expression + wrong order within group and wrong group order + alphabetically
{
code: `
const foo = class Foo {
public static c: string = "";
public static B: string = "";
public static a: string;
constructor() {}
public d: string = "";
}
`,
options: [
{
default: {
memberTypes: defaultOrder,
order: 'alphabetically-case-insensitive',
},
},
],
errors: [
{
messageId: 'incorrectGroupOrder',
data: {
name: 'd',
rank: 'public constructor',
},
},
],
},
],
};
ruleTester.run('member-ordering-alphabetically-case-insensitive-order', rule, {
valid: [...sortedCiWithoutGrouping.valid, ...sortedCiWithGrouping.valid],
invalid: [
...sortedCiWithoutGrouping.invalid,
...sortedCiWithGrouping.invalid,
],
}); | the_stack |
import * as vscode from 'vscode';
// only needed for creating the config file
const fs = require('fs');
const debounce = require('./modules/client/debounce');
const readFileSendReqAndWriteResponse = require('./modules/client/readFileSendReqAndWriteResponse');
const serverOn = require('./modules/server/serverOn');
const serverOff = require('./modules/server/serverOff');
// require in new function that checks for a running server
const checkForRunningServer = require('./modules/server/checkForRunningServer');
// require in file that finds root directory
const findRootDirectory = require('./modules/client/findRootDirectory');
// require in file that returns entryPoint when given the root path
const parseConfigFile = require('./modules/client/parseConfigFile');
// functionality that prints the entire GraphQL schema to the output channel
const showGraphqlSchema = require('./modules/client/showGraphqlSchema');
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
// * These are some variables that I need to pass between different commands, so they're in
// * a higher scope
// this ChannelRef variable will be used to pass the output channel between separate function defs
// let graphQuillChannelRef: vscode.OutputChannel;
const gqChannel = vscode.window.createOutputChannel('GraphQuill');
// a toggle variable that will is true when the server is on
let isOnToggle = false;
// a disposable variable to get rid of the save event listener
let saveListener: vscode.Disposable;
// set rootPath and entryPoint to a string of the path to the server startup file (has app.listen)
const rootPath = findRootDirectory();
// putting these variables in the global scope with the expectation that they will be set upon
// activating the extension. I'm moving them to be able to manage "live" changes
let entryPoint: string;
let allowServerTimeoutConfigSetting: number;
let portNumber: number; // portNumber will also come from the config file
// boolean to track if the server has been successfully turned on by the user
let serverTurnedOnByGraphQuill = false;
/** **********************************************************************************************
* * The command must be defined in package.json under contributes/commands AND activation events
* Now provide the implementation of the command with registerCommand
* The commandId parameter must match the command field in package.json
* * This is the first GraphQuill option in the command palette for activating GraphQuill
*********************************************************************************************** */
const disposableActivateGraphQuill = vscode.commands.registerCommand('extension.activateGraphQuill', async () => {
if (isOnToggle) {
// if server is already running, break out of function by returning null
// console.log('Server is already running');
vscode.window.showInformationMessage('GraphQuill is already active');
return null;
}
// show output channel, clear any old stuff off of it
gqChannel.show(true);
gqChannel.clear();
// parse the config file
let parseResult = parseConfigFile(rootPath);
entryPoint = parseResult.entryPoint; // will return the found entry point or an empty string
allowServerTimeoutConfigSetting = parseResult.allowServerTimeoutConfigSetting;
portNumber = parseResult.portNumber; // will return the found port number or zero if not found
// console.log('parseResults', parseResult);
// if the entryPoint is falsey, break out and tell the user to create a config file
if (!entryPoint || !portNumber) {
gqChannel.append('The config file was not found or had an error, please use the Create GraphQuill Config File Command to make one.');
// break out of this execution context
return null;
}
// Check ONCE if the port is open (also this does not need the third param)
// will resolve to a true or false value
const serverOnFromUser = await checkForRunningServer(portNumber, true);
const externalURL = entryPoint.slice(0, 4) === 'http';
// trigger serverOn if the user does not already have the server running
// AND if the server is not hosted at an external URL
if (!serverOnFromUser && !externalURL) {
// start up the user's server, pass in the gqChannel to log any error messages
serverOn(entryPoint, gqChannel);
// give user feedback that server is starting up
gqChannel.clear();
gqChannel.append('The server is starting up...\n');
// await this function that will return true or false based on if the server has been started
// false: if starting the server is longer than the time allotted in the config file (defaults
// to 3 seconds)
serverTurnedOnByGraphQuill = await checkForRunningServer(portNumber,
// once setting is false, so the returned promise will only resolve when the server has
// started OR the timeout (next variable or 3sec) is reached
false,
// allowServerT.C.S. is either a time in milliseconds that defaults to 3000
allowServerTimeoutConfigSetting);
// if it is false, that means there was an error starting the server
// notify the user & end the thread of execution
if (!serverTurnedOnByGraphQuill) {
// console.log('server is taking too long to startup');
// give feedback to user that port didn't start (and the specified timeout config setting,
// defaults to 3 seconds)
gqChannel.clear();
gqChannel.append(`The server is taking too long to startup (>${(allowServerTimeoutConfigSetting || 3000) / 1000} seconds).\nTo increase this time, update the "serverStartupTimeAllowed" setting in the graphquill.config.js file.`);
// break out, and just in case I'm going to try to kill the port if it did open
// otherwise we could get runaway node processes...
return setTimeout(() => serverOff(portNumber), 5000);
}
}
// if the server is on from either the user or graphquill,
// or the user is querying an external URL,
// continue and send first query & setup on save listener
if (serverOnFromUser || serverTurnedOnByGraphQuill || externalURL) {
let url: (undefined|string);
// if user's server is running at external url, set url to their specified entryPoint
if (externalURL) url = entryPoint;
// make isOnToggle true regardless of url to enable deactivation functionality
isOnToggle = true;
// get the fileName of the open file when the extension is FIRST fired
const currOpenEditorPath: string = vscode.window.activeTextEditor!.document.fileName;
// send that request from the currentopeneditor
readFileSendReqAndWriteResponse(currOpenEditorPath, gqChannel, portNumber, rootPath, url);
const debouncedRFSRWR = debounce(
readFileSendReqAndWriteResponse,
200,
false,
);
// initialize the save listener here to clear the channel and resend new requests
saveListener = vscode.workspace.onDidSaveTextDocument((event) => {
// console.log('save event!!!', event);
// clear the graphQuill channel
gqChannel.clear();
// re-parse the config file (in case the user made a change)
parseResult = parseConfigFile(rootPath);
entryPoint = parseResult.entryPoint;
allowServerTimeoutConfigSetting = parseResult.allowServerTimeoutConfigSetting;
portNumber = parseResult.portNumber;
if (!entryPoint) {
gqChannel.append('The config file was not found, please use the Create GraphQuill Config File Command to make one.');
// break out of this execution context
return null;
}
// send the filename and channel to the readFileSRAWR function
debouncedRFSRWR(event.fileName, gqChannel, portNumber, rootPath, url);
// satisfying linter
return null;
});
}
// to satisfy typescript linter...
return null;
});
// push it to the subscriptions
context.subscriptions.push(disposableActivateGraphQuill);
/** **************************************************************************
* * Second GraphQuill option in the command palette (Cmd Shift P) for deactivating graphquill
************************************************************************** */
const disposableDisableGraphQuill = vscode.commands.registerCommand('extension.deactivateGraphQuill', () => {
// console.log('--deactivate functionality triggered');
// check isontoggle boolean
// as long as user isn't querying external URL
if (!isOnToggle) {
// server is already off
// console.log('server is already off');
vscode.window.showInformationMessage('GraphQuill is already off');
return null;
}
// change toggle boolean
isOnToggle = false;
// dispose of the onDidSaveTextDocument event listener
if (saveListener) saveListener.dispose();
// close/hide GraphQuill channel
gqChannel.hide();
gqChannel.clear();
// eslint-disable-next-line max-len
// console.log('in deactivate, the server turned on by graphquill boolean is: ', serverTurnedOnByGraphQuill);
// invoke server off in this function
return setTimeout(() => (serverTurnedOnByGraphQuill && serverOff(portNumber)), 1);
});
// push it into the subscriptions
context.subscriptions.push(disposableDisableGraphQuill);
/** **************************************************************************
* * Third GraphQuill option in command palette to toggle graphquill extension
************************************************************************** */
const disposableToggleGraphQuill = vscode.commands.registerCommand('extension.toggleGraphQuill', () => {
// console.log('--toggle triggered!');
// if the toggle boolean is false, then start the extension, otherwise end it...
if (!isOnToggle) {
// console.log('--toggle starting extension');
// using the built in execute command and passing in a string of the command to trigger
vscode.commands.executeCommand('extension.activateGraphQuill');
} else {
// console.log('--toggle stopping the extension');
vscode.commands.executeCommand('extension.deactivateGraphQuill');
}
// just to make the linter happy...
return null;
});
// push it to the subscriptions
context.subscriptions.push(disposableToggleGraphQuill);
/** **************************************************************************
* * Fourth GraphQuill option in command palette to CREATE A CONFIG FILE
************************************************************************** */
const disposableCreateConfigFile = vscode.commands.registerCommand('extension.createConfigFile', () => {
// console.log('--config file setup triggered');
// check if the root directory already has a graphquill.config.json file
const graphQuillConfigPath = `${rootPath}/graphquill.config.js`;
if (fs.existsSync(graphQuillConfigPath)) {
vscode.window.showInformationMessage(`A GraphQuill configuration file already exists at ${graphQuillConfigPath}`);
// exit out
return null;
}
// if it does not already exist, write to a new file
fs.writeFileSync(graphQuillConfigPath,
// string to populate the file with
'module.exports = {\n // change "./server/index.js" to the relative path from the root directory to\n // the file that starts your server.\n // if you\'re connecting to an external server,\n // change "./server/index.js" to its URL in the following format:\n // "https://yourserverurl.com"\n entry: \'./server/index.js\',\n\n // change 3000 to the port number that your server runs on\n portNumber: 3000,\n\n // to increase the amount of time allowed for the server to startup, add a time\n // in milliseconds (integer) to the "serverStartupTimeAllowed"\n // serverStartupTimeAllowed: 5000,\n};\n',
'utf-8');
// open the file in vscode
vscode.workspace.openTextDocument(graphQuillConfigPath).then((doc) => {
// apparently openTextDocument doesn't mean it's visible...
vscode.window.showTextDocument(doc);
});
return null;
});
// push it to the subscriptions
context.subscriptions.push(disposableCreateConfigFile);
/** **************************************************************************
* * Fifth GraphQuill option in command palette to SHOW THE SCHEMA
************************************************************************** */
const disposableShowGraphQLSchema = vscode.commands.registerCommand('extension.showGraphQLSchema', async () => {
// console.log('show schema running');
// show output channel, clear any old stuff off of it
gqChannel.show(true);
gqChannel.clear();
// parse the config file
const parseResult = parseConfigFile(rootPath);
entryPoint = parseResult.entryPoint; // will return the found entry point or an empty string
allowServerTimeoutConfigSetting = parseResult.allowServerTimeoutConfigSetting;
portNumber = parseResult.portNumber; // will return the found port number or zero if not found
// console.log('parseResults', parseResult);
// if the entryPoint is falsey, break out and tell the user to create a config file
if (!entryPoint || !portNumber) {
gqChannel.append('The config file was not found or had an error, please use the Create GraphQuill Config File Command to make one.');
// break out of this execution context
return null;
}
// Check ONCE if the port is open (also this does not need the third param)
// will resolve to a true or false value
const serverOnAlready = await checkForRunningServer(portNumber, true);
const externalURL = entryPoint.slice(0, 4) === 'http';
// console.log('--serverOnFromUser after once check is:', serverOnFromUser);
let serverTurnedOnBySchemaOutputter = false;
// trigger serverOn if the user does not already have the server running
// or if user is requesting data from external server
if (!serverOnAlready && !externalURL) {
// start up the user's server, pass in the gqChannel to log any error messages
serverOn(entryPoint, gqChannel);
// give user feedback that server is starting up
gqChannel.clear();
gqChannel.append('The server is starting up...\n');
// await this function that will return true or false based on if the server has been started
// false: if starting the server is longer than the time allotted in the config file (defaults
// to 3 seconds)
serverTurnedOnBySchemaOutputter = await checkForRunningServer(portNumber,
// once setting is false, so the returned promise will only resolve when the server has
// started OR the timeout (next variable or 3sec) is reached
false,
// allowServerT.C.S. is either a time in milliseconds that defaults to 3000
allowServerTimeoutConfigSetting);
// if it is false, that means there was an error starting the server
// notify the user & end the thread of execution
if (!serverTurnedOnBySchemaOutputter) {
// console.log('server is taking too long to startup');
// give feedback to user that port didn't start (and the specified timeout config setting,
// defaults to 3 seconds)
gqChannel.clear();
gqChannel.append(`The server is taking too long to startup (>${(allowServerTimeoutConfigSetting || 3000) / 1000} seconds).\nTo increase this time, update the "serverStartupTimeAllowed" setting in the graphquill.config.js file.`);
// break out, and just in case I'm going to try to kill the port if it did open
// otherwise we could get runaway node processes...
return setTimeout(() => serverOff(portNumber), 5000);
}
}
let url: (undefined|string);
if (externalURL) url = entryPoint;
// console.log('before invoking showSchema: ', url);
// clear the channel off?
gqChannel.clear();
// run required in functionality here, required in
showGraphqlSchema(serverOnAlready, serverTurnedOnBySchemaOutputter, gqChannel, portNumber, url);
// turn the server off if the extension turned it on
// eslint-disable-next-line max-len
// console.log('killing port', 'kill server boolean:', serverTurnedOnByGraphQuill, 'port number', portNumber);
// will resolve to false if graphquill did not start the server,
// will kill the server/port otherwise
return setTimeout(() => (serverTurnedOnBySchemaOutputter && serverOff(portNumber)), 1);
});
context.subscriptions.push(disposableShowGraphQLSchema);
}
// this method is called when your extension is deactivated
export function deactivate() {
// deactivate must return a promise if cleanup operations are async.
// console.log('---deactive function called!!');
// executing the deactivateGQ command seems to achieve a similar effect & is nice because it has
// access to the portNumber variable
vscode.commands.executeCommand('extension.deactivateGraphQuill');
} | the_stack |
import React, { useState, useCallback, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import {
Dropdown, DropdownMenu, DropdownToggle, DropdownItem,
} from 'reactstrap';
import {
IPageInfoAll, isIPageInfoForOperation,
} from '~/interfaces/page';
import { IPageOperationProcessData } from '~/interfaces/page-operation';
import { useSWRxPageInfo } from '~/stores/page';
import loggerFactory from '~/utils/logger';
const logger = loggerFactory('growi:cli:PageItemControl');
export const MenuItemType = {
BOOKMARK: 'bookmark',
RENAME: 'rename',
DUPLICATE: 'duplicate',
DELETE: 'delete',
REVERT: 'revert',
PATH_RECOVERY: 'pathRecovery',
} as const;
export type MenuItemType = typeof MenuItemType[keyof typeof MenuItemType];
export type ForceHideMenuItems = MenuItemType[];
export type AdditionalMenuItemsRendererProps = { pageInfo: IPageInfoAll };
type CommonProps = {
pageInfo?: IPageInfoAll,
isEnableActions?: boolean,
forceHideMenuItems?: ForceHideMenuItems,
onClickBookmarkMenuItem?: (pageId: string, newValue?: boolean) => Promise<void>,
onClickRenameMenuItem?: (pageId: string, pageInfo: IPageInfoAll | undefined) => Promise<void> | void,
onClickDuplicateMenuItem?: (pageId: string) => Promise<void> | void,
onClickDeleteMenuItem?: (pageId: string, pageInfo: IPageInfoAll | undefined) => Promise<void> | void,
onClickRevertMenuItem?: (pageId: string) => Promise<void> | void,
onClickPathRecoveryMenuItem?: (pageId: string) => Promise<void> | void,
additionalMenuItemRenderer?: React.FunctionComponent<AdditionalMenuItemsRendererProps>,
isInstantRename?: boolean,
alignRight?: boolean,
}
type DropdownMenuProps = CommonProps & {
pageId: string,
isLoading?: boolean,
operationProcessData?: IPageOperationProcessData,
}
const PageItemControlDropdownMenu = React.memo((props: DropdownMenuProps): JSX.Element => {
const { t } = useTranslation('');
const {
pageId, isLoading,
pageInfo, isEnableActions, forceHideMenuItems, operationProcessData,
onClickBookmarkMenuItem, onClickRenameMenuItem, onClickDuplicateMenuItem, onClickDeleteMenuItem, onClickRevertMenuItem, onClickPathRecoveryMenuItem,
additionalMenuItemRenderer: AdditionalMenuItems, isInstantRename, alignRight,
} = props;
// eslint-disable-next-line react-hooks/rules-of-hooks
const bookmarkItemClickedHandler = useCallback(async() => {
if (!isIPageInfoForOperation(pageInfo) || onClickBookmarkMenuItem == null) {
return;
}
await onClickBookmarkMenuItem(pageId, !pageInfo.isBookmarked);
}, [onClickBookmarkMenuItem, pageId, pageInfo]);
// eslint-disable-next-line react-hooks/rules-of-hooks
const renameItemClickedHandler = useCallback(async() => {
if (onClickRenameMenuItem == null) {
return;
}
if (!pageInfo?.isMovable) {
logger.warn('This page could not be renamed.');
return;
}
await onClickRenameMenuItem(pageId, pageInfo);
}, [onClickRenameMenuItem, pageId, pageInfo]);
// eslint-disable-next-line react-hooks/rules-of-hooks
const duplicateItemClickedHandler = useCallback(async() => {
if (onClickDuplicateMenuItem == null) {
return;
}
await onClickDuplicateMenuItem(pageId);
}, [onClickDuplicateMenuItem, pageId]);
const revertItemClickedHandler = useCallback(async() => {
if (onClickRevertMenuItem == null) {
return;
}
await onClickRevertMenuItem(pageId);
}, [onClickRevertMenuItem, pageId]);
// eslint-disable-next-line react-hooks/rules-of-hooks
const deleteItemClickedHandler = useCallback(async() => {
if (pageInfo == null || onClickDeleteMenuItem == null) {
return;
}
if (!pageInfo.isDeletable) {
logger.warn('This page could not be deleted.');
return;
}
await onClickDeleteMenuItem(pageId, pageInfo);
}, [onClickDeleteMenuItem, pageId, pageInfo]);
// eslint-disable-next-line react-hooks/rules-of-hooks
const pathRecoveryItemClickedHandler = useCallback(async() => {
if (onClickPathRecoveryMenuItem == null) {
return;
}
await onClickPathRecoveryMenuItem(pageId);
}, [onClickPathRecoveryMenuItem, pageId]);
let contents = <></>;
if (isLoading) {
contents = (
<div className="text-muted text-center my-2">
<i className="fa fa-spinner fa-pulse"></i>
</div>
);
}
else if (pageId != null && pageInfo != null) {
const showDeviderBeforeAdditionalMenuItems = (forceHideMenuItems?.length ?? 0) < 3;
const showDeviderBeforeDelete = AdditionalMenuItems != null || showDeviderBeforeAdditionalMenuItems;
// PathRecovery
// Todo: It is wanted to find a better way to pass operationProcessData to PageItemControl
const shouldShowPathRecoveryButton = operationProcessData?.Rename != null ? operationProcessData?.Rename.isProcessable : false;
contents = (
<>
{ !isEnableActions && (
<DropdownItem>
<p>
{t('search_result.currently_not_implemented')}
</p>
</DropdownItem>
) }
{/* Bookmark */}
{ !forceHideMenuItems?.includes(MenuItemType.BOOKMARK) && isEnableActions && !pageInfo.isEmpty && isIPageInfoForOperation(pageInfo) && (
<DropdownItem
onClick={bookmarkItemClickedHandler}
className="grw-page-control-dropdown-item"
>
<i className="fa fa-fw fa-bookmark-o grw-page-control-dropdown-icon"></i>
{ pageInfo.isBookmarked ? t('remove_bookmark') : t('add_bookmark') }
</DropdownItem>
) }
{/* Move/Rename */}
{ !forceHideMenuItems?.includes(MenuItemType.RENAME) && isEnableActions && pageInfo.isMovable && (
<DropdownItem
onClick={renameItemClickedHandler}
data-testid="open-page-move-rename-modal-btn"
className="grw-page-control-dropdown-item"
>
<i className="icon-fw icon-action-redo grw-page-control-dropdown-icon"></i>
{t(isInstantRename ? 'Rename' : 'Move/Rename')}
</DropdownItem>
) }
{/* Duplicate */}
{ !forceHideMenuItems?.includes(MenuItemType.DUPLICATE) && isEnableActions && (
<DropdownItem
onClick={duplicateItemClickedHandler}
data-testid="open-page-duplicate-modal-btn"
className="grw-page-control-dropdown-item"
>
<i className="icon-fw icon-docs grw-page-control-dropdown-icon"></i>
{t('Duplicate')}
</DropdownItem>
) }
{/* Revert */}
{ !forceHideMenuItems?.includes(MenuItemType.REVERT) && isEnableActions && pageInfo.isRevertible && (
<DropdownItem
onClick={revertItemClickedHandler}
className="grw-page-control-dropdown-item"
>
<i className="icon-fw icon-action-undo grw-page-control-dropdown-icon"></i>
{t('modal_putback.label.Put Back Page')}
</DropdownItem>
) }
{ AdditionalMenuItems && (
<>
{ showDeviderBeforeAdditionalMenuItems && <DropdownItem divider /> }
<AdditionalMenuItems pageInfo={pageInfo} />
</>
) }
{/* PathRecovery */}
{ !forceHideMenuItems?.includes(MenuItemType.PATH_RECOVERY) && isEnableActions && shouldShowPathRecoveryButton && (
<DropdownItem
onClick={pathRecoveryItemClickedHandler}
className="grw-page-control-dropdown-item"
>
<i className="icon-fw icon-wrench grw-page-control-dropdown-icon"></i>
{t('PathRecovery')}
</DropdownItem>
) }
{/* divider */}
{/* Delete */}
{ !forceHideMenuItems?.includes(MenuItemType.DELETE) && isEnableActions && pageInfo.isMovable && (
<>
{ showDeviderBeforeDelete && <DropdownItem divider /> }
<DropdownItem
className={`pt-2 grw-page-control-dropdown-item ${pageInfo.isDeletable ? 'text-danger' : ''}`}
disabled={!pageInfo.isDeletable}
onClick={deleteItemClickedHandler}
data-testid="open-page-delete-modal-btn"
>
<i className="icon-fw icon-trash grw-page-control-dropdown-icon"></i>
{t('Delete')}
</DropdownItem>
</>
)}
</>
);
}
return (
<DropdownMenu positionFixed modifiers={{ preventOverflow: { boundariesElement: undefined } }} right={alignRight}>
{contents}
</DropdownMenu>
);
});
type PageItemControlSubstanceProps = CommonProps & {
pageId: string,
fetchOnInit?: boolean,
children?: React.ReactNode,
operationProcessData?: IPageOperationProcessData,
}
export const PageItemControlSubstance = (props: PageItemControlSubstanceProps): JSX.Element => {
const {
pageId, pageInfo: presetPageInfo, fetchOnInit,
children,
onClickBookmarkMenuItem, onClickRenameMenuItem, onClickDuplicateMenuItem, onClickDeleteMenuItem, onClickPathRecoveryMenuItem,
} = props;
const [isOpen, setIsOpen] = useState(false);
const [shouldFetch, setShouldFetch] = useState(fetchOnInit ?? false);
const { data: fetchedPageInfo, mutate: mutatePageInfo } = useSWRxPageInfo(shouldFetch ? pageId : null);
// update shouldFetch (and will never be false)
useEffect(() => {
if (shouldFetch) {
return;
}
if (!isIPageInfoForOperation(presetPageInfo) && isOpen) {
setShouldFetch(true);
}
}, [isOpen, presetPageInfo, shouldFetch]);
// mutate after handle event
const bookmarkMenuItemClickHandler = useCallback(async(_pageId: string, _newValue: boolean) => {
if (onClickBookmarkMenuItem != null) {
await onClickBookmarkMenuItem(_pageId, _newValue);
}
if (shouldFetch) {
mutatePageInfo();
}
}, [mutatePageInfo, onClickBookmarkMenuItem, shouldFetch]);
const isLoading = shouldFetch && fetchedPageInfo == null;
const renameMenuItemClickHandler = useCallback(async() => {
if (onClickRenameMenuItem == null) {
return;
}
await onClickRenameMenuItem(pageId, fetchedPageInfo ?? presetPageInfo);
}, [onClickRenameMenuItem, pageId, fetchedPageInfo, presetPageInfo]);
const duplicateMenuItemClickHandler = useCallback(async() => {
if (onClickDuplicateMenuItem == null) {
return;
}
await onClickDuplicateMenuItem(pageId);
}, [onClickDuplicateMenuItem, pageId]);
const deleteMenuItemClickHandler = useCallback(async() => {
if (onClickDeleteMenuItem == null) {
return;
}
await onClickDeleteMenuItem(pageId, fetchedPageInfo ?? presetPageInfo);
}, [onClickDeleteMenuItem, pageId, fetchedPageInfo, presetPageInfo]);
const pathRecoveryMenuItemClickHandler = useCallback(async() => {
if (onClickPathRecoveryMenuItem == null) {
return;
}
await onClickPathRecoveryMenuItem(pageId);
}, [onClickPathRecoveryMenuItem, pageId]);
return (
<Dropdown isOpen={isOpen} toggle={() => setIsOpen(!isOpen)} data-testid="open-page-item-control-btn">
{ children ?? (
<DropdownToggle color="transparent" className="border-0 rounded btn-page-item-control d-flex align-items-center justify-content-center">
<i className="icon-options"></i>
</DropdownToggle>
) }
<PageItemControlDropdownMenu
{...props}
isLoading={isLoading}
pageInfo={fetchedPageInfo ?? presetPageInfo}
onClickBookmarkMenuItem={bookmarkMenuItemClickHandler}
onClickRenameMenuItem={renameMenuItemClickHandler}
onClickDuplicateMenuItem={duplicateMenuItemClickHandler}
onClickDeleteMenuItem={deleteMenuItemClickHandler}
onClickPathRecoveryMenuItem={pathRecoveryMenuItemClickHandler}
/>
</Dropdown>
);
};
type PageItemControlProps = CommonProps & {
pageId?: string,
children?: React.ReactNode,
operationProcessData?: IPageOperationProcessData,
}
export const PageItemControl = (props: PageItemControlProps): JSX.Element => {
const { pageId } = props;
if (pageId == null) {
return <></>;
}
return <PageItemControlSubstance pageId={pageId} {...props} />;
};
type AsyncPageItemControlProps = Omit<CommonProps, 'pageInfo'> & {
pageId?: string,
children?: React.ReactNode,
}
export const AsyncPageItemControl = (props: AsyncPageItemControlProps): JSX.Element => {
const { pageId } = props;
if (pageId == null) {
return <></>;
}
return <PageItemControlSubstance pageId={pageId} fetchOnInit {...props} />;
}; | the_stack |
import React from 'react';
import { Simulator, SimulatorButton } from "./simulator";
import { tickEvent } from '../telemetry/appinsights';
import '../css/Joystick.css';
export interface JoystickProps {
simulator: Simulator;
changeMode: (mode: "play" | "share" | "mod") => void;
}
const SVG_WIDTH = 40;
const HALF_WIDTH = SVG_WIDTH >> 1;
export class Joystick extends React.Component<JoystickProps, {}> {
protected dPadUp: SVGRectElement | undefined;
protected dPadDown: SVGRectElement | undefined;
protected dPadLeft: SVGRectElement | undefined;
protected dPadRight: SVGRectElement | undefined;
protected joystickHandle: SVGCircleElement | undefined;
protected joystickAnimation: number | undefined;
protected handleX = SVG_WIDTH >> 1;
protected handleY = SVG_WIDTH >> 1;
protected lastOctet: number | undefined;
protected joystickGestureCount: number = 0;
protected joystickGestureInterval: any;
componentDidMount() {
this.dPadUp = this.refs["dpad-up"] as SVGRectElement;
this.dPadDown = this.refs["dpad-down"] as SVGRectElement;
this.dPadLeft = this.refs["dpad-left"] as SVGRectElement;
this.dPadRight = this.refs["dpad-right"] as SVGRectElement;
this.joystickHandle = this.refs["joystick-handle"] as SVGCircleElement;
this.bindEvents(this.refs["joystick-bounds"] as HTMLDivElement);
this.props.simulator.addChangeListener(this.buttonChangeListener);
}
componentWillUnmount() {
this.dPadUp = undefined;
this.dPadDown = undefined;
this.dPadLeft = undefined;
this.dPadRight = undefined;
this.joystickHandle = undefined;
this.props.simulator.removeChangeListener(this.buttonChangeListener);
this.cleanupInterval();
}
render() {
const { changeMode } = this.props;
return (
<div ref="joystick-container" className="game-joystick">
<div className="spacer" />
<div className="action-button">
<button className="share-mod-button" onClick={() => changeMode("mod")}>Mod</button>
</div>
<svg xmlns="http://www.w3.org/2000/svg" ref="joystick-bounds" className="game-joystick-svg" viewBox="1 0 40 40" width="200px" height="200px">
<circle id="joystick-background" cx="20" cy="20" r="16" fill="#397382" stroke="#397382" strokeWidth="2"/>
<rect ref="dpad-up" x="16" y="6" width="8" height="12" rx="2" fill="#cecece" stroke="none" strokeWidth="1" />
<rect ref="dpad-down" x="16" y="22" width="8" height="12" rx="2" fill="#cecece" stroke="none" strokeWidth="1" />
<rect ref="dpad-right" x="22" y="16" width="12" height="8" ry="2" fill="#cecece" stroke="none" strokeWidth="1" />
<rect ref="dpad-left" x="6" y="16" width="12" height="8" ry="2" fill="#cecece" stroke="none" strokeWidth="1" />
<circle cx="20" cy="20" r="6" fill="#cecece" />
<circle ref="joystick-handle" cx="20" cy="20" r="6" fill="#333" stroke="#999" strokeWidth="2" />
</svg>
</div>
)
}
protected buttonChangeListener = (button: SimulatorButton, isPressed: boolean) => {
switch (button) {
case SimulatorButton.Down:
this.updateDirection(this.dPadDown, isPressed);
break;
case SimulatorButton.Up:
this.updateDirection(this.dPadUp, isPressed);
break;
case SimulatorButton.Left:
this.updateDirection(this.dPadLeft, isPressed);
break;
case SimulatorButton.Right:
this.updateDirection(this.dPadRight, isPressed);
break;
}
}
protected updateDirection(button: SVGRectElement | undefined, isPressed: boolean) {
if (button) {
button.setAttribute("fill", isPressed ? "#249ca3" : "#cecece");
}
}
protected bindEvents(div: HTMLDivElement) {
if (!div) return;
if (hasPointerEvents()) {
this.bindPointerEvents(div);
}
else if (isTouchEnabled()) {
this.bindTouchEvents(div);
}
else {
this.bindMouseEvents(div);
}
this.joystickGestureInterval = setInterval(this.logEvents, 5000);
}
protected bindPointerEvents(div: HTMLDivElement) {
let inGesture = false;
div.addEventListener("pointerup", ev => {
if (inGesture) {
this.updateJoystickDrag(ev.clientX, ev.clientY);
this.startAnimation();
}
inGesture = false;
});
div.addEventListener("pointerdown", ev => {
this.updateJoystickDrag(ev.clientX, ev.clientY);
inGesture = true
});
div.addEventListener("pointermove", ev => {
if (inGesture) this.updateJoystickDrag(ev.clientX, ev.clientY);
});
div.addEventListener("pointerleave", ev => {
if (inGesture) {
this.updateJoystickDrag(ev.clientX, ev.clientY);
this.startAnimation();
}
inGesture = false;
});
}
protected bindMouseEvents(div: HTMLDivElement) {
let inGesture = false;
div.addEventListener("mouseup", ev => {
if (inGesture) {
this.updateJoystickDrag(ev.clientX, ev.clientY);
this.startAnimation();
}
inGesture = false;
});
div.addEventListener("mousedown", ev => {
this.updateJoystickDrag(ev.clientX, ev.clientY);
inGesture = true
});
div.addEventListener("mousemove", ev => {
if (inGesture) this.updateJoystickDrag(ev.clientX, ev.clientY);
});
div.addEventListener("mouseleave", ev => {
if (inGesture) {
this.updateJoystickDrag(ev.clientX, ev.clientY);
this.startAnimation();
}
inGesture = false;
});
}
protected bindTouchEvents(div: HTMLDivElement) {
let touchIdentifier: number | undefined;
div.addEventListener("touchend", ev => {
if (touchIdentifier) {
const touch = getTouch(ev, touchIdentifier);
if (touch) {
this.updateJoystickDrag(touch.clientX, touch.clientY);
this.startAnimation();
ev.preventDefault();
}
}
touchIdentifier = undefined;
});
div.addEventListener("touchstart", ev => {
touchIdentifier = ev.changedTouches[0].identifier;
this.updateJoystickDrag(ev.changedTouches[0].clientX, ev.changedTouches[0].clientY);
});
div.addEventListener("touchmove", ev => {
if (touchIdentifier) {
const touch = getTouch(ev, touchIdentifier);
if (touch) {
this.updateJoystickDrag(touch.clientX, touch.clientY);
ev.preventDefault();
}
}
});
div.addEventListener("touchcancel", ev => {
if (touchIdentifier) {
const touch = getTouch(ev, touchIdentifier);
if (touch) {
this.updateJoystickDrag(touch.clientX, touch.clientY);
this.startAnimation();
}
}
touchIdentifier = undefined;
});
}
protected updateJoystickDrag(x: number, y: number) {
if (this.joystickHandle) {
const bounds = (this.refs["joystick-bounds"] as HTMLDivElement).getBoundingClientRect();
const dx = ((x - bounds.left) * (SVG_WIDTH / bounds.width)) - HALF_WIDTH;
const dy = ((y - bounds.top) * (SVG_WIDTH / bounds.height)) - HALF_WIDTH;
const angle = Math.atan2(dy, dx);
const distance = Math.min(Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2)), 10);
this.setHandlePosition(HALF_WIDTH + distance * Math.cos(angle), HALF_WIDTH + distance * Math.sin(angle));
}
}
protected startAnimation() {
this.clearButtonPresses();
if (this.joystickHandle) {
this.stopAnimation();
const animationFrame = () => {
let distance = this.getHandleDistance();
if (distance < 0.5) {
this.setHandlePosition(HALF_WIDTH, HALF_WIDTH, true);
this.stopAnimation();
}
else {
const angle = this.getHandleAngle();
distance = Math.max(distance - 1, 0);
this.setHandlePosition(HALF_WIDTH + distance * Math.cos(angle), HALF_WIDTH + distance * Math.sin(angle), true);
this.joystickAnimation = requestAnimationFrame(animationFrame);
}
}
this.joystickAnimation = requestAnimationFrame(animationFrame);
}
}
protected stopAnimation() {
if (this.joystickAnimation) {
cancelAnimationFrame(this.joystickAnimation);
this.joystickAnimation = undefined;
this.joystickGestureCount += 1;
}
}
protected logEvents = () => {
if (this.joystickGestureCount > 0) {
tickEvent("shareExperiment.play.joystickGestureUp", {"count": this.joystickGestureCount});
this.joystickGestureCount = 0;
}
}
protected cleanupInterval = () => {
clearInterval(this.joystickGestureInterval);
this.joystickGestureCount = 0;
}
/**
*
* @param x The x location in SVG coordinates
* @param y The y location in SVG coordinates
*/
protected setHandlePosition(x: number, y: number, animation = false) {
if (this.joystickHandle) {
this.joystickHandle.setAttribute("cx", "" + x)
this.joystickHandle.setAttribute("cy", "" + y)
this.handleX = x;
this.handleY = y;
if (!animation) {
if (this.getHandleDistance() < 5) {
this.clearButtonPresses();
}
else {
const { simulator } = this.props;
const angle = this.getHandleAngle();
const octet = (5 + Math.floor((angle / (Math.PI / 4)) - 0.5)) % 8;
if (octet === this.lastOctet) return;
this.lastOctet = octet;
let left = false;
let right = false;
let up = false;
let down = false;
switch (octet) {
case 0:
left = true;
break;
case 1:
left = true;
up = true;
break;
case 2:
up = true;
break;
case 3:
up = true;
right = true;
break;
case 4:
right = true;
break;
case 5:
right = true;
down = true;
break;
case 6:
down = true;
break;
case 7:
left = true;
down = true;
break;
}
if (down) simulator.pressButton(SimulatorButton.Down);
else simulator.releaseButton(SimulatorButton.Down);
if (up) simulator.pressButton(SimulatorButton.Up);
else simulator.releaseButton(SimulatorButton.Up);
if (left) simulator.pressButton(SimulatorButton.Left);
else simulator.releaseButton(SimulatorButton.Left);
if (right) simulator.pressButton(SimulatorButton.Right);
else simulator.releaseButton(SimulatorButton.Right);
}
}
}
}
protected getHandleAngle() {
return Math.atan2(this.handleY - HALF_WIDTH, this.handleX - HALF_WIDTH);;
}
protected getHandleDistance() {
return Math.sqrt(Math.pow(this.handleX - HALF_WIDTH, 2) + Math.pow(this.handleY - HALF_WIDTH, 2));
}
protected clearButtonPresses() {
const { simulator } = this.props;
simulator.releaseButton(SimulatorButton.Down);
simulator.releaseButton(SimulatorButton.Up);
simulator.releaseButton(SimulatorButton.Left);
simulator.releaseButton(SimulatorButton.Right);
this.lastOctet = undefined;
}
}
function hasPointerEvents(): boolean {
return typeof window != "undefined" && !!(window as any).PointerEvent;
}
function isTouchEnabled(): boolean {
return typeof window !== "undefined" &&
('ontouchstart' in window // works on most browsers
|| (navigator && navigator.maxTouchPoints > 0)); // works on IE10/11 and Surface);
}
function getTouch(ev: TouchEvent, identifier: number) {
for (let i = 0; i < ev.changedTouches.length; i++) {
if (ev.changedTouches[i].identifier === identifier) {
return ev.changedTouches[i];
}
}
return undefined;
}
export default Joystick; | the_stack |
import { readFileSync } from "fs";
import * as ts from "typescript";
import * as uuid from "uuid";
import * as uml from "./uml/index";
export class Delinter {
private _umlCodeModel: uml.CodeModel;
/**
* Uml code model description filled by the parse method(s)
*
* @readonly
* @type {uml.CodeModel}
* @memberOf Delinter
*/
public get umlCodeModel(): uml.CodeModel {
return this._umlCodeModel;
}
constructor() {
this._umlCodeModel = new uml.CodeModel();
}
/**
* Delint a TypeScript source file, adding the parsed elements to umlCodeModel.
*
* @param {ts.SourceFile} file TypeScript source file
*
* @memberOf Delinter
*/
public parse(file: ts.SourceFile) {
this._delintNode(file);
}
private _delintNode(node: ts.Node) {
switch (node.kind) {
case ts.SyntaxKind.ClassDeclaration:
this._delintClass(node as ts.ClassDeclaration, this._delintClassNode.bind(this));
break;
case ts.SyntaxKind.InterfaceDeclaration:
this._delintClass(node as ts.InterfaceDeclaration, this._delintInterfaceNode.bind(this));
break;
default:
ts.forEachChild(node, (n) => { this._delintNode(n); });
break;
}
}
private _delintClass(
node: ts.ClassDeclaration | ts.InterfaceDeclaration,
delintChild: (child: ts.Node, umlClass: uml.Class) => void,
) {
let stereotype = uml.Stereotype.None;
if (node.kind === ts.SyntaxKind.InterfaceDeclaration) {
stereotype = uml.Stereotype.Interface;
}
const umlClass = new uml.Class(node.name.getText(), stereotype);
this._umlCodeModel.nodes.setValue(umlClass.identifier, umlClass);
this._delintHeritageClauses(node.heritageClauses, umlClass);
ts.forEachChild(node, (n) => { delintChild(n, umlClass); });
}
private _delintClassNode(node: ts.Node, umlClass: uml.Class) {
switch (node.kind) {
case ts.SyntaxKind.PropertyDeclaration:
this._delintProperty(node as ts.PropertyDeclaration, umlClass);
break;
case ts.SyntaxKind.GetAccessor:
case ts.SyntaxKind.SetAccessor:
this._delintClassGetterSetter(node as ts.GetAccessorDeclaration | ts.SetAccessorDeclaration, umlClass);
break;
case ts.SyntaxKind.MethodDeclaration:
this._delintMethod(node as ts.MethodDeclaration, umlClass);
break;
default:
ts.forEachChild(node, (n) => { this._delintClassNode(n, umlClass); });
break;
}
}
private _delintInterfaceNode(node: ts.Node, umlClass: uml.Class) {
switch (node.kind) {
case ts.SyntaxKind.PropertySignature:
this._delintProperty(node as ts.PropertySignature, umlClass);
break;
case ts.SyntaxKind.MethodSignature:
this._delintMethod(node as ts.MethodDeclaration, umlClass);
break;
default:
ts.forEachChild(node, (n) => { this._delintClassNode(n, umlClass); });
break;
}
}
private _delintHeritageClauses(heritageClauses: ts.HeritageClause[], umlClass: uml.Class) {
if (heritageClauses) {
heritageClauses.forEach((h) => {
switch (h.token) {
case ts.SyntaxKind.ImplementsKeyword:
h.types.forEach((t) => {
const interfaceName = t.expression.getText();
// Add interface to CodeModel if not exists
if (!this._umlCodeModel.nodes.containsKey(interfaceName)) {
const umlInterface = new uml.Class(interfaceName, uml.Stereotype.Interface);
this._umlCodeModel.nodes.setValue(interfaceName, umlInterface);
}
const generalization = new uml.Generalization(umlClass.identifier, interfaceName);
this._umlCodeModel.generalizations.add(generalization);
});
break;
case ts.SyntaxKind.ExtendsKeyword:
h.types.forEach((t) => {
const parentClassName = t.expression.getText();
// Add interface to CodeModel if not exists
if (!this._umlCodeModel.nodes.containsKey(parentClassName)) {
const umlParentClass = new uml.Class(parentClassName);
this._umlCodeModel.nodes.setValue(parentClassName, umlParentClass);
}
const generalization = new uml.Generalization(umlClass.identifier, parentClassName);
this._umlCodeModel.generalizations.add(generalization);
});
break;
/* istanbul ignore next: default case never reached */
default:
break;
}
});
}
}
private _delintMethod(methodDeclaration: ts.MethodDeclaration | ts.MethodSignature, umlClass: uml.Class) {
const identifier = methodDeclaration.name.getText();
// Default to public accessibility
const accessibility = this._delintAccessibilityModifiers(methodDeclaration.modifiers);
const method = new uml.FunctionProperty(identifier, accessibility);
if (methodDeclaration.type) {
method.returnType = this._delintType(methodDeclaration.type);
}
methodDeclaration.parameters.forEach((p) => {
const parameter = new uml.Parameter(p.name.getText());
parameter.type = this._delintType(p.type);
if (p.initializer) {
parameter.defaultInitializer = p.initializer.getText();
parameter.optional = true;
}
if (p.questionToken) {
parameter.optional = true;
}
method.parameters.push(parameter);
});
method.optional = methodDeclaration.questionToken !== undefined;
umlClass.methods.setValue(identifier, method);
}
private _delintClassGetterSetter(node: ts.GetAccessorDeclaration | ts.SetAccessorDeclaration, umlClass: uml.Class) {
const identifier = node.name.getText();
// Default to public accessibility
const accessibility = this._delintAccessibilityModifiers(node.modifiers);
let type: uml.Type;
if (node.kind === ts.SyntaxKind.GetAccessor) {
type = this._delintType(node.type);
} else {
if (node.parameters.length > 0) {
type = this._delintType(node.parameters[0].type);
}
}
const variable = new uml.VariableProperty(identifier, accessibility, type);
// Set stereotype based on kind
const existingVariable = umlClass.variables.getValue(identifier);
let stereotype: uml.Stereotype;
if (node.kind === ts.SyntaxKind.GetAccessor) {
// If a setter already exists, use stereotype GetSet
stereotype = (existingVariable && existingVariable.stereotype === uml.Stereotype.Set) ?
uml.Stereotype.GetSet :
stereotype = uml.Stereotype.Get;
} else {
// If a setter already exists, use stereotype GetSet
stereotype = (existingVariable && existingVariable.stereotype === uml.Stereotype.Get) ?
uml.Stereotype.GetSet :
uml.Stereotype.Set;
}
variable.stereotype = stereotype;
umlClass.variables.setValue(identifier, variable);
this._typeAssociations(umlClass.identifier, type).forEach((a) => {
this.umlCodeModel.associations.add(a);
});
}
private _delintProperty(property: ts.PropertyDeclaration | ts.PropertySignature, umlInterface: uml.Class) {
const identifier = property.name.getText();
// Default to public accessibility
const accessibility = this._delintAccessibilityModifiers(property.modifiers);
const type = this._delintType(property.type);
const variable = new uml.VariableProperty(identifier, accessibility, type);
variable.optional = property.questionToken !== undefined;
umlInterface.variables.setValue(identifier, variable);
this._typeAssociations(umlInterface.identifier, type).forEach((a) => {
this.umlCodeModel.associations.add(a);
});
}
private _delintAccessibilityModifiers(modifiers: ts.NodeArray<ts.Modifier>) {
let accessibility = uml.Accessibility.Public;
if (modifiers) {
modifiers.forEach((m) => {
switch (m.kind) {
case ts.SyntaxKind.PrivateKeyword:
accessibility = uml.Accessibility.Private;
break;
case ts.SyntaxKind.ProtectedKeyword:
accessibility = uml.Accessibility.Protected;
break;
case ts.SyntaxKind.PublicKeyword:
accessibility = uml.Accessibility.Public;
break;
}
});
}
return accessibility;
}
private _delintType(typeNode: ts.TypeNode): uml.PrimaryType | uml.UnionOrIntersectionType {
let type: uml.PrimaryType | uml.UnionOrIntersectionType = null;
const kind = typeNode ? typeNode.kind : null;
switch (kind) {
case ts.SyntaxKind.AnyKeyword:
case ts.SyntaxKind.NumberKeyword:
case ts.SyntaxKind.BooleanKeyword:
case ts.SyntaxKind.StringKeyword:
case ts.SyntaxKind.SymbolKeyword:
case ts.SyntaxKind.VoidKeyword:
type = new uml.PrimaryType(typeNode.getText(), uml.PrimaryTypeKind.PredefinedType);
break;
case ts.SyntaxKind.TypeReference:
const typeReference = typeNode as ts.TypeReferenceNode;
type = new uml.PrimaryType(typeReference.getText(), uml.PrimaryTypeKind.TypeReference);
type.name = typeReference.typeName.getText();
const typeRef = (typeNode as any) as ts.TypeReference;
type.typeArguments = this._delintTypeArguments((typeRef.typeArguments as any) as ts.TypeNode[]);
break;
case ts.SyntaxKind.TypeLiteral:
type = new uml.PrimaryType("TypeLiteral", uml.PrimaryTypeKind.ObjectType);
break;
case ts.SyntaxKind.TupleType:
type = new uml.PrimaryType(typeNode.getText(), uml.PrimaryTypeKind.TupleType);
const tupleType = typeNode as ts.TupleTypeNode;
type.typeArguments = this._delintTypeArguments(tupleType.elementTypes);
break;
case ts.SyntaxKind.ArrayType:
type = new uml.PrimaryType(typeNode.getText(), uml.PrimaryTypeKind.ArrayType);
break;
case ts.SyntaxKind.TypeQuery:
type = new uml.PrimaryType(typeNode.getText(), uml.PrimaryTypeKind.TypeQuery);
break;
case ts.SyntaxKind.ThisType:
type = new uml.PrimaryType(typeNode.getText(), uml.PrimaryTypeKind.ThisType);
break;
case ts.SyntaxKind.UnionType:
type = new uml.UnionOrIntersectionType(typeNode.getText(), uml.UnionOrIntersectionTypeKind.Union);
const union = typeNode as ts.UnionOrIntersectionTypeNode;
type.types = this._delintTypeArguments(union.types);
break;
case ts.SyntaxKind.IntersectionType:
type = new uml.UnionOrIntersectionType(typeNode.getText(),
uml.UnionOrIntersectionTypeKind.Intersection);
const intersection = typeNode as ts.UnionOrIntersectionTypeNode;
type.types = this._delintTypeArguments(intersection.types);
break;
default:
type = new uml.PrimaryType("any", uml.PrimaryTypeKind.ImplicitAny);
break;
}
return type;
}
private _delintTypeArguments(typeArguments: ts.TypeNode[]): uml.Type[] {
let delintedTypes: uml.Type[] = [];
if (typeArguments) {
delintedTypes = typeArguments.map((value) => {
return this._delintType(value);
});
}
return delintedTypes;
}
private _typeAssociations(from: string, type: uml.Type): uml.Association[] {
// Add association to type
let associations: uml.Association[] = [];
if (type) {
if (type instanceof uml.PrimaryType || type instanceof uml.UnionOrIntersectionType) {
switch (type.kind) {
case uml.PrimaryTypeKind.TypeReference:
associations = [new uml.Association(from, type.name)];
// Fall through to process potential (generic) type arguments
case uml.PrimaryTypeKind.ArrayType:
case uml.PrimaryTypeKind.TupleType:
(type as uml.PrimaryType).typeArguments.forEach((t) => {
associations = associations.concat(this._typeAssociations(from, t));
});
break;
case uml.UnionOrIntersectionTypeKind.Union:
case uml.UnionOrIntersectionTypeKind.Intersection:
(type as uml.UnionOrIntersectionType).types.forEach((t) => {
associations = associations.concat(this._typeAssociations(from, t));
});
break;
default:
// Do not produce associations
break;
}
}
}
return associations;
}
} | the_stack |
import {Injectable} from '@angular/core';
import {LogicEnum} from '@renderer/enum/logic.enum';
import {PropertyEnum} from '@renderer/enum/property.enum';
import {ColumnModel} from '@renderer/model/column.model';
import {DatabaseModel} from '@renderer/model/database.model';
import {PropertyModel} from '@renderer/model/property.model';
import {RequestModel} from '@renderer/model/request.model';
import {ResponseModel} from '@renderer/model/response.model';
import {BaseService} from '@renderer/services/base.service';
import {HttpService} from '@renderer/services/http.service';
import {SqlUtils} from '@renderer/utils/sql.utils';
import {StringUtils} from '@renderer/utils/string.utils';
import {TableTtlModel} from '@renderer/model/table/table.ttl.model';
import {SshService} from '@renderer/services/ssh.service';
import {BasicService} from '@renderer/services/system/basic.service';
import {ForwardService} from '@renderer/services/forward.service';
import {FactoryService} from "@renderer/services/factory.service";
@Injectable()
export class TableService extends ForwardService implements BaseService {
constructor(httpService: HttpService,
factoryService: FactoryService,
sshService: SshService,
basicService: BasicService) {
super(basicService, factoryService, httpService, sshService);
}
getResponse(request: RequestModel, sql?: string): Promise<ResponseModel> {
return this.forward(request, sql);
}
getAll(request: RequestModel, database: string): Promise<ResponseModel> {
const sql = StringUtils.format('SELECT name, engine FROM system.tables WHERE database = \'{0}\'', [database]);
return this.getResponse(request, sql);
}
check(request: RequestModel, database: string, table: string): Promise<ResponseModel> {
const sql = StringUtils.format(`
SELECT
name
FROM
system.tables
WHERE
database = '{0}' AND name = '{1}'
`, [database, table]);
return this.getResponse(request, sql);
}
getSize(request: RequestModel, database: string, table: string): Promise<ResponseModel> {
const sql = StringUtils.format(`
SELECT
database AS db, table AS name, SUM(bytes_on_disk) AS tableUsedBytes,
formatReadableSize(sum(bytes_on_disk)) AS value,
if(SUM(bytes_on_disk) > (1024*1024*1024*50), 1, 0) AS flag
FROM system.parts
WHERE database = '{0}' AND name = '{1}'
GROUP BY db, name
`, [database, table]);
return this.getResponse(request, sql);
}
createTable(request: RequestModel, configure: DatabaseModel, columns: ColumnModel[]): Promise<ResponseModel> {
let sql = StringUtils.format('CREATE TABLE {0} (\n', [SqlUtils.getTableName(configure.database, configure.targetName)]);
sql += StringUtils.format('{0}\n', [this.builderColumnsToString(columns)]);
sql += StringUtils.format(') {0}\n', [this.builderEngine(configure)]);
const mergeProperties = this.mergeProperties(configure);
sql += this.builderProperties(mergeProperties);
return this.getResponse(request, sql);
}
delete(request: RequestModel, value: DatabaseModel): Promise<ResponseModel> {
const sql = StringUtils.format('DROP TABLE {0}', [SqlUtils.getTableName(value.database, value.name)]);
return this.getResponse(request, sql);
}
rename(request: RequestModel, value: DatabaseModel, newName: string): Promise<ResponseModel> {
const sql = StringUtils.format('RENAME TABLE {0} TO {1}', [SqlUtils.getTableName(value.database, value.name), SqlUtils.getTableName(value.database, newName)]);
return this.getResponse(request, sql);
}
truncate(request: RequestModel, value: DatabaseModel): Promise<ResponseModel> {
const sql = StringUtils.format('TRUNCATE TABLE {0}', [SqlUtils.getTableName(value.database, value.name)]);
return this.getResponse(request, sql);
}
clean(request: RequestModel, value: DatabaseModel, partition: string): Promise<ResponseModel> {
const sql = StringUtils.format('ALTER TABLE {0} DROP PARTITION ID \'{1}\'',
[SqlUtils.getTableName(value.database, value.name), partition]);
return this.getResponse(request, sql);
}
optimize(request: RequestModel, value: DatabaseModel, partition: string, final: boolean): Promise<ResponseModel> {
let sql = StringUtils.format('OPTIMIZE TABLE {0} PARTITION \'{1}\'', [SqlUtils.getTableName(value.database, value.name), partition]);
if (final) {
sql = StringUtils.format('{0} FINAL', [sql]);
}
return this.getResponse(request, sql);
}
getCreateStatement(request: RequestModel, value: DatabaseModel): Promise<ResponseModel> {
const sql = StringUtils.format('SHOW CREATE TABLE {0}', [SqlUtils.getTableName(value.database, value.name)]);
return this.getResponse(request, sql);
}
getPartitions(request: RequestModel, value: DatabaseModel, partition?: string, logic?: LogicEnum): Promise<ResponseModel> {
let sql = StringUtils.format(`
SELECT
DISTINCT "partition" AS "partition", partition_id AS id,
engine, SUM(rows) AS rows, formatReadableSize(SUM(bytes_on_disk)) AS size
FROM
"system".parts
WHERE
"database" = '{0}'
AND "table" = '{1}'
GROUP BY "partition", partition_id, engine
ORDER BY "partition" ASC`, [value.database, value.name]);
if (StringUtils.isNotEmpty(partition) && StringUtils.isNotEmpty(logic)) {
sql = StringUtils.format(`
SELECT
DISTINCT "partition" AS "partition", partition_id AS id,
engine, SUM(rows) AS rows, formatReadableSize(SUM(bytes_on_disk)) AS size
FROM
"system".parts
WHERE
"database" = '{0}'
AND "table" = '{1}'
AND "partition" {2} '{3}'
GROUP BY "partition", partition_id, engine
ORDER BY "partition" ASC`, [value.database, value.name, logic, partition]);
}
return this.getResponse(request, sql);
}
getPreview(request: RequestModel, value: DatabaseModel): Promise<ResponseModel> {
const sql = StringUtils.format(`SELECT * FROM {0} LIMIT 10`, [SqlUtils.getTableName(value.database, value.name)]);
return this.getResponse(request, sql);
}
getTimeColumns(request: RequestModel, value: DatabaseModel): Promise<ResponseModel> {
const sql = StringUtils.format(`
SELECT name FROM "system"."columns"
WHERE "database" = '{0}' AND "table" = '{1}' AND type like 'Date%'`,
[value.database, value.name]);
return this.getResponse(request, sql);
}
modifyTTL(request: RequestModel, value: TableTtlModel): Promise<ResponseModel> {
let sql;
if (value.custom) {
sql = StringUtils.format('ALTER TABLE {0} MODIFY TTL `{1}` {2}',
[SqlUtils.getTableName(value.database, value.table), value.column, value.value]);
} else {
sql = StringUtils.format('ALTER TABLE {0} MODIFY TTL `{1}` + INTERVAL {2} {3}',
[SqlUtils.getTableName(value.database, value.table), value.column, value.ranger, value.value]);
}
return this.getResponse(request, sql);
}
getTTL(request: RequestModel, value: TableTtlModel): Promise<ResponseModel> {
const sql = StringUtils.format(`
SELECT
extract(engine_full, 'TTL [\\s\\S]*ETTINGS') AS full,
REPLACE(REPLACE(full, 'TTL', ''), ' SETTINGS', '') AS ttl,
splitByString('+', ttl) AS ttlArray,
trimBoth(arrayElement(ttlArray, 1)) AS "column",
extract(arrayElement(ttlArray, 2), '\\d+') AS value,
splitByString('(', replace(arrayElement(ttlArray, 2), 'toInterval', '')) AS rangerArray,
upperUTF8(arrayElement(rangerArray, 1)) AS ranger
FROM "system"."tables"
WHERE "database" = '{0}' AND "name" = '{1}'
`,
[value.database, value.table]);
return this.getResponse(request, sql);
}
removeTTL(request: RequestModel, value: TableTtlModel): Promise<ResponseModel> {
const sql = StringUtils.format(`{0} REMOVE TTL`,
[SqlUtils.getAlterTablePrefix(value.database, value.table)]);
return this.getResponse(request, sql);
}
builderColumnsToString(columns: ColumnModel[]): string {
let columnStr = '';
columns.forEach((value, index) => {
if (index !== columns.length - 1) {
columnStr += this.builderColumnToString(value, true);
} else {
columnStr += this.builderColumnToString(value, false);
}
});
return columnStr;
}
builderColumnToString(value: ColumnModel, end: boolean): string {
let column: string;
let dStr: string;
if (value.empty) {
dStr = StringUtils.format(' {0} Nullable({1})', [value.name, value.type]);
} else {
dStr = StringUtils.format(' {0} {1}', [value.name, value.type]);
}
const endStr = end ? ',\n' : '';
if (StringUtils.isNotEmpty(value.description)) {
column = StringUtils.format(` {0} COMMENT '{1}' {2}`, [dStr, value.description, endStr]);
} else {
column = StringUtils.format(' {0} {1}', [dStr, endStr]);
}
return column;
}
/**
* Build key-value pairs based on configured table engine parameters
* @param properties Configuration parameters
* @returns sql string
*/
private builderProperties(properties: PropertyModel[]): string {
let substr: string = '';
// const map = this.flatProperties(properties);
// map.forEach((v, k) => {
// if (k !== 'type') {
// substr += StringUtils.format('\n {0} = \'{1}\',', [k, v]);
// }
// });
properties
.filter(p => p.origin !== undefined && StringUtils.isNotEmpty(p.origin))
.filter(p => p.value !== undefined)
.forEach(p => {
substr += StringUtils.format('\n {0} = \'{1}\',', [p.origin, p.value]);
});
if (StringUtils.isNotEmpty(substr)) {
substr = StringUtils.format('SETTINGS {0}', [substr.substring(0, substr.length - 1)]);
}
return substr;
}
private builderEngine(configure: DatabaseModel): string {
let sql: string = '';
const prefix = '\nENGINE = ';
switch (configure.propertyType) {
case PropertyEnum.key:
default:
sql = StringUtils.format('{0} {1}()', [prefix, configure.type]);
break;
case PropertyEnum.name:
const substr = configure.properties
.filter(element => StringUtils.isNotEmpty(element.value))
.flatMap(element => StringUtils.format('\'{0}\'', [element.value]))
.join(', ');
sql = StringUtils.format('{0} {1}({2})', [prefix, configure.type, substr]);
break;
}
return sql;
}
private flatProperties(properties: PropertyModel[]): Map<string, string> {
const map = new Map<string, string>();
properties
.filter(p => p.isSetting === undefined || p.isSetting)
.forEach(p => {
if (StringUtils.isNotEmpty(p.origin)) {
map.set('type', PropertyEnum.key);
map.set(p.origin, p.value);
} else {
map.set('type', PropertyEnum.name);
map.set(p.name, p.value);
}
});
return map;
}
/**
* Merges required and optional configurations
* @param configure Data model configuration
* @private merges array
*/
private mergeProperties(configure: DatabaseModel): PropertyModel[] {
let applyArray = new Array();
if (configure?.properties) {
applyArray = applyArray.concat(configure.properties);
}
const filterOptionalProperties = configure.optionalProperties?.filter(element => StringUtils.isNotEmpty(element.value));
if (filterOptionalProperties) {
applyArray = applyArray.concat(filterOptionalProperties);
}
return applyArray;
}
} | the_stack |
import { TextRange, TextProcessingOptions } from '../common';
import { TextHelper } from '../text_helper';
import * as deasciifier from '../deasciifier'
import * as testdata from './testdata';
import chai = require('chai');
let assert = chai.assert;
let expect = chai.expect;
describe('Asciifier', function () {
let asciifier = new deasciifier.Asciifier();
it('should asciify', function () {
assert.equal(
testdata.TEST_DATA[0].asciified,
asciifier.process(testdata.TEST_DATA[0].deasciified, null).text);
});
it('should asciify range', function () {
// Null text.
let result = asciifier.processRange(null, <TextRange>{ start: 0, end: 0 }, null);
expect(result).to.eql(null);
// Empty string.
result = asciifier.processRange("", <TextRange>{ start: 0, end: 10 }, null);
expect(result.changedPositions).to.eql([]);
assert.equal("", result.text);
// Empty range.
result = asciifier.processRange("Tรผrkรงe", <TextRange>{ start: 0, end: 0 }, null);
expect(result.changedPositions).to.eql([]);
assert.equal("Tรผrkรงe", result.text);
// First character.
result = asciifier.processRange("Tรผrkรงe", <TextRange>{ start: 0, end: 1 }, null);
expect(result.changedPositions).to.eql([]);
assert.equal("Tรผrkรงe", result.text);
// First two characters.
result = asciifier.processRange("Tรผrkรงe", <TextRange>{ start: 0, end: 2 }, null);
expect(result.changedPositions).to.eql([1]);
assert.equal("Turkรงe", result.text);
// All characters.
result = asciifier.processRange("Tรผrkรงe", <TextRange>{ start: 0, end: 6 }, null);
expect(result.changedPositions).to.eql([1, 4]);
assert.equal("Turkce", result.text);
// All characters, beyond text length.
result = asciifier.processRange("Tรผrkรงe", <TextRange>{ start: 0, end: 100 }, null);
expect(result.changedPositions).to.eql([1, 4]);
assert.equal("Turkce", result.text);
});
});
function keysOf(dict: { [key: string]: any }): Array<string> {
let keys: Array<string> = [];
for (let key in dict) {
keys.push(key);
}
return keys;
}
describe('Deasciifier', function () {
it('should detect URLs and hostnames', function () {
function match(input: string) : RegExpMatchArray {
let m = input.match(deasciifier.URL_REGEX);
if (m) {
return m;
}
return input.match(deasciifier.HOSTNAME_REGEX);
}
class TestCase {
public constructor(
public readonly text: string,
public readonly matched: string) {
if (this.matched == "<self>") {
this.matched = text;
}
}
}
const URLS: Array<TestCase> = [
// URLs:
new TestCase("http://www.google.com", "<self>"),
new TestCase(" http://www.google.com ", "http://www.google.com"),
new TestCase("http://google.com", "<self>"),
new TestCase("https://www.google.com", "<self>"),
new TestCase("ftp://www.google.com", "<self>"),
new TestCase("http:// google.com", "google.com"),
// TODO: These should match http://www.google.com instead:
new TestCase(" http://www.google.com'a", "http://www.google.com'a"),
new TestCase(" http://www.google.com.", "http://www.google.com."),
// TODO: Should ignore if the hostname doesn't have a dot:
new TestCase("http://www", "<self>"),
// TODO: Should ignore if the hostname doesn't have letters:
new TestCase("http:///", "<self>"),
// Hostnames:
new TestCase("www.google.com", "<self>"),
new TestCase("www.google.net", "<self>"),
new TestCase("www.google", "<self>"),
new TestCase("google.com", "google.com"),
new TestCase("google.com.", "google.com"),
new TestCase("google.com ", "google.com"),
new TestCase("google.com\n", "google.com"),
new TestCase("google.com'a", "google.com"),
new TestCase("google.com-a", "google.com"),
new TestCase("google.com test", "google.com"),
new TestCase("google.co.uk test", "google.co.uk"),
new TestCase("google.com.tr", "google.com.tr"),
new TestCase("google.tr", "google.tr"),
new TestCase("openoffice.org", "openoffice.org"),
];
const NON_URLS: Array<string> = [
"Test",
"Test.string",
"www",
"www. Test",
"http://",
"google.co",
"google.co.",
"google.come",
"google.com1",
"google.comรผ",
"google-com",
"google.test",
];
// Matches:
for (let i = 0; i < URLS.length; i++) {
let m = match(URLS[i].text);
let t = URLS[i];
assert.isNotNull(m, "Case " + i + ": " + URLS[i]);
assert.equal(t.matched, m[0], "Case " + i + ": " + URLS[i]);
}
// Non-matches:
for (let i = 0; i < NON_URLS.length; i++) {
assert.isNull(match(NON_URLS[i]), "Case " + i + ": " + URLS[i]);
}
});
it('should detect Email Like Words', function () {
const MATCHES: Array<string> = [
"test@test.com",
"@test.com",
"test@",
"test@ ",
" test@ string"
];
const NON_MATCHES: Array<string> = [
"http://www.google.com",
"http://google.com",
"https://www.google.com",
"ftp://www.google.com",
"www.google.com",
"www.google.net",
"www.google",
"Test",
"Test.string",
"www",
"www. Test",
"http:// google.com",
"google.com"
];
// Matches
for (let i = 0; i < MATCHES.length; i++) {
assert.isNotNull(MATCHES[i].match(deasciifier.EMAIL_REGEX), "Case " + i);
}
// Non-matches
for (let i = 0; i < NON_MATCHES.length; i++) {
assert.isNull(NON_MATCHES[i].match(deasciifier.EMAIL_REGEX), "Case " + i);
}
});
const PATTERNS = {
'c': 'aXa|-bXb|-aX|-Xa',
'g': 'aXa|-bX|-Xb'
};
it('should load patterns', function () {
let deasc = new deasciifier.Deasciifier();
deasc.init(PATTERNS);
expect(keysOf(deasc.turkish_pattern_table)).to.eql(['c', 'g']);
expect(deasc.turkish_pattern_table['c']).to.eql({ 'aXa': 1, 'bXb': -2, 'aX': -3, 'Xa': -4 });
expect(deasc.turkish_pattern_table['g']).to.eql({ 'aXa': 1, 'bX': -2, 'Xb': -3 });
});
it('should deasciify', function () {
let deasc = new deasciifier.Deasciifier();
deasc.init(PATTERNS);
let result = deasc.process(null, null);
assert.equal(null, result);
result = deasc.process("", null);
assert.equal("", result.text);
expect(result.changedPositions).to.eql([]);
result = deasc.process("agaca", null);
assert.equal("aฤaรงa", result.text);
expect(result.changedPositions).to.eql([1, 3]);
result = deasc.process("aGaCa", null);
assert.equal("aฤaรa", result.text);
expect(result.changedPositions).to.eql([1, 3]);
result = deasc.process("AgAcA", null);
assert.equal("AฤAรงA", result.text);
expect(result.changedPositions).to.eql([1, 3]);
result = deasc.process("bgbcb", null);
assert.equal("bgbcb", result.text);
expect(result.changedPositions).to.eql([]);
// See the TODO in turkish_match_pattern for this. Default behavior is to
// deasciify if no pattern matches.
result = deasc.process("c", null);
assert.equal("รง", result.text);
expect(result.changedPositions).to.eql([0]);
result = deasc.process("caacaac", null);
assert.equal("caaรงaac", result.text);
expect(result.changedPositions).to.eql([3]);
});
it('should deasciify range', function () {
let deasc = new deasciifier.Deasciifier();
deasc.init(PATTERNS);
let result = deasc.processRange("agaca", <TextRange>{ start: 0, end: 0 }, null);
assert.equal("agaca", result.text);
expect(result.changedPositions).to.eql([]);
result = deasc.processRange("agaca", <TextRange>{ start: 0, end: 100 }, null);
assert.equal("aฤaรงa", result.text);
expect(result.changedPositions).to.eql([1, 3]);
result = deasc.processRange("agaca", <TextRange>{ start: 100, end: 0 }, null);
assert.equal("agaca", result.text);
expect(result.changedPositions).to.eql([]);
result = deasc.processRange("agaca", <TextRange>{ start: 0, end: 1 }, null);
assert.equal("agaca", result.text);
expect(result.changedPositions).to.eql([]);
result = deasc.processRange("agaca", <TextRange>{ start: 0, end: 2 }, null);
assert.equal("aฤaca", result.text);
expect(result.changedPositions).to.eql([1]);
result = deasc.processRange("agaca", <TextRange>{ start: 0, end: 4 }, null);
assert.equal("aฤaรงa", result.text);
expect(result.changedPositions).to.eql([1, 3]);
result = deasc.processRange("agaca", <TextRange>{ start: 1, end: 2 }, null);
assert.equal("aฤaca", result.text);
expect(result.changedPositions).to.eql([1]);
result = deasc.processRange("agaca", <TextRange>{ start: 2, end: 2 }, null);
assert.equal("agaca", result.text);
expect(result.changedPositions).to.eql([]);
result = deasc.processRange("agaca", <TextRange>{ start: 1, end: 4 }, null);
assert.equal("aฤaรงa", result.text);
expect(result.changedPositions).to.eql([1, 3]);
});
it('should skip URLs', function () {
let deasc = new deasciifier.Deasciifier();
deasc.init(PATTERNS);
let options = <TextProcessingOptions>{ skipURLs: true };
let result = deasc.process("http://agaca.com agaca", options);
assert.equal("http://agaca.com aฤaรงa", result.text);
expect(result.changedPositions).to.eql([18, 20]);
});
});
describe('TextHelper', function () {
it('isCursorInsideWord', function () {
class TestCase {
constructor(
public readonly index: number, public readonly expected: boolean) { }
}
const TEST_STRING = "abc de f g";
const test_cases: Array<TestCase> = [
new TestCase(0, false), // *abc de f g
new TestCase(1, true), // a*bc de f g
new TestCase(2, true), // ab*c de f g
new TestCase(3, false), // abc* de f g
new TestCase(4, false), // abc *de f g
new TestCase(5, true), // abc d*e f g
new TestCase(6, false), // abc de* f g
new TestCase(7, false), // abc de * f g
new TestCase(8, false), // abc de *f g
new TestCase(9, false), // abc de f* g
new TestCase(10, false), // abc de f * g
new TestCase(11, false), // abc de f *g
new TestCase(12, false), // abc de f g*
// Before the string:
new TestCase(-1, false), // *|abc de f g
// Past the end of the string:
new TestCase(13, false), // abc de f g|*
];
for (let test_case of test_cases) {
assert.equal(
test_case.expected,
TextHelper.isCursorInsideWord(TEST_STRING, test_case.index),
"Wrong result for index " + test_case.index);
}
});
it('getWordAtCursor', function () {
class TestCase {
constructor(
public readonly index: number,
public readonly expected_start: number,
public readonly expected_end: number) { }
}
const TEST_STRING = "abc de f g";
const test_cases: Array<TestCase> = [
new TestCase(0, 0, 3), // *abc de f g
new TestCase(1, 0, 3), // a*bc de f g
new TestCase(2, 0, 3), // ab*c de f g
new TestCase(3, 0, 3), // abc* de f g
new TestCase(4, 4, 6), // abc *de f g
new TestCase(5, 4, 6), // abc d*e f g
new TestCase(6, 4, 6), // abc de* f g
new TestCase(7, 7, 7), // abc de * f g
new TestCase(8, 8, 9), // abc de *f g
new TestCase(9, 8, 9), // abc de f* g
new TestCase(10, 10, 10), // abc de f * g
new TestCase(11, 11, 11), // abc de f * g
new TestCase(12, 12, 13), // abc de f *g
new TestCase(13, 12, 13), // abc de f g*
// Before the string.
// TODO: Fix, should return empty range.
new TestCase(-1, 0, 3), // *|abc de f g
// Past the end of string.
// TODO: Fix, should return empty range.
new TestCase(14, 12, 13), // abc de f g|*
];
for (let test_case of test_cases) {
expect(
TextHelper.getWordAtCursor(TEST_STRING, test_case.index)).to.eql(
new TextRange(test_case.expected_start, test_case.expected_end),
"Wrong result for index " + test_case.index);
}
});
it('getWordBeforeCursor', function () {
class TestCase {
constructor(
public readonly index: number,
public readonly expected_start: number,
public readonly expected_end: number) { }
}
const TEST_STRING = "abc de f g";
const test_cases: Array<TestCase> = [
new TestCase(0, 0, 3), // *bc de f g
new TestCase(1, 0, 3), // a*c de f g
new TestCase(2, 0, 3), // ab* de f g
new TestCase(3, 0, 3), // abc*de f g
new TestCase(4, 0, 3), // abc *e f g
new TestCase(5, 4, 6), // abc d* f g
new TestCase(6, 4, 6), // abc de* f g
new TestCase(7, 4, 6), // abc de *f g
new TestCase(8, 4, 6), // abc de * g
new TestCase(9, 8, 9), // abc de f* g
new TestCase(10, 8, 9), // abc de f * g
new TestCase(11, 8, 9), // abc de f *g
new TestCase(12, 8, 9), // abc de f *
new TestCase(13, 12, 13), // abc de f g*
// Before the string.
// TODO: Fix, should return empty range.
new TestCase(-1, 0, 3), // *|abc de f g
// Past the end of string.
// TODO: Fix, should return empty range.
new TestCase(14, 12, 13), // abc de f g|*
];
for (let test_case of test_cases) {
expect(
TextHelper.getWordBeforeCursor(TEST_STRING, test_case.index)).to.eql(
new TextRange(test_case.expected_start, test_case.expected_end),
"Wrong result for index " + test_case.index);
}
});
}); | the_stack |
import type { IncomingMessage, ServerResponse } from 'http';
import {
ExecutionArgs,
getOperationAST,
GraphQLSchema,
OperationTypeNode,
parse,
validate as graphqlValidate,
execute as graphqlExecute,
subscribe as graphqlSubscribe,
} from 'graphql';
import { isObject } from './utils';
import {
RequestParams,
StreamEvent,
StreamData,
StreamDataForID,
ExecutionResult,
ExecutionPatchResult,
TOKEN_HEADER_KEY,
TOKEN_QUERY_KEY,
} from './common';
/**
* A concrete GraphQL execution context value type.
*
* Mainly used because TypeScript collapes unions
* with `any` or `unknown` to `any` or `unknown`. So,
* we use a custom type to allow definitions such as
* the `context` server option.
*
* @category Server
*/
export type ExecutionContext =
// eslint-disable-next-line @typescript-eslint/ban-types
| object // you can literally pass "any" JS object as the context value
| symbol
| number
| string
| boolean
| undefined
| null;
/** @category Server */
export type OperationResult =
| Promise<
| AsyncGenerator<ExecutionResult | ExecutionPatchResult>
| AsyncIterable<ExecutionResult | ExecutionPatchResult>
| ExecutionResult
>
| AsyncGenerator<ExecutionResult | ExecutionPatchResult>
| AsyncIterable<ExecutionResult | ExecutionPatchResult>
| ExecutionResult;
/** @category Server */
export interface HandlerOptions<
Request extends IncomingMessage = IncomingMessage,
Response extends ServerResponse = ServerResponse,
> {
/**
* The GraphQL schema on which the operations will
* be executed and validated against.
*
* If a function is provided, it will be called on every
* subscription request allowing you to manipulate schema
* dynamically.
*
* If the schema is left undefined, you're trusted to
* provide one in the returned `ExecutionArgs` from the
* `onSubscribe` callback.
*/
schema?:
| GraphQLSchema
| ((
req: Request,
args: Omit<ExecutionArgs, 'schema'>,
) => Promise<GraphQLSchema> | GraphQLSchema);
/**
* A value which is provided to every resolver and holds
* important contextual information like the currently
* logged in user, or access to a database.
*
* Note that the context function is invoked on each operation only once.
* Meaning, for subscriptions, only at the point of initialising the subscription;
* not on every subscription event emission. Read more about the context lifecycle
* in subscriptions here: https://github.com/graphql/graphql-js/issues/894.
*/
context?:
| ExecutionContext
| ((
req: Request,
args: ExecutionArgs,
) => Promise<ExecutionContext> | ExecutionContext);
/**
* A custom GraphQL validate function allowing you to apply your
* own validation rules.
*/
validate?: typeof graphqlValidate;
/**
* Is the `execute` function from GraphQL which is
* used to execute the query and mutation operations.
*/
execute?: (args: ExecutionArgs) => OperationResult;
/**
* Is the `subscribe` function from GraphQL which is
* used to execute the subscription operation.
*/
subscribe?: (args: ExecutionArgs) => OperationResult;
/**
* Authenticate the client. Returning a string indicates that the client
* is authenticated and the request is ready to be processed.
*
* A token of type string MUST be supplied; if there is no token, you may
* return an empty string (`''`);
*
* If you want to respond to the client with a custom status or body,
* you should do so using the provided `res` argument which will stop
* further execution.
*
* @default 'req.headers["x-graphql-event-stream-token"] || req.url.searchParams["token"] || generateRandomUUID()' // https://gist.github.com/jed/982883
*/
authenticate?: (
req: Request,
res: Response,
) => Promise<string | undefined | void> | string | undefined | void;
/**
* Called when a new event stream is connecting BEFORE it is accepted.
* By accepted, its meant the server responded with a 200 (OK), alongside
* flushing the necessary event stream headers.
*
* If you want to respond to the client with a custom status or body,
* you should do so using the provided `res` argument which will stop
* further execution.
*/
onConnecting?: (req: Request, res: Response) => Promise<void> | void;
/**
* Called when a new event stream has been succesfully connected and
* accepted, and after all pending messages have been flushed.
*/
onConnected?: (req: Request) => Promise<void> | void;
/**
* The subscribe callback executed right after processing the request
* before proceeding with the GraphQL operation execution.
*
* If you return `ExecutionArgs` from the callback, it will be used instead of
* trying to build one internally. In this case, you are responsible for providing
* a ready set of arguments which will be directly plugged in the operation execution.
*
* Omitting the fields `contextValue` from the returned `ExecutionArgs` will use the
* provided `context` option, if available.
*
* If you want to respond to the client with a custom status or body,
* you should do so using the provided `res` argument which will stop
* further execution.
*
* Useful for preparing the execution arguments following a custom logic. A typical
* use-case is persisted queries. You can identify the query from the request parameters
* and supply the appropriate GraphQL operation execution arguments.
*/
onSubscribe?: (
req: Request,
res: Response,
params: RequestParams,
) => Promise<ExecutionArgs | void> | ExecutionArgs | void;
/**
* Executed after the operation call resolves. For streaming
* operations, triggering this callback does not necessarely
* mean that there is already a result available - it means
* that the subscription process for the stream has resolved
* and that the client is now subscribed.
*
* The `OperationResult` argument is the result of operation
* execution. It can be an iterator or already a value.
*
* Use this callback to listen for GraphQL operations and
* execution result manipulation.
*
* If you want to respond to the client with a custom status or body,
* you should do so using the provided `res` argument which will stop
* further execution.
*
* First argument, the request, is always the GraphQL operation
* request.
*/
onOperation?: (
req: Request,
res: Response,
args: ExecutionArgs,
result: OperationResult,
) => Promise<OperationResult | void> | OperationResult | void;
/**
* Executed after an operation has emitted a result right before
* that result has been sent to the client.
*
* Results from both single value and streaming operations will
* invoke this callback.
*
* Use this callback if you want to format the execution result
* before it reaches the client.
*
* First argument, the request, is always the GraphQL operation
* request.
*/
onNext?: (
req: Request,
args: ExecutionArgs,
result: ExecutionResult | ExecutionPatchResult,
) =>
| Promise<ExecutionResult | ExecutionPatchResult | void>
| ExecutionResult
| ExecutionPatchResult
| void;
/**
* The complete callback is executed after the operation
* has completed and the client has been notified.
*
* Since the library makes sure to complete streaming
* operations even after an abrupt closure, this callback
* will always be called.
*
* First argument, the request, is always the GraphQL operation
* request.
*/
onComplete?: (req: Request, args: ExecutionArgs) => Promise<void> | void;
/**
* Called when an event stream has disconnected right before the
* accepting the stream.
*/
onDisconnect?: (req: Request) => Promise<void> | void;
}
/**
* The ready-to-use handler. Simply plug it in your favourite HTTP framework
* and enjoy.
*
* Beware that the handler resolves only after the whole operation completes.
* - If query/mutation, waits for result
* - If subscription, waits for complete
*
* Errors thrown from **any** of the provided options or callbacks (or even due to
* library misuse or potential bugs) will reject the handler's promise. They are
* considered internal errors and you should take care of them accordingly.
*
* For production environments, its recommended not to transmit the exact internal
* error details to the client, but instead report to an error logging tool or simply
* the console. Roughly:
*
* ```ts
* import http from 'http';
* import { createHandler } from 'graphql-sse';
*
* const handler = createHandler({ ... });
*
* http.createServer(async (req, res) => {
* try {
* await handler(req, res);
* } catch (err) {
* console.error(err);
* // or
* Sentry.captureException(err);
*
* if (!res.headersSent) {
* res.writeHead(500, 'Internal Server Error').end();
* }
* }
* });
* ```
*
* Note that some libraries, like fastify, parse the body before reaching the handler.
* In such cases all request 'data' events are already consumed. Use this `body` argument
* too pass in the read body and avoid listening for the 'data' events internally. Do
* beware that the `body` argument will be consumed **only** if it's an object.
*
* @category Server
*/
export type Handler<
Request extends IncomingMessage = IncomingMessage,
Response extends ServerResponse = ServerResponse,
> = (req: Request, res: Response, body?: unknown) => Promise<void>;
interface Stream<
Request extends IncomingMessage = IncomingMessage,
Response extends ServerResponse = ServerResponse,
> {
/**
* Does the stream have an open connection to some client.
*/
readonly open: boolean;
/**
* If the operation behind an ID is an `AsyncIterator` - the operation
* is streaming; on the contrary, if the operation is `null` - it is simply
* a reservation, meaning - the operation resolves to a single result or is still
* pending/being prepared.
*/
ops: Record<string, AsyncGenerator<unknown> | AsyncIterable<unknown> | null>;
/**
* Use this connection for streaming.
*/
use(req: Request, res: Response): Promise<void>;
/**
* Stream from provided execution result to used connection.
*/
from(
operationReq: Request, // holding the operation request (not necessarily the event stream)
args: ExecutionArgs,
result:
| AsyncGenerator<ExecutionResult | ExecutionPatchResult>
| AsyncIterable<ExecutionResult | ExecutionPatchResult>
| ExecutionResult
| ExecutionPatchResult,
opId?: string,
): Promise<void>;
}
/**
* Makes a Protocol complient HTTP GraphQL server handler. The handler can
* be used with your favourite server library.
*
* Read more about the Protocol in the PROTOCOL.md documentation file.
*
* @category Server
*/
export function createHandler<
Request extends IncomingMessage = IncomingMessage,
Response extends ServerResponse = ServerResponse,
>(options: HandlerOptions<Request, Response>): Handler<Request, Response> {
const {
schema,
context,
validate = graphqlValidate,
execute = graphqlExecute,
subscribe = graphqlSubscribe,
authenticate = function extractOrCreateStreamToken(req) {
const headerToken =
req.headers[TOKEN_HEADER_KEY] || req.headers['x-graphql-stream-token']; // @deprecated >v1.0.0
if (headerToken)
return Array.isArray(headerToken) ? headerToken.join('') : headerToken;
const urlToken = new URL(
req.url ?? '',
'http://localhost/',
).searchParams.get(TOKEN_QUERY_KEY);
if (urlToken) return urlToken;
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0,
v = c == 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
},
onConnecting,
onConnected,
onSubscribe,
onOperation,
onNext,
onComplete,
onDisconnect,
} = options;
const streams: Record<string, Stream> = {};
function createStream(token: string | null): Stream<Request, Response> {
let request: Request | null = null,
response: Response | null = null,
pinger: ReturnType<typeof setInterval>,
disposed = false;
const pendingMsgs: string[] = [];
const ops: Record<
string,
AsyncGenerator<unknown> | AsyncIterable<unknown> | null
> = {};
function write(msg: unknown) {
return new Promise<boolean>((resolve, reject) => {
if (disposed || !response || !response.writable) return resolve(false);
response.write(msg, (err) => {
if (err) return reject(err);
resolve(true);
});
});
}
async function emit<E extends StreamEvent>(
event: E,
data: StreamData<E> | StreamDataForID<E>,
): Promise<void> {
let msg = `event: ${event}`;
if (data) msg += `\ndata: ${JSON.stringify(data)}`;
msg += '\n\n';
const wrote = await write(msg);
if (!wrote) pendingMsgs.push(msg);
}
async function dispose() {
if (disposed) return;
disposed = true;
// make room for another potential stream while this one is being disposed
if (typeof token === 'string') delete streams[token];
// complete all operations and flush messages queue before ending the stream
for (const op of Object.values(ops)) {
if (isAsyncGenerator(op)) await op.return(undefined);
}
while (pendingMsgs.length) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const msg = pendingMsgs.shift()!;
await write(msg);
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
response!.end(); // response must exist at this point
response = null;
clearInterval(pinger);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
onDisconnect?.(request!); // request must exist at this point
request = null;
}
return {
get open() {
return disposed || Boolean(response);
},
ops,
async use(req, res) {
request = req;
response = res;
req.socket.setTimeout(0);
req.socket.setNoDelay(true);
req.socket.setKeepAlive(true);
res.once('close', dispose);
res.statusCode = 200;
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('X-Accel-Buffering', 'no');
if (req.httpVersionMajor < 2) res.setHeader('Connection', 'keep-alive');
res.flushHeaders();
// write an empty message because some browsers (like Firefox and Safari)
// dont accept the header flush
await write(':\n\n');
// ping client every 12 seconds to keep the connection alive
pinger = setInterval(() => write(':\n\n'), 12_000);
while (pendingMsgs.length) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const msg = pendingMsgs.shift()!;
const wrote = await write(msg);
if (!wrote) throw new Error('Unable to flush messages');
}
await onConnected?.(req);
},
async from(operationReq, args, result, opId) {
if (isAsyncIterable(result)) {
/** multiple emitted results */
for await (let part of result) {
const maybeResult = await onNext?.(operationReq, args, part);
if (maybeResult) part = maybeResult;
await emit(
'next',
opId
? {
id: opId,
payload: part,
}
: part,
);
}
} else {
/** single emitted result */
const maybeResult = await onNext?.(operationReq, args, result);
if (maybeResult) result = maybeResult;
await emit(
'next',
opId
? {
id: opId,
payload: result,
}
: result,
);
}
await emit('complete', opId ? { id: opId } : null);
// end on complete when no operation id is present
// because distinct event streams are used for each operation
if (!opId) await dispose();
else delete ops[opId];
await onComplete?.(operationReq, args);
},
};
}
async function prepare(
req: Request,
res: Response,
params: RequestParams,
): Promise<[args: ExecutionArgs, perform: () => OperationResult] | void> {
let args: ExecutionArgs, operation: OperationTypeNode;
const maybeExecArgs = await onSubscribe?.(req, res, params);
if (maybeExecArgs) args = maybeExecArgs;
else {
// you either provide a schema dynamically through
// `onSubscribe` or you set one up during the server setup
if (!schema) throw new Error('The GraphQL schema is not provided');
const { operationName, variables } = params;
let { query } = params;
if (typeof query === 'string') {
try {
query = parse(query);
} catch {
return res.writeHead(400, 'GraphQL query syntax error').end();
}
}
const argsWithoutSchema = {
operationName,
document: query,
variableValues: variables,
};
args = {
...argsWithoutSchema,
schema:
typeof schema === 'function'
? await schema(req, argsWithoutSchema)
: schema,
};
}
try {
const ast = getOperationAST(args.document, args.operationName);
if (!ast) throw null;
operation = ast.operation;
} catch {
return res.writeHead(400, 'Unable to detect operation AST').end();
}
// mutations cannot happen over GETs as per the spec
// Read more: https://github.com/graphql/graphql-over-http/blob/main/spec/GraphQLOverHTTP.md#get
if (operation === 'mutation' && req.method === 'GET')
return res
.writeHead(405, 'Cannot perform mutations over GET', {
Allow: 'POST',
})
.end();
if (!('contextValue' in args))
args.contextValue =
typeof context === 'function' ? await context(req, args) : context;
// we validate after injecting the context because the process of
// reporting the validation errors might need the supplied context value
const validationErrs = validate(args.schema, args.document);
if (validationErrs.length) {
if (req.headers.accept === 'text/event-stream') {
// accept the request and emit the validation error in event streams,
// promoting graceful GraphQL error reporting
// Read more: https://www.w3.org/TR/eventsource/#processing-model
// Read more: https://github.com/graphql/graphql-over-http/blob/main/spec/GraphQLOverHTTP.md#document-validation
return [
args,
function perform() {
return { errors: validationErrs };
},
];
}
res
.writeHead(400, {
'Content-Type':
req.headers.accept === 'application/json'
? 'application/json; charset=utf-8'
: 'application/graphql+json; charset=utf-8',
})
.write(JSON.stringify({ errors: validationErrs }));
return res.end();
}
return [
args,
async function perform() {
let result =
operation === 'subscription' ? subscribe(args) : execute(args);
const maybeResult = await onOperation?.(req, res, args, result);
if (maybeResult) result = maybeResult;
return result;
},
];
}
return async function handler(req: Request, res: Response, body: unknown) {
// authenticate first and acquire unique identification token
const token = await authenticate(req, res);
if (res.writableEnded) return;
if (typeof token !== 'string') throw new Error('Token was not supplied');
const accept = req.headers.accept ?? '*/*';
const stream = streams[token];
if (accept === 'text/event-stream') {
// if event stream is not registered, process it directly.
// this means that distinct connections are used for graphql operations
if (!stream) {
let params;
try {
params = await parseReq(req, body);
} catch (err) {
return res.writeHead(400, err.message).end();
}
const distinctStream = createStream(null);
// reserve space for the operation
distinctStream.ops[''] = null;
const prepared = await prepare(req, res, params);
if (res.writableEnded) return;
if (!prepared)
throw new Error(
"Operation preparation didn't respond, yet it was not prepared",
);
const [args, perform] = prepared;
const result = await perform();
if (res.writableEnded) {
if (isAsyncGenerator(result)) result.return(undefined);
return; // `onOperation` responded
}
if (isAsyncIterable(result)) distinctStream.ops[''] = result;
await onConnecting?.(req, res);
if (res.writableEnded) return;
await distinctStream.use(req, res);
await distinctStream.from(req, args, result);
return;
}
// open stream cant exist, only one per token is allowed
if (stream.open) return res.writeHead(409, 'Stream already open').end();
await onConnecting?.(req, res);
if (res.writableEnded) return;
await stream.use(req, res);
return;
}
if (req.method === 'PUT') {
// method PUT prepares a stream for future incoming connections.
if (!['*/*', 'text/plain'].includes(accept))
return res.writeHead(406).end();
// streams mustnt exist if putting new one
if (stream) return res.writeHead(409, 'Stream already registered').end();
streams[token] = createStream(token);
res
.writeHead(201, { 'Content-Type': 'text/plain; charset=utf-8' })
.write(token);
return res.end();
} else if (req.method === 'DELETE') {
// method DELETE completes an existing operation streaming in streams
// streams must exist when completing operations
if (!stream) return res.writeHead(404, 'Stream not found').end();
const opId = new URL(req.url ?? '', 'http://localhost/').searchParams.get(
'operationId',
);
if (!opId) return res.writeHead(400, 'Operation ID is missing').end();
const op = stream.ops[opId];
if (isAsyncGenerator(op)) op.return(undefined);
delete stream.ops[opId]; // deleting the operation means no further activity should take place
return res.writeHead(200).end();
} else if (req.method !== 'GET' && req.method !== 'POST')
// only POSTs and GETs are accepted at this point
return res
.writeHead(405, undefined, { Allow: 'GET, POST, PUT, DELETE' })
.end();
else if (!stream)
// for all other requests, streams must exist to attach the result onto
return res.writeHead(404, 'Stream not found').end();
if (
!['*/*', 'application/graphql+json', 'application/json'].includes(accept)
)
return res.writeHead(406).end();
let params;
try {
params = await parseReq(req, body);
} catch (err) {
return res.writeHead(400, err.message).end();
}
const opId = String(params.extensions?.operationId ?? '');
if (!opId) return res.writeHead(400, 'Operation ID is missing').end();
if (opId in stream.ops)
return res.writeHead(409, 'Operation with ID already exists').end();
// reserve space for the operation through ID
stream.ops[opId] = null;
const prepared = await prepare(req, res, params);
if (res.writableEnded) return;
if (!prepared)
throw new Error(
"Operation preparation didn't respond, yet it was not prepared",
);
const [args, perform] = prepared;
// operation might have completed before prepared
if (!(opId in stream.ops)) return res.writeHead(204).end();
const result = await perform();
if (res.writableEnded) {
if (isAsyncGenerator(result)) result.return(undefined);
delete stream.ops[opId];
return; // `onOperation` responded
}
// operation might have completed before performed
if (!(opId in stream.ops)) {
if (isAsyncGenerator(result)) result.return(undefined);
return res.writeHead(204).end();
}
if (isAsyncIterable(result)) stream.ops[opId] = result;
res.writeHead(202).end();
// streaming to an empty reservation is ok (will be flushed on connect)
await stream.from(req, args, result, opId);
};
}
async function parseReq<Request extends IncomingMessage = IncomingMessage>(
req: Request,
body: unknown,
): Promise<RequestParams> {
const params: Partial<RequestParams> = {};
if (req.method === 'GET') {
await new Promise<void>((resolve, reject) => {
try {
const url = new URL(req.url ?? '', 'http://localhost/');
params.operationName =
url.searchParams.get('operationName') ?? undefined;
params.query = url.searchParams.get('query') ?? undefined;
const variables = url.searchParams.get('variables');
if (variables) params.variables = JSON.parse(variables);
const extensions = url.searchParams.get('extensions');
if (extensions) params.extensions = JSON.parse(extensions);
resolve();
} catch {
reject(new Error('Unparsable URL'));
}
});
} else if (req.method === 'POST') {
await new Promise<void>((resolve, reject) => {
const end = (body: Record<string, unknown> | string) => {
try {
const data = typeof body === 'string' ? JSON.parse(body) : body;
params.operationName = data.operationName;
params.query = data.query;
params.variables = data.variables;
params.extensions = data.extensions;
resolve();
} catch {
reject(new Error('Unparsable body'));
}
};
if (typeof body === 'string' || isObject(body)) end(body);
else {
let body = '';
req.on('data', (chunk) => (body += chunk));
req.on('end', () => end(body));
}
});
} else throw new Error(`Unsupported method ${req.method}`); // should never happen
if (!params.query) throw new Error('Missing query');
if (params.variables && typeof params.variables !== 'object')
throw new Error('Invalid variables');
if (params.extensions && typeof params.extensions !== 'object')
throw new Error('Invalid extensions');
return params as RequestParams;
}
function isAsyncIterable<T = unknown>(val: unknown): val is AsyncIterable<T> {
return typeof Object(val)[Symbol.asyncIterator] === 'function';
}
export function isAsyncGenerator<T = unknown>(
val: unknown,
): val is AsyncGenerator<T> {
return (
isObject(val) &&
typeof Object(val)[Symbol.asyncIterator] === 'function' &&
typeof val.return === 'function'
// for lazy ones, we only need the return anyway
// typeof val.throw === 'function' &&
// typeof val.next === 'function'
);
} | the_stack |
import { types } from "@algo-builder/web";
import { getApplicationAddress } from "algosdk";
import { assert } from "chai";
import { AccountStore, Runtime } from "../../../src/index";
import { ALGORAND_ACCOUNT_MIN_BALANCE, ASSET_CREATION_FEE } from "../../../src/lib/constants";
import { AccountStoreI, AppDeploymentFlags } from "../../../src/types";
import { useFixture } from "../../helpers/integration";
describe("Algorand Smart Contracts(TEALv5) - Inner Transactions[Asset Transfer, Asset Freeze..]", function () {
useFixture("inner-transaction");
const fee = 1000;
const minBalance = ALGORAND_ACCOUNT_MIN_BALANCE * 50 + fee;
const master = new AccountStore(300e6);
let john = new AccountStore(minBalance + fee);
let elon = new AccountStore(minBalance + fee);
let bob = new AccountStore(minBalance + fee);
let appAccount: AccountStoreI; // initialized later
let runtime: Runtime;
let approvalProgramFileName: string;
let clearProgramFileName: string;
let appCreationFlags: AppDeploymentFlags;
let appID: number;
let assetID: number;
let appCallParams: types.ExecParams;
this.beforeAll(function () {
runtime = new Runtime([master, john, elon, bob]); // setup test
approvalProgramFileName = 'approval-asset-tx.py';
clearProgramFileName = 'clear.teal';
appCreationFlags = {
sender: john.account,
globalBytes: 1,
globalInts: 1,
localBytes: 1,
localInts: 1
};
});
this.beforeEach(() => {
// reset app (delete + create)
john.createdApps.delete(appID);
appID = runtime.deployApp(approvalProgramFileName, clearProgramFileName, appCreationFlags, {}).appID;
appAccount = runtime.getAccount(getApplicationAddress(appID)); // update app account
// create asset
assetID = runtime.deployASA('gold',
{ creator: { ...john.account, name: "john" } }).assetID;
// fund app (escrow belonging to app) with 10 ALGO
const fundAppParams: types.AlgoTransferParam = {
type: types.TransactionType.TransferAlgo,
sign: types.SignType.SecretKey,
fromAccount: master.account,
toAccountAddr: getApplicationAddress(appID),
amountMicroAlgos: 10e6,
payFlags: { totalFee: 1000 }
};
runtime.executeTx(fundAppParams);
syncAccounts();
appCallParams = {
type: types.TransactionType.CallApp,
sign: types.SignType.SecretKey,
fromAccount: john.account,
appID: appID,
payFlags: { totalFee: 1000 }
};
});
function syncAccounts (): void {
appAccount = runtime.getAccount(getApplicationAddress(appID));
john = runtime.getAccount(john.address);
elon = runtime.getAccount(elon.address);
bob = runtime.getAccount(bob.address);
};
function optInToASAbyApp (): void {
const optInParams = {
...appCallParams,
appArgs: ['str:opt_in_to_asa'],
foreignAssets: [assetID]
};
runtime.executeTx(optInParams);
syncAccounts();
// transfer some ASA to app
const asaTransferParam: types.ExecParams = {
type: types.TransactionType.TransferAsset,
sign: types.SignType.SecretKey,
fromAccount: john.account,
toAccountAddr: appAccount.address,
amount: 10,
assetID: assetID,
payFlags: { totalFee: 1000 }
};
runtime.executeTx(asaTransferParam);
syncAccounts();
runtime.optIntoASA(assetID, elon.address, {});
syncAccounts();
}
it("should optin to ASA (by app account)", function () {
const appHoldingBefore = appAccount.getAssetHolding(assetID);
assert.isUndefined(appHoldingBefore);
// optin by app to assetID
optInToASAbyApp();
// verify optin
assert.isDefined(appAccount.getAssetHolding(assetID));
});
it("fail on ASA transfer by App if app not optedin to ASA", function () {
// contracts sends 1 ASA to sender, and 2 ASA to txn.accounts[1]
const transferASAbyAppParam = {
...appCallParams,
appArgs: ['str:transfer_asa'],
accounts: [elon.address],
foreignAssets: [assetID]
};
assert.throws(
() => runtime.executeTx(transferASAbyAppParam),
`RUNTIME_ERR1404: Account ${appAccount.address} doesn't hold asset index ${assetID}`
);
});
it("initiate ASA transfer from smart contract", function () {
optInToASAbyApp();
const appHoldingBefore = appAccount.getAssetHolding(assetID)?.amount as bigint;
const johnHoldingBefore = john.getAssetHolding(assetID)?.amount as bigint;
const elonHoldingBefore = elon.getAssetHolding(assetID)?.amount as bigint;
// contracts sends 1 ASA to sender, and 2 ASA to txn.accounts[1]
const transferASAbyAppParam = {
...appCallParams,
appArgs: ['str:transfer_asa'],
accounts: [elon.address],
foreignAssets: [assetID]
};
runtime.executeTx(transferASAbyAppParam);
syncAccounts();
// verify ASA transfer
assert.equal(appAccount.getAssetHolding(assetID)?.amount, appHoldingBefore - 3n);
assert.equal(john.getAssetHolding(assetID)?.amount, johnHoldingBefore + 1n);
assert.equal(elon.getAssetHolding(assetID)?.amount, elonHoldingBefore + 2n);
});
it("empty app's account ASA holding to txn.accounts[1] if close remainder to is passed", function () {
optInToASAbyApp();
const appHoldingBefore = appAccount.getAssetHolding(assetID)?.amount as bigint;
const elonHoldingBefore = elon.getAssetHolding(assetID)?.amount as bigint;
assert.isDefined(appHoldingBefore);
// empties contract's ALGO's to elon (after deducting fees)
const txParams = {
...appCallParams,
payFlags: { totalFee: 1000 },
appArgs: ['str:transfer_asa_with_close_rem_to'],
accounts: [elon.address],
foreignAssets: [assetID]
};
runtime.executeTx(txParams);
syncAccounts();
// verify app holding removed and all ASA transferred to elon
assert.isUndefined(appAccount.getAssetHolding(assetID));
assert.equal(elon.getAssetHolding(assetID)?.amount, elonHoldingBefore + appHoldingBefore);
});
it("should fail on asset clawback if clawback !== application account", function () {
optInToASAbyApp();
// empties contract's ALGO's to elon (after deducting fees)
const txParams = {
...appCallParams,
payFlags: { totalFee: 1000 },
appArgs: ['str:asa_clawback_from_txn1_to_txn2'],
accounts: [john.address, elon.address], // clawback 2 ASA from john -> elon by App
foreignAssets: [assetID]
};
assert.throws(
() => runtime.executeTx(txParams),
`RUNTIME_ERR1506: Only Clawback account WHVQXVVCQAD7WX3HHFKNVUL3MOANX3BYXXMEEJEJWOZNRXJNTN7LTNPSTY can revoke asset`
);
});
it("should clawback 2 ASA by application account from Txn.accounts[1] to Txn.accounts[2]", function () {
optInToASAbyApp();
const johnHoldingBefore = john.getAssetHolding(assetID)?.amount as bigint;
const elonHoldingBefore = elon.getAssetHolding(assetID)?.amount as bigint;
// update clawback to app account
const asaDef = john.createdAssets.get(assetID);
if (asaDef) asaDef.clawback = appAccount.address;
// empties contract's ALGO's to elon (after deducting fees)
const txParams = {
...appCallParams,
appArgs: ['str:asa_clawback_from_txn1_to_txn2'],
accounts: [john.address, elon.address], // clawback 2 ASA from john -> elon by App
foreignAssets: [assetID]
};
runtime.executeTx(txParams);
syncAccounts();
// verify 2 ASA are clawbacked from john -> elon
assert.equal(john.getAssetHolding(assetID)?.amount, johnHoldingBefore - 2n);
assert.equal(elon.getAssetHolding(assetID)?.amount, elonHoldingBefore + 2n);
});
it("should fail on asset freeze if asset freeze !== application account", function () {
const txParams = {
...appCallParams,
appArgs: ['str:freeze_asa'],
accounts: [john.address],
foreignAssets: [assetID]
};
assert.throws(
() => runtime.executeTx(txParams),
`RUNTIME_ERR1505: Only Freeze account WHVQXVVCQAD7WX3HHFKNVUL3MOANX3BYXXMEEJEJWOZNRXJNTN7LTNPSTY can freeze asset`
);
});
it("should fail if txn.accounts[1] not optedIn to ASA", function () {
// update freeze to app account
const asaDef = john.createdAssets.get(assetID);
if (asaDef) asaDef.freeze = appAccount.address;
const txParams = {
...appCallParams,
appArgs: ['str:freeze_asa'],
accounts: [elon.address], // elon is not optedin
foreignAssets: [assetID]
};
assert.throws(
() => runtime.executeTx(txParams),
`RUNTIME_ERR1404: Account ${elon.address} doesn't hold asset index ${assetID}`
);
});
it("should freeze asset (by app account)", function () {
// update freeze to app account
const asaDef = john.createdAssets.get(assetID);
if (asaDef) asaDef.freeze = appAccount.address;
// not frozen
assert.equal(john.getAssetHolding(assetID)?.["is-frozen"], false);
const txParams = {
...appCallParams,
appArgs: ['str:freeze_asa'],
accounts: [john.address],
foreignAssets: [assetID]
};
runtime.executeTx(txParams);
syncAccounts();
// frozen
assert.equal(john.getAssetHolding(assetID)?.["is-frozen"], true);
});
it("should unfreeze asset (by app account)", function () {
// update freeze to app account
const asaDef = john.createdAssets.get(assetID);
if (asaDef) asaDef.freeze = appAccount.address;
// set frozen == true
const johnAssetHolding = john.getAssetHolding(assetID);
if (johnAssetHolding) johnAssetHolding["is-frozen"] = true;
const txParams = {
...appCallParams,
appArgs: ['str:unfreeze_asa'],
accounts: [john.address],
foreignAssets: [assetID]
};
runtime.executeTx(txParams);
syncAccounts();
// verify unfrozen
assert.equal(john.getAssetHolding(assetID)?.["is-frozen"], false);
});
it("should fail on asset delete if asset manager !== application account", function () {
const txParams = {
...appCallParams,
appArgs: ['str:delete_asa'],
foreignAssets: [assetID]
};
assert.throws(
() => runtime.executeTx(txParams),
`RUNTIME_ERR1504: Only Manager account WHVQXVVCQAD7WX3HHFKNVUL3MOANX3BYXXMEEJEJWOZNRXJNTN7LTNPSTY can modify or destroy asset`
);
});
it("should delete asset (by app account)", function () {
// update asset manager to app account
const asaDef = john.createdAssets.get(assetID);
if (asaDef) asaDef.manager = appAccount.address;
// assert ASA defined
assert.isDefined(runtime.getAssetDef(assetID));
const txParams = {
...appCallParams,
appArgs: ['str:delete_asa'],
foreignAssets: [assetID]
};
runtime.executeTx(txParams);
syncAccounts();
// assert ASA deleted
assert.throws(
() => runtime.getAssetDef(assetID),
`RUNTIME_ERR1502: Asset with Index ${assetID} not found`
);
});
it("should fail on asset modification if asset manager !== application account", function () {
const txParams = {
...appCallParams,
appArgs: ['str:modify_asa'],
foreignAssets: [assetID],
accounts: [elon.address, bob.address]
};
assert.throws(
() => runtime.executeTx(txParams),
`RUNTIME_ERR1504: Only Manager account WHVQXVVCQAD7WX3HHFKNVUL3MOANX3BYXXMEEJEJWOZNRXJNTN7LTNPSTY can modify or destroy asset`
);
});
it("should modify asset (by app account)", function () {
// update asset manager to app account
let asaDef = john.createdAssets.get(assetID);
if (asaDef) asaDef.manager = appAccount.address;
// assert ASA defined
assert.isDefined(runtime.getAssetDef(assetID));
const txParams = {
...appCallParams,
appArgs: ['str:modify_asa'],
foreignAssets: [assetID],
accounts: [elon.address, bob.address]
};
runtime.executeTx(txParams);
syncAccounts();
// verify fields modified (according to asc logic)
asaDef = runtime.getAssetDef(assetID);
assert.deepEqual(asaDef.manager, txParams.accounts[0]);
assert.deepEqual(asaDef.reserve, txParams.accounts[1]);
assert.deepEqual(asaDef.freeze, txParams.fromAccount?.addr);
assert.deepEqual(asaDef.clawback, appAccount.address);
});
it("should deploy a new ASA (by app account)", function () {
// saved in global state, initially undefined
let createdAsaID = runtime.getGlobalState(appID, "created_asa_key");
assert.isUndefined(createdAsaID);
const initialMinBalance = appAccount.minBalance;
const txParams = {
...appCallParams,
appArgs: ['str:deploy_asa']
};
runtime.executeTx(txParams);
syncAccounts();
// verify asa created by contract
createdAsaID = runtime.getGlobalState(appID, "created_asa_key");
assert.isDefined(createdAsaID);
const asaDef = runtime.getAssetDef(Number(createdAsaID));
assert.isDefined(asaDef);
assert.equal(asaDef.name, 'gold');
assert.equal(asaDef.decimals, 3);
assert.equal(asaDef.defaultFrozen, false);
assert.equal(asaDef.total, 10000000n);
assert.deepEqual(asaDef.metadataHash, undefined);
assert.equal(asaDef.unitName, "oz");
assert.equal(asaDef.url, "https://gold.rush/");
assert.equal(asaDef.manager, appAccount.address);
assert.equal(asaDef.reserve, appAccount.address);
assert.equal(asaDef.freeze, appAccount.address);
assert.equal(asaDef.clawback, appAccount.address);
// verify app account's min balance is also raised
assert.equal(appAccount.minBalance, initialMinBalance + ASSET_CREATION_FEE);
});
it("should deploy a new ASA with app_args (by app account)", function () {
// saved in global state, initially undefined
let createdAsaID = runtime.getGlobalState(appID, "created_asa_key");
assert.isUndefined(createdAsaID);
const initialMinBalance = appAccount.minBalance;
const txParams = {
...appCallParams,
appArgs: ['str:deploy_asa_with_app_args', `str:asa_name`, `str:ipfs://ABCDEF`]
};
runtime.executeTx(txParams);
syncAccounts();
// verify asa created by contract
createdAsaID = runtime.getGlobalState(appID, "created_asa_key");
assert.isDefined(createdAsaID);
const asaDef = runtime.getAssetDef(Number(createdAsaID));
assert.isDefined(asaDef);
assert.equal(asaDef.name, 'asa_name');
assert.equal(asaDef.decimals, 0);
assert.equal(asaDef.defaultFrozen, true);
assert.equal(asaDef.total, 1n);
if (asaDef.metadataHash) { assert.deepEqual(asaDef.metadataHash, new Uint8Array(Buffer.from("12312442142141241244444411111133", 'base64'))); }
assert.equal(asaDef.unitName, "TEST");
assert.equal(asaDef.url, "ipfs://ABCDEF");
assert.equal(asaDef.manager, appAccount.address);
assert.equal(asaDef.reserve, appAccount.address);
assert.equal(asaDef.freeze, appAccount.address);
assert.equal(asaDef.clawback, appAccount.address);
// verify ASA holding is set in creator account
const creatorASAHolding = runtime.getAssetHolding(Number(createdAsaID), appAccount.address);
assert.isDefined(creatorASAHolding);
assert.equal(creatorASAHolding.amount, asaDef.total);
assert.equal(creatorASAHolding["asset-id"], Number(createdAsaID));
assert.equal(creatorASAHolding.creator, appAccount.address);
assert.equal(creatorASAHolding["is-frozen"], false);
// verify app account's min balance is also raised
assert.equal(appAccount.minBalance, initialMinBalance + ASSET_CREATION_FEE);
});
}); | the_stack |
import { Button, Drawer, Space } from 'ant-design-vue'
import type { Drawer as DrawerProps } from 'ant-design-vue/types/drawer'
import { FormProvider, h, Fragment } from '@formily/vue'
import { observer } from '@formily/reactive-vue'
import type { IMiddleware } from '@formily/shared'
import { isNum, isStr, isBool, isFn, applyMiddleware } from '@formily/shared'
import { toJS } from '@formily/reactive'
import type { Form, IFormProps } from '@formily/core'
import { createForm } from '@formily/core'
import type { Component, VNode } from 'vue'
import Vue from 'vue'
import { stylePrefix } from '../__builtins__/configs'
import { defineComponent } from '@vue/composition-api'
import { Portal, PortalTarget } from 'portal-vue'
import {
isValidElement,
resolveComponent,
createPortalProvider,
getProtalContext,
loading,
} from '../__builtins__/shared'
const PORTAL_TARGET_NAME = 'FormDrawerFooter'
type FormDrawerRenderer = VNode | ((form: Form) => VNode)
type DrawerTitle = string | number | Component | VNode | (() => VNode)
const isDrawerTitle = (props: any): props is DrawerTitle => {
return isNum(props) || isStr(props) || isBool(props) || isValidElement(props)
}
const getDrawerProps = (props: any): IDrawerProps => {
if (isDrawerTitle(props)) {
return {
title: props,
} as IDrawerProps
} else {
return props
}
}
export interface IFormDrawer {
forOpen(middleware: IMiddleware<IFormProps>): IFormDrawer
forConfirm(middleware: IMiddleware<Form>): IFormDrawer
forCancel(middleware: IMiddleware<Form>): IFormDrawer
open(props?: IFormProps): Promise<any>
close(): void
}
export interface IDrawerProps extends DrawerProps {
onOk?: (event?: MouseEvent) => void | boolean
onClose?: (event?: MouseEvent) => void | boolean
loadingText?: string
}
export function FormDrawer(
title: IDrawerProps,
id: string,
renderer: FormDrawerRenderer
): IFormDrawer
export function FormDrawer(
title: IDrawerProps,
renderer: FormDrawerRenderer
): IFormDrawer
export function FormDrawer(
title: DrawerTitle,
id: string,
renderer: FormDrawerRenderer
): IFormDrawer
export function FormDrawer(
title: DrawerTitle,
renderer: FormDrawerRenderer
): IFormDrawer
export function FormDrawer(
title: DrawerTitle | IDrawerProps,
id: string | symbol | FormDrawerRenderer,
renderer?: FormDrawerRenderer
): IFormDrawer {
if (isFn(id) || isValidElement(id)) {
renderer = id as FormDrawerRenderer
id = 'form-drawer'
}
const prefixCls = `${stylePrefix}-form-drawer`
const env = {
root: document.createElement('div'),
form: null,
promise: null,
instance: null,
openMiddlewares: [],
confirmMiddlewares: [],
cancelMiddlewares: [],
}
document.body.appendChild(env.root)
const props = getDrawerProps(title)
const drawerProps = {
...props,
width: '40%',
onClose: () => {
props.onClose?.()
// env.instance.$destroy()
// env.instance = null
// env.root?.parentNode?.removeChild(env.root)
// env.root = undefined
},
afterVisibleChange: (visible: boolean) => {
props?.afterVisibleChange?.(visible)
if (visible) return
env.instance.$destroy()
env.instance = null
env.root?.parentNode?.removeChild(env.root)
env.root = undefined
},
}
const DrawerContent = observer(
defineComponent({
setup() {
return () =>
h(
Fragment,
{},
{
default: () => resolveComponent(renderer, { form: env.form }),
}
)
},
})
)
const renderDrawer = (
visible = true,
resolve?: () => any,
reject?: () => any
) => {
if (!env.instance) {
const ComponentConstructor = observer(
Vue.extend({
props: ['drawerProps'],
data() {
return {
visible: false,
}
},
render() {
const {
onOk,
onClose,
title,
footer,
okText = '็กฎๅฎ',
okType = 'primary',
okButtonProps,
cancelButtonProps,
cancelText = 'ๅๆถ',
...drawerProps
} = this.drawerProps
return h(
Drawer,
{
class: prefixCls,
props: {
...drawerProps,
visible: this.visible,
},
on: {
'update:visible': (val) => {
this.visible = val
},
close: (e) => {
if (onClose?.(e) !== false) {
reject?.()
}
},
ok: (e) => {
if (onOk?.(e) !== false) {
resolve?.()
}
},
},
},
{
default: () =>
h(
FormProvider,
{
props: {
form: env.form,
},
},
{
default: () => [
h(
'div',
{
class: [`${prefixCls}-body`],
},
{
default: () => h(DrawerContent, {}, {}),
}
),
h(
'div',
{
class: [`${prefixCls}-footer`],
},
{
default: () =>
h(
Space,
{},
{
default: () => {
const FooterProtalTarget = h(
PortalTarget,
{
props: {
name: PORTAL_TARGET_NAME,
slim: true,
},
},
{}
)
if (footer === null) {
return [null, FooterProtalTarget]
} else if (footer) {
return [
resolveComponent(footer),
FooterProtalTarget,
]
}
return [
h(
Button,
{
attrs: cancelButtonProps,
on: {
click: (e) => {
onClose?.(e)
reject()
},
},
},
{
default: () =>
resolveComponent(cancelText),
}
),
h(
Button,
{
attrs: {
...okButtonProps,
type: okType,
loading: env.form.submitting,
},
on: {
click: (e) => {
onOk?.(e)
resolve()
},
},
},
{
default: () =>
resolveComponent(okText),
}
),
FooterProtalTarget,
]
},
}
),
}
),
],
}
),
title: () =>
h(Fragment, {}, { default: () => resolveComponent(title) }),
}
)
},
})
)
env.instance = new ComponentConstructor({
propsData: {
drawerProps,
},
parent: getProtalContext(id as string | symbol),
})
env.instance.$mount(env.root)
}
env.instance.visible = visible
}
const formDrawer = {
forOpen: (middleware: IMiddleware<IFormProps>) => {
if (isFn(middleware)) {
env.openMiddlewares.push(middleware)
}
return formDrawer
},
forConfirm: (middleware: IMiddleware<Form>) => {
if (isFn(middleware)) {
env.confirmMiddlewares.push(middleware)
}
return formDrawer
},
forCancel: (middleware: IMiddleware<Form>) => {
if (isFn(middleware)) {
env.cancelMiddlewares.push(middleware)
}
return formDrawer
},
open: async (props: IFormProps) => {
if (env.promise) return env.promise
env.promise = new Promise(async (resolve, reject) => {
try {
props = await loading(drawerProps.loadingText, () =>
applyMiddleware(props, env.openMiddlewares)
)
env.form = env.form || createForm(props)
} catch (e) {
reject(e)
}
renderDrawer(
true,
() => {
env.form
.submit(async () => {
await applyMiddleware(env.form, env.confirmMiddlewares)
resolve(toJS(env.form.values))
formDrawer.close()
})
.catch(reject)
},
async () => {
formDrawer.close()
}
)
})
return env.promise
},
close: () => {
if (!env.root) return
renderDrawer(false)
},
}
return formDrawer
}
const DrawerFooter = defineComponent({
name: 'DrawerFooter',
setup(props, { slots }) {
return () => {
return h(
Portal,
{
props: {
to: PORTAL_TARGET_NAME,
},
},
slots
)
}
},
})
FormDrawer.Footer = DrawerFooter
FormDrawer.Portal = createPortalProvider('form-drawer')
export default FormDrawer | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.